diff --git a/3rd_src/pom.xml b/3rd_src/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..022739ae66eaa407d8d6ed72d9d902922efa9689 --- /dev/null +++ b/3rd_src/pom.xml @@ -0,0 +1,426 @@ + + 4.0.0 + com.download + download + + org.openjfx + javafx + 18-ea+2 + + 0.0.1 + common-lib + + + + 18-ea+2 + win + + + + org.antlr + antlr4-runtime + 4.9.2 + + + + org.apache.commons + commons-lang3 + 3.12.0 + + + + org.apache.commons + commons-collections4 + 4.4 + + + + org.apache.commons + commons-compress + 1.21 + + + + org.apache.commons + commons-math3 + 3.6.1 + + + + commons-io + commons-io + 2.11.0 + + + + org.apache.logging.log4j + log4j-core + 2.17.1 + + + + org.apache.logging.log4j + log4j-api + 2.17.1 + + + + org.apache.poi + poi-ooxml + 4.1.2 + + + + org.apache.xmlbeans + xmlbeans + 3.1.0 + + + + org.apache.commons + commons-csv + 1.9.0 + + + + com.google.guava + guava + 30.1.1-jre + + + + com.google.inject + guice + 4.2.0 + + + + com.google.code.gson + gson + 2.8.6 + + + + commons-codec + commons-codec + 1.15 + + + + com.github.jsqlparser + jsqlparser + 3.2 + + + + org.hamcrest + hamcrest-api + 1.0 + + + + junit + junit + 4.11 + + + + log4j + log4j + 1.2.15 + + + javax.jms + jms + + + com.sun.jdmk + jmxtools + + + com.sun.jmx + jmxri + + + + + + commons-logging + commons-logging + 1.0.4 + + + + oro + oro + 2.0.8 + + + + org.jdom + jdom + 2.0.2 + + + + com.mockrunner + mockrunner-jdbc + 2.0.6 + + + + xml-apis + xml-apis + 1.0.b2 + + + + cglib + cglib-nodep + 3.3.0 + + + + org.easymock + easymock + 4.3 + + + + org.objenesis + objenesis + 3.2 + + + + org.eclipse.tycho + org.eclipse.osgi + 3.9.1.v20130814-1242 + + + + org.powermock + powermock-api-mockito + 1.6.6 + + + + org.powermock + powermock-api-mockito-common + 1.6.6 + + + + org.powermock + powermock-api-support + 1.6.6 + + + + org.powermock + powermock-core + 1.6.6 + + + + org.powermock + powermock-api-easymock + 1.6.6 + + + + org.powermock + powermock-api-mockito2 + 1.6.6 + + + + org.powermock + powermock-module-javaagent + 1.6.6 + + + + org.powermock + powermock-module-junit4 + 1.6.6 + + + + org.powermock + powermock-module-junit4-common + 1.6.6 + + + + org.powermock + powermock-module-junit4-legacy + 1.6.6 + test + + + + org.powermock + powermock-module-testng + 1.6.6 + test + + + + org.powermock + powermock-module-testng-common + 1.6.6 + + + + org.powermock + powermock-classloading-base + 1.6.6 + + + + org.powermock + powermock-module-junit4-rule-agent + 1.6.6 + + + + org.powermock + powermock-module-testng-agent + 1.6.6 + + + + org.powermock + powermock-reflect + 1.6.6 + + + + bsh + bsh + 2.0b4 + + + + org.javassist + javassist + 3.20.0-GA + + + + com.beust + jcommander + 1.27 + + + + org.mockito + mockito-all + 1.10.19 + + + + org.yaml + snakeyaml + 1.30 + + + + org.eclipse.core + org.eclipse.core.contenttype + 3.4.100 + + + + org.eclipse.core + org.eclipse.core.jobs + 3.5.100 + + + + org.eclipse.core + org.eclipse.core.runtime + 3.7.0 + + + + org.eclipse.platform + org.eclipse.e4.core.services + 2.0.100 + + + org.eclipse.platform + org.eclipse.e4.core.di + + + + + + org.eclipse.platform + org.eclipse.e4.core.di + 1.8.100 + + + + + org.eclipse.equinox + org.eclipse.equinox.app + 1.3.100 + + + + + org.eclipse.equinox + org.eclipse.equinox.common + 3.6.0 + + + + org.eclipse.platform + org.eclipse.equinox.preferences + 3.6.1 + + + + org.eclipse.platform + org.eclipse.equinox.registry + 3.6.100 + + + + org.eclipse.platform + org.eclipse.osgi.services + 3.5.100 + + + + com.anaptecs.jeaf.owalibs + runtime_registry_compatibility + 4.3.1 + + + + org.openjfx + javafx-base + ${javafx.version} + ${javafx.classifier} + + + + org.openjfx + javafx-controls + ${javafx.version} + ${javafx.classifier} + + + + org.openjfx + javafx-graphics + ${javafx.version} + ${javafx.classifier} + + + \ No newline at end of file diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 0000000000000000000000000000000000000000..b2c7e75485144333a47e9c17ad0eaba5587f5751 --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,48 @@ +@Library('codeflow') _ +node("mesos") { + stage("init") { + cloudBuildConfig { + group_id = "gfc0c0a9a63aa4c1191fd6c5007da94f3" + service_id = "1090009db65f4e628d736650fb30f4a3" + project_id = "3da32fd2704148a5a153b922c7e583b4" + project_name = "DataStudio_Main_MR" + gate_name = "DataStudio_Main_MR" + } + } + + cloudBuild { + jobs = [ + "cmetrics_OpenGauss_master": { + cloudDragonGate() + }, + "compile_OpenGauss_master": { + cloudDragonGate() + }, + "devtestPresentPropertiesOGauss": { + cloudDragonGate() + }, + "devtestPresentTableOGauss": { + cloudDragonGate() + }, + "devtest_bl_database_OGauss": { + cloudDragonGate() + }, + "devtest_bl_object_OGauss": { + cloudDragonGate() + }, + "devtest_bl_table_OGauss": { + cloudDragonGate() + }, + "devtest_other_OGauss": { + cloudDragonGate() + }, + "findbugs_OpenGauss_master": { + cloudDragonGate() + }, + "Reviewbot__OpenGauss_master": { + cloudDragonGate() + }, + ] + } +} + diff --git a/README.md b/README.md index 5b9395e63f5b3a85924dfd9181df88d7343428aa..7e1afdeeb6427cae717e8f88a0eedbd88ca49ca4 100644 --- a/README.md +++ b/README.md @@ -1,39 +1,110 @@ -# DataStudio +# Data Studio介绍 -#### 介绍 -{**以下是 Gitee 平台说明,您可以替换此简介** -Gitee 是 OSCHINA 推出的基于 Git 的代码托管平台(同时支持 SVN)。专为开发者提供稳定、高效、安全的云端软件开发协作平台 -无论是个人、团队、或是企业,都能够用 Gitee 实现代码托管、项目管理、协作开发。企业项目请看 [https://gitee.com/enterprises](https://gitee.com/enterprises)} +## 版本介绍 -#### 软件架构 -软件架构说明 +本版本为openGauss Data Studio的3.0.0版本,主要提供如下功能: +- 管理/创建数据库对象(函数、存储过程、表、视图、序列、触发器等) +- 执行SQL语句或者SQL脚本 +- 创建、执行、调试函数或存储过程 +- 表数据增、删、改、查 +- 导入/导出表数据 +- 显示/导出DDL +- SQL助手、格式化、执行历史记录 -#### 安装教程 +## 特性介绍 -1. xxxx -2. xxxx -3. xxxx +- 管理/创建数据库对象 -#### 使用说明 + 支持管理/创建数据库、模式、函数、存储过程、表、列、索引、约束、视图、外表、序列、同义词、触发器、表空间、用户/角色等多种数据库对象 -1. xxxx -2. xxxx -3. xxxx +- 执行SQL语句或者SQL脚本 -#### 参与贡献 + 支持执行SQL语句或SQL脚本 -1. Fork 本仓库 -2. 新建 Feat_xxx 分支 -3. 提交代码 -4. 新建 Pull Request +- 创建、执行、调试函数/存储过程 + 支持创建、执行、调试函数/存储过程,在调试过程中,可显示堆栈、变量信息,支持断点的增、删、使能、禁用等操作 -#### 特技 +- 表数据增、删、改、查 -1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md -2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com) -3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目 -4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目 -5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help) -6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) + 支持可视化操作表数据的增、删、改、查 + +- 导入/导出表数据 + + 支持表数据的导入和导出,支持的文件格式包括excel、csv、txt及二进制文件 + +- 导入/导出连接配置文件 + + 支持连接配置文件的导入和导出 + +- 显示/导出DDL + + 支持显示/导出表、函数/存储过程、视图、序列、同义词等多种数据库对象的DDL + +- SQL助手、格式化、执行历史记录 + + 提供SQL助手、编辑器智能SQL提示、格式化、历史SQL记录等功能 + +- 安全管理 + + 支持SSL安全网络连接、用户权限管理、密码管理等功能,保证数据库在管理层、应用层、系统层和网络层的安全性 + +## 版本使用注意事项 + +- openGauss Data Studio为openGauss数据库的唯一官方客户端工具,其内置openGauss的JDBC驱动,与openGauss数据库配套使用,不能作为其他数据库的客户端工具 +- openGauss Data Studio为一个Java应用,在使用时需确保配置Java 11+运行环境 + +# 源码编译指导 + +通过源码构建Data Studio二进制包的具体步骤 + +- ## 前置条件 + + 1. 下载安装JDK11,并配置`JAVA_HOME`环境变量 + 2. 下载安装apache maven3.x,并配置`M2_HOME`环境变量 + 3. 通过`https://download2.gluonhq.com/openjfx/11.0.2/openjfx-11.0.2_windows-x64_bin-sdk.zip`下载javafx sdk依赖包,并配置`javafx_home`环境变量,值为${javafx-sdk-11.0.2} + +- ## 源码编译 + + 通过命令行进入Data Studio源码src目录,并运行脚本文件 + + ```shell + cd ${Data_Studio_code}\code\datastudio\src + .\copyExternalsToBuild.bat(windows) 或者 sh copyExternalsToBuild.sh(linux) + mvn clean package -Dmaven.test.skip=true + ``` + + 生成的安装包位置为: + + ```shell + ${Data_Studio_code}\code\datastudio\build + ``` + +# 参与贡献 + +**参与贡献** + +作为openGauss用户,你可以通过多种方式协助openGauss社区。参与社区贡献的方法请参见[社区贡献](https://opengauss.org/zh/contribution.html),这里简单列出部分方式供参考。 + +**特别兴趣小组** + +openGauss将拥有共同兴趣的人们聚在一起,组成了不同的特别兴趣小组(SIG)。当前已有的SIG请参见[SIG列表](https://opengauss.org/zh/contribution.html)。 + +我们欢迎并鼓励你加入已有的SIG或创建新的SIG,创建方法请参见[SIG管理指南](https://opengauss.org/zh/contribution.html)。 + +**邮件列表和任务** + +欢迎你积极地帮助用户解决在[邮件列表](https://opengauss.org/zh/community/mails.html)和issue任务(包括[代码仓任务](https://gitee.com/organizations/opengauss/issues)) 中提出的问题。另外,我们也欢迎你提出问题。这些都将帮助openGauss社区更好地发展。 + +**文档** + +你不仅可以通过提交代码参与社区贡献,我们也欢迎你反馈遇到的问题、困难,或者对文档易用性、完整性的改进建议等。例如获取软件或文档过程中的问题,使用系统过程中的难点。欢迎关注并改进openGauss社区的文档模块。 + +**IRC** + +openGauss也在IRC开辟了频道,作为提供社区支持和交互的额外渠道。详情请参见[openGauss IRC](https://opengauss.org/zh/community/onlineCommunication.html)。 + +# 开源的资料文档应附有对应的文档许可证 + +本文档遵循[知识共享许可协议CC 4.0](https://creativecommons.org/licenses/by/4.0/) (http://creativecommons.org/Licenses/by/4.0/)。 diff --git a/VersionSet.xml b/VersionSet.xml new file mode 100644 index 0000000000000000000000000000000000000000..4ba8653f49d94c33390d977b4529b540fc759d48 --- /dev/null +++ b/VersionSet.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/app_define.json b/app_define.json new file mode 100644 index 0000000000000000000000000000000000000000..9727d4110030b0454d54f56ce3f03231fd889245 --- /dev/null +++ b/app_define.json @@ -0,0 +1 @@ +{"fileVersion":"1","name":"DataStudio_Main_MR","serviceId":"1090009db65f4e628d736650fb30f4a3","description":"","version":"1.0.0","type":"microService","processes":{"DataStudio_Main_MR":{"subscribes":[]}}} \ No newline at end of file diff --git a/code/datastudio/ci/rule/Findbug_filter_ds.xml b/code/datastudio/ci/rule/Findbug_filter_ds.xml new file mode 100644 index 0000000000000000000000000000000000000000..36e29a7e8cf27f1e5fe168ba6679cc2b583a7aae --- /dev/null +++ b/code/datastudio/ci/rule/Findbug_filter_ds.xml @@ -0,0 +1,2275 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/code/datastudio/ci/script/CompilationGuidePackage.bat b/code/datastudio/ci/script/CompilationGuidePackage.bat new file mode 100644 index 0000000000000000000000000000000000000000..743ce3f47eadf6e4bcdb7268804db52f2e88bf56 --- /dev/null +++ b/code/datastudio/ci/script/CompilationGuidePackage.bat @@ -0,0 +1,8 @@ +cd ../../build +mkdir Package_64 + +xcopy "*-win32.win32.x86_64.zip" "Package_64" +del "*-win32.win32.x86_64.zip" + +cd ../Package_64 +ren *x86_64.zip Data_Studio_64.zip \ No newline at end of file diff --git a/code/datastudio/ci/script/compile_package.sh b/code/datastudio/ci/script/compile_package.sh new file mode 100644 index 0000000000000000000000000000000000000000..c1102da0982ca7d9294510bc3ed3af7f6bcc0265 --- /dev/null +++ b/code/datastudio/ci/script/compile_package.sh @@ -0,0 +1,61 @@ +ci_path=$PWD +info_path=$PWD/../../../../information/datastudio +code_path=$PWD/../../src +echo $ci_path +echo $code_path +time_stamp=$(date -d "today" +"%Y-%m-%d %H:%M:%S") +application_name="Data Studio" +commit_id=$(git rev-parse HEAD) +cd $code_path +sh copyExternalsToBuild.sh +sleep 2 +mvn -B -f pom.xml -nsu clean package -Dmaven.test.skip=true +sleep 5 + +echo "Packaging Datastudio files" +cd $code_path/../build +ls -l +win32=$(ls -l $code_path/../build | grep -c win32.x86.zip) +win64=$(ls -l $code_path/../build | grep -c win32.x86_64.zip) +linux_x86=$(ls -l $code_path/../build | grep -c gtk.x86_64.zip) +linux_aarch=$(ls -l $code_path/../build | grep -c gtk.aarch64.zip) +echo $win32 +echo $win64 +echo $linux_x86 +echo $linux_aarch + +if [ "$win64" != 0 ]; +then + echo "windows 32 bit package is available"; + mkdir -p Package_win_64 + mv *win32.x86_64.zip Package_win_64/Data_Studio_win_64.zip + sleep 5 + cd Package_win_64 + unzip Data_Studio_win_64.zip + rm -rf Data_Studio_win_64.zip + cd "Data Studio" + rm *.p2bu + find ./ -name ckeditor -type d | xargs rm -rf + find -path '*/linux*' -delete + echo -e "{\"application_name\":\""$application_name"\", \"compiled_time\":\""$time_stamp"\", \"commit_id\":\""$commit_id"\"}" > version.json + cp -rf $info_path/openGauss* . + cp -rf "$info_path/Data Studio 2.1.0 Open Source Software Notice.doc" . + cd .. + zip -r DataStudio_win_64.zip "Data Studio" + sha256sum DataStudio_win_64.zip > DataStudio_win_64.zip.sha256.txt + rm -rf "Data Studio" + chmod a+x * + mv * ../ + cd .. + rm -rf Package_win_64 +else + echo "Windows 64 bit package is not found in build folder" +fi + + + + + + + + diff --git a/code/datastudio/db_assistant/beginnerGuide.html b/code/datastudio/db_assistant/beginnerGuide.html new file mode 100644 index 0000000000000000000000000000000000000000..a92fe078e7f824cc22a63ad3c218f980b4b09977 --- /dev/null +++ b/code/datastudio/db_assistant/beginnerGuide.html @@ -0,0 +1,65 @@ + + + + + + SQL助手 + + + + + + + + + + + +
+
+
语法
+
操作列表
+
新手入门
+
案列
+
+
+ + + + +
+ \ No newline at end of file diff --git a/code/datastudio/db_assistant/case.html b/code/datastudio/db_assistant/case.html new file mode 100644 index 0000000000000000000000000000000000000000..f59785de0844b5750063fc0d2238b4d37e896687 --- /dev/null +++ b/code/datastudio/db_assistant/case.html @@ -0,0 +1,65 @@ + + + + + + SQL助手 + + + + + + + + + + + +
+
+
语法
+
操作列表
+
新手入门
+
案列
+
+
+ + + + +
+ \ No newline at end of file diff --git a/code/datastudio/db_assistant/css/bootstrap.min.css b/code/datastudio/db_assistant/css/bootstrap.min.css new file mode 100644 index 0000000000000000000000000000000000000000..882691283ab5b356f9643f8507666d71f3372ca1 --- /dev/null +++ b/code/datastudio/db_assistant/css/bootstrap.min.css @@ -0,0 +1,7 @@ +/*! + * Bootstrap v4.1.3 (https://getbootstrap.com/) + * Copyright 2011-2018 The Bootstrap Authors + * Copyright 2011-2018 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + */:root{--blue:#007bff;--indigo:#6610f2;--purple:#6f42c1;--pink:#e83e8c;--red:#dc3545;--orange:#fd7e14;--yellow:#ffc107;--green:#28a745;--teal:#20c997;--cyan:#17a2b8;--white:#fff;--gray:#6c757d;--gray-dark:#343a40;--primary:#007bff;--secondary:#6c757d;--success:#28a745;--info:#17a2b8;--warning:#ffc107;--danger:#dc3545;--light:#f8f9fa;--dark:#343a40;--breakpoint-xs:0;--breakpoint-sm:576px;--breakpoint-md:768px;--breakpoint-lg:992px;--breakpoint-xl:1200px;--font-family-sans-serif:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-family-monospace:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}*,::after,::before{box-sizing:border-box}html{font-family:sans-serif;line-height:1.15;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;-ms-overflow-style:scrollbar;-webkit-tap-highlight-color:transparent}@-ms-viewport{width:device-width}article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";font-size:1rem;font-weight:400;line-height:1.5;color:#212529;text-align:left;background-color:#fff}[tabindex="-1"]:focus{outline:0!important}hr{box-sizing:content-box;height:0;overflow:visible}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem}p{margin-top:0;margin-bottom:1rem}abbr[data-original-title],abbr[title]{text-decoration:underline;-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;border-bottom:0}address{margin-bottom:1rem;font-style:normal;line-height:inherit}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-left:0}blockquote{margin:0 0 1rem}dfn{font-style:italic}b,strong{font-weight:bolder}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:#007bff;text-decoration:none;background-color:transparent;-webkit-text-decoration-skip:objects}a:hover{color:#0056b3;text-decoration:underline}a:not([href]):not([tabindex]){color:inherit;text-decoration:none}a:not([href]):not([tabindex]):focus,a:not([href]):not([tabindex]):hover{color:inherit;text-decoration:none}a:not([href]):not([tabindex]):focus{outline:0}code,kbd,pre,samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;font-size:1em}pre{margin-top:0;margin-bottom:1rem;overflow:auto;-ms-overflow-style:scrollbar}figure{margin:0 0 1rem}img{vertical-align:middle;border-style:none}svg{overflow:hidden;vertical-align:middle}table{border-collapse:collapse}caption{padding-top:.75rem;padding-bottom:.75rem;color:#6c757d;text-align:left;caption-side:bottom}th{text-align:inherit}label{display:inline-block;margin-bottom:.5rem}button{border-radius:0}button:focus{outline:1px dotted;outline:5px auto -webkit-focus-ring-color}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,input{overflow:visible}button,select{text-transform:none}[type=reset],[type=submit],button,html [type=button]{-webkit-appearance:button}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{padding:0;border-style:none}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=date],input[type=datetime-local],input[type=month],input[type=time]{-webkit-appearance:listbox}textarea{overflow:auto;resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;max-width:100%;padding:0;margin-bottom:.5rem;font-size:1.5rem;line-height:inherit;color:inherit;white-space:normal}progress{vertical-align:baseline}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:none}[type=search]::-webkit-search-cancel-button,[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}output{display:inline-block}summary{display:list-item;cursor:pointer}template{display:none}[hidden]{display:none!important}.h1,.h2,.h3,.h4,.h5,.h6,h1,h2,h3,h4,h5,h6{margin-bottom:.5rem;font-family:inherit;font-weight:500;line-height:1.2;color:inherit}.h1,h1{font-size:2.5rem}.h2,h2{font-size:2rem}.h3,h3{font-size:1.75rem}.h4,h4{font-size:1.5rem}.h5,h5{font-size:1.25rem}.h6,h6{font-size:1rem}.lead{font-size:1.25rem;font-weight:300}.display-1{font-size:6rem;font-weight:300;line-height:1.2}.display-2{font-size:5.5rem;font-weight:300;line-height:1.2}.display-3{font-size:4.5rem;font-weight:300;line-height:1.2}.display-4{font-size:3.5rem;font-weight:300;line-height:1.2}hr{margin-top:1rem;margin-bottom:1rem;border:0;border-top:1px solid rgba(0,0,0,.1)}.small,small{font-size:80%;font-weight:400}.mark,mark{padding:.2em;background-color:#fcf8e3}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none}.list-inline-item{display:inline-block}.list-inline-item:not(:last-child){margin-right:.5rem}.initialism{font-size:90%;text-transform:uppercase}.blockquote{margin-bottom:1rem;font-size:1.25rem}.blockquote-footer{display:block;font-size:80%;color:#6c757d}.blockquote-footer::before{content:"\2014 \00A0"}.img-fluid{max-width:100%;height:auto}.img-thumbnail{padding:.25rem;background-color:#fff;border:1px solid #dee2e6;border-radius:.25rem;max-width:100%;height:auto}.figure{display:inline-block}.figure-img{margin-bottom:.5rem;line-height:1}.figure-caption{font-size:90%;color:#6c757d}code{font-size:87.5%;color:#e83e8c;word-break:break-word}a>code{color:inherit}kbd{padding:.2rem .4rem;font-size:87.5%;color:#fff;background-color:#212529;border-radius:.2rem}kbd kbd{padding:0;font-size:100%;font-weight:700}pre{display:block;font-size:87.5%;color:#212529}pre code{font-size:inherit;color:inherit;word-break:normal}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{width:100%;padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}@media (min-width:576px){.container{max-width:540px}}@media (min-width:768px){.container{max-width:720px}}@media (min-width:992px){.container{max-width:960px}}@media (min-width:1200px){.container{max-width:1140px}}.container-fluid{width:100%;padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}.row{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;margin-right:-15px;margin-left:-15px}.no-gutters{margin-right:0;margin-left:0}.no-gutters>.col,.no-gutters>[class*=col-]{padding-right:0;padding-left:0}.col,.col-1,.col-10,.col-11,.col-12,.col-2,.col-3,.col-4,.col-5,.col-6,.col-7,.col-8,.col-9,.col-auto,.col-lg,.col-lg-1,.col-lg-10,.col-lg-11,.col-lg-12,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-auto,.col-md,.col-md-1,.col-md-10,.col-md-11,.col-md-12,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-auto,.col-sm,.col-sm-1,.col-sm-10,.col-sm-11,.col-sm-12,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-auto,.col-xl,.col-xl-1,.col-xl-10,.col-xl-11,.col-xl-12,.col-xl-2,.col-xl-3,.col-xl-4,.col-xl-5,.col-xl-6,.col-xl-7,.col-xl-8,.col-xl-9,.col-xl-auto{position:relative;width:100%;min-height:1px;padding-right:15px;padding-left:15px}.col{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:none}.col-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-first{-ms-flex-order:-1;order:-1}.order-last{-ms-flex-order:13;order:13}.order-0{-ms-flex-order:0;order:0}.order-1{-ms-flex-order:1;order:1}.order-2{-ms-flex-order:2;order:2}.order-3{-ms-flex-order:3;order:3}.order-4{-ms-flex-order:4;order:4}.order-5{-ms-flex-order:5;order:5}.order-6{-ms-flex-order:6;order:6}.order-7{-ms-flex-order:7;order:7}.order-8{-ms-flex-order:8;order:8}.order-9{-ms-flex-order:9;order:9}.order-10{-ms-flex-order:10;order:10}.order-11{-ms-flex-order:11;order:11}.order-12{-ms-flex-order:12;order:12}.offset-1{margin-left:8.333333%}.offset-2{margin-left:16.666667%}.offset-3{margin-left:25%}.offset-4{margin-left:33.333333%}.offset-5{margin-left:41.666667%}.offset-6{margin-left:50%}.offset-7{margin-left:58.333333%}.offset-8{margin-left:66.666667%}.offset-9{margin-left:75%}.offset-10{margin-left:83.333333%}.offset-11{margin-left:91.666667%}@media (min-width:576px){.col-sm{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-sm-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:none}.col-sm-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-sm-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-sm-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-sm-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-sm-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-sm-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-sm-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-sm-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-sm-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-sm-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-sm-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-sm-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-sm-first{-ms-flex-order:-1;order:-1}.order-sm-last{-ms-flex-order:13;order:13}.order-sm-0{-ms-flex-order:0;order:0}.order-sm-1{-ms-flex-order:1;order:1}.order-sm-2{-ms-flex-order:2;order:2}.order-sm-3{-ms-flex-order:3;order:3}.order-sm-4{-ms-flex-order:4;order:4}.order-sm-5{-ms-flex-order:5;order:5}.order-sm-6{-ms-flex-order:6;order:6}.order-sm-7{-ms-flex-order:7;order:7}.order-sm-8{-ms-flex-order:8;order:8}.order-sm-9{-ms-flex-order:9;order:9}.order-sm-10{-ms-flex-order:10;order:10}.order-sm-11{-ms-flex-order:11;order:11}.order-sm-12{-ms-flex-order:12;order:12}.offset-sm-0{margin-left:0}.offset-sm-1{margin-left:8.333333%}.offset-sm-2{margin-left:16.666667%}.offset-sm-3{margin-left:25%}.offset-sm-4{margin-left:33.333333%}.offset-sm-5{margin-left:41.666667%}.offset-sm-6{margin-left:50%}.offset-sm-7{margin-left:58.333333%}.offset-sm-8{margin-left:66.666667%}.offset-sm-9{margin-left:75%}.offset-sm-10{margin-left:83.333333%}.offset-sm-11{margin-left:91.666667%}}@media (min-width:768px){.col-md{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-md-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:none}.col-md-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-md-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-md-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-md-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-md-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-md-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-md-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-md-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-md-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-md-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-md-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-md-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-md-first{-ms-flex-order:-1;order:-1}.order-md-last{-ms-flex-order:13;order:13}.order-md-0{-ms-flex-order:0;order:0}.order-md-1{-ms-flex-order:1;order:1}.order-md-2{-ms-flex-order:2;order:2}.order-md-3{-ms-flex-order:3;order:3}.order-md-4{-ms-flex-order:4;order:4}.order-md-5{-ms-flex-order:5;order:5}.order-md-6{-ms-flex-order:6;order:6}.order-md-7{-ms-flex-order:7;order:7}.order-md-8{-ms-flex-order:8;order:8}.order-md-9{-ms-flex-order:9;order:9}.order-md-10{-ms-flex-order:10;order:10}.order-md-11{-ms-flex-order:11;order:11}.order-md-12{-ms-flex-order:12;order:12}.offset-md-0{margin-left:0}.offset-md-1{margin-left:8.333333%}.offset-md-2{margin-left:16.666667%}.offset-md-3{margin-left:25%}.offset-md-4{margin-left:33.333333%}.offset-md-5{margin-left:41.666667%}.offset-md-6{margin-left:50%}.offset-md-7{margin-left:58.333333%}.offset-md-8{margin-left:66.666667%}.offset-md-9{margin-left:75%}.offset-md-10{margin-left:83.333333%}.offset-md-11{margin-left:91.666667%}}@media (min-width:992px){.col-lg{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-lg-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:none}.col-lg-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-lg-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-lg-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-lg-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-lg-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-lg-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-lg-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-lg-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-lg-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-lg-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-lg-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-lg-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-lg-first{-ms-flex-order:-1;order:-1}.order-lg-last{-ms-flex-order:13;order:13}.order-lg-0{-ms-flex-order:0;order:0}.order-lg-1{-ms-flex-order:1;order:1}.order-lg-2{-ms-flex-order:2;order:2}.order-lg-3{-ms-flex-order:3;order:3}.order-lg-4{-ms-flex-order:4;order:4}.order-lg-5{-ms-flex-order:5;order:5}.order-lg-6{-ms-flex-order:6;order:6}.order-lg-7{-ms-flex-order:7;order:7}.order-lg-8{-ms-flex-order:8;order:8}.order-lg-9{-ms-flex-order:9;order:9}.order-lg-10{-ms-flex-order:10;order:10}.order-lg-11{-ms-flex-order:11;order:11}.order-lg-12{-ms-flex-order:12;order:12}.offset-lg-0{margin-left:0}.offset-lg-1{margin-left:8.333333%}.offset-lg-2{margin-left:16.666667%}.offset-lg-3{margin-left:25%}.offset-lg-4{margin-left:33.333333%}.offset-lg-5{margin-left:41.666667%}.offset-lg-6{margin-left:50%}.offset-lg-7{margin-left:58.333333%}.offset-lg-8{margin-left:66.666667%}.offset-lg-9{margin-left:75%}.offset-lg-10{margin-left:83.333333%}.offset-lg-11{margin-left:91.666667%}}@media (min-width:1200px){.col-xl{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-xl-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:none}.col-xl-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-xl-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-xl-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-xl-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-xl-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-xl-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-xl-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-xl-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-xl-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-xl-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-xl-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-xl-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-xl-first{-ms-flex-order:-1;order:-1}.order-xl-last{-ms-flex-order:13;order:13}.order-xl-0{-ms-flex-order:0;order:0}.order-xl-1{-ms-flex-order:1;order:1}.order-xl-2{-ms-flex-order:2;order:2}.order-xl-3{-ms-flex-order:3;order:3}.order-xl-4{-ms-flex-order:4;order:4}.order-xl-5{-ms-flex-order:5;order:5}.order-xl-6{-ms-flex-order:6;order:6}.order-xl-7{-ms-flex-order:7;order:7}.order-xl-8{-ms-flex-order:8;order:8}.order-xl-9{-ms-flex-order:9;order:9}.order-xl-10{-ms-flex-order:10;order:10}.order-xl-11{-ms-flex-order:11;order:11}.order-xl-12{-ms-flex-order:12;order:12}.offset-xl-0{margin-left:0}.offset-xl-1{margin-left:8.333333%}.offset-xl-2{margin-left:16.666667%}.offset-xl-3{margin-left:25%}.offset-xl-4{margin-left:33.333333%}.offset-xl-5{margin-left:41.666667%}.offset-xl-6{margin-left:50%}.offset-xl-7{margin-left:58.333333%}.offset-xl-8{margin-left:66.666667%}.offset-xl-9{margin-left:75%}.offset-xl-10{margin-left:83.333333%}.offset-xl-11{margin-left:91.666667%}}.table{width:100%;margin-bottom:1rem;background-color:transparent}.table td,.table th{padding:.75rem;vertical-align:top;border-top:1px solid #dee2e6}.table thead th{vertical-align:bottom;border-bottom:2px solid #dee2e6}.table tbody+tbody{border-top:2px solid #dee2e6}.table .table{background-color:#fff}.table-sm td,.table-sm th{padding:.3rem}.table-bordered{border:1px solid #dee2e6}.table-bordered td,.table-bordered th{border:1px solid #dee2e6}.table-bordered thead td,.table-bordered thead th{border-bottom-width:2px}.table-borderless tbody+tbody,.table-borderless td,.table-borderless th,.table-borderless thead th{border:0}.table-striped tbody tr:nth-of-type(odd){background-color:rgba(0,0,0,.05)}.table-hover tbody tr:hover{background-color:rgba(0,0,0,.075)}.table-primary,.table-primary>td,.table-primary>th{background-color:#b8daff}.table-hover .table-primary:hover{background-color:#9fcdff}.table-hover .table-primary:hover>td,.table-hover .table-primary:hover>th{background-color:#9fcdff}.table-secondary,.table-secondary>td,.table-secondary>th{background-color:#d6d8db}.table-hover .table-secondary:hover{background-color:#c8cbcf}.table-hover .table-secondary:hover>td,.table-hover .table-secondary:hover>th{background-color:#c8cbcf}.table-success,.table-success>td,.table-success>th{background-color:#c3e6cb}.table-hover .table-success:hover{background-color:#b1dfbb}.table-hover .table-success:hover>td,.table-hover .table-success:hover>th{background-color:#b1dfbb}.table-info,.table-info>td,.table-info>th{background-color:#bee5eb}.table-hover .table-info:hover{background-color:#abdde5}.table-hover .table-info:hover>td,.table-hover .table-info:hover>th{background-color:#abdde5}.table-warning,.table-warning>td,.table-warning>th{background-color:#ffeeba}.table-hover .table-warning:hover{background-color:#ffe8a1}.table-hover .table-warning:hover>td,.table-hover .table-warning:hover>th{background-color:#ffe8a1}.table-danger,.table-danger>td,.table-danger>th{background-color:#f5c6cb}.table-hover .table-danger:hover{background-color:#f1b0b7}.table-hover .table-danger:hover>td,.table-hover .table-danger:hover>th{background-color:#f1b0b7}.table-light,.table-light>td,.table-light>th{background-color:#fdfdfe}.table-hover .table-light:hover{background-color:#ececf6}.table-hover .table-light:hover>td,.table-hover .table-light:hover>th{background-color:#ececf6}.table-dark,.table-dark>td,.table-dark>th{background-color:#c6c8ca}.table-hover .table-dark:hover{background-color:#b9bbbe}.table-hover .table-dark:hover>td,.table-hover .table-dark:hover>th{background-color:#b9bbbe}.table-active,.table-active>td,.table-active>th{background-color:rgba(0,0,0,.075)}.table-hover .table-active:hover{background-color:rgba(0,0,0,.075)}.table-hover .table-active:hover>td,.table-hover .table-active:hover>th{background-color:rgba(0,0,0,.075)}.table .thead-dark th{color:#fff;background-color:#212529;border-color:#32383e}.table .thead-light th{color:#495057;background-color:#e9ecef;border-color:#dee2e6}.table-dark{color:#fff;background-color:#212529}.table-dark td,.table-dark th,.table-dark thead th{border-color:#32383e}.table-dark.table-bordered{border:0}.table-dark.table-striped tbody tr:nth-of-type(odd){background-color:rgba(255,255,255,.05)}.table-dark.table-hover tbody tr:hover{background-color:rgba(255,255,255,.075)}@media (max-width:575.98px){.table-responsive-sm{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive-sm>.table-bordered{border:0}}@media (max-width:767.98px){.table-responsive-md{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive-md>.table-bordered{border:0}}@media (max-width:991.98px){.table-responsive-lg{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive-lg>.table-bordered{border:0}}@media (max-width:1199.98px){.table-responsive-xl{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive-xl>.table-bordered{border:0}}.table-responsive{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive>.table-bordered{border:0}.form-control{display:block;width:100%;height:calc(2.25rem + 2px);padding:.375rem .75rem;font-size:1rem;line-height:1.5;color:#495057;background-color:#fff;background-clip:padding-box;border:1px solid #ced4da;border-radius:.25rem;transition:border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media screen and (prefers-reduced-motion:reduce){.form-control{transition:none}}.form-control::-ms-expand{background-color:transparent;border:0}.form-control:focus{color:#495057;background-color:#fff;border-color:#80bdff;outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.form-control::-webkit-input-placeholder{color:#6c757d;opacity:1}.form-control::-moz-placeholder{color:#6c757d;opacity:1}.form-control:-ms-input-placeholder{color:#6c757d;opacity:1}.form-control::-ms-input-placeholder{color:#6c757d;opacity:1}.form-control::placeholder{color:#6c757d;opacity:1}.form-control:disabled,.form-control[readonly]{background-color:#e9ecef;opacity:1}select.form-control:focus::-ms-value{color:#495057;background-color:#fff}.form-control-file,.form-control-range{display:block;width:100%}.col-form-label{padding-top:calc(.375rem + 1px);padding-bottom:calc(.375rem + 1px);margin-bottom:0;font-size:inherit;line-height:1.5}.col-form-label-lg{padding-top:calc(.5rem + 1px);padding-bottom:calc(.5rem + 1px);font-size:1.25rem;line-height:1.5}.col-form-label-sm{padding-top:calc(.25rem + 1px);padding-bottom:calc(.25rem + 1px);font-size:.875rem;line-height:1.5}.form-control-plaintext{display:block;width:100%;padding-top:.375rem;padding-bottom:.375rem;margin-bottom:0;line-height:1.5;color:#212529;background-color:transparent;border:solid transparent;border-width:1px 0}.form-control-plaintext.form-control-lg,.form-control-plaintext.form-control-sm{padding-right:0;padding-left:0}.form-control-sm{height:calc(1.8125rem + 2px);padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}.form-control-lg{height:calc(2.875rem + 2px);padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem}select.form-control[multiple],select.form-control[size]{height:auto}textarea.form-control{height:auto}.form-group{margin-bottom:1rem}.form-text{display:block;margin-top:.25rem}.form-row{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;margin-right:-5px;margin-left:-5px}.form-row>.col,.form-row>[class*=col-]{padding-right:5px;padding-left:5px}.form-check{position:relative;display:block;padding-left:1.25rem}.form-check-input{position:absolute;margin-top:.3rem;margin-left:-1.25rem}.form-check-input:disabled~.form-check-label{color:#6c757d}.form-check-label{margin-bottom:0}.form-check-inline{display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;align-items:center;padding-left:0;margin-right:.75rem}.form-check-inline .form-check-input{position:static;margin-top:0;margin-right:.3125rem;margin-left:0}.valid-feedback{display:none;width:100%;margin-top:.25rem;font-size:80%;color:#28a745}.valid-tooltip{position:absolute;top:100%;z-index:5;display:none;max-width:100%;padding:.25rem .5rem;margin-top:.1rem;font-size:.875rem;line-height:1.5;color:#fff;background-color:rgba(40,167,69,.9);border-radius:.25rem}.custom-select.is-valid,.form-control.is-valid,.was-validated .custom-select:valid,.was-validated .form-control:valid{border-color:#28a745}.custom-select.is-valid:focus,.form-control.is-valid:focus,.was-validated .custom-select:valid:focus,.was-validated .form-control:valid:focus{border-color:#28a745;box-shadow:0 0 0 .2rem rgba(40,167,69,.25)}.custom-select.is-valid~.valid-feedback,.custom-select.is-valid~.valid-tooltip,.form-control.is-valid~.valid-feedback,.form-control.is-valid~.valid-tooltip,.was-validated .custom-select:valid~.valid-feedback,.was-validated .custom-select:valid~.valid-tooltip,.was-validated .form-control:valid~.valid-feedback,.was-validated .form-control:valid~.valid-tooltip{display:block}.form-control-file.is-valid~.valid-feedback,.form-control-file.is-valid~.valid-tooltip,.was-validated .form-control-file:valid~.valid-feedback,.was-validated .form-control-file:valid~.valid-tooltip{display:block}.form-check-input.is-valid~.form-check-label,.was-validated .form-check-input:valid~.form-check-label{color:#28a745}.form-check-input.is-valid~.valid-feedback,.form-check-input.is-valid~.valid-tooltip,.was-validated .form-check-input:valid~.valid-feedback,.was-validated .form-check-input:valid~.valid-tooltip{display:block}.custom-control-input.is-valid~.custom-control-label,.was-validated .custom-control-input:valid~.custom-control-label{color:#28a745}.custom-control-input.is-valid~.custom-control-label::before,.was-validated .custom-control-input:valid~.custom-control-label::before{background-color:#71dd8a}.custom-control-input.is-valid~.valid-feedback,.custom-control-input.is-valid~.valid-tooltip,.was-validated .custom-control-input:valid~.valid-feedback,.was-validated .custom-control-input:valid~.valid-tooltip{display:block}.custom-control-input.is-valid:checked~.custom-control-label::before,.was-validated .custom-control-input:valid:checked~.custom-control-label::before{background-color:#34ce57}.custom-control-input.is-valid:focus~.custom-control-label::before,.was-validated .custom-control-input:valid:focus~.custom-control-label::before{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(40,167,69,.25)}.custom-file-input.is-valid~.custom-file-label,.was-validated .custom-file-input:valid~.custom-file-label{border-color:#28a745}.custom-file-input.is-valid~.custom-file-label::after,.was-validated .custom-file-input:valid~.custom-file-label::after{border-color:inherit}.custom-file-input.is-valid~.valid-feedback,.custom-file-input.is-valid~.valid-tooltip,.was-validated .custom-file-input:valid~.valid-feedback,.was-validated .custom-file-input:valid~.valid-tooltip{display:block}.custom-file-input.is-valid:focus~.custom-file-label,.was-validated .custom-file-input:valid:focus~.custom-file-label{box-shadow:0 0 0 .2rem rgba(40,167,69,.25)}.invalid-feedback{display:none;width:100%;margin-top:.25rem;font-size:80%;color:#dc3545}.invalid-tooltip{position:absolute;top:100%;z-index:5;display:none;max-width:100%;padding:.25rem .5rem;margin-top:.1rem;font-size:.875rem;line-height:1.5;color:#fff;background-color:rgba(220,53,69,.9);border-radius:.25rem}.custom-select.is-invalid,.form-control.is-invalid,.was-validated .custom-select:invalid,.was-validated .form-control:invalid{border-color:#dc3545}.custom-select.is-invalid:focus,.form-control.is-invalid:focus,.was-validated .custom-select:invalid:focus,.was-validated .form-control:invalid:focus{border-color:#dc3545;box-shadow:0 0 0 .2rem rgba(220,53,69,.25)}.custom-select.is-invalid~.invalid-feedback,.custom-select.is-invalid~.invalid-tooltip,.form-control.is-invalid~.invalid-feedback,.form-control.is-invalid~.invalid-tooltip,.was-validated .custom-select:invalid~.invalid-feedback,.was-validated .custom-select:invalid~.invalid-tooltip,.was-validated .form-control:invalid~.invalid-feedback,.was-validated .form-control:invalid~.invalid-tooltip{display:block}.form-control-file.is-invalid~.invalid-feedback,.form-control-file.is-invalid~.invalid-tooltip,.was-validated .form-control-file:invalid~.invalid-feedback,.was-validated .form-control-file:invalid~.invalid-tooltip{display:block}.form-check-input.is-invalid~.form-check-label,.was-validated .form-check-input:invalid~.form-check-label{color:#dc3545}.form-check-input.is-invalid~.invalid-feedback,.form-check-input.is-invalid~.invalid-tooltip,.was-validated .form-check-input:invalid~.invalid-feedback,.was-validated .form-check-input:invalid~.invalid-tooltip{display:block}.custom-control-input.is-invalid~.custom-control-label,.was-validated .custom-control-input:invalid~.custom-control-label{color:#dc3545}.custom-control-input.is-invalid~.custom-control-label::before,.was-validated .custom-control-input:invalid~.custom-control-label::before{background-color:#efa2a9}.custom-control-input.is-invalid~.invalid-feedback,.custom-control-input.is-invalid~.invalid-tooltip,.was-validated .custom-control-input:invalid~.invalid-feedback,.was-validated .custom-control-input:invalid~.invalid-tooltip{display:block}.custom-control-input.is-invalid:checked~.custom-control-label::before,.was-validated .custom-control-input:invalid:checked~.custom-control-label::before{background-color:#e4606d}.custom-control-input.is-invalid:focus~.custom-control-label::before,.was-validated .custom-control-input:invalid:focus~.custom-control-label::before{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(220,53,69,.25)}.custom-file-input.is-invalid~.custom-file-label,.was-validated .custom-file-input:invalid~.custom-file-label{border-color:#dc3545}.custom-file-input.is-invalid~.custom-file-label::after,.was-validated .custom-file-input:invalid~.custom-file-label::after{border-color:inherit}.custom-file-input.is-invalid~.invalid-feedback,.custom-file-input.is-invalid~.invalid-tooltip,.was-validated .custom-file-input:invalid~.invalid-feedback,.was-validated .custom-file-input:invalid~.invalid-tooltip{display:block}.custom-file-input.is-invalid:focus~.custom-file-label,.was-validated .custom-file-input:invalid:focus~.custom-file-label{box-shadow:0 0 0 .2rem rgba(220,53,69,.25)}.form-inline{display:-ms-flexbox;display:flex;-ms-flex-flow:row wrap;flex-flow:row wrap;-ms-flex-align:center;align-items:center}.form-inline .form-check{width:100%}@media (min-width:576px){.form-inline label{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;margin-bottom:0}.form-inline .form-group{display:-ms-flexbox;display:flex;-ms-flex:0 0 auto;flex:0 0 auto;-ms-flex-flow:row wrap;flex-flow:row wrap;-ms-flex-align:center;align-items:center;margin-bottom:0}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .form-control-plaintext{display:inline-block}.form-inline .custom-select,.form-inline .input-group{width:auto}.form-inline .form-check{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;width:auto;padding-left:0}.form-inline .form-check-input{position:relative;margin-top:0;margin-right:.25rem;margin-left:0}.form-inline .custom-control{-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center}.form-inline .custom-control-label{margin-bottom:0}}.btn{display:inline-block;font-weight:400;text-align:center;white-space:nowrap;vertical-align:middle;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;border:1px solid transparent;padding:.375rem .75rem;font-size:1rem;line-height:1.5;border-radius:.25rem;transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media screen and (prefers-reduced-motion:reduce){.btn{transition:none}}.btn:focus,.btn:hover{text-decoration:none}.btn.focus,.btn:focus{outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.btn.disabled,.btn:disabled{opacity:.65}.btn:not(:disabled):not(.disabled){cursor:pointer}a.btn.disabled,fieldset:disabled a.btn{pointer-events:none}.btn-primary{color:#fff;background-color:#007bff;border-color:#007bff}.btn-primary:hover{color:#fff;background-color:#0069d9;border-color:#0062cc}.btn-primary.focus,.btn-primary:focus{box-shadow:0 0 0 .2rem rgba(0,123,255,.5)}.btn-primary.disabled,.btn-primary:disabled{color:#fff;background-color:#007bff;border-color:#007bff}.btn-primary:not(:disabled):not(.disabled).active,.btn-primary:not(:disabled):not(.disabled):active,.show>.btn-primary.dropdown-toggle{color:#fff;background-color:#0062cc;border-color:#005cbf}.btn-primary:not(:disabled):not(.disabled).active:focus,.btn-primary:not(:disabled):not(.disabled):active:focus,.show>.btn-primary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(0,123,255,.5)}.btn-secondary{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-secondary:hover{color:#fff;background-color:#5a6268;border-color:#545b62}.btn-secondary.focus,.btn-secondary:focus{box-shadow:0 0 0 .2rem rgba(108,117,125,.5)}.btn-secondary.disabled,.btn-secondary:disabled{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-secondary:not(:disabled):not(.disabled).active,.btn-secondary:not(:disabled):not(.disabled):active,.show>.btn-secondary.dropdown-toggle{color:#fff;background-color:#545b62;border-color:#4e555b}.btn-secondary:not(:disabled):not(.disabled).active:focus,.btn-secondary:not(:disabled):not(.disabled):active:focus,.show>.btn-secondary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(108,117,125,.5)}.btn-success{color:#fff;background-color:#28a745;border-color:#28a745}.btn-success:hover{color:#fff;background-color:#218838;border-color:#1e7e34}.btn-success.focus,.btn-success:focus{box-shadow:0 0 0 .2rem rgba(40,167,69,.5)}.btn-success.disabled,.btn-success:disabled{color:#fff;background-color:#28a745;border-color:#28a745}.btn-success:not(:disabled):not(.disabled).active,.btn-success:not(:disabled):not(.disabled):active,.show>.btn-success.dropdown-toggle{color:#fff;background-color:#1e7e34;border-color:#1c7430}.btn-success:not(:disabled):not(.disabled).active:focus,.btn-success:not(:disabled):not(.disabled):active:focus,.show>.btn-success.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(40,167,69,.5)}.btn-info{color:#fff;background-color:#17a2b8;border-color:#17a2b8}.btn-info:hover{color:#fff;background-color:#138496;border-color:#117a8b}.btn-info.focus,.btn-info:focus{box-shadow:0 0 0 .2rem rgba(23,162,184,.5)}.btn-info.disabled,.btn-info:disabled{color:#fff;background-color:#17a2b8;border-color:#17a2b8}.btn-info:not(:disabled):not(.disabled).active,.btn-info:not(:disabled):not(.disabled):active,.show>.btn-info.dropdown-toggle{color:#fff;background-color:#117a8b;border-color:#10707f}.btn-info:not(:disabled):not(.disabled).active:focus,.btn-info:not(:disabled):not(.disabled):active:focus,.show>.btn-info.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(23,162,184,.5)}.btn-warning{color:#212529;background-color:#ffc107;border-color:#ffc107}.btn-warning:hover{color:#212529;background-color:#e0a800;border-color:#d39e00}.btn-warning.focus,.btn-warning:focus{box-shadow:0 0 0 .2rem rgba(255,193,7,.5)}.btn-warning.disabled,.btn-warning:disabled{color:#212529;background-color:#ffc107;border-color:#ffc107}.btn-warning:not(:disabled):not(.disabled).active,.btn-warning:not(:disabled):not(.disabled):active,.show>.btn-warning.dropdown-toggle{color:#212529;background-color:#d39e00;border-color:#c69500}.btn-warning:not(:disabled):not(.disabled).active:focus,.btn-warning:not(:disabled):not(.disabled):active:focus,.show>.btn-warning.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(255,193,7,.5)}.btn-danger{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-danger:hover{color:#fff;background-color:#c82333;border-color:#bd2130}.btn-danger.focus,.btn-danger:focus{box-shadow:0 0 0 .2rem rgba(220,53,69,.5)}.btn-danger.disabled,.btn-danger:disabled{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-danger:not(:disabled):not(.disabled).active,.btn-danger:not(:disabled):not(.disabled):active,.show>.btn-danger.dropdown-toggle{color:#fff;background-color:#bd2130;border-color:#b21f2d}.btn-danger:not(:disabled):not(.disabled).active:focus,.btn-danger:not(:disabled):not(.disabled):active:focus,.show>.btn-danger.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(220,53,69,.5)}.btn-light{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-light:hover{color:#212529;background-color:#e2e6ea;border-color:#dae0e5}.btn-light.focus,.btn-light:focus{box-shadow:0 0 0 .2rem rgba(248,249,250,.5)}.btn-light.disabled,.btn-light:disabled{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-light:not(:disabled):not(.disabled).active,.btn-light:not(:disabled):not(.disabled):active,.show>.btn-light.dropdown-toggle{color:#212529;background-color:#dae0e5;border-color:#d3d9df}.btn-light:not(:disabled):not(.disabled).active:focus,.btn-light:not(:disabled):not(.disabled):active:focus,.show>.btn-light.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(248,249,250,.5)}.btn-dark{color:#fff;background-color:#343a40;border-color:#343a40}.btn-dark:hover{color:#fff;background-color:#23272b;border-color:#1d2124}.btn-dark.focus,.btn-dark:focus{box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.btn-dark.disabled,.btn-dark:disabled{color:#fff;background-color:#343a40;border-color:#343a40}.btn-dark:not(:disabled):not(.disabled).active,.btn-dark:not(:disabled):not(.disabled):active,.show>.btn-dark.dropdown-toggle{color:#fff;background-color:#1d2124;border-color:#171a1d}.btn-dark:not(:disabled):not(.disabled).active:focus,.btn-dark:not(:disabled):not(.disabled):active:focus,.show>.btn-dark.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.btn-outline-primary{color:#007bff;background-color:transparent;background-image:none;border-color:#007bff}.btn-outline-primary:hover{color:#fff;background-color:#007bff;border-color:#007bff}.btn-outline-primary.focus,.btn-outline-primary:focus{box-shadow:0 0 0 .2rem rgba(0,123,255,.5)}.btn-outline-primary.disabled,.btn-outline-primary:disabled{color:#007bff;background-color:transparent}.btn-outline-primary:not(:disabled):not(.disabled).active,.btn-outline-primary:not(:disabled):not(.disabled):active,.show>.btn-outline-primary.dropdown-toggle{color:#fff;background-color:#007bff;border-color:#007bff}.btn-outline-primary:not(:disabled):not(.disabled).active:focus,.btn-outline-primary:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-primary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(0,123,255,.5)}.btn-outline-secondary{color:#6c757d;background-color:transparent;background-image:none;border-color:#6c757d}.btn-outline-secondary:hover{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-outline-secondary.focus,.btn-outline-secondary:focus{box-shadow:0 0 0 .2rem rgba(108,117,125,.5)}.btn-outline-secondary.disabled,.btn-outline-secondary:disabled{color:#6c757d;background-color:transparent}.btn-outline-secondary:not(:disabled):not(.disabled).active,.btn-outline-secondary:not(:disabled):not(.disabled):active,.show>.btn-outline-secondary.dropdown-toggle{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-outline-secondary:not(:disabled):not(.disabled).active:focus,.btn-outline-secondary:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-secondary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(108,117,125,.5)}.btn-outline-success{color:#28a745;background-color:transparent;background-image:none;border-color:#28a745}.btn-outline-success:hover{color:#fff;background-color:#28a745;border-color:#28a745}.btn-outline-success.focus,.btn-outline-success:focus{box-shadow:0 0 0 .2rem rgba(40,167,69,.5)}.btn-outline-success.disabled,.btn-outline-success:disabled{color:#28a745;background-color:transparent}.btn-outline-success:not(:disabled):not(.disabled).active,.btn-outline-success:not(:disabled):not(.disabled):active,.show>.btn-outline-success.dropdown-toggle{color:#fff;background-color:#28a745;border-color:#28a745}.btn-outline-success:not(:disabled):not(.disabled).active:focus,.btn-outline-success:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-success.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(40,167,69,.5)}.btn-outline-info{color:#17a2b8;background-color:transparent;background-image:none;border-color:#17a2b8}.btn-outline-info:hover{color:#fff;background-color:#17a2b8;border-color:#17a2b8}.btn-outline-info.focus,.btn-outline-info:focus{box-shadow:0 0 0 .2rem rgba(23,162,184,.5)}.btn-outline-info.disabled,.btn-outline-info:disabled{color:#17a2b8;background-color:transparent}.btn-outline-info:not(:disabled):not(.disabled).active,.btn-outline-info:not(:disabled):not(.disabled):active,.show>.btn-outline-info.dropdown-toggle{color:#fff;background-color:#17a2b8;border-color:#17a2b8}.btn-outline-info:not(:disabled):not(.disabled).active:focus,.btn-outline-info:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-info.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(23,162,184,.5)}.btn-outline-warning{color:#ffc107;background-color:transparent;background-image:none;border-color:#ffc107}.btn-outline-warning:hover{color:#212529;background-color:#ffc107;border-color:#ffc107}.btn-outline-warning.focus,.btn-outline-warning:focus{box-shadow:0 0 0 .2rem rgba(255,193,7,.5)}.btn-outline-warning.disabled,.btn-outline-warning:disabled{color:#ffc107;background-color:transparent}.btn-outline-warning:not(:disabled):not(.disabled).active,.btn-outline-warning:not(:disabled):not(.disabled):active,.show>.btn-outline-warning.dropdown-toggle{color:#212529;background-color:#ffc107;border-color:#ffc107}.btn-outline-warning:not(:disabled):not(.disabled).active:focus,.btn-outline-warning:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-warning.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(255,193,7,.5)}.btn-outline-danger{color:#dc3545;background-color:transparent;background-image:none;border-color:#dc3545}.btn-outline-danger:hover{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-outline-danger.focus,.btn-outline-danger:focus{box-shadow:0 0 0 .2rem rgba(220,53,69,.5)}.btn-outline-danger.disabled,.btn-outline-danger:disabled{color:#dc3545;background-color:transparent}.btn-outline-danger:not(:disabled):not(.disabled).active,.btn-outline-danger:not(:disabled):not(.disabled):active,.show>.btn-outline-danger.dropdown-toggle{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-outline-danger:not(:disabled):not(.disabled).active:focus,.btn-outline-danger:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-danger.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(220,53,69,.5)}.btn-outline-light{color:#f8f9fa;background-color:transparent;background-image:none;border-color:#f8f9fa}.btn-outline-light:hover{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-outline-light.focus,.btn-outline-light:focus{box-shadow:0 0 0 .2rem rgba(248,249,250,.5)}.btn-outline-light.disabled,.btn-outline-light:disabled{color:#f8f9fa;background-color:transparent}.btn-outline-light:not(:disabled):not(.disabled).active,.btn-outline-light:not(:disabled):not(.disabled):active,.show>.btn-outline-light.dropdown-toggle{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-outline-light:not(:disabled):not(.disabled).active:focus,.btn-outline-light:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-light.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(248,249,250,.5)}.btn-outline-dark{color:#343a40;background-color:transparent;background-image:none;border-color:#343a40}.btn-outline-dark:hover{color:#fff;background-color:#343a40;border-color:#343a40}.btn-outline-dark.focus,.btn-outline-dark:focus{box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.btn-outline-dark.disabled,.btn-outline-dark:disabled{color:#343a40;background-color:transparent}.btn-outline-dark:not(:disabled):not(.disabled).active,.btn-outline-dark:not(:disabled):not(.disabled):active,.show>.btn-outline-dark.dropdown-toggle{color:#fff;background-color:#343a40;border-color:#343a40}.btn-outline-dark:not(:disabled):not(.disabled).active:focus,.btn-outline-dark:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-dark.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.btn-link{font-weight:400;color:#007bff;background-color:transparent}.btn-link:hover{color:#0056b3;text-decoration:underline;background-color:transparent;border-color:transparent}.btn-link.focus,.btn-link:focus{text-decoration:underline;border-color:transparent;box-shadow:none}.btn-link.disabled,.btn-link:disabled{color:#6c757d;pointer-events:none}.btn-group-lg>.btn,.btn-lg{padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem}.btn-group-sm>.btn,.btn-sm{padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:.5rem}input[type=button].btn-block,input[type=reset].btn-block,input[type=submit].btn-block{width:100%}.fade{transition:opacity .15s linear}@media screen and (prefers-reduced-motion:reduce){.fade{transition:none}}.fade:not(.show){opacity:0}.collapse:not(.show){display:none}.collapsing{position:relative;height:0;overflow:hidden;transition:height .35s ease}@media screen and (prefers-reduced-motion:reduce){.collapsing{transition:none}}.dropdown,.dropleft,.dropright,.dropup{position:relative}.dropdown-toggle::after{display:inline-block;width:0;height:0;margin-left:.255em;vertical-align:.255em;content:"";border-top:.3em solid;border-right:.3em solid transparent;border-bottom:0;border-left:.3em solid transparent}.dropdown-toggle:empty::after{margin-left:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:10rem;padding:.5rem 0;margin:.125rem 0 0;font-size:1rem;color:#212529;text-align:left;list-style:none;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.15);border-radius:.25rem}.dropdown-menu-right{right:0;left:auto}.dropup .dropdown-menu{top:auto;bottom:100%;margin-top:0;margin-bottom:.125rem}.dropup .dropdown-toggle::after{display:inline-block;width:0;height:0;margin-left:.255em;vertical-align:.255em;content:"";border-top:0;border-right:.3em solid transparent;border-bottom:.3em solid;border-left:.3em solid transparent}.dropup .dropdown-toggle:empty::after{margin-left:0}.dropright .dropdown-menu{top:0;right:auto;left:100%;margin-top:0;margin-left:.125rem}.dropright .dropdown-toggle::after{display:inline-block;width:0;height:0;margin-left:.255em;vertical-align:.255em;content:"";border-top:.3em solid transparent;border-right:0;border-bottom:.3em solid transparent;border-left:.3em solid}.dropright .dropdown-toggle:empty::after{margin-left:0}.dropright .dropdown-toggle::after{vertical-align:0}.dropleft .dropdown-menu{top:0;right:100%;left:auto;margin-top:0;margin-right:.125rem}.dropleft .dropdown-toggle::after{display:inline-block;width:0;height:0;margin-left:.255em;vertical-align:.255em;content:""}.dropleft .dropdown-toggle::after{display:none}.dropleft .dropdown-toggle::before{display:inline-block;width:0;height:0;margin-right:.255em;vertical-align:.255em;content:"";border-top:.3em solid transparent;border-right:.3em solid;border-bottom:.3em solid transparent}.dropleft .dropdown-toggle:empty::after{margin-left:0}.dropleft .dropdown-toggle::before{vertical-align:0}.dropdown-menu[x-placement^=bottom],.dropdown-menu[x-placement^=left],.dropdown-menu[x-placement^=right],.dropdown-menu[x-placement^=top]{right:auto;bottom:auto}.dropdown-divider{height:0;margin:.5rem 0;overflow:hidden;border-top:1px solid #e9ecef}.dropdown-item{display:block;width:100%;padding:.25rem 1.5rem;clear:both;font-weight:400;color:#212529;text-align:inherit;white-space:nowrap;background-color:transparent;border:0}.dropdown-item:focus,.dropdown-item:hover{color:#16181b;text-decoration:none;background-color:#f8f9fa}.dropdown-item.active,.dropdown-item:active{color:#fff;text-decoration:none;background-color:#007bff}.dropdown-item.disabled,.dropdown-item:disabled{color:#6c757d;background-color:transparent}.dropdown-menu.show{display:block}.dropdown-header{display:block;padding:.5rem 1.5rem;margin-bottom:0;font-size:.875rem;color:#6c757d;white-space:nowrap}.dropdown-item-text{display:block;padding:.25rem 1.5rem;color:#212529}.btn-group,.btn-group-vertical{position:relative;display:-ms-inline-flexbox;display:inline-flex;vertical-align:middle}.btn-group-vertical>.btn,.btn-group>.btn{position:relative;-ms-flex:0 1 auto;flex:0 1 auto}.btn-group-vertical>.btn:hover,.btn-group>.btn:hover{z-index:1}.btn-group-vertical>.btn.active,.btn-group-vertical>.btn:active,.btn-group-vertical>.btn:focus,.btn-group>.btn.active,.btn-group>.btn:active,.btn-group>.btn:focus{z-index:1}.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group,.btn-group-vertical .btn+.btn,.btn-group-vertical .btn+.btn-group,.btn-group-vertical .btn-group+.btn,.btn-group-vertical .btn-group+.btn-group{margin-left:-1px}.btn-toolbar{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-pack:start;justify-content:flex-start}.btn-toolbar .input-group{width:auto}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn-group:not(:last-child)>.btn,.btn-group>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:not(:first-child)>.btn,.btn-group>.btn:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.dropdown-toggle-split{padding-right:.5625rem;padding-left:.5625rem}.dropdown-toggle-split::after,.dropright .dropdown-toggle-split::after,.dropup .dropdown-toggle-split::after{margin-left:0}.dropleft .dropdown-toggle-split::before{margin-right:0}.btn-group-sm>.btn+.dropdown-toggle-split,.btn-sm+.dropdown-toggle-split{padding-right:.375rem;padding-left:.375rem}.btn-group-lg>.btn+.dropdown-toggle-split,.btn-lg+.dropdown-toggle-split{padding-right:.75rem;padding-left:.75rem}.btn-group-vertical{-ms-flex-direction:column;flex-direction:column;-ms-flex-align:start;align-items:flex-start;-ms-flex-pack:center;justify-content:center}.btn-group-vertical .btn,.btn-group-vertical .btn-group{width:100%}.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn-group:not(:last-child)>.btn,.btn-group-vertical>.btn:not(:last-child):not(.dropdown-toggle){border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:not(:first-child)>.btn,.btn-group-vertical>.btn:not(:first-child){border-top-left-radius:0;border-top-right-radius:0}.btn-group-toggle>.btn,.btn-group-toggle>.btn-group>.btn{margin-bottom:0}.btn-group-toggle>.btn input[type=checkbox],.btn-group-toggle>.btn input[type=radio],.btn-group-toggle>.btn-group>.btn input[type=checkbox],.btn-group-toggle>.btn-group>.btn input[type=radio]{position:absolute;clip:rect(0,0,0,0);pointer-events:none}.input-group{position:relative;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-align:stretch;align-items:stretch;width:100%}.input-group>.custom-file,.input-group>.custom-select,.input-group>.form-control{position:relative;-ms-flex:1 1 auto;flex:1 1 auto;width:1%;margin-bottom:0}.input-group>.custom-file+.custom-file,.input-group>.custom-file+.custom-select,.input-group>.custom-file+.form-control,.input-group>.custom-select+.custom-file,.input-group>.custom-select+.custom-select,.input-group>.custom-select+.form-control,.input-group>.form-control+.custom-file,.input-group>.form-control+.custom-select,.input-group>.form-control+.form-control{margin-left:-1px}.input-group>.custom-file .custom-file-input:focus~.custom-file-label,.input-group>.custom-select:focus,.input-group>.form-control:focus{z-index:3}.input-group>.custom-file .custom-file-input:focus{z-index:4}.input-group>.custom-select:not(:last-child),.input-group>.form-control:not(:last-child){border-top-right-radius:0;border-bottom-right-radius:0}.input-group>.custom-select:not(:first-child),.input-group>.form-control:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.input-group>.custom-file{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.input-group>.custom-file:not(:last-child) .custom-file-label,.input-group>.custom-file:not(:last-child) .custom-file-label::after{border-top-right-radius:0;border-bottom-right-radius:0}.input-group>.custom-file:not(:first-child) .custom-file-label{border-top-left-radius:0;border-bottom-left-radius:0}.input-group-append,.input-group-prepend{display:-ms-flexbox;display:flex}.input-group-append .btn,.input-group-prepend .btn{position:relative;z-index:2}.input-group-append .btn+.btn,.input-group-append .btn+.input-group-text,.input-group-append .input-group-text+.btn,.input-group-append .input-group-text+.input-group-text,.input-group-prepend .btn+.btn,.input-group-prepend .btn+.input-group-text,.input-group-prepend .input-group-text+.btn,.input-group-prepend .input-group-text+.input-group-text{margin-left:-1px}.input-group-prepend{margin-right:-1px}.input-group-append{margin-left:-1px}.input-group-text{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;padding:.375rem .75rem;margin-bottom:0;font-size:1rem;font-weight:400;line-height:1.5;color:#495057;text-align:center;white-space:nowrap;background-color:#e9ecef;border:1px solid #ced4da;border-radius:.25rem}.input-group-text input[type=checkbox],.input-group-text input[type=radio]{margin-top:0}.input-group-lg>.form-control,.input-group-lg>.input-group-append>.btn,.input-group-lg>.input-group-append>.input-group-text,.input-group-lg>.input-group-prepend>.btn,.input-group-lg>.input-group-prepend>.input-group-text{height:calc(2.875rem + 2px);padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem}.input-group-sm>.form-control,.input-group-sm>.input-group-append>.btn,.input-group-sm>.input-group-append>.input-group-text,.input-group-sm>.input-group-prepend>.btn,.input-group-sm>.input-group-prepend>.input-group-text{height:calc(1.8125rem + 2px);padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}.input-group>.input-group-append:last-child>.btn:not(:last-child):not(.dropdown-toggle),.input-group>.input-group-append:last-child>.input-group-text:not(:last-child),.input-group>.input-group-append:not(:last-child)>.btn,.input-group>.input-group-append:not(:last-child)>.input-group-text,.input-group>.input-group-prepend>.btn,.input-group>.input-group-prepend>.input-group-text{border-top-right-radius:0;border-bottom-right-radius:0}.input-group>.input-group-append>.btn,.input-group>.input-group-append>.input-group-text,.input-group>.input-group-prepend:first-child>.btn:not(:first-child),.input-group>.input-group-prepend:first-child>.input-group-text:not(:first-child),.input-group>.input-group-prepend:not(:first-child)>.btn,.input-group>.input-group-prepend:not(:first-child)>.input-group-text{border-top-left-radius:0;border-bottom-left-radius:0}.custom-control{position:relative;display:block;min-height:1.5rem;padding-left:1.5rem}.custom-control-inline{display:-ms-inline-flexbox;display:inline-flex;margin-right:1rem}.custom-control-input{position:absolute;z-index:-1;opacity:0}.custom-control-input:checked~.custom-control-label::before{color:#fff;background-color:#007bff}.custom-control-input:focus~.custom-control-label::before{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(0,123,255,.25)}.custom-control-input:active~.custom-control-label::before{color:#fff;background-color:#b3d7ff}.custom-control-input:disabled~.custom-control-label{color:#6c757d}.custom-control-input:disabled~.custom-control-label::before{background-color:#e9ecef}.custom-control-label{position:relative;margin-bottom:0}.custom-control-label::before{position:absolute;top:.25rem;left:-1.5rem;display:block;width:1rem;height:1rem;pointer-events:none;content:"";-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-color:#dee2e6}.custom-control-label::after{position:absolute;top:.25rem;left:-1.5rem;display:block;width:1rem;height:1rem;content:"";background-repeat:no-repeat;background-position:center center;background-size:50% 50%}.custom-checkbox .custom-control-label::before{border-radius:.25rem}.custom-checkbox .custom-control-input:checked~.custom-control-label::before{background-color:#007bff}.custom-checkbox .custom-control-input:checked~.custom-control-label::after{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3E%3Cpath fill='%23fff' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26 2.974 7.25 8 2.193z'/%3E%3C/svg%3E")}.custom-checkbox .custom-control-input:indeterminate~.custom-control-label::before{background-color:#007bff}.custom-checkbox .custom-control-input:indeterminate~.custom-control-label::after{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 4'%3E%3Cpath stroke='%23fff' d='M0 2h4'/%3E%3C/svg%3E")}.custom-checkbox .custom-control-input:disabled:checked~.custom-control-label::before{background-color:rgba(0,123,255,.5)}.custom-checkbox .custom-control-input:disabled:indeterminate~.custom-control-label::before{background-color:rgba(0,123,255,.5)}.custom-radio .custom-control-label::before{border-radius:50%}.custom-radio .custom-control-input:checked~.custom-control-label::before{background-color:#007bff}.custom-radio .custom-control-input:checked~.custom-control-label::after{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3E%3Ccircle r='3' fill='%23fff'/%3E%3C/svg%3E")}.custom-radio .custom-control-input:disabled:checked~.custom-control-label::before{background-color:rgba(0,123,255,.5)}.custom-select{display:inline-block;width:100%;height:calc(2.25rem + 2px);padding:.375rem 1.75rem .375rem .75rem;line-height:1.5;color:#495057;vertical-align:middle;background:#fff url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3E%3Cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3E%3C/svg%3E") no-repeat right .75rem center;background-size:8px 10px;border:1px solid #ced4da;border-radius:.25rem;-webkit-appearance:none;-moz-appearance:none;appearance:none}.custom-select:focus{border-color:#80bdff;outline:0;box-shadow:0 0 0 .2rem rgba(128,189,255,.5)}.custom-select:focus::-ms-value{color:#495057;background-color:#fff}.custom-select[multiple],.custom-select[size]:not([size="1"]){height:auto;padding-right:.75rem;background-image:none}.custom-select:disabled{color:#6c757d;background-color:#e9ecef}.custom-select::-ms-expand{opacity:0}.custom-select-sm{height:calc(1.8125rem + 2px);padding-top:.375rem;padding-bottom:.375rem;font-size:75%}.custom-select-lg{height:calc(2.875rem + 2px);padding-top:.375rem;padding-bottom:.375rem;font-size:125%}.custom-file{position:relative;display:inline-block;width:100%;height:calc(2.25rem + 2px);margin-bottom:0}.custom-file-input{position:relative;z-index:2;width:100%;height:calc(2.25rem + 2px);margin:0;opacity:0}.custom-file-input:focus~.custom-file-label{border-color:#80bdff;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.custom-file-input:focus~.custom-file-label::after{border-color:#80bdff}.custom-file-input:disabled~.custom-file-label{background-color:#e9ecef}.custom-file-input:lang(en)~.custom-file-label::after{content:"Browse"}.custom-file-label{position:absolute;top:0;right:0;left:0;z-index:1;height:calc(2.25rem + 2px);padding:.375rem .75rem;line-height:1.5;color:#495057;background-color:#fff;border:1px solid #ced4da;border-radius:.25rem}.custom-file-label::after{position:absolute;top:0;right:0;bottom:0;z-index:3;display:block;height:2.25rem;padding:.375rem .75rem;line-height:1.5;color:#495057;content:"Browse";background-color:#e9ecef;border-left:1px solid #ced4da;border-radius:0 .25rem .25rem 0}.custom-range{width:100%;padding-left:0;background-color:transparent;-webkit-appearance:none;-moz-appearance:none;appearance:none}.custom-range:focus{outline:0}.custom-range:focus::-webkit-slider-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(0,123,255,.25)}.custom-range:focus::-moz-range-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(0,123,255,.25)}.custom-range:focus::-ms-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(0,123,255,.25)}.custom-range::-moz-focus-outer{border:0}.custom-range::-webkit-slider-thumb{width:1rem;height:1rem;margin-top:-.25rem;background-color:#007bff;border:0;border-radius:1rem;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;-webkit-appearance:none;appearance:none}@media screen and (prefers-reduced-motion:reduce){.custom-range::-webkit-slider-thumb{transition:none}}.custom-range::-webkit-slider-thumb:active{background-color:#b3d7ff}.custom-range::-webkit-slider-runnable-track{width:100%;height:.5rem;color:transparent;cursor:pointer;background-color:#dee2e6;border-color:transparent;border-radius:1rem}.custom-range::-moz-range-thumb{width:1rem;height:1rem;background-color:#007bff;border:0;border-radius:1rem;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;-moz-appearance:none;appearance:none}@media screen and (prefers-reduced-motion:reduce){.custom-range::-moz-range-thumb{transition:none}}.custom-range::-moz-range-thumb:active{background-color:#b3d7ff}.custom-range::-moz-range-track{width:100%;height:.5rem;color:transparent;cursor:pointer;background-color:#dee2e6;border-color:transparent;border-radius:1rem}.custom-range::-ms-thumb{width:1rem;height:1rem;margin-top:0;margin-right:.2rem;margin-left:.2rem;background-color:#007bff;border:0;border-radius:1rem;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;appearance:none}@media screen and (prefers-reduced-motion:reduce){.custom-range::-ms-thumb{transition:none}}.custom-range::-ms-thumb:active{background-color:#b3d7ff}.custom-range::-ms-track{width:100%;height:.5rem;color:transparent;cursor:pointer;background-color:transparent;border-color:transparent;border-width:.5rem}.custom-range::-ms-fill-lower{background-color:#dee2e6;border-radius:1rem}.custom-range::-ms-fill-upper{margin-right:15px;background-color:#dee2e6;border-radius:1rem}.custom-control-label::before,.custom-file-label,.custom-select{transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media screen and (prefers-reduced-motion:reduce){.custom-control-label::before,.custom-file-label,.custom-select{transition:none}}.nav{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;padding-left:0;margin-bottom:0;list-style:none}.nav-link{display:block;padding:.5rem 1rem}.nav-link:focus,.nav-link:hover{text-decoration:none}.nav-link.disabled{color:#6c757d}.nav-tabs{border-bottom:1px solid #dee2e6}.nav-tabs .nav-item{margin-bottom:-1px}.nav-tabs .nav-link{border:1px solid transparent;border-top-left-radius:.25rem;border-top-right-radius:.25rem}.nav-tabs .nav-link:focus,.nav-tabs .nav-link:hover{border-color:#e9ecef #e9ecef #dee2e6}.nav-tabs .nav-link.disabled{color:#6c757d;background-color:transparent;border-color:transparent}.nav-tabs .nav-item.show .nav-link,.nav-tabs .nav-link.active{color:#495057;background-color:#fff;border-color:#dee2e6 #dee2e6 #fff}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-left-radius:0;border-top-right-radius:0}.nav-pills .nav-link{border-radius:.25rem}.nav-pills .nav-link.active,.nav-pills .show>.nav-link{color:#fff;background-color:#007bff}.nav-fill .nav-item{-ms-flex:1 1 auto;flex:1 1 auto;text-align:center}.nav-justified .nav-item{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;text-align:center}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.navbar{position:relative;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-align:center;align-items:center;-ms-flex-pack:justify;justify-content:space-between;padding:.5rem 1rem}.navbar>.container,.navbar>.container-fluid{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-align:center;align-items:center;-ms-flex-pack:justify;justify-content:space-between}.navbar-brand{display:inline-block;padding-top:.3125rem;padding-bottom:.3125rem;margin-right:1rem;font-size:1.25rem;line-height:inherit;white-space:nowrap}.navbar-brand:focus,.navbar-brand:hover{text-decoration:none}.navbar-nav{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;padding-left:0;margin-bottom:0;list-style:none}.navbar-nav .nav-link{padding-right:0;padding-left:0}.navbar-nav .dropdown-menu{position:static;float:none}.navbar-text{display:inline-block;padding-top:.5rem;padding-bottom:.5rem}.navbar-collapse{-ms-flex-preferred-size:100%;flex-basis:100%;-ms-flex-positive:1;flex-grow:1;-ms-flex-align:center;align-items:center}.navbar-toggler{padding:.25rem .75rem;font-size:1.25rem;line-height:1;background-color:transparent;border:1px solid transparent;border-radius:.25rem}.navbar-toggler:focus,.navbar-toggler:hover{text-decoration:none}.navbar-toggler:not(:disabled):not(.disabled){cursor:pointer}.navbar-toggler-icon{display:inline-block;width:1.5em;height:1.5em;vertical-align:middle;content:"";background:no-repeat center center;background-size:100% 100%}@media (max-width:575.98px){.navbar-expand-sm>.container,.navbar-expand-sm>.container-fluid{padding-right:0;padding-left:0}}@media (min-width:576px){.navbar-expand-sm{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-sm .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand-sm .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-sm .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-sm>.container,.navbar-expand-sm>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-sm .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-sm .navbar-toggler{display:none}}@media (max-width:767.98px){.navbar-expand-md>.container,.navbar-expand-md>.container-fluid{padding-right:0;padding-left:0}}@media (min-width:768px){.navbar-expand-md{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-md .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand-md .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-md .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-md>.container,.navbar-expand-md>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-md .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-md .navbar-toggler{display:none}}@media (max-width:991.98px){.navbar-expand-lg>.container,.navbar-expand-lg>.container-fluid{padding-right:0;padding-left:0}}@media (min-width:992px){.navbar-expand-lg{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-lg .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand-lg .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-lg .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-lg>.container,.navbar-expand-lg>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-lg .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-lg .navbar-toggler{display:none}}@media (max-width:1199.98px){.navbar-expand-xl>.container,.navbar-expand-xl>.container-fluid{padding-right:0;padding-left:0}}@media (min-width:1200px){.navbar-expand-xl{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-xl .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand-xl .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-xl .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-xl>.container,.navbar-expand-xl>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-xl .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-xl .navbar-toggler{display:none}}.navbar-expand{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand>.container,.navbar-expand>.container-fluid{padding-right:0;padding-left:0}.navbar-expand .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand .navbar-nav .dropdown-menu{position:absolute}.navbar-expand .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand>.container,.navbar-expand>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand .navbar-toggler{display:none}.navbar-light .navbar-brand{color:rgba(0,0,0,.9)}.navbar-light .navbar-brand:focus,.navbar-light .navbar-brand:hover{color:rgba(0,0,0,.9)}.navbar-light .navbar-nav .nav-link{color:rgba(0,0,0,.5)}.navbar-light .navbar-nav .nav-link:focus,.navbar-light .navbar-nav .nav-link:hover{color:rgba(0,0,0,.7)}.navbar-light .navbar-nav .nav-link.disabled{color:rgba(0,0,0,.3)}.navbar-light .navbar-nav .active>.nav-link,.navbar-light .navbar-nav .nav-link.active,.navbar-light .navbar-nav .nav-link.show,.navbar-light .navbar-nav .show>.nav-link{color:rgba(0,0,0,.9)}.navbar-light .navbar-toggler{color:rgba(0,0,0,.5);border-color:rgba(0,0,0,.1)}.navbar-light .navbar-toggler-icon{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 30 30' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath stroke='rgba(0, 0, 0, 0.5)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 7h22M4 15h22M4 23h22'/%3E%3C/svg%3E")}.navbar-light .navbar-text{color:rgba(0,0,0,.5)}.navbar-light .navbar-text a{color:rgba(0,0,0,.9)}.navbar-light .navbar-text a:focus,.navbar-light .navbar-text a:hover{color:rgba(0,0,0,.9)}.navbar-dark .navbar-brand{color:#fff}.navbar-dark .navbar-brand:focus,.navbar-dark .navbar-brand:hover{color:#fff}.navbar-dark .navbar-nav .nav-link{color:rgba(255,255,255,.5)}.navbar-dark .navbar-nav .nav-link:focus,.navbar-dark .navbar-nav .nav-link:hover{color:rgba(255,255,255,.75)}.navbar-dark .navbar-nav .nav-link.disabled{color:rgba(255,255,255,.25)}.navbar-dark .navbar-nav .active>.nav-link,.navbar-dark .navbar-nav .nav-link.active,.navbar-dark .navbar-nav .nav-link.show,.navbar-dark .navbar-nav .show>.nav-link{color:#fff}.navbar-dark .navbar-toggler{color:rgba(255,255,255,.5);border-color:rgba(255,255,255,.1)}.navbar-dark .navbar-toggler-icon{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 30 30' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath stroke='rgba(255, 255, 255, 0.5)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 7h22M4 15h22M4 23h22'/%3E%3C/svg%3E")}.navbar-dark .navbar-text{color:rgba(255,255,255,.5)}.navbar-dark .navbar-text a{color:#fff}.navbar-dark .navbar-text a:focus,.navbar-dark .navbar-text a:hover{color:#fff}.card{position:relative;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;min-width:0;word-wrap:break-word;background-color:#fff;background-clip:border-box;border:1px solid rgba(0,0,0,.125);border-radius:.25rem}.card>hr{margin-right:0;margin-left:0}.card>.list-group:first-child .list-group-item:first-child{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.card>.list-group:last-child .list-group-item:last-child{border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.card-body{-ms-flex:1 1 auto;flex:1 1 auto;padding:1.25rem}.card-title{margin-bottom:.75rem}.card-subtitle{margin-top:-.375rem;margin-bottom:0}.card-text:last-child{margin-bottom:0}.card-link:hover{text-decoration:none}.card-link+.card-link{margin-left:1.25rem}.card-header{padding:.75rem 1.25rem;margin-bottom:0;background-color:rgba(0,0,0,.03);border-bottom:1px solid rgba(0,0,0,.125)}.card-header:first-child{border-radius:calc(.25rem - 1px) calc(.25rem - 1px) 0 0}.card-header+.list-group .list-group-item:first-child{border-top:0}.card-footer{padding:.75rem 1.25rem;background-color:rgba(0,0,0,.03);border-top:1px solid rgba(0,0,0,.125)}.card-footer:last-child{border-radius:0 0 calc(.25rem - 1px) calc(.25rem - 1px)}.card-header-tabs{margin-right:-.625rem;margin-bottom:-.75rem;margin-left:-.625rem;border-bottom:0}.card-header-pills{margin-right:-.625rem;margin-left:-.625rem}.card-img-overlay{position:absolute;top:0;right:0;bottom:0;left:0;padding:1.25rem}.card-img{width:100%;border-radius:calc(.25rem - 1px)}.card-img-top{width:100%;border-top-left-radius:calc(.25rem - 1px);border-top-right-radius:calc(.25rem - 1px)}.card-img-bottom{width:100%;border-bottom-right-radius:calc(.25rem - 1px);border-bottom-left-radius:calc(.25rem - 1px)}.card-deck{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}.card-deck .card{margin-bottom:15px}@media (min-width:576px){.card-deck{-ms-flex-flow:row wrap;flex-flow:row wrap;margin-right:-15px;margin-left:-15px}.card-deck .card{display:-ms-flexbox;display:flex;-ms-flex:1 0 0%;flex:1 0 0%;-ms-flex-direction:column;flex-direction:column;margin-right:15px;margin-bottom:0;margin-left:15px}}.card-group{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}.card-group>.card{margin-bottom:15px}@media (min-width:576px){.card-group{-ms-flex-flow:row wrap;flex-flow:row wrap}.card-group>.card{-ms-flex:1 0 0%;flex:1 0 0%;margin-bottom:0}.card-group>.card+.card{margin-left:0;border-left:0}.card-group>.card:first-child{border-top-right-radius:0;border-bottom-right-radius:0}.card-group>.card:first-child .card-header,.card-group>.card:first-child .card-img-top{border-top-right-radius:0}.card-group>.card:first-child .card-footer,.card-group>.card:first-child .card-img-bottom{border-bottom-right-radius:0}.card-group>.card:last-child{border-top-left-radius:0;border-bottom-left-radius:0}.card-group>.card:last-child .card-header,.card-group>.card:last-child .card-img-top{border-top-left-radius:0}.card-group>.card:last-child .card-footer,.card-group>.card:last-child .card-img-bottom{border-bottom-left-radius:0}.card-group>.card:only-child{border-radius:.25rem}.card-group>.card:only-child .card-header,.card-group>.card:only-child .card-img-top{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.card-group>.card:only-child .card-footer,.card-group>.card:only-child .card-img-bottom{border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.card-group>.card:not(:first-child):not(:last-child):not(:only-child){border-radius:0}.card-group>.card:not(:first-child):not(:last-child):not(:only-child) .card-footer,.card-group>.card:not(:first-child):not(:last-child):not(:only-child) .card-header,.card-group>.card:not(:first-child):not(:last-child):not(:only-child) .card-img-bottom,.card-group>.card:not(:first-child):not(:last-child):not(:only-child) .card-img-top{border-radius:0}}.card-columns .card{margin-bottom:.75rem}@media (min-width:576px){.card-columns{-webkit-column-count:3;-moz-column-count:3;column-count:3;-webkit-column-gap:1.25rem;-moz-column-gap:1.25rem;column-gap:1.25rem;orphans:1;widows:1}.card-columns .card{display:inline-block;width:100%}}.accordion .card:not(:first-of-type):not(:last-of-type){border-bottom:0;border-radius:0}.accordion .card:not(:first-of-type) .card-header:first-child{border-radius:0}.accordion .card:first-of-type{border-bottom:0;border-bottom-right-radius:0;border-bottom-left-radius:0}.accordion .card:last-of-type{border-top-left-radius:0;border-top-right-radius:0}.breadcrumb{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;padding:.75rem 1rem;margin-bottom:1rem;list-style:none;background-color:#e9ecef;border-radius:.25rem}.breadcrumb-item+.breadcrumb-item{padding-left:.5rem}.breadcrumb-item+.breadcrumb-item::before{display:inline-block;padding-right:.5rem;color:#6c757d;content:"/"}.breadcrumb-item+.breadcrumb-item:hover::before{text-decoration:underline}.breadcrumb-item+.breadcrumb-item:hover::before{text-decoration:none}.breadcrumb-item.active{color:#6c757d}.pagination{display:-ms-flexbox;display:flex;padding-left:0;list-style:none;border-radius:.25rem}.page-link{position:relative;display:block;padding:.5rem .75rem;margin-left:-1px;line-height:1.25;color:#007bff;background-color:#fff;border:1px solid #dee2e6}.page-link:hover{z-index:2;color:#0056b3;text-decoration:none;background-color:#e9ecef;border-color:#dee2e6}.page-link:focus{z-index:2;outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.page-link:not(:disabled):not(.disabled){cursor:pointer}.page-item:first-child .page-link{margin-left:0;border-top-left-radius:.25rem;border-bottom-left-radius:.25rem}.page-item:last-child .page-link{border-top-right-radius:.25rem;border-bottom-right-radius:.25rem}.page-item.active .page-link{z-index:1;color:#fff;background-color:#007bff;border-color:#007bff}.page-item.disabled .page-link{color:#6c757d;pointer-events:none;cursor:auto;background-color:#fff;border-color:#dee2e6}.pagination-lg .page-link{padding:.75rem 1.5rem;font-size:1.25rem;line-height:1.5}.pagination-lg .page-item:first-child .page-link{border-top-left-radius:.3rem;border-bottom-left-radius:.3rem}.pagination-lg .page-item:last-child .page-link{border-top-right-radius:.3rem;border-bottom-right-radius:.3rem}.pagination-sm .page-link{padding:.25rem .5rem;font-size:.875rem;line-height:1.5}.pagination-sm .page-item:first-child .page-link{border-top-left-radius:.2rem;border-bottom-left-radius:.2rem}.pagination-sm .page-item:last-child .page-link{border-top-right-radius:.2rem;border-bottom-right-radius:.2rem}.badge{display:inline-block;padding:.25em .4em;font-size:75%;font-weight:700;line-height:1;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25rem}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.badge-pill{padding-right:.6em;padding-left:.6em;border-radius:10rem}.badge-primary{color:#fff;background-color:#007bff}.badge-primary[href]:focus,.badge-primary[href]:hover{color:#fff;text-decoration:none;background-color:#0062cc}.badge-secondary{color:#fff;background-color:#6c757d}.badge-secondary[href]:focus,.badge-secondary[href]:hover{color:#fff;text-decoration:none;background-color:#545b62}.badge-success{color:#fff;background-color:#28a745}.badge-success[href]:focus,.badge-success[href]:hover{color:#fff;text-decoration:none;background-color:#1e7e34}.badge-info{color:#fff;background-color:#17a2b8}.badge-info[href]:focus,.badge-info[href]:hover{color:#fff;text-decoration:none;background-color:#117a8b}.badge-warning{color:#212529;background-color:#ffc107}.badge-warning[href]:focus,.badge-warning[href]:hover{color:#212529;text-decoration:none;background-color:#d39e00}.badge-danger{color:#fff;background-color:#dc3545}.badge-danger[href]:focus,.badge-danger[href]:hover{color:#fff;text-decoration:none;background-color:#bd2130}.badge-light{color:#212529;background-color:#f8f9fa}.badge-light[href]:focus,.badge-light[href]:hover{color:#212529;text-decoration:none;background-color:#dae0e5}.badge-dark{color:#fff;background-color:#343a40}.badge-dark[href]:focus,.badge-dark[href]:hover{color:#fff;text-decoration:none;background-color:#1d2124}.jumbotron{padding:2rem 1rem;margin-bottom:2rem;background-color:#e9ecef;border-radius:.3rem}@media (min-width:576px){.jumbotron{padding:4rem 2rem}}.jumbotron-fluid{padding-right:0;padding-left:0;border-radius:0}.alert{position:relative;padding:.75rem 1.25rem;margin-bottom:1rem;border:1px solid transparent;border-radius:.25rem}.alert-heading{color:inherit}.alert-link{font-weight:700}.alert-dismissible{padding-right:4rem}.alert-dismissible .close{position:absolute;top:0;right:0;padding:.75rem 1.25rem;color:inherit}.alert-primary{color:#004085;background-color:#cce5ff;border-color:#b8daff}.alert-primary hr{border-top-color:#9fcdff}.alert-primary .alert-link{color:#002752}.alert-secondary{color:#383d41;background-color:#e2e3e5;border-color:#d6d8db}.alert-secondary hr{border-top-color:#c8cbcf}.alert-secondary .alert-link{color:#202326}.alert-success{color:#155724;background-color:#d4edda;border-color:#c3e6cb}.alert-success hr{border-top-color:#b1dfbb}.alert-success .alert-link{color:#0b2e13}.alert-info{color:#0c5460;background-color:#d1ecf1;border-color:#bee5eb}.alert-info hr{border-top-color:#abdde5}.alert-info .alert-link{color:#062c33}.alert-warning{color:#856404;background-color:#fff3cd;border-color:#ffeeba}.alert-warning hr{border-top-color:#ffe8a1}.alert-warning .alert-link{color:#533f03}.alert-danger{color:#721c24;background-color:#f8d7da;border-color:#f5c6cb}.alert-danger hr{border-top-color:#f1b0b7}.alert-danger .alert-link{color:#491217}.alert-light{color:#818182;background-color:#fefefe;border-color:#fdfdfe}.alert-light hr{border-top-color:#ececf6}.alert-light .alert-link{color:#686868}.alert-dark{color:#1b1e21;background-color:#d6d8d9;border-color:#c6c8ca}.alert-dark hr{border-top-color:#b9bbbe}.alert-dark .alert-link{color:#040505}@-webkit-keyframes progress-bar-stripes{from{background-position:1rem 0}to{background-position:0 0}}@keyframes progress-bar-stripes{from{background-position:1rem 0}to{background-position:0 0}}.progress{display:-ms-flexbox;display:flex;height:1rem;overflow:hidden;font-size:.75rem;background-color:#e9ecef;border-radius:.25rem}.progress-bar{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;-ms-flex-pack:center;justify-content:center;color:#fff;text-align:center;white-space:nowrap;background-color:#007bff;transition:width .6s ease}@media screen and (prefers-reduced-motion:reduce){.progress-bar{transition:none}}.progress-bar-striped{background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-size:1rem 1rem}.progress-bar-animated{-webkit-animation:progress-bar-stripes 1s linear infinite;animation:progress-bar-stripes 1s linear infinite}.media{display:-ms-flexbox;display:flex;-ms-flex-align:start;align-items:flex-start}.media-body{-ms-flex:1;flex:1}.list-group{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;padding-left:0;margin-bottom:0}.list-group-item-action{width:100%;color:#495057;text-align:inherit}.list-group-item-action:focus,.list-group-item-action:hover{color:#495057;text-decoration:none;background-color:#f8f9fa}.list-group-item-action:active{color:#212529;background-color:#e9ecef}.list-group-item{position:relative;display:block;padding:.75rem 1.25rem;margin-bottom:-1px;background-color:#fff;border:1px solid rgba(0,0,0,.125)}.list-group-item:first-child{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.list-group-item:focus,.list-group-item:hover{z-index:1;text-decoration:none}.list-group-item.disabled,.list-group-item:disabled{color:#6c757d;background-color:#fff}.list-group-item.active{z-index:2;color:#fff;background-color:#007bff;border-color:#007bff}.list-group-flush .list-group-item{border-right:0;border-left:0;border-radius:0}.list-group-flush:first-child .list-group-item:first-child{border-top:0}.list-group-flush:last-child .list-group-item:last-child{border-bottom:0}.list-group-item-primary{color:#004085;background-color:#b8daff}.list-group-item-primary.list-group-item-action:focus,.list-group-item-primary.list-group-item-action:hover{color:#004085;background-color:#9fcdff}.list-group-item-primary.list-group-item-action.active{color:#fff;background-color:#004085;border-color:#004085}.list-group-item-secondary{color:#383d41;background-color:#d6d8db}.list-group-item-secondary.list-group-item-action:focus,.list-group-item-secondary.list-group-item-action:hover{color:#383d41;background-color:#c8cbcf}.list-group-item-secondary.list-group-item-action.active{color:#fff;background-color:#383d41;border-color:#383d41}.list-group-item-success{color:#155724;background-color:#c3e6cb}.list-group-item-success.list-group-item-action:focus,.list-group-item-success.list-group-item-action:hover{color:#155724;background-color:#b1dfbb}.list-group-item-success.list-group-item-action.active{color:#fff;background-color:#155724;border-color:#155724}.list-group-item-info{color:#0c5460;background-color:#bee5eb}.list-group-item-info.list-group-item-action:focus,.list-group-item-info.list-group-item-action:hover{color:#0c5460;background-color:#abdde5}.list-group-item-info.list-group-item-action.active{color:#fff;background-color:#0c5460;border-color:#0c5460}.list-group-item-warning{color:#856404;background-color:#ffeeba}.list-group-item-warning.list-group-item-action:focus,.list-group-item-warning.list-group-item-action:hover{color:#856404;background-color:#ffe8a1}.list-group-item-warning.list-group-item-action.active{color:#fff;background-color:#856404;border-color:#856404}.list-group-item-danger{color:#721c24;background-color:#f5c6cb}.list-group-item-danger.list-group-item-action:focus,.list-group-item-danger.list-group-item-action:hover{color:#721c24;background-color:#f1b0b7}.list-group-item-danger.list-group-item-action.active{color:#fff;background-color:#721c24;border-color:#721c24}.list-group-item-light{color:#818182;background-color:#fdfdfe}.list-group-item-light.list-group-item-action:focus,.list-group-item-light.list-group-item-action:hover{color:#818182;background-color:#ececf6}.list-group-item-light.list-group-item-action.active{color:#fff;background-color:#818182;border-color:#818182}.list-group-item-dark{color:#1b1e21;background-color:#c6c8ca}.list-group-item-dark.list-group-item-action:focus,.list-group-item-dark.list-group-item-action:hover{color:#1b1e21;background-color:#b9bbbe}.list-group-item-dark.list-group-item-action.active{color:#fff;background-color:#1b1e21;border-color:#1b1e21}.close{float:right;font-size:1.5rem;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.5}.close:not(:disabled):not(.disabled){cursor:pointer}.close:not(:disabled):not(.disabled):focus,.close:not(:disabled):not(.disabled):hover{color:#000;text-decoration:none;opacity:.75}button.close{padding:0;background-color:transparent;border:0;-webkit-appearance:none}.modal-open{overflow:hidden}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1050;display:none;overflow:hidden;outline:0}.modal-dialog{position:relative;width:auto;margin:.5rem;pointer-events:none}.modal.fade .modal-dialog{transition:-webkit-transform .3s ease-out;transition:transform .3s ease-out;transition:transform .3s ease-out,-webkit-transform .3s ease-out;-webkit-transform:translate(0,-25%);transform:translate(0,-25%)}@media screen and (prefers-reduced-motion:reduce){.modal.fade .modal-dialog{transition:none}}.modal.show .modal-dialog{-webkit-transform:translate(0,0);transform:translate(0,0)}.modal-dialog-centered{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;min-height:calc(100% - (.5rem * 2))}.modal-dialog-centered::before{display:block;height:calc(100vh - (.5rem * 2));content:""}.modal-content{position:relative;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;width:100%;pointer-events:auto;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.2);border-radius:.3rem;outline:0}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{opacity:0}.modal-backdrop.show{opacity:.5}.modal-header{display:-ms-flexbox;display:flex;-ms-flex-align:start;align-items:flex-start;-ms-flex-pack:justify;justify-content:space-between;padding:1rem;border-bottom:1px solid #e9ecef;border-top-left-radius:.3rem;border-top-right-radius:.3rem}.modal-header .close{padding:1rem;margin:-1rem -1rem -1rem auto}.modal-title{margin-bottom:0;line-height:1.5}.modal-body{position:relative;-ms-flex:1 1 auto;flex:1 1 auto;padding:1rem}.modal-footer{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:end;justify-content:flex-end;padding:1rem;border-top:1px solid #e9ecef}.modal-footer>:not(:first-child){margin-left:.25rem}.modal-footer>:not(:last-child){margin-right:.25rem}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media (min-width:576px){.modal-dialog{max-width:500px;margin:1.75rem auto}.modal-dialog-centered{min-height:calc(100% - (1.75rem * 2))}.modal-dialog-centered::before{height:calc(100vh - (1.75rem * 2))}.modal-sm{max-width:300px}}@media (min-width:992px){.modal-lg{max-width:800px}}.tooltip{position:absolute;z-index:1070;display:block;margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";font-style:normal;font-weight:400;line-height:1.5;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;white-space:normal;line-break:auto;font-size:.875rem;word-wrap:break-word;opacity:0}.tooltip.show{opacity:.9}.tooltip .arrow{position:absolute;display:block;width:.8rem;height:.4rem}.tooltip .arrow::before{position:absolute;content:"";border-color:transparent;border-style:solid}.bs-tooltip-auto[x-placement^=top],.bs-tooltip-top{padding:.4rem 0}.bs-tooltip-auto[x-placement^=top] .arrow,.bs-tooltip-top .arrow{bottom:0}.bs-tooltip-auto[x-placement^=top] .arrow::before,.bs-tooltip-top .arrow::before{top:0;border-width:.4rem .4rem 0;border-top-color:#000}.bs-tooltip-auto[x-placement^=right],.bs-tooltip-right{padding:0 .4rem}.bs-tooltip-auto[x-placement^=right] .arrow,.bs-tooltip-right .arrow{left:0;width:.4rem;height:.8rem}.bs-tooltip-auto[x-placement^=right] .arrow::before,.bs-tooltip-right .arrow::before{right:0;border-width:.4rem .4rem .4rem 0;border-right-color:#000}.bs-tooltip-auto[x-placement^=bottom],.bs-tooltip-bottom{padding:.4rem 0}.bs-tooltip-auto[x-placement^=bottom] .arrow,.bs-tooltip-bottom .arrow{top:0}.bs-tooltip-auto[x-placement^=bottom] .arrow::before,.bs-tooltip-bottom .arrow::before{bottom:0;border-width:0 .4rem .4rem;border-bottom-color:#000}.bs-tooltip-auto[x-placement^=left],.bs-tooltip-left{padding:0 .4rem}.bs-tooltip-auto[x-placement^=left] .arrow,.bs-tooltip-left .arrow{right:0;width:.4rem;height:.8rem}.bs-tooltip-auto[x-placement^=left] .arrow::before,.bs-tooltip-left .arrow::before{left:0;border-width:.4rem 0 .4rem .4rem;border-left-color:#000}.tooltip-inner{max-width:200px;padding:.25rem .5rem;color:#fff;text-align:center;background-color:#000;border-radius:.25rem}.popover{position:absolute;top:0;left:0;z-index:1060;display:block;max-width:276px;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";font-style:normal;font-weight:400;line-height:1.5;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;white-space:normal;line-break:auto;font-size:.875rem;word-wrap:break-word;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.2);border-radius:.3rem}.popover .arrow{position:absolute;display:block;width:1rem;height:.5rem;margin:0 .3rem}.popover .arrow::after,.popover .arrow::before{position:absolute;display:block;content:"";border-color:transparent;border-style:solid}.bs-popover-auto[x-placement^=top],.bs-popover-top{margin-bottom:.5rem}.bs-popover-auto[x-placement^=top] .arrow,.bs-popover-top .arrow{bottom:calc((.5rem + 1px) * -1)}.bs-popover-auto[x-placement^=top] .arrow::after,.bs-popover-auto[x-placement^=top] .arrow::before,.bs-popover-top .arrow::after,.bs-popover-top .arrow::before{border-width:.5rem .5rem 0}.bs-popover-auto[x-placement^=top] .arrow::before,.bs-popover-top .arrow::before{bottom:0;border-top-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=top] .arrow::after,.bs-popover-top .arrow::after{bottom:1px;border-top-color:#fff}.bs-popover-auto[x-placement^=right],.bs-popover-right{margin-left:.5rem}.bs-popover-auto[x-placement^=right] .arrow,.bs-popover-right .arrow{left:calc((.5rem + 1px) * -1);width:.5rem;height:1rem;margin:.3rem 0}.bs-popover-auto[x-placement^=right] .arrow::after,.bs-popover-auto[x-placement^=right] .arrow::before,.bs-popover-right .arrow::after,.bs-popover-right .arrow::before{border-width:.5rem .5rem .5rem 0}.bs-popover-auto[x-placement^=right] .arrow::before,.bs-popover-right .arrow::before{left:0;border-right-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=right] .arrow::after,.bs-popover-right .arrow::after{left:1px;border-right-color:#fff}.bs-popover-auto[x-placement^=bottom],.bs-popover-bottom{margin-top:.5rem}.bs-popover-auto[x-placement^=bottom] .arrow,.bs-popover-bottom .arrow{top:calc((.5rem + 1px) * -1)}.bs-popover-auto[x-placement^=bottom] .arrow::after,.bs-popover-auto[x-placement^=bottom] .arrow::before,.bs-popover-bottom .arrow::after,.bs-popover-bottom .arrow::before{border-width:0 .5rem .5rem .5rem}.bs-popover-auto[x-placement^=bottom] .arrow::before,.bs-popover-bottom .arrow::before{top:0;border-bottom-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=bottom] .arrow::after,.bs-popover-bottom .arrow::after{top:1px;border-bottom-color:#fff}.bs-popover-auto[x-placement^=bottom] .popover-header::before,.bs-popover-bottom .popover-header::before{position:absolute;top:0;left:50%;display:block;width:1rem;margin-left:-.5rem;content:"";border-bottom:1px solid #f7f7f7}.bs-popover-auto[x-placement^=left],.bs-popover-left{margin-right:.5rem}.bs-popover-auto[x-placement^=left] .arrow,.bs-popover-left .arrow{right:calc((.5rem + 1px) * -1);width:.5rem;height:1rem;margin:.3rem 0}.bs-popover-auto[x-placement^=left] .arrow::after,.bs-popover-auto[x-placement^=left] .arrow::before,.bs-popover-left .arrow::after,.bs-popover-left .arrow::before{border-width:.5rem 0 .5rem .5rem}.bs-popover-auto[x-placement^=left] .arrow::before,.bs-popover-left .arrow::before{right:0;border-left-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=left] .arrow::after,.bs-popover-left .arrow::after{right:1px;border-left-color:#fff}.popover-header{padding:.5rem .75rem;margin-bottom:0;font-size:1rem;color:inherit;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-top-left-radius:calc(.3rem - 1px);border-top-right-radius:calc(.3rem - 1px)}.popover-header:empty{display:none}.popover-body{padding:.5rem .75rem;color:#212529}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-item{position:relative;display:none;-ms-flex-align:center;align-items:center;width:100%;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-perspective:1000px;perspective:1000px}.carousel-item-next,.carousel-item-prev,.carousel-item.active{display:block;transition:-webkit-transform .6s ease;transition:transform .6s ease;transition:transform .6s ease,-webkit-transform .6s ease}@media screen and (prefers-reduced-motion:reduce){.carousel-item-next,.carousel-item-prev,.carousel-item.active{transition:none}}.carousel-item-next,.carousel-item-prev{position:absolute;top:0}.carousel-item-next.carousel-item-left,.carousel-item-prev.carousel-item-right{-webkit-transform:translateX(0);transform:translateX(0)}@supports ((-webkit-transform-style:preserve-3d) or (transform-style:preserve-3d)){.carousel-item-next.carousel-item-left,.carousel-item-prev.carousel-item-right{-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}}.active.carousel-item-right,.carousel-item-next{-webkit-transform:translateX(100%);transform:translateX(100%)}@supports ((-webkit-transform-style:preserve-3d) or (transform-style:preserve-3d)){.active.carousel-item-right,.carousel-item-next{-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}}.active.carousel-item-left,.carousel-item-prev{-webkit-transform:translateX(-100%);transform:translateX(-100%)}@supports ((-webkit-transform-style:preserve-3d) or (transform-style:preserve-3d)){.active.carousel-item-left,.carousel-item-prev{-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}}.carousel-fade .carousel-item{opacity:0;transition-duration:.6s;transition-property:opacity}.carousel-fade .carousel-item-next.carousel-item-left,.carousel-fade .carousel-item-prev.carousel-item-right,.carousel-fade .carousel-item.active{opacity:1}.carousel-fade .active.carousel-item-left,.carousel-fade .active.carousel-item-right{opacity:0}.carousel-fade .active.carousel-item-left,.carousel-fade .active.carousel-item-prev,.carousel-fade .carousel-item-next,.carousel-fade .carousel-item-prev,.carousel-fade .carousel-item.active{-webkit-transform:translateX(0);transform:translateX(0)}@supports ((-webkit-transform-style:preserve-3d) or (transform-style:preserve-3d)){.carousel-fade .active.carousel-item-left,.carousel-fade .active.carousel-item-prev,.carousel-fade .carousel-item-next,.carousel-fade .carousel-item-prev,.carousel-fade .carousel-item.active{-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}}.carousel-control-next,.carousel-control-prev{position:absolute;top:0;bottom:0;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;width:15%;color:#fff;text-align:center;opacity:.5}.carousel-control-next:focus,.carousel-control-next:hover,.carousel-control-prev:focus,.carousel-control-prev:hover{color:#fff;text-decoration:none;outline:0;opacity:.9}.carousel-control-prev{left:0}.carousel-control-next{right:0}.carousel-control-next-icon,.carousel-control-prev-icon{display:inline-block;width:20px;height:20px;background:transparent no-repeat center center;background-size:100% 100%}.carousel-control-prev-icon{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3E%3Cpath d='M5.25 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3E%3C/svg%3E")}.carousel-control-next-icon{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3E%3Cpath d='M2.75 0l-1.5 1.5 2.5 2.5-2.5 2.5 1.5 1.5 4-4-4-4z'/%3E%3C/svg%3E")}.carousel-indicators{position:absolute;right:0;bottom:10px;left:0;z-index:15;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;padding-left:0;margin-right:15%;margin-left:15%;list-style:none}.carousel-indicators li{position:relative;-ms-flex:0 1 auto;flex:0 1 auto;width:30px;height:3px;margin-right:3px;margin-left:3px;text-indent:-999px;cursor:pointer;background-color:rgba(255,255,255,.5)}.carousel-indicators li::before{position:absolute;top:-10px;left:0;display:inline-block;width:100%;height:10px;content:""}.carousel-indicators li::after{position:absolute;bottom:-10px;left:0;display:inline-block;width:100%;height:10px;content:""}.carousel-indicators .active{background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center}.align-baseline{vertical-align:baseline!important}.align-top{vertical-align:top!important}.align-middle{vertical-align:middle!important}.align-bottom{vertical-align:bottom!important}.align-text-bottom{vertical-align:text-bottom!important}.align-text-top{vertical-align:text-top!important}.bg-primary{background-color:#007bff!important}a.bg-primary:focus,a.bg-primary:hover,button.bg-primary:focus,button.bg-primary:hover{background-color:#0062cc!important}.bg-secondary{background-color:#6c757d!important}a.bg-secondary:focus,a.bg-secondary:hover,button.bg-secondary:focus,button.bg-secondary:hover{background-color:#545b62!important}.bg-success{background-color:#28a745!important}a.bg-success:focus,a.bg-success:hover,button.bg-success:focus,button.bg-success:hover{background-color:#1e7e34!important}.bg-info{background-color:#17a2b8!important}a.bg-info:focus,a.bg-info:hover,button.bg-info:focus,button.bg-info:hover{background-color:#117a8b!important}.bg-warning{background-color:#ffc107!important}a.bg-warning:focus,a.bg-warning:hover,button.bg-warning:focus,button.bg-warning:hover{background-color:#d39e00!important}.bg-danger{background-color:#dc3545!important}a.bg-danger:focus,a.bg-danger:hover,button.bg-danger:focus,button.bg-danger:hover{background-color:#bd2130!important}.bg-light{background-color:#f8f9fa!important}a.bg-light:focus,a.bg-light:hover,button.bg-light:focus,button.bg-light:hover{background-color:#dae0e5!important}.bg-dark{background-color:#343a40!important}a.bg-dark:focus,a.bg-dark:hover,button.bg-dark:focus,button.bg-dark:hover{background-color:#1d2124!important}.bg-white{background-color:#fff!important}.bg-transparent{background-color:transparent!important}.border{border:1px solid #dee2e6!important}.border-top{border-top:1px solid #dee2e6!important}.border-right{border-right:1px solid #dee2e6!important}.border-bottom{border-bottom:1px solid #dee2e6!important}.border-left{border-left:1px solid #dee2e6!important}.border-0{border:0!important}.border-top-0{border-top:0!important}.border-right-0{border-right:0!important}.border-bottom-0{border-bottom:0!important}.border-left-0{border-left:0!important}.border-primary{border-color:#007bff!important}.border-secondary{border-color:#6c757d!important}.border-success{border-color:#28a745!important}.border-info{border-color:#17a2b8!important}.border-warning{border-color:#ffc107!important}.border-danger{border-color:#dc3545!important}.border-light{border-color:#f8f9fa!important}.border-dark{border-color:#343a40!important}.border-white{border-color:#fff!important}.rounded{border-radius:.25rem!important}.rounded-top{border-top-left-radius:.25rem!important;border-top-right-radius:.25rem!important}.rounded-right{border-top-right-radius:.25rem!important;border-bottom-right-radius:.25rem!important}.rounded-bottom{border-bottom-right-radius:.25rem!important;border-bottom-left-radius:.25rem!important}.rounded-left{border-top-left-radius:.25rem!important;border-bottom-left-radius:.25rem!important}.rounded-circle{border-radius:50%!important}.rounded-0{border-radius:0!important}.clearfix::after{display:block;clear:both;content:""}.d-none{display:none!important}.d-inline{display:inline!important}.d-inline-block{display:inline-block!important}.d-block{display:block!important}.d-table{display:table!important}.d-table-row{display:table-row!important}.d-table-cell{display:table-cell!important}.d-flex{display:-ms-flexbox!important;display:flex!important}.d-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}@media (min-width:576px){.d-sm-none{display:none!important}.d-sm-inline{display:inline!important}.d-sm-inline-block{display:inline-block!important}.d-sm-block{display:block!important}.d-sm-table{display:table!important}.d-sm-table-row{display:table-row!important}.d-sm-table-cell{display:table-cell!important}.d-sm-flex{display:-ms-flexbox!important;display:flex!important}.d-sm-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}@media (min-width:768px){.d-md-none{display:none!important}.d-md-inline{display:inline!important}.d-md-inline-block{display:inline-block!important}.d-md-block{display:block!important}.d-md-table{display:table!important}.d-md-table-row{display:table-row!important}.d-md-table-cell{display:table-cell!important}.d-md-flex{display:-ms-flexbox!important;display:flex!important}.d-md-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}@media (min-width:992px){.d-lg-none{display:none!important}.d-lg-inline{display:inline!important}.d-lg-inline-block{display:inline-block!important}.d-lg-block{display:block!important}.d-lg-table{display:table!important}.d-lg-table-row{display:table-row!important}.d-lg-table-cell{display:table-cell!important}.d-lg-flex{display:-ms-flexbox!important;display:flex!important}.d-lg-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}@media (min-width:1200px){.d-xl-none{display:none!important}.d-xl-inline{display:inline!important}.d-xl-inline-block{display:inline-block!important}.d-xl-block{display:block!important}.d-xl-table{display:table!important}.d-xl-table-row{display:table-row!important}.d-xl-table-cell{display:table-cell!important}.d-xl-flex{display:-ms-flexbox!important;display:flex!important}.d-xl-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}@media print{.d-print-none{display:none!important}.d-print-inline{display:inline!important}.d-print-inline-block{display:inline-block!important}.d-print-block{display:block!important}.d-print-table{display:table!important}.d-print-table-row{display:table-row!important}.d-print-table-cell{display:table-cell!important}.d-print-flex{display:-ms-flexbox!important;display:flex!important}.d-print-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}.embed-responsive{position:relative;display:block;width:100%;padding:0;overflow:hidden}.embed-responsive::before{display:block;content:""}.embed-responsive .embed-responsive-item,.embed-responsive embed,.embed-responsive iframe,.embed-responsive object,.embed-responsive video{position:absolute;top:0;bottom:0;left:0;width:100%;height:100%;border:0}.embed-responsive-21by9::before{padding-top:42.857143%}.embed-responsive-16by9::before{padding-top:56.25%}.embed-responsive-4by3::before{padding-top:75%}.embed-responsive-1by1::before{padding-top:100%}.flex-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.flex-fill{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-grow-1{-ms-flex-positive:1!important;flex-grow:1!important}.flex-shrink-0{-ms-flex-negative:0!important;flex-shrink:0!important}.flex-shrink-1{-ms-flex-negative:1!important;flex-shrink:1!important}.justify-content-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-center{-ms-flex-align:center!important;align-items:center!important}.align-items-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}@media (min-width:576px){.flex-sm-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-sm-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-sm-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-sm-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-sm-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-sm-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-sm-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.flex-sm-fill{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-sm-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-sm-grow-1{-ms-flex-positive:1!important;flex-grow:1!important}.flex-sm-shrink-0{-ms-flex-negative:0!important;flex-shrink:0!important}.flex-sm-shrink-1{-ms-flex-negative:1!important;flex-shrink:1!important}.justify-content-sm-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-sm-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-sm-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-sm-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-sm-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-sm-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-sm-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-sm-center{-ms-flex-align:center!important;align-items:center!important}.align-items-sm-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-sm-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-sm-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-sm-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-sm-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-sm-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-sm-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-sm-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-sm-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-sm-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-sm-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-sm-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-sm-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-sm-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}}@media (min-width:768px){.flex-md-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-md-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-md-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-md-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-md-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-md-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-md-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.flex-md-fill{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-md-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-md-grow-1{-ms-flex-positive:1!important;flex-grow:1!important}.flex-md-shrink-0{-ms-flex-negative:0!important;flex-shrink:0!important}.flex-md-shrink-1{-ms-flex-negative:1!important;flex-shrink:1!important}.justify-content-md-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-md-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-md-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-md-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-md-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-md-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-md-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-md-center{-ms-flex-align:center!important;align-items:center!important}.align-items-md-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-md-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-md-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-md-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-md-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-md-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-md-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-md-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-md-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-md-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-md-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-md-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-md-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-md-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}}@media (min-width:992px){.flex-lg-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-lg-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-lg-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-lg-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-lg-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-lg-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-lg-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.flex-lg-fill{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-lg-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-lg-grow-1{-ms-flex-positive:1!important;flex-grow:1!important}.flex-lg-shrink-0{-ms-flex-negative:0!important;flex-shrink:0!important}.flex-lg-shrink-1{-ms-flex-negative:1!important;flex-shrink:1!important}.justify-content-lg-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-lg-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-lg-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-lg-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-lg-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-lg-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-lg-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-lg-center{-ms-flex-align:center!important;align-items:center!important}.align-items-lg-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-lg-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-lg-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-lg-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-lg-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-lg-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-lg-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-lg-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-lg-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-lg-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-lg-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-lg-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-lg-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-lg-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}}@media (min-width:1200px){.flex-xl-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-xl-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-xl-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-xl-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-xl-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-xl-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-xl-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.flex-xl-fill{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-xl-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-xl-grow-1{-ms-flex-positive:1!important;flex-grow:1!important}.flex-xl-shrink-0{-ms-flex-negative:0!important;flex-shrink:0!important}.flex-xl-shrink-1{-ms-flex-negative:1!important;flex-shrink:1!important}.justify-content-xl-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-xl-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-xl-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-xl-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-xl-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-xl-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-xl-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-xl-center{-ms-flex-align:center!important;align-items:center!important}.align-items-xl-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-xl-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-xl-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-xl-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-xl-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-xl-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-xl-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-xl-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-xl-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-xl-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-xl-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-xl-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-xl-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-xl-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}}.float-left{float:left!important}.float-right{float:right!important}.float-none{float:none!important}@media (min-width:576px){.float-sm-left{float:left!important}.float-sm-right{float:right!important}.float-sm-none{float:none!important}}@media (min-width:768px){.float-md-left{float:left!important}.float-md-right{float:right!important}.float-md-none{float:none!important}}@media (min-width:992px){.float-lg-left{float:left!important}.float-lg-right{float:right!important}.float-lg-none{float:none!important}}@media (min-width:1200px){.float-xl-left{float:left!important}.float-xl-right{float:right!important}.float-xl-none{float:none!important}}.position-static{position:static!important}.position-relative{position:relative!important}.position-absolute{position:absolute!important}.position-fixed{position:fixed!important}.position-sticky{position:-webkit-sticky!important;position:sticky!important}.fixed-top{position:fixed;top:0;right:0;left:0;z-index:1030}.fixed-bottom{position:fixed;right:0;bottom:0;left:0;z-index:1030}@supports ((position:-webkit-sticky) or (position:sticky)){.sticky-top{position:-webkit-sticky;position:sticky;top:0;z-index:1020}}.sr-only{position:absolute;width:1px;height:1px;padding:0;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;overflow:visible;clip:auto;white-space:normal}.shadow-sm{box-shadow:0 .125rem .25rem rgba(0,0,0,.075)!important}.shadow{box-shadow:0 .5rem 1rem rgba(0,0,0,.15)!important}.shadow-lg{box-shadow:0 1rem 3rem rgba(0,0,0,.175)!important}.shadow-none{box-shadow:none!important}.w-25{width:25%!important}.w-50{width:50%!important}.w-75{width:75%!important}.w-100{width:100%!important}.w-auto{width:auto!important}.h-25{height:25%!important}.h-50{height:50%!important}.h-75{height:75%!important}.h-100{height:100%!important}.h-auto{height:auto!important}.mw-100{max-width:100%!important}.mh-100{max-height:100%!important}.m-0{margin:0!important}.mt-0,.my-0{margin-top:0!important}.mr-0,.mx-0{margin-right:0!important}.mb-0,.my-0{margin-bottom:0!important}.ml-0,.mx-0{margin-left:0!important}.m-1{margin:.25rem!important}.mt-1,.my-1{margin-top:.25rem!important}.mr-1,.mx-1{margin-right:.25rem!important}.mb-1,.my-1{margin-bottom:.25rem!important}.ml-1,.mx-1{margin-left:.25rem!important}.m-2{margin:.5rem!important}.mt-2,.my-2{margin-top:.5rem!important}.mr-2,.mx-2{margin-right:.5rem!important}.mb-2,.my-2{margin-bottom:.5rem!important}.ml-2,.mx-2{margin-left:.5rem!important}.m-3{margin:1rem!important}.mt-3,.my-3{margin-top:1rem!important}.mr-3,.mx-3{margin-right:1rem!important}.mb-3,.my-3{margin-bottom:1rem!important}.ml-3,.mx-3{margin-left:1rem!important}.m-4{margin:1.5rem!important}.mt-4,.my-4{margin-top:1.5rem!important}.mr-4,.mx-4{margin-right:1.5rem!important}.mb-4,.my-4{margin-bottom:1.5rem!important}.ml-4,.mx-4{margin-left:1.5rem!important}.m-5{margin:3rem!important}.mt-5,.my-5{margin-top:3rem!important}.mr-5,.mx-5{margin-right:3rem!important}.mb-5,.my-5{margin-bottom:3rem!important}.ml-5,.mx-5{margin-left:3rem!important}.p-0{padding:0!important}.pt-0,.py-0{padding-top:0!important}.pr-0,.px-0{padding-right:0!important}.pb-0,.py-0{padding-bottom:0!important}.pl-0,.px-0{padding-left:0!important}.p-1{padding:.25rem!important}.pt-1,.py-1{padding-top:.25rem!important}.pr-1,.px-1{padding-right:.25rem!important}.pb-1,.py-1{padding-bottom:.25rem!important}.pl-1,.px-1{padding-left:.25rem!important}.p-2{padding:.5rem!important}.pt-2,.py-2{padding-top:.5rem!important}.pr-2,.px-2{padding-right:.5rem!important}.pb-2,.py-2{padding-bottom:.5rem!important}.pl-2,.px-2{padding-left:.5rem!important}.p-3{padding:1rem!important}.pt-3,.py-3{padding-top:1rem!important}.pr-3,.px-3{padding-right:1rem!important}.pb-3,.py-3{padding-bottom:1rem!important}.pl-3,.px-3{padding-left:1rem!important}.p-4{padding:1.5rem!important}.pt-4,.py-4{padding-top:1.5rem!important}.pr-4,.px-4{padding-right:1.5rem!important}.pb-4,.py-4{padding-bottom:1.5rem!important}.pl-4,.px-4{padding-left:1.5rem!important}.p-5{padding:3rem!important}.pt-5,.py-5{padding-top:3rem!important}.pr-5,.px-5{padding-right:3rem!important}.pb-5,.py-5{padding-bottom:3rem!important}.pl-5,.px-5{padding-left:3rem!important}.m-auto{margin:auto!important}.mt-auto,.my-auto{margin-top:auto!important}.mr-auto,.mx-auto{margin-right:auto!important}.mb-auto,.my-auto{margin-bottom:auto!important}.ml-auto,.mx-auto{margin-left:auto!important}@media (min-width:576px){.m-sm-0{margin:0!important}.mt-sm-0,.my-sm-0{margin-top:0!important}.mr-sm-0,.mx-sm-0{margin-right:0!important}.mb-sm-0,.my-sm-0{margin-bottom:0!important}.ml-sm-0,.mx-sm-0{margin-left:0!important}.m-sm-1{margin:.25rem!important}.mt-sm-1,.my-sm-1{margin-top:.25rem!important}.mr-sm-1,.mx-sm-1{margin-right:.25rem!important}.mb-sm-1,.my-sm-1{margin-bottom:.25rem!important}.ml-sm-1,.mx-sm-1{margin-left:.25rem!important}.m-sm-2{margin:.5rem!important}.mt-sm-2,.my-sm-2{margin-top:.5rem!important}.mr-sm-2,.mx-sm-2{margin-right:.5rem!important}.mb-sm-2,.my-sm-2{margin-bottom:.5rem!important}.ml-sm-2,.mx-sm-2{margin-left:.5rem!important}.m-sm-3{margin:1rem!important}.mt-sm-3,.my-sm-3{margin-top:1rem!important}.mr-sm-3,.mx-sm-3{margin-right:1rem!important}.mb-sm-3,.my-sm-3{margin-bottom:1rem!important}.ml-sm-3,.mx-sm-3{margin-left:1rem!important}.m-sm-4{margin:1.5rem!important}.mt-sm-4,.my-sm-4{margin-top:1.5rem!important}.mr-sm-4,.mx-sm-4{margin-right:1.5rem!important}.mb-sm-4,.my-sm-4{margin-bottom:1.5rem!important}.ml-sm-4,.mx-sm-4{margin-left:1.5rem!important}.m-sm-5{margin:3rem!important}.mt-sm-5,.my-sm-5{margin-top:3rem!important}.mr-sm-5,.mx-sm-5{margin-right:3rem!important}.mb-sm-5,.my-sm-5{margin-bottom:3rem!important}.ml-sm-5,.mx-sm-5{margin-left:3rem!important}.p-sm-0{padding:0!important}.pt-sm-0,.py-sm-0{padding-top:0!important}.pr-sm-0,.px-sm-0{padding-right:0!important}.pb-sm-0,.py-sm-0{padding-bottom:0!important}.pl-sm-0,.px-sm-0{padding-left:0!important}.p-sm-1{padding:.25rem!important}.pt-sm-1,.py-sm-1{padding-top:.25rem!important}.pr-sm-1,.px-sm-1{padding-right:.25rem!important}.pb-sm-1,.py-sm-1{padding-bottom:.25rem!important}.pl-sm-1,.px-sm-1{padding-left:.25rem!important}.p-sm-2{padding:.5rem!important}.pt-sm-2,.py-sm-2{padding-top:.5rem!important}.pr-sm-2,.px-sm-2{padding-right:.5rem!important}.pb-sm-2,.py-sm-2{padding-bottom:.5rem!important}.pl-sm-2,.px-sm-2{padding-left:.5rem!important}.p-sm-3{padding:1rem!important}.pt-sm-3,.py-sm-3{padding-top:1rem!important}.pr-sm-3,.px-sm-3{padding-right:1rem!important}.pb-sm-3,.py-sm-3{padding-bottom:1rem!important}.pl-sm-3,.px-sm-3{padding-left:1rem!important}.p-sm-4{padding:1.5rem!important}.pt-sm-4,.py-sm-4{padding-top:1.5rem!important}.pr-sm-4,.px-sm-4{padding-right:1.5rem!important}.pb-sm-4,.py-sm-4{padding-bottom:1.5rem!important}.pl-sm-4,.px-sm-4{padding-left:1.5rem!important}.p-sm-5{padding:3rem!important}.pt-sm-5,.py-sm-5{padding-top:3rem!important}.pr-sm-5,.px-sm-5{padding-right:3rem!important}.pb-sm-5,.py-sm-5{padding-bottom:3rem!important}.pl-sm-5,.px-sm-5{padding-left:3rem!important}.m-sm-auto{margin:auto!important}.mt-sm-auto,.my-sm-auto{margin-top:auto!important}.mr-sm-auto,.mx-sm-auto{margin-right:auto!important}.mb-sm-auto,.my-sm-auto{margin-bottom:auto!important}.ml-sm-auto,.mx-sm-auto{margin-left:auto!important}}@media (min-width:768px){.m-md-0{margin:0!important}.mt-md-0,.my-md-0{margin-top:0!important}.mr-md-0,.mx-md-0{margin-right:0!important}.mb-md-0,.my-md-0{margin-bottom:0!important}.ml-md-0,.mx-md-0{margin-left:0!important}.m-md-1{margin:.25rem!important}.mt-md-1,.my-md-1{margin-top:.25rem!important}.mr-md-1,.mx-md-1{margin-right:.25rem!important}.mb-md-1,.my-md-1{margin-bottom:.25rem!important}.ml-md-1,.mx-md-1{margin-left:.25rem!important}.m-md-2{margin:.5rem!important}.mt-md-2,.my-md-2{margin-top:.5rem!important}.mr-md-2,.mx-md-2{margin-right:.5rem!important}.mb-md-2,.my-md-2{margin-bottom:.5rem!important}.ml-md-2,.mx-md-2{margin-left:.5rem!important}.m-md-3{margin:1rem!important}.mt-md-3,.my-md-3{margin-top:1rem!important}.mr-md-3,.mx-md-3{margin-right:1rem!important}.mb-md-3,.my-md-3{margin-bottom:1rem!important}.ml-md-3,.mx-md-3{margin-left:1rem!important}.m-md-4{margin:1.5rem!important}.mt-md-4,.my-md-4{margin-top:1.5rem!important}.mr-md-4,.mx-md-4{margin-right:1.5rem!important}.mb-md-4,.my-md-4{margin-bottom:1.5rem!important}.ml-md-4,.mx-md-4{margin-left:1.5rem!important}.m-md-5{margin:3rem!important}.mt-md-5,.my-md-5{margin-top:3rem!important}.mr-md-5,.mx-md-5{margin-right:3rem!important}.mb-md-5,.my-md-5{margin-bottom:3rem!important}.ml-md-5,.mx-md-5{margin-left:3rem!important}.p-md-0{padding:0!important}.pt-md-0,.py-md-0{padding-top:0!important}.pr-md-0,.px-md-0{padding-right:0!important}.pb-md-0,.py-md-0{padding-bottom:0!important}.pl-md-0,.px-md-0{padding-left:0!important}.p-md-1{padding:.25rem!important}.pt-md-1,.py-md-1{padding-top:.25rem!important}.pr-md-1,.px-md-1{padding-right:.25rem!important}.pb-md-1,.py-md-1{padding-bottom:.25rem!important}.pl-md-1,.px-md-1{padding-left:.25rem!important}.p-md-2{padding:.5rem!important}.pt-md-2,.py-md-2{padding-top:.5rem!important}.pr-md-2,.px-md-2{padding-right:.5rem!important}.pb-md-2,.py-md-2{padding-bottom:.5rem!important}.pl-md-2,.px-md-2{padding-left:.5rem!important}.p-md-3{padding:1rem!important}.pt-md-3,.py-md-3{padding-top:1rem!important}.pr-md-3,.px-md-3{padding-right:1rem!important}.pb-md-3,.py-md-3{padding-bottom:1rem!important}.pl-md-3,.px-md-3{padding-left:1rem!important}.p-md-4{padding:1.5rem!important}.pt-md-4,.py-md-4{padding-top:1.5rem!important}.pr-md-4,.px-md-4{padding-right:1.5rem!important}.pb-md-4,.py-md-4{padding-bottom:1.5rem!important}.pl-md-4,.px-md-4{padding-left:1.5rem!important}.p-md-5{padding:3rem!important}.pt-md-5,.py-md-5{padding-top:3rem!important}.pr-md-5,.px-md-5{padding-right:3rem!important}.pb-md-5,.py-md-5{padding-bottom:3rem!important}.pl-md-5,.px-md-5{padding-left:3rem!important}.m-md-auto{margin:auto!important}.mt-md-auto,.my-md-auto{margin-top:auto!important}.mr-md-auto,.mx-md-auto{margin-right:auto!important}.mb-md-auto,.my-md-auto{margin-bottom:auto!important}.ml-md-auto,.mx-md-auto{margin-left:auto!important}}@media (min-width:992px){.m-lg-0{margin:0!important}.mt-lg-0,.my-lg-0{margin-top:0!important}.mr-lg-0,.mx-lg-0{margin-right:0!important}.mb-lg-0,.my-lg-0{margin-bottom:0!important}.ml-lg-0,.mx-lg-0{margin-left:0!important}.m-lg-1{margin:.25rem!important}.mt-lg-1,.my-lg-1{margin-top:.25rem!important}.mr-lg-1,.mx-lg-1{margin-right:.25rem!important}.mb-lg-1,.my-lg-1{margin-bottom:.25rem!important}.ml-lg-1,.mx-lg-1{margin-left:.25rem!important}.m-lg-2{margin:.5rem!important}.mt-lg-2,.my-lg-2{margin-top:.5rem!important}.mr-lg-2,.mx-lg-2{margin-right:.5rem!important}.mb-lg-2,.my-lg-2{margin-bottom:.5rem!important}.ml-lg-2,.mx-lg-2{margin-left:.5rem!important}.m-lg-3{margin:1rem!important}.mt-lg-3,.my-lg-3{margin-top:1rem!important}.mr-lg-3,.mx-lg-3{margin-right:1rem!important}.mb-lg-3,.my-lg-3{margin-bottom:1rem!important}.ml-lg-3,.mx-lg-3{margin-left:1rem!important}.m-lg-4{margin:1.5rem!important}.mt-lg-4,.my-lg-4{margin-top:1.5rem!important}.mr-lg-4,.mx-lg-4{margin-right:1.5rem!important}.mb-lg-4,.my-lg-4{margin-bottom:1.5rem!important}.ml-lg-4,.mx-lg-4{margin-left:1.5rem!important}.m-lg-5{margin:3rem!important}.mt-lg-5,.my-lg-5{margin-top:3rem!important}.mr-lg-5,.mx-lg-5{margin-right:3rem!important}.mb-lg-5,.my-lg-5{margin-bottom:3rem!important}.ml-lg-5,.mx-lg-5{margin-left:3rem!important}.p-lg-0{padding:0!important}.pt-lg-0,.py-lg-0{padding-top:0!important}.pr-lg-0,.px-lg-0{padding-right:0!important}.pb-lg-0,.py-lg-0{padding-bottom:0!important}.pl-lg-0,.px-lg-0{padding-left:0!important}.p-lg-1{padding:.25rem!important}.pt-lg-1,.py-lg-1{padding-top:.25rem!important}.pr-lg-1,.px-lg-1{padding-right:.25rem!important}.pb-lg-1,.py-lg-1{padding-bottom:.25rem!important}.pl-lg-1,.px-lg-1{padding-left:.25rem!important}.p-lg-2{padding:.5rem!important}.pt-lg-2,.py-lg-2{padding-top:.5rem!important}.pr-lg-2,.px-lg-2{padding-right:.5rem!important}.pb-lg-2,.py-lg-2{padding-bottom:.5rem!important}.pl-lg-2,.px-lg-2{padding-left:.5rem!important}.p-lg-3{padding:1rem!important}.pt-lg-3,.py-lg-3{padding-top:1rem!important}.pr-lg-3,.px-lg-3{padding-right:1rem!important}.pb-lg-3,.py-lg-3{padding-bottom:1rem!important}.pl-lg-3,.px-lg-3{padding-left:1rem!important}.p-lg-4{padding:1.5rem!important}.pt-lg-4,.py-lg-4{padding-top:1.5rem!important}.pr-lg-4,.px-lg-4{padding-right:1.5rem!important}.pb-lg-4,.py-lg-4{padding-bottom:1.5rem!important}.pl-lg-4,.px-lg-4{padding-left:1.5rem!important}.p-lg-5{padding:3rem!important}.pt-lg-5,.py-lg-5{padding-top:3rem!important}.pr-lg-5,.px-lg-5{padding-right:3rem!important}.pb-lg-5,.py-lg-5{padding-bottom:3rem!important}.pl-lg-5,.px-lg-5{padding-left:3rem!important}.m-lg-auto{margin:auto!important}.mt-lg-auto,.my-lg-auto{margin-top:auto!important}.mr-lg-auto,.mx-lg-auto{margin-right:auto!important}.mb-lg-auto,.my-lg-auto{margin-bottom:auto!important}.ml-lg-auto,.mx-lg-auto{margin-left:auto!important}}@media (min-width:1200px){.m-xl-0{margin:0!important}.mt-xl-0,.my-xl-0{margin-top:0!important}.mr-xl-0,.mx-xl-0{margin-right:0!important}.mb-xl-0,.my-xl-0{margin-bottom:0!important}.ml-xl-0,.mx-xl-0{margin-left:0!important}.m-xl-1{margin:.25rem!important}.mt-xl-1,.my-xl-1{margin-top:.25rem!important}.mr-xl-1,.mx-xl-1{margin-right:.25rem!important}.mb-xl-1,.my-xl-1{margin-bottom:.25rem!important}.ml-xl-1,.mx-xl-1{margin-left:.25rem!important}.m-xl-2{margin:.5rem!important}.mt-xl-2,.my-xl-2{margin-top:.5rem!important}.mr-xl-2,.mx-xl-2{margin-right:.5rem!important}.mb-xl-2,.my-xl-2{margin-bottom:.5rem!important}.ml-xl-2,.mx-xl-2{margin-left:.5rem!important}.m-xl-3{margin:1rem!important}.mt-xl-3,.my-xl-3{margin-top:1rem!important}.mr-xl-3,.mx-xl-3{margin-right:1rem!important}.mb-xl-3,.my-xl-3{margin-bottom:1rem!important}.ml-xl-3,.mx-xl-3{margin-left:1rem!important}.m-xl-4{margin:1.5rem!important}.mt-xl-4,.my-xl-4{margin-top:1.5rem!important}.mr-xl-4,.mx-xl-4{margin-right:1.5rem!important}.mb-xl-4,.my-xl-4{margin-bottom:1.5rem!important}.ml-xl-4,.mx-xl-4{margin-left:1.5rem!important}.m-xl-5{margin:3rem!important}.mt-xl-5,.my-xl-5{margin-top:3rem!important}.mr-xl-5,.mx-xl-5{margin-right:3rem!important}.mb-xl-5,.my-xl-5{margin-bottom:3rem!important}.ml-xl-5,.mx-xl-5{margin-left:3rem!important}.p-xl-0{padding:0!important}.pt-xl-0,.py-xl-0{padding-top:0!important}.pr-xl-0,.px-xl-0{padding-right:0!important}.pb-xl-0,.py-xl-0{padding-bottom:0!important}.pl-xl-0,.px-xl-0{padding-left:0!important}.p-xl-1{padding:.25rem!important}.pt-xl-1,.py-xl-1{padding-top:.25rem!important}.pr-xl-1,.px-xl-1{padding-right:.25rem!important}.pb-xl-1,.py-xl-1{padding-bottom:.25rem!important}.pl-xl-1,.px-xl-1{padding-left:.25rem!important}.p-xl-2{padding:.5rem!important}.pt-xl-2,.py-xl-2{padding-top:.5rem!important}.pr-xl-2,.px-xl-2{padding-right:.5rem!important}.pb-xl-2,.py-xl-2{padding-bottom:.5rem!important}.pl-xl-2,.px-xl-2{padding-left:.5rem!important}.p-xl-3{padding:1rem!important}.pt-xl-3,.py-xl-3{padding-top:1rem!important}.pr-xl-3,.px-xl-3{padding-right:1rem!important}.pb-xl-3,.py-xl-3{padding-bottom:1rem!important}.pl-xl-3,.px-xl-3{padding-left:1rem!important}.p-xl-4{padding:1.5rem!important}.pt-xl-4,.py-xl-4{padding-top:1.5rem!important}.pr-xl-4,.px-xl-4{padding-right:1.5rem!important}.pb-xl-4,.py-xl-4{padding-bottom:1.5rem!important}.pl-xl-4,.px-xl-4{padding-left:1.5rem!important}.p-xl-5{padding:3rem!important}.pt-xl-5,.py-xl-5{padding-top:3rem!important}.pr-xl-5,.px-xl-5{padding-right:3rem!important}.pb-xl-5,.py-xl-5{padding-bottom:3rem!important}.pl-xl-5,.px-xl-5{padding-left:3rem!important}.m-xl-auto{margin:auto!important}.mt-xl-auto,.my-xl-auto{margin-top:auto!important}.mr-xl-auto,.mx-xl-auto{margin-right:auto!important}.mb-xl-auto,.my-xl-auto{margin-bottom:auto!important}.ml-xl-auto,.mx-xl-auto{margin-left:auto!important}}.text-monospace{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}.text-justify{text-align:justify!important}.text-nowrap{white-space:nowrap!important}.text-truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.text-left{text-align:left!important}.text-right{text-align:right!important}.text-center{text-align:center!important}@media (min-width:576px){.text-sm-left{text-align:left!important}.text-sm-right{text-align:right!important}.text-sm-center{text-align:center!important}}@media (min-width:768px){.text-md-left{text-align:left!important}.text-md-right{text-align:right!important}.text-md-center{text-align:center!important}}@media (min-width:992px){.text-lg-left{text-align:left!important}.text-lg-right{text-align:right!important}.text-lg-center{text-align:center!important}}@media (min-width:1200px){.text-xl-left{text-align:left!important}.text-xl-right{text-align:right!important}.text-xl-center{text-align:center!important}}.text-lowercase{text-transform:lowercase!important}.text-uppercase{text-transform:uppercase!important}.text-capitalize{text-transform:capitalize!important}.font-weight-light{font-weight:300!important}.font-weight-normal{font-weight:400!important}.font-weight-bold{font-weight:700!important}.font-italic{font-style:italic!important}.text-white{color:#fff!important}.text-primary{color:#007bff!important}a.text-primary:focus,a.text-primary:hover{color:#0062cc!important}.text-secondary{color:#6c757d!important}a.text-secondary:focus,a.text-secondary:hover{color:#545b62!important}.text-success{color:#28a745!important}a.text-success:focus,a.text-success:hover{color:#1e7e34!important}.text-info{color:#17a2b8!important}a.text-info:focus,a.text-info:hover{color:#117a8b!important}.text-warning{color:#ffc107!important}a.text-warning:focus,a.text-warning:hover{color:#d39e00!important}.text-danger{color:#dc3545!important}a.text-danger:focus,a.text-danger:hover{color:#bd2130!important}.text-light{color:#f8f9fa!important}a.text-light:focus,a.text-light:hover{color:#dae0e5!important}.text-dark{color:#343a40!important}a.text-dark:focus,a.text-dark:hover{color:#1d2124!important}.text-body{color:#212529!important}.text-muted{color:#6c757d!important}.text-black-50{color:rgba(0,0,0,.5)!important}.text-white-50{color:rgba(255,255,255,.5)!important}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.visible{visibility:visible!important}.invisible{visibility:hidden!important}@media print{*,::after,::before{text-shadow:none!important;box-shadow:none!important}a:not(.btn){text-decoration:underline}abbr[title]::after{content:" (" attr(title) ")"}pre{white-space:pre-wrap!important}blockquote,pre{border:1px solid #adb5bd;page-break-inside:avoid}thead{display:table-header-group}img,tr{page-break-inside:avoid}h2,h3,p{orphans:3;widows:3}h2,h3{page-break-after:avoid}@page{size:a3}body{min-width:992px!important}.container{min-width:992px!important}.navbar{display:none}.badge{border:1px solid #000}.table{border-collapse:collapse!important}.table td,.table th{background-color:#fff!important}.table-bordered td,.table-bordered th{border:1px solid #dee2e6!important}.table-dark{color:inherit}.table-dark tbody+tbody,.table-dark td,.table-dark th,.table-dark thead th{border-color:#dee2e6}.table .thead-dark th{color:inherit;border-color:#dee2e6}} +/*# sourceMappingURL=bootstrap.min.css.map */ \ No newline at end of file diff --git a/code/datastudio/db_assistant/css/demo.css b/code/datastudio/db_assistant/css/demo.css new file mode 100644 index 0000000000000000000000000000000000000000..b0959aa43656c8c27fde8bbf8e296e0d03533882 --- /dev/null +++ b/code/datastudio/db_assistant/css/demo.css @@ -0,0 +1,189 @@ +@charset "utf-8" + +.windowTitle{ +font-size: 16px; +font-family:"Microsoft YaHei"; +color: #ffffff; +vertical-align:middle; +padding-left:7px; +} + +body +{ +font-size: 14px; +font-family:"Microsoft YaHei"; +color: #333333; +line-height:1.3; +background-color:#f5f7fa; +padding:0 0 0 0; +margin:0 0 0 0; +} + +ul,li{margin:0px 0px 0px 5px;padding:0px 0px 0px 5px;} + +table +{ +font-size: 14px; +font-family:"Microsoft YaHei"; +} + +table caption +{ +padding:10 0 8 0; +} + +.fignone{ +padding:8 0 10 0; +} + +.figcap{ +line-height:36px; +} + +.notice{ +background:#fdfced; +padding:8 0 5 5; +} + +.note{ +background:#fdfced; +padding:8 0 2 2; +} + +.windowTitleText{ +font-size: 15px; +font-family:"Microsoft YaHei"; +color: #ffffff; +vertical-align:middle; +padding-left:7px; +font-weight:normal; +} + +.div-ab{ float:none;width:99.6%;height:1px;padding:0 0 0 0;} +.div-a{ float:left;width:50%;height:34px;padding:10 0 0 0;background-color:#83a3f0;vertical-align:middle;} +.div-b{ float:right;width:50%;height:34px;padding:10 0 0 0;background-color:#83A2F2;vertical-align:middle;} +.div-cd{ display:none;width:99.4%;height:100px;background:#eff4fe;border: 1px solid #83A2F2;} +.div-c{ float:left;width:90%;padding-top:15px} +.div-d{ float:right;width:10%;padding-top:15px} +.div-e{ display:none;width:99.4%;height:395px;background:#eff4fe;margin-top:0px;border: 1px solid #83A2F2;padding-top:10px} + +.sectionTitle{ +font-size: 15px; +font-family:"Microsoft YaHei"; +color: #005ebe; +line-height:26px; +valigh: middle; +font-weight:normal; +} + +.pText{ +line-height:20px; +} + +.preText{ +font-size: 11px; +background:#dfe8fa; +padding:5 0 5 5; +white-space: pre-wrap; +white-space: -moz-pre-wrap; +white-space: -pre-wrap; +white-space: -o-pre-wrap; +word-wrap: break-word; +white-space: normal; +line-height:16px; +} + + +.screen{ +font-size: 13px; +background:#ebeef1; +padding:5 0 5 5; +line-height:22px; +} + +.fieldExpText{ +font-size: 14px; +font-family:"Microsoft YaHei"; +color: #777777; +line-height:22px; +} + +.sectionText{ +font-size: 14px; +font-family:"Microsoft YaHei"; +color: #333333; +line-height:24px; +} + +.sectionSugTitle{ +font-size: 15px; +font-family: "Microsoft YaHei"; +color: #ed6b44; +} + +.sectionCmdTitle{ +font-size: 17px; +font-family: "Microsoft YaHei"; +color: #005ebe; +font-weight:normal; +} + +.sectionTextRed{ +font-size: 14px; +font-family:"Microsoft YaHei"; +color: #ed6b44; +} + +a.linkText:link { +font-size: 14px; +font-family:"Microsoft YaHei"; +color: #016bd8; +text-decoration: none; +line-height:22px; +} +a.linkText:visited { +font-size: 14px; +font-family:"Microsoft YaHei"; +color: #9e46dc; +text-decoration: none; +line-height:22px; +} +a.linkText:hover { +font-size: 14px; +font-family:"Microsoft YaHei"; +color: #1c88f7; +line-height:22px; +} + +.hrStyle{ +height:0px; +border-top:1px solid #cccccc; +border-right:0px; +border-bottom:0px; +border-left:0px'; +} + +.inputStyle{ +width:100%; +height:24px; +padding-left:4px; +border-radius:4px; +border:#83a3f0 1px solid; +vertical-align:middle; +} + +.buttonStyle{ +cursor:hand; +padding:5 5 5 5; +background-color:#83A2F2; +color:white; +vertical-align: middle; +} +pre.screen{ +padding:5px 5px 5px 5px; +background-color:#F0F0F0; +margin-top:2px; +margin-bottom:2px; +WORD-BREAK: break-all; +WORD-WRAP: break-word; +} \ No newline at end of file diff --git a/code/datastudio/db_assistant/css/enter_list.css b/code/datastudio/db_assistant/css/enter_list.css new file mode 100644 index 0000000000000000000000000000000000000000..f5ec6654c7793e78596855fb3b832603c15bbb59 --- /dev/null +++ b/code/datastudio/db_assistant/css/enter_list.css @@ -0,0 +1,156 @@ +body { + font-size: 14px; + font-family: "Microsoft YaHei"; + color: #333333; + line-height: 1.3; + background-color: #f5f7fa; + padding: 0 0 0 0; + margin: 0 0 0 0; +} + + +/* 点击按钮进入后的CSS样式 */ + +div.section-header ol.breadcrumb { + display: flex; + padding: 0px; + list-style: none; + margin-bottom: 0px; + background-color: #F7F7F7; + border-radius: 0px; +} + + +/* 首页字体颜色 */ + +div.section-header li.breadcrumb-item a { + text-decoration: none; + color: #666666; +} + +div.section-header { + padding-bottom: 10px; + margin-bottom: 20px; + margin-left: 20px; + border-bottom: 1px dashed #c6c6c6; +} + +li.breadcrumb-item { + padding: 0px; + margin: 0px; + font-size: 14px; + line-height: 15px; +} + + +/* +:代表相邻俩个元素之间 */ + +div.section-header li.breadcrumb-item+li.breadcrumb-item::before { + content: ">"; +} + +div.operationName { + margin-left: 20px; + height: 16px; + font-size: 16px; + line-height: 15px; + margin-bottom: 20px; + color: #0470c4; +} + +div.promptStatement { + margin-left: 20px; + margin-bottom: 10px; + height: 15px; + font-size: 14px; + line-height: 15px; + color: #666666; +} + +thead.tablehead { + background-color: #0371C3; + color: #FFFFFF; + width: 518px; + height: 23px; +} + +table.operShowTable { + margin-left: 20px; +} + +table { + background-color: #EFEFEF; + font-family: arial, sans-serif; + border-collapse: collapse; + width: calc(100% - 20px); +} + +th { + border: 1px solid #dddddd; + text-align: left; + font-size: 14px; + line-height: 15px; + height: 24px; +} + +td { + border: 1px solid #dddddd; + text-align: left; + font-size: 12px; + line-height: 15px; + height: 24px; +} + +tr:nth-child(even) { + background-color: #E0E0E0; +} + +tbody tr:hover { + background-color: rgb(127, 194, 245); +} + +.font_color { + color: #0470c4; +} + +.description { + background-color: #EFEFEF; + width: 100%; +} + +.title_task { + width: 50px; +} + +.title_cmd { + width: 100px; +} + + +/*第三级页面 */ + +.grammaticalContent { + margin-left: 20px; +} + +.sectionCmdTitle { + font-family: "Microsoft YaHei"; + /* width: 101px; + height: 14px; */ + font-size: 16px; + font-weight: normal; + font-stretch: normal; + line-height: 15px; + letter-spacing: 0px; + color: #0470c4!important; + margin-bottom: 20px; +} + +.sectionTitle { + font-size: 15px; + font-family: "Microsoft YaHei"; + color: #005ebe; + line-height: 26px; + valigh: middle; + font-weight: normal; +} \ No newline at end of file diff --git a/code/datastudio/db_assistant/css/index.css b/code/datastudio/db_assistant/css/index.css new file mode 100644 index 0000000000000000000000000000000000000000..429c55588a6fe93cf7ff61897c409e9e7d77a235 --- /dev/null +++ b/code/datastudio/db_assistant/css/index.css @@ -0,0 +1,192 @@ +.safe_area { + /* width: 566px; */ + width: 100%; +} + +.buttontitlearea { + margin-top: 20px; + height: 25px; + width: 350px; + padding: 0px 20px 0px 20px; +} + +.contentArea { + margin-top: 10px; + width: 100%; +} + +.button-title-Item { + background-color: #E6E6E6; + float: left; + margin-right: 2px; + height: 22px; + font-size: 14px; + line-height: 14px; + color: #333333; + cursor: pointer; +} + +.button-title-Item-sm { + width: 60px; +} + +.button-title-Item-md { + width: 80px; +} + +.button-title-Item:hover { + background-color: #0371C3; + color: #FFFFFF; + box-shadow: 0 0 0 #FFFFFF; +} + +.button-title-Item.active { + background-color: #0371C3; + color: #FFFFFF; +} + +.hidden { + display: none!important; +} + +.button-item { + height: 20px; + width: 100px; + margin-right: 20px; +} + +.center { + display: flex; + justify-content: center; + align-items: center; +} + +p { + margin: 0px 0px 0px 0px; +} + +#grammarContent { + padding: 0px 20px 0px 20px; +} + +.grammar_content_title { + width: 350px; +} + + +/* 输入框的样式 */ + +.keywordselect { + font-size: 10px; + line-height: 14px; + width: 224px; + height: 19px; + border: solid 1px #0470c4; +} + +.grammar-item-one { + margin-bottom: 10px; + width: 100%; +} + + +/* 返回箭头 */ + +.grammar-item-goback { + line-height: 22px; + /* display: inline-flex; */ + position: fixed; + top: 60px; + left: 300px; + margin: 0 0 0 2; + padding-left: 6px; + padding-right: 1px; + border-radius: 4px; + border: 0px solid; + border-color: #aaa9a9; + cursor: pointer; +} + + +/* 列表框的样式 */ + +.keyInfoStyle { + position: absolute; + z-index: 9999; + display: none; + font-weight: normal; + font-style: normal; + border: 1px solid rgb(0, 110, 195); + color: rgb(0, 0, 0); + background-color: rgb(238, 238, 238); + overflow: auto; + left: 80px; + top: 78px; + width: 221px!important; +} + +.grammar-font { + height: 14px; + width: 55px; + font-size: 12px; + line-height: 14px; + color: #666666; + align-items: center; +} + +.operationTip { + padding: 0px 20px 0px 20px; +} + +.operationTipTnfo { + font-size: 12px; + line-height: 15px; + color: #666666; +} + +.operationTipselect { + width: 137px; + height: 15px; + font-size: 14px; + line-height: 15px; + margin-top: 20px; + color: #0470c4; +} + +.contentTitle { + display: flex; + width: calc(100% - 66px); + font-size: 14px; + line-height: 15px; + padding: 10px 0px 10px 0px; + margin: 0px 20px 0px 20px; + color: #666666; + border-bottom: 1px dashed #c6c6c6; +} + +.button-item-A { + text-decoration: none; + color: #666666; +} + +.button-item { + float: left; + width: 100px; + height: 32px; + font-size: 12px; + border: 1px solid #1083f1; + color: #0470c4; + border-radius: 6px; + margin: 10px 0px 10px 20px; +} + +.button-item:hover { + background-color: #0371C3; + color: #FFFFFF; + box-shadow: 0 0 0 #FFFFFF; +} + +.button-item.active { + background-color: #0371C3; + color: #FFFFFF; +} \ No newline at end of file diff --git a/code/datastudio/db_assistant/css/scrollBar.css b/code/datastudio/db_assistant/css/scrollBar.css new file mode 100644 index 0000000000000000000000000000000000000000..63ff1344ac7a1f8ec679cbacaf446148a5e113d9 --- /dev/null +++ b/code/datastudio/db_assistant/css/scrollBar.css @@ -0,0 +1,31 @@ +.zl-scrollBarBox{ + height:100%; + position:absolute; + background:#f3f3f3; +} +.zl-scrollBar{ + position:absolute; + left:0; + top:0; + background:#A5BFDD; + transition:background 0.3s; +} +.zl-scrollBar.zl-verticalBar{ + min-height:10px; +} + +.zl-scrollBar.zl-horizontalBar{ + min-width:10px; +} +.zl-scrollBar:hover{ + background:#A5BFDD; +} +.zl-scrollContentDiv{ + position:relative !important; + width:100% !important; + height:100% !important; + padding:0 !important; + margin:0 !important; + top:0; + left:0; +} \ No newline at end of file diff --git a/code/datastudio/db_assistant/dbassist.properties b/code/datastudio/db_assistant/dbassist.properties new file mode 100644 index 0000000000000000000000000000000000000000..aaa5102ec1f355baede4b8e695d94e0158d162fb --- /dev/null +++ b/code/datastudio/db_assistant/dbassist.properties @@ -0,0 +1 @@ +GAUSS200=openGauss 1.0.0 \ No newline at end of file diff --git a/code/datastudio/db_assistant/enter_list.html b/code/datastudio/db_assistant/enter_list.html new file mode 100644 index 0000000000000000000000000000000000000000..b747429c329e31f80dc43ab0b81d56f75e1f34b0 --- /dev/null +++ b/code/datastudio/db_assistant/enter_list.html @@ -0,0 +1,59 @@ + + + + + + SQL助手 + + + + + + + + + + + +
+
+
语法
+
操作列表
+ +
+
+
+
+ +
+
+ +
+ 选择您要做的具体操作: +
+
+
+ + + + + + + + + + + +
任务命令说明
+
+ +
+
+ +
+ \ No newline at end of file diff --git a/code/datastudio/db_assistant/enter_list_next.html b/code/datastudio/db_assistant/enter_list_next.html new file mode 100644 index 0000000000000000000000000000000000000000..6f1d20712cd93be4152f35e8b60c7cff7a8d86bf --- /dev/null +++ b/code/datastudio/db_assistant/enter_list_next.html @@ -0,0 +1,43 @@ + + + + + + SQL助手 + + + + + + + + + + + + +
+
+
语法
+
操作列表
+ +
+
+
+
+ +
+
+
+

在中间窗口中,选中SQL语句,SQL助手会显示对应的说明信息

+
+
+
+
+ + \ No newline at end of file diff --git a/code/datastudio/db_assistant/img/ask.png b/code/datastudio/db_assistant/img/ask.png new file mode 100644 index 0000000000000000000000000000000000000000..5bc9f844e2295e7ba4effed3d1280a5ab0c8aa3f Binary files /dev/null and b/code/datastudio/db_assistant/img/ask.png differ diff --git a/code/datastudio/db_assistant/img/ask1.png b/code/datastudio/db_assistant/img/ask1.png new file mode 100644 index 0000000000000000000000000000000000000000..8b25f154885e5972c30e0991e67cfad162b4622b Binary files /dev/null and b/code/datastudio/db_assistant/img/ask1.png differ diff --git a/code/datastudio/db_assistant/img/assistantCopy.png b/code/datastudio/db_assistant/img/assistantCopy.png new file mode 100644 index 0000000000000000000000000000000000000000..1f6899bd024e3254111a28b93ee17f63b63b568a Binary files /dev/null and b/code/datastudio/db_assistant/img/assistantCopy.png differ diff --git a/code/datastudio/db_assistant/img/closeblue.png b/code/datastudio/db_assistant/img/closeblue.png new file mode 100644 index 0000000000000000000000000000000000000000..7abc92c3e43b1e116b41229d7bca3bc19907c8ed Binary files /dev/null and b/code/datastudio/db_assistant/img/closeblue.png differ diff --git a/code/datastudio/db_assistant/img/comp.png b/code/datastudio/db_assistant/img/comp.png new file mode 100644 index 0000000000000000000000000000000000000000..a7315f5c6bc5107b6ed06002b53baa2e4b2ee126 Binary files /dev/null and b/code/datastudio/db_assistant/img/comp.png differ diff --git a/code/datastudio/db_assistant/img/doc.png b/code/datastudio/db_assistant/img/doc.png new file mode 100644 index 0000000000000000000000000000000000000000..b022d51d4a47a7bb22c2684b977a2690e3e0111d Binary files /dev/null and b/code/datastudio/db_assistant/img/doc.png differ diff --git a/code/datastudio/db_assistant/img/down.png b/code/datastudio/db_assistant/img/down.png new file mode 100644 index 0000000000000000000000000000000000000000..4a658495f2ea7a8e69168c22371a99344d22b2b3 Binary files /dev/null and b/code/datastudio/db_assistant/img/down.png differ diff --git a/code/datastudio/db_assistant/img/goback.png b/code/datastudio/db_assistant/img/goback.png new file mode 100644 index 0000000000000000000000000000000000000000..c3781498998605cdfbdeae25b87a46c46fd86448 Binary files /dev/null and b/code/datastudio/db_assistant/img/goback.png differ diff --git a/code/datastudio/db_assistant/img/openblue.png b/code/datastudio/db_assistant/img/openblue.png new file mode 100644 index 0000000000000000000000000000000000000000..534f075458d2aabf2d96c81c6617e6222bc7627b Binary files /dev/null and b/code/datastudio/db_assistant/img/openblue.png differ diff --git a/code/datastudio/db_assistant/img/remove.png b/code/datastudio/db_assistant/img/remove.png new file mode 100644 index 0000000000000000000000000000000000000000..319811e382e9da30bb7beca9e85955fb651fcf93 Binary files /dev/null and b/code/datastudio/db_assistant/img/remove.png differ diff --git a/code/datastudio/db_assistant/img/search.png b/code/datastudio/db_assistant/img/search.png new file mode 100644 index 0000000000000000000000000000000000000000..c513e123b8fdcc9053bb88b68642e2943e3e1820 Binary files /dev/null and b/code/datastudio/db_assistant/img/search.png differ diff --git a/code/datastudio/db_assistant/img/search2.png b/code/datastudio/db_assistant/img/search2.png new file mode 100644 index 0000000000000000000000000000000000000000..4e6af850506e05605ba89d8c7b6e60683ea389c4 Binary files /dev/null and b/code/datastudio/db_assistant/img/search2.png differ diff --git a/code/datastudio/db_assistant/img/up.png b/code/datastudio/db_assistant/img/up.png new file mode 100644 index 0000000000000000000000000000000000000000..9c0abf14b5b4ebfa383f25768dee2e890b76af2a Binary files /dev/null and b/code/datastudio/db_assistant/img/up.png differ diff --git a/code/datastudio/db_assistant/index_en.html b/code/datastudio/db_assistant/index_en.html new file mode 100644 index 0000000000000000000000000000000000000000..0cce35b1cf7180523f6cd39f176ac10623178e7a --- /dev/null +++ b/code/datastudio/db_assistant/index_en.html @@ -0,0 +1,487 @@ + + + + + SQL Assitant + + + + + + + + + + + +
Syntaxes:
+ +

In the middle window, if you choose the related SQL, the SQL assistant will show the related information.

+ + \ No newline at end of file diff --git a/code/datastudio/db_assistant/index_zh.html b/code/datastudio/db_assistant/index_zh.html new file mode 100644 index 0000000000000000000000000000000000000000..96cdc0a30267cae2d7575e135231828b2e96e7da --- /dev/null +++ b/code/datastudio/db_assistant/index_zh.html @@ -0,0 +1,113 @@ + + + + + + SQL助手 + + + + + + + + + + + + +
+
+
语法
+
操作列表
+ +
+
+
+
+
所有语法: + +
+
+ + +
+
+
+
+ +
+
+ + +
+ + + \ No newline at end of file diff --git a/code/datastudio/db_assistant/js/enter_list.js b/code/datastudio/db_assistant/js/enter_list.js new file mode 100644 index 0000000000000000000000000000000000000000..6590a0f37b8b8cd81e136966f09072fd04ea3eb5 --- /dev/null +++ b/code/datastudio/db_assistant/js/enter_list.js @@ -0,0 +1,187 @@ +var recordpath = getCookie("recordDataPath"); +var datajspath = "" +document.write(datajspath); +// document.write(""); +var tbodyTdbId = document.getElementById("tbodyTdbId"); +var nameS = undefined; +var tempClass = []; +var tempSuggestion = ""; +var num = 0; +var record = 0; +var tempClassBool = true; +var bool = false; +var commandIdArr = []; +var commandName = []; +var allcmds = []; +var description = ""; + +function LoadXmlSuggestion(recordpath) { + commands = new Commands(); + var xml = new ActiveXObject("Microsoft.XMLDOM"); + xml.async = false; + xml.load(recordpath + "/suggestion.xml"); + commands.load(xml); + allcmds = commands.cmds; +} +//获取功能描述的内容添加到说明对应的位置 +function getSQLHtmlForDescription(tempValues, NameSnext) { + $.each(tempValues, function(n, v) { + if (v.alias == NameSnext || NameSnext == v.id) { + $("#getdescriptioncontent").html(v.suggestion); + description = $("div.section-item-content p:first").text(); + } + }); +} + +function  GetChinese(strValue)  {     + if (strValue !=  null  &&  strValue !=  "") {          + var  reg  =  /[\u4e00-\u9fa5]/g;           + return strValue.match(reg).join("");      + }       + else { + return  "";   + }           +}  + +function responseButton() { + //用heroers存储json文件里menbers的信息 + var heroes = db['sheet2']; + for (var i = 0; i < heroes.length; i++) { + var commandId = "commandId" + num; + if (nameS == heroes[i].功能大类) { + if (heroes[i].功能子类 != "") { + var tbodySubClassId = "#" + heroes[i].功能子类; + for (var j = 0; j <= tempClass.length; j++) { + if (tempClass[j] == heroes[i].功能子类) { + tempClassBool = false; + } + } + if (tempClassBool) { + + tempClass[tempClass.length] = heroes[i].功能子类; + tempSuggestion = "
" + heroes[i].功能子类 + "
" + "
任务命令说明
"; + $('#haveSubclass').append(tempSuggestion); + } + tempClassBool = true; + getSQLHtmlForDescription(allcmds, heroes[i].操作命令); + tempSuggestion = "" + heroes[i].任务名称 + "" + heroes[i].操作命令 + "" + description + ""; + commandIdArr[commandIdArr.length] = commandId; + num++; + $(tbodySubClassId).append(tempSuggestion); + $("#noSubclass").addClass("hidden"); + $("#haveSubclass").removeClass("hidden"); + } else { + $("#noSubclass").removeClass("hidden"); + $("#haveSubclass").addClass("hidden"); + getSQLHtmlForDescription(allcmds, heroes[i].操作命令); + tempSuggestion = "" + heroes[i].任务名称 + "" + heroes[i].操作命令 + "" + description + "" + commandIdArr[commandIdArr.length] = commandId; + num++; + $('#tbodyTdbId').append(tempSuggestion); + } + + + } else if (nameS == heroes[i].大场景) { + if (heroes[i].子场景 != "") { + if (tempClass != heroes[i].子场景) { + tempSuggestion = "
" + heroes[i].子场景 + "
" + "任务命令说明"; + $('#haveSubclass').append(tempSuggestion); + } + getSQLHtmlForDescription(allcmds, heroes[i].操作命令); + tempSuggestion = "" + heroes[i].任务名称 + "" + heroes[i].操作命令 + "" + description + ""; + commandIdArr[commandIdArr.length] = commandId; + num++; + $('#haveSubclass').append(tempSuggestion); + $("#noSubclass").addClass("hidden"); + $("#haveSubclass").removeClass("hidden"); + } else { + $("#noSubclass").removeClass("hidden"); + $("#haveSubclass").addClass("hidden"); + getSQLHtmlForDescription(allcmds, heroes[i].操作命令); + tempSuggestion = "" + heroes[i].任务名称 + "" + heroes[i].操作命令 + "" + description + "" + commandIdArr[commandIdArr.length] = commandId; + num++; + $('#tbodyTdbId').append(tempSuggestion); + + } + } else if (nameS == heroes[i].操作类别1) { + getSQLHtmlForDescription(allcmds, heroes[i].操作命令); + tempSuggestion = "" + heroes[i].任务名称 + "" + heroes[i].操作命令 + "" + description + "" + commandIdArr[commandIdArr.length] = commandId; + num++; + $('#tbodyTdbId').append(tempSuggestion); + + } else if (nameS == heroes[i].操作类别2) { + getSQLHtmlForDescription(allcmds, heroes[i].操作命令); + tempSuggestion = "" + heroes[i].任务名称 + "" + heroes[i].操作命令 + "" + description + "" + commandIdArr[commandIdArr.length] = commandId; + num++; + $('#tbodyTdbId').append(tempSuggestion); + + } else if (nameS == heroes[i].操作类别3) { + getSQLHtmlForDescription(allcmds, heroes[i].操作命令); + tempSuggestion = "" + heroes[i].任务名称 + "" + heroes[i].操作命令 + "" + description + "" + commandIdArr[commandIdArr.length] = commandId; + num++; + $('#tbodyTdbId').append(tempSuggestion); + + } + } +} +//读取cookies +function getCookie(name) { + var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); + + if (arr = document.cookie.match(reg)) + + return unescape(arr[2]); + else + return null; +} + +function getParams(key) { + var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)"); + var r = window.location.search.substr(1).match(reg); + if (r != null) { + return unescape(r[2]); + } + return null; +}; +$(function() { + $("#grammarNext").click(function() { + location.href = "index_zh.html"; + $(this).addClass("active"); + $("#operationListNext").removeClass("active"); + $("#beginnerGuideNext").removeClass("active"); + $("#caseNext").removeClass("active"); + }); + $("#beginnerGuideNext").click(function() { + $(this).addClass("active"); + $("#operationListNext").removeClass("active"); + $("#grammarNext").removeClass("active"); + $("#caseNext").removeClass("active"); + }); + + $("#caseNext").click(function() { + $(this).addClass("active"); + $("#operationListNext").removeClass("active"); + $("#beginnerGuideNext").removeClass("active"); + $("#grammarNext").removeClass("active"); + }); + var heroes = db['sheet1']; + bool = getParams("param3"); + if (bool) { + record = getParams("param4"); + } else { + record = getParams("param"); + } + nameS = heroes[record].分类名称; + $("#operNameS").text(nameS); + $("#operNameB").html(function() { + var operNameContentB = "" + nameS + "" + return operNameContentB; + }); + LoadXmlSuggestion(recordpath); + responseButton(); + +}); \ No newline at end of file diff --git a/code/datastudio/db_assistant/js/enter_list_next.js b/code/datastudio/db_assistant/js/enter_list_next.js new file mode 100644 index 0000000000000000000000000000000000000000..d715b28defc754df0e19eec5fe0ce1928085528a --- /dev/null +++ b/code/datastudio/db_assistant/js/enter_list_next.js @@ -0,0 +1,231 @@ +var recordpath = getCookie("recordDataPath"); +var datajspath = "" +document.write(datajspath); +//document.write(""); +var isNotSingle = true; +var selectedCmdAlias = "temp"; +var formerCmd = ""; +var cur_cmd = ""; +var NameSnext; +//读取cookies +function getCookie(name) { + var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); + + if (arr = document.cookie.match(reg)) + + return unescape(arr[2]); + else + return null; +} + +function isHidden(oDiv) { + var vDiv = oDiv.nextSibling; + while (vDiv.nodeType == 3) { + vDiv = vDiv.nextSibling; + } + vDiv.style.display = (vDiv.style.display == 'none') ? 'block' : 'none'; + var pngs = oDiv.getElementsByTagName("img"); + switch (pngs[1].style.display) { + case 'none': + pngs[0].style.display = 'none'; + pngs[1].style.display = 'inline'; + break; + case 'inline': + pngs[0].style.display = 'inline'; + pngs[1].style.display = 'none'; + break; + } +} + +function LoadSuggestion(recordpath) { + commands = new Commands(); + var xml = new ActiveXObject("Microsoft.XMLDOM"); + xml.async = false; + xml.load(recordpath + "/suggestion.xml"); + commands.load(xml); + getSQLHtmlForConent(commands.cmds); + +} + + + +function getSQLHtmlForConent(tempValues) { + + $.each(tempValues, function(n, v) { + if (v.alias == NameSnext || NameSnext == v.id) { + processInput(NameSnext); + } + }); +} + +function processInput(tempId) { + tempId = $.trim(tempId); //trim()方法从字符串的两边删除空格 + if ("" != tempId) { + var tempIds = tempId.split(/;/); //split()方法用于将字符串拆分为子字符串数组,并返回新数组 + tempId = tempIds[tempIds.length - 1]; + if ("" == tempId || "$$" == tempId) tempId = tempIds[tempIds.length - 2]; + var tokens = StringReader(tempId); + var tempCmds = []; + var cur_pos = 0; + for (var li = 0; li < tokens.length; li++) { + if (tempCmds.length == 0) { + tempCmds = commands.find(tokens[li].toUpperCase(), cur_pos); //toUpperCase() 方法用于把字符串转换为大写 + if (tempCmds.length != 0) { + cur_pos++; + } + } else { + var formmerA = tempCmds; + tempCmds = commands.findInArray(tempCmds, tokens[li].toUpperCase(), cur_pos); + if (tempCmds.length != 0 && formmerA != tempCmds) { + cur_pos++; + } + } + } + if (tempCmds.length > 0) { + var tempSuggestion = ""; + if (tempCmds.length == 1) { + cur_cmd = tempCmds[0]; + if (cur_cmd.suggestion != "") { + tempSuggestion = "

" + cur_cmd.alias + "

" + cur_cmd.suggestion + tempSuggestion; + if (cur_cmd.subs.length > 0) { + var tempSubSuggestion = ""; + $(cur_cmd.subs).each(function(i, sub) { + { + var tempAllKeywords = ".*?" + ((sub.id).replace(/\s/g, ".*?")); + var reg = new RegExp(tempAllKeywords, 'gi'); + if (reg.test(tempId) && "" != sub.suggestion) { + tempSubSuggestion = sub.suggestion + tempSubSuggestion; + } + } + }); + if (tempSubSuggestion != "") + tempSuggestion = "

Suggestion

" + tempSubSuggestion + "
" + tempSuggestion; + } + } + } else { + cur_cmd = commands.getOneFromArray(tempCmds, cur_pos); + + if (cur_cmd != "") { + tempSuggestion = "

" + cur_cmd.alias + "

" + cur_cmd.suggestion + tempSuggestion; + if (cur_cmd.subs.length > 0) { + var tempSubSuggestion = ""; + $(cur_cmd.subs).each(function(i, sub) { + { + var tempAllKeywords = ".*?" + ((sub.id).replace(/\s/g, ".*?")); + var reg = new RegExp(tempAllKeywords, 'gi'); + if (reg.test(tempId) && "" != sub.suggestion) { + tempSubSuggestion = sub.suggestion + tempSubSuggestion; + } + } + }); + if (tempSubSuggestion != "") + tempSuggestion = "

Suggestion

" + tempSubSuggestion + "
" + tempSuggestion; + } + } else { + backString = tempId; + var num = 0; + $.each(tempCmds, function(n, v) { + cur_cmd = tempCmds[num]; + if (v.alias.indexOf('|') > -1) { + if (v.alias == NameSnext) { + tempSuggestion = "

" + cur_cmd.alias + "

" + cur_cmd.suggestion + tempSuggestion; + if (cur_cmd.subs.length > 0) { + var tempSubSuggestion = ""; + $(cur_cmd.subs).each(function(i, sub) { + { + var tempAllKeywords = ".*?" + ((sub.id).replace(/\s/g, ".*?")); + var reg = new RegExp(tempAllKeywords, 'gi'); + if (reg.test(tempId) && "" != sub.suggestion) { + tempSubSuggestion = sub.suggestion + tempSubSuggestion; + } + } + }); + if (tempSubSuggestion != "") + tempSuggestion = "

Suggestion

" + tempSubSuggestion + "
" + tempSuggestion; + } + } else { + num++; + } + } else { + if (v.alias == NameSnext) { + tempSuggestion = "

" + cur_cmd.alias + "

" + cur_cmd.suggestion + tempSuggestion; + if (cur_cmd.subs.length > 0) { + var tempSubSuggestion = ""; + $(cur_cmd.subs).each(function(i, sub) { + { + var tempAllKeywords = ".*?" + ((sub.id).replace(/\s/g, ".*?")); + var reg = new RegExp(tempAllKeywords, 'gi'); + if (reg.test(tempId) && "" != sub.suggestion) { + tempSubSuggestion = sub.suggestion + tempSubSuggestion; + } + } + }); + if (tempSubSuggestion != "") + tempSuggestion = "

Suggestion

" + tempSubSuggestion + "
" + tempSuggestion; + } + } else { + num++; + } + } + }); + formerCmd = ""; + } + } + if (cur_cmd != "" && formerCmd == "") { + $('#divSuggestion').html(tempSuggestion); + $(document).scrollTop(0); + assistantHighlight("assistantExamples"); + formerCmd = cur_cmd; + } else if (cur_cmd != "" && formerCmd != "" && cur_cmd.alias != formerCmd.alias) { + $('#divSuggestion').html(tempSuggestion); + $(document).scrollTop(0); + assistantHighlight("assistantExamples"); + formerCmd = cur_cmd; + } else if (formerCmd == "") { + $('#divSuggestion').html(tempSuggestion); + $(document).scrollTop(0); + } + } + } +} + +function getParams(key) { + var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)"); + var r = window.location.search.substr(1).match(reg); + if (r != null) { + return unescape(r[2]); + } + return null; +}; +$(function() { + $("#grammarNext").click(function() { + location.href = "index_zh.html"; + $(this).addClass("active"); + $("#operationListNext").removeClass("active"); + $("#beginnerGuideNext").removeClass("active"); + $("#caseNext").removeClass("active"); + }); + $("#beginnerGuideNext").click(function() { + $(this).addClass("active"); + $("#operationListNext").removeClass("active"); + $("#grammarNext").removeClass("active"); + $("#caseNext").removeClass("active"); + }); + + $("#caseNext").click(function() { + $(this).addClass("active"); + $("#operationListNext").removeClass("active"); + $("#beginnerGuideNext").removeClass("active"); + $("#grammarNext").removeClass("active"); + }); + var heroes = db['sheet1']; + var mun = getParams("param1"); + NameS = heroes[mun].分类名称; + NameSnext = getParams("param2"); + $("#operNameSnext").text(NameSnext); + var operNameNext = "" + NameS + "" + $("#operNameS").append(operNameNext); + // $("#operNameB").append(recordpath); + LoadSuggestion(recordpath); + +}); \ No newline at end of file diff --git a/code/datastudio/db_assistant/js/errorcodeParser.js b/code/datastudio/db_assistant/js/errorcodeParser.js new file mode 100644 index 0000000000000000000000000000000000000000..f433a0347a9ab291410edfc0a2c81c17b873603b --- /dev/null +++ b/code/datastudio/db_assistant/js/errorcodeParser.js @@ -0,0 +1,47 @@ +function ErrorCodes() +{ + this.errs=[]; + this.add=add; + this.find=find; + this.get=get; + this.load=load; + var __that__=this; + function add(err) + { + this.errs[this.errs.length]=err; + } + function find(errId) + { + var tmpErr=""; + $(this.errs).each(function(i,err) + { + if(errId==err.id) + { + tmpErr=err; + } + }); + return tmpErr; + } + function get(index) + { + return this.errs[index]; + } + function load(xml) + { + __that__.errs.length=0; + $(xml).find("errorcode").each(function(i,errXml) + { + var err=new ErrorCode(errXml.getAttribute("id"),errXml.childNodes[0].text,errXml.childNodes[1].text,errXml.childNodes[2].text,errXml.childNodes[3].text); + __that__.add(err); + }); + } +} + +function ErrorCode(id,description,sqlstate,cause,solution) +{ + this.id=id; + this.description=description; + this.sqlstate=sqlstate; + this.cause=cause; + this.solution=solution; +} \ No newline at end of file diff --git a/code/datastudio/db_assistant/js/index.js b/code/datastudio/db_assistant/js/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f4b51729f4ea0ca1636d8401aff84a3028a2ffa6 --- /dev/null +++ b/code/datastudio/db_assistant/js/index.js @@ -0,0 +1,456 @@ +// var data = require('../js/operationList'); +var commands; +var errorcodes; +var selectedCmdAlias = "temp"; +var isNotSingle = true; +var oTextSelection = ""; +var currentSQL = ""; +var backString = ""; +var rightMenu = ""; +var divDefault = ""; +var divGoBack = ""; +var formerCmd = ""; +var cur_cmd = ""; + +function getSQLHtml(tempValues) { + var tempSuggestion = "
";
+    $.each(tempValues, function(n, v) {
+        if (v.alias.indexOf('|') > -1) {
+            tempSuggestion = tempSuggestion + "· " + v.id + "\r\n";
+        } else {
+            tempSuggestion = tempSuggestion + "· " + v.alias + "\r\n";
+        }
+    });
+    tempSuggestion = tempSuggestion + "
"; + return tempSuggestion; +} + +function hideKeyWord(needHide) { + if (needHide) { + $('#keywordInfo').hide(); + $("#listStatus").removeClass("hideList").addClass("showList"); + } else { + $('#keywordInfo').show(); + $("#listStatus").removeClass("showList").addClass("hideList"); + } +} + +function hideOrShowKeyWord() { + if ($("#keywordInfo").is(':visible')) { + hideKeyWord(true); + } else { + hideKeyWord(false); + } +} + +function hideKeyWordList(str) { + $('#keyword').val(str); + hideKeyWord(true); +} + +function getSQLHtmlForList(tempValues, recordPath) { + var tempSuggestion = ""; + $.each(tempValues, function(n, v) { + if (v.alias.indexOf('|') > -1) { + tempSuggestion = tempSuggestion + "" + v.id + ""; + } else { + tempSuggestion = tempSuggestion + "" + v.alias + ""; + } + }); + $('#keywordInfo').css("height", "300px"); + $('#keywordInfoBody').html(tempSuggestion); + setCookie("recordDataPath", recordPath); +} + +function checkField(keyword) { + var tempSuggestion = ""; + var tempValues = commands.cmds; + var temStr = keyword.toUpperCase(); + var rowCount = 0; + $.each(tempValues, function(n, v) { + if (v.alias.indexOf(temStr) == 0) { + rowCount++; + if (v.alias.indexOf('|') > -1) { + tempSuggestion = tempSuggestion + "" + v.id + ""; + } else { + tempSuggestion = tempSuggestion + "" + v.alias + ""; + } + } + }); + if (rowCount < 16) { + $('#keywordInfo').css("height", (14 * rowCount) + "px"); + } else { + $('#keywordInfo').css("height", "300px"); + } + $('#keywordInfoBody').html(tempSuggestion); + hideKeyWord(false); +} + +function processInput(tempId) { + if ("hideAssistant" == tempId) { + myCallDBAssistant('hide'); + return; + } + if (document.selection) { + document.selection.empty(); + } else { + window.getSelection().removeAllRanges(); + } + if (divGoBack != "") { + divGoBack.remove ? divGoBack.remove() : divGoBack.removeNode(true); + } + if (rightMenu != "") { + rightMenu.remove ? rightMenu.remove() : rightMenu.removeNode(true); + } + + tempId = $.trim(tempId); + hideKeyWord(true); + if ("" != tempId) { + var tempIds = tempId.split(/;/); + tempId = tempIds[tempIds.length - 1]; + if ("" == tempId || "$$" == tempId) tempId = tempIds[tempIds.length - 2]; + var tokens = StringReader(tempId); + //var tokens=tempId.split(/[ ]+/); + //alert(JSON.stringify(tokens)); + var tempCmds = []; + var cur_pos = 0; + for (var li = 0; li < tokens.length; li++) { + if (tempCmds.length == 0) { + tempCmds = commands.find(tokens[li].toUpperCase(), cur_pos); + if (tempCmds.length != 0) { + cur_pos++; + } + } else { + var formmerA = tempCmds; + tempCmds = commands.findInArray(tempCmds, tokens[li].toUpperCase(), cur_pos); + if (tempCmds.length != 0 && formmerA != tempCmds) { + cur_pos++; + } + } + } + if (tempCmds.length > 0) { + var tempSuggestion = ""; + if (tempCmds.length == 1) { + cur_cmd = tempCmds[0]; + if (cur_cmd.suggestion != "") { + if (isNotSingle) myCallDBAssistant('show'); + /*if(cur_cmd.alias.indexOf('|')>-1) + { + tempSuggestion="

"+cur_cmd.id+"

"+cur_cmd.suggestion+tempSuggestion; + }else{ + tempSuggestion="

"+cur_cmd.alias+"

"+cur_cmd.suggestion+tempSuggestion; + }*/ + tempSuggestion = "

" + cur_cmd.alias + "

" + cur_cmd.suggestion + tempSuggestion; + $('#keyword').val(cur_cmd.alias); + if (cur_cmd.subs.length > 0) { + var tempSubSuggestion = ""; + $(cur_cmd.subs).each(function(i, sub) { + { + var tempAllKeywords = ".*?" + ((sub.id).replace(/\s/g, ".*?")); + var reg = new RegExp(tempAllKeywords, 'gi'); + if (reg.test(tempId) && "" != sub.suggestion) { + tempSubSuggestion = sub.suggestion + tempSubSuggestion; + } + } + }); + if (tempSubSuggestion != "") + tempSuggestion = "

性能优化建议

" + tempSubSuggestion + "
" + tempSuggestion; + } + } + } else { + cur_cmd = commands.getOneFromArray(tempCmds, cur_pos); + if (cur_cmd != "") { + if (isNotSingle) myCallDBAssistant('show'); + /*if(cur_cmd.alias.indexOf('|')>-1) + { + tempSuggestion="

"+cur_cmd.id+"

"+cur_cmd.suggestion+tempSuggestion; + }else{ + tempSuggestion="

"+cur_cmd.alias+"

"+cur_cmd.suggestion+tempSuggestion; + }*/ + tempSuggestion = "

" + cur_cmd.alias + "

" + cur_cmd.suggestion + tempSuggestion; + $('#keyword').val(cur_cmd.alias); + if (cur_cmd.subs.length > 0) { + var tempSubSuggestion = ""; + $(cur_cmd.subs).each(function(i, sub) { + { + var tempAllKeywords = ".*?" + ((sub.id).replace(/\s/g, ".*?")); + var reg = new RegExp(tempAllKeywords, 'gi'); + if (reg.test(tempId) && "" != sub.suggestion) { + tempSubSuggestion = sub.suggestion + tempSubSuggestion; + } + } + }); + if (tempSubSuggestion != "") + tempSuggestion = "

性能优化建议

" + tempSubSuggestion + "
" + tempSuggestion; + } + } else { + backString = tempId; + if (isNotSingle) myCallDBAssistant('show'); + tempSuggestion = getSQLHtml(tempCmds); + formerCmd = ""; + } + } + if (cur_cmd != "" && formerCmd == "") { + $('#divSuggestion').html(tempSuggestion); + $(document).scrollTop(0); + assistantHighlight("assistantExamples"); + formerCmd = cur_cmd; + } else if (cur_cmd != "" && formerCmd != "" && cur_cmd.alias != formerCmd.alias) { + $('#divSuggestion').html(tempSuggestion); + $(document).scrollTop(0); + assistantHighlight("assistantExamples"); + formerCmd = cur_cmd; + } else if (formerCmd == "") { + $('#divSuggestion').html(tempSuggestion); + $(document).scrollTop(0); + } + } else { + backString = tempId; + $('#divSuggestion').html(getSQLHtml(commands.cmds)); + $(document).scrollTop(0); + formerCmd = ""; + } + } else { + backString = tempId; + $('#divSuggestion').html(getSQLHtml(commands.cmds)); + $(document).scrollTop(0); + formerCmd = ""; + //$('#divSuggestion').html(""); + //if(isNotSingle)myCallDBAssistant('hide'); + } +} + +function processErrorCode(errorCode) { + var err = errorcodes.find($.trim(errorCode)); + if (err != "") { + var tempHtml = "

" + errorCode + "

Descrition

" + err.description + "

SQLSTATE

" + err.sqlstate + "

Possible Causes

" + err.cause + "

Solution

" + err.solution + "

"; + $('#divSuggestion').html(tempHtml); + if (isNotSingle) myCallDBAssistant('show'); + } +} + +function processSelection1() { + if (oTextSelection != "") { + myCallDBAssistantProcessSelection(oTextSelection); + } +} + +function processSelection2() { + if (oTextSelection != "") { + myCallDBAssistantProcessSelection2(oTextSelection); + } +} + +function displayVersionNote(curVersion) { + var divVersionNote = $('
'); + var p1 = $('

请从华为Support上下载FusionInsight LibrA对应版本的知识库。

'); + divVersionNote.append(p1); + $('body').append(divVersionNote); +} + +function disableNote(disable) { + if (disable) { + if (divDefault != "") { + divDefault.remove(); + divDefault = ""; + } + } else { + divDefault = $('
'); + var p1 = $('

在中间窗口中,选中SQL语句或错误码,SQL助手会显示对应的说明信息

'); + var p2 = $('

我知道了

'); + divDefault.append(p1); + divDefault.append(p2); + $('body').append(divDefault); + } +} + +function setCurrentSQL(sql) { + currentSQL = sql; +} + +function setCookie(name, value) { + var Days = 30; + var exp = new Date(); + exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000); + document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString(); +} + +function loadSuggestion(docRealPath) { + commands = new Commands(); + var xml = new ActiveXObject("Microsoft.XMLDOM"); + xml.async = false; + xml.load(docRealPath + "/suggestion.xml"); + commands.load(xml); + var valueStr = JSON.stringify(commands); + getSQLHtmlForList(commands.cmds, docRealPath); + +} + +function loadErrorcode(docRealPath) { + errorcodes = new ErrorCodes(); + //var xml = new ActiveXObject("Microsoft.XMLDOM"); + //xml.async = false; + //xml.load(docRealPath+"/errorcode.xml"); + //errorcodes.load(xml); + processInput(currentSQL); + myCallDBAssistant('show'); +} + +function isHidden(oDiv) { + var vDiv = oDiv.nextSibling; + while (vDiv.nodeType == 3) { + vDiv = vDiv.nextSibling; + } + vDiv.style.display = (vDiv.style.display == 'none') ? 'block' : 'none'; + var pngs = oDiv.getElementsByTagName("img"); + switch (pngs[1].style.display) { + case 'none': + pngs[0].style.display = 'none'; + pngs[1].style.display = 'inline'; + break; + case 'inline': + pngs[0].style.display = 'inline'; + pngs[1].style.display = 'none'; + break; + } +} + +function goBack(display) { + if (display == "none") { + divGoBack.remove ? divGoBack.remove() : divGoBack.removeNode(true); + divGoBack = ""; + processInput(backString); + } else { + divGoBack = $('
'); + var img1 = $(''); + divGoBack.append(img1); + $(".grammar-item-one").append(divGoBack); + } +} + +function readWorkbookFromRemoteFile(callback) { + var xhr = new XMLHttpRequest(); + xhr.open('get', url, true); + xhr.responseType = 'arraybuffer'; + xhr.onload = function(e) { + if (xhr.status == 200) { + var data = new Uint8Array(xhr.response) + var workbook = XLSX.read(data, { type: 'array' }); + if (callback) callback(workbook); + } + }; + xhr.send(); +} +$(function() { + $("#keywordInfo").scrollBar({ + width: 252 + }); + setTimeout(function() { //用于在指定的毫秒数后调用函数或计算表达式 + myCallDBAssistantLoad(''); + }, 1000); + $('body').contextmenu(function(event) { + //hideKeyWordList(); + if (document.selection) { + oTextSelection = document.selection.createRange().text; + } else { + oTextSelection = window.getSelection().toString(); + } + //var event = event || window.event; + var leftX = event.pageX; + var topY = event.pageY; + + if (oTextSelection != "" && rightMenu == "") { + var bodyW = $('body').width(); + if (bodyW <= leftX + 130) { + leftX = bodyW - 130; + } + rightMenu = $('
'); + var span1 = $('
拷贝
'); + //var br1 =$('
'); + var span2 = $('
拷贝到编辑区
'); + rightMenu.append(span1); + //rightMenu.append(br1); + rightMenu.append(span2); + $('body').append(rightMenu); + } else if (oTextSelection != "" && rightMenu != "") { + var bodyW = $('body').width(); + if (bodyW <= leftX + 130) { + leftX = bodyW - 130; + } + rightMenu.css('left', leftX); + rightMenu.css('top', topY); + } else if (rightMenu != "") { + rightMenu.remove ? rightMenu.remove() : rightMenu.removeNode(true); + rightMenu = ""; + } + return false; + }); + document.onclick = function() { + if (rightMenu != "") { + rightMenu.remove ? rightMenu.remove() : rightMenu.removeNode(true); + rightMenu = ""; + } + }; + document.onkeydown = function(e) { + var e = window.event ? window.event : e; + if (e.ctrlKey && e.keyCode == 67) { + if (document.selection) { + oTextSelection = document.selection.createRange().text; + } else { + oTextSelection = window.getSelection().toString(); + } + if (oTextSelection != "") { + processSelection1(); + return false; + } + } + }; + $("#grammar").click(function() { + $(this).addClass("active"); + $("#operationList").removeClass("active"); + $("#beginnerGuide").removeClass("active"); + $("#case").removeClass("active"); + location.href = "index_zh.html"; + // $("#caseContent").addClass("hidden"); + // $("#beginnerContent").addClass("hidden"); + // $("#operationListContent").addClass("hidden"); + // $("#grammarContent").removeClass("hidden"); + }); + + $("#operationList").click(function() { + $(this).addClass("active"); + $("#grammar").removeClass("active"); + $("#beginnerGuide").removeClass("active"); + $("#case").removeClass("active"); + location.href = "operationList.html"; + // $("#caseContent").addClass("hidden"); + // $("#beginnerContent").addClass("hidden"); + // $("#operationListContent").removeClass("hidden"); + // $("#grammarContent").addClass("hidden"); + }); + + $("#beginnerGuide").click(function() { + $(this).addClass("active"); + $("#operationList").removeClass("active"); + $("#grammar").removeClass("active"); + $("#case").removeClass("active"); + location.href = "beginnerGuide.html"; + // $("#caseContent").addClass("hidden"); + // $("#beginnerContent").removeClass("hidden"); + // $("#operationListContent").addClass("hidden"); + // $("#grammarContent").addClass("hidden"); + }); + + $("#case").click(function() { + $(this).addClass("active"); + $("#operationList").removeClass("active"); + $("#beginnerGuide").removeClass("active"); + $("#grammar").removeClass("active"); + location.href = "case.html"; + // $("#caseContent").removeClass("hidden"); + // $("#beginnerContent").addClass("hidden"); + // $("#operationListContent").addClass("hidden"); + // $("#grammarContent").addClass("hidden"); + }); + // setCookie("recordDataPath", "Gauss200 OLAP V100R007C10/zh"); +}); \ No newline at end of file diff --git a/code/datastudio/db_assistant/js/jquery.min.js b/code/datastudio/db_assistant/js/jquery.min.js new file mode 100644 index 0000000000000000000000000000000000000000..c4c6022f2982e8dae64cebd6b9a2b59f2547faad --- /dev/null +++ b/code/datastudio/db_assistant/js/jquery.min.js @@ -0,0 +1,2 @@ +/*! jQuery v3.6.0 | (c) OpenJS Foundation and other contributors | jquery.org/license */ +!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],r=Object.getPrototypeOf,s=t.slice,g=t.flat?function(e){return t.flat.call(e)}:function(e){return t.concat.apply([],e)},u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType&&"function"!=typeof e.item},x=function(e){return null!=e&&e===e.window},E=C.document,c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.6.0",S=function(e,t){return new S.fn.init(e,t)};function p(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp(F),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(p.childNodes),p.childNodes),t[p.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!N[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&(U.test(t)||z.test(t))){(f=ee.test(t)&&ye(e.parentNode)||e)===e&&d.scope||((s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=S)),o=(l=h(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+xe(l[o]);c=l.join(",")}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){N(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return g(t.replace($,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[S]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e&&e.namespaceURI,n=e&&(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:p;return r!=C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),p!=C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.scope=ce(function(e){return a.appendChild(e).appendChild(C.createElement("div")),"undefined"!=typeof e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=S,!C.getElementsByName||!C.getElementsByName(S).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){var t;a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+S+"-]").length||v.push("~="),(t=C.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||v.push("\\["+M+"*name"+M+"*="+M+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||v.push(".#.+[+~]"),e.querySelectorAll("\\\f"),v.push("[\\r\\n\\f]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",F)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},j=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e==C||e.ownerDocument==p&&y(p,e)?-1:t==C||t.ownerDocument==p&&y(p,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==C?-1:t==C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]==p?-1:s[r]==p?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(T(e),d.matchesSelector&&E&&!N[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){N(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=m[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&m(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?S.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?S.grep(e,function(e){return e===n!==r}):"string"!=typeof n?S.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(S.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||D,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:q.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof S?t[0]:t,S.merge(this,S.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),N.test(r[1])&&S.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(S):S.makeArray(e,this)}).prototype=S.fn,D=S(E);var L=/^(?:parents|prev(?:Until|All))/,H={children:!0,contents:!0,next:!0,prev:!0};function O(e,t){while((e=e[t])&&1!==e.nodeType);return e}S.fn.extend({has:function(e){var t=S(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i;ce=E.createDocumentFragment().appendChild(E.createElement("div")),(fe=E.createElement("input")).setAttribute("type","radio"),fe.setAttribute("checked","checked"),fe.setAttribute("name","t"),ce.appendChild(fe),y.checkClone=ce.cloneNode(!0).cloneNode(!0).lastChild.checked,ce.innerHTML="",y.noCloneChecked=!!ce.cloneNode(!0).lastChild.defaultValue,ce.innerHTML="",y.option=!!ce.lastChild;var ge={thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?S.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;n",""]);var me=/<|&#?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d\s*$/g;function je(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&S(e).children("tbody")[0]||e}function De(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function qe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Le(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(Y.hasData(e)&&(s=Y.get(e).events))for(i in Y.remove(t,"handle events"),s)for(n=0,r=s[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var _t,zt=[],Ut=/(=)\?(?=&|$)|\?\?/;S.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=zt.pop()||S.expando+"_"+wt.guid++;return this[e]=!0,e}}),S.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Ut.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Ut.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Ut,"$1"+r):!1!==e.jsonp&&(e.url+=(Tt.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||S.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?S(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,zt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((_t=E.implementation.createHTMLDocument("").body).innerHTML="
",2===_t.childNodes.length),S.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=N.exec(e))?[t.createElement(i[1])]:(i=xe([e],t,o),o&&o.length&&S(o).remove(),S.merge([],i.childNodes)));var r,i,o},S.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(S.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},S.expr.pseudos.animated=function(t){return S.grep(S.timers,function(e){return t===e.elem}).length},S.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=S.css(e,"position"),c=S(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=S.css(e,"top"),u=S.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,S.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===S.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===S.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=S(e).offset()).top+=S.css(e,"borderTopWidth",!0),i.left+=S.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-S.css(r,"marginTop",!0),left:t.left-i.left-S.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===S.css(e,"position"))e=e.offsetParent;return e||re})}}),S.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;S.fn[t]=function(e){return $(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),S.each(["top","left"],function(e,n){S.cssHooks[n]=Fe(y.pixelPosition,function(e,t){if(t)return t=We(e,n),Pe.test(t)?S(e).position()[n]+"px":t})}),S.each({Height:"height",Width:"width"},function(a,s){S.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){S.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return $(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?S.css(e,t,i):S.style(e,t,n,i)},s,n?e:void 0,n)}})}),S.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){S.fn[t]=function(e){return this.on(t,e)}}),S.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),S.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){S.fn[n]=function(e,t){return 0" +document.write(datajspath); +var operNameS = document.getElementById("operNameS"); +var operNameB = document.getElementById("operNameB"); + +function createButton(data) { + //用heroers存储json文件里menbers的信息 + var heroes = data['sheet1']; + var notscenDimen = true; + var notoperDimen = true; + for (var i = 0; i < heroes.length; i++) { + var buttonId = "button" + i; + switch (heroes[i].分类维度) { + case "功能大类": + { + $('.functionalDimension').removeClass('hidden'); + myArticle = "
" + heroes[i].分类名称 + "
" + $("#funcDimen").append(myArticle); + }; + break; + case "大场景": + { + notscenDimen = false; + $('.sceneDimension').removeClass('hidden'); + myArticle = "
" + heroes[i].分类名称 + "
" + $("#scenDimen").append(myArticle); + }; + break; + case "操作类别": + { + notoperDimen = false; + $('.operationalDimension').removeClass('hidden'); + myArticle = "
" + heroes[i].分类名称 + "
" + $("#operDimen").append(myArticle); + }; + default: + break; + } + } + if (notoperDimen && notscenDimen) { + $('.is-func-deime').addClass('hidden'); + } +} +var mun = 0; + +//读取cookies +function getCookie(name) { + var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); + + if (arr = document.cookie.match(reg)) + + return unescape(arr[2]); + else + return null; +} + + +$(function() { + // $("#operNameC").append(recordpath); + createButton(db); + +}); \ No newline at end of file diff --git a/code/datastudio/db_assistant/js/scrollBar.js b/code/datastudio/db_assistant/js/scrollBar.js new file mode 100644 index 0000000000000000000000000000000000000000..9f4598a981d0725da4c9985c65eccc3daadb52da --- /dev/null +++ b/code/datastudio/db_assistant/js/scrollBar.js @@ -0,0 +1,459 @@ +;(function($){ + $.fn.extend({ + "scrollBar":function(options){ + var settings = { + width:200, + barWidth:5, + position:"x,y", + wheelDis:15 + + }; + + options = $.extend(settings,options); + + var horizontalDiv = '
'+ + '
'+ + '
'; + var verticalDiv = '
'+ + '
'+ + '
'; + + var T = this; + + T.each(function(){ + + $(this).attr("paddingR",$(this).css("padding-right")).attr("paddingB",$(this).css("padding-bottom")); + + }); + + function creatScrollBar(obj){ + + var This = $(obj).get(0); + + var paddingR = parseFloat($(obj).attr("paddingR")); + var paddingB = parseFloat($(obj).attr("paddingB")); + + $(obj).css({ + "padding-right":paddingR+"px", + "padding-bottom":paddingB+"px", + "overflow":"hidden" + }); + + if(!($(obj).children().hasClass("zl-scrollContentDiv"))){ + $(obj).wrapInner('
'); + }; + + if($(obj).css("position")=="static"){ + $(obj).css({"position":"relative"}); + }; + + var scrollContentDiv = $(obj).find(".zl-scrollContentDiv"); + + var scrollH = scrollContentDiv[0].scrollHeight; + var scrollW = scrollContentDiv[0].scrollWidth; + + var innerH = scrollContentDiv.height(); + var innerW = scrollContentDiv.width(); + var outerH = $(obj).innerHeight(); + var outerW = $(obj).innerWidth(); + + function addVerticalBar(a){ + + This.style.paddingRight = paddingR + settings.barWidth + 'px'; + + innerH = $(a).height(); + + var barHeight = outerH*(innerH/scrollH); + + $(a).width(settings.width-settings.barWidth).find(".zl-scrollBarBox").remove().end().append(verticalDiv).find(".zl-verticalBar").height(barHeight); + + }; + function addHorizontalBar(a){ + + This.style.paddingBottom = paddingB + settings.barWidth + 'px'; + innerW = $(a).width(); + + var barWidth = outerW*(innerW/scrollW); + + $(a).find(".zl-scrollBarBox").remove().end().append(horizontalDiv).find(".zl-horizontalBar").width(barWidth); + + }; + + switch (settings.position){ + + case "x,y": + + if(scrollH>innerH && scrollW>innerW){ + This.style.paddingRight = paddingR + settings.barWidth + 'px'; + innerH = $(obj).height(); + outerH = $(obj).innerHeight(); + + var barHeight = (outerH-settings.barWidth)*((innerH-settings.barWidth)/scrollH); + if(!($(obj).find(".zl-verticalBar").length)){ + $(obj).append(verticalDiv); + }; + + $(obj).find(".zl-verticalBar").height(barHeight).parent().height(outerH-settings.barWidth); + + + This.style.paddingBottom = paddingB + settings.barWidth + 'px'; + innerW = $(obj).width(); + + var barWidth = (outerW-settings.barWidth)*((innerW-settings.barWidth)/scrollW); + + if(!($(obj).find(".zl-horizontalBar").length)){ + $(obj).append(horizontalDiv); + }; + $(obj).find(".zl-horizontalBar").width(barWidth).parent().width(outerW) + .css({ + "padding-right":settings.barWidth+"px", + "box-sizing":"border-box" + }); + + }else if(scrollH>innerH){ + + addVerticalBar(obj); + + + }else if(scrollW>innerW){ + + addHorizontalBar(obj); + + }else{ + $(obj).width(settings.width).find(".zl-scrollBarBox").remove(); + } + break; + + case "x": + + if(scrollW>innerW){ + + addHorizontalBar(obj); + + }else{ + $(obj).find(".zl-scrollBarBox").remove(); + } + break; + + case "y": + + if(scrollH>innerH){ + + addVerticalBar(obj); + + }else{ + $(obj).find(".zl-scrollBarBox").remove(); + } + + break; + }; + + + } + + function recycleThis(){ + + T.each(function(){ + + creatScrollBar(this); + + }); + }; + + recycleThis(); + + function creatTimer(obj,oldWidth,oldHeight,oldInnerWidth,oldInnerHeight,timer){ + + timer = setInterval(function(){ + + var newWidth = null; + var newHeight = null; + var newInnerWidth = null; + var newInnerHeight = null; + var topDiv = null; + var leftDiv = null; + var topBar = null; + var leftBar = null; + var scrollContentDiv = $(obj).find(".zl-scrollContentDiv"); + + if(scrollContentDiv.length){ + newWidth = scrollContentDiv[0].scrollWidth; + newHeight = scrollContentDiv[0].scrollHeight; + + newInnerWidth = scrollContentDiv.width(); + newInnerHeight = scrollContentDiv.height(); + }else{ + newWidth = $(obj)[0].scrollWidth - parseFloat($(obj).css("padding-left")); + newHeight = $(obj)[0].scrollHeight - parseFloat($(obj).css("padding-top")); + newInnerWidth = $(obj).width(); + newInnerHeight = $(obj).height(); + + }; + + if(newWidth!=oldWidth || newHeight!=oldHeight || newInnerWidth!=oldInnerWidth || newInnerHeight!=oldInnerHeight){ + + if(scrollContentDiv.length){ + topDiv = parseFloat(scrollContentDiv.css("top")); + leftDiv = parseFloat(scrollContentDiv.css("left")); + }; + if($(obj).find(".zl-verticalBar").length){ + topBar = parseFloat($(obj).find(".zl-verticalBar").css("top")); + }; + if($(obj).find(".zl-horizontalBar").length){ + leftBar = parseFloat($(obj).find(".zl-horizontalBar").css("left")); + }; + creatScrollBar(obj); + + if($(obj).find(".zl-scrollBarBox").length){ + if(topDiv){ + var maxTopBox = scrollContentDiv[0].scrollHeight - $(obj).height(); + var maxLeftBox = scrollContentDiv[0].scrollWidth - $(obj).width(); + if(-leftDiv>maxLeftBox){ + leftDiv = -maxLeftBox; + } + if(-topDiv>maxTopBox){ + topDiv = -maxTopBox; + } + scrollContentDiv.css({ + "left":leftDiv+'px', + "top":topDiv+'px' + }); + }; + if(topBar && $(obj).find(".zl-verticalBar").length){ + var verticalBar = $(obj).find(".zl-verticalBar"); + var maxTop = verticalBar.parent().height() -verticalBar.height(); + + if(topBar>maxTop){ + topBar = maxTop; + } + verticalBar.css("top",topBar+'px'); + }; + if(leftBar && $(obj).find(".zl-horizontalBar").length){ + var horizontalBar = $(obj).find(".zl-verticalBar"); + var maxLeft = horizontalBar.parent().width() -horizontalBar.width(); + + if(leftBar>maxLeft){ + leftBar = maxLeft; + } + + $(obj).find(".zl-horizontalBar").css("left",leftBar+'px'); + }; + } + + oldWidth = newWidth; + oldHeight = newHeight; + + oldInnerHeight = newInnerHeight; + oldInnerWidth = newInnerWidth; + } + + },100); + } + + function addTimer(){ + $.each(T,function(k,v){ + + var obj = v; + var timer = "timer"+k; + var oldWidth = null; + var oldHeight = null; + var oldInnerWidth = null; + var oldInnerHeight = null; + + if($(v).find(".zl-scrollContentDiv").length){ + oldWidth = $(v).find(".zl-scrollContentDiv")[0].scrollWidth ; + oldHeight = $(v).find(".zl-scrollContentDiv")[0].scrollHeight; + oldInnerWidth = $(v).find(".zl-scrollContentDiv").width(); + oldInnerHeight = $(v).find(".zl-scrollContentDiv").height(); + + }else{ + oldWidth = $(obj)[0].scrollWidth - parseFloat($(obj).css("padding-left")); + oldHeight = $(obj)[0].scrollHeight - parseFloat($(obj).css("padding-top")); + + oldInnerWidth = $(obj).width(); + oldInnerHeight = $(obj).height(); + } + creatTimer(obj,oldWidth,oldHeight,oldInnerWidth,oldInnerHeight,timer); + }); + } + addTimer(); + function clearTimer(){ + $.each(T,function(index,item){ + var timer = "timer"+index; + clearInterval(timer); + }); + }; + this.on("mousedown",".zl-scrollBar",function(ev){ + + clearTimer(); + var direction = null; + + if($(this).hasClass("zl-verticalBar")){ + direction = "0"; + }else if($(this).hasClass("zl-horizontalBar")){ + direction = "1"; + } + + var This = $(this).get(0); + + var height = $(this).parent().height() - $(this).height(); + var width = $(this).parent().width() - $(this).width(); + + var contentDiv = $(this).parent().parent().find(".zl-scrollContentDiv").get(0); + + var scrollH = contentDiv.scrollHeight; + var innerH = $(this).parent().parent().height(); + + var scrollW = contentDiv.scrollWidth; + var innerW = $(this).parent().parent().width(); + + var ev = ev || event; + + var disY = ev.clientY - This.offsetTop; + var disX = ev.clientX - This.offsetLeft; + + var topCount = null; + var leftCount = null; + + switch (direction){ + + case "0": + + document.onmousemove = function(ev){ + + var ev = ev || event; + + if(ev.clientY - disY <= 0){ + topCount = 0; + }else + + if((ev.clientY - disY) >= height){ + topCount = height; + }else{ + topCount = ev.clientY - disY; + } + + This.style.top = topCount + "px"; + + contentDiv.style.top = -(topCount*(scrollH - innerH)/height) + 'px'; + + }; + + break; + + case "1": + + document.onmousemove = function(ev){ + + var ev = ev || event; + + if(ev.clientX - disX <= 0){ + leftCount = 0; + }else + + if((ev.clientX - disX) >= width){ + leftCount = width; + }else{ + leftCount = ev.clientX - disX; + } + + This.style.left = leftCount + "px"; + + contentDiv.style.left = -(leftCount*(scrollW - innerW)/width) + 'px'; + + }; + + break; + + } + + document.onmouseup = function(){ + + document.onmousemove = null; + document.onmouseup = null; + + addTimer(); + + }; + + return false; + }); + + function fn(ev,a){ + if(a.find(".zl-verticalBar").length){ + + var b = true; + var height = a.find(".zl-scrollBarBox").height() - a.find(".zl-scrollBar").height(); + var contentDiv = a.find(".zl-scrollContentDiv").get(0); + var scrollH = contentDiv.scrollHeight; + var innerH = a.height(); + + if(ev.wheelDelta){ + b = ev.wheelDelta>0?true:false; + }else{ + b = ev.detail<0?true:false; + } + + var topDis = parseFloat(a.find(".zl-scrollBar").css("top")); + + if(b){ + + topDis -= settings.wheelDis; + + if(topDis <0){ + + topDis = 0; + + } + + }else{ + + topDis += settings.wheelDis; + + if(topDis > height){ + topDis = height; + } + } + + a.find(".zl-scrollBar").get(0).style.top = topDis + "px"; + a.find(".zl-scrollContentDiv").get(0).style.top = -(topDis*(scrollH - innerH)/height) + 'px'; + + } + }; + + T.each(function(){ + + var oDiv = $(this).get(0); + + if(oDiv.addEventListener){ + + oDiv.addEventListener("DOMMouseScroll",function(ev){ + + var ev = ev || event; + var $This = $(this); + + fn(ev,$This); + + ev.preventDefault(); + + },false); + + } + + oDiv.onmousewheel = function(ev){ + + var ev = ev || event; + var $This = $(this); + + fn(ev,$This); + + return false; + }; + + }); + + return this; + } + + }); +})(jQuery); \ No newline at end of file diff --git a/code/datastudio/db_assistant/js/stringReader.js b/code/datastudio/db_assistant/js/stringReader.js new file mode 100644 index 0000000000000000000000000000000000000000..044f32fa7a4890f5aa9166e2cd14596481ab2e32 --- /dev/null +++ b/code/datastudio/db_assistant/js/stringReader.js @@ -0,0 +1,248 @@ +var newTokenState; +var tokenState; +var tokenReader; +var tokenList=[]; +var tokenWord=""; +var punctuatorList=["{", "}", "(", ")", "[", "]", ".", ";", ",", "<", ">", "<=", + ">=", "==", "!=", "===", "!==", "+", "-", "*", "%", "++", "--", + "<<", ">>", ">>>", "&", "|", "^", "!", "~", "&&", "||", "?", ":", + "=", "+=", "-=", "*=", "%=", "<<=", ">>=", ">>>=", "&=", "|=", "^="]; + +var operatorList=["<", ">", "<=",">=", "==", "!="]; + +function StringReader(statement) +{ + tokenReader=TempReader(statement); + tokenList.length=0; + var tokens=[]; + tokenState=dataState; + while(!tokenReader.eof()){ + var tempC=tokenReader.getChar(); + newTokenState=tokenState(tempC); + newTokenState && (tokenState=newTokenState); + tokenReader.next(); + } + $(tokenList).each(function(i,token){ + if(token[0]=='id') + { + tokens.push(token[1]); + } + }); + return tokens; +} + +function TempReader(str) +{ + var index=0; + var stream=str+" "; + var me={}; + me.getChar=function(){ + return stream.charAt(index); + }; + me.length=function (){ + return stream.length; + }; + me.stream=function(){ + return stream; + }; + me.pchar=function(){ + return stream.charAt(index-1); + }; + me.nchar=function(){ + return stream.charAt(index+1); + }; + me.eof=function (){ + return index === stream.length; + }; + me.next=function(){ + index++; + }; + me.prev=function (){ + index--; + }; + + return me; +} + +function checkUnicodeLetter(c){ + return c.match(/[a-z]/i); +} + +function checkUnicodeNumber(c){ + return (c.charCodeAt() >= "\u0030".charCodeAt() && c.charCodeAt() <= "\u0039".charCodeAt()) + || (c.charCodeAt() >= "\u1D7CE".charCodeAt() && c.charCodeAt() <= "\u1D7FF".charCodeAt()); + +} + +function emitToken(type){ + tokenList.push([type, tokenWord]); + tokenWord=""; +} + +function arrIndexOf(arr,c) +{ + for(var i=0;i -1){ + tokenWord=c; + return punctuatorState; + + }else if(checkUnicodeLetter(c) || c==="_" || c==="$" || c==="\\"){ + tokenWord=c; + return identifierState; + + }else if(c==="\""){ + tokenWord=c; + return doubleStringLiteralState; + } +} + +function punctuatorState(c){ + //if(punctuatorList.indexOf(tokenWord+c) === -1){ + if($.inArray(tokenWord+c,punctuatorList) === -1){ + if($.inArray(tokenWord,operatorList)>-1) + { + emitToken("id"); + }else{ + emitToken("pun"); + } + tokenReader.prev(); + return dataState; + }else{ + tokenWord += c; + } +} + +function identifierState(c){ + if(checkUnicodeLetter(c) || checkUnicodeNumber(c)){ + tokenWord += c; + + }else{ + emitToken("id"); + tokenReader.prev(); + return dataState; + } +} + +function doubleStringLiteralState(c){ + if(c==="\\"){ + tokenWord += c; + return doubleStringLiteralEscapeSequenceState; + }else if(c==="\""){ + tokenWord += c; + emitToken("str"); + return dataState; + }else{ + tokenWord += c; + } +} + +function doubleStringLiteralEscapeSequenceState(c){ + tokenWord+=c; + return doubleStringLiteralState; +} + +var assistantKeywordsPurple=unescape("ABORT ABSOLUTE ACCESS ACCOUNT ACTION ADD ADMIN AFTER AGGREGATE ALIAS ALSO ALTER ALWAYS APP ATTRIBUTE AUTOEXTEND AUTOMAPPED AVG BACKWARD BARRIER BEFORE BEGIN BLOB BY CACHE CALL CALLED CASCADED CASCADE CATALOG CHAIN CHARACTERISTICS CHECKPOINT CLASS CLEAN CLOB CLOSE CLUSTER COMMENT COMMENTS COMMIT COMMITTED COMPRESS CONFIGURATION CONNECTION CONSTRAINTS CONTENT CONTINUE CONVERSION COORDINATOR COPY COST CSV CURRENT CURSOR CYCLE DATABASE DATAFILE DATA DAY DEALLOCATE DECLARE DEFAULTS DEFERRED DEFINER DELETE DELIMITER DELIMITERS DELTA DETERMINISTIC DICTIONARY DIRECT DISABLE DISCARD DISTRIBUTE DISTRIBUTION DOCUMENT DOMAIN DOUBLE DROP EACH ENABLE ENCODING ENCRYPTED ENFORCED ENUM EOL ESCAPE ESCAPING EXCHANGE EXCLUDE EXCLUDING EXCLUSIVE EXECUTE EXPLAIN EXTENSION EXTERNAL FAMILY FILEHEADER FIRST FIXED FOLLOWING FORCE FORMATTER FORWARD FUNCTIONS GLOBAL GRANTED HANDLER HEADER HOLD HOUR IDENTIFIED IDENTITY IF IMMEDIATE IMMUTABLE IMPLICIT INCLUDING INCREMENT INDEXES INDEX INHERIT INHERITS INITIAL INITRANS INLINE INPUT INSENSITIVE INSERT INSTEAD INVOKER ISOLATION KEY LABEL LANGUAGE LARGE LAST LC_COLLATE LC_CTYPE LEAKPROOF LENGTH LEVEL LISTEN LOAD LOCAL LOCATION LOCK LOGGING LOGIN LOG LOOP MAPPING MATCH MAX MAXEXTENTS MAXSIZE MAXTRANS MAXVALUE MERGE MESSAGE_TEXT MIN MINEXTENTS MINUTE MINVALUE MODE MONTH MOVE MOVEMENT NAME NAMES NEXT NOCOMPRESS NOCYCLE NODE NOLOGGING NOLOGIN NOMAXVALUE NOMINVALUE NOTHING NOTIFY NOWAIT NO NULLS NUMSTR NVARCHAR2 OBJECT OFF OF OIDS OPERATOR OPTIMIZATION OPTIONS OPTION OWNED OWNER PARSER PARTIAL PARTITION PARTITIONS PASSING PASSWORD PCTFREE PER PERCENT PLANS POOL PRECEDING PREFERRED PREFIX PREPARE PREPARED PRESERVE PRIOR PRIVILEGES PRIVILEGE PROCEDURAL PROFILE QUERY QUOTE RANGE RAW READ REASSIGN REBUILD RECHECK RECURSIVE REF REINDEX RELATIVE RELEASE RELOPTIONS REMOTE RENAME REPEATABLE REPLACE REPLICA RESET RESIZE RESOURCE RESTART RESTRICT RETURNED_SQLSTATE RETURNS REUSE REVOKE ROLE ROLLBACK ROWS ROW_COUNT RULE SAVEPOINT SCHEMA SCROLL SEARCH SECOND SECURITY SEQUENCE SEQUENCES SERIALIZABLE SERVER SESSION SET SHARE SHOW SIMPLE SIZE SNAPSHOT SQLSTATE STABLE STANDALONE START STATEMENT STATISTICS STDIN STDOUT STORAGE STORE STRICT STRIP SUPERUSER SYS_REFCURSOR SYSID SYSTEM TABLESPACE TABLES TEMPLATE TEMPORARY TEMP TEXT THAN TRANSACTION TRUNCATE TRUSTED TYPE TYPES UNBOUNDED UNCOMMITTED UNENCRYPTED UNKNOWN UNLIMITED UNLISTEN UNLOCK UNLOGGED UNTIL UNUSABLE UPDATE VACUUM VALID VALIDATE VALIDATION VALIDATOR VALUE VERSION VIEW VOLATILE WHITESPACE WITHOUT WORK WORKLOAD WRAPPER WRITE XMLATTRIBUTES XMLCONCAT XMLELEMENT XMLEXISTS XMLFOREST XMLPARSE XMLPI XMLROOT XMLSERIALIZE XML YEAR YES ZONE".replace(/\+/g, ' ')).split(/\s+/);//#C60086 + +var assistantKeywordsBlue=unescape("BETWEEN BIGINT BINARY_DOUBLE BINARY_INTEGER BIT BOOLEAN CHAR CHARACTER COALESCE DECIMAL DECODE DEC EXTRACT EXISTS FLOAT8 FLOAT GREATEST INOUT INTERVAL INTEGER INT4 INT LEAST NATIONAL NCHAR NONE NULLIF NUMBER NUMERIC NVL OUT OVERLAY POSITION PRECISION REAL ROW SETOF SMALLDATETIME SMALLINT SUBSTRING TIMESTAMP TIME TINYINT TREAT TRIM VALUES VARCHAR2 VARCHAR".replace(/\+/g, ' ')).split(/\s+/);//#4166ED + + +var assistantKeywordsDeepGreen=unescape("ABS ADA ALLOCATE ALL ANALYSE ANALYZE AND ANY ARE ARRAY ASC ASENSITIVE ASYMMETRIC AS ATOMIC AUTHID AUTHORIZATION BINARY BITVAR BIT_LENGTH BOTH BUCKETS BREADTH CARDINALITY CASE CAST CATALOG_NAME CHARACTER_LENGTH CHARACTER_SET_CATALOG CHARACTER_SET_NAME CHARACTER_SET_SCHEMA CHAR_LENGTH CHECK CHECKED CLASS_ORIGIN COBOL COLLATE COLLATION COLLATION_CATALOG COLLATION_NAME COLLATION_SCHEMA COLUMN COLUMN_NAME COMMAND_FUNCTION COMMAND_FUNCTION_CODE COMPLETION CONCURRENTLY CONDITION CONDITION_NUMBER CONNECT CONNECTION_NAME CONSTRAINT CONSTRAINT_CATALOG CONSTRAINT_NAME CONSTRAINT_SCHEMA CONSTRUCTOR CONTAINS CONVERT CORRESPONDING COUNT CREATE CROSS CUBE CURRENT_CATALOG CURRENT_DATE CURRENT_PATH CURRENT_ROLE CURRENT_SCHEMA CURRENT_TIME CURRENT_TIMESTAMP CURRENT_USER CURSOR_NAME DATETIME_INTERVAL_CODE DATETIME_INTERVAL_PRECISION DATE DBCOMPATIBILITY DEFAULT DEFERRABLE DEFINED DEPTH DEREF DESC DESCRIBE DESCRIPTOR DESTROY DESTRUCTOR DIAGNOSTICS DISCONNECT DISPATCH DISTINCT DO DYNAMIC DYNAMIC_FUNCTION DYNAMIC_FUNCTION_CODE ELSE END END-EXEC EQUALS EVERY EXCEPT EXCEPTION EXEC EXISTING FALSE FETCH FINAL FOREIGN FORTRAN FOR FOUND FREEZE FREE FROM FULL FUNCTION GENERAL GENERATED GET GOTO GO GRANT GROUP GROUPING HAVING HIERARCHY HOST IGNORE ILIKE IMPLEMENTATION INDICATOR INFIX INITIALIZE INITIALLY INNER INSTANCE INSTANTIABLE INTERSECT INTO IN ISNULL IS ITERATE JOIN KEY_MEMBER KEY_TYPE LATERAL LEADING LEFT LESS LIKE LIMIT LOCALTIME LOCALTIMESTAMP LOCATOR LOWER MAP MATCHED MESSAGE_LENGTH MESSAGE_OCTET_LENGTH METHOD MINUS MOD MODIFIES MODIFY MODULE MORE MUMPS NATURAL NCLOB NEW NLSSORT NOT NOTNULL NULL NULLABLE OCTET_LENGTH OFFSET OLD ON ONLY OPEN OPERATION ORDER ORDINALITY OUTER OUTPUT OVER OVERLAPS OVERRIDING PAD PARAMETER PARAMETERS PARAMETER_MODE PARAMETER_NAME PARAMETER_ORDINAL_POSITION PARAMETER_SPECIFIC_CATALOG PARAMETER_SPECIFIC_NAME PARAMETER_SPECIFIC_SCHEMA PASCAL PATH PERFORMANCE PLACING PLI POSTFIX PREORDER PRIMARY PROCEDURE PUBLIC READS REFERENCES REFERENCING REJECT RESULT RETURN RETURNED_LENGTH RETURNED_OCTET_LENGTH RETURNING RIGHT ROLLUP ROUTINE ROUTINE_CATALOG ROUTINE_NAME ROUTINE_SCHEMA SCALE SCHEMA_NAME SCOPE SECTION SELECT SELF SENSITIVE SERVER_NAME SESSION_USER SETS SIMILAR SOME SOURCE SPACE SPECIFIC SPECIFICTYPE SPECIFIC_NAME SPLIT SQL SQLCODE SQLERROR SQLEXCEPTION SQLWARNING STATE STATIC STRUCTURE SUBCLASS_ORIGIN SUBLIST SUM SYMMETRIC SYSDATE SYSTEM_USER TABLE_NAME TABLE TERMINATE THEN TIMEZONE_HOUR TIMEZONE_MINUTE TO TRAILING TRANSACTIONS_COMMITTED TRANSACTIONS_ROLLED_BACK TRANSACTION_ACTIVE TRANSFORM TRANSFORMS TRANSLATE TRANSLATION TRIGGER TRIGGER_CATALOG TRIGGER_NAME TRIGGER_SCHEMA TRUE UESCAPE UNDER UNION UNIQUE UNNAMED UNNEST UPPER USAGE USER USER_DEFINED_TYPE_CATALOG USER_DEFINED_TYPE_NAME USER_DEFINED_TYPE_SCHEMA USING VARIABLE VARIADIC VARYING VERBOSE WHEN WHENEVER WHERE WINDOW WITH".replace(/\+/g, ' ')).split(/\s+/);//#237E18 + +function assistantHighlight(idVal) { + var pucl = document.getElementById(idVal); + if (pucl == null) return; + var temp = pucl.innerHTML; + + var htmlReg = new RegExp("\<.*?\>", "i"); + var arrA = new Array(); + for (var i = 0; true; i++) { + var m = htmlReg.exec(temp); + if (m) { + arrA[i] = m; + } + else { + break; + } + temp = temp.replace(m, "{[(" + i + ")]}"); + } + var temps=temp.split("\n"); + var realStr=""; + for (var i = 0; i < temps.length; i++) { + var tempStr=" "+temps[i]+" "; + if($.trim(tempStr)=="") + { + continue; + } + if(tempStr.indexOf(' --')==0) + { + realStr=realStr+""+tempStr+"\n"; + continue; + } + for (var w = 0; w < assistantKeywordsPurple.length; w++) { + var r = new RegExp(" (" + assistantKeywordsPurple[w] + ") ", "ig"); + tempStr = tempStr.replace(r, " $1 "); + } + for (var w = 0; w < assistantKeywordsBlue.length; w++) { + var r = new RegExp(" (" + assistantKeywordsBlue[w] + ") ", "ig"); + tempStr= tempStr.replace(r, " $1 "); + } + for (var w = 0; w < assistantKeywordsDeepGreen.length; w++) { + var r = new RegExp(" (" + assistantKeywordsDeepGreen[w] + ") ", "ig"); + tempStr = tempStr.replace(r, " $1 "); + } + realStr=realStr+tempStr+"\n"; + } + + for (var i = 0; i < arrA.length; i++) { + realStr = realStr.replace("{[(" + i + ")]}", arrA[i]); + } + + temps=realStr.split("\n"); + + realStr=""; + for (var i = 0; i < temps.length; i++) { + var tempStr=temps[i]; + if($.trim(tempStr)=="") + { + continue; + } + if(tempStr.indexOf('--')==0) + { + realStr=realStr+tempStr+"\r\n"; + continue; + } + for (var w = 0; w < assistantKeywordsPurple.length; w++) { + if(tempStr.toLowerCase()==assistantKeywordsPurple[w].toLowerCase()) + { + tempStr = ""+assistantKeywordsPurple[w]+""+tempStr.substr(assistantKeywordsPurple[w].length); + break; + } + } + for (var w = 0; w < assistantKeywordsBlue.length; w++) { + if(tempStr.toLowerCase()==assistantKeywordsBlue[w].toLowerCase()) + { + tempStr = ""+assistantKeywordsBlue[w]+""+tempStr.substr(assistantKeywordsBlue[w].length); + break; + } + } + for (var w = 0; w < assistantKeywordsDeepGreen.length; w++) { + if(tempStr.toLowerCase()==assistantKeywordsDeepGreen[w].toLowerCase()) + { + tempStr = ""+assistantKeywordsDeepGreen[w]+""+tempStr.substr(assistantKeywordsDeepGreen[w].length); + break; + } + } + realStr=realStr+tempStr+"\r\n"; + } + pucl.innerHTML = "
"+realStr.replace(/ , /g,",").replace(/' /g,"'").replace(/ ';/g,"';").replace(/ ; /g,";")+"
"; +} \ No newline at end of file diff --git a/code/datastudio/db_assistant/js/suggestionParser.js b/code/datastudio/db_assistant/js/suggestionParser.js new file mode 100644 index 0000000000000000000000000000000000000000..93edc6f868329cec6c9a3b09123703da8b4a36be --- /dev/null +++ b/code/datastudio/db_assistant/js/suggestionParser.js @@ -0,0 +1,203 @@ +function Commands() +{ + this.cmds=[]; + this.add=add; + this.find=find; + this.findInArray=findInArray; + this.getOneFromArray=getOneFromArray; + this.load=load; + var __that__=this; + function add(cmd) + { + this.cmds[this.cmds.length]=cmd; + } + function find(cmdId,cur_pos) + { + var tmpCmds=[]; + $(this.cmds).each(function(i,cmd) + { + if(cmd.id.split(' ')[cur_pos]==cmdId) + { + tmpCmds[tmpCmds.length]=cmd; + } + }); + return tmpCmds; + } + function findInArray(array,cmdId,cur_pos) + { + var tmpCmds=[]; + $(array).each(function(i,cmd) + { + /*$(cmd.subs).each(function(j,sub){ + if(sub.id==cmdId) + { + sub.show=true; + return array; + } + });*/ + if(cmd.id.split(' ')[cur_pos]==cmdId) + { + tmpCmds[tmpCmds.length]=cmd; + } + }); + if(tmpCmds.length==0) + { + tmpCmds=array; + } + return tmpCmds; + } + function getOneFromArrayCnt(array,cur_pos) + { + var cc=0; + $(array).each(function(i,cmd) + { + if(cmd.id.split(' ').length==cur_pos) + { + cc++; + } + }); + return cc; + } + function getOneFromArray(array,cur_pos) + { + var rtnCmd=""; + var tempCnt=getOneFromArrayCnt(array,cur_pos); + $(array).each(function(i,cmd) + { + if(cmd.id.split(' ').length==cur_pos&&(tempCnt==1||tempCnt>2||(tempCnt==2 &&(cmd.alias.replace(/\s+/g,"") ==selectedCmdAlias.replace(/\s+/g,""))))) + { + rtnCmd=cmd; + } + }); + return rtnCmd; + } + function load(xml) + { + __that__.cmds.length=0; + $(xml).find("command").each(function(i,cmdXml) + { + var cmd=new Command(cmdXml.getAttribute("id"),cmdXml.getAttribute("alias"),cmdXml.childNodes[0].text); + $(cmdXml).children("sub").each(function(j,subXml) + { + var sub=new Sub($(subXml).attr("id"),$(subXml).children("suggestion").text()); + //fillSub(sub,subXml); + cmd.addSub(sub); + }); + __that__.add(cmd); + }); + } +} + +function fillSub(sub,subXml) +{ + $(subXml).children("option").each(function(i,optionXml) + { + var option=new Option($(optionXml).attr("id"),$(optionXml).children("suggestion").text()); + sub.addOption(option); + }); + $(subXml).children("sub").each(function(i,subXmlTemp) + { + var subTemp=new Sub($(subXmlTemp).attr("id"),$(subXmlTemp).children("suggestion").text()); + fillSub(subTemp,subXmlTemp); + sub.addSub(subTemp); + }); +} +function Command(id,alias,suggestion) +{ + this.id=id; + this.alias=alias; + this.suggestion=suggestion; + this.options=[]; + this.subs=[]; + this.addOption=addOption; + this.findOption=findOption; + this.addSub=addSub; + this.findSub=findSub; + + function addOption(option) + { + this.options[this.options.length]=option; + } + function findOption(optionId) + { + var tmpOption=""; + $(this.options).each(function(i,option) + { + if(optionId==option.id) + { + tmpOption=option; + } + }); + return tmpOption; + } + + function addSub(sub) + { + this.subs[this.subs.length]=sub; + } + function findSub(subId) + { + var tmpSub=""; + $(this.subs).each(function(i,sub) + { + if(subId==sub.id) + { + tmpSub=sub; + } + }); + return tmpSub; + } +} + +function Option(id,suggestion) +{ + this.id=id; + this.suggestion=suggestion; +} + +function Sub(id,suggestion) +{ + this.id=id; + this.suggestion=suggestion; + //this.show=false; + this.options=[]; + this.subs=[]; + this.addOption=addOption; + this.findOption=findOption; + this.addSub=addSub; + this.findSub=findSub; + + function addOption(option) + { + this.options[this.options.length]=option; + } + function findOption(optionId) + { + var tmpOption=""; + $(this.options).each(function(i,option) + { + if(optionId==option.id) + { + tmpOption=option; + } + }); + return tmpOption; + } + + function addSub(sub) + { + this.subs[this.subs.length]=sub; + } + function findSub(subId) + { + var tmpSub=""; + $(this.subs).each(function(i,sub) + { + if(subId==sub.id) + { + tmpSub=sub; + } + }); + return tmpSub; + } +} \ No newline at end of file diff --git a/code/datastudio/db_assistant/openGauss 1.0.0/en/errorcode.xml b/code/datastudio/db_assistant/openGauss 1.0.0/en/errorcode.xml new file mode 100644 index 0000000000000000000000000000000000000000..9e60313e72f0d5738845ce45ea81d2a891b7fb15 --- /dev/null +++ b/code/datastudio/db_assistant/openGauss 1.0.0/en/errorcode.xml @@ -0,0 +1,28969 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  • 退出当前session,再重新连接并创建临时表
  • 使用DROP SCHEMA %s, %s CASCADE来删除临时schema,再重建临时表。
  • ]]>
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  • 查看当前relation的统计信息模式。
  • 查看guc参数enable_global_stats的类型。
  • 在当前guc参数模式下对relation进行analyze后再执行query。
  • ]]>
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  • 如果是主动调用访问不存在的事务的状态,无须处理。
  • 如果是gs_clean报出来的,可能是事务在某个节点未参与,无须处理。
  • 如果是一个正常的事务,节点也参与,请联系华为技术支持工程师提供技术支持。
  • ]]>
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    \ No newline at end of file diff --git a/code/datastudio/db_assistant/openGauss 1.0.0/en/gramma/public_sys-resources/caution_3.0-en-us.png b/code/datastudio/db_assistant/openGauss 1.0.0/en/gramma/public_sys-resources/caution_3.0-en-us.png new file mode 100644 index 0000000000000000000000000000000000000000..c9183d8a8c536be0eff9b1aa8a142d70ef5b6b48 Binary files /dev/null and b/code/datastudio/db_assistant/openGauss 1.0.0/en/gramma/public_sys-resources/caution_3.0-en-us.png differ diff --git a/code/datastudio/db_assistant/openGauss 1.0.0/en/gramma/public_sys-resources/note_3.0-en-us.png b/code/datastudio/db_assistant/openGauss 1.0.0/en/gramma/public_sys-resources/note_3.0-en-us.png new file mode 100644 index 0000000000000000000000000000000000000000..7f70ed7efaaf8fc439b2011bfa4374bc3f6c84e4 Binary files /dev/null and b/code/datastudio/db_assistant/openGauss 1.0.0/en/gramma/public_sys-resources/note_3.0-en-us.png differ diff --git a/code/datastudio/db_assistant/openGauss 1.0.0/en/gramma/public_sys-resources/notice_3.0-en-us.png b/code/datastudio/db_assistant/openGauss 1.0.0/en/gramma/public_sys-resources/notice_3.0-en-us.png new file mode 100644 index 0000000000000000000000000000000000000000..a92a3d5bb2b62e6ab28e94bb2dcb467c69ba4db5 Binary files /dev/null and b/code/datastudio/db_assistant/openGauss 1.0.0/en/gramma/public_sys-resources/notice_3.0-en-us.png differ diff --git a/code/datastudio/db_assistant/openGauss 1.0.0/en/suggestion.xml b/code/datastudio/db_assistant/openGauss 1.0.0/en/suggestion.xml new file mode 100644 index 0000000000000000000000000000000000000000..76d410153f39268b0ad20e027c2f4962957f53db --- /dev/null +++ b/code/datastudio/db_assistant/openGauss 1.0.0/en/suggestion.xml @@ -0,0 +1,7220 @@ + + + +

    Function 

    +

    ALTER DATABASE modifies a database, including its name, owner, connection limitation, and object isolation.

    +
    +

    Precautions 

    +
    • Only the owner of a database or a system administrator has the permission to run the ALTER DATABASE statement. Users other than system administrators may have the following permission constraints depending on the 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 and a member of the new owner, and have the CREATEDB permission.
      • To change the default tablespace, you must be a database owner or a system administrator, and must have the CREATE permission on the new 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.
      • Only a database owner or a system administrator can modify GUC parameters for the database.
      • Only database owners and system administrators can modify the object isolation attribute of a database.
      +
    • You are not allowed to rename a database in use. To rename it, connect to another database.
    +
    +

    Examples 

    +
    -- Set the maximum number of connections to database music to 10:
    +postgres=# ALTER DATABASE music CONNECTION LIMIT= 10 ; 
    +
    +-- Rename database music to music4:
    +postgres=# ALTER DATABASE music RENAME TO music4 ; 
    +
    +-- Change the owner of database music2 to user tom:
    +postgres=# ALTER DATABASE music2 OWNER TO tom ; 
    +
    +-- Set the tablespace of database music3 to PG_DEFAULT:
    +postgres=# ALTER DATABASE music3 SET TABLESPACE PG_DEFAULT ; 
    +
    +-- Disable the default index scan on database music3.
    +postgres=# ALTER DATABASE music3 SET enable_indexscan TO off ; 
    +
    +-- Reset the enable_indexscan parameter.
    +postgres=# ALTER DATABASE music3 RESET enable_indexscan ; 
    +Delete the databases:
    +postgres=# DROP DATABASE music2 ; 
    +postgres=# DROP DATABASE music3 ; 
    +postgres=# DROP DATABASE music4 ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]> + + +

    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 in openGauss.
    +
    +

    Examples 

    +
    -- Rename the data source.
    +postgres=# ALTER DATA SOURCE ds_test1 RENAME TO ds_test;
    +
    +-- Change the owner.
    +postgres=# CREATE USER user_test1 IDENTIFIED BY ' Gs@123456 ' ; 
    +postgres=# ALTER USER user_test1 WITH SYSADMIN ; 
    +postgres=# ALTER DATA SOURCE ds_test OWNER TO user_test1 ; 
    +
    +-- Modify TYPE and VERSION.
    +postgres=# ALTER DATA SOURCE ds_test TYPE ' MPPDB_TYPE ' VERSION ' XXX ' ; 
    +
    +-- Add a column.
    +postgres=# ALTER DATA SOURCE ds_test OPTIONS ( add dsn ' gaussdb ' , username ' test_user ' ) ; 
    +
    +-- Modify a column.
    +postgres=# ALTER DATA SOURCE ds_test OPTIONS ( set dsn ' unknown ' ) ; 
    +
    +-- Delete a column.
    +postgres=# ALTER DATA SOURCE ds_test OPTIONS ( drop username ) ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]> + + +

    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 the permissions for tables (including views), functions, and types (including domains) can be altered.

    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]> + + +

    Function 

    +

    ALTER DIRECTORY modifies a directory.

    +
    +

    Precautions 

    +
    • Currently, only the directory owner can be changed.
    • The owner can only be a user with the sysadmin permission.
    +
    +

    Examples 

    +
    -- Change the owner of the directory.
    +postgres=# ALTER DIRECTORY dir OWNER TO system ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]> + + +

    Function 

    +

    ALTER FUNCTION modifies the attributes of a customized function.

    +
    +

    Precautions 

    +

    Only the owner of the function or a system administrator has the permission to run this statement. If a function involves operations on temporary tables, ALTER FUNCTION cannot be used.

    +
    +

    Examples 

    +
    -- Alter the execution rule of function add to IMMUTABLE ( that is, the same result is returned if the parameter remains unchanged ) .
    +postgres=# ALTER FUNCTION func_add_sql2 ( INTEGER , INTEGER ) IMMUTABLE ; 
    +
    +-- Alter the name of function add to add_two_number.
    +postgres=# ALTER FUNCTION func_add_sql2 ( INTEGER , INTEGER ) RENAME TO add_two_number ; 
    +
    +-- Change the owner of function add to omm.
    +postgres=# ALTER FUNCTION add_two_number ( INTEGER , INTEGER ) OWNER TO omm ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]> + + +

    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 

    + +

    Parameter Description 

    +]]> + + +

    Function 

    +

    ALTER INDEX modifies the definition of an existing index.

    +

    It has the following forms:

    + +
    +

    Precautions 

    +

    Only the index owner or a system administrator can run this statement.

    +
    +

    Examples 

    +
    -- Rename an existing index.
    +postgres=# ALTER INDEX tpcds.ds_ship_mode_t1_index1 RENAME TO ds_ship_mode_t1_index5 ; 
    +
    +-- Set the index as unusable.
    +postgres=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 UNUSABLE ; 
    +
    +-- Rebuild an index.
    +postgres=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 REBUILD ; 
    +
    +-- Change the tablespace of the partitioned table index CA_ADDRESS_SK_index2 to example1.
    +postgres=# 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.
    +postgres=# ALTER INDEX tpcds.ds_customer_address_p1_index2 MOVE PARTITION CA_ADDRESS_SK_index3 TABLESPACE example2 ; 
    +
    +-- Rename a partitioned table index.
    +postgres=# ALTER INDEX tpcds.ds_customer_address_p1_index2 RENAME PARTITION CA_ADDRESS_SK_index1 TO CA_ADDRESS_SK_index4 ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]> + + +

    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 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    ALTER ROLE modifies role attributes.

    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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.

    +
    +

    Examples 

    +
    -- Change the name of the all_data_rls policy.
    +postgres=# 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.
    +postgres=# ALTER ROW LEVEL SECURITY POLICY all_data_new_rls ON all_data TO alice , bob ; 
    +postgres=# \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.
    +postgres=# ALTER ROW LEVEL SECURITY POLICY all_data_new_rls ON all_data USING ( id > 100 AND role = current_user ) ; 
    +postgres=# \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
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    ALTER SCHEMA modifies schema properties.

    +
    +

    Precautions 

    +

    Only the owner of a schema or a system administrator has the permission to run the ALTER SCHEMA statement.

    +
    +

    Examples 

    +
    -- Rename the current schema ds to ds_new.
    +postgres=# ALTER SCHEMA ds RENAME TO ds_new ; 
    +
    +-- Change the owner of ds_new to jack.
    +postgres=# ALTER SCHEMA ds_new OWNER TO jack ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    ALTER SEQUENCE modifies the parameters of an existing sequence.

    +
    +

    Precautions 

    +
    • You must be the owner of the sequence to use ALTER SEQUENCE.
    • In the current version, you can modify only the owner, owning column, and maximum value. 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 transactions, functions, and stored procedures.
    • After the maximum value of a sequence is changed, the cache of the sequence in all sessions is cleared.
    • The ALTER SEQUENCE statement blocks the invoking of nextval, setval, currval, and lastval.
    +
    +

    Examples 

    +
    -- Change the owning column of serial to T1.C1.
    +postgres=# ALTER SEQUENCE serial OWNED BY T1.C1 ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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.
    +
    +

    Examples 

    +
    -- Set the character code of the current session to UTF8.
    +postgres=# ALTER SESSION SET NAMES ' UTF8 ' ; 
    +
    +-- Set the current schema.
    +postgres=# ALTER SESSION SET CURRENT_SCHEMA TO tpcds ; 
    +
    +-- Set XML OPTION to DOCUMENT.
    +postgres=# ALTER SESSION SET XML OPTION DOCUMENT ; 
    +
    +-- Create the role joe and set it as the session role.
    +postgres=# CREATE ROLE joe WITH PASSWORD ' Bigdata@123 ' ; 
    +postgres=# ALTER SESSION SET SESSION AUTHORIZATION joe PASSWORD ' Bigdata@123 ' ; 
    +
    +-- Switch to the default user.
    +postgres=> ALTER SESSION SET SESSION AUTHORIZATION default;
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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.
    +
    +

    Examples 

    +
    -- Change the owner of synonym t1 to u1.
    +postgres=# ALTER SYNONYM t1 OWNER TO u1 ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    ALTER SYSTEM KILL SESSION ends a session.

    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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 access control, and adding or updating multiple columns.

    +
    +

    Precautions 

    +
    • Only the table owner or a system administrator has the permission to run the ALTER TABLE statement.
    • 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 PARTIAL CLUSTER KEY table-level constraints, but do not support primary and 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 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, and DEFAULT constant values. Only the DEFAULT value can be modified (by using SET DEFAULT and DROP DEFAULT). Currently, NULL and NOT NULL constraints cannot be modified.
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    ALTER TABLE PARTITION modifies table partition, including adding, deleting, splitting, merging partitions, and modifying partition attributes.

    +
    +

    Precautions 

    +
    • The tablespace for the added partition cannot be PG_GLOBAL.
    • The name of the added partition must be different from names of existing partitions in the partition table.
    • The partition key of the added partition must be the same type as that of the partition table. The key value of the added partition must exceed the upper limit of the last partition range.
    • If the number of partitions in the target partition table has reached the maximum (32767), partitions cannot be added.
    +
    • If a partition 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 partition, and they must be consistent.
    • The Value partition table does not support the Alter Partition operation.
    • Column-store tables and row-store tables cannot be partitioned.
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    ALTER TABLESPACE modifies the attributes of a tablespace.

    +
    +

    Precautions 

    +
    • Only the owner of a tablespace or a system administrator can execute the ALTER TABLESPACE statement.
    • To change the owner, you must also be a direct or indirect member of the new owning role.

      If new_owner is the same as old_owner, the current user will not be verified. A message indicating successful ALTER execution is displayed.

      +
      +
    +
    +

    Examples 

    +
    -- Rename the ds_location1 tablespace to ds_location3.
    +postgres=# ALTER TABLESPACE ds_location1 RENAME TO ds_location3 ; 
    +
    +-- Change the owner of the ds_location2 tablespace.
    +postgres=# ALTER TABLESPACE ds_location2 OWNER TO jay ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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.
    +
    +

    Examples 

    +
    -- Add text search configuration string mapping.
    +postgres=# ALTER TEXT SEARCH CONFIGURATION english_1 ADD MAPPING FOR word WITH simple , english_stem ; 
    +ALTER TEXT SEARCH CONFIGURATION
    +
    +-- Add text search configuration string mapping.
    +postgres=# ALTER TEXT SEARCH CONFIGURATION english_1 ADD MAPPING FOR email WITH english_stem , french_stem ; 
    +ALTER TEXT SEARCH CONFIGURATION
    +
    +-- Add text search configuration string mapping.
    +postgres=# ALTER TEXT SEARCH CONFIGURATION english_1 ALTER MAPPING REPLACE french_stem with german_stem ; 
    +ALTER TEXT SEARCH CONFIGURATION
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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.
    +
    +

    Examples 

    +
    -- Modify the definition of stop words in Snowball dictionaries. Retain the values of other parameters.
    +postgres=# 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.
    +postgres=# ALTER TEXT SEARCH DICTIONARY my_dict ( Language = dutch , StopWords ) ; 
    +
    +-- Update the dictionary definition and do not change any other content.
    +postgres=# ALTER TEXT SEARCH DICTIONARY my_dict ( dummy ) ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    ALTER TRIGGER modifies the definition of a trigger.

    +
    +

    Precautions 

    +

    Only the owner of a table where the trigger is created and a system administrator can run the ALTER TRIGGER statement.

    +
    +

    Examples 

    +
    -- Modify a trigger.
    +postgres=# ALTER TRIGGER delete_trigger ON test_trigger_src_tbl RENAME TO delete_trigger_renamed ; 
    +
    +-- Disable insert_trigger.
    +postgres=# ALTER TABLE test_trigger_src_tbl DISABLE TRIGGER insert_trigger ; 
    +
    +-- Disable all triggers on the current table.
    +postgres=# ALTER TABLE test_trigger_src_tbl DISABLE TRIGGER ALL ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    ALTER TYPE modifies the definition of a type.

    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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 owner of a view can use ALTER VIEW.
    • To change the schema of a view, you must have the CREATE permission on the new schema.
    • To change the owner of a view, you must be a direct or indirect member of the new owning role, and the member must have the CREATE permission on the view's schema.
    • An administrator can change the owner relationship of any view.
    +
    +

    Examples 

    +
    -- Rename a view.
    +postgres=# ALTER VIEW tpcds.customer_details_view_v1 RENAME TO customer_details_view_v2 ; 
    +
    +-- Change the schema of a view.
    +postgres=# ALTER VIEW tpcds.customer_details_view_v2 SET schema public ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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.

    +
    +

    Examples 

    +
    postgres=# 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.
    +postgres=# 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.
    +postgres=# ANALYZE customer ; 
    +
    +-- Run ANALYZE VERBOSE statement to update statistics and display table information.
    +postgres=# 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
    +If any environment-related fault occurs , check the logs of the primary node of the database.
    +
    +-- Delete the table.
    +postgres=# DROP TABLE customer ; 
    +postgres=# DROP TABLE customer_par ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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.

    +
    +

    Examples 

    +
    postgres=# 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.
    +postgres=# 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.
    +postgres=# ANALYZE customer ; 
    +
    +-- Run ANALYZE VERBOSE statement to update statistics and display table information.
    +postgres=# 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
    +If any environment-related fault occurs , check the logs of the primary node of the database.
    +
    +-- Delete the table.
    +postgres=# DROP TABLE customer ; 
    +postgres=# DROP TABLE customer_par ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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.

    +

    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.

    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    CALL can be used to call defined functions and stored procedures.

    +
    +

    Examples 

    +
    -- Transfer by parameter value.
    +postgres=# CALL func_add_sql ( 1 , 3 ) ; 
    +
    +-- Transfer by naming tag method.
    +postgres=# CALL func_add_sql ( num1 => 1 , num2 => 3 ) ; 
    +postgres=# CALL func_add_sql ( num2 := 2 , num1 := 3 ) ; 
    +
    +-- Transfer a constant as an output parameter.
    +postgres=# CALL func_increment_sql ( 1 , 2 , 1 ) ; 
    +
    +-- Call the function.
    +postgres=# call package_func_overload ( 1 , ' test ' ) ; 
    +postgres=# call package_func_overload ( 1 , 1 ) ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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 and checkpoint_timeout to adjust the atomized checkpoint intervals.

    +
    +

    Examples 

    +
    -- Set a checkpoint.
    +postgres=# CHECKPOINT ; 
    +
    +

    Syntax 

    +]]>
    +
    + +

    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.
    +
    +

    Examples 

    +
    -- Close the cursor and commit the transaction.
    +postgres=# CLOSE cursor1 ; 
    +
    +-- Close the cursor and commit the transaction.
    +postgres=# CLOSE cursor2 ; 
    +
    +-- Close the cursor.
    +postgres=# CLOSE cursor1 ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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.

    +
    +

    Examples 

    +
    -- Cluster the tpcds.inventory_p1 table.
    +postgres=# CLUSTER tpcds.inventory_p1 USING ds_inventory_p1_index1 ; 
    +
    +-- Cluster the p3 partition.
    +postgres=# CLUSTER tpcds.inventory_p1 PARTITION ( p3 ) USING ds_inventory_p1_index1 ; 
    +
    +-- Cluster the tables that can be clustered in the database.
    +postgres=# CLUSTER ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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.
    • For most objects, only the owner of the object can set comments. 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.
    +
    +

    Examples 

    +
    -- Comment out the tpcds.customer_demographics_t2.cd_demo_sk column.
    +postgres=# COMMENT ON COLUMN tpcds.customer_demographics_t2.cd_demo_sk IS ' Primary key of customer demographics table. ' ; 
    +
    +-- Comment out the tpcds.customer_details_view_v2 view.
    +postgres=# COMMENT ON VIEW tpcds.customer_details_view_v2 IS ' View of customer detail ' ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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.

    +
    +

    Examples 

    +
    -- Create a table.
    +postgres=# 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.
    +postgres=# START TRANSACTION ; 
    +
    +-- Insert data.
    +postgres=# INSERT INTO tpcds.customer_demographics_t2 VALUES ( 1 , ' M ' , ' U ' , ' DOCTOR DEGREE ' , 1200 , ' GOOD ' , 1 , 0 , 0 ) ; 
    +postgres=# 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.
    +postgres=# COMMIT ; 
    +
    +-- Query data.
    +postgres=# SELECT * FROM tpcds.customer_demographics_t2 ; 
    +
    +-- Delete the tpcds.customer_demographics_t2 table.
    +postgres=# DROP TABLE tpcds.customer_demographics_t2 ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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.

    +
    +

    Examples 

    +
    -- Create a table.
    +postgres=# 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.
    +postgres=# START TRANSACTION ; 
    +
    +-- Insert data.
    +postgres=# INSERT INTO tpcds.customer_demographics_t2 VALUES ( 1 , ' M ' , ' U ' , ' DOCTOR DEGREE ' , 1200 , ' GOOD ' , 1 , 0 , 0 ) ; 
    +postgres=# 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.
    +postgres=# COMMIT ; 
    +
    +-- Query data.
    +postgres=# SELECT * FROM tpcds.customer_demographics_t2 ; 
    +
    +-- Delete the tpcds.customer_demographics_t2 table.
    +postgres=# DROP TABLE tpcds.customer_demographics_t2 ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    COMMIT PREPARED commits a prepared two-phase transaction.

    +
    +

    Precautions 

    +
    • The function is only available in maintenance mode (when 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 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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 

    +
    • To run the COPY FROM FILENAME or COPY TO FILENAME statement, you must have the SYSADMIN permission. By default, user SYSADMIN is not allowed to run the COPY FROM FILENAME or COPY TO FILENAME statement on database configuration files, key files, certificate files, and audit logs, preventing user SYSADMIN from viewing or modifying sensitive files without authorization. To grant the permission, you need to change the setting of enable_copy_server_files.
    • COPY applies only to tables but not views.
    • To insert data to a table, you must have the permission to insert data.
    • 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 a backslash and a period (\.). 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.
    +
    +

    Examples 

    +
    -- Copy data from the tpcds.ship_mode file to the /home/omm/ds_ship_mode.dat file:
    +postgres=# COPY tpcds.ship_mode TO ' /home/omm/ds_ship_mode.dat ' ; 
    +
    +-- Output tpcds.ship_mode to stdout.
    +postgres=# COPY tpcds.ship_mode TO stdout;
    +
    +-- Copy data from stdin to the tpcds.ship_mode_t1 table.
    +postgres=# 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.
    +postgres=# 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, 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' ) .
    +postgres=# 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 ) .
    +postgres=# 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 ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    Create a database. By default, a new database is created by copying the standard system database template0. Only template0 can be used to create a new database.

    +
    +

    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.
    • Errors along the line of "could not initialize database directory" are most likely related to insufficient permissions on the data directory, a full disk, or other file system problems.
    +
    +

    Examples 

    +
    -- Create database music using GBK ( the local encoding type is also GBK ) :
    +postgres=# CREATE DATABASE music ENCODING ' GBK ' template = template0 ; 
    +
    +-- Create database music2 and specify user jim as its owner:
    +postgres=# CREATE DATABASE music2 OWNER jim ; 
    +
    +-- Create database music3 using template template0 and specify user jim as its owner:
    +postgres=# CREATE DATABASE music3 OWNER jim TEMPLATE template0 ; 
    +
    +-- Create a database compatible with the TD format.
    +postgres=# CREATE DATABASE td_compatible_db DBCOMPATIBILITY ' C ' ; 
    +
    +-- Create a database compatible with the ORA format.
    +postgres=# CREATE DATABASE ora_compatible_db DBCOMPATIBILITY ' A ' ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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 in openGauss.
    +
    +

    Examples 

    +
    -- Create an empty data source that does not contain any information.
    +postgres=# CREATE DATA SOURCE ds_test1 ; 
    +
    +-- Create a data source with TYPE information and VERSION being null.
    +postgres=# CREATE DATA SOURCE ds_test2 TYPE ' MPPDB ' VERSION NULL ; 
    +
    +-- Create a data source that contains only OPTIONS.
    +postgres=# CREATE DATA SOURCE ds_test3 OPTIONS ( dsn ' openGauss ' , encoding ' utf8 ' ) ; 
    +
    +-- Create a data source that contains TYPE, VERSION, and OPTIONS.
    +postgres=# CREATE DATA SOURCE ds_test4 TYPE ' unknown ' VERSION ' 11.2.3 ' OPTIONS ( dsn ' openGauss ' , username ' userid ' , password ' pwd@123456 ' , encoding ' ' ) ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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 

    +
    • By default, only initial users can create directories. If enable_access_server_directory is enabled (for details, see enable_access_server_directory), users with the sysadmin permission can also create directories.
    • 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.
    +
    +

    Examples 

    +
    -- Create a directory.
    +postgres=# CREATE OR REPLACE DIRECTORY dir as ' /tmp/ ' ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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.
    • 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. 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.
    +
    +

    Examples 

    +
    -- Define a function as SQL query.
    +postgres=# 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.
    +postgres=# CREATE OR REPLACE FUNCTION func_increment_plsql ( i integer ) RETURNS integer AS $$
    +BEGIN
    +RETURN i + 1 ; 
    +END ; 
    +$$ LANGUAGE plpgsql ; 
    +
    +-- Return the RECORD type.
    +CREATE OR REPLACE FUNCTION compute ( 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.
    +postgres=# CREATE FUNCTION func_dup_sql ( in int , out f1 int , out f2 text ) 
    +AS $$ SELECT $1 , CAST ( $1 AS text ) || ' is text ' $$
    +LANGUAGE SQL ; 
    +postgres=# SELECT * FROM func_dup_sql ( 42 ) ; 
    +
    +-- Compute the sum of two integers and return the result ( if the input is null, the returned result is null ) .
    +postgres=# CREATE FUNCTION func_add_sql2 ( num1 integer , num2 integer ) RETURN integer
    +AS
    +BEGIN
    +RETURN num1 + num2 ; 
    +END ; 
    +/
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    CREATE INDEX creates an index in a specified table.

    +

    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, 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
    +

    Partitioned tables do not support concurrent index creation, partial index creation, and NULL FIRST.

    +
    +

    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.
    • A unique index created on a partitioned table must include a partitioned column and all the partition keys.
    • Column-store tables support B-tree and psort indexes. If the two indexes are used, you cannot create expression, partial, and 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.
    +
    +

    Examples 

    +
    -- Create a common index on the SM_SHIP_MODE_SK column in the tpcds.ship_mode_t1 table.
    +postgres=# 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.
    +postgres=# 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:
    +postgres=# 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.
    +postgres=# CREATE UNIQUE INDEX ds_ship_mode_t1_index3 ON tpcds.ship_mode_t1 ( SM_SHIP_MODE_SK ) WHERE SM_SHIP_MODE_SK>10 ; 
    +
    +-- Create the partitioned table index ds_customer_address_p1_index1 without specifying the index partition name.
    +postgres=# 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.
    +postgres=# 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 column-store table and its GIN index:
    +postgres=# create table cgin_create_test ( a int , b text ) with ( orientation = column ) ; 
    +CREATE TABLE
    +postgres=# create index cgin_test on cgin_create_test using gin ( to_tsvector ( ' ngram ' , b ) ) ; 
    +CREATE INDEX
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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, replication tables, unlogged tables, and hash tables.
    • Row-level access control policies cannot be defined for foreign tables and 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 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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.
    • 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.
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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.
    +
    +

    Examples 

    +
    -- Create a schema named role1 for the role1 role. The owner of the films and winners tables created by the clause is role1.
    +postgres=# 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 ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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.
    +
    +

    Examples 

    +
    postgres=# CREATE SEQUENCE serial
    +START 101
    +CACHE 20 ; 
    +Select the next number from the sequence.
    +postgres=# SELECT nextval ( ' serial ' ) ; 
    +nextval
    +
    +--
    +102
    +Create a sequence associated with the table.
    +postgres=# 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 ) 
    + ) ; 
    +postgres=# CREATE SEQUENCE serial1
    +START 101
    +CACHE 20
    +OWNED BY customer_address.ca_address_sk ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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.
    • The CREATE SYNONYM statement of an associated function or stored procedure cannot be used in a stored procedure. You are advised to use synonyms existing in the pg_synonym system catalog in the stored procedure.
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    CREATE TABLE is used to create 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.
    • It is recommended that the number of column-store tables do not exceed 1000.
    • The primary key constraint and unique constraint in the table must contain distribution keys.
    • 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.
    • Column-store tables support only PARTIAL CLUSTER KEY table-level constraints, but do not support primary and foreign key table-level constraints.
    • Only the NULL, NOT NULL, and DEFAULT constant values 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.
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    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 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    CREATE TABLE PARTITION creates a partitioned table. A partitioned table is a logical table that is divided into several physical partitions for storage based on a specific plan. Data is stored in physical partitions not the logical table.

    +

    The common forms of partitioning include range partitioning, hash partitioning, list partitioning, and value partitioning. Currently, the system supports only range partitioning for row-store and column-store tables.

    +

    In range partitioning, a table is partitioned based on ranges defined by values in one or more columns, with no overlap between the ranges of values assigned to different partitions. Each range has a dedicated partition for data storage.

    +

    The range partitioning policy 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.

    +

    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 

    +

    A partitioned table supports unique and primary key constraints. The constraint keys of these constraints must contain all partition keys.

    +
    +

    Examples 

    +
    -- Create a range-partitioned table tpcds.web_returns_p1.
    +postgres=# 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 ) 
    + ) ; 
    +
    +-- Query the number of rows in the P1 partition.
    +postgres=# 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.
    +postgres=# CREATE TABLESPACE example1 RELATIVE LOCATION ' tablespace1/tablespace_1 ' ; 
    +postgres=# CREATE TABLESPACE example2 RELATIVE LOCATION ' tablespace2/tablespace_2 ' ; 
    +postgres=# CREATE TABLESPACE example3 RELATIVE LOCATION ' tablespace3/tablespace_3 ' ; 
    +postgres=# CREATE TABLESPACE example4 RELATIVE LOCATION ' tablespace4/tablespace_4 ' ; 
    +postgres=# 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.
    +postgres=# CREATE TABLE tpcds.web_returns_p3 ( LIKE tpcds.web_returns_p2 INCLUDING PARTITION ) ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    CREATE TABLESPACE creates a tablespace in a database.

    +
    +

    Precautions 

    +
    • Only system administrators can create a tablespace.
    • Do not run CREATE TABLESPACE in a transaction block.
    • If executing CREATE TABLESPACE fails but the internal directory (or file) has been created, the directory (or file) will remain. You need to manually clear it before creating the tablespace again. If there are residual files of soft links for the tablespace in the data directory, delete the residual files, and then perform O&M operations.
    • CREATE TABLESPACE cannot be used for two-phase transactions. If it fails on some nodes, the execution cannot be rolled back.
    • For details about how to prepare for creating tablespaces, see the description of parameters below.
    +
    +

    Examples 

    +
    -- Create a tablespace.
    +postgres=# CREATE TABLESPACE ds_location1 RELATIVE LOCATION ' tablespace/tablespace_1 ' ; 
    +
    +-- Create a tablespace and set its owner to user joe.
    +postgres=# CREATE TABLESPACE ds_location2 OWNER joe RELATIVE LOCATION ' tablespace/tablespace_1 ' ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    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.

    +
    +

    Precautions 

    +
    • If only the parser is specified, the new text search configuration initially has no mapping from token types to dictionaries, and therefore will ignore all words. Subsequently, ALTER TEXT SEARCH CONFIGURATION must be used to create mapping to make the configuration useful. If COPY is specified, the parser, mapping and parameters of the text search configuration is copied automatically.
    • If the schema name is given, the text search configuration will be created in the specified schema. Otherwise, the configuration will be created in the current schema.
    • The user who defines a text search configuration becomes its owner.
    • PARSER and COPY options are mutually exclusive, because when an existing configuration is copied, its parser selection is copied too.
    • If only the parser is specified, the new text search configuration initially has no mapping from token types to dictionaries, and therefore will ignore all words.
    +
    +

    Examples 

    +
    -- Create a text search configuration.
    +postgres=# CREATE TEXT SEARCH CONFIGURATION ngram2 ( parser=ngram ) WITH ( gram_size = 2 , grapsymbol_ignore = false ) ; 
    +
    +-- Create a text search configuration.
    +postgres=# CREATE TEXT SEARCH CONFIGURATION ngram3 ( copy=ngram2 ) WITH ( gram_size = 2 , grapsymbol_ignore = false ) ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    CREATE TEXT SEARCH DICTIONARY creates a full-text retrieval dictionary. A dictionary is used to identify and process particular words during full-text retrieval.

    +

    Dictionaries are created by using predefined templates (defined in the PG_TS_TEMPLATE system catalog). Five types of dictionaries can be created, Simple, Ispell, Synonym, Thesaurus, and Snowball. These dictionaries are used to handle different types of tasks.

    +
    +

    Precautions 

    +
    • A user with the SYSADMIN permission can create a dictionary. Then, the user automatically becomes the owner of the dictionary.
    • A dictionary cannot be created in pg_temp mode.
    • After a dictionary is created or modified, any modification to the customized dictionary definition file will not affect the dictionary in the database. To make such modifications take effect in the dictionary in the database, run the ALTER statement to update the definition file of the dictionary.
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    CREATE TRIGGER creates a trigger. The trigger will be associated with the specified table or view, and will execute the specified function operations are performed.

    +
    +

    Precautions 

    +
    • Currently, triggers can be created only on ordinary row-store tables, instead of on column-store tables, temporary tables, or unlogged tables.
    • If multiple triggers of the same kind are defined for the same event, they will be fired in alphabetical order by name.
    • Triggers are usually used for data association and synchronization between multiple tables. SQL execution performance is greatly affected. Therefore, you are advised not to use this statement when a large amount of data needs to be synchronized and performance requirements are high.
    +
    +

    Examples 

    +
    -- Create a source table and a destination table.
    +postgres=# CREATE TABLE test_trigger_src_tbl ( id1 INT , id2 INT , id3 INT ) ; 
    +postgres=# CREATE TABLE test_trigger_des_tbl ( id1 INT , id2 INT , id3 INT ) ; 
    +
    +-- Create a trigger function.
    +postgres=# CREATE OR REPLACE FUNCTION tri_insert_func ( ) RETURNS TRIGGER AS
    +$$
    +DECLARE
    +BEGIN
    +INSERT INTO test_trigger_des_tbl VALUES ( NEW.id1 , NEW.id2 , NEW.id3 ) ; 
    +RETURN NEW ; 
    +END
    +$$ LANGUAGE PLPGSQL ; 
    +postgres=# CREATE OR REPLACE FUNCTION tri_update_func ( ) RETURNS TRIGGER AS
    +$$
    +DECLARE
    +BEGIN
    +UPDATE test_trigger_des_tbl SET id3 = NEW.id3 WHERE id1=OLD.id1 ; 
    +RETURN OLD ; 
    +END
    +$$ LANGUAGE PLPGSQL ; 
    +postgres=# CREATE OR REPLACE FUNCTION TRI_DELETE_FUNC ( ) RETURNS TRIGGER AS
    +$$
    +DECLARE
    +BEGIN
    +DELETE FROM test_trigger_des_tbl WHERE id1=OLD.id1 ; 
    +RETURN OLD ; 
    +END
    +$$ LANGUAGE PLPGSQL ; 
    +
    +-- Create an INSERT trigger.
    +postgres=# CREATE TRIGGER insert_trigger
    +BEFORE INSERT ON test_trigger_src_tbl
    +FOR EACH ROW
    +EXECUTE PROCEDURE tri_insert_func ( ) ; 
    +
    +-- Create an UPDATE trigger.
    +postgres=# CREATE TRIGGER update_trigger
    +AFTER UPDATE ON test_trigger_src_tbl
    +FOR EACH ROW
    +EXECUTE PROCEDURE tri_update_func ( ) ; 
    +
    +-- Create a DELETE trigger.
    +postgres=# CREATE TRIGGER delete_trigger
    +BEFORE DELETE ON test_trigger_src_tbl
    +FOR EACH ROW
    +EXECUTE PROCEDURE tri_delete_func ( ) ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    CREATE TYPE registers 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.

    +

    The following data types can be created: composite type, base type, shell type, and enumerated type.

    +
    • Composite type

      A composite type is specified by a list of attribute names and data types. If the data type of an attribute is collatable, the attribute's collation rule can also be specified. This is essentially the same as the row type of a table, but using CREATE TYPE avoids the need to create an actual table when all that is wanted is to define a type. A stand-alone composite type is useful as the parameter or return type of a function.

      +

      To create a composite type, you must have the USAGE permission on all of its attribute types.

      +
    • Base type

      You can create a base type (scalar type). Generally, these functions must be written in the underlying language.

      +
    • Shell type

      A shell type is simply a placeholder for a type to be defined later; it is created by issuing CREATE TYPE with no parameters except for the type name. Shell types are needed as forward references when base types are created.

      +
    • Enumerated type

      An enumerated type is a list of one or more quoted labels, each of which must be 1 to 64 bytes long.

      +
    +
    +

    Precautions 

    +

    If a schema name is given then the type is created in the specified schema. Otherwise, it is created in the current schema. The type name must be distinct from the name of any existing type or domain in the same schema. (Because tables have associated data types, the type name must also be distinct from the name of any existing table in the same schema.)

    +
    +

    Examples 

    +
    -- Create a composite type, create a table, insert data, and make a query.
    +postgres=# CREATE TYPE compfoo AS ( f1 int , f2 text ) ; 
    +postgres=# CREATE TABLE t1_compfoo ( a int , b compfoo ) ; 
    +postgres=# CREATE TABLE t2_compfoo ( a int , b compfoo ) ; 
    +postgres=# INSERT INTO t1_compfoo values ( 1 , ( 1 , ' demo ' ) ) ; 
    +postgres=# INSERT INTO t2_compfoo select * from t1_typ5 ; 
    +postgres=# SELECT ( b ) .f1 FROM t1_compfoo ; 
    +postgres=# SELECT * FROM t1_compfoo t1 join t2_compfoo t2 on ( t1.b ) .f1= ( t1.b ) .f1 ; 
    +
    +-- Change the owner of the user-defined type compfoo1 to usr1.
    +postgres=# CREATE USER usr1 PASSWORD ' Bigdata@123 ' ; 
    +postgres=# ALTER TYPE compfoo1 OWNER TO usr1 ; 
    +
    +-- Create an enumerated type.
    +postgres=# CREATE TYPE bugstatus AS ENUM ( ' create ' , ' modify ' , ' closed ' ) ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    CREATE USER creates a user.

    +
    +

    Precautions 

    +
    • A user created using the CREATE USER statement has the LOGIN permission by default.
    • A schema named after the user is automatically created in the database where the statement is executed, but not in other databases. You can run the CREATE SCHEMA statement to create such a schema for the user in other databases.
    • 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 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    CREATE VIEW creates a view. A view is a virtual table, not a base table. Only view definition is stored in the database and view data is not. The data is stored in a base table. If data in the base table changes, the data in the view changes accordingly. In this sense, a view is like a window through which users can know their interested data and data changes in the database.

    +
    +

    Examples 

    +
    -- Create a view consisting of columns whose spcname is pg_default.
    +postgres=# CREATE VIEW myView AS
    +SELECT * FROM pg_tablespace WHERE spcname = ' pg_default ' ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    CURSOR defines a cursor to retrieve a small number of rows at a time out of a larger query.

    +

    To process SQL statements, the stored procedure process assigns a memory segment to store context association. Cursors are handles or pointers pointing to context regions. With cursors, stored procedures can control alterations in context regions.

    +
    +

    Precautions 

    +
    • CURSOR is used only in transaction blocks.
    • Generally, CURSOR and SELECT both have text returns. Since data is stored in binary format in the system, the system needs to convert the data from the binary format to the text format. If data is returned in text format, client applications need to convert the data back to the binary format for processing. FETCH implements conversion between binary data and text data.
    • Binary cursors should be used carefully. Text usually occupies larger space than binary data. A binary cursor returns internal binary data, which is easier to operate. A text cursor returns text, which is easier to retrieve and therefore reduces workload on the client. As an example, if a query returns a value of one from an integer column, you would get a string of 1 with a default cursor, whereas with a binary cursor you would get a 4-byte field containing the internal representation of the value (in big-endian byte order).
    +
    +

    Examples 

    +
    -- Set up cursor1.
    +postgres=# CURSOR cursor1 FOR SELECT * FROM tpcds.customer_address ORDER BY 1 ; 
    +
    +-- Fetch the first three rows in cursor1.
    +postgres=# FETCH FORWARD 3 FROM cursor1 ; 
    +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type
    +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+----------------------
    +1 | AAAAAAAABAAAAAAA | 18 | Jackson | Parkway | Suite 280 | Fairfield | Maricopa County | AZ | 86192 | United States | -7.00 | condo
    +2 | AAAAAAAACAAAAAAA | 362 | Washington 6th | RD | Suite 80 | Fairview | Taos County | NM | 85709 | United States | -7.00 | condo
    +3 | AAAAAAAADAAAAAAA | 585 | Dogwood Washington | Circle | Suite Q | Pleasant Valley | York County | PA | 12477 | United States | -5.00 | single family
    + ( 3 rows ) 
    +
    +-- Close the cursor and commit the transaction.
    +postgres=# CLOSE cursor1 ; 
    +
    +-- Set up cursor2.
    +postgres=# CURSOR cursor2 FOR VALUES ( 1 , 2 ) , ( 0 , 3 ) ORDER BY 1 ; 
    +
    +-- Fetch the first two rows in cursor2.
    +postgres=# FETCH FORWARD 2 FROM cursor2 ; 
    +column1 | column2
    +---------+---------
    +0 | 3
    +1 | 2
    + ( 2 rows ) 
    +
    +-- Close the cursor and commit the transaction.
    +postgres=# CLOSE cursor2 ; 
    +
    +-- Set up a WITH HOLD cursor.
    +postgres=# DECLARE cursor1 CURSOR WITH HOLD FOR SELECT * FROM tpcds.customer_address ORDER BY 1 ; 
    +
    +-- Fetch the first two rows in cursor1.
    +postgres=# FETCH FORWARD 2 FROM cursor1 ; 
    +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type
    +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+----------------------
    +1 | AAAAAAAABAAAAAAA | 18 | Jackson | Parkway | Suite 280 | Fairfield | Maricopa County | AZ | 86192 | United States | -7.00 | condo
    +2 | AAAAAAAACAAAAAAA | 362 | Washington 6th | RD | Suite 80 | Fairview | Taos County | NM | 85709 | United States | -7.00 | condo
    + ( 2 rows ) 
    +
    +-- Fetch the next row in cursor1.
    +postgres=# FETCH FORWARD 1 FROM cursor1 ; 
    +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type
    +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+----------------------
    +3 | AAAAAAAADAAAAAAA | 585 | Dogwood Washington | Circle | Suite Q | Pleasant Valley | York County | PA | 12477 | United States | -5.00 | single family
    + ( 1 row ) 
    +
    +-- Close the cursor.
    +postgres=# CLOSE cursor1 ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DEALLOCATE deallocates a previously prepared statement. If you do not explicitly deallocate a prepared statement, it is deallocated when the session ends.

    +

    The PREPARE keyword is always ignored.

    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DECLARE defines a cursor to retrieve a small number of rows at a time out of a larger query and can be the start of an anonymous block.

    +

    This section describes usage of cursors. The usage of anonymous blocks is available in BEGIN.

    +

    To process SQL statements, the stored procedure process assigns a memory segment to store context association. Cursors are handles or pointers pointing to context regions. With cursors, stored procedures can control alterations in context regions.

    +

    Generally, CURSOR and SELECT both have text returns. Since data is stored in binary format in the system, the system needs to convert the data from the binary format to the text format. If data is returned in text format, client applications need to convert the data back to the binary format for processing. FETCH implements conversion between binary data and text data.

    +
    +

    Precautions 

    +
    • CURSOR is used only in transaction blocks.
    • Binary cursors should be used carefully. Text usually occupies larger space than binary data. A binary cursor returns internal binary data, which is easier to operate. A text cursor returns text, which is easier to retrieve and therefore reduces workload on the client. As an example, if a query returns a value of one from an integer column, you would get a string of 1 with a default cursor, whereas with a binary cursor you would get a 4-byte field containing the internal representation of the value (in big-endian byte order).
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DELETE deletes rows that satisfy the WHERE clause from the specified table. If the WHERE clause is absent, the effect is to delete all rows in the table. The result is a valid, but an empty table.

    +
    +

    Precautions 

    +
    • You must have the DELETE permission on the table to delete from it, as well as the SELECT permission for any table in the USING clause or whose values are read in the condition.
    • For row-store tables, the DELETE operation can be used only when they have primary key constraints.
    • For column-store tables, the RETURNING clause is currently not supported.
    +
    +

    Examples 

    +
    -- Delete employees whose ca_address_sk is smaller than 14888 from the tpcds.customer_address_bak table.
    +postgres=# DELETE FROM tpcds.customer_address_bak WHERE ca_address_sk < 14888 ; 
    +
    +-- Delete all data from the tpcds.customer_address_bak table.
    +postgres=# DELETE FROM tpcds.customer_address_bak ; 
    +Delete the tpcds.customer_address_bak table.
    +postgres=# DROP TABLE tpcds.customer_address_bak ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DO executes an anonymous code block.

    +

    The code block is treated as though it were the body of a function with no parameters, returning void. It is parsed and executed a single time.

    +
    +

    Precautions 

    +
    • he procedural language to be used must already have been installed into the current database by means of CREATE LANGUAGE. plpgsql is installed by default, but other languages are not.
    • The user must have the USAGE permission on the procedural language, or must be a system administrator if the language is untrusted.
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DROP DATABASE deletes a database.

    +
    +

    Precautions 

    +
    • Only the owner of a database or a system administrator has the DROP DATABASE permission.
    • The preinstalled POSTGRES, TEMPLATE0, and TEMPLATE1 databases are protected and therefore cannot be deleted. To check databases in the current service, run the gsql statement \l.
    • If any users are connected to the database, the database cannot be deleted.
    • DROP DATABASE cannot be executed within a transaction block.
    • If DROP DATABASE fails and is rolled back, run DROP DATABASE IF EXISTS again.
    +

    DROP DATABASE cannot be undone.

    +
    +
    +

    Examples 

    +
    -- Reset the enable_indexscan parameter.
    +postgres=# ALTER DATABASE music3 RESET enable_indexscan ; 
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DROP DATA SOURCE deletes a data source.

    +
    +

    Examples 

    +
    -- Delete the data source.
    +postgres=# DROP DATA SOURCE ds_tst1 CASCADE ; 
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DROP Directory deletes a synonym.

    +
    +

    Precautions 

    +

    By default, only the initial user can perform the drop operation. When enable_access_server_directory (enable_access_server_directory), users with the sysadmin permission can also perform the drop operation.

    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DROP FUNCTION deletes a function.

    +
    +

    Precautions 

    +

    If a function involves operations on temporary tables, DROP FUNCTION cannot be used.

    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DROP GROUP deletes a user group.

    +

    DROP GROUP is an alias for DROP ROLE.

    +
    +

    Precautions 

    +

    DROP GROUP is an internal interface of the openGauss management tool. You are not advised to use this interface, because doing so affects openGauss.

    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DROP INDEX deletes an index.

    +
    +

    Precautions 

    +

    Only the owner of an index or a system administrator has the DROP INDEX permission.

    +
    +

    Examples 

    +
    -- Delete an existing index.
    +postgres=# DROP INDEX tpcds.ds_ship_mode_t1_index2 ; 
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DROP OWNED deletes the database objects owned by a database role.

    +
    +

    Precautions 

    +
    • This interface will revoke the role's permissions on all objects in the current database and shared objects (databases and tablespaces).
    • DROP OWNED is often used to prepare for removing one or more roles. Because DROP OWNED affects only the objects in the current database, you need to run this statement in each database that contains the objects owned by the role to be removed.
    • Using the CASCADE option may cause this statement to recursively remove objects owned by other users.
    • The databases and tablespaces owned by the role will not be removed.
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DROP ROW LEVEL SECURITY POLICY deletes a row-level access control policy from a table.

    +
    +

    Precautions 

    +

    Only the owner of a table or a system administrator has the DROP ROW LEVEL SECURITY POLICY permission.

    +
    +

    Examples 

    +
    -- Delete a row-level access control policy.
    +postgres=# DROP ROW LEVEL SECURITY POLICY all_data_rls ON all_data ; 
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DROP PROCEDURE deletes a stored procedure.

    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DROP ROLE deletes a role.

    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DROP SCHEMA deletes a schema from the current database.

    +
    +

    Precautions 

    +

    Only the owner of a schema or a system administrator has the DROP SCHEMA permission.

    +
    +

    Examples 

    +
    -- Delete the schema.
    +postgres=# DROP SCHEMA role1 CASCADE ; 
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DROP SEQUENCE deletes a sequence from the current database.

    +
    +

    Precautions 

    +

    Only the owner of a schema or a system administrator has the DROP SEQUENCE permission.

    +
    +

    Examples 

    +
    -- Delete a sequence.
    +postgres=# DROP SEQUENCE serial ; 
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DROP SYNONYM deletes a synonym.

    +
    +

    Precautions 

    +

    Only the owner of a synonym or a system administrator has the DROP SYNONYM permission.

    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DROP TABLE deletes a table.

    +
    +

    Precautions 

    +

    DROP TABLE forcibly deletes the specified table and the indexes depending on the table. After the table is deleted, the functions and stored procedures that need to use this table cannot be executed. Deleting a partitioned table also deletes all partitions in the table.

    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DROP TABLESPACE deletes a tablespace.

    +
    +

    Precautions 

    +
    • Only the owner of a tablespace or a system administrator has the DROP TABLESPACE permission.
    • The tablespace to be deleted should not contain any database objects. Otherwise, an error will be reported.
    • DROP TABLESPACE cannot be rolled back and therefore cannot be run in transaction blocks.
    • During execution of DROP TABLESPACE, database queries by other sessions using \db may fail and need to be reattempted.
    • If DROP TABLESPACE fails to be executed, run DROP TABLESPACE IF EXISTS.
    +
    +

    Examples 

    +
    -- Delete the tablespace.
    +postgres=# DROP TABLESPACE ds_location2 ; 
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DROP TEXT SEARCH CONFIGURATION deletes a text search configuration.

    +
    +

    Precautions 

    +

    Only the owner of a text search configuration has the DROP TEXT SEARCH CONFIGURATION permission.

    +
    +

    Examples 

    +
    -- Delete the text search configuration.
    +postgres=# DROP TEXT SEARCH CONFIGURATION joe.ngram_2 ; 
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DROP TEXT SEARCH DICTIONARY deletes a full-text retrieval dictionary.

    +
    +

    Precautions 

    +
    • Predefined dictionaries do not support the DROP operations.
    • Only the owner of a dictionary or a system administrator has the DROP TEXT SEARCH DICTIONARY permission.
    • Execute DROP...CASCADE only when necessary because this operation will delete the text search configurations that use this dictionary.
    +
    +

    Examples 

    +
    -- Delete the english dictionary.
    +DROP TEXT SEARCH DICTIONARY english ; 
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DROP TRIGGER deletes a trigger.

    +
    +

    Precautions 

    +

    Only the owner of a trigger or a system administrator has the DROP TRIGGER permission.

    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DROP TYPE deletes a user-defined data type. Only the owner of a type has the DROP TYPE permission.

    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DROP USER deletes a user and the schema with the same name as the user.

    +
    +

    Precautions 

    +
    • CASCADE is used to delete the objects (excluding databases) that depend on the user. CASCADE cannot delete locked objects unless the objects are unlocked or the processes locking the objects are killed.
    • In openGauss, the enable_kill_query configuration parameter exists in the postgresql.conf file. This parameter affects CASCADE.
      • If enable_kill_query is on and CASCADE is used, the statement automatically kills the processes locking dependent objects and then deletes the specified user.
      • If enable_kill_query is off and CASCADE is used, the statement waits until the processes locking dependent objects stop and then deletes the specified user.
      +
    • If the dependent objects are other databases or reside in other databases, manually delete them before deleting the user from the current database. DROP USER cannot delete objects across databases.
    • If a data source depends on the user, the user cannot be deleted directly. You need to manually delete the data source first.
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    DROP VIEW forcibly deletes a view from the database.

    +
    +

    Precautions 

    +

    Only the owner of a view or a system administrator has the DROP VIEW permission.

    +
    +

    Examples 

    +
    -- Delete the view.
    +postgres=# DROP VIEW myView ; 
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    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.

    +
    +

    Precautions 

    +

    If the PREPARE statement creating the prepared statement declares some parameters, the parameter set passed to the EXECUTE statement must be compatible. Otherwise, an error will occur.

    +
    +

    Examples 

    +
    -- Create a prepared statement for an INSERT statement and execute the prepared statement.
    +postgres=# PREPARE insert_reason ( integer , character ( 16 ) , character ( 100 ) ) AS INSERT INTO tpcds.reason_t1 VALUES ( $1 , $2 , $3 ) ; 
    +postgres=# EXECUTE insert_reason ( 52 , ' AAAAAAAADDAAAAAA ' , ' reason 52 ' ) ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    EXPLAIN shows the execution plan of an SQL statement.

    +

    The execution plan shows how the tables referenced by the statement will be scanned - by plain sequential scan, index scan, etc. - and if multiple tables are referenced, what join algorithms will be used to bring together the required rows from each input table.

    +

    The most critical part of the display is the estimated statement execution cost, which is the planner's guess at how long it will take to run the statement.

    +

    The ANALYZE option causes the statement to be actually executed, not only planned. The total elapsed time expended within each plan node (in milliseconds) and total number of rows it actually returned are added to the display. This is useful for seeing whether the planner's estimates are close to reality.

    +
    +

    Precautions 

    +

    The statement is actually executed when the ANALYZE option is used. If you wish to use EXPLAIN ANALYZE on an INSERT, UPDATE, DELETE, CREATE TABLE AS, or EXECUTE statement without letting the statement affect your data, use this approach:

    +
    START TRANSACTION;
    +EXPLAIN ANALYZE ...;
    +ROLLBACK;
    +
    +

    Examples 

    +
    -- Change the value of explain_perf_mode to normal.
    +postgres=# SET explain_perf_mode=normal ; 
    +
    +-- Display an execution plan for simple queries in the table.
    +postgres=# EXPLAIN SELECT * FROM tpcds.customer_address_p1 ; 
    +QUERY PLAN
    +--------------------------------------------------
    +Data Node Scan ( cost=0.00..0.00 rows=0 width=0 ) 
    +Node/s: All dbnodes
    + ( 2 rows ) 
    +
    +-- Generate an execution plan in JSON format ( with explain_perf_mode being normal ) .
    +postgres=# EXPLAIN ( FORMAT JSON ) SELECT * FROM tpcds.customer_address_p1 ; 
    +QUERY PLAN
    +--------------------------------------
    +[ +
    +{ +
    +"Plan": { +
    +"Node Type": "Data Node Scan" , +
    +"Startup Cost": 0.00 , +
    +"Total Cost": 0.00 , +
    +"Plan Rows": 0 , +
    +"Plan Width": 0 , +
    +"Node/s": "All dbnodes" +
    +} +
    +} +
    +]
    + ( 1 row ) 
    +
    +-- If there is an index and we use a query with an indexable WHERE condition, EXPLAIN might show a different plan.
    +postgres=# EXPLAIN SELECT * FROM tpcds.customer_address_p1 WHERE ca_address_sk=10000 ; 
    +QUERY PLAN
    +--------------------------------------------------
    +Data Node Scan ( cost=0.00..0.00 rows=0 width=0 ) 
    +Node/s: dn_6005_6006
    + ( 2 rows ) 
    +
    +-- Generate an execution plan in YAML format ( with explain_perf_mode being normal ) .
    +postgres=# EXPLAIN ( FORMAT YAML ) SELECT * FROM tpcds.customer_address_p1 WHERE ca_address_sk=10000 ; 
    +QUERY PLAN
    +---------------------------------
    +- Plan: +
    +Node Type: "Data Node Scan"+
    +Startup Cost: 0.00 +
    +Total Cost: 0.00 +
    +Plan Rows: 0 +
    +Plan Width: 0 +
    +Node/s: "dn_6005_6006"
    + ( 1 row ) 
    +
    +-- Here is an example of a query plan with cost estimates suppressed:
    +postgres=# EXPLAIN ( COSTS FALSE ) SELECT * FROM tpcds.customer_address_p1 WHERE ca_address_sk=10000 ; 
    +QUERY PLAN
    +------------------------
    +Data Node Scan
    +Node/s: dn_6005_6006
    + ( 2 rows ) 
    +
    +-- Here is an example of a query plan for a query using an aggregate function:
    +postgres=# EXPLAIN SELECT SUM ( ca_address_sk ) FROM tpcds.customer_address_p1 WHERE ca_address_sk<10000 ; 
    +QUERY PLAN
    +---------------------------------------------------------------------------------------
    +Aggregate ( cost=18.19..14.32 rows=1 width=4 ) 
    +-> Streaming ( type: GATHER ) ( cost=18.19..14.32 rows=3 width=4 ) 
    +Node/s: All dbnodes
    +-> Aggregate ( cost=14.19..14.20 rows=3 width=4 ) 
    +-> Seq Scan on customer_address_p1 ( cost=0.00..14.18 rows=10 width=4 ) 
    +Filter: ( ca_address_sk < 10000 ) 
    + ( 6 rows ) 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    EXPLAIN PLAN saves information about an execution plan into the PLAN_TABLE table. Different from the EXPLAIN statement, EXPLAIN PLAN only saves plan information and does not print information on the screen.

    +
    +

    Precautions 

    +
    • EXPLAIN PLAN cannot be executed on a database node.
    • Plan information cannot be collected for SQL statements that failed to be executed.
    • Data in PLAN_TABLE is in a session-level lifecycle. Sessions are isolated from users, and therefore users can only view the data of the current session and current user.
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    FETCH retrieves rows using a previously created cursor.

    +

    A cursor has an associated position, which is used by FETCH. The cursor position can be before the first row of the query result, on any particular row of the result, or after the last row of the result.

    +
    • When created, a cursor is positioned before the first row.
    • After fetching some rows, the cursor is positioned on the row most recently retrieved.
    • If FETCH runs off the end of the available rows then the cursor is left positioned after the last row, or before the first row if fetching backward.
    • FETCH ALL or FETCH BACKWARD ALL will always leave the cursor positioned after the last row or before the first row.
    +
    +

    Precautions 

    +
    • If the cursor is declared with NO SCROLL, backward fetches like FETCH BACKWARD are not allowed.
    • The forms NEXT, PRIOR, FIRST, LAST, ABSOLUTE, and RELATIVE fetch a single row after moving the cursor appropriately. If there is no such row, an empty result is returned, and the cursor is left positioned before the first row (backward fetch) or after the last row (forward fetch) as appropriate.
    • The forms using FORWARD and BACKWARD retrieve the indicated number of rows moving in the forward or backward direction, leaving the cursor positioned on the last-returned row or after (backward fetch)/before (forward fetch) all rows if the count exceeds the number of rows available.
    • RELATIVE 0, FORWARD 0, and BACKWARD 0 all request fetching the current row without moving the cursor, that is, re-fetching the most recently fetched row. This will succeed unless the cursor is positioned before the first row or after the last row; in which case, no row is returned.
    • If the cursor of FETCH involves a column-store table, backward fetches like BACKWARD, PRIOR, and FIRST are not allowed.
    +
    +

    Examples 

    +
    -- Fetch the first three rows in cursor1.
    +postgres=# FETCH FORWARD 3 FROM cursor1 ; 
    +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type
    +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+----------------------
    +1 | AAAAAAAABAAAAAAA | 18 | Jackson | Parkway | Suite 280 | Fairfield | Maricopa County | AZ | 86192 | United States | -7.00 | condo
    +2 | AAAAAAAACAAAAAAA | 362 | Washington 6th | RD | Suite 80 | Fairview | Taos County | NM | 85709 | United States | -7.00 | condo
    +3 | AAAAAAAADAAAAAAA | 585 | Dogwood Washington | Circle | Suite Q | Pleasant Valley | York County | PA | 12477 | United States | -5.00 | single family
    + ( 3 rows ) 
    +
    +-- Fetch the first two rows in cursor2.
    +postgres=# FETCH FORWARD 2 FROM cursor2 ; 
    +column1 | column2
    +---------+---------
    +0 | 3
    +1 | 2
    + ( 2 rows ) 
    +
    +-- Fetch the first two rows in cursor1.
    +postgres=# FETCH FORWARD 2 FROM cursor1 ; 
    +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type
    +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+----------------------
    +1 | AAAAAAAABAAAAAAA | 18 | Jackson | Parkway | Suite 280 | Fairfield | Maricopa County | AZ | 86192 | United States | -7.00 | condo
    +2 | AAAAAAAACAAAAAAA | 362 | Washington 6th | RD | Suite 80 | Fairview | Taos County | NM | 85709 | United States | -7.00 | condo
    + ( 2 rows ) 
    +
    +-- Fetch the next row in cursor1.
    +postgres=# FETCH FORWARD 1 FROM cursor1 ; 
    +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type
    +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+----------------------
    +3 | AAAAAAAADAAAAAAA | 585 | Dogwood Washington | Circle | Suite Q | Pleasant Valley | York County | PA | 12477 | United States | -5.00 | single family
    + ( 1 row ) 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    GRANT is used to grant permissions to roles and users.

    +

    GRANT is used in the following scenarios:

    +
    • Granting system permissions to roles or users

      System permissions are also called user properties, including SYSADMIN, CREATEDB, CREATEROLE, AUDITADMIN, and LOGIN.

      +

      They can be specified only by the CREATE ROLE or ALTER ROLE statement. The SYSADMIN permissions can be granted and revoked using GRANT ALL PRIVILEGE and REVOKE ALL PRIVILEGE, respectively. System permissions cannot be inherited by a user from a role, and cannot be granted using PUBLIC.

      +
    • Granting database object permissions to roles or users

      Grant permissions related to database objects (tables, views, specified columns, databases, functions, schemas, and tablespaces) to specified roles or users.

      +

      GRANT gives specific permissions on a database object to one or more roles. These permissions are added to those already granted, if any.

      +

      The keyword PUBLIC indicates that the permissions are to be granted to all roles, including those that might be created later. PUBLIC can be thought of as an implicitly defined group that always includes all roles. Any particular role will have the sum of permissions granted directly to it, permissions granted to any role it is presently a member of, and permissions granted to PUBLIC.

      +

      If WITH GRANT OPTION is specified, the recipient of the permission can in turn grant it to others. Without a grant option, the recipient cannot do that. GRANT options cannot be granted to PUBLIC. Only openGauss supports this operation.

      +

      openGauss grants the permissions for objects of certain types to PUBLIC. By default, permissions on tables, columns, sequences, foreign data sources, foreign servers, schemas, and tablespaces are not granted to PUBLIC, but the following permissions are granted to PUBLIC: CONNECT and CREATE TEMP TABLE permissions on databases, EXECUTE permission on functions, and USAGE permission on languages and data types (including domains). An object owner can revoke the default permissions granted to PUBLIC and grant permissions to other users as needed. For security purposes, you are advised to create an object and set its permissions in the same transaction so that other users do not have time windows to use the object. In addition, you can run the ALTER DEFAULT PRIVILEGES statement to modify the default permissions.

      +
    • Granting a role's or user's permissions to other roles or users

      Grant a role's or user's permissions to one or more roles or users. In this case, every role or user can be regarded as a set of one or more database permissions.

      +

      If WITH ADMIN OPTION is specified, the recipients can in turn grant the permissions to other roles or users or revoke the permissions they have granted to other roles or users. If recipients' permissions are changed or revoked later, the grantees' permissions will also change.

      +

      Database administrators can grant or revoke permissions for any roles or users. Roles with the CREATEROLE permission can grant or revoke permissions for non-admin roles.

      +
    +
    +

    Examples 

    +
    postgres=# CREATE USER joe PASSWORD ' Bigdata@123 ' ; 
    +postgres=# GRANT ALL PRIVILEGES TO joe ; 
    +Afterward , user joe has the sysadmin permissions.
    +Example 2: Granting object permissions to a user or role
    +Revoke the sysadmin permission from the joe user. Grant the usage permission of the tpcds schema and all permissions on the tpcds.reason table to joe.postgres=# REVOKE ALL PRIVILEGES FROM joe ; 
    +postgres=# GRANT USAGE ON SCHEMA tpcds TO joe ; 
    +postgres=# GRANT ALL PRIVILEGES ON tpcds.reason TO joe ; 
    +Then joe has all permissions on the tpcds.reason table , including create , retrieve , update , and delete.
    +Grant the retrieve permission of r_reason_sk , r_reason_id , and r_reason_desc columns and the update permission of the r_reason_desc column in the tpcds.reason table to joe.postgres=# GRANT select ( r_reason_sk , r_reason_id , r_reason_desc ) , update ( r_reason_desc ) ON tpcds.reason TO joe ; 
    +Then joe has the retrieve permission of r_reason_sk and r_reason_id columns in the tpcds.reason table. To enable user joe to grant these permissions to other users , execute the following statement:
    +postgres=# GRANT select ( r_reason_sk , r_reason_id ) ON tpcds.reason TO joe WITH GRANT OPTION ; 
    +Grant the postgres database connection permission and schema creation permission to user joe , and enable this user to grant these permissions to other users.
    +postgres=# GRANT create , connect on database postgres TO joe WITH GRANT OPTION ; 
    +Create role tpcds_manager , grant the tpcds schema access permission and object creation permission to this role , but do not enable this role to grant these permissions to others.
    +postgres=# CREATE ROLE tpcds_manager PASSWORD ' Bigdata@123 ' ; 
    +postgres=# GRANT USAGE , CREATE ON SCHEMA tpcds TO tpcds_manager ; 
    +Grant all the permissions on the tpcds_tbspc tablespace to user joe but do not enable this user to grant these permissions to others.
    +postgres=# CREATE TABLESPACE tpcds_tbspc RELATIVE LOCATION ' tablespace/tablespace_1 ' ; 
    +postgres=# GRANT ALL ON TABLESPACE tpcds_tbspc TO joe ; 
    +Example 3: Granting the permissions of one user or role to others
    +Create role manager , grant user joe ' s permissions to the created role , and enable this role to grant its permissions to others.postgres=# CREATE ROLE manager PASSWORD ' Bigdata@123 ' ; 
    +postgres=# GRANT joe TO manager WITH ADMIN OPTION ; 
    +Create role senior_manager and grant manager ' s permissions to senior_manager.postgres=# CREATE ROLE senior_manager PASSWORD ' Bigdata@123 ' ; 
    +postgres=# GRANT manager TO senior_manager ; 
    +Revoke permissions granted to senior_manager and manager and delete manager.postgres=# REVOKE manager FROM joe ; 
    +postgres=# REVOKE senior_manager FROM manager ; 
    +postgres=# DROP USER manager ; 
    +Example 4: Revoking permissions and deleting roles and users
    +postgres=# REVOKE ALL PRIVILEGES ON tpcds.reason FROM joe ; 
    +postgres=# REVOKE ALL PRIVILEGES ON SCHEMA tpcds FROM joe ; 
    +postgres=# REVOKE ALL ON TABLESPACE tpcds_tbspc FROM joe ; 
    +postgres=# DROP TABLESPACE tpcds_tbspc ; 
    +postgres=# REVOKE USAGE , CREATE ON SCHEMA tpcds FROM tpcds_manager ; 
    +postgres=# DROP ROLE tpcds_manager ; 
    +postgres=# DROP ROLE senior_manager ; 
    +postgres=# DROP USER joe CASCADE ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    INSERT inserts new rows into a table.

    +
    +

    Precautions 

    +
    • You must have the INSERT permission on a table in order to insert rows into it.
    • Use of the RETURNING clause requires the SELECT permission on all columns mentioned in RETURNING.
    • If ON DUPLICATE KEY UPDATE is used, you must have the SELECT and UPDATE permissions on the table and the SELECT permission on the unique constraint (primary key or unique index).
    • If you use the query clause to insert rows from a query, you need to have the SELECT permission on any table or column used in the query.
    • When you connect to a database compatible to Teradata and td_compatible_truncation is on, a long string will be automatically truncated. If later INSERT statements (not involving foreign tables) insert long strings to columns of char- and varchar-typed columns in the target table, the system will truncate the long strings to ensure no strings exceed the maximum length defined in the target table.

      If inserting multi-byte character data (such as Chinese characters) to database with the character set byte encoding (SQL_ASCII, LATIN1), and the character data crosses the truncation position, the string is truncated based on its bytes instead of characters. Unexpected result will occur in tail after the truncation. If you want correct truncation result, you are advised to adopt encoding set such as UTF8, which has no character data crossing the truncation position.

      +
      +
    +
    +

    Examples 

    +
    -- Insert a record into a table.
    +postgres=# INSERT INTO tpcds.reason_t2 ( r_reason_sk , r_reason_id , r_reason_desc ) VALUES ( 1 , ' AAAAAAAABAAAAAAA ' , ' reason1 ' ) ; 
    +
    +-- Insert a record into the table, which is equivalent to the previous syntax.
    +postgres=# INSERT INTO tpcds.reason_t2 VALUES ( 2 , ' AAAAAAAABAAAAAAA ' , ' reason2 ' ) ; 
    +
    +-- Insert multiple records into the table.
    +postgres=# INSERT INTO tpcds.reason_t2 VALUES ( 3 , ' AAAAAAAACAAAAAAA ' , ' reason3 ' ) , ( 4 , ' AAAAAAAADAAAAAAA ' , ' reason4 ' ) , ( 5 , ' AAAAAAAAEAAAAAAA ' , ' reason5 ' ) ; 
    +
    +-- Insert records whose r_reason_sk in the tpcds.tpcds.reason table is less than 5.
    +postgres=# INSERT INTO tpcds.reason_t2 SELECT * FROM tpcds.reason WHERE r_reason_sk <5 ; 
    +
    +-- Insert multiple records into the table. If the records conflict, update the r_reason_id field in the conflicting row to 'BBBBBBBBCAAAAAAA'.
    +postgres=# INSERT INTO tpcds.reason_t2 VALUES ( 5 , ' BBBBBBBBCAAAAAAA ' , ' reason5 ' ) , ( 6 , ' AAAAAAAADAAAAAAA ' , ' reason6 ' ) ON DUPLICATE KEY UPDATE r_reason_id = ' BBBBBBBBCAAAAAAA ' ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    LOCK TABLE obtains a table-level lock.

    +

    openGauss always tries to select the lock mode with minimum constraints when automatically requesting a lock for a statement referenced by a table. Use LOCK if users need a more strict lock mode. For example, suppose an application runs a transaction at the Read Committed isolation level and needs to ensure that data in a table remains stable in the duration of the transaction. To achieve this, you could obtain SHARE lock mode over the table before the query. This will prevent concurrent data changes and ensure subsequent reads of the table see a stable view of committed data. It is because the SHARE lock mode conflicts with the ROW EXCLUSIVE lock acquired by writers, and your LOCK TABLE name IN SHARE MODE statement will wait until any concurrent holders of ROW EXCLUSIVE mode locks commit or roll back. Therefore, once you obtain the lock, there are no uncommitted writes outstanding; furthermore none can begin until you release the lock.

    +
    +

    Precautions 

    +
    • LOCK TABLE is useless outside a transaction block: the lock would remain held only to the completion of the statement. If LOCK TABLE is out of any transaction block, an error is reported.
    • If no lock mode is specified, then ACCESS EXCLUSIVE, the most restrictive mode, is used.
    • LOCK TABLE ... IN ACCESS SHARE MODE requires the SELECT permission on the target table. All other forms of LOCK require table-level UPDATE and/or the DELETE permission.
    • There is no UNLOCK TABLE statement. Locks are always released at transaction end.
    • LOCK TABLE only deals with table-level locks, and so the mode names involving ROW are all misnomers. These mode names should generally be read as indicating the intention of the user to acquire row-level locks within the locked table. Also, ROW EXCLUSIVE mode is a shareable table lock. Note that all the lock modes have identical semantics so far as LOCK TABLE is concerned, differing only in the rules about which modes conflict with which. For details about the rules, see Table 1.
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    MOVE repositions a cursor without retrieving any data. MOVE works exactly like the FETCH statement, except it only repositions the cursor and does not return rows.

    +
    +

    Examples 

    +
    -- Skip the first three rows of cursor1.
    +postgres=# MOVE FORWARD 3 FROM cursor1 ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    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

    +
    +

    Precautions 

    +
    • You have the INSERT and UPDATE permissions for the target table and the SELECT permission for the source table.
    • MERGE INTO cannot be executed during redistribution.
    +
    +

    Examples 

    +
    -- Run MERGE INTO.
    +postgres=# MERGE INTO products p
    +USING newproducts np
    +ON ( p.product_id = np.product_id ) 
    +WHEN MATCHED THEN
    +UPDATE SET p.product_name = np.product_name , p.category = np.category WHERE p.product_name != ' play gym ' 
    +WHEN NOT MATCHED THEN
    +INSERT VALUES ( np.product_id , np.product_name , np.category ) WHERE np.category = ' books ' ; 
    +MERGE 4
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    PREPARE creates a prepared statement.

    +

    A prepared statement is a performance optimizing object on the server. When the PREPARE statement is executed, the specified query is parsed, analyzed, and rewritten. When EXECUTE is executed, the prepared statement is planned and executed. This avoids repetitive parsing and analysis. After the PREPARE statement is created, it exists throughout the database session. Once it is created (even if in a transaction block), it will not be deleted when a transaction is rolled back. It can only be deleted by explicitly invoking DEALLOCATE or automatically deleted when the session ends.

    +
    +

    Examples 

    +
    -- Create a prepared statement for an INSERT statement and execute the prepared statement.
    +postgres=# PREPARE insert_reason ( integer , character ( 16 ) , character ( 100 ) ) AS INSERT INTO tpcds.reason_t1 VALUES ( $1 , $2 , $3 ) ; 
    +postgres=# EXECUTE insert_reason ( 52 , ' AAAAAAAADDAAAAAA ' , ' reason 52 ' ) ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    PREPARE TRANSACTION prepares the current transaction for two-phase commit.

    +

    After this statement, the transaction is no longer associated with the current session; instead, its state is fully stored on disk, and there is a high probability that it can be committed successfully, even if a database crash occurs before the commit is requested.

    +

    Once prepared, a transaction can later be committed or rolled back with COMMIT PREPARED or ROLLBACK PREPARED, respectively. Those statements can be issued from any session, not only the one that executed the original transaction.

    +

    From the point of view of the issuing session, PREPARE TRANSACTION is not unlike a ROLLBACK statement: after executing it, there is no active current transaction, and the effects of the prepared transaction are no longer visible. (The effects will become visible again if the transaction is committed.)

    +

    If the PREPARE TRANSACTION statement fails for any reason, it becomes a ROLLBACK and the current transaction is canceled.

    +
    +

    Precautions 

    +
    • The transaction function is maintained automatically by the database, and should be not visible to users.
    • When running the PREPARE TRANSACTION statement, increase the value of max_prepared_transactions in configuration file postgresql.conf. You are advised to set max_prepared_transactions to a value not less than that of max_connections so that one pending prepared transaction is available for each session.
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    REASSIGN OWNED changes the owner of the database object.

    +

    REASSIGN OWNED requires that the system change owners of all the database objects owned by old_roles to new_role.

    +
    +

    Precautions 

    +
    • REASSIGN OWNED is often executed before role deletion.
    • To run the REASSIGN OWNED statement, you must have the permissions of the original and target roles.
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    REINDEX rebuilds an index using the data stored in the index's table, replacing the old copy of the index.

    +

    There are several scenarios in which REINDEX can be used:

    +
    • An index has become corrupted, and no longer contains valid data.
    • An index has become "bloated", that is, it contains many empty or nearly-empty pages.
    • You have altered a storage parameter (such as a fill factor) for an index, and wish that the change takes full effect.

      An index build with the CONCURRENTLY option failed, leaving an "invalid" index.

      +
    +
    +

    Precautions 

    +

    REINDEX DATABASE and REINDEX SYSTEM type cannot be performed in transaction blocks.

    +
    +

    Examples 

    +
    -- Rebuild a single index.
    +postgres=# REINDEX INDEX tpcds.tpcds_customer_index1 ; 
    +
    +-- Rebuild all indexes in the tpcds.customer_t1 table:
    +postgres=# REINDEX TABLE tpcds.customer_t1 ; 
    +Delete the tpcds.customer_t1 table.
    +postgres=# DROP TABLE tpcds.customer_t1 ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    RELEASE SAVEPOINT destroys a savepoint previously defined in the current transaction.

    +

    Destroying a savepoint makes it unavailable as a rollback point, but it has no other user visible behavior. It does not undo the effects of statements executed after the savepoint was established. To do that, use ROLLBACK TO SAVEPOINT. Destroying a savepoint when it is no longer needed allows the system to reclaim some resources earlier than transaction end.

    +

    RELEASE SAVEPOINT also destroys all savepoints that were established after the named savepoint was established.

    +
    +

    Precautions 

    +
    • Specifying a savepoint name that was not previously defined causes an error.
    • It is not possible to release a savepoint when the transaction is in an aborted state.
    • If multiple savepoints have the same name, only the one that was most recently defined is released.
    +
    +

    Examples 

    +
    -- Delete the savepoint.
    +postgres=# RELEASE SAVEPOINT my_savepoint;
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    RESET restores run-time parameters to their default values. The default values are parameter default values complied in the postgresql.conf configuration file.

    +

    RESET is an alternative spelling for:

    +

    SET configuration_parameter TO DEFAULT

    +
    +

    Precautions 

    +

    RESET and SET have the same transaction behavior. Their impact will be rolled back.

    +
    +

    Examples 

    +
    -- Reset timezone to the default value.
    +postgres=# RESET timezone ; 
    +
    +-- Set all parameters to their default values.
    +postgres=# RESET ALL ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    REVOKE revokes permissions from one or more roles.

    +
    +

    Precautions 

    +

    If a non-owner user of an object attempts to REVOKE permission on the object, the statement is executed based on the following rules:

    +
    • If the user has no permissions whatsoever on the object, the statement will fail outright.
    • If an authorized user has some permissions, only the permissions with authorization options are revoked.
    • If the authorized user does not have the authorization option, the REVOKE ALL PRIVILEGES form will issue an error message. For other forms of statements, if the permission specified in the statement does not have the corresponding authorization option, the statement will issue a warning.
    • Do not perform REVOKE to a table partition. Otherwise, an alarm will be generated.
    +
    +

    Examples 

    +
    postgres=# CREATE USER joe PASSWORD ' Bigdata@123 ' ; 
    +postgres=# GRANT ALL PRIVILEGES TO joe ; 
    +Afterward , user joe has the sysadmin permissions.
    +Example 2: Granting object permissions to a user or role
    +Revoke the sysadmin permission from the joe user. Grant the usage permission of the tpcds schema and all permissions on the tpcds.reason table to joe.postgres=# REVOKE ALL PRIVILEGES FROM joe ; 
    +postgres=# GRANT USAGE ON SCHEMA tpcds TO joe ; 
    +postgres=# GRANT ALL PRIVILEGES ON tpcds.reason TO joe ; 
    +Then joe has all permissions on the tpcds.reason table , including create , retrieve , update , and delete.
    +Grant the retrieve permission of r_reason_sk , r_reason_id , and r_reason_desc columns and the update permission of the r_reason_desc column in the tpcds.reason table to joe.postgres=# GRANT select ( r_reason_sk , r_reason_id , r_reason_desc ) , update ( r_reason_desc ) ON tpcds.reason TO joe ; 
    +Then joe has the retrieve permission of r_reason_sk and r_reason_id columns in the tpcds.reason table. To enable user joe to grant these permissions to other users , execute the following statement:
    +postgres=# GRANT select ( r_reason_sk , r_reason_id ) ON tpcds.reason TO joe WITH GRANT OPTION ; 
    +Grant the postgres database connection permission and schema creation permission to user joe , and enable this user to grant these permissions to other users.
    +postgres=# GRANT create , connect on database postgres TO joe WITH GRANT OPTION ; 
    +Create role tpcds_manager , grant the tpcds schema access permission and object creation permission to this role , but do not enable this role to grant these permissions to others.
    +postgres=# CREATE ROLE tpcds_manager PASSWORD ' Bigdata@123 ' ; 
    +postgres=# GRANT USAGE , CREATE ON SCHEMA tpcds TO tpcds_manager ; 
    +Grant all the permissions on the tpcds_tbspc tablespace to user joe but do not enable this user to grant these permissions to others.
    +postgres=# CREATE TABLESPACE tpcds_tbspc RELATIVE LOCATION ' tablespace/tablespace_1 ' ; 
    +postgres=# GRANT ALL ON TABLESPACE tpcds_tbspc TO joe ; 
    +Example 3: Granting the permissions of one user or role to others
    +Create role manager , grant user joe ' s permissions to the created role , and enable this role to grant its permissions to others.postgres=# CREATE ROLE manager PASSWORD ' Bigdata@123 ' ; 
    +postgres=# GRANT joe TO manager WITH ADMIN OPTION ; 
    +Create role senior_manager and grant manager ' s permissions to senior_manager.postgres=# CREATE ROLE senior_manager PASSWORD ' Bigdata@123 ' ; 
    +postgres=# GRANT manager TO senior_manager ; 
    +Revoke permissions granted to senior_manager and manager and delete manager.postgres=# REVOKE manager FROM joe ; 
    +postgres=# REVOKE senior_manager FROM manager ; 
    +postgres=# DROP USER manager ; 
    +Example 4: Revoking permissions and deleting roles and users
    +postgres=# REVOKE ALL PRIVILEGES ON tpcds.reason FROM joe ; 
    +postgres=# REVOKE ALL PRIVILEGES ON SCHEMA tpcds FROM joe ; 
    +postgres=# REVOKE ALL ON TABLESPACE tpcds_tbspc FROM joe ; 
    +postgres=# DROP TABLESPACE tpcds_tbspc ; 
    +postgres=# REVOKE USAGE , CREATE ON SCHEMA tpcds FROM tpcds_manager ; 
    +postgres=# DROP ROLE tpcds_manager ; 
    +postgres=# DROP ROLE senior_manager ; 
    +postgres=# DROP USER joe CASCADE ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    ROLLBACK rolls back the current transaction and backs out all updates in the transaction.

    +

    ROLLBACK backs out of all changes that a transaction makes to a database if the transaction fails to be executed due to a fault.

    +
    +

    Precautions 

    +

    If a ROLLBACK statement is executed out of a transaction, no error occurs, but a notice is displayed.

    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    ROLLBACK PREPARED cancels a transaction ready for two-phase committing.

    +
    +

    Precautions 

    +
    • The function is only available in maintenance mode (when 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 user that initiates a transaction or the system administrator can roll back the transaction.
    • The transaction function is maintained automatically by the database, and should be not visible to users.
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    ROLLBACK TO SAVEPOINT rolls back to a savepoint. It implicitly destroys all savepoints that were established after the named savepoint.

    +

    Rolls back all statements that were executed after the savepoint was established. The savepoint remains valid and can be rolled back to again later, if needed.

    +
    +

    Precautions 

    +
    • Specifying a savepoint name that has not been established is an error.
    • Cursors have somewhat non-transactional behavior with respect to savepoints. Any cursor that is opened inside a savepoint will be closed when the savepoint is rolled back. If a previously opened cursor is affected by a FETCH or MOVE statement inside a savepoint that is later rolled back, the cursor remains at the position that FETCH left it pointing to (that is, the cursor motion caused by FETCH is not rolled back). Closing a cursor is not undone by rolling back, either. A cursor whose execution causes a transaction to abort is put in a cannot-execute state, so while the transaction can be restored using ROLLBACK TO SAVEPOINT, the cursor can no longer be used.
    • Use ROLLBACK TO SAVEPOINT to roll back to a savepoint. Use RELEASE SAVEPOINT to destroy a savepoint but keep the effects of the statements executed after the savepoint was established.
    +
    +

    Examples 

    +
    -- Undo the effects of the statements executed after my_savepoint was established:
    +postgres=# START TRANSACTION ; 
    +postgres=# SAVEPOINT my_savepoint;
    +postgres=# ROLLBACK TO SAVEPOINT my_savepoint;
    +
    +-- Cursor positions are not affected by savepoint rollback.
    +postgres=# DECLARE foo CURSOR FOR SELECT 1 UNION SELECT 2 ; 
    +postgres=# SAVEPOINT foo ; 
    +postgres=# FETCH 1 FROM foo ; 
    +?column?
    +----------
    +1
    +postgres=# ROLLBACK TO SAVEPOINT foo ; 
    +postgres=# FETCH 1 FROM foo ; 
    +?column?
    +----------
    +2
    +postgres=# RELEASE SAVEPOINT my_savepoint;
    +postgres=# COMMIT ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    SAVEPOINT establishes a new savepoint within the current transaction.

    +

    A savepoint is a special mark inside a transaction. It allows all statements executed following its establishment to be rolled back, restoring the transaction state to what it was at the time of the savepoint.

    +
    +

    Precautions 

    +
    • Use ROLLBACK TO SAVEPOINT to roll back to a savepoint. Use RELEASE SAVEPOINT to destroy a savepoint but keep the effects of the statements executed after the savepoint was established.
    • Savepoints can only be established when inside a transaction block. Multiple savepoints can be defined in a transaction.
    • Functions, anonymous blocks, and stored procedures do not support the SAVEPOINT syntax.
    • In the case of an unexpected termination of a distributed thread or process caused by a node or connection failure, or of an error caused by the inconsistency between source and destination table structures in a COPY FROM operation, the transaction cannot be rolled back to the established savepoint. Instead, the entire transaction will be rolled back.
    • According to the SQL standard, when a savepoint with the same name is created, the previous savepoint with the same name is automatically deleted. In openGauss, the old savepoint is retained, but only the latest one is used during rollback or release. Releasing the newer savepoint with RELEASE SAVEPOINT will cause the older one to again become accessible to ROLLBACK TO SAVEPOINT and RELEASE SAVEPOINT. In addition, SAVEPOINT fully complies with the SQL standard.
    +
    +

    Examples 

    +
    -- Create a savepoint.
    +postgres=# SAVEPOINT my_savepoint;
    +
    +-- Roll back a savepoint.
    +postgres=# ROLLBACK TO SAVEPOINT my_savepoint;
    +
    +-- Create a savepoint.
    +postgres=# SAVEPOINT my_savepoint;
    +
    +-- Roll back a savepoint.
    +postgres=# RELEASE SAVEPOINT my_savepoint;
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    SELECT retrieves data from a table or view.

    +

    Serving as an overlaid filter for a database table, SELECT filters required data from the table using SQL keywords.

    +
    +

    Precautions 

    +
    • You must have the SELECT permission on each field used in the SELECT statement.
    +
    +

    Examples 

    +
    -- Obtain the temp_t temporary table by a subquery and query all records in this table.
    +postgres=# WITH temp_t ( name , isdba ) AS ( SELECT usename , usesuper FROM pg_user ) SELECT * FROM temp_t;
    +
    +-- Query all r_reason_sk records in the tpcds.reason table and delete duplicate records.
    +postgres=# SELECT DISTINCT ( r_reason_sk ) FROM tpcds.reason ; 
    +
    +-- Example of a LIMIT clause: Obtain a record from the table.
    +postgres=# SELECT * FROM tpcds.reason LIMIT 1 ; 
    +
    +-- Query all records and sort them in alphabetic order.
    +postgres=# SELECT r_reason_desc FROM tpcds.reason ORDER BY r_reason_desc ; 
    +
    +-- Use table aliases to obtain data from the pg_user and pg_user_status tables:
    +postgres=# SELECT a.usename , b.locktime FROM pg_user a , pg_user_status b WHERE a.usesysid=b.roloid ; 
    +
    +-- Example of the FULL JOIN clause: Join data in the pg_user and pg_user_status tables.
    +postgres=# SELECT a.usename , b.locktime , a.usesuper FROM pg_user a FULL JOIN pg_user_status b on a.usesysid=b.roloid ; 
    +
    +-- Example of the GROUP BY clause: Filter data based on query conditions, and group the results.
    +postgres=# SELECT r_reason_id , AVG ( r_reason_sk ) FROM tpcds.reason GROUP BY r_reason_id HAVING AVG ( r_reason_sk ) > 25 ; 
    +
    +-- Example of the GROUP BY CUBE clause: Filter data based on query conditions, and group the results.
    +postgres=# SELECT r_reason_id , AVG ( r_reason_sk ) FROM tpcds.reason GROUP BY CUBE ( r_reason_id , r_reason_sk ) ; 
    +
    +-- Example of the GROUP BY GROUPING SETS clause: Filter data based on query conditions, and group the results.
    +postgres=# SELECT r_reason_id , AVG ( r_reason_sk ) FROM tpcds.reason GROUP BY GROUPING SETS ( ( r_reason_id , r_reason_sk ) , r_reason_sk ) ; 
    +
    +-- Example of the UNION clause: Merge the names started with W and N in the r_reason_desc column in the tpcds.reason table.
    +postgres=# SELECT r_reason_sk , tpcds.reason.r_reason_desc
    +FROM tpcds.reason
    +WHERE tpcds.reason.r_reason_desc LIKE ' W% ' 
    +UNION
    +SELECT r_reason_sk , tpcds.reason.r_reason_desc
    +FROM tpcds.reason
    +WHERE tpcds.reason.r_reason_desc LIKE ' N% ' ; 
    +
    +-- Example of the NLS_SORT clause: Sort by Chinese Pinyin.
    +postgres=# SELECT * FROM tpcds.reason ORDER BY NLSSORT ( r_reason_desc , ' NLS_SORT = SCHINESE_PINYIN_M ' ) ; 
    +
    +-- Case-insensitive order:
    +postgres=# SELECT * FROM tpcds.reason ORDER BY NLSSORT ( r_reason_desc , ' NLS_SORT = generic_m_ci ' ) ; 
    +
    +-- Example of the PARTITION clause: Obtain data from the P_05_BEFORE partition in the tpcds.reason_p table.
    +postgres=# SELECT * FROM tpcds.reason_p PARTITION ( P_05_BEFORE ) ; 
    +r_reason_sk | r_reason_id | r_reason_desc
    +-------------+------------------+------------------------------------
    +4 | AAAAAAAABAAAAAAA | reason 3
    +3 | AAAAAAAABAAAAAAA | reason 1
    + ( 2 rows ) 
    +
    +-- Example of the GROUP BY clause: Group records in the tpcds.reason_p table by r_reason_id, and count the number of records in each group.
    +postgres=# SELECT COUNT ( * ) , r_reason_id FROM tpcds.reason_p GROUP BY r_reason_id ; 
    +count | r_reason_id
    +-------+------------------
    +2 | AAAAAAAACAAAAAAA
    +5 | AAAAAAAABAAAAAAA
    + ( 2 rows ) 
    +
    +-- Example of the GROUP BY CUBE clause: Filter data based on query conditions, and group the results.
    +postgres=# SELECT * FROM tpcds.reason GROUP BY CUBE ( r_reason_id , r_reason_sk , r_reason_desc ) ; 
    +
    +-- Example of the GROUP BY GROUPING SETS clause: Filter data based on query conditions, and group the results.
    +postgres=# SELECT * FROM tpcds.reason GROUP BY GROUPING SETS ( ( r_reason_id , r_reason_sk ) , r_reason_desc ) ; 
    +
    +-- Example of the HAVING clause: Group records in the tpcds.reason_p table by r_reason_id, count the number of records in each group, and display only values whose number of r_reason_id is greater than 2.
    +postgres=# SELECT COUNT ( * ) c , r_reason_id FROM tpcds.reason_p GROUP BY r_reason_id HAVING c>2 ; 
    +c | r_reason_id
    +
    +-- Example of the IN clause: Group records in the tpcds.reason_p table by r_reason_id, count the number of records in each group, and display only the numbers of records whose r_reason_id is AAAAAAAABAAAAAAA or AAAAAAAADAAAAAAA.
    +postgres=# SELECT COUNT ( * ) , r_reason_id FROM tpcds.reason_p GROUP BY r_reason_id HAVING r_reason_id IN ( ' AAAAAAAABAAAAAAA ' , ' AAAAAAAADAAAAAAA ' ) ; 
    +count | r_reason_id
    +-------+------------------
    +5 | AAAAAAAABAAAAAAA
    + ( 1 row ) 
    +
    +-- Example of the INTERSECT clause: Query records whose r_reason_id is AAAAAAAABAAAAAAA and whose r_reason_sk is smaller than 5.
    +postgres=# SELECT * FROM tpcds.reason_p WHERE r_reason_id= ' AAAAAAAABAAAAAAA ' INTERSECT SELECT * FROM tpcds.reason_p WHERE r_reason_sk<5 ; 
    +r_reason_sk | r_reason_id | r_reason_desc
    +-------------+------------------+------------------------------------
    +4 | AAAAAAAABAAAAAAA | reason 3
    +3 | AAAAAAAABAAAAAAA | reason 1
    + ( 2 rows ) 
    +
    +-- Example of the EXCEPT clause: Query records whose r_reason_id is AAAAAAAABAAAAAAA and whose r_reason_sk is greater than or equal to 4.
    +postgres=# SELECT * FROM tpcds.reason_p WHERE r_reason_id= ' AAAAAAAABAAAAAAA ' EXCEPT SELECT * FROM tpcds.reason_p WHERE r_reason_sk<4 ; 
    +r_reason_sk | r_reason_id | r_reason_desc
    +-------------+------------------+------------------------------------
    +10 | AAAAAAAABAAAAAAA | reason 2
    +10 | AAAAAAAABAAAAAAA | reason 5
    +10 | AAAAAAAABAAAAAAA | reason 4
    +4 | AAAAAAAABAAAAAAA | reason 3
    + ( 4 rows ) 
    +
    +-- Specify the operator ( + ) in the WHERE clause to indicate a left join.
    +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where t1.sr_customer_sk = t2.c_customer_sk ( + ) 
    +order by 1 desc limit 1 ; 
    +sr_item_sk | c_customer_id
    +------------+---------------
    +18000 |
    + ( 1 row ) 
    +
    +-- Specify the operator ( + ) in the WHERE clause to indicate a right join.
    +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where t1.sr_customer_sk ( + ) = t2.c_customer_sk
    +order by 1 desc limit 1 ; 
    +sr_item_sk | c_customer_id
    +------------+------------------
    +| AAAAAAAAJNGEBAAA
    + ( 1 row ) 
    +
    +-- Specify the operator ( + ) in the WHERE clause to indicate a left join and add a join condition.
    +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where t1.sr_customer_sk = t2.c_customer_sk ( + ) and t2.c_customer_sk ( + ) < 1 order by 1 limit 1 ; 
    +sr_item_sk | c_customer_id
    +------------+---------------
    +1 |
    + ( 1 row ) 
    +
    +-- If the operator ( + ) is specified in the WHERE clause, do not use expressions connected through AND/OR.
    +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where not ( t1.sr_customer_sk = t2.c_customer_sk ( + ) and t2.c_customer_sk ( + ) < 1 ) ; 
    +ERROR: Operator " ( + ) " can not be used in nesting expression.
    +LINE 1: ...tomer_id from store_returns t1 , customer t2 where not ( t1.sr_...
    +^
    +
    +-- If the operator ( + ) is specified in the WHERE clause which does not support expression macros, an error will be reported.
    +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where ( t1.sr_customer_sk = t2.c_customer_sk ( + ) ) ::bool ; 
    +ERROR: Operator " ( + ) " can only be used in common expression.
    +
    +-- If the operator ( + ) is specified on both sides of an expression in the WHERE clause, an error will be reported.
    +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where t1.sr_customer_sk ( + ) = t2.c_customer_sk ( + ) ; 
    +ERROR: Operator " ( + ) " can ' t be specified on more than one relation in one join condition
    +HINT: "t1" , "t2"...are specified Operator " ( + ) " in one condition.
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    SELECT INTO defines a new table based on a query result and inserts data obtained by query to the new table.

    +

    Different from SELECT, data found by SELECT INTO is not returned to the client. The table columns have the same names and data types as the output columns of the SELECT.

    +
    +

    Precautions 

    +

    CREATE TABLE AS provides functions similar to SELECT INTO in functions and provides a superset of functions provided by SELECT INTO. You are advised to use CREATE TABLE AS, because SELECT INTO cannot be used in a stored procedure.

    +
    +

    Examples 

    +
    -- Add the values that are less than 5 in the r_reason_sk field in the tpcds.reason table to the new table.
    +postgres=# SELECT * INTO tpcds.reason_t1 FROM tpcds.reason WHERE r_reason_sk < 5 ; 
    +INSERT 0 6
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    SET modifies a run-time parameter.

    +
    +

    Precautions 

    +

    Most run-time parameters can be modified by executing SET. Some parameters cannot be modified after a server or session starts.

    +
    +

    Examples 

    +
    -- Set the search path of a schema.
    +postgres=# SET search_path TO tpcds , public ; 
    +
    +-- Set the date style to the traditional POSTGRES style ( date placed before month ) .
    +postgres=# SET datestyle TO postgres ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    SET CONSTRAINTS sets the behavior of constraint checking within the current transaction.

    +

    IMMEDIATE constraints are checked at the end of each statement. DEFERRED constraints are not checked until transaction commit. Each constraint has its own IMMEDIATE or DEFERRED mode.

    +

    Upon creation, a constraint is given one of three characteristics DEFERRABLE INITIALLY DEFERRED, DEFERRABLE INITIALLY IMMEDIATE, or NOT DEFERRABLE. The third class is always IMMEDIATE and is not affected by the SET CONSTRAINTS statement. The first two classes start every transaction in specified modes, but its behaviors can be changed within a transaction by SET CONSTRAINTS.

    +

    SET CONSTRAINTS with a list of constraint names changes the mode of just those constraints (which must all be deferrable). If multiple constraints match a name, the name is affected by all of these constraints. SET CONSTRAINTS ALL changes the modes of all deferrable constraints.

    +

    When SET CONSTRAINTS changes the mode of a constraint from DEFERRED to IMMEDIATE, the new mode takes effect retroactively: any outstanding data modifications that would have been checked at the end of the transaction are instead checked during the execution of the SET CONSTRAINTS statement. If any such constraint is violated, the SET CONSTRAINTS fails (and does not change the constraint mode). Therefore, SET CONSTRAINTS can be used to force checking of constraints to occur at a specific point in a transaction.

    +

    Check and unique constraints are always checked immediately when a row is inserted or modified.

    +
    +

    Precautions 

    +

    SET CONSTRAINTS sets the behavior of constraint checking only within the current transaction. Therefore, if you execute this statement outside of a transaction block (START TRANSACTION/COMMIT pair), it will not appear to have any effect.

    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    SET ROLE sets the current user identifier of the current session.

    +
    +

    Precautions 

    +
    • Users of the current session must be members of specified rolename, but the system administrator can choose any roles.
    • Executing this statement may add rights of a user or restrict rights of a user. If the role of a session user has the INHERITS attribute, it automatically has all rights of roles that SET ROLE enables the role to be. In this case, SET ROLE physically deletes all rights directly granted to session users and rights of its belonging roles and only leaves rights of the specified roles. If the role of the session user has the NOINHERITS attribute, SET ROLE deletes rights directly granted to the session user and obtains rights of the specified role.
    +
    +

    Examples 

    +
    -- Set the current user to paul.
    +postgres=# SET ROLE paul PASSWORD ' Bigdata@123 ' ; 
    +
    +-- Reset the current user.
    +postgres=# RESET role ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    SET SESSION AUTHORIZATION sets the session user identifier and the current user identifier of the current SQL session to a specified user.

    +
    +

    Precautions 

    +

    The session identifier can be changed only when the initial session user has the system administrator rights. Otherwise, the system supports the statement only when the authenticated user name is specified.

    +
    +

    Examples 

    +
    -- Set the current user to paul.
    +postgres=# SET SESSION AUTHORIZATION paul password ' Bigdata@123 ' ; 
    +
    +-- Reset the current user.
    +postgres=# RESET SESSION AUTHORIZATION ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    SET TRANSACTION sets the characteristics of the current transaction. It has no effect on any subsequent transactions. Available transaction characteristics include the transaction isolation level and transaction access mode (read/write or read only).

    +
    +

    Examples 

    +
    -- Start a transaction and set its isolation level to READ COMMITTED and access mode to READ ONLY.
    +postgres=# START TRANSACTION ; 
    +postgres=# SET LOCAL TRANSACTION ISOLATION LEVEL READ COMMITTED READ ONLY ; 
    +postgres=# COMMIT ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    SHOW shows the current value of a run-time parameter.

    +
    +

    Examples 

    +
    -- Show the value of timezone.
    +postgres=# SHOW timezone ; 
    +
    +-- Show all parameters.
    +postgres=# SHOW ALL ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    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.

    +
    +

    Examples 

    +
    -- Start a transaction in default mode.
    +postgres=# START TRANSACTION ; 
    +postgres=# SELECT * FROM tpcds.reason ; 
    +postgres=# END ; 
    +
    +-- Start a transaction with the isolation level being READ COMMITTED and the access mode being READ WRITE:
    +postgres=# START TRANSACTION ISOLATION LEVEL READ COMMITTED READ WRITE ; 
    +postgres=# SELECT * FROM tpcds.reason ; 
    +postgres=# COMMIT ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    TRUNCATE quickly removes all rows from a database table.

    +

    It has the same effect as an unqualified DELETE on each table, but it is faster since it does not actually scan the tables. This is most useful on large tables.

    +
    +

    Precautions 

    +
    • TRUNCATE TABLE has the same function as a DELETE statement with no WHERE clause, emptying a table.
    • TRUNCATE TABLE uses less system and transaction log resources as compared with DELETE.
      • DELETE deletes a row each time, and records the deletion of each row in the transaction log.
      • TRUNCATE TABLE deletes all rows in a table by releasing the data page storing the table data, and records the releasing of the data page only in the transaction log.
      +
    • The differences between TRUNCATE, DELETE, and DROP are as follows:
      • TRUNCATE TABLE deletes content, releases space, but does not delete definitions.
      • DELETE TABLE deletes content, but does not delete definitions nor release space.
      • DROP TABLE deletes content and definitions, and releases space.
      +
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + +

    Function 

    +

    UPDATE updates data in a table. UPDATE changes the values of the specified columns in all rows that satisfy the condition. The WHERE clause clarifies conditions. The columns to be modified need to be mentioned in the SET clause; columns not explicitly modified retain their previous values.

    +
    +

    Precautions 

    +
    • You must have the UPDATE permission on a table to be updated.
    • You must have the SELECT permission on all tables involved in the expressions or conditions.
    • For column-store tables, the RETURNING clause is currently not supported.
    • Column-store tables do not support non-deterministic update. If you update data in one row with multiple rows of data in a column-store table, an error will be reported.
    • Memory space that records update operations in column-store tables is not reclaimed. You need to clean it by executing VACUUM FULL table_name.
    • Currently, UPDATE cannot be used in column-store replication tables.
    +
    +

    Examples 

    +
    -- Update the values of all records.
    +postgres=# UPDATE student1 SET classno = classno*2 ; 
    +
    +

    Syntax 

    + +

    Parameter Description 

    +]]>
    +
    + \ No newline at end of file diff --git a/code/datastudio/db_assistant/openGauss 1.0.0/zh/data.js b/code/datastudio/db_assistant/openGauss 1.0.0/zh/data.js new file mode 100644 index 0000000000000000000000000000000000000000..50fc79983616c0edcb85b5f6c2c8e15193a85af5 --- /dev/null +++ b/code/datastudio/db_assistant/openGauss 1.0.0/zh/data.js @@ -0,0 +1 @@ +var db={"sheet3":[{"大场景":"首次使用数据库","子场景/任务":"创建数据库用户"},{"大场景":"","子场景/任务":"创建数据库"},{"大场景":"","子场景/任务":"创建表"},{"大场景":"","子场景/任务":"利用外表访问HDFS数据"},{"大场景":"","子场景/任务":""},{"大场景":"","子场景/任务":""},{"大场景":"","子场景/任务":""},{"大场景":"","子场景/任务":""},{"大场景":"","子场景/任务":""},{"大场景":"","子场景/任务":""},{"大场景":"","子场景/任务":""},{"大场景":"","子场景/任务":""}],"sheet1":[{"备注":"","分类维度":"功能大类","分类名称":"数据增删改查"},{"备注":"","分类维度":"功能大类","分类名称":"表增删改"},{"备注":"","分类维度":"功能大类","分类名称":"表空间增删改"},{"备注":"","分类维度":"功能大类","分类名称":"数据库增删改"},{"备注":"","分类维度":"功能大类","分类名称":"索引"},{"备注":"","分类维度":"功能大类","分类名称":"视图"},{"备注":"","分类维度":"功能大类","分类名称":"用户组"},{"备注":"","分类维度":"功能大类","分类名称":"事务"},{"备注":"","分类维度":"功能大类","分类名称":"数据库用户角色"},{"备注":"","分类维度":"功能大类","分类名称":"权限管理"},{"备注":"","分类维度":"功能大类","分类名称":"函数"},{"备注":"","分类维度":"功能大类","分类名称":"负载组"},{"备注":"","分类维度":"功能大类","分类名称":"资源池"},{"备注":"","分类维度":"功能大类","分类名称":"游标"},{"备注":"","分类维度":"功能大类","分类名称":"存储过程"},{"备注":"","分类维度":"功能大类","分类名称":"序列"},{"备注":"","分类维度":"功能大类","分类名称":"数据统计"},{"备注":"","分类维度":"功能大类","分类名称":"模式"},{"备注":"","分类维度":"功能大类","分类名称":"节点"},{"备注":"","分类维度":"功能大类","分类名称":"其他"},{"备注":"其对应页面手动编写,非自动生成。其包括的内容见“非自动生成页面”页签。","分类维度":"大场景","分类名称":"首次使用数据库"},{"备注":"","分类维度":"大场景","分类名称":"数据处理"},{"备注":"","分类维度":"大场景","分类名称":"创建和应用数据库"},{"备注":"","分类维度":"大场景","分类名称":"创建和应用序列"},{"备注":"","分类维度":"大场景","分类名称":"创建和应用索引"},{"备注":"","分类维度":"大场景","分类名称":"创建和应用视图"},{"备注":"","分类维度":"大场景","分类名称":"数据库用户角色管理"},{"备注":"","分类维度":"大场景","分类名称":"数据库权限管理"},{"备注":"","分类维度":"大场景","分类名称":"跨集群协同分析"},{"备注":"","分类维度":"大场景","分类名称":"数据库维护"},{"备注":"","分类维度":"大场景","分类名称":"性能调优"},{"备注":"","分类维度":"大场景","分类名称":"资源负载管理"},{"备注":"","分类维度":"大场景","分类名称":"安全管理"},{"备注":"","分类维度":"大场景","分类名称":"导入导出数据"},{"备注":"","分类维度":"大场景","分类名称":"弹性伸缩管理"},{"备注":"","分类维度":"操作类别","分类名称":"创建"},{"备注":"","分类维度":"操作类别","分类名称":"修改"},{"备注":"","分类维度":"操作类别","分类名称":"查询"},{"备注":"","分类维度":"操作类别","分类名称":"删除"},{"备注":"","分类维度":"操作类别","分类名称":"设置"},{"备注":"","分类维度":"操作类别","分类名称":"恢复"},{"备注":"","分类维度":"操作类别","分类名称":"回滚"},{"备注":"","分类维度":"操作类别","分类名称":"排序"},{"备注":"","分类维度":"操作类别","分类名称":"复制"},{"备注":"","分类维度":"操作类别","分类名称":"取消"},{"备注":"","分类维度":"操作类别","分类名称":"重置"}],"sheet2":[{"操作命令":"CREATE RESOURCE POOL","操作类别3":"","子场景":"","操作类别2":"","大场景":"资源负载管理","操作类别1":"创建","功能子类":"","备注":"","功能大类":"资源池","任务名称":"创建资源池"},{"操作命令":"ALTER RESOURCE POOL","操作类别3":"","子场景":"","操作类别2":"","大场景":"资源负载管理","操作类别1":"修改","功能子类":"","备注":"","功能大类":"资源池","任务名称":"修改资源池属性"},{"操作命令":"DROP RESOURCE POOL","操作类别3":"","子场景":"","操作类别2":"","大场景":"资源负载管理","操作类别1":"删除","功能子类":"","备注":"","功能大类":"资源池","任务名称":"删除资源池"},{"操作命令":"CLOSE","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"游标","任务名称":"关闭游标"},{"操作命令":"CURSOR","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"创建","功能子类":"","备注":"","功能大类":"游标","任务名称":"创建游标"},{"操作命令":"DECLARE","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"游标","任务名称":"定义游标"},{"操作命令":"FETCH","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据处理","操作类别1":"","功能子类":"","备注":"待确认","功能大类":"游标","任务名称":"从游标中提取数据"},{"操作命令":"MOVE","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"游标","任务名称":"移动游标"},{"操作命令":"CREATE GROUP","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据库权限管理","操作类别1":"创建","功能子类":"","备注":"","功能大类":"用户组","任务名称":"创建用户组"},{"操作命令":"ALTER GROUP","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据库权限管理","操作类别1":"修改","功能子类":"","备注":"","功能大类":"用户组","任务名称":"修改用户组属性"},{"操作命令":"DROP GROUP","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据库权限管理","操作类别1":"删除","功能子类":"","备注":"","功能大类":"用户组","任务名称":"删除用户组"},{"操作命令":"CREATE SEQUENCE","操作类别3":"","子场景":"","操作类别2":"","大场景":"创建和应用序列","操作类别1":"创建","功能子类":"","备注":"","功能大类":"序列","任务名称":"创建序列"},{"操作命令":"ALTER SEQUENCE","操作类别3":"","子场景":"","操作类别2":"","大场景":"创建和应用序列","操作类别1":"修改","功能子类":"","备注":"","功能大类":"序列","任务名称":"修改序列"},{"操作命令":"DROP SEQUENCE","操作类别3":"","子场景":"","操作类别2":"","大场景":"创建和应用序列","操作类别1":"删除","功能子类":"","备注":"","功能大类":"序列","任务名称":"删除序列"},{"操作命令":"CREATE INDEX","操作类别3":"","子场景":"","操作类别2":"","大场景":"创建和应用索引","操作类别1":"创建","功能子类":"","备注":"","功能大类":"索引","任务名称":"创建索引"},{"操作命令":"ALTER INDEX","操作类别3":"","子场景":"","操作类别2":"","大场景":"创建和应用索引","操作类别1":"修改","功能子类":"","备注":"","功能大类":"索引","任务名称":"修改索引属性"},{"操作命令":"CLUSTER","操作类别3":"","子场景":"","操作类别2":"","大场景":"创建和应用索引","操作类别1":"排序","功能子类":"","备注":"待确认","功能大类":"索引","任务名称":"聚簇排序"},{"操作命令":"DROP INDEX","操作类别3":"","子场景":"","操作类别2":"","大场景":"创建和应用索引","操作类别1":"删除","功能子类":"","备注":"","功能大类":"索引","任务名称":"删除索引"},{"操作命令":"REINDEX","操作类别3":"","子场景":"","操作类别2":"","大场景":"创建和应用索引","操作类别1":"","功能子类":"","备注":"","功能大类":"索引","任务名称":"重建索引"},{"操作命令":"DELETE","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据处理","操作类别1":"删除","功能子类":"","备注":"需在资料中说明,Delete删除后有日志,truncate删除后无日志。","功能大类":"数据增删改查","任务名称":"删除数据"},{"操作命令":"SELECT","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据处理","操作类别1":"查询","功能子类":"","备注":"","功能大类":"数据增删改查","任务名称":"查询数据"},{"操作命令":"SELECT INTO","操作类别3":"","子场景":"","操作类别2":"增加","大场景":"数据处理","操作类别1":"查询","功能子类":"","备注":"","功能大类":"数据增删改查","任务名称":"查询数据并添加到新表"},{"操作命令":"ANALYSE","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据处理","操作类别1":"","功能子类":"","备注":"","功能大类":"数据统计","任务名称":"搜集统计信息"},{"操作命令":"ANALYZE","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据处理","操作类别1":"","功能子类":"","备注":"","功能大类":"数据统计","任务名称":"搜集统计信息"},{"操作命令":"CREATE DATABASE","操作类别3":"","子场景":"","操作类别2":"","大场景":"首次使用数据库","操作类别1":"创建","功能子类":"","备注":"","功能大类":"数据库增删改","任务名称":"创建数据库"},{"操作命令":"ALTER DATABASE","操作类别3":"","子场景":"","操作类别2":"","大场景":"创建和应用数据库","操作类别1":"修改","功能子类":"","备注":"","功能大类":"数据库增删改","任务名称":"修改数据库属性"},{"操作命令":"DROP DATABASE","操作类别3":"","子场景":"","操作类别2":"","大场景":"创建和应用数据库","操作类别1":"删除","功能子类":"","备注":"","功能大类":"数据库增删改","任务名称":"删除数据库"},{"操作命令":"ALTER ROLE","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据库用户角色管理","操作类别1":"修改","功能子类":"","备注":"","功能大类":"数据库用户角色","任务名称":"修改角色属性"},{"操作命令":"ALTER USER","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据库用户角色管理","操作类别1":"修改","功能子类":"","备注":"","功能大类":"数据库用户角色","任务名称":"修改用户属性"},{"操作命令":"CREATE ROLE","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据库用户角色管理","操作类别1":"创建","功能子类":"","备注":"","功能大类":"数据库用户角色","任务名称":"创建角色"},{"操作命令":"CREATE USER","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据库用户角色管理","操作类别1":"创建","功能子类":"","备注":"","功能大类":"数据库用户角色","任务名称":"创建用户"},{"操作命令":"DROP ROLE","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据库用户角色管理","操作类别1":"删除","功能子类":"","备注":"","功能大类":"数据库用户角色","任务名称":"删除角色"},{"操作命令":"DROP USER","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据库用户角色管理","操作类别1":"删除","功能子类":"","备注":"","功能大类":"数据库用户角色","任务名称":"删除用户"},{"操作命令":"SET ROLE","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据库用户角色管理","操作类别1":"设置","功能子类":"","备注":"","功能大类":"数据库用户角色","任务名称":"设置当前用户角色"},{"操作命令":"SET SESSION AUTHORIZATION","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据库用户角色管理","操作类别1":"重置","功能子类":"","备注":"待确认","功能大类":"数据库用户角色","任务名称":"重置当前用户"},{"操作命令":"REASSIGN OWNED","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据库用户角色管理","操作类别1":"修改","功能子类":"","备注":"","功能大类":"数据库用户角色","任务名称":"修改数据库对象属主"},{"操作命令":"DROP OWNED","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据库用户角色管理","操作类别1":"删除","功能子类":"","备注":"待确认","功能大类":"数据库用户角色","任务名称":"删除角色所拥有的数据库对象"},{"操作命令":"CREATE VIEW","操作类别3":"","子场景":"","操作类别2":"","大场景":"创建和应用视图","操作类别1":"创建","功能子类":"","备注":"","功能大类":"视图","任务名称":"创建视图"},{"操作命令":"ALTER VIEW","操作类别3":"","子场景":"","操作类别2":"","大场景":"创建和应用视图","操作类别1":"修改","功能子类":"","备注":"","功能大类":"视图","任务名称":"修改视图"},{"操作命令":"BEGIN…END","操作类别3":"","子场景":"","操作类别2":"","大场景":"创建和应用视图","操作类别1":"","功能子类":"","备注":"","功能大类":"视图","任务名称":"标记符"},{"操作命令":"DROP VIEW","操作类别3":"","子场景":"","操作类别2":"","大场景":"创建和应用视图","操作类别1":"删除","功能子类":"","备注":"","功能大类":"视图","任务名称":"删除视图"},{"操作命令":"START TRANSACTION","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"事务","任务名称":"启动事务"},{"操作命令":"PREPARE TRANSACTION","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"待确认","功能大类":"事务","任务名称":"事务提交准备"},{"操作命令":"ABORT","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"取消","功能子类":"","备注":"","功能大类":"事务","任务名称":"回滚事务"},{"操作命令":"BEGIN…END","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"事务","任务名称":"标记符"},{"操作命令":"COMMIT","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"事务","任务名称":"提交事务"},{"操作命令":"COMMIT PREPARED","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"待确认","功能大类":"事务","任务名称":"提交预备事务"},{"操作命令":"ROLLBACK","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"回滚","功能子类":"","备注":"","功能大类":"事务","任务名称":"回滚事务"},{"操作命令":"ROLLBACK PREPARED","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"回滚","功能子类":"","备注":"待确认","功能大类":"事务","任务名称":"回滚预备事务"},{"操作命令":"SET TRANSACTION","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"设置","功能子类":"","备注":"","功能大类":"事务","任务名称":"设置当前事务特性"},{"操作命令":"ALTER DEFAULT PRIVILEGES","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据库权限管理","操作类别1":"修改","功能子类":"","备注":"","功能大类":"权限管理","任务名称":"修改默认权限"},{"操作命令":"GRANT","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据库权限管理","操作类别1":"","功能子类":"","备注":"","功能大类":"权限管理","任务名称":"授权"},{"操作命令":"REVOKE","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据库权限管理","操作类别1":"","功能子类":"","备注":"","功能大类":"权限管理","任务名称":"收回授权"},{"操作命令":"ALTER DATA SOURCE","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"修改","功能子类":"","备注":"","功能大类":"其他","任务名称":"修改数据源属性"},{"操作命令":"ALTER EXTENSION","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"修改","功能子类":"","备注":"","功能大类":"其他","任务名称":"修改扩展对象属性"},{"操作命令":"ALTER LARGE OBJECT","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"修改","功能子类":"","备注":"待确认","功能大类":"其他","任务名称":"修改大对象所有者"},{"操作命令":"ALTER SERVER","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"修改","功能子类":"","备注":"","功能大类":"其他","任务名称":"修改Server属性"},{"操作命令":"ALTER TEXT SEARCH CONFIGURATION","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"修改","功能子类":"","备注":"","功能大类":"其他","任务名称":"更改文本搜索配置"},{"操作命令":"CHECKPOINT","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据库维护","操作类别1":"设置","功能子类":"","备注":"","功能大类":"其他","任务名称":"设置检查点"},{"操作命令":"CLEAN CONNECTION","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据库维护","操作类别1":"","功能子类":"","备注":"","功能大类":"其他","任务名称":"清理数据库连接"},{"操作命令":"COMMENT","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"其他","任务名称":"注释"},{"操作命令":"COPY","操作类别3":"","子场景":"","操作类别2":"","大场景":"导入导出数据","操作类别1":"复制","功能子类":"","备注":"","功能大类":"其他","任务名称":"拷贝数据"},{"操作命令":"CREATE APP WORKLOAD GROUP MAPPING","操作类别3":"","子场景":"","操作类别2":"","大场景":"资源负载管理","操作类别1":"创建","功能子类":"","备注":"","功能大类":"其他","任务名称":"创建应用映射组"},{"操作命令":"CREATE BARRIER","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"创建","功能子类":"","备注":"","功能大类":"其他","任务名称":"创建同步点"},{"操作命令":"CREATE DATA SOURCE","操作类别3":"","子场景":"","操作类别2":"","大场景":"跨集群协同分析","操作类别1":"创建","功能子类":"","备注":"","功能大类":"其他","任务名称":"创建数据源"},{"操作命令":"CREATE EXTENSION","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"创建","功能子类":"","备注":"","功能大类":"其他","任务名称":"创建扩展对象"},{"操作命令":"CREATE SERVER","操作类别3":"","子场景":"","操作类别2":"","大场景":"跨集群协同分析","操作类别1":"创建","功能子类":"","备注":"","功能大类":"其他","任务名称":"创建Server"},{"操作命令":"DEALLOCATE","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"删除","功能子类":"","备注":"待确认","功能大类":"其他","任务名称":"删除预备语句"},{"操作命令":"DO","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"执行","功能子类":"","备注":"","功能大类":"其他","任务名称":"执行代码块"},{"操作命令":"DROP APP WORKLOAD GROUP MAPPING","操作类别3":"","子场景":"","操作类别2":"","大场景":"资源负载管理","操作类别1":"删除","功能子类":"","备注":"","功能大类":"其他","任务名称":"删除应用映射组"},{"操作命令":"DROP DATA SOURCE","操作类别3":"","子场景":"","操作类别2":"","大场景":"跨集群协同分析","操作类别1":"删除","功能子类":"","备注":"","功能大类":"其他","任务名称":"删除数据源"},{"操作命令":"DROP EXTENSION","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"删除","功能子类":"","备注":"","功能大类":"其他","任务名称":"删除扩展对象"},{"操作命令":"DROP SERVER","操作类别3":"","子场景":"","操作类别2":"","大场景":"跨集群协同分析","操作类别1":"删除","功能子类":"","备注":"","功能大类":"其他","任务名称":"删除数据服务器"},{"操作命令":"DROP TEXT SEARCH CONFIGURATION","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"删除","功能子类":"","备注":"","功能大类":"其他","任务名称":"删除文本搜索配置"},{"操作命令":"EXECUTE","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"执行","功能子类":"","备注":"","功能大类":"其他","任务名称":"执行预备语句"},{"操作命令":"EXECUTE DIRECT","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"待确认","功能大类":"其他","任务名称":"在指定的节点上执行SQL语句"},{"操作命令":"EXPLAIN","操作类别3":"","子场景":"","操作类别2":"","大场景":"性能调优","操作类别1":"","功能子类":"","备注":"待确认","功能大类":"其他","任务名称":"显示执行计划"},{"操作命令":"PREPARE","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"创建","功能子类":"","备注":"","功能大类":"其他","任务名称":"创建预备语句"},{"操作命令":"RELEASE SAVEPOINT","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"删除","功能子类":"","备注":"","功能大类":"其他","任务名称":"删除保存点"},{"操作命令":"RESET","操作类别3":"","子场景":"","操作类别2":"","大场景":"数据处理","操作类别1":"恢复","功能子类":"","备注":"","功能大类":"其他","任务名称":"恢复缺省值"},{"操作命令":"ROLLBACK TO SAVEPOINT","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"回滚","功能子类":"","备注":"","功能大类":"其他","任务名称":"回滚到保存点"},{"操作命令":"SAVEPOINT","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"创建","功能子类":"","备注":"","功能大类":"其他","任务名称":"建立保存点"},{"操作命令":"SET CONSTRAINTS","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"设置","功能子类":"","备注":"","功能大类":"其他","任务名称":"设置约束条件"},{"操作命令":"SHOW","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"查询","功能子类":"","备注":"","功能大类":"其他","任务名称":"显示参数值"},{"操作命令":"CREATE SCHEMA","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"创建","功能子类":"","备注":"","功能大类":"模式","任务名称":"创建模式"},{"操作命令":"ALTER SCHEMA","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"修改","功能子类":"","备注":"","功能大类":"模式","任务名称":"修改模式属性"},{"操作命令":"DROP SCHEMA","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"删除","功能子类":"","备注":"","功能大类":"模式","任务名称":"删除模式"},{"操作命令":"ALTER NODE","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"修改","功能子类":"","备注":"","功能大类":"节点","任务名称":"修改节点"},{"操作命令":"CREATE NODE","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"创建","功能子类":"","备注":"","功能大类":"节点","任务名称":"创建节点"},{"操作命令":"CREATE NODE GROUP","操作类别3":"","子场景":"","操作类别2":"","大场景":"弹性伸缩管理","操作类别1":"创建","功能子类":"","备注":"","功能大类":"节点","任务名称":"创建节点组"},{"操作命令":"DROP NODE","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"删除","功能子类":"","备注":"","功能大类":"节点","任务名称":"删除节点"},{"操作命令":"DROP NODE GROUP","操作类别3":"","子场景":"","操作类别2":"","大场景":"弹性伸缩管理","操作类别1":"删除","功能子类":"","备注":"","功能大类":"节点","任务名称":"删除节点组"},{"操作命令":"ALTER SESSION","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"修改","功能子类":"","备注":"","功能大类":"会话","任务名称":"修改会话"},{"操作命令":"ALTER SYSTEM KILL SESSION","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"修改","功能子类":"","备注":"","功能大类":"会话","任务名称":"结束会话"},{"操作命令":"CREATE FUNCTION","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"创建","功能子类":"","备注":"","功能大类":"函数","任务名称":"创建函数"},{"操作命令":"ALTER FUNCTION","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"修改","功能子类":"","备注":"","功能大类":"函数","任务名称":"修改函数属性"},{"操作命令":"CALL","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"执行","功能子类":"","备注":"","功能大类":"函数","任务名称":"调用函数"},{"操作命令":"DROP FUNCTION","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"删除","功能子类":"","备注":"","功能大类":"函数","任务名称":"删除函数"},{"操作命令":"CREATE WORKLOAD GROUP","操作类别3":"","子场景":"","操作类别2":"","大场景":"资源负载管理","操作类别1":"创建","功能子类":"","备注":"","功能大类":"负载组","任务名称":"创建负载组"},{"操作命令":"ALTER APP WORKLOAD GROUP MAPPING","操作类别3":"","子场景":"","操作类别2":"","大场景":"资源负载管理","操作类别1":"修改","功能子类":"","备注":"","功能大类":"负载组","任务名称":"修改应用关联的负载组"},{"操作命令":"ALTER WORKLOAD GROUP","操作类别3":"","子场景":"","操作类别2":"","大场景":"资源负载管理","操作类别1":"修改","功能子类":"","备注":"","功能大类":"负载组","任务名称":"修改负载组属性"},{"操作命令":"DROP WORKLOAD GROUP","操作类别3":"","子场景":"","操作类别2":"","大场景":"资源负载管理","操作类别1":"删除","功能子类":"","备注":"","功能大类":"负载组","任务名称":"删除负载组"},{"操作命令":"CREATE PROCEDURE","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"创建","功能子类":"","备注":"","功能大类":"存储过程","任务名称":"创建存储过程"},{"操作命令":"DROP PROCEDURE","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"删除","功能子类":"","备注":"","功能大类":"存储过程","任务名称":"删除存储过程"},{"操作命令":"ALTER FOREIGN TABLE (FOR GDS)","操作类别3":"","子场景":"","操作类别2":"","大场景":"导入导出数据","操作类别1":"修改","功能子类":"外表","备注":"","功能大类":"表增删改","任务名称":"修改外表"},{"操作命令":"ALTER FOREIGN TABLE (FOR HDFS)","操作类别3":"","子场景":"","操作类别2":"","大场景":"跨集群协同分析","操作类别1":"修改","功能子类":"外表","备注":"","功能大类":"表增删改","任务名称":"修改外表"},{"操作命令":"ALTER TABLE","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"修改","功能子类":"普通表增删改","备注":"","功能大类":"表增删改","任务名称":"修改表属性"},{"操作命令":"ALTER TABLE PARTITION","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"修改","功能子类":"分区表增删改","备注":"","功能大类":"表增删改","任务名称":"修改分区表属性"},{"操作命令":"CREATE FOREIGN TABLE (FOR GDS)","操作类别3":"","子场景":"","操作类别2":"","大场景":"导入导出数据","操作类别1":"创建","功能子类":"外表","备注":"","功能大类":"表增删改","任务名称":"创建外表"},{"操作命令":"CREATE FOREIGN TABLE (FOR HDFS)","操作类别3":"","子场景":"","操作类别2":"","大场景":"跨集群协同分析","操作类别1":"创建","功能子类":"外表","备注":"","功能大类":"表增删改","任务名称":"创建外表"},{"操作命令":"CREATE TABLE","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"创建","功能子类":"普通表增删改","备注":"","功能大类":"表增删改","任务名称":"创建表"},{"操作命令":"CREATE TABLE AS","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"创建","功能子类":"普通表增删改","备注":"","功能大类":"表增删改","任务名称":"快速创建表"},{"操作命令":"CREATE TABLE PARTITION","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"创建","功能子类":"分区表增删改","备注":"","功能大类":"表增删改","任务名称":"创建分区表"},{"操作命令":"DROP FOREIGN TABLE","操作类别3":"","子场景":"","操作类别2":"","大场景":"导入导出数据","操作类别1":"删除","功能子类":"外表","备注":"","功能大类":"表增删改","任务名称":"删除外表"},{"操作命令":"DROP FOREIGN TABLE","操作类别3":"","子场景":"","操作类别2":"","大场景":"跨集群协同分析","操作类别1":"删除","功能子类":"外表","备注":"","功能大类":"表增删改","任务名称":"删除外表"},{"操作命令":"DROP TABLE","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"删除","功能子类":"普通表增删改","备注":"","功能大类":"表增删改","任务名称":"删除表"},{"操作命令":"INSERT","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"数据增删改查","任务名称":"插入数据"},{"操作命令":"TRUNCATE","操作类别3":"","子场景":"数据处理","操作类别2":"","大场景":"","操作类别1":"删除","功能子类":"普通表增删改","备注":"需在资料中说明,Delete删除后有日志,truncate删除后无日志。","功能大类":"表增删改","任务名称":"删除数据"},{"操作命令":"UPDATE","操作类别3":"","子场景":"数据处理","操作类别2":"","大场景":"","操作类别1":"修改","功能子类":"","备注":"","功能大类":"数据增删改查","任务名称":"更新数据"},{"操作命令":"LOCK","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"普通表增删改","备注":"待确认","功能大类":"表增删改","任务名称":"锁定表"},{"操作命令":"CREATE TABLESPACE","操作类别3":"","子场景":"","操作类别2":"","大场景":"创建和应用表空间","操作类别1":"创建","功能子类":"","备注":"","功能大类":"表空间增删改","任务名称":"创建表空间"},{"操作命令":"ALTER TABLESPACE","操作类别3":"","子场景":"","操作类别2":"","大场景":"创建和应用表空间","操作类别1":"修改","功能子类":"","备注":"","功能大类":"表空间增删改","任务名称":"修改表空间属性"},{"操作命令":"CREATE TEXT SEARCH CONFIGURATION","操作类别3":"","子场景":"","操作类别2":"","大场景":"创建和应用表空间","操作类别1":"创建","功能子类":"","备注":"","功能大类":"表空间增删改","任务名称":"创建文本搜索配置"},{"操作命令":"DROP TABLESPACE","操作类别3":"","子场景":"","操作类别2":"","大场景":"创建和应用表空间","操作类别1":"删除","功能子类":"","备注":"","功能大类":"表空间增删改","任务名称":"删除表空间"},{"操作命令":"VACUUM","操作类别3":"","子场景":"性能优化","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":"回收存储空间"},{"操作命令":"SET","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"修改","功能子类":"","备注":"待确认","功能大类":"","任务名称":"修改配置参数"},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""},{"操作命令":"","操作类别3":"","子场景":"","操作类别2":"","大场景":"","操作类别1":"","功能子类":"","备注":"","功能大类":"","任务名称":""}]} \ No newline at end of file diff --git a/code/datastudio/db_assistant/openGauss 1.0.0/zh/errorcode.xml b/code/datastudio/db_assistant/openGauss 1.0.0/zh/errorcode.xml new file mode 100644 index 0000000000000000000000000000000000000000..9e60313e72f0d5738845ce45ea81d2a891b7fb15 --- /dev/null +++ b/code/datastudio/db_assistant/openGauss 1.0.0/zh/errorcode.xml @@ -0,0 +1,28969 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  • 退出当前session,再重新连接并创建临时表
  • 使用DROP SCHEMA %s, %s CASCADE来删除临时schema,再重建临时表。
  • ]]>
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  • 查看当前relation的统计信息模式。
  • 查看guc参数enable_global_stats的类型。
  • 在当前guc参数模式下对relation进行analyze后再执行query。
  • ]]>
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  • 如果是主动调用访问不存在的事务的状态,无须处理。
  • 如果是gs_clean报出来的,可能是事务在某个节点未参与,无须处理。
  • 如果是一个正常的事务,节点也参与,请联系华为技术支持工程师提供技术支持。
  • ]]>
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    \ No newline at end of file diff --git a/code/datastudio/db_assistant/openGauss 1.0.0/zh/gramma/public_sys-resources/caution_3.0-zh-cn.png b/code/datastudio/db_assistant/openGauss 1.0.0/zh/gramma/public_sys-resources/caution_3.0-zh-cn.png new file mode 100644 index 0000000000000000000000000000000000000000..d245d48dc07e2b01734e21ec1952e89fa9269bdb Binary files /dev/null and b/code/datastudio/db_assistant/openGauss 1.0.0/zh/gramma/public_sys-resources/caution_3.0-zh-cn.png differ diff --git a/code/datastudio/db_assistant/openGauss 1.0.0/zh/gramma/public_sys-resources/note_3.0-zh-cn.png b/code/datastudio/db_assistant/openGauss 1.0.0/zh/gramma/public_sys-resources/note_3.0-zh-cn.png new file mode 100644 index 0000000000000000000000000000000000000000..a32856aa08e459ed0f51f8fcf4c2f51511c12095 Binary files /dev/null and b/code/datastudio/db_assistant/openGauss 1.0.0/zh/gramma/public_sys-resources/note_3.0-zh-cn.png differ diff --git a/code/datastudio/db_assistant/openGauss 1.0.0/zh/gramma/public_sys-resources/notice_3.0-zh-cn.png b/code/datastudio/db_assistant/openGauss 1.0.0/zh/gramma/public_sys-resources/notice_3.0-zh-cn.png new file mode 100644 index 0000000000000000000000000000000000000000..f4d46d9dbb5402adfa07bdc2eb6c1298013c1732 Binary files /dev/null and b/code/datastudio/db_assistant/openGauss 1.0.0/zh/gramma/public_sys-resources/notice_3.0-zh-cn.png differ diff --git a/code/datastudio/db_assistant/openGauss 1.0.0/zh/suggestion.xml b/code/datastudio/db_assistant/openGauss 1.0.0/zh/suggestion.xml new file mode 100644 index 0000000000000000000000000000000000000000..4d31c9cbb55d806fbd888d732558a9ae346c56cd --- /dev/null +++ b/code/datastudio/db_assistant/openGauss 1.0.0/zh/suggestion.xml @@ -0,0 +1,8271 @@ + + + +

    功能描述 

    +

    修改数据库的属性,包括它的名称、所有者、连接数限制、对象隔离属性等。

    +
    +

    注意事项 

    +
    • 只有拥有数据库所有者权限的用户才能执行ALTER DATABASE命令,系统管理员默认拥有此权限。如果是非系统管理员,针对所要修改属性的不同,对其还有以下权限约束:
      • 修改数据库名称,必须拥有CREATEDB权限。
      • 修改数据库所有者,当前用户必须是该database的所有者,必须拥有CREATEDB权限,且该用户是新所有者角色的成员。
      • 修改数据库默认表空间,该用户必须是该database的所有者或系统管理员,必须拥有新表空间的CREATE权限。这个语句会从物理上将一个数据库原来缺省表空间上的表和索引移至新的表空间。注意不在缺省表空间的表和索引不受此影响。
      • 修改某个按数据库设置的相关参数,只有数据库所有者或者系统管理员可以改变这些设置。
      • 修改某个数据库对象隔离属性,只有数据库所有者或者系统管理员可以执行此操作。
      +
    • 不能重命名当前使用的数据库,如果需要重新命名,须连接至其他数据库上。
    +
    +

    示例 

    +
    --设置music数据库的连接数为10。
    +postgres=# ALTER DATABASE music CONNECTION LIMIT= 10 ; 
    +
    +--将music名称改为music4。
    +postgres=# ALTER DATABASE music RENAME TO music4 ; 
    +
    +--将数据库music2的所属者改为tom。
    +postgres=# ALTER DATABASE music2 OWNER TO tom ; 
    +
    +--设置music3的表空间为PG_DEFAULT。
    +postgres=# ALTER DATABASE music3 SET TABLESPACE PG_DEFAULT ; 
    +
    +--关闭在数据库music3上缺省的索引扫描。
    +postgres=# ALTER DATABASE music3 SET enable_indexscan TO off ; 
    +
    +--重置enable_indexscan参数。
    +postgres=# ALTER DATABASE music3 RESET enable_indexscan ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    修改Data Source对象的属性和内容。

    +

    属性有:名称和属主;内容有:类型、版本和连接选项。

    +
    +

    示例 

    +
    --修改名称。
    +postgres=# ALTER DATA SOURCE ds_test1 RENAME TO ds_test;
    +
    +--修改属主。
    +postgres=# CREATE USER user_test1 IDENTIFIED BY ' Gs@123456 ' ; 
    +postgres=# ALTER USER user_test1 WITH SYSADMIN ; 
    +postgres=# ALTER DATA SOURCE ds_test OWNER TO user_test1 ; 
    +
    +--修改TYPE和VERSION。
    +postgres=# ALTER DATA SOURCE ds_test TYPE ' MPPDB_TYPE ' VERSION ' XXX ' ; 
    +
    +--添加字段。
    +postgres=# ALTER DATA SOURCE ds_test OPTIONS ( add dsn ' gaussdb ' , username ' test_user ' ) ; 
    +
    +--修改字段。
    +postgres=# ALTER DATA SOURCE ds_test OPTIONS ( set dsn ' unknown ' ) ; 
    +
    +--删除字段。
    +postgres=# ALTER DATA SOURCE ds_test OPTIONS ( drop username ) ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    设置应用于将来创建的对象的权限(这不会影响分配到已有对象中的权限)。

    +
    +

    注意事项 

    +

    目前只支持表(包括视图)、 函数和类型(包括域)的权限更改。

    +
    +

    示例 

    +
    --将创建在模式tpcds里的所有表(和视图)的SELECT权限授予每一个用户。
    +postgres=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds GRANT SELECT ON TABLES TO PUBLIC ; 
    +
    +--将tpcds下的所有表的插入权限授予用户jack。
    +postgres=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds GRANT INSERT ON TABLES TO jack ; 
    +
    +--撤销上述权限。
    +postgres=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds REVOKE SELECT ON TABLES FROM PUBLIC ; 
    +postgres=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds REVOKE INSERT ON TABLES FROM jack ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    对directory属性进行修改。

    +
    +

    注意事项 

    +
    • 目前只支持修改directory属主。
    • 属主仅允许是sysadmin权限用户,不允许赋予普通用户。
    +
    +

    示例 

    +
    --修改目录的owner。
    +postgres=# ALTER DIRECTORY dir OWNER TO system ; 
    +
    +

    语法格式 

    +]]>
    +
    + +

    功能描述 

    +

    修改自定义函数的属性。

    +
    +

    注意事项 

    +

    只有该函数的所有者,才有权限执行该命令,系统管理员默认拥有该权限。如果函数中涉及对临时表相关的操作,则无法使用ALTER FUNCTION。

    +
    +

    示例 

    +
    --修改函数add的执行规则为IMMUTABLE,即参数不变时返回相同结果。
    +postgres=# ALTER FUNCTION func_add_sql2 ( INTEGER , INTEGER ) IMMUTABLE ; 
    +
    +--将函数add的名称修改为add_two_number。
    +postgres=# ALTER FUNCTION func_add_sql2 ( INTEGER , INTEGER ) RENAME TO add_two_number ; 
    +
    +--将函数add的属者改为omm。
    +postgres=# ALTER FUNCTION add_two_number ( INTEGER , INTEGER ) OWNER TO omm ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    修改一个用户组的属性。

    +
    +

    注意事项 

    +

    ALTER GROUP是ALTER ROLE的别名,非SQL标准语法,不推荐使用,建议用户直接使用ALTER ROLE替代。

    +
    +

    示例 

    +
    --向用户组中添加用户。
    +postgres=# ALTER GROUP super_users ADD USER lche , jim ; 
    +
    +--从用户组中删除用户。
    +postgres=# ALTER GROUP super_users DROP USER jim ; 
    +
    +--修改用户组的名称。
    +postgres=# ALTER GROUP super_users RENAME TO normal_users ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    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

      用于设置表或者索引分区上的索引不可用。

      +
    • REBUILD [ PARTITION index_partition_name ]

      用于重建表或者索引分区上的索引。

      +
    • RENAME PARTITION

      用于重命名索引分区

      +
    • MOVE PARTITION

      用于修改索引分区的所属表空间。

      +
    +
    +

    注意事项 

    +

    只有索引的所有者有权限执行此命令,系统管理员默认拥有此权限。

    +
    +

    示例 

    +
    --重命名一个现有的索引。
    +postgres=# ALTER INDEX tpcds.ds_ship_mode_t1_index1 RENAME TO ds_ship_mode_t1_index5 ; 
    +
    +--设置索引不可用。
    +postgres=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 UNUSABLE ; 
    +
    +--重建索引。
    +postgres=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 REBUILD ; 
    +
    +--修改分区表索引CA_ADDRESS_SK_index2的表空间为example1。
    +postgres=# ALTER INDEX tpcds.ds_customer_address_p1_index2 MOVE PARTITION CA_ADDRESS_SK_index2 TABLESPACE example1 ; 
    +
    +--修改分区表索引CA_ADDRESS_SK_index3的表空间为example2。
    +postgres=# ALTER INDEX tpcds.ds_customer_address_p1_index2 MOVE PARTITION CA_ADDRESS_SK_index3 TABLESPACE example2 ; 
    +
    +--重命名分区表索引。
    +postgres=# ALTER INDEX tpcds.ds_customer_address_p1_index2 RENAME PARTITION CA_ADDRESS_SK_index1 TO CA_ADDRESS_SK_index4 ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    ALTER LARGE OBJECT用于更改一个large object的定义。它的唯一的功能是分配一个新的所有者。

    +
    +

    注意事项 

    +

    使用ALTER LARGE OBJECT必须是系统管理员或者是其所有者。

    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    修改角色属性。

    +
    +

    示例 

    +
    --修改角色manager的密码为abcd@123。
    +postgres=# ALTER ROLE manager IDENTIFIED BY ' abcd@123 ' REPLACE ' Bigdata@123 ' ; 
    +
    +--修改角色manager为系统管理员。
    +postgres=# ALTER ROLE manager SYSADMIN ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    对已存在的行访问控制策略(包括行访问控制策略的名称,行访问控制指定的用户,行访问控制的策略表达式)进行修改。

    +
    +

    注意事项 

    +

    表的所有者或管理员用户才能进行此操作。

    +
    +

    示例 

    +
    --修改行访问控制all_data_rls的名称
    +postgres=# ALTER ROW LEVEL SECURITY POLICY all_data_rls ON all_data RENAME TO all_data_new_rls ; 
    +
    +--修改行访问控制策略影响的用户
    +postgres=# ALTER ROW LEVEL SECURITY POLICY all_data_new_rls ON all_data TO alice , bob ; 
    +postgres=# \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
    +
    +--修改行访问控制策略表达式
    +postgres=# ALTER ROW LEVEL SECURITY POLICY all_data_new_rls ON all_data USING ( id > 100 AND role = current_user ) ; 
    +postgres=# \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
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    修改模式属性。

    +
    +

    注意事项 

    +

    只有模式的所有者有权限执行ALTER SCHEMA命令,系统管理员默认拥有此权限。

    +
    +

    示例 

    +
    --将当前模式ds更名为ds_new。
    +postgres=# ALTER SCHEMA ds RENAME TO ds_new ; 
    +
    +--将DS_NEW的所有者修改为jack。
    +postgres=# ALTER SCHEMA ds_new OWNER TO jack ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    修改一个现有的序列的参数。

    +
    +

    注意事项 

    +
    • 使用ALTER SEQUENCE的用户必须是该序列的所有者。
    • 当前版本仅支持修改拥有者、归属列和最大值。若要修改其他参数,可以删除重建,并用Setval函数恢复当前值。
    • ALTER SEQUENCE MAXVALUE不支持在事务、函数和存储过程中使用。
    • 修改序列的最大值后,会清空该序列在所有会话的cache。
    • ALTER SEQUENCE会阻塞nextval、setval、currval和lastval的调用、
    +
    +

    示例 

    +
    --将序列serial的归属列变为T1.C1。
    +postgres=# ALTER SEQUENCE serial OWNED BY T1.C1 ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    ALTER SESSION命令用于定义或修改那些对当前会话有影响的条件或参数。修改后的会话参数会一直保持,直到断开当前会话。

    +
    +

    注意事项 

    +
    • 如果执行SET TRANSACTION之前没有执行START TRANSACTION,则事务立即结束,命令无法显示效果。
    • 可以用START TRANSACTION里面声明所需要的transaction_mode(s)的方法来避免使用SET TRANSACTION。
    +
    +

    示例 

    +
    --设置当前会话的字符编码为UTF8。
    +postgres=# ALTER SESSION SET NAMES ' UTF8 ' ; 
    +
    +--设置当前模式。
    +postgres=# ALTER SESSION SET CURRENT_SCHEMA TO tpcds ; 
    +
    +--设置XML OPTION为DOCUMENT。
    +postgres=# ALTER SESSION SET XML OPTION DOCUMENT ; 
    +
    +--创建角色joe,并设置会话的角色为joe。
    +postgres=# CREATE ROLE joe WITH PASSWORD ' Bigdata@123 ' ; 
    +postgres=# ALTER SESSION SET SESSION AUTHORIZATION joe PASSWORD ' Bigdata@123 ' ; 
    +
    +--切换到默认用户。
    +postgres=> ALTER SESSION SET SESSION AUTHORIZATION default;
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    修改SYNONYM对象的属性。

    +
    +

    注意事项 

    +
    • 目前仅支持修改SYNONYM对象的属主。
    • 只有系统管理员有权限修改SYNONYM对象的属主信息。
    • 新属主必须具有SYNONYM对象所在模式的CREATE权限。
    +
    +

    示例 

    +
    --修改同义词t1的owner为u1。
    +postgres=# ALTER SYNONYM t1 OWNER TO u1 ; 
    +
    +

    语法格式 

    +]]>
    +
    + +

    功能描述 

    +

    ALTER SYSTEM KILL SESSION命令用于结束一个会话。

    +
    +

    示例 

    +
    --结束SID为140131075880720的会话。
    +postgres=# ALTER SYSTEM KILL SESSION ' 140131075880720 , 0 ' IMMEDIATE ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    修改表,包括修改表的定义、重命名表、重命名表中指定的列、重命名表的约束、设置表的所属模式、添加/更新多个列、打开/关闭行访问控制开关

    +
    +

    注意事项 

    +
    • 只有表的所有者有权限执行ALTER TABLE命令,系统管理员默认拥有此权限。
    • 不能修改分区表的tablespace,但可以修改分区的tablespace。
    • 不支持修改存储参数ORIENTATION。
    • SET SCHEMA操作不支持修改为系统内部模式,当前仅支持用户模式之间的修改。
    • 列存表只支持PARTIAL CLUSTER KEY表级约束,不支持主外键等表级约束。
    • 列存表只支持添加字段ADD COLUMN、修改字段的数据类型ALTER TYPE、设置单个字段的收集目标SET STATISTICS、支持更改表名称、支持更改表空间,支持删除字段DROP COLUMN。对于添加的字段和修改的字段类型要求是列存支持的数据类型。ALTER TYPE的USING选项只支持常量表达式和涉及本字段的表达式,暂不支持涉及其他字段的表达式。
    • 列存表支持的字段约束包括NULL、NOT NULL和DEFAULT常量值;对字段约束的修改当前只支持对DEFAULT值的修改(SET DEFAULT)和删除(DROP DEFAULT),暂不支持对非空约束NULL/NOT NULL的修改。
    +
    +

    示例 

    +
    --向tpcds.warehouse_t19表中增加一个varchar列。
    +postgres=# ALTER TABLE tpcds.warehouse_t19 ADD W_GOODS_CATEGORY varchar ( 30 ) ; 
    +
    +--给tpcds.warehouse_t19表增加一个检查约束。
    +postgres=# ALTER TABLE tpcds.warehouse_t19 ADD CONSTRAINT W_CONSTR_KEY4 CHECK ( W_STATE IS NOT NULL ) ; 
    +
    +--在一个操作中改变两个现存字段的类型。
    +postgres=# ALTER TABLE tpcds.warehouse_t19
    +ALTER COLUMN W_GOODS_CATEGORY TYPE varchar ( 80 ) , 
    +ALTER COLUMN W_STREET_NAME TYPE varchar ( 100 ) ; 
    +
    +--此语句与上面语句等效。
    +postgres=# ALTER TABLE tpcds.warehouse_t19 MODIFY ( W_GOODS_CATEGORY varchar ( 30 ) , W_STREET_NAME varchar ( 60 ) ) ; 
    +
    +--给一个已存在字段添加非空约束。
    +postgres=# ALTER TABLE tpcds.warehouse_t19 ALTER COLUMN W_GOODS_CATEGORY SET NOT NULL ; 
    +
    +--移除已存在字段的非空约束。
    +postgres=# ALTER TABLE tpcds.warehouse_t19 ALTER COLUMN W_GOODS_CATEGORY DROP NOT NULL ; 
    +
    +--如果列存表中还未指定局部聚簇,向在一个列存表中添加局部聚簇列。
    +postgres=# ALTER TABLE tpcds.warehouse_t17 ADD PARTIAL CLUSTER KEY ( W_WAREHOUSE_SK ) ; 
    +
    +--查看约束的名称,并删除一个列存表中的局部聚簇列。
    +postgres=# \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
    +postgres=# ALTER TABLE tpcds.warehouse_t17 DROP CONSTRAINT warehouse_t17_cluster ; 
    +
    +--将表移动到另一个表空间。
    +postgres=# ALTER TABLE tpcds.warehouse_t19 SET TABLESPACE PG_DEFAULT ; 
    +
    +--将表移动到另一个模式中。
    +postgres=# ALTER TABLE tpcds.warehouse_t19 SET SCHEMA joe ; 
    +
    +--重命名已存在的表。
    +postgres=# ALTER TABLE joe.warehouse_t19 RENAME TO warehouse_t23 ; 
    +
    +--从warehouse_t23表中删除一个字段。
    +postgres=# ALTER TABLE joe.warehouse_t23 DROP COLUMN W_STREET_NAME ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    修改表分区,包括增删分区、切割分区、合成分区,以及修改分区属性等。

    +
    +

    注意事项 

    +
    • 添加分区的表空间不能是PG_GLOBAL。
    • 添加分区的名称不能与该分区表已有分区的名称相同。
    • 添加分区的分区键值要和分区表的分区键的类型一致,且要大于分区表中最后一个范围分区的上边界。
    • 如果目标分区表中已有分区数达到了最大值(32767),则不能继续添加分区。
    +
    • 当分区表只有一个分区时,不能删除该分区。
    • 选择分区使用PARTITION FOR(),括号里指定值个数应该与定义分区时使用的列个数相同,并且一一对应。
    • Value分区表不支持相应的Alter Partition操作。
    • 列存分区表不支持切割分区。
    +
    +

    示例 

    +
    --删除分区P8。
    +postgres=# ALTER TABLE tpcds.web_returns_p1 DROP PARTITION P8 ; 
    +
    +--增加分区WR_RETURNED_DATE_SK介于2453005和2453105之间。
    +postgres=# ALTER TABLE tpcds.web_returns_p1 ADD PARTITION P8 VALUES LESS THAN ( 2453105 ) ; 
    +
    +--增加分区WR_RETURNED_DATE_SK介于2453105和MAXVALUE之间。
    +postgres=# ALTER TABLE tpcds.web_returns_p1 ADD PARTITION P9 VALUES LESS THAN ( MAXVALUE ) ; 
    +
    +--删除分区P8。
    +postgres=# ALTER TABLE tpcds.web_returns_p1 DROP PARTITION FOR ( 2453005 ) ; 
    +
    +--分区P7重命名为P10。
    +postgres=# ALTER TABLE tpcds.web_returns_p1 RENAME PARTITION P7 TO P10 ; 
    +
    +--分区P6重命名为P11。
    +postgres=# ALTER TABLE tpcds.web_returns_p1 RENAME PARTITION FOR ( 2452639 ) TO P11 ; 
    +
    +--修改分区P1的表空间为example2。
    +postgres=# ALTER TABLE tpcds.web_returns_p2 MOVE PARTITION P1 TABLESPACE example2 ; 
    +
    +--修改分区P2的表空间为example3。
    +postgres=# ALTER TABLE tpcds.web_returns_p2 MOVE PARTITION P2 TABLESPACE example3 ; 
    +
    +--以2453010为分割点切分P8。
    +postgres=# ALTER TABLE tpcds.web_returns_p2 SPLIT PARTITION P8 AT ( 2453010 ) INTO
    + ( 
    +PARTITION P9 , 
    +PARTITION P10
    + ) ; 
    +
    +--将P6,P7合并为一个分区。
    +postgres=# ALTER TABLE tpcds.web_returns_p2 MERGE PARTITIONS P6 , P7 INTO PARTITION P8 ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    修改表空间的属性。

    +
    +

    注意事项 

    +
    • 只有表空间的所有者有权限执行ALTER TABLESPACE命令,系统管理员默认拥有此权限。
    • 要修改表空间的所有者A为B,则A必须是B的直接或者间接成员。

      如果new_owner与old_owner一致,此处不再校验当前执行操作的用户是否具有修改权限,而直接显示ALTER成功。

      +
      +
    +
    +

    示例 

    +
    --把表空间ds_location1重命名为ds_location3。
    +postgres=# ALTER TABLESPACE ds_location1 RENAME TO ds_location3 ; 
    +
    +--改变表空间ds_location2的所有者。
    +postgres=# ALTER TABLESPACE ds_location2 OWNER TO jay ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    更改文本搜索配置的定义。用户可以将映射从字串类型调整为字典,或者改变配置的名称或者所有者,或者修改搜索配置的配置参数。

    +

    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,用户必须是配置的所有者。
    +
    +

    示例 

    +
    --增加文本搜索配置字串类型映射语法。
    +postgres=# ALTER TEXT SEARCH CONFIGURATION english_1 ADD MAPPING FOR word WITH simple , english_stem ; 
    +ALTER TEXT SEARCH CONFIGURATION
    +
    +--增加文本搜索配置字串类型映射语法。
    +postgres=# ALTER TEXT SEARCH CONFIGURATION english_1 ADD MAPPING FOR email WITH english_stem , french_stem ; 
    +ALTER TEXT SEARCH CONFIGURATION
    +
    +--增加文本搜索配置字串类型映射语法。
    +postgres=# ALTER TEXT SEARCH CONFIGURATION english_1 ALTER MAPPING REPLACE french_stem with german_stem ; 
    +ALTER TEXT SEARCH CONFIGURATION
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    修改全文检索词典的相关定义,包括参数、名称、所有者、以及模式等。

    +
    +

    注意事项 

    +
    • 预定义词典不支持ALTER操作。
    • 只有词典的所有者可以执行ALTER操作,系统管理员默认拥有此权限。
    • 创建或修改词典之后,任何对于filepath路径下用户自定义的词典定义文件的修改,将不会影响到数据库中的词典。如果需要在数据库中使用这些修改,需使用ALTER TEXT SEARCH DICTIONARY语句更新对应词典的定义文件。
    +
    +

    示例 

    +
    --更改Snowball类型字典的停用词定义,其他参数保持不变。
    +postgres=# ALTER TEXT SEARCH DICTIONARY my_dict ( StopWords = newrussian , FilePath = ' file:///home/dicts ' ) ; 
    +
    +--更改Snowball类型字典的Language参数,并删除停用词定义。
    +postgres=# ALTER TEXT SEARCH DICTIONARY my_dict ( Language = dutch, StopWords ) ; 
    +
    +--更新词典定义,不实际更改任何内容。
    +postgres=# ALTER TEXT SEARCH DICTIONARY my_dict ( dummy ) ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    修改触发器定义。

    +
    +

    注意事项 

    +

    只有触发器所在表的所有者可以执行ALTER TRIGGER操作,系统管理员默认拥有此权限。

    +
    +

    示例 

    +
    --修改触发器
    +postgres=# ALTER TRIGGER delete_trigger ON test_trigger_src_tbl RENAME TO delete_trigger_renamed ; 
    +
    +--禁用insert_trigger触发器
    +postgres=# ALTER TABLE test_trigger_src_tbl DISABLE TRIGGER insert_trigger ; 
    +
    +--禁用当前表上所有触发器
    +postgres=# ALTER TABLE test_trigger_src_tbl DISABLE TRIGGER ALL ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    修改一个类型的定义。

    +
    +

    示例 

    +
    --重命名数据类型。
    +postgres=# ALTER TYPE compfoo RENAME TO compfoo1 ; 
    +
    +--要改变一个用户定义类型compfoo1的所有者为usr1。
    +postgres=# CREATE USER usr1 PASSWORD ' Bigdata@123 ' ; 
    +postgres=# ALTER TYPE compfoo1 OWNER TO usr1 ; 
    +
    +--把用户定义类型compfoo1的模式改变为usr1。
    +postgres=# ALTER TYPE compfoo1 SET SCHEMA usr1 ; 
    +
    +--给一个数据类型增加一个新的属性。
    +postgres=# ALTER TYPE usr1.compfoo1 ADD ATTRIBUTE f3 int;
    +
    +--添加一个标签值。
    +postgres=# ALTER TYPE bugstatus ADD VALUE IF NOT EXISTS ' regress ' BEFORE ' closed ' ; 
    +
    +--重命名一个标签值。
    +postgres=# ALTER TYPE bugstatus RENAME VALUE ' create ' TO ' new ' ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    修改数据库用户的属性。

    +
    +

    注意事项 

    +

    ALTER USER中修改的会话参数只针对指定的用户,且在下一次会话中有效。

    +
    +

    示例 

    +
    --将用户jim的登录密码由Bigdata@123修改为Abcd@123。
    +postgres=# ALTER USER jim IDENTIFIED BY ' Abcd@123 ' REPLACE ' Bigdata@123 ' ; 
    +
    +--为用户jim追加CREATEROLE权限。
    +postgres=# ALTER USER jim CREATEROLE ; 
    +
    +--将enable_seqscan的值设置为on, 设置成功后,在下一会话中生效。
    +postgres=# ALTER USER jim SET enable_seqscan TO on ; 
    +
    +--重置jim的enable_seqscan参数。
    +postgres=# ALTER USER jim RESET enable_seqscan ; 
    +
    +--锁定jim帐户。
    +postgres=# ALTER USER jim ACCOUNT LOCK ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    ALTER VIEW更改视图的各种辅助属性。(如果用户是更改视图的查询定义,要使用CREATE OR REPLACE VIEW。)

    +
    +

    注意事项 

    +
    • 用户必须是视图的所有者才可以使用ALTER VIEW。
    • 要改变视图的模式,用户必须要有新模式的CREATE权限。
    • 要改变视图的所有者,用户必须是新所属角色的直接或者间接的成员,并且此角色必须有视图模式的CREATE权限。
    • 管理员用户可以更改任何视图的所属关系。
    +
    +

    示例 

    +
    --修改视图名称。
    +postgres=# ALTER VIEW tpcds.customer_details_view_v1 RENAME TO customer_details_view_v2 ; 
    +
    +--修改视图所属schema。
    +postgres=# ALTER VIEW tpcds.customer_details_view_v2 SET schema public ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    用于收集与数据库中普通表内容相关的统计信息,统计结果存储在系统表PG_STATISTIC下。执行计划生成器会使用这些统计数据,以确定最有效的执行计划。

    +

    如果没有指定参数,ANALYZE会分析当前数据库中的每个表和分区表。同时也可以通过指定table_name、column和partition_name参数把分析限定在特定的表、列或分区表中。

    +

    ANALYZE|ANALYSE VERIFY用于检测数据库中普通表(行存表、列存表)的数据文件是否损坏。

    +
    +

    注意事项 

    +

    ANALYZE非临时表不能在一个匿名块、事务块、函数或存储过程内被执行。支持存储过程中ANALYZE临时表,不支持统计信息回滚操作。

    +

    ANALYZE VERIFY 操作处理的大多为异常场景检测需要使用RELEASE版本。ANALYZE VERIFY 场景不触发远程读,因此远程读参数不生效。对于关键系统表出现错误被系统检测出页面损坏时,将直接报错不再继续检测。

    +
    +

    示例 

    +
    postgres=# 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
    + ) 
    + ; 
    +
    +-- 创建分区表。
    +postgres=# 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语句更新统计信息。
    +postgres=# ANALYZE customer ; 
    +
    +-- 使用ANALYZE VERBOSE语句更新统计信息,并输出表的相关信息。
    +postgres=# 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
    +若环境若有故障,需查看数据库主节点的log。
    +
    +-- 删除表。
    +postgres=# DROP TABLE customer ; 
    +postgres=# DROP TABLE customer_par ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    用于收集与数据库中普通表内容相关的统计信息,统计结果存储在系统表PG_STATISTIC下。执行计划生成器会使用这些统计数据,以确定最有效的执行计划。

    +

    如果没有指定参数,ANALYZE会分析当前数据库中的每个表和分区表。同时也可以通过指定table_name、column和partition_name参数把分析限定在特定的表、列或分区表中。

    +

    ANALYZE|ANALYSE VERIFY用于检测数据库中普通表(行存表、列存表)的数据文件是否损坏。

    +
    +

    注意事项 

    +

    ANALYZE非临时表不能在一个匿名块、事务块、函数或存储过程内被执行。支持存储过程中ANALYZE临时表,不支持统计信息回滚操作。

    +

    ANALYZE VERIFY 操作处理的大多为异常场景检测需要使用RELEASE版本。ANALYZE VERIFY 场景不触发远程读,因此远程读参数不生效。对于关键系统表出现错误被系统检测出页面损坏时,将直接报错不再继续检测。

    +
    +

    示例 

    +
    postgres=# 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
    + ) 
    + ; 
    +
    +-- 创建分区表。
    +postgres=# 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语句更新统计信息。
    +postgres=# ANALYZE customer ; 
    +
    +-- 使用ANALYZE VERBOSE语句更新统计信息,并输出表的相关信息。
    +postgres=# 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
    +若环境若有故障,需查看数据库主节点的log。
    +
    +-- 删除表。
    +postgres=# DROP TABLE customer ; 
    +postgres=# DROP TABLE customer_par ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    BEGIN可以用于开始一个匿名块,也可以用于开始一个事务。本节描述用BEGIN开始匿名块的语法,以BEGIN开始事务的语法见START TRANSACTION

    +

    匿名块是能够动态地创建和执行过程代码的结构,而不需要以持久化的方式将代码作为数据库对象储存在数据库中。

    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    使用CALL命令可以调用已定义的函数和存储过程。

    +
    +

    示例 

    +
    --按参数值传递。
    +postgres=# CALL func_add_sql ( 1 , 3 ) ; 
    +
    +--使用命名标记法传参。
    +postgres=# CALL func_add_sql ( num1 => 1 , num2 => 3 ) ; 
    +postgres=# CALL func_add_sql ( num2 := 2 , num1 := 3 ) ; 
    +
    +--出参传入常量。
    +postgres=# CALL func_increment_sql ( 1 , 2 , 1 ) ; 
    +
    +--函数调用。
    +postgres=# call package_func_overload ( 1 , ' test ' ) ; 
    +postgres=# call package_func_overload ( 1 , 1 ) ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    检查点(CHECKPOINT)是一个事务日志中的点,所有数据文件都在该点被更新以反映日志中的信息,所有数据文件都将被刷新到磁盘。

    +

    设置事务日志检查点。预写式日志(WAL)缺省时在事务日志中每隔一段时间放置一个检查点。可以使用gs_guc命令设置相关运行时参数(checkpoint_segments和checkpoint_timeout)来调整这个原子化检查点的间隔。

    +
    +

    示例 

    +
    --设置检查点。
    +postgres=# CHECKPOINT ; 
    +
    +

    语法格式 

    +]]>
    +
    + +

    功能描述 

    +

    CLOSE释放和一个游标关联的所有资源。

    +
    +

    注意事项 

    +
    • 不允许对一个已关闭的游标再做任何操作。
    • 一个不再使用的游标应该尽早关闭。
    • 当创建游标的事务用COMMIT或ROLLBACK终止之后,每个不可保持的已打开游标都隐含关闭。
    • 当创建游标的事务通过ROLLBACK退出之后,每个可以保持的游标都将隐含关闭。
    • 当创建游标的事务成功提交,可保持的游标将保持打开,直到执行一个明确的CLOSE或者客户端断开。
    • openGauss没有明确打开游标的OPEN语句,因为一个游标在使用CURSOR命令定义的时候就打开了。可以通过查询系统视图pg_cursors看到所有可用的游标。
    +
    +

    示例 

    +
    --关闭游标并提交事务。
    +postgres=# CLOSE cursor1 ; 
    +
    +--关闭游标并提交事务。
    +postgres=# CLOSE cursor2 ; 
    +
    +--关闭游标。
    +postgres=# CLOSE cursor1 ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    根据一个索引对表进行聚簇排序。

    +

    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不允许在事务中执行。

    +
    +

    示例 

    +
    -- 对表tpcds.inventory_p1进行聚集。
    +postgres=# CLUSTER tpcds.inventory_p1 USING ds_inventory_p1_index1 ; 
    +
    +-- 对分区p3进行聚集。
    +postgres=# CLUSTER tpcds.inventory_p1 PARTITION ( p3 ) USING ds_inventory_p1_index1 ; 
    +
    +-- 对数据库中可以进行聚集的表进聚集。
    +postgres=# CLUSTER ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    + +
  • 建议在新近聚簇的表上运行ANALYZE。否则,优化器可能会选择很差劲的查询规划。
  • 不允许在事务中执行CLUSTER。
  • +]]>
    +
    +
    + +

    功能描述 

    +

    定义或修改一个对象的注释。

    +
    +

    注意事项 

    +
    • 每个对象只存储一条注释,因此要修改一个注释,对同一个对象发出一条新的COMMENT命令即可。要删除注释,在文本字符串的位置写上NULL即可。当删除对象时,注释自动被删除掉。
    • 目前注释浏览没有安全机制:任何连接到某数据库上的用户都可以看到所有该数据库对象的注释。共享对象(比如数据库、角色、表空间)的注释是全局存储的,连接到任何数据库的任何用户都可以看到它们。因此,不要在注释里存放与安全有关的敏感信息。
    • 对大多数对象,只有对象的所有者可以设置注释。角色没有所有者,所以COMMENT ON ROLE命令仅可以由系统管理员对系统管理员角色执行,有CREATEROLE权限的角色也可以为非系统管理员角色设置注释。系统管理员可以对所有对象进行注释。
    +
    +

    示例 

    +
    -- 为tpcds.customer_demographics_t2.cd_demo_sk列加注释。
    +postgres=# COMMENT ON COLUMN tpcds.customer_demographics_t2.cd_demo_sk IS ' Primary key of customer demographics table. ' ; 
    +
    +-- 为tpcds.customer_details_view_v2视图加注释。
    +postgres=# COMMENT ON VIEW tpcds.customer_details_view_v2 IS ' View of customer detail ' ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    通过COMMIT或者END可完成提交事务的功能,即提交事务的所有操作。

    +
    +

    注意事项 

    +

    执行COMMIT这个命令的时候,命令执行者必须是该事务的创建者或系统管理员,且创建和提交操作可以不在同一个会话中。

    +
    +

    示例 

    +
    --创建表。
    +postgres=# 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 ) 
    + ; 
    +
    +--开启事务。
    +postgres=# START TRANSACTION ; 
    +
    +--插入数据。
    +postgres=# INSERT INTO tpcds.customer_demographics_t2 VALUES ( 1 , ' M ' , ' U ' , ' DOCTOR DEGREE ' , 1200 , ' GOOD ' , 1 , 0 , 0 ) ; 
    +postgres=# INSERT INTO tpcds.customer_demographics_t2 VALUES ( 2 , ' F ' , ' U ' , ' MASTER DEGREE ' , 300 , ' BAD ' , 1 , 0 , 0 ) ; 
    +
    +--提交事务,让所有更改永久化。
    +postgres=# COMMIT ; 
    +
    +--查询数据。
    +postgres=# SELECT * FROM tpcds.customer_demographics_t2 ; 
    +
    +--删除表tpcds.customer_demographics_t2。
    +postgres=# DROP TABLE tpcds.customer_demographics_t2 ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    通过COMMIT或者END可完成提交事务的功能,即提交事务的所有操作。

    +
    +

    注意事项 

    +

    执行COMMIT这个命令的时候,命令执行者必须是该事务的创建者或系统管理员,且创建和提交操作可以不在同一个会话中。

    +
    +

    示例 

    +
    --创建表。
    +postgres=# 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 ) 
    + ; 
    +
    +--开启事务。
    +postgres=# START TRANSACTION ; 
    +
    +--插入数据。
    +postgres=# INSERT INTO tpcds.customer_demographics_t2 VALUES ( 1 , ' M ' , ' U ' , ' DOCTOR DEGREE ' , 1200 , ' GOOD ' , 1 , 0 , 0 ) ; 
    +postgres=# INSERT INTO tpcds.customer_demographics_t2 VALUES ( 2 , ' F ' , ' U ' , ' MASTER DEGREE ' , 300 , ' BAD ' , 1 , 0 , 0 ) ; 
    +
    +--提交事务,让所有更改永久化。
    +postgres=# COMMIT ; 
    +
    +--查询数据。
    +postgres=# SELECT * FROM tpcds.customer_demographics_t2 ; 
    +
    +--删除表tpcds.customer_demographics_t2。
    +postgres=# DROP TABLE tpcds.customer_demographics_t2 ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    提交一个早先为两阶段提交准备好的事务。

    +
    +

    注意事项 

    +
    • 该功能仅在维护模式(GUC参数xc_maintenance_mode为on时)下可用。该模式谨慎打开,一般供维护人员排查问题使用,一般用户不应使用该模式。
    • 命令执行者必须是该事务的创建者或系统管理员,且创建和提交操作可以不在同一个会话中。
    • 事务功能由数据库自动维护,不应显式使用事务功能。
    +
    +

    示例 

    +
    --提交标识符为的trans_test的事务。
    +postgres=# COMMIT PREPARED ' trans_test ' ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    通过COPY命令实现在表和文件之间拷贝数据。

    +

    COPY FROM从一个文件拷贝数据到一个表,COPY TO把一个表的数据拷贝到一个文件。

    +
    +

    注意事项 

    +
    • 执行COPY FROM FILENAME或COPY TO FILENAME语句需要SYSADMIN权限,但默认禁止SYSADMIN用户对数据库配置文件,密钥文件,证书文件和审计日志执行COPY FROM FILENAME或COPY TO FILENAME,以防止SYSADMIN用户越权查看或修改敏感文件。放开这一权限需要通过更改enable_copy_server_files的设定来完成。
    • COPY只能用于表,不能用于视图。
    • 对任何要插入数据的表必须有插入权限。
    • 如果声明了一个字段列表,COPY将只在文件和表之间拷贝已声明字段的数据。如果表中有任何不在字段列表里的字段,COPY FROM将为那些字段插入缺省值。
    • 如果声明了数据源文件,服务器必须可以访问该文件;如果指定了STDIN,数据将在客户前端和服务器之间流动,输入时,表的列与列之间使用TAB键分隔,在新的一行中以反斜杠和句点(\.)表示输入结束。
    • 如果数据文件的任意行包含比预期多或者少的字段,COPY FROM将抛出一个错误。
    • 数据的结束可以用一个只包含反斜杠和句点(\.)的行表示。如果从文件中读取数据,数据结束的标记是不必要的;如果在客户端应用之间拷贝数据,必须要有结束标记。
    • COPY FROM中\N为空字符串,如果要输入实际数据值\N ,使用\\N。
    +
    +

    示例 

    +
    --将tpcds.ship_mode中的数据拷贝到/home/omm/ds_ship_mode.dat文件中。
    +postgres=# COPY tpcds.ship_mode TO ' /home/omm/ds_ship_mode.dat ' ; 
    +
    +--将tpcds.ship_mode 输出到stdout。
    +postgres=# COPY tpcds.ship_mode TO stdout;
    +
    +--从stdin拷贝数据到表tpcds.ship_mode_t1。
    +postgres=# COPY tpcds.ship_mode_t1 FROM stdin ; 
    +
    +--从/home/omm/ds_ship_mode.dat文件拷贝数据到表tpcds.ship_mode_t1。
    +postgres=# COPY tpcds.ship_mode_t1 FROM ' /home/omm/ds_ship_mode.dat ' ; 
    +
    +--从/home/omm/ds_ship_mode.dat文件拷贝数据到表tpcds.ship_mode_t1,使用参数如下:导入格式为TEXT(format 'text'),分隔符为'\t'(delimiter E'\t'),忽略多余列(ignore_extra_data 'true'),不指定转义(noescaping 'true')。
    +postgres=# 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)。
    +postgres=# 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 ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    创建一个新的数据库。缺省情况下新数据库将通过复制标准系统数据库template0来创建,且仅支持使用template0来创建。

    +
    +

    注意事项 

    +
    • 只有拥有CREATEDB权限的用户才可以创建新数据库,系统管理员默认拥有此权限。
    • 不能在事务块中执行创建数据库语句。
    • 在创建数据库过程中,若出现类似“could not initialize database directory”的错误提示,可能是由于文件系统上数据目录的权限不足或磁盘满等原因引起。
    +
    +

    示例 

    +
    --创建一个GBK编码的数据库music(本地环境的编码格式必须也为GBK)。
    +postgres=# CREATE DATABASE music ENCODING ' GBK ' template = template0 ; 
    +
    +--创建数据库music2,并指定所有者为jim。
    +postgres=# CREATE DATABASE music2 OWNER jim ; 
    +
    +--用模板template0创建数据库music3,并指定所有者为jim。
    +postgres=# CREATE DATABASE music3 OWNER jim TEMPLATE template0 ; 
    +
    +--创建兼容TD格式的数据库。
    +postgres=# CREATE DATABASE td_compatible_db DBCOMPATIBILITY ' C ' ; 
    +
    +--创建兼容ORA格式的数据库。
    +postgres=# CREATE DATABASE ora_compatible_db DBCOMPATIBILITY ' A ' ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    + + 事务中不支持创建database。

    +]]>
    +
    +
    + +

    功能描述 

    +

    创建一个新的外部数据源对象,该对象用于定义openGauss要连接的目标库信息。

    +
    +

    注意事项 

    +
    • Data Source名称在数据库中需唯一,遵循标识符命名规范,长度限制为63字节,过长则会被截断。
    • 只有系统管理员或初始用户才有权限创建Data Source对象。且创建该对象的用户为其默认属主。
    • 当在OPTIONS中出现password选项时,需要保证openGauss每个节点的$GAUSSHOME/bin目录下存在datasource.key.cipher和datasource.key.rand文件,如果不存在这两个文件,请使用gs_guc工具生成并使用gs_ssh工具发布到openGauss每个节点的$GAUSSHOME/bin目录下。
    +
    +

    示例 

    +
    --创建一个空的Data Source对象,不含任何信息。
    +postgres=# CREATE DATA SOURCE ds_test1 ; 
    +
    +--创建一个Data Source对象,含TYPE信息,VERSION为NULL。
    +postgres=# CREATE DATA SOURCE ds_test2 TYPE ' MPPDB ' VERSION NULL ; 
    +
    +--创建一个Data Source对象,仅含OPTIONS。
    +postgres=# CREATE DATA SOURCE ds_test3 OPTIONS ( dsn ' openGauss ' , encoding ' utf8 ' ) ; 
    +
    +--创建一个Data Source对象,含TYPE, VERSION, OPTIONS。
    +postgres=# CREATE DATA SOURCE ds_test4 TYPE ' unknown ' VERSION ' 11.2.3 ' OPTIONS ( dsn ' openGauss ' , username ' userid ' , password ' pwd@123456 ' , encoding ' ' ) ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    使用CREATE DIRECTORY语句创建一个目录对象,该目录对象定义了服务器文件系统上目录的别名,用于存放用户使用的数据文件。

    +
    +

    注意事项 

    +
    • 默认只允许初始化用户创建,如果开启enable_access_server_directory(可参考enable_access_server_directory),sysadmin权限的用户也可以创建目录。
    • 创建用户默认拥有此路径的READ和WRITE操作权限。
    • 目录的默认owner为创建directory的用户。
    • 以下路径禁止创建:
      • 路径含特殊字符。
      • 路径是相对路径。
      • 路径是符号连接。
      +
    • 创建目录时会进行以下合法性校验:
      • 创建时会检查添加路径是否为操作系统实际存在路径,如不存在会提示用户使用风险。
      • 创建时会校验数据库初始化(omm)用户对于添加路径的权限(即操作系统目录权限,读/写/执行 - R/W/X),如果权限不全,会提示用户使用风险。
      +
    • 在openGauss环境下用户指定的路径需要用户保证各节点上路径的一致性,否则在不同节点上执行会产生找不到路径的问题。
    +
    +

    示例 

    +
    --创建目录。
    +postgres=# CREATE OR REPLACE DIRECTORY dir as ' /tmp/ ' ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    创建一个函数。

    +
    +

    注意事项 

    +
    • 如果创建函数时参数或返回值带有精度,不进行精度检测。
    • 创建函数时,函数定义中对表对象的操作建议都显式指定模式,否则可能会导致函数执行异常。
    • 在创建函数时,函数内部通过SET语句设置current_schema和search_path无效。执行完函数search_path和current_schema与执行函数前的search_path和current_schema保持一致。
    • 如果函数参数中带有出参,SELECT调用函数必须缺省出参,CALL调用函数必须指定出参,对于调用重载的带有PACKAGE属性的函数,CALL调用函数可以缺省出参,具体信息参见CALL的示例。
    • 兼容Postgresql风格的函数或者带有PACKAGE属性的函数支持重载。在指定REPLACE的时候,如果参数个数、类型、返回值有变化,不会替换原有函数,而是会建立新的函数。
    • SELECT调用可以指定不同参数来进行同名函数调用。由于语法不支持调用不带有PACKAGE属性的同名函数。
    • 在创建function时,不能在avg函数外面嵌套其他agg函数,或者其他系统函数。
    • 新创建的函数默认会给PUBLIC授予执行权限(详见GRANT)。用户可以选择收回PUBLIC默认执行权限,然后根据需要将执行权限授予其他用户,为了避免出现新函数能被所有人访问的时间窗口,应在一个事务中创建函数并且设置函数执行权限。
    +
    +

    示例 

    +
    --定义函数为SQL查询。
    +postgres=# CREATE FUNCTION func_add_sql ( integer , integer ) RETURNS integer
    +AS ' select $1 + $2 ; ' 
    +LANGUAGE SQL
    +IMMUTABLE
    +RETURNS NULL ON NULL INPUT ; 
    +
    +--利用参数名用 PL/pgSQL 自增一个整数。
    +postgres=# CREATE OR REPLACE FUNCTION func_increment_plsql ( i integer ) RETURNS integer AS $$
    +BEGIN
    +RETURN i + 1 ; 
    +END ; 
    +$$ LANGUAGE plpgsql ; 
    +
    +--返回RECORD类型
    +CREATE OR REPLACE FUNCTION compute ( 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 ; 
    +
    +--返回一个包含多个输出参数的记录。
    +postgres=# CREATE FUNCTION func_dup_sql ( in int , out f1 int , out f2 text ) 
    +AS $$ SELECT $1 , CAST ( $1 AS text ) || ' is text ' $$
    +LANGUAGE SQL ; 
    +postgres=# SELECT * FROM func_dup_sql ( 42 ) ; 
    +
    +--计算两个整数的和,并返回结果。若果输入为null,则返回null。
    +postgres=# CREATE FUNCTION func_add_sql2 ( num1 integer , num2 integer ) RETURN integer
    +AS
    +BEGIN
    +RETURN num1 + num2 ; 
    +END ; 
    +/
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    创建一个新用户组。

    +
    +

    注意事项 

    +

    CREATE GROUP是CREATE ROLE的别名,非SQL标准语法,不推荐使用,建议用户直接使用CREATE ROLE替代。

    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    在指定的表上创建索引。

    +

    索引可以用来提高数据库查询性能,但是不恰当的使用将导致数据库性能下降。建议仅在匹配如下某条原则时创建索引:

    +
    • 经常执行查询的字段。
    • 在连接条件上创建索引,对于存在多字段连接的查询,建议在这些字段上建立组合索引。例如,select * from t1 join t2 on t1.a=t2.a and t1.b=t2.b,可以在t1表上的a,b字段上建立组合索引。
    • where子句的过滤条件字段上(尤其是范围条件)。
    • 在经常出现在order by、group by和distinct后的字段。
    +

    在分区表上创建索引与在普通表上创建索引的语法不太一样,使用时请注意,如分区表上不支持并行创建索引、不支持创建部分索引、不支持NULL FIRST特性。

    +
    +

    注意事项 

    +
    • 索引自身也占用存储空间、消耗计算资源,创建过多的索引将对数据库性能造成负面影响(尤其影响数据导入的性能,建议在数据导入后再建索引)。因此,仅在必要时创建索引。
    • 索引定义里的所有函数和操作符都必须是immutable类型的,即它们的结果必须只能依赖于它们的输入参数,而不受任何外部的影响(如另外一个表的内容或者当前时间)。这个限制可以确保该索引的行为是定义良好的。要在一个索引上或WHERE中使用用户定义函数,请把它标记为immutable类型函数。
    • 在分区表上创建唯一索引时,索引项中必须包含分布列和所有分区键。
    • 列存表支持的PSORT和B-tree索引都不支持创建表达式索引、部分索引和唯一索引。
    • 列存表支持的GIN索引支持创建表达式索引,但表达式不能包含空分词、空列和多列,不支持创建部分索引和唯一索引。
    +
    +

    示例 

    +
    --在表tpcds.ship_mode_t1上的SM_SHIP_MODE_SK字段上创建普通索引。
    +postgres=# 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索引。
    +postgres=# CREATE INDEX ds_ship_mode_t1_index4 ON tpcds.ship_mode_t1 USING btree ( SM_SHIP_MODE_SK ) ; 
    +
    +--在表tpcds.ship_mode_t1上SM_CODE字段上创建表达式索引。
    +postgres=# 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的部分索引。
    +postgres=# CREATE UNIQUE INDEX ds_ship_mode_t1_index3 ON tpcds.ship_mode_t1 ( SM_SHIP_MODE_SK ) WHERE SM_SHIP_MODE_SK>10 ; 
    +
    +--创建分区表索引ds_customer_address_p1_index1,不指定索引分区的名称。
    +postgres=# CREATE INDEX ds_customer_address_p1_index1 ON tpcds.customer_address_p1 ( CA_ADDRESS_SK ) LOCAL ; 
    +
    +--创建分区表索引ds_customer_address_p1_index2,并指定索引分区的名称。
    +postgres=# 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 ; 
    +
    +--创建列存表以及列存表GIN索引。
    +postgres=# create table cgin_create_test ( a int , b text ) with ( orientation = column ) ; 
    +CREATE TABLE
    +postgres=# create index cgin_test on cgin_create_test using gin ( to_tsvector ( ' ngram ' , b ) ) ; 
    +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后的字段。
    +
    约束限制:
    • 分区表上不支持创建部分索引、不支持NULL FIRST特性。
    +
    • 在分区表上创建唯一索引时,索引项中必须包含分布列和所有分区键。
    +
    +]]>
    +
    +
    + +

    功能描述 

    +

    对表创建行访问控制策略。

    +

    当对表创建了行访问控制策略,只有打开该表的行访问控制开关(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语句、视图、函数、存储过程查询包含行访问控制策略的表,都会受影响。
    +
    +

    示例 

    +
    --创建行访问控制策略,当前用户只能查看用户自身的数据
    +postgres=# CREATE ROW LEVEL SECURITY POLICY all_data_rls ON all_data USING ( role = CURRENT_USER ) ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    创建一个新的存储过程。

    +
    +

    注意事项 

    +
    • 如果创建存储过程时参数或返回值带有精度,不进行精度检测。
    • 创建存储过程时,存储过程定义中对表对象的操作建议都显示指定模式,否则可能会导致存储过程执行异常。
    • 在创建存储过程时,存储过程内部通过SET语句设置current_schema和search_path无效。执行完函数search_path和current_schema与执行函数前的search_path和current_schema保持一致。
    • 如果存储过程参数中带有出参,SELECT调用存储过程必须缺省出参,CALL调用存储过程调用非重载函数时必须指定出参,对于重载的package函数,out参数可以缺省,具体信息参见CALL的示例。
    • 存储过程指定package属性时支持重载。
    • 在创建procedure时,不能在avg函数外面嵌套其他agg函数,或者其他系统函数。
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    + +
  • 不支持在事务或匿名块中执行analyze 。
  • 不支持在函数或存储过程中执行analyze操作。
  • +]]>
    +
    + +
  • 不支持在事务或匿名块中执行analyze 。
  • 不支持在函数或存储过程中执行analyze操作。
  • +]]>
    +
    +
    + +

    功能描述 

    +

    创建角色。

    +

    角色是拥有数据库对象和权限的实体。在不同的环境中角色可以认为是一个用户,一个组或者兼顾两者。

    +
    +

    注意事项 

    +
    • 在数据库中添加一个新角色,角色无登录权限。
    • 创建角色的用户必须具备CREATE ROLE的权限或者是系统管理员。
    +
    +

    示例 

    +
    --创建一个角色,名为manager,密码为Bigdata@123。
    +postgres=# CREATE ROLE manager IDENTIFIED BY ' Bigdata@123 ' ; 
    +
    +--创建一个角色,从2015年1月1日开始生效,到2026年1月1日失效。
    +postgres=# CREATE ROLE miriam WITH LOGIN PASSWORD ' Bigdata@123 ' VALID BEGIN ' 2015-01-01 ' VALID UNTIL ' 2026-01-01 ' ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    创建模式。

    +

    访问命名对象时可以使用模式名作为前缀进行访问,如果无模式名前缀,则访问当前模式下的命名对象。创建命名对象时也可用模式名作为前缀修饰。

    +

    另外,CREATE SCHEMA可以包括在新模式中创建对象的子命令,这些子命令和那些在创建完模式后发出的命令没有任何区别。如果使用了AUTHORIZATION子句,则所有创建的对象都将被该用户所拥有。

    +
    +

    注意事项 

    +
    • 只要用户对当前数据库有CREATE权限,就可以创建模式。
    • 系统管理员在普通用户同名schema下创建的对象,所有者为schema的同名用户(非系统管理员)。
    +
    +

    示例 

    +
    -- 为用户role1创建一个同名schema,子命令创建的表films和winners的拥有者为role1。
    +postgres=# 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 ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    CREATE SEQUENCE用于向当前数据库里增加一个新的序列。序列的Owner为创建此序列的用户。

    +
    +

    注意事项 

    +
    • Sequence是一个存放等差数列的特殊表。这个表没有实际意义,通常用于为行或者表生成唯一的标识符。
    • 如果给出一个模式名,则该序列就在给定的模式中创建,否则会在当前模式中创建。序列名必须和同一个模式中的其他序列、表、索引、视图或外表的名称不同。
    • 创建序列后,在表中使用序列的nextval()函数和generate_series(1,N)函数对表插入数据,请保证nextval的可调用次数大于等于N+1次,否则会因为generate_series()函数会调用N+1次而导致报错。
    +
    +

    示例 

    +
    postgres=# CREATE SEQUENCE serial
    +START 101
    +CACHE 20 ; 
    +从序列中选出下一个数字:
    +postgres=# SELECT nextval ( ' serial ' ) ; 
    +nextval
    +
    +--
    +102
    +创建与表关联的序列:
    +postgres=# 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 ) 
    + ) ; 
    +postgres=# CREATE SEQUENCE serial1
    +START 101
    +CACHE 20
    +OWNED BY customer_address.ca_address_sk ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    创建一个同义词对象。同义词是数据库对象的别名,用于记录与其他数据库对象名间的映射关系,用户可以使用同义词访问关联的数据库对象。

    +
    +

    注意事项 

    +
    • 定义同义词的用户成为其所有者。
    • 若指定模式名称,则同义词在指定模式中创建。否则,在当前模式创建。
    • 支持通过同义词访问的数据库对象包括:表、视图、函数和存储过程。
    • 使用同义词时,用户需要具有对关联对象的相应权限。
    • 支持使用同义词的DML语句包括:SELECT、INSERT、UPDATE、DELETE、EXPLAIN、CALL。
    • 不支持关联函数或存储过程的CREATE SYNONYM语句出现在存储过程中,建议存储过程中使用系统表pg_synonym中已存在的同义词对象。
    +
    +

    示例 

    +
    --创建表ot.t1及其同义词t1。
    +postgres=# CREATE TABLE ot.t1 ( id int , name varchar2 ( 10 ) ) ; 
    +postgres=# CREATE OR REPLACE SYNONYM t1 FOR ot.t1 ; 
    +
    +--创建同义词v1及其关联视图ot.v_t1。
    +postgres=# CREATE SYNONYM v1 FOR ot.v_t1 ; 
    +postgres=# CREATE VIEW ot.v_t1 AS SELECT * FROM ot.t1 ; 
    +
    +--创建重载函数ot.add及其同义词add。
    +postgres=# CREATE OR REPLACE FUNCTION ot.add ( a integer , b integer ) RETURNS integer AS
    +$$
    +SELECT $1 + $2
    +$$
    +LANGUAGE sql ; 
    +postgres=# CREATE OR REPLACE FUNCTION ot.add ( a decimal ( 5 , 2 ) , b decimal ( 5 , 2 ) ) RETURNS decimal ( 5 , 2 ) AS
    +$$
    +SELECT $1 + $2
    +$$
    +LANGUAGE sql ; 
    +postgres=# CREATE OR REPLACE SYNONYM add FOR ot.add ; 
    +
    +--创建存储过程ot.register及其同义词register。
    +postgres=# 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 ; 
    +/
    +postgres=# CREATE OR REPLACE SYNONYM register FOR ot.register ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    在当前数据库中创建一个新的空白表,该表由命令执行者所有。

    +
    +

    注意事项 

    +
    • 列存表支持的数据类型请参考列存表支持的数据类型
    • 创建列存表的数量建议不超过1000个。
    • 表中的主键约束和唯一约束必须包含分布列。
    • 如果在建表过程中数据库系统发生故障,系统恢复后可能无法自动清除之前已创建的、大小为0的磁盘文件。此种情况出现概率小,不影响数据库系统的正常运行。
    • 列存表的表级约束只支持PARTIAL CLUSTER KEY,不支持主外键等表级约束。
    • 列存表的字段约束只支持NULL、NOT NULL和DEFAULT常量值。
    • 列存表支持delta表,受参数enable_delta_store 控制是否开启,受参数deltarow_threshold控制进入delta表的阀值。
    • 使用JDBC时,支持通过PrepareStatement对DEFAUTL值进行参数化设置。
    +
    +

    示例 

    +
    --创建简单的表。
    +postgres=# 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 ) 
    + ) ; 
    +postgres=# 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 ) DICTIONARY , 
    +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。
    +postgres=# 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字段是否有重复。
    +postgres=# 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%填充因子的表。
    +postgres=# 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 ) 
    + ) ; 
    +
    +--或者用下面的语法。
    +postgres=# 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 ) ; 
    +
    +--创建表,并指定该表数据不写入预写日志。
    +postgres=# 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 ) 
    + ) ; 
    +
    +--创建表临时表。
    +postgres=# 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 ) 
    + ) ; 
    +
    +--事务中创建表临时表,并指定提交事务时删除该临时表数据。
    +postgres=# 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 ; 
    +
    +--创建表时,不希望因为表已存在而报错。
    +postgres=# 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 ) 
    + ) ; 
    +
    +--创建普通表空间。
    +postgres=# CREATE TABLESPACE DS_TABLESPACE1 RELATIVE LOCATION ' tablespace/tablespace_1 ' ; 
    +
    +--创建表时,指定表空间。
    +postgres=# 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的索引表空间。
    +postgres=# 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 ) 
    + ) ; 
    +
    +--创建一个有主键约束的表。
    +postgres=# 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 ) 
    + ) ; 
    +
    +--或是用下面的语法,效果完全一样。
    +postgres=# 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 ) 
    + ) ; 
    +
    +--或是用下面的语法,指定约束的名称。
    +postgres=# 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 ) 
    + ) ; 
    +
    +--创建一个有复合主键约束的表。
    +postgres=# 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 ) 
    + ) ; 
    +
    +--创建列存表。
    +postgres=# 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 ) ; 
    +
    +--创建局部聚簇存储的列存表。
    +postgres=# 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 ) ; 
    +
    +--定义一个带压缩的列存表。
    +postgres=# 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 ) ; 
    +
    +--定义一个带压缩的表。
    +postgres=# CREATE TABLE tpcds.warehouse_t18
    + ( 
    +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 ) 
    + ) COMPRESS ; 
    +
    +--定义一个检查列约束。
    +postgres=# 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 ) 
    + ) ; 
    +postgres=# 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 ) 
    + ) ; 
    +
    +--定义一个表,表中每一个行存在数据库节点中。
    +postgres=# CREATE TABLE tpcds.warehouse_t21
    + ( 
    +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 ) 
    + ) ; 
    +
    +--定义一个表,使用HASH分布。
    +postgres=# CREATE TABLE tpcds.warehouse_t22
    + ( 
    +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_CONSTR_KEY3 UNIQUE ( W_WAREHOUSE_SK ) 
    + ) ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    + +
  • UNLOGGED表和表上的索引因为数据写入时不通过WAL日志机制,写入速度远高于普通表。因此,可以用于缓冲存储复杂查询的中间结果集,增强复杂查询的性能。
  • UNLOGGED表无主备机制,在系统故障或异常断点等情况下,会有数据丢失风险,因此,不可用来存储基础数据。
  • +]]>
    +
    + +
  • 临时表只在当前会话可见,会话结束后会自动删除。
  • +]]>
    +
    + +
  • 临时表只在当前会话可见,会话结束后会自动删除。
  • +]]>
    +
    + +
  • 新表自动从这个表中继承所有字段名及其数据类型和非空约束,新表与源表之间在创建动作完毕之后是完全无关的。
  • +]]>
    +
    + +
  • 源表上的字段缺省表达式只有在指定INCLUDING DEFAULTS时,才会复制到新表中。缺省是不包含缺省表达式的,即新表中的所有字段的缺省值都是NULL。
  • +]]>
    +
    + +
  • 源表上的CHECK约束仅在指定INCLUDING CONSTRAINTS时,会复制到新表中,而其他类型的约束永远不会复制到新表中。非空约束总是复制到新表中。此规则同时适用于表约束和列约束。
  • +]]>
    +
    + +
  • 如果指定了INCLUDING INDEXES,则源表上的索引也将在新表上创建,默认不建立索引。
  • +]]>
    +
    + +
  • 如果指定了INCLUDING STORAGE,则复制列的STORAGE设置会复制到新表中,默认情况下不包含STORAGE设置。
  • +]]>
    +
    + +
  • 如果指定了INCLUDING COMMENTS,则源表列、约束和索引的注释会复制到新表中。默认情况下,不复制源表的注释。
  • +]]>
    +
    + +
  • 如果指定了INCLUDING PARTITION,则源表的分区定义会复制到新表中,同时新表将不能再使用PARTITION BY子句。默认情况下,不拷贝源表的分区定义。
  • +]]>
    +
    + +
  • 如果指定了INCLUDING RELOPTIONS,则源表的存储参数(即源表的WITH子句)会复制到新表中。默认情况下,不复制源表的存储参数。
  • +]]>
    +
    + +
  • INCLUDING ALL包含了INCLUDING DEFAULTS、INCLUDING CONSTRAINTS、INCLUDING INDEXES、INCLUDING STORAGE、INCLUDING COMMENTS、INCLUDING PARTITION、INCLUDING RELOPTIONS的内容。
  • +]]>
    +
    + +
  • 创建行存表,行存储适合于OLTP业务,此类型的表上交互事务比较多,一次交互会涉及表中的多个列,用行存查询效率较高。
  • +]]>
    +
    + +
  • 创建列存表,列存储适合于数据仓库业务,此类型的表上会做大量的汇聚计算,且涉及的列操作较少。
  • +]]>
    +
    +
    + +

    功能描述 

    +

    根据查询结果创建表。

    +

    CREATE TABLE AS创建一个表并且用来自SELECT命令的结果填充该表。该表的字段和SELECT输出字段的名称及数据类型相关。不过用户可以通过明确地给出一个字段名称列表来覆盖SELECT输出字段的名称。

    +

    CREATE TABLE AS对源表进行一次查询,然后将数据写入新表中,而查询视图结果会根据源表的变化而有所改变。相比之下,每次做查询的时候,视图都重新计算定义它的SELECT语句。

    +
    +

    注意事项 

    +
    • 分区表不能采用此方式进行创建。
    • 如果在建表过程中数据库系统发生故障,系统恢复后可能无法自动清除之前已创建的、大小非0的磁盘文件。此种情况出现概率小,不影响数据库系统的正常运行。
    +
    +

    示例 

    +
    --创建一个表tpcds.store_returns_t1并插入tpcds.store_returns表中sr_item_sk字段中大于16的数值。
    +postgres=# CREATE TABLE tpcds.store_returns_t1 AS SELECT * FROM tpcds.store_returns WHERE sr_item_sk > ' 4795 ' ; 
    +
    +--使用tpcds.store_returns拷贝一个新表tpcds.store_returns_t2。
    +postgres=# CREATE TABLE tpcds.store_returns_t2 AS table tpcds.store_returns ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    创建分区表。分区表是把逻辑上的一张表根据某种方案分成几张物理块进行存储,这张逻辑上的表称之为分区表,物理块称之为分区。分区表是一张逻辑表,不存储数据,数据实际是存储在分区上的。

    +

    常见的分区方案有范围分区(Range Partitioning)、哈希分区(Hash Partitioning)、列表分区(List Partitioning)、数值分区(Value Partition)等。目前行存表、列存表仅支持范围分区。

    +

    范围分区是根据表的一列或者多列,将要插入表的记录分为若干个范围,这些范围在不同的分区里没有重叠。为每个范围创建一个分区,用来存储相应的数据。

    +

    范围分区的分区策略是指记录插入分区的方式。目前范围分区仅支持范围分区策略。

    +

    范围分区策略:根据分区键值将记录映射到已创建的某个分区上,如果可以映射到已创建的某一分区上,则把记录插入到对应的分区上,否则给出报错和提示信息。这是最常用的分区策略。

    +

    分区可以提供若干好处:

    +
    • 某些类型的查询性能可以得到极大提升。特别是表中访问率较高的行位于一个单独分区或少数几个分区上的情况下。分区可以减少数据的搜索空间,提高数据访问效率。
    • 当查询或更新一个分区的大部分记录时,连续扫描那个分区而不是访问整个表可以获得巨大的性能提升。
    • 如果需要大量加载或者删除的记录位于单独的分区上,则可以通过直接读取或删除那个分区以获得巨大的性能提升,同时还可以避免由于大量DELETE导致的VACUUM超载(仅范围分区)。
    +
    +

    注意事项 

    +

    有限地支持唯一约束和主键约束,即唯一约束和主键约束的约束键必须包含所有分区键。

    +
    +

    示例 

    +
    --创建分区表tpcds.web_returns_p1。
    +postgres=# 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 ) 
    + ) ; 
    +
    +--查询分区P1的行数。
    +postgres=# 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用户拥有读写权限的空目录。
    +postgres=# CREATE TABLESPACE example1 RELATIVE LOCATION ' tablespace1/tablespace_1 ' ; 
    +postgres=# CREATE TABLESPACE example2 RELATIVE LOCATION ' tablespace2/tablespace_2 ' ; 
    +postgres=# CREATE TABLESPACE example3 RELATIVE LOCATION ' tablespace3/tablespace_3 ' ; 
    +postgres=# CREATE TABLESPACE example4 RELATIVE LOCATION ' tablespace4/tablespace_4 ' ; 
    +postgres=# 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方式创建一个分区表。
    +postgres=# CREATE TABLE tpcds.web_returns_p3 ( LIKE tpcds.web_returns_p2 INCLUDING PARTITION ) ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    在数据库中创建一个新的表空间。

    +
    +

    注意事项 

    +
    • 只有系统管理员可以创建表空间。
    • 不允许在一个事务块内部执行CREATE TABLESPACE。
    • 执行CREATE TABLESPACE失败,如果内部创建目录(文件)操作成功了就会产生残留的目录(文件),重新创建时需要用户手动清理表空间指定的目录下残留的内容。如果在创建过程中涉及到数据目录下的表空间软连接残留,需要先将软连接的残留文件删除,再重新执行OM相关操作。
    • CREATE TABLESPACE不支持两阶段事务,如果部分节点执行失败,不支持回滚。
    • 创建表空间前的准备工作参考下述参数说明。
    +
    +

    示例 

    +
    --创建表空间。
    +postgres=# CREATE TABLESPACE ds_location1 RELATIVE LOCATION ' tablespace/tablespace_1 ' ; 
    +
    +--创建表空间,且所有者指定为用户joe。
    +postgres=# CREATE TABLESPACE ds_location2 OWNER joe RELATIVE LOCATION ' tablespace/tablespace_1 ' ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    + + 不建议在事务内部创建表空间。

    +]]>
    +
    +
    + +

    功能描述 

    +

    创建新的文本搜索配置。一个文本搜索配置声明一个能将一个字符串划分成符号的文本搜索解析器,加上可以用于确定搜索对哪些标记感兴趣的字典。

    +
    +

    注意事项 

    +
    • 若仅声明分析器,那么新的文本搜索配置初始没有从符号类型到词典的映射, 因此会忽略所有的单词。后面必须调用ALTER TEXT SEARCH CONFIGURATION命令创建映射使配置生效。如果声明了COPY选项,那么会自动拷贝指定的文本搜索配置的解析器、映射、配置选项等信息。
    • 若模式名称已给出,那么文本搜索配置会在声明的模式中创建。否则会在当前模式创建。
    • 定义文本搜索配置的用户成为其所有者。
    • PARSER和COPY选项是互相排斥的,因为当一个现有配置被复制,其分析器配置也被复制了。
    • 若仅声明分析器,那么新的文本搜索配置初始没有从符号类型到词典的映射, 因此会忽略所有的单词。
    +
    +

    示例 

    +
    --创建文本搜索配置。
    +postgres=# CREATE TEXT SEARCH CONFIGURATION ngram2 ( parser=ngram ) WITH ( gram_size = 2 , grapsymbol_ignore = false ) ; 
    +
    +--创建文本搜索配置。
    +postgres=# CREATE TEXT SEARCH CONFIGURATION ngram3 ( copy=ngram2 ) WITH ( gram_size = 2 , grapsymbol_ignore = false ) ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    创建一个新的全文检索词典。词典是一种指定在全文检索时识别特定词并处理的方法。

    +

    词典的创建依赖于预定义模板(在系统表PG_TS_TEMPLATE中定义),支持创建五种类型的词典,分别是Simple、Ispell、Synonym、Thesaurus、以及Snowball,每种类型的词典可以完成不同的任务。

    +
    +

    注意事项 

    +
    • 具有SYSADMIN权限的用户可以执行创建词典操作,创建该词典的用户自动成为其所有者。
    • 临时模式(pg_temp)下不允许创建词典。
    • 创建或修改词典之后,任何对于用户自定义的词典定义文件的修改,将不会影响到数据库中的词典。如果需要在数据库中使用这些修改,需使用ALTER语句更新对应词典的定义文件。
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    创建一个触发器。 触发器将与指定的表或视图关联,并在特定条件下执行指定的函数。

    +
    +

    注意事项 

    +
    • 当前仅支持在普通行存表上创建触发器,不支持在列存表、临时表、unlogged表等类型表上创建触发器。
    • 如果为同一事件定义了多个相同类型的触发器,则按触发器的名称字母顺序触发它们。
    • 触发器常用于多表间数据关联同步场景,对SQL执行性能影响较大,不建议在大数据量同步及对性能要求高的场景中使用。
    +
    +

    示例 

    +
    --创建源表及触发表
    +postgres=# CREATE TABLE test_trigger_src_tbl ( id1 INT , id2 INT , id3 INT ) ; 
    +postgres=# CREATE TABLE test_trigger_des_tbl ( id1 INT , id2 INT , id3 INT ) ; 
    +
    +--创建触发器函数
    +postgres=# CREATE OR REPLACE FUNCTION tri_insert_func ( ) RETURNS TRIGGER AS
    +$$
    +DECLARE
    +BEGIN
    +INSERT INTO test_trigger_des_tbl VALUES ( NEW.id1 , NEW.id2 , NEW.id3 ) ; 
    +RETURN NEW ; 
    +END
    +$$ LANGUAGE PLPGSQL ; 
    +postgres=# CREATE OR REPLACE FUNCTION tri_update_func ( ) RETURNS TRIGGER AS
    +$$
    +DECLARE
    +BEGIN
    +UPDATE test_trigger_des_tbl SET id3 = NEW.id3 WHERE id1=OLD.id1 ; 
    +RETURN OLD ; 
    +END
    +$$ LANGUAGE PLPGSQL ; 
    +postgres=# CREATE OR REPLACE FUNCTION TRI_DELETE_FUNC ( ) RETURNS TRIGGER AS
    +$$
    +DECLARE
    +BEGIN
    +DELETE FROM test_trigger_des_tbl WHERE id1=OLD.id1 ; 
    +RETURN OLD ; 
    +END
    +$$ LANGUAGE PLPGSQL ; 
    +
    +--创建INSERT触发器
    +postgres=# CREATE TRIGGER insert_trigger
    +BEFORE INSERT ON test_trigger_src_tbl
    +FOR EACH ROW
    +EXECUTE PROCEDURE tri_insert_func ( ) ; 
    +
    +--创建UPDATE触发器
    +postgres=# CREATE TRIGGER update_trigger
    +AFTER UPDATE ON test_trigger_src_tbl
    +FOR EACH ROW
    +EXECUTE PROCEDURE tri_update_func ( ) ; 
    +
    +--创建DELETE触发器
    +postgres=# CREATE TRIGGER delete_trigger
    +BEFORE DELETE ON test_trigger_src_tbl
    +FOR EACH ROW
    +EXECUTE PROCEDURE tri_delete_func ( ) ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    在当前数据库中定义一种新的数据类型。定义数据类型的用户将成为该数据类型的拥有者。类型只适用于行存表

    +

    有四种形式的CREATE TYPE分别为:复合类型、基本类型、shell类型和枚举类型。

    +
    • 复合类型

      复合类型由一个属性名和数据类型的列表指定。如果属性的数据类型是可排序的,也可以指定该属性的排序规则。复合类型本质上和表的行类型相同,但是如果只想定义一种类型,使用CREATE TYPE避免了创建一个实际的表。单独的复合类型也是很有用的,例如可以作为函数的参数或者返回类型。

      +

      为了能够创建复合类型,必须拥有在其所有属性类型上的USAGE特权。

      +
    • 基本类型

      用户可以自定义一种新的基本类型(标量类型)。通常来说这些函数必须是底层语言所编写。

      +
    • shell类型

      shell类型是一种用于后面要定义的类型的占位符,通过发出一个不带除类型名之外其他参数的CREATE TYPE命令可以创建这种类型。在创建基本类型时,需要shell类型作为一种向前引用

      +
    • 枚举类型

      由若干个标签构成的列表,每一个标签值都是一个非空字符串,且字符串长度必须不超过64个字节。

      +
    +
    +

    注意事项 

    +

    如果给定一个模式名,那么该类型将被创建在指定的模式中。否则它会被创建在当前模式中。类型名称必须与同一个模式中任何现有的类型或者域相区别(因为表具有相关的数据类型,类型名称也必须与同一个模式中任何现有表的名称不同)

    +
    +

    示例 

    +
    --创建一种复合类型,建表并插入数据以及查询。
    +postgres=# CREATE TYPE compfoo AS ( f1 int , f2 text ) ; 
    +postgres=# CREATE TABLE t1_compfoo ( a int , b compfoo ) ; 
    +postgres=# CREATE TABLE t2_compfoo ( a int , b compfoo ) ; 
    +postgres=# INSERT INTO t1_compfoo values ( 1 , ( 1 , ' demo ' ) ) ; 
    +postgres=# INSERT INTO t2_compfoo select * from t1_typ5 ; 
    +postgres=# SELECT ( b ) .f1 FROM t1_compfoo ; 
    +postgres=# SELECT * FROM t1_compfoo t1 join t2_compfoo t2 on ( t1.b ) .f1= ( t1.b ) .f1 ; 
    +
    +--要改变一个用户定义类型compfoo1的所有者为usr1。
    +postgres=# CREATE USER usr1 PASSWORD ' Bigdata@123 ' ; 
    +postgres=# ALTER TYPE compfoo1 OWNER TO usr1 ; 
    +
    +--创建一个枚举类型。
    +postgres=# CREATE TYPE bugstatus AS ENUM ( ' create ' , ' modify ' , ' closed ' ) ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    创建一个用户。

    +
    +

    注意事项 

    +
    • 通过CREATE USER创建的用户,默认具有LOGIN权限;
    • 通过CREATE USER创建用户的同时系统会在执行该命令的数据库中,为该用户创建一个同名的SCHEMA;其他数据库中,则不自动创建同名的SCHEMA;用户可使用CREATE SCHEMA命令,分别在其他数据库中,为该用户创建同名SCHEMA。
    • 系统管理员在普通用户同名schema下创建的对象,所有者为schema的同名用户(非系统管理员)。
    +
    +

    示例 

    +
    --创建用户jim,登录密码为Bigdata@123。
    +postgres=# CREATE USER jim PASSWORD ' Bigdata@123 ' ; 
    +
    +--下面语句与上面的等价。
    +postgres=# CREATE USER kim IDENTIFIED BY ' Bigdata@123 ' ; 
    +
    +--如果创建有“创建数据库”权限的用户,则需要加CREATEDB关键字。
    +postgres=# CREATE USER dim CREATEDB PASSWORD ' Bigdata@123 ' ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    创建一个视图。视图与基本表不同,是一个虚拟的表。数据库中仅存放视图的定义,而不存放视图对应的数据,这些数据仍存放在原来的基本表中。若基本表中的数据发生变化,从视图中查询出的数据也随之改变。从这个意义上讲,视图就像一个窗口,透过它可以看到数据库中用户感兴趣的数据及变化。

    +
    +

    示例 

    +
    --创建字段spcname为pg_default组成的视图。
    +postgres=# CREATE VIEW myView AS
    +SELECT * FROM pg_tablespace WHERE spcname = ' pg_default ' ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    CURSOR命令定义一个游标,用于在一个大的查询里面检索少数几行数据。

    +

    为了处理SQL语句,存储过程进程分配一段内存区域来保存上下文联系。游标是指向上下文区域的句柄或指针。借助游标,存储过程可以控制上下文区域的变化。

    +
    +

    注意事项 

    +
    • 游标命令只能在事务块里使用。
    • 通常游标和SELECT一样返回文本格式。因为数据在系统内部是用二进制格式存储的,系统必须对数据做一定转换以生成文本格式。一旦数据是以文本形式返回,客户端应用需要把它们转换成二进制进行操作。使用FETCH语句,游标可以返回文本或二进制格式。
    • 应该小心使用二进制游标。文本格式一般都比对应的二进制格式占用的存储空间大。二进制游标返回内部二进制形态的数据,可能更易于操作。如果想以文本方式显示数据,则以文本方式检索会为用户节约很多客户端的工作。比如,如果查询从某个整数列返回1,在缺省的游标里将获得一个字符串1,但在二进制游标里将得到一个4字节的包含该数值内部形式的数值(大端顺序)。
    +
    +

    示例 

    +
    --建立一个名为cursor1的游标。
    +postgres=# CURSOR cursor1 FOR SELECT * FROM tpcds.customer_address ORDER BY 1 ; 
    +
    +--抓取头3行到游标cursor1里。
    +postgres=# FETCH FORWARD 3 FROM cursor1 ; 
    +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type
    +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+----------------------
    +1 | AAAAAAAABAAAAAAA | 18 | Jackson | Parkway | Suite 280 | Fairfield | Maricopa County | AZ | 86192 | United States | -7.00 | condo
    +2 | AAAAAAAACAAAAAAA | 362 | Washington 6th | RD | Suite 80 | Fairview | Taos County | NM | 85709 | United States | -7.00 | condo
    +3 | AAAAAAAADAAAAAAA | 585 | Dogwood Washington | Circle | Suite Q | Pleasant Valley | York County | PA | 12477 | United States | -5.00 | single family
    + ( 3 rows ) 
    +
    +--关闭游标并提交事务。
    +postgres=# CLOSE cursor1 ; 
    +
    +--建立一个名为cursor2的游标。
    +postgres=# CURSOR cursor2 FOR VALUES ( 1 , 2 ) , ( 0 , 3 ) ORDER BY 1 ; 
    +
    +--抓取头2行到游标cursor2里。
    +postgres=# FETCH FORWARD 2 FROM cursor2 ; 
    +column1 | column2
    +---------+---------
    +0 | 3
    +1 | 2
    + ( 2 rows ) 
    +
    +--关闭游标并提交事务。
    +postgres=# CLOSE cursor2 ; 
    +
    +--创建一个with hold游标。
    +postgres=# DECLARE cursor1 CURSOR WITH HOLD FOR SELECT * FROM tpcds.customer_address ORDER BY 1 ; 
    +
    +--抓取头2行到游标cursor1里。
    +postgres=# FETCH FORWARD 2 FROM cursor1 ; 
    +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type
    +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+----------------------
    +1 | AAAAAAAABAAAAAAA | 18 | Jackson | Parkway | Suite 280 | Fairfield | Maricopa County | AZ | 86192 | United States | -7.00 | condo
    +2 | AAAAAAAACAAAAAAA | 362 | Washington 6th | RD | Suite 80 | Fairview | Taos County | NM | 85709 | United States | -7.00 | condo
    + ( 2 rows ) 
    +
    +--抓取下一行到游标cursor1里。
    +postgres=# FETCH FORWARD 1 FROM cursor1 ; 
    +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type
    +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+----------------------
    +3 | AAAAAAAADAAAAAAA | 585 | Dogwood Washington | Circle | Suite Q | Pleasant Valley | York County | PA | 12477 | United States | -5.00 | single family
    + ( 1 row ) 
    +
    +--关闭游标。
    +postgres=# CLOSE cursor1 ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    DEALLOCATE用于删除前面编写的预备语句。如果用户没有明确删除一个预备语句,那么它将在会话结束的时候被删除。

    +

    PREPARE关键字总被忽略。

    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    DECLARE命令既可以定义一个游标,用于在一个大的查询里面检索少数几行数据,也可以作为一个匿名块的开始。

    +

    本节主要描述定义为游标的用法,开启匿名块的用法见BEGIN

    +

    为了处理SQL语句,存储过程进程分配一段内存区域来保存上下文联系。游标是指向上下文区域的句柄或指针。借助游标,存储过程可以控制上下文区域的变化。

    +

    通常游标和SELECT一样返回文本格式。因为数据在系统内部是用二进制格式存储的,系统必须对数据做一定转换以生成文本格式。一旦数据是以文本形式返回,客户端应用需要把它们转换成二进制进行操作。使用FETCH语句,游标可以返回文本或二进制格式。

    +
    +

    注意事项 

    +
    • 游标命令只能在事务块里使用。
    • 应该小心使用二进制游标。文本格式一般都比对应的二进制格式占用的存储空间大。二进制游标返回内部二进制形态的数据,可能更易于操作。如果想以文本方式显示数据,则以文本方式检索会为用户节约很多客户端的工作。比如,如果查询从某个整数列返回1,在缺省的游标里将获得一个字符串1,但在二进制游标里将得到一个4字节的包含该数值内部形式的数值(大端顺序)。
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    DELETE从指定的表里删除满足WHERE子句的行。如果WHERE子句不存在,将删除表中所有行,结果只保留表结构。

    +
    +

    注意事项 

    +
    • 要删除表中的数据,用户必须对它有DELETE权限。同样也必须有USING子句引用的表以及condition上读取的表的SELECT权限。
    • 对于行存复制表,仅支持有主键约束场景下的delete操作。
    • 对于列存表,暂时不支持RETURNING子句。
    +
    +

    示例 

    +
    --删除tpcds.customer_address_bak中ca_address_sk小于14888的职员。
    +postgres=# DELETE FROM tpcds.customer_address_bak WHERE ca_address_sk < 14888 ; 
    +
    +--删除tpcds.customer_address_bak中所有数据。
    +postgres=# DELETE FROM tpcds.customer_address_bak ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    + + 如果要删除表中的所有记录,建议使用truncate语法。

    +]]>
    +
    +
    + +

    功能描述 

    +

    执行匿名代码块。

    +

    代码块被看做是没有参数的一段函数体,返回值类型是void。它的解析和执行是同一时刻发生的。

    +
    +

    注意事项 

    +
    • 程序语言在使用之前,必须通过命令CREATE LANGUAGE安装到当前的数据库中。 plpgsql是默认的安装语言,其它语言安装时必须指定。
    • 如果语言是不受信任的,用户必须有使用程序语言的USAGE权限,或者是系统管理员。
    +
    +

    示例 

    +
    --授予用户webuser对模式tpcds下视图的所有操作权限。
    +postgres=# DO $$DECLARE r record ; 
    +BEGIN
    +FOR r IN SELECT c.relname table_name , n.nspname table_schema FROM pg_class c , pg_namespace n
    +WHERE c.relnamespace = n.oid AND n.nspname = ' tpcds ' AND relkind IN ( ' r ' , ' v ' ) 
    +LOOP
    +EXECUTE ' GRANT ALL ON ' || quote_ident ( r.table_schema ) || ' . ' || quote_ident ( r.table_name ) || ' TO webuser ' ; 
    +END LOOP ; 
    +END$$ ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    删除一个数据库。

    +
    +

    注意事项 

    +
    • 只有数据库所有者有权限执行DROP DATABASE命令,系统管理员默认拥有此权限。
    • 不能对系统默认安装的三个数据库(POSTGRES、TEMPLATE0和TEMPLATE1)执行删除操作,系统做了保护。如果想查看当前服务中有哪几个数据库,可以用gsql的\l命令查看。
    • 如果有用户正在与要删除的数据库连接,则删除操作失败。
    • 不能在事务块中执行DROP DATABASE命令。
    • 如果执行DROP DATABASE失败,事务回滚,需要再次执行一次DROP DATABASE IF EXISTS。
    +

    DROP DATABASE一旦执行将无法撤销,请谨慎使用。

    +
    +
    +

    示例 

    +
    --删除数据库。
    +postgres=# DROP DATABASE music2 ; 
    +

    语法格式 

    + +

    参数说明 

    +]]>
    + + 不支持在事务中删除database。

    +]]>
    +
    +
    + +

    功能描述 

    +

    删除一个Data Source对象。

    +
    +

    注意事项 

    +

    只有属主/系统管理员/初始用户才可以删除一个Data Source对象。

    +
    +

    示例 

    +
    --删除Data Source对象。
    +postgres=# DROP DATA SOURCE ds_tst1 CASCADE ; 
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    删除指定的directory对象。

    +
    +

    注意事项 

    +

    默认只有初始化用户可以执行drop操作,当enable_access_server_directory开启时(可参考enable_access_server_directory),sysadmin权限的用户也可以执行drop操作。

    +
    +

    示例 

    +
    --删除目录。
    +postgres=# DROP DIRECTORY dir ; 
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    删除一个已存在的函数。

    +
    +

    注意事项 

    +

    如果函数中涉及对临时表相关操作,则无法使用DROP FUNCTION删除函数。

    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    删除用户组。

    +

    DROP GROUP是DROP ROLE的别名。

    +
    +

    注意事项 

    +

    DROP GROUP是openGauss管理工具封装的内部接口,用来实现openGauss管理。该接口不建议用户直接使用,以免对openGauss状态造成影响。

    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    删除索引。

    +
    +

    注意事项 

    +

    只有索引的所有者有权限执行DROP INDEX命令,系统管理员默认拥有此权限。

    +
    +

    示例 

    +
    --删除一个现有的索引。
    +postgres=# DROP INDEX tpcds.ds_ship_mode_t1_index2 ; 
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    删除一个数据库角色所拥有的数据库对象。

    +
    +

    注意事项 

    +
    • 所有该角色在当前数据库里和共享对象(数据库,表空间) 上的所有对象上的权限都将被撤销。
    • DROP OWNED常常被用来为移除一个或者多个角色做准备。因为DROP OWNED只影响当前数据库中的对象,通常需要在包含将被移除角色所拥有的对象的每一个数据库中都执行这个命令。
    • 使用CASCADE选项可能导致这个命令递归去删除由其他用户所拥有的对象。
    • 角色所拥有的数据库、表空间将不会被移除。
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    删除表上某个行访问控制策略。

    +
    +

    注意事项 

    +

    仅表的所有者或者管理员用户才能删除表的行访问控制策略。

    +
    +

    示例 

    +
    --删除行访问控制策略
    +postgres=# DROP ROW LEVEL SECURITY POLICY all_data_rls ON all_data ; 
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    删除已存在的存储过程。

    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    删除指定的角色。

    +
    +

    示例 

    +
    --删除角色manager。
    +postgres=# DROP ROLE manager ; 
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    从数据库中删除模式。

    +
    +

    注意事项 

    +

    只有模式的所有者有权限执行DROP SCHEMA命令,系统管理员默认拥有此权限。

    +
    +

    示例 

    +
    --删除schema。
    +postgres=# DROP SCHEMA role1 CASCADE ; 
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    从当前数据库里删除序列。

    +
    +

    注意事项 

    +

    只有序列的所有者或者系统管理员才能删除。

    +
    +

    示例 

    +
    --删除序列。
    +postgres=# DROP SEQUENCE serial ; 
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    删除指定的SYNONYM对象。

    +
    +

    注意事项 

    +

    只有SYNONYM的所有者有权限执行DROP SYNONYM命令,系统管理员默认拥有此权限。

    +
    +

    示例 

    +
    --删除同义词。
    +postgres=# DROP SYNONYM t1 ; 
    +

    语法格式 

    +]]>
    +
    + +

    功能描述 

    +

    删除指定的表。

    +
    +

    注意事项 

    +

    DROP TABLE会强制删除指定的表,删除表后,依赖该表的索引会被删除,而使用到该表的函数和存储过程将无法执行。删除分区表,会同时删除分区表中的所有分区。

    +
    +

    示例 

    +
    --删除表空间、模式joe和模式表warehouse。
    +postgres=# DROP TABLE tpcds.warehouse_t1 ; 
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    删除一个表空间。

    +
    +

    注意事项 

    +
    • 只有表空间所有者有权限执行DROP TABLESPACE命令,系统管理员默认拥有此权限。
    • 在删除一个表空间之前,表空间里面不能有任何数据库对象,否则会报错。
    • DROP TABLESPACE不支持回滚,因此,不能出现在事务块内部。
    • 执行DROP TABLESPACE操作时,如果有另外的会话执行\db查询操作,可能会由于tablespace事务的原因导致查询失败,请重新执行\db查询操作。
    • 如果执行DROP TABLESPACE失败,需要再次执行一次DROP TABLESPACE IF EXISTS。
    +
    +

    示例 

    +
    --删除表空间。
    +postgres=# DROP TABLESPACE ds_location2 ; 
    +

    语法格式 

    + +

    参数说明 

    +]]>
    + + 不支持在事务中删除database。

    +]]>
    +
    +
    + +

    功能描述 

    +

    删除已有文本搜索配置。

    +
    +

    注意事项 

    +

    要执行这个命令,用户必须是该配置的所有者。

    +
    +

    示例 

    +
    --删除文本搜索配置。
    +postgres=# DROP TEXT SEARCH CONFIGURATION joe.ngram_2 ; 
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    删除全文检索词典。

    +
    +

    注意事项 

    +
    • 预定义词典不支持DROP操作。
    • 只有词典的所有者可以执行DROP操作,系统管理员默认拥有此权限。
    • 谨慎执行DROP...CASCADE操作,该操作将级联删除使用该词典的文本搜索配置(TEXT SEARCH CONFIGURATION)。
    +
    +

    示例 

    +
    --删除词典english
    +DROP TEXT SEARCH DICTIONARY english ; 
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    删除触发器。

    +
    +

    注意事项 

    +

    只有触发器的所有者可以执行DROP TRIGGER操作,系统管理员默认拥有此权限。

    +
    +

    示例 

    +
    --删除触发器
    +postgres=# DROP TRIGGER insert_trigger ON test_trigger_src_tbl ; 
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    删除一个用户定义的数据类型。只有类型所有者才有删除权限。

    +
    +

    示例 

    +
    --删除compfoo1类型。
    +postgres=# DROP TYPE usr1.compfoo1 cascade ; 
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    删除用户,同时会删除同名的schema。

    +
    +

    注意事项 

    +
    • 须使用CASCADE级联删除依赖用户的对象(除数据库外)。当删除用户的级联对象时,如果级联对象处于锁定状态,则此级联对象无法被删除,直到对象被解锁或锁定级联对象的进程被杀死。
    • openGauss中,存在一个配置参数enable_kill_query,此参数在配置文件postgresql.conf中。此参数影响级联删除用户对象的行为:
      • 当参数enable_kill_query为on ,且使用CASCADE模式删除用户时,会自动kill锁定用户级联对象的进程,并删除用户。
      • 当参数enable_kill_query为off,且使用CASCADE模式删除用户时,会等待锁定级联对象的进程结束之后再删除用户。
      +
    • 在数据库中删除用户时,如果依赖用户的对象在其他数据库中或者依赖用户的对象是其他数据库,请用户先手动删除其他数据库中的依赖对象或直接删除依赖数据库,再删除用户。即drop user不支持跨数据库进行级联删除。
    • 如果该用户被DATA SOURCE对象依赖时,无法直接级联删除该用户,需要手动删除对应的DATA SOURCE对象之后再删除该用户。
    +
    +

    示例 

    +
    --删除用户。
    +postgres=# DROP USER kim CASCADE ; 
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    数据库中强制删除已有的视图。

    +
    +

    注意事项 

    +

    只有视图的所有者有权限执行DROP VIEW的命令,系统管理员默认拥有此权限。

    +
    +

    示例 

    +
    --删除视图myView。
    +postgres=# DROP VIEW myView ; 
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    执行一个前面准备好的预备语句。因为一个预备语句只在会话的生命期里存在,那么预备语句必须是在当前会话的前些时候用PREPARE语句创建的。

    +
    +

    注意事项 

    +

    如果创建预备语句的PREPARE语句声明了一些参数,那么传递给EXECUTE语句的必须是一个兼容的参数集,否则就会生成一个错误。

    +
    +

    示例 

    +
    --为一个INSERT语句创建一个预备语句然后执行它。
    +postgres=# PREPARE insert_reason ( integer , character ( 16 ) , character ( 100 ) ) AS INSERT INTO tpcds.reason_t1 VALUES ( $1 , $2 , $3 ) ; 
    +postgres=# EXECUTE insert_reason ( 52 , ' AAAAAAAADDAAAAAA ' , ' reason 52 ' ) ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    显示SQL语句的执行计划。

    +

    执行计划将显示SQL语句所引用的表会采用什么样的扫描方式,如:简单的顺序扫描、索引扫描等。如果引用了多个表,执行计划还会显示用到的JOIN算法。

    +

    执行计划的最关键的部分是语句的预计执行开销,这是计划生成器估算执行该语句将花费多长的时间。

    +

    若指定了ANALYZE选项,则该语句会被执行,然后根据实际的运行结果显示统计数据,包括每个计划节点内时间总开销(毫秒为单位)和实际返回的总行数。这对于判断计划生成器的估计是否接近现实非常有用。

    +
    +

    注意事项 

    +

    在指定ANALYZE选项时,语句会被执行。如果用户想使用EXPLAIN分析INSERT,UPDATE,DELETE,CREATE TABLE AS或EXECUTE语句,而不想改动数据(执行这些语句会影响数据),请使用这种方法:

    +
    START TRANSACTION;
    +EXPLAIN ANALYZE ...;
    +ROLLBACK;
    +
    +

    示例 

    +
    --修改explain_perf_mode为normal
    +postgres=# SET explain_perf_mode=normal ; 
    +
    +--显示表简单查询的执行计划。
    +postgres=# EXPLAIN SELECT * FROM tpcds.customer_address_p1 ; 
    +QUERY PLAN
    +--------------------------------------------------
    +Data Node Scan ( cost=0.00..0.00 rows=0 width=0 ) 
    +Node/s: All dbnodes
    + ( 2 rows ) 
    +
    +--以JSON格式输出的执行计划(explain_perf_mode为normal时)。
    +postgres=# EXPLAIN ( FORMAT JSON ) SELECT * FROM tpcds.customer_address_p1 ; 
    +QUERY PLAN
    +--------------------------------------
    +[ +
    +{ +
    +"Plan": { +
    +"Node Type": "Data Node Scan" , +
    +"Startup Cost": 0.00 , +
    +"Total Cost": 0.00 , +
    +"Plan Rows": 0 , +
    +"Plan Width": 0 , +
    +"Node/s": "All dbnodes" +
    +} +
    +} +
    +]
    + ( 1 row ) 
    +
    +--如果有一个索引,当使用一个带索引WHERE条件的查询,可能会显示一个不同的计划。
    +postgres=# EXPLAIN SELECT * FROM tpcds.customer_address_p1 WHERE ca_address_sk=10000 ; 
    +QUERY PLAN
    +--------------------------------------------------
    +Data Node Scan ( cost=0.00..0.00 rows=0 width=0 ) 
    +Node/s: dn_6005_6006
    + ( 2 rows ) 
    +
    +--以YAML格式输出的执行计划(explain_perf_mode为normal时)。
    +postgres=# EXPLAIN ( FORMAT YAML ) SELECT * FROM tpcds.customer_address_p1 WHERE ca_address_sk=10000 ; 
    +QUERY PLAN
    +---------------------------------
    +- Plan: +
    +Node Type: "Data Node Scan"+
    +Startup Cost: 0.00 +
    +Total Cost: 0.00 +
    +Plan Rows: 0 +
    +Plan Width: 0 +
    +Node/s: "dn_6005_6006"
    + ( 1 row ) 
    +
    +--禁止开销估计的执行计划。
    +postgres=# EXPLAIN ( COSTS FALSE ) SELECT * FROM tpcds.customer_address_p1 WHERE ca_address_sk=10000 ; 
    +QUERY PLAN
    +------------------------
    +Data Node Scan
    +Node/s: dn_6005_6006
    + ( 2 rows ) 
    +
    +--带有聚集函数查询的执行计划。
    +postgres=# EXPLAIN SELECT SUM ( ca_address_sk ) FROM tpcds.customer_address_p1 WHERE ca_address_sk<10000 ; 
    +QUERY PLAN
    +---------------------------------------------------------------------------------------
    +Aggregate ( cost=18.19..14.32 rows=1 width=4 ) 
    +-> Streaming ( type: GATHER ) ( cost=18.19..14.32 rows=3 width=4 ) 
    +Node/s: All dbnodes
    +-> Aggregate ( cost=14.19..14.20 rows=3 width=4 ) 
    +-> Seq Scan on customer_address_p1 ( cost=0.00..14.18 rows=10 width=4 ) 
    +Filter: ( ca_address_sk < 10000 ) 
    + ( 6 rows ) 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    通过EXPLAIN PLAN命令可以将查询执行的计划信息存储于PLAN_TABLE表中。与EXPLAIN命令不同的是,EXPLAIN PLAN仅将计划信息进行存储,而不会打印到屏幕。

    +
    +

    注意事项 

    +
    • EXPLAIN PLAN不支持在数据库节点上执行。
    • 对于执行错误的SQL无法进行计划信息的收集。
    • PLAN_TABLE中的数据是session级生命周期并且session隔离和用户隔离,用户只能看到当前session、当前用户的数据。
    +
    +

    示例 

    +
    explain plan set statement_id= ' TPCH-Q4 ' for
    +select
    +o_orderpriority , 
    +count ( * ) as order_count
    +from
    +orders
    +where
    +o_orderdate >= ' 1993-07-01 ' ::date
    +and o_orderdate < ' 1993-07-01 ' ::date + interval ' 3 month ' 
    +and exists ( 
    +select
    +*
    +from
    +lineitem
    +where
    +l_orderkey = o_orderkey
    +and l_commitdate < l_receiptdate
    + ) 
    +group by
    +o_orderpriority
    +order by
    +o_orderpriority ; 
    +查询PLAN_TABLE。SELECT * FROM PLAN_TABLE ; 
    +清理PLAN_TABLE表中的数据。DELETE FROM PLAN_TABLE WHERE xxx ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    FETCH通过已创建的游标来检索数据。

    +

    每个游标都有一个供FETCH使用的关联位置。游标的关联位置可以在查询结果的第一行之前,或者在结果中的任意行,或者在结果的最后一行之后:

    +
    • 游标刚创建完之后,关联位置在第一行之前的。
    • 在抓取了一些移动行之后,关联位置在检索到的最后一行上。
    • 如果FETCH抓取完了所有可用行,它就停在最后一行后面,或者在反向抓取的情况下是停在第一行前面。
    • FETCH ALL或FETCH BACKWARD ALL将总是把游标的关联位置放在最后一行或者在第一行前面。
    +
    +

    注意事项 

    +
    • 如果游标定义了NO SCROLL,则不允许使用例如FETCH BACKWARD之类的反向抓取。
    • NEXT,PRIOR,FIRST,LAST,ABSOLUTE,RELATIVE形式在恰当地移动游标之后抓取一条记录。如果后面没有数据行,就返回一个空的结果,此时游标就会停在查询结果的最后一行之后(向后查询时)或者第一行之前(向前查询时)。
    • FORWARD和BACKWARD形式在向前或者向后移动的过程中抓取指定的行数,然后把游标定位在最后返回的行上;或者是,如果count大于可用的行数,则在所有行之后(向后查询时)或者之前(向前查询时)。
    • RELATIVE 0,FORWARD 0,BACKWARD 0都要求在不移动游标的前提下抓取当前行,也就是重新抓取最近刚抓取过的行。除非游标定位在第一行之前或者最后一行之后,这个动作都应该成功,而在那两种情况下,不返回任何行。
    • 当FETCH的游标上涉及列存表时,不支持BACKWARD、PRIOR、FIRST等涉及反向获取操作。
    +
    +

    示例 

    +
    --抓取头3行到游标cursor1里。
    +postgres=# FETCH FORWARD 3 FROM cursor1 ; 
    +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type
    +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+----------------------
    +1 | AAAAAAAABAAAAAAA | 18 | Jackson | Parkway | Suite 280 | Fairfield | Maricopa County | AZ | 86192 | United States | -7.00 | condo
    +2 | AAAAAAAACAAAAAAA | 362 | Washington 6th | RD | Suite 80 | Fairview | Taos County | NM | 85709 | United States | -7.00 | condo
    +3 | AAAAAAAADAAAAAAA | 585 | Dogwood Washington | Circle | Suite Q | Pleasant Valley | York County | PA | 12477 | United States | -5.00 | single family
    + ( 3 rows ) 
    +
    +--抓取头2行到游标cursor2里。
    +postgres=# FETCH FORWARD 2 FROM cursor2 ; 
    +column1 | column2
    +---------+---------
    +0 | 3
    +1 | 2
    + ( 2 rows ) 
    +
    +--抓取头2行到游标cursor1里。
    +postgres=# FETCH FORWARD 2 FROM cursor1 ; 
    +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type
    +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+----------------------
    +1 | AAAAAAAABAAAAAAA | 18 | Jackson | Parkway | Suite 280 | Fairfield | Maricopa County | AZ | 86192 | United States | -7.00 | condo
    +2 | AAAAAAAACAAAAAAA | 362 | Washington 6th | RD | Suite 80 | Fairview | Taos County | NM | 85709 | United States | -7.00 | condo
    + ( 2 rows ) 
    +
    +--抓取下一行到游标cursor1里。
    +postgres=# FETCH FORWARD 1 FROM cursor1 ; 
    +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type
    +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+----------------------
    +3 | AAAAAAAADAAAAAAA | 585 | Dogwood Washington | Circle | Suite Q | Pleasant Valley | York County | PA | 12477 | United States | -5.00 | single family
    + ( 1 row ) 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    对角色和用户进行授权操作。

    +

    使用GRANT命令进行用户授权包括以下三种场景:

    +
    • 将系统权限授权给角色或用户

      系统权限又称为用户属性,包括SYSADMIN、CREATEDB、CREATEROLE、AUDITADMIN和LOGIN。

      +

      系统权限一般通过CREATE/ALTER ROLE语法来指定。其中,SYSADMIN权限可以通过GRANT/REVOKE ALL PRIVILEGE授予或撤销。但系统权限无法通过ROLE和USER的权限被继承,也无法授予PUBLIC。

      +
    • 将数据库对象授权给角色或用户

      将数据库对象(表和视图、指定字段、数据库、函数、模式、表空间等)的相关权限授予特定角色或用户;

      +

      GRANT命令将数据库对象的特定权限授予一个或多个角色。这些权限会追加到已有的权限上。

      +

      关键字PUBLIC表示该权限要赋予所有角色,包括以后创建的用户。PUBLIC可以看做是一个隐含定义好的组,它总是包括所有角色。任何角色或用户都将拥有通过GRANT直接赋予的权限和所属的权限,再加上PUBLIC的权限。

      +

      如果声明了WITH GRANT OPTION,则被授权的用户也可以将此权限赋予他人,否则就不能授权给他人。这个选项不能赋予PUBLIC,这是openGauss特有的属性。

      +

      openGauss会将某些类型的对象上的权限授予PUBLIC。默认情况下,对表、表字段、序列、外部数据源、外部服务器、模式或表空间对象的权限不会授予PUBLIC,而以下这些对象的权限会授予PUBLIC:数据库的CONNECT权限和CREATE TEMP TABLE权限、函数的EXECUTE特权、语言和数据类型(包括域)的USAGE特权。当然,对象拥有者可以撤销默认授予PUBLIC的权限并专门授予权限给其他用户。为了更安全,建议在同一个事务中创建对象并设置权限,这样其他用户就没有时间窗口使用该对象。另外,这些初始的默认权限可以使用ALTER DEFAULT PRIVILEGES命令修改。

      +
    • 将角色或用户的权限授权给其他角色或用户

      将一个角色或用户的权限授予一个或多个其他角色或用户。在这种情况下,每个角色或用户都可视为拥有一个或多个数据库权限的集合。

      +

      当声明了WITH ADMIN OPTION,被授权的用户可以将该权限再次授予其他角色或用户,以及撤销所有由该角色或用户继承到的权限。当授权的角色或用户发生变更或被撤销时,所有继承该角色或用户权限的用户拥有的权限都会随之发生变更。

      +

      数据库系统管理员可以给任何角色或用户授予/撤销任何权限。拥有CREATEROLE权限的角色可以赋予或者撤销任何非系统管理员角色的权限。

      +
    +
    +

    示例 

    +
    postgres=# CREATE USER joe PASSWORD ' Bigdata@123 ' ; 
    +postgres=# GRANT ALL PRIVILEGES TO joe ; 
    +授权成功后,用户joe会拥有sysadmin的所有权限。
    +示例:将对象权限授权给用户或者角色。
    +撤销joe用户的sysadmin权限,然后将模式tpcds的使用权限和表tpcds.reason的所有权限授权给用户joe。postgres=# REVOKE ALL PRIVILEGES FROM joe ; 
    +postgres=# GRANT USAGE ON SCHEMA tpcds TO joe ; 
    +postgres=# GRANT ALL PRIVILEGES ON tpcds.reason TO joe ; 
    +授权成功后,joe用户就拥有了tpcds.reason表的所有权限,包括增删改查等权限。
    +将tpcds.reason表中r_reason_sk、r_reason_id、r_reason_desc列的查询权限,r_reason_desc的更新权限授权给joe。postgres=# GRANT select ( r_reason_sk , r_reason_id , r_reason_desc ) , update ( r_reason_desc ) ON tpcds.reason TO joe ; 
    +授权成功后,用户joe对tpcds.reason表中r_reason_sk,r_reason_id的查询权限会立即生效。如果joe用户需要拥有将这些权限授权给其他用户的权限,可以通过以下语法对joe用户进行授权。
    +postgres=# GRANT select ( r_reason_sk , r_reason_id ) ON tpcds.reason TO joe WITH GRANT OPTION ; 
    +将数据库postgres的连接权限授权给用户joe,并给予其在postgres中创建schema的权限,而且允许joe将此权限授权给其他用户。
    +postgres=# GRANT create , connect on database postgres TO joe WITH GRANT OPTION ; 
    +创建角色tpcds_manager,将模式tpcds的访问权限授权给角色tpcds_manager,并授予该角色在tpcds下创建对象的权限,不允许该角色中的用户将权限授权给其他人。
    +postgres=# CREATE ROLE tpcds_manager PASSWORD ' Bigdata@123 ' ; 
    +postgres=# GRANT USAGE , CREATE ON SCHEMA tpcds TO tpcds_manager ; 
    +将表空间tpcds_tbspc的所有权限授权给用户joe,但用户joe无法将权限继续授予其他用户。
    +postgres=# CREATE TABLESPACE tpcds_tbspc RELATIVE LOCATION ' tablespace/tablespace_1 ' ; 
    +postgres=# GRANT ALL ON TABLESPACE tpcds_tbspc TO joe ; 
    +示例:将用户或者角色的权限授权给其他用户或角色。
    +创建角色manager,将joe的权限授权给manager,并允许该角色将权限授权给其他人。postgres=# CREATE ROLE manager PASSWORD ' Bigdata@123 ' ; 
    +postgres=# GRANT joe TO manager WITH ADMIN OPTION ; 
    +创建用户senior_manager,将用户manager的权限授权给该用户。postgres=# CREATE ROLE senior_manager PASSWORD ' Bigdata@123 ' ; 
    +postgres=# GRANT manager TO senior_manager ; 
    +撤销权限,并清理用户。postgres=# REVOKE manager FROM joe ; 
    +postgres=# REVOKE senior_manager FROM manager ; 
    +postgres=# DROP USER manager ; 
    +示例:撤销上述授予的权限,并清理角色和用户。
    +postgres=# REVOKE ALL PRIVILEGES ON tpcds.reason FROM joe ; 
    +postgres=# REVOKE ALL PRIVILEGES ON SCHEMA tpcds FROM joe ; 
    +postgres=# REVOKE ALL ON TABLESPACE tpcds_tbspc FROM joe ; 
    +postgres=# DROP TABLESPACE tpcds_tbspc ; 
    +postgres=# REVOKE USAGE , CREATE ON SCHEMA tpcds FROM tpcds_manager ; 
    +postgres=# DROP ROLE tpcds_manager ; 
    +postgres=# DROP ROLE senior_manager ; 
    +postgres=# DROP USER joe CASCADE ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    向表中添加一行或多行数据。

    +
    +

    注意事项 

    +
    • 只有拥有表INSERT权限的用户,才可以向表中插入数据。
    • 如果使用RETURNING子句,用户必须要有该表的SELECT权限。
    • 如果使用ON DUPLICATE KEY UPDATE,用户必须要有该表的SELECT、UPDATE权限,唯一约束(主键或唯一索引)的SELECT权限。
    • 如果使用query子句插入来自查询里的数据行,用户还需要拥有在查询里使用的表的SELECT权限。
    • 当连接到TD兼容的数据库时,td_compatible_truncation参数设置为on时,将启用超长字符串自动截断功能,在后续的insert语句中(不包含外表的场景下),对目标表中char和varchar类型的列上插入超长字符串时,系统会自动按照目标表中相应列定义的最大长度对超长字符串进行截断。

      如果向字符集为字节类型编码(SQL_ASCII,LATIN1等)的数据库中插入多字节字符数据(如汉字等),且字符数据跨越截断位置,这种情况下,按照字节长度自动截断,自动截断后会在尾部产生非预期结果。如果用户有对于截断结果正确性的要求,建议用户采用UTF8等能够按照字符截断的输入字符集作为数据库的编码集。

      +
      +
    +
    +

    示例 

    +
    --向表中插入一条记录。
    +postgres=# INSERT INTO tpcds.reason_t2 ( r_reason_sk , r_reason_id , r_reason_desc ) VALUES ( 1 , ' AAAAAAAABAAAAAAA ' , ' reason1 ' ) ; 
    +
    +--向表中插入一条记录,和上一条语法等效。
    +postgres=# INSERT INTO tpcds.reason_t2 VALUES ( 2 , ' AAAAAAAABAAAAAAA ' , ' reason2 ' ) ; 
    +
    +--向表中插入多条记录。
    +postgres=# INSERT INTO tpcds.reason_t2 VALUES ( 3 , ' AAAAAAAACAAAAAAA ' , ' reason3 ' ) , ( 4 , ' AAAAAAAADAAAAAAA ' , ' reason4 ' ) , ( 5 , ' AAAAAAAAEAAAAAAA ' , ' reason5 ' ) ; 
    +
    +--向表中插入tpcds.reason中r_reason_sk小于5的记录。
    +postgres=# INSERT INTO tpcds.reason_t2 SELECT * FROM tpcds.reason WHERE r_reason_sk <5 ; 
    +
    +--向表中插入多条记录,如果冲突则更新冲突数据行中r_reason_id字段为'BBBBBBBBCAAAAAAA'。
    +postgres=# INSERT INTO tpcds.reason_t2 VALUES ( 5 , ' BBBBBBBBCAAAAAAA ' , ' reason5 ' ) , ( 6 , ' AAAAAAAADAAAAAAA ' , ' reason6 ' ) ON DUPLICATE KEY UPDATE r_reason_id = ' BBBBBBBBCAAAAAAA ' ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    + + 通过insert语句批量插入数据时,建议将多条记录合并入一条语句中执行插入,以提高数据加载性能。例如,INSERT INTO sections VALUES (30, 'Administration', 31, 1900),(40, 'Development', 35, 2000), (50, 'Development' , 60 , 2001);

    +]]>
    +
    +
    + +

    功能描述 

    +

    LOCK TABLE获取表级锁。

    +

    openGauss在为一个引用了表的命令自动请求锁时,尽可能选择最小限制的锁模式。如果用户需要一种更为严格的锁模式,可以使用LOCK命令。例如,一个应用是在Read Committed隔离级别上运行事务,并且它需要保证表中的数据在事务的运行过程中不被修改。为实现这个目的,则可以在查询之前对表使用SHARE锁模式进行锁定。这样将防止数据不被并发修改,从而保证后续的查询可以读到已提交的持久化的数据。因为SHARE锁模式与任何写操作需要的ROW EXCLUSIVE模式冲突,并且LOCK TABLE name IN SHARE MODE语句将等到所有当前持有ROW EXCLUSIVE模式锁的事务提交或回滚后才能执行。因此,一旦获得该锁,就不会存在未提交的写操作,并且其他操作也只能等到该锁释放之后才能开始。

    +
    +

    注意事项 

    +
    • LOCK TABLE只能在一个事务块的内部有用,因为锁在事务结束时就会被释放。出现在任意事务块外面的LOCK TABLE都会报错。
    • 如果没有声明锁模式,缺省为最严格的模式ACCESS EXCLUSIVE。
    • LOCK TABLE ... IN ACCESS SHARE MODE需要在目标表上有SELECT权限。所有其他形式的LOCK需要UPDATE和/或DELETE权限。
    • 没有UNLOCK TABLE命令,锁总是在事务结束时释放。
    • LOCK TABLE只处理表级的锁,因此那些带“ROW”字样的锁模式都是有歧义的。这些模式名称通常可理解为用户试图在一个被锁定的表中获取行级的锁。同样,ROW EXCLUSIVE模式也是一个可共享的表级锁。注意,只要是涉及到LOCK TABLE ,所有锁模式都有相同的语意,区别仅在于规则中锁与锁之间是否冲突,规则请参见表1
    +
    +

    示例 

    +
    --在执行删除操作时对一个有主键的表进行 SHARE ROW EXCLUSIVE 锁。
    +postgres=# CREATE TABLE tpcds.reason_t1 AS TABLE tpcds.reason ; 
    +postgres=# START TRANSACTION ; 
    +postgres=# LOCK TABLE tpcds.reason_t1 IN SHARE ROW EXCLUSIVE MODE ; 
    +postgres=# DELETE FROM tpcds.reason_t1 WHERE r_reason_desc IN ( SELECT r_reason_desc FROM tpcds.reason_t1 WHERE r_reason_sk < 6 ) ; 
    +postgres=# DELETE FROM tpcds.reason_t1 WHERE r_reason_sk = 7 ; 
    +postgres=# COMMIT ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    MOVE在不检索数据的情况下重新定位一个游标。MOVE的作用类似于FETCH命令,但只是重定位游标而不返回行。

    +
    +

    示例 

    +
    --忽略游标cursor1的前3行。
    +postgres=# MOVE FORWARD 3 FROM cursor1 ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    通过MERGE INTO语句,将目标表和源表中数据针对关联条件进行匹配,若关联条件匹配时对目标表进行UPDATE,无法匹配时对目标表执行INSERT。此语法可以很方便地用来合并执行UPDATE和INSERT,避免多次执行。

    +
    +

    注意事项 

    +
    • 进行MERGE INTO操作的用户需要同时拥有目标表的UPDATE和INSERT权限,以及源表的SELECT权限。
    • 不支持重分布过程中MERGE INTO。
    +
    +

    示例 

    +
    -- 进行MERGE INTO操作
    +postgres=# MERGE INTO products p
    +USING newproducts np
    +ON ( p.product_id = np.product_id ) 
    +WHEN MATCHED THEN
    +UPDATE SET p.product_name = np.product_name , p.category = np.category WHERE p.product_name != ' play gym ' 
    +WHEN NOT MATCHED THEN
    +INSERT VALUES ( np.product_id , np.product_name , np.category ) WHERE np.category = ' books ' ; 
    +MERGE 4
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    创建一个预备语句。

    +

    预备语句是服务端的对象,可以用于优化性能。在执行PREPARE语句的时候,指定的查询被解析、分析、重写。当随后发出EXECUTE语句的时候,预备语句被规划和执行。这种设计避免了重复解析、分析工作。PREPARE语句创建后在整个数据库会话期间一直存在,一旦创建成功,即便是在事务块中创建,事务回滚,PREPARE也不会删除。只能通过显式调用DEALLOCATE进行删除,会话结束时,PREPARE也会自动删除。

    +
    +

    示例 

    +
    --为一个INSERT语句创建一个预备语句然后执行它。
    +postgres=# PREPARE insert_reason ( integer , character ( 16 ) , character ( 100 ) ) AS INSERT INTO tpcds.reason_t1 VALUES ( $1 , $2 , $3 ) ; 
    +postgres=# EXECUTE insert_reason ( 52 , ' AAAAAAAADDAAAAAA ' , ' reason 52 ' ) ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    为当前事务做两阶段提交的准备。

    +

    在命令之后,事务就不再和当前会话关联了;它的状态完全保存在磁盘上,它被提交成功的可能性非常高,即使是在请求提交之前数据库发生了崩溃也如此。

    +

    一旦准备好了,一个事务就可以在稍后用COMMIT PREPAREDROLLBACK PREPARED命令分别进行提交或者回滚。这些命令可以从任何会话中发出,而不光是最初执行事务的那个会话。

    +

    从发出命令的会话的角度来看,PREPARE TRANSACTION不同于ROLLBACK:在执行它之后,就不再有活跃的当前事务了,并且预备事务的效果无法见到 (在事务提交的时候其效果会再次可见)。

    +

    如果PREPARE TRANSACTION因为某些原因失败,那么它就会变成一个ROLLBACK,当前事务被取消。

    +
    +

    注意事项 

    +
    • 事务功能由数据库自动维护,不应显式使用事务功能。
    • 在运行PREPARE TRANSACTION命令时,必须在postgresql.conf配置文件中增大max_prepared_transactions的数值。建议至少将其设置为等于max_connections,这样每个会话都可以有一个等待中的预备事务。
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    修改数据库对象的属主。

    +

    REASSIGN OWNED要求系统将所有old_roles拥有的数据库对象的属主更改为new_role。

    +
    +

    注意事项 

    +
    • REASSIGN OWNED常用于在删除角色之前的准备工作。
    • 执行REASSIGN OWNED需要有原角色和目标角色上的权限。
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    为表中的数据重建索引。

    +

    在以下几种情况下需要使用REINDEX重建索引:

    +
    • 索引崩溃,并且不再包含有效的数据。
    • 索引变得“臃肿”,包含大量的空页或接近空页。
    • 为索引更改了存储参数(例如填充因子),并且希望这个更改完全生效。

      使用CONCURRENTLY选项创建索引失败,留下了一个“非法”索引。

      +
    +
    +

    注意事项 

    +

    REINDEX DATABASE和SYSTEM这种形式的重建索引不能在事务块中执行。

    +
    +

    示例 

    +
    --重建一个单独索引。
    +postgres=# REINDEX INDEX tpcds.tpcds_customer_index1 ; 
    +
    +--重建表tpcds.customer_t1上的所有索引。
    +postgres=# REINDEX TABLE tpcds.customer_t1 ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    + + 此种情况大多用于故障恢复,不建议进行并发操作。

    +]]>
    +
    + + 不建议在事务中reindex database。

    +]]>
    +
    + + 不建议在事务中reindex系统表。

    +]]>
    +
    +
    + +

    功能描述 

    +

    RELEASE SAVEPOINT删除一个当前事务先前定义的保存点。

    +

    把一个保存点删除就令其无法作为回滚点使用,除此之外它没有其它用户可见的行为。它并不能撤销在保存点建立起来之后执行的命令的影响。要撤销那些命令可以使用ROLLBACK TO SAVEPOINT 。在不再需要的时候删除一个保存点可以令系统在事务结束之前提前回收一些资源。

    +

    RELEASE SAVEPOINT也删除所有在指定的保存点建立之后的所有保存点。

    +
    +

    注意事项 

    +
    • 不能RELEASE一个没有定义的保存点,语法上会报错。
    • 如果事务在回滚状态,则不能释放保存点。
    • 如果多个保存点拥有同样的名称,只有最近定义的那个才被释放。
    +
    +

    示例 

    +
    --删除保存点。
    +postgres=# RELEASE SAVEPOINT my_savepoint;
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    RESET将指定的运行时参数恢复为缺省值。这些参数的缺省值是指postgresql.conf配置文件中所描述的参数缺省值。

    +

    RESET命令与如下命令的作用相同:

    +

    SET configuration_parameter TO DEFAULT

    +
    +

    注意事项 

    +

    RESET的事务性行为和SET相同:它的影响将会被事务回滚撤销。

    +
    +

    示例 

    +
    --把timezone设为缺省值。
    +postgres=# RESET timezone ; 
    +
    +--把所有参数设置为缺省值。
    +postgres=# RESET ALL ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    REVOKE用于撤销一个或多个角色的权限。

    +
    +

    注意事项 

    +

    非对象所有者试图在对象上REVOKE权限,命令按照以下规则执行:

    +
    • 如果授权用户没有该对象上的权限,则命令立即失败。
    • 如果授权用户有部分权限,则只撤销那些有授权选项的权限。
    • 如果授权用户没有授权选项,REVOKE ALL PRIVILEGES形式将发出一个错误信息,而对于其他形式的命令而言,如果是命令中指定名称的权限没有相应的授权选项,该命令将发出一个警告。
    • 不允许对表分区进行REVOKE操作,对分区表进行REVOKE操作会引起告警。
    +
    +

    示例 

    +
    postgres=# CREATE USER joe PASSWORD ' Bigdata@123 ' ; 
    +postgres=# GRANT ALL PRIVILEGES TO joe ; 
    +授权成功后,用户joe会拥有sysadmin的所有权限。
    +示例:将对象权限授权给用户或者角色。
    +撤销joe用户的sysadmin权限,然后将模式tpcds的使用权限和表tpcds.reason的所有权限授权给用户joe。postgres=# REVOKE ALL PRIVILEGES FROM joe ; 
    +postgres=# GRANT USAGE ON SCHEMA tpcds TO joe ; 
    +postgres=# GRANT ALL PRIVILEGES ON tpcds.reason TO joe ; 
    +授权成功后,joe用户就拥有了tpcds.reason表的所有权限,包括增删改查等权限。
    +将tpcds.reason表中r_reason_sk、r_reason_id、r_reason_desc列的查询权限,r_reason_desc的更新权限授权给joe。postgres=# GRANT select ( r_reason_sk , r_reason_id , r_reason_desc ) , update ( r_reason_desc ) ON tpcds.reason TO joe ; 
    +授权成功后,用户joe对tpcds.reason表中r_reason_sk,r_reason_id的查询权限会立即生效。如果joe用户需要拥有将这些权限授权给其他用户的权限,可以通过以下语法对joe用户进行授权。
    +postgres=# GRANT select ( r_reason_sk , r_reason_id ) ON tpcds.reason TO joe WITH GRANT OPTION ; 
    +将数据库postgres的连接权限授权给用户joe,并给予其在postgres中创建schema的权限,而且允许joe将此权限授权给其他用户。
    +postgres=# GRANT create , connect on database postgres TO joe WITH GRANT OPTION ; 
    +创建角色tpcds_manager,将模式tpcds的访问权限授权给角色tpcds_manager,并授予该角色在tpcds下创建对象的权限,不允许该角色中的用户将权限授权给其他人。
    +postgres=# CREATE ROLE tpcds_manager PASSWORD ' Bigdata@123 ' ; 
    +postgres=# GRANT USAGE , CREATE ON SCHEMA tpcds TO tpcds_manager ; 
    +将表空间tpcds_tbspc的所有权限授权给用户joe,但用户joe无法将权限继续授予其他用户。
    +postgres=# CREATE TABLESPACE tpcds_tbspc RELATIVE LOCATION ' tablespace/tablespace_1 ' ; 
    +postgres=# GRANT ALL ON TABLESPACE tpcds_tbspc TO joe ; 
    +示例:将用户或者角色的权限授权给其他用户或角色。
    +创建角色manager,将joe的权限授权给manager,并允许该角色将权限授权给其他人。postgres=# CREATE ROLE manager PASSWORD ' Bigdata@123 ' ; 
    +postgres=# GRANT joe TO manager WITH ADMIN OPTION ; 
    +创建用户senior_manager,将用户manager的权限授权给该用户。postgres=# CREATE ROLE senior_manager PASSWORD ' Bigdata@123 ' ; 
    +postgres=# GRANT manager TO senior_manager ; 
    +撤销权限,并清理用户。postgres=# REVOKE manager FROM joe ; 
    +postgres=# REVOKE senior_manager FROM manager ; 
    +postgres=# DROP USER manager ; 
    +示例:撤销上述授予的权限,并清理角色和用户。
    +postgres=# REVOKE ALL PRIVILEGES ON tpcds.reason FROM joe ; 
    +postgres=# REVOKE ALL PRIVILEGES ON SCHEMA tpcds FROM joe ; 
    +postgres=# REVOKE ALL ON TABLESPACE tpcds_tbspc FROM joe ; 
    +postgres=# DROP TABLESPACE tpcds_tbspc ; 
    +postgres=# REVOKE USAGE , CREATE ON SCHEMA tpcds FROM tpcds_manager ; 
    +postgres=# DROP ROLE tpcds_manager ; 
    +postgres=# DROP ROLE senior_manager ; 
    +postgres=# DROP USER joe CASCADE ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    回滚当前事务并取消当前事务中的所有更新。

    +

    在事务运行的过程中发生了某种故障,事务不能继续执行,系统将事务中对数据库的所有已完成的操作全部撤销,数据库状态回到事务开始时。

    +
    +

    注意事项 

    +

    如果不在一个事务内部发出ROLLBACK不会有问题,但是将抛出一个NOTICE信息。

    +
    +

    示例 

    +
    --取消所有更改
    +postgres=# ROLLBACK ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    取消一个先前为两阶段提交准备好的事务。

    +
    +

    注意事项 

    +
    • 该功能仅在维护模式(GUC参数xc_maintenance_mode为on时)下可用。该模式谨慎打开,一般供维护人员排查问题使用,一般用户不应使用该模式。
    • 要想回滚一个预备事务,必须是最初发起事务的用户,或者是系统管理员。
    • 事务功能由数据库自动维护,不应显式使用事务功能。
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    ROLLBACK TO SAVEPOINT用于回滚到一个保存点,隐含地删除所有在该保存点之后建立的保存点。

    +

    回滚所有指定保存点建立之后执行的命令。保存点仍然有效,并且需要时可以再次回滚到该点。

    +
    +

    注意事项 

    +
    • 不能回滚到一个未定义的保存点,语法上会报错。
    • 在保存点方面,游标有一些非事务性的行为。任何在保存点里打开的游标都会在回滚掉这个保存点之后关闭。如果一个前面打开了的游标在保存点里面,并且游标被一个FETCH命令影响,而这个保存点稍后回滚了,那么这个游标的位置仍然在FETCH让它指向的位置(也就是FETCH不会被回滚)。关闭一个游标的行为也不会被回滚给撤消掉。如果一个游标的操作导致事务回滚,那么这个游标就会置于不可执行状态,所以,尽管一个事务可以用ROLLBACK TO SAVEPOINT重新恢复,但是游标不能再使用了。
    • 使用ROLLBACK TO SAVEPOINT回滚到一个保存点。使用RELEASE SAVEPOINT删除一个保存点,但是保留该保存点建立后执行的命令的效果。
    +
    +

    示例 

    +
    --撤销 my_savepoint 建立之后执行的命令的影响。
    +postgres=# START TRANSACTION ; 
    +postgres=# SAVEPOINT my_savepoint;
    +postgres=# ROLLBACK TO SAVEPOINT my_savepoint;
    +
    +--游标位置不受保存点回滚的影响。
    +postgres=# DECLARE foo CURSOR FOR SELECT 1 UNION SELECT 2 ; 
    +postgres=# SAVEPOINT foo ; 
    +postgres=# FETCH 1 FROM foo ; 
    +?column?
    +----------
    +1
    +postgres=# ROLLBACK TO SAVEPOINT foo ; 
    +postgres=# FETCH 1 FROM foo ; 
    +?column?
    +----------
    +2
    +postgres=# RELEASE SAVEPOINT my_savepoint;
    +postgres=# COMMIT ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    SAVEPOINT用于在当前事务里建立一个新的保存点。

    +

    保存点是事务中的一个特殊记号,它允许将那些在它建立后执行的命令全部回滚,把事务的状态恢复到保存点所在的时刻。

    +
    +

    注意事项 

    +
    • 使用ROLLBACK TO SAVEPOINT回滚到一个保存点。使用RELEASE SAVEPOINT删除一个保存点,但是保留该保存点建立后执行的命令的效果。
    • 保存点只能在一个事务块里面建立。在一个事务里面可以定义多个保存点。
    • 函数、匿名块和存储过程中不支持使用SAVEPOINT语法。
    • 由于节点故障或者通信故障引起的分布式节点线程或进程退出导致的报错,以及由于COPY FROM操作中源数据与目标表的表结构不一致导致的报错,均不能正常回滚到保存点之前,而是整个事务回滚。
    • SQL标准要求,使用savepoint建立一个同名保存点时,需要自动删除前面那个同名保存点。在openGauss数据库里,我们将保留旧的保存点,但是在回滚或者释放的时候,只使用最近的那个。释放了新的保存点将导致旧的再次成为ROLLBACK TO SAVEPOINT和RELEASE SAVEPOINT可以访问的保存点。除此之外,SAVEPOINT是完全符合SQL标准的。
    +
    +

    示例 

    +
    --建立保存点。
    +postgres=# SAVEPOINT my_savepoint;
    +
    +--回滚保存点。
    +postgres=# ROLLBACK TO SAVEPOINT my_savepoint;
    +
    +--建立保存点。
    +postgres=# SAVEPOINT my_savepoint;
    +
    +--回滚保存点。
    +postgres=# RELEASE SAVEPOINT my_savepoint;
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    SELECT用于从表或视图中取出数据。

    +

    SELECT语句就像叠加在数据库表上的过滤器,利用SQL关键字从数据表中过滤出用户需要的数据。

    +
    +

    注意事项 

    +
    • 必须对每个在SELECT命令中使用的字段有SELECT权限。
    +
    +

    示例 

    +
    --先通过子查询得到一张临时表temp_t,然后查询表temp_t中的所有数据。
    +postgres=# WITH temp_t ( name , isdba ) AS ( SELECT usename , usesuper FROM pg_user ) SELECT * FROM temp_t;
    +
    +--查询tpcds.reason表的所有r_reason_sk记录,且去除重复。
    +postgres=# SELECT DISTINCT ( r_reason_sk ) FROM tpcds.reason ; 
    +
    +--LIMIT子句示例:获取表中一条记录。
    +postgres=# SELECT * FROM tpcds.reason LIMIT 1 ; 
    +
    +--查询所有记录,且按字母升序排列。
    +postgres=# SELECT r_reason_desc FROM tpcds.reason ORDER BY r_reason_desc ; 
    +
    +--通过表别名,从pg_user和pg_user_status这两张表中获取数据。
    +postgres=# SELECT a.usename , b.locktime FROM pg_user a , pg_user_status b WHERE a.usesysid=b.roloid ; 
    +
    +--FULL JOIN子句示例:将pg_user和pg_user_status这两张表的数据进行全连接显示,即数据的合集。
    +postgres=# SELECT a.usename , b.locktime , a.usesuper FROM pg_user a FULL JOIN pg_user_status b on a.usesysid=b.roloid ; 
    +
    +--GROUP BY子句示例:根据查询条件过滤,并对结果进行分组。
    +postgres=# SELECT r_reason_id , AVG ( r_reason_sk ) FROM tpcds.reason GROUP BY r_reason_id HAVING AVG ( r_reason_sk ) > 25 ; 
    +
    +--GROUP BY CUBE子句示例:根据查询条件过滤,并对结果进行分组汇总。
    +postgres=# SELECT r_reason_id , AVG ( r_reason_sk ) FROM tpcds.reason GROUP BY CUBE ( r_reason_id , r_reason_sk ) ; 
    +
    +--GROUP BY GROUPING SETS子句示例:根据查询条件过滤,并对结果进行分组汇总。
    +postgres=# SELECT r_reason_id , AVG ( r_reason_sk ) FROM tpcds.reason GROUP BY GROUPING SETS ( ( r_reason_id , r_reason_sk ) , r_reason_sk ) ; 
    +
    +--UNION子句示例:将表tpcds.reason里r_reason_desc字段中的内容以W开头和以N开头的进行合并。
    +postgres=# SELECT r_reason_sk , tpcds.reason.r_reason_desc
    +FROM tpcds.reason
    +WHERE tpcds.reason.r_reason_desc LIKE ' W% ' 
    +UNION
    +SELECT r_reason_sk , tpcds.reason.r_reason_desc
    +FROM tpcds.reason
    +WHERE tpcds.reason.r_reason_desc LIKE ' N% ' ; 
    +
    +--NLS_SORT子句示例:中文拼音排序。
    +postgres=# SELECT * FROM tpcds.reason ORDER BY NLSSORT ( r_reason_desc , ' NLS_SORT = SCHINESE_PINYIN_M ' ) ; 
    +
    +--不区分大小写排序:
    +postgres=# SELECT * FROM tpcds.reason ORDER BY NLSSORT ( r_reason_desc , ' NLS_SORT = generic_m_ci ' ) ; 
    +
    +--PARTITION子句示例:从tpcds.reason_p的表分区P_05_BEFORE中获取数据。
    +postgres=# SELECT * FROM tpcds.reason_p PARTITION ( P_05_BEFORE ) ; 
    +r_reason_sk | r_reason_id | r_reason_desc
    +-------------+------------------+------------------------------------
    +4 | AAAAAAAABAAAAAAA | reason 3
    +3 | AAAAAAAABAAAAAAA | reason 1
    + ( 2 rows ) 
    +
    +--GROUP BY子句示例:按r_reason_id分组统计tpcds.reason_p表中的记录数。
    +postgres=# SELECT COUNT ( * ) , r_reason_id FROM tpcds.reason_p GROUP BY r_reason_id ; 
    +count | r_reason_id
    +-------+------------------
    +2 | AAAAAAAACAAAAAAA
    +5 | AAAAAAAABAAAAAAA
    + ( 2 rows ) 
    +
    +--GROUP BY CUBE子句示例:根据查询条件过滤,并对查询结果分组汇总。
    +postgres=# SELECT * FROM tpcds.reason GROUP BY CUBE ( r_reason_id , r_reason_sk , r_reason_desc ) ; 
    +
    +--GROUP BY GROUPING SETS子句示例:根据查询条件过滤,并对查询结果分组汇总。
    +postgres=# SELECT * FROM tpcds.reason GROUP BY GROUPING SETS ( ( r_reason_id , r_reason_sk ) , r_reason_desc ) ; 
    +
    +--HAVING子句示例:按r_reason_id分组统计tpcds.reason_p表中的记录,并只显示r_reason_id个数大于2的信息。
    +postgres=# SELECT COUNT ( * ) c , r_reason_id FROM tpcds.reason_p GROUP BY r_reason_id HAVING c>2 ; 
    +c | r_reason_id
    +
    +--IN子句示例:按r_reason_id分组统计tpcds.reason_p表中的r_reason_id个数,并只显示r_reason_id值为 AAAAAAAABAAAAAAA或AAAAAAAADAAAAAAA的个数。
    +postgres=# SELECT COUNT ( * ) , r_reason_id FROM tpcds.reason_p GROUP BY r_reason_id HAVING r_reason_id IN ( ' AAAAAAAABAAAAAAA ' , ' AAAAAAAADAAAAAAA ' ) ; 
    +count | r_reason_id
    +-------+------------------
    +5 | AAAAAAAABAAAAAAA
    + ( 1 row ) 
    +
    +--INTERSECT子句示例:查询r_reason_id等于AAAAAAAABAAAAAAA,并且r_reason_sk小于5的信息。
    +postgres=# SELECT * FROM tpcds.reason_p WHERE r_reason_id= ' AAAAAAAABAAAAAAA ' INTERSECT SELECT * FROM tpcds.reason_p WHERE r_reason_sk<5 ; 
    +r_reason_sk | r_reason_id | r_reason_desc
    +-------------+------------------+------------------------------------
    +4 | AAAAAAAABAAAAAAA | reason 3
    +3 | AAAAAAAABAAAAAAA | reason 1
    + ( 2 rows ) 
    +
    +--EXCEPT子句示例:查询r_reason_id等于AAAAAAAABAAAAAAA,并且去除r_reason_sk小于4的信息。
    +postgres=# SELECT * FROM tpcds.reason_p WHERE r_reason_id= ' AAAAAAAABAAAAAAA ' EXCEPT SELECT * FROM tpcds.reason_p WHERE r_reason_sk<4 ; 
    +r_reason_sk | r_reason_id | r_reason_desc
    +-------------+------------------+------------------------------------
    +10 | AAAAAAAABAAAAAAA | reason 2
    +10 | AAAAAAAABAAAAAAA | reason 5
    +10 | AAAAAAAABAAAAAAA | reason 4
    +4 | AAAAAAAABAAAAAAA | reason 3
    + ( 4 rows ) 
    +
    +--通过在where子句中指定" ( + ) "来实现左连接。
    +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where t1.sr_customer_sk = t2.c_customer_sk ( + ) 
    +order by 1 desc limit 1 ; 
    +sr_item_sk | c_customer_id
    +------------+---------------
    +18000 |
    + ( 1 row ) 
    +
    +--通过在where子句中指定" ( + ) "来实现右连接。
    +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where t1.sr_customer_sk ( + ) = t2.c_customer_sk
    +order by 1 desc limit 1 ; 
    +sr_item_sk | c_customer_id
    +------------+------------------
    +| AAAAAAAAJNGEBAAA
    + ( 1 row ) 
    +
    +--通过在where子句中指定" ( + ) "来实现左连接,并且增加连接条件。
    +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where t1.sr_customer_sk = t2.c_customer_sk ( + ) and t2.c_customer_sk ( + ) < 1 order by 1 limit 1 ; 
    +sr_item_sk | c_customer_id
    +------------+---------------
    +1 |
    + ( 1 row ) 
    +
    +--不支持在where子句中指定" ( + ) "的同时使用内层嵌套AND/OR的表达式。
    +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where not ( t1.sr_customer_sk = t2.c_customer_sk ( + ) and t2.c_customer_sk ( + ) < 1 ) ; 
    +ERROR: Operator " ( + ) " can not be used in nesting expression.
    +LINE 1: ...tomer_id from store_returns t1 , customer t2 where not ( t1.sr_...
    +^
    +
    +--where子句在不支持表达式宏指定" ( + ) "会报错。
    +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where ( t1.sr_customer_sk = t2.c_customer_sk ( + ) ) ::bool ; 
    +ERROR: Operator " ( + ) " can only be used in common expression.
    +
    +--where子句在表达式的两边都指定" ( + ) "会报错。
    +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where t1.sr_customer_sk ( + ) = t2.c_customer_sk ( + ) ; 
    +ERROR: Operator " ( + ) " can ' t be specified on more than one relation in one join condition
    +HINT: "t1" , "t2"...are specified Operator " ( + ) " in one condition.
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    SELECT INTO用于根据查询结果创建一个新表,并且将查询到的数据插入到新表中。

    +

    数据并不返回给客户端,这一点和普通的SELECT不同。新表的字段具有和SELECT的输出字段相同的名称和数据类型。

    +
    +

    注意事项 

    +

    CREATE TABLE AS的作用和SELECT INTO类似,且提供了SELECT INTO所提供功能的超集。建议使用CREATE TABLE AS语法替代SELECT INTO,因为SELECT INTO不能在存储过程中使用。

    +
    +

    示例 

    +
    --将tpcds.reason表中r_reason_sk小于5的值加入到新建表中。
    +postgres=# SELECT * INTO tpcds.reason_t1 FROM tpcds.reason WHERE r_reason_sk < 5 ; 
    +INSERT 0 6
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    + + 不建议在事务中reindex database。

    +]]>
    +
    + + 不建议在事务中reindex系统表。

    +]]>
    +
    +
    + +

    功能描述 

    +

    用于修改运行时配置参数。

    +
    +

    注意事项 

    +

    大多数运行时参数都可以用SET在运行时设置,但有些则在服务运行过程中或会话开始之后不能修改。

    +
    +

    示例 

    +
    --设置模式搜索路径。
    +postgres=# SET search_path TO tpcds , public ; 
    +
    +--把日期时间风格设置为传统的 POSTGRES 风格 ( 日在月前 ) 。
    +postgres=# SET datestyle TO postgres ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    SET CONSTRAINTS设置当前事务检查行为的约束条件。

    +

    IMMEDIATE约束是在每条语句后面进行检查。DEFERRED约束一直到事务提交时才检查。每个约束都有自己的模式。

    +

    从创建约束条件开始,一个约束总是设定为DEFERRABLE INITIALLY DEFERRED,DEFERRABLE INITIALLY IMMEDIATE,NOT DEFERRABLE三个特性之一。第三种总是IMMEDIATE,并且不会受SET CONSTRAINTS影响。前两种以指定的方式启动每个事务,但是其行为可以在事务里用SET CONSTRAINTS改变。

    +

    带着一个约束名列表的SET CONSTRAINTS改变这些约束的模式(都必须是可推迟的)。如果有多个约束匹配某个名称,则所有都会被影响。SET CONSTRAINTS ALL改变所有可推迟约束的模式。

    +

    当SET CONSTRAINTS把一个约束从DEFERRED改成IMMEDIATE的时候,新模式反作用式地起作用:任何将在事务结束准备进行的数据修改都将在SET CONSTRAINTS的时候执行检查。如果违反了任何约束,SET CONSTRAINTS都会失败(并且不会修改约束模式)。因此,SET CONSTRAINTS可以用于强制在事务中某一点进行约束检查。

    +

    检查和唯一约束总是不可推迟的。

    +
    +

    注意事项 

    +

    SET CONSTRAINTS只在当前事务里设置约束的行为。因此,如果用户在事务块之外(START TRANSACTION/COMMIT对)执行这个命令,它将没有任何作用。

    +
    +

    示例 

    +
    --设置所有约束在事务提交时检查。
    +postgres=# SET CONSTRAINTS ALL DEFERRED ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    设置当前会话的当前用户标识符。

    +
    +

    注意事项 

    +
    • 当前会话的用户必须是指定的rolename角色的成员,但系统管理员可以选择任何角色。
    • 使用这条命令,它可能会增加一个用户的权限,也可能会限制一个用户的权限。如果会话用户的角色有INHERITS属性,则它自动拥有它能SET ROLE变成的角色的所有权限;在这种情况下,SET ROLE实际上是删除了所有直接赋予会话用户的权限,以及它的所属角色的权限,只剩下指定角色的权限。另一方面,如果会话用户的角色有NOINHERITS属性,SET ROLE删除直接赋予会话用户的权限,而获取指定角色的权限。
    +
    +

    示例 

    +
    --设置当前用户为paul。
    +postgres=# SET ROLE paul PASSWORD ' Bigdata@123 ' ; 
    +
    +--重置当前用户。
    +postgres=# RESET role ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    把当前会话里的会话用户标识和当前用户标识都设置为指定的用户。

    +
    +

    注意事项 

    +

    只有在初始会话用户有系统管理员权限的时候,会话用户标识符才能改变。否则,只有在指定了被认证的用户名的情况下,系统才接受该命令。

    +
    +

    示例 

    +
    --设置当前用户为paul。
    +postgres=# SET SESSION AUTHORIZATION paul password ' Bigdata@123 ' ; 
    +
    +--重置当前用户。
    +postgres=# RESET SESSION AUTHORIZATION ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    为当前事务设置特性。它对后面的事务没有影响。事务特性包括事务隔离级别、事务访问模式(读/写或者只读)。

    +
    +

    示例 

    +
    --开启一个事务,设置事务的隔离级别为READ COMMITTED,访问模式为READ ONLY。
    +postgres=# START TRANSACTION ; 
    +postgres=# SET LOCAL TRANSACTION ISOLATION LEVEL READ COMMITTED READ ONLY ; 
    +postgres=# COMMIT ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    SHOW将显示当前运行时参数的数值。

    +
    +

    示例 

    +
    --显示 timezone 参数值。
    +postgres=# SHOW timezone ; 
    +
    +--显示所有参数。
    +postgres=# SHOW ALL ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    通过START TRANSACTION启动事务。如果声明了隔离级别、读写模式,那么新事务就使用这些特性,类似执行了SET TRANSACTION

    +
    +

    示例 

    +
    --以默认方式启动事务。
    +postgres=# START TRANSACTION ; 
    +postgres=# SELECT * FROM tpcds.reason ; 
    +postgres=# END ; 
    +
    +--以隔离级别为READ COMMITTED,读/写方式启动事务。
    +postgres=# START TRANSACTION ISOLATION LEVEL READ COMMITTED READ WRITE ; 
    +postgres=# SELECT * FROM tpcds.reason ; 
    +postgres=# COMMIT ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    清理表数据,TRUNCATE快速地从表中删除所有行。

    +

    它和在目标表上进行无条件的DELETE有同样的效果,但由于TRUNCATE不做表扫描,因而快得多。在大表上操作效果更明显。

    +
    +

    注意事项 

    +
    • TRUNCATE TABLE在功能上与不带WHERE子句DELETE语句相同:二者均删除表中的全部行。
    • TRUNCATE TABLE比DELETE速度快且使用系统和事务日志资源少:
      • DELETE语句每次删除一行,并在事务日志中为所删除每行记录一项。
      • TRUNCATE TABLE通过释放存储表数据所用数据页来删除数据,并且只在事务日志中记录页的释放。
      +
    • TRUNCATE,DELETE,DROP三者的差异如下:
      • TRUNCATE TABLE,删除内容,释放空间,但不删除定义。
      • DELETE TABLE,删除内容,不删除定义,不释放空间。
      • DROP TABLE,删除内容和定义,释放空间。
      +
    +
    +

    示例 

    +
    --清空表tpcds.reason_t1。
    +postgres=# TRUNCATE TABLE tpcds.reason_t1 ; 
    +
    +--清空分区p_05_before。
    +postgres=# ALTER TABLE tpcds.reason_p TRUNCATE PARTITION p_05_before ; 
    +
    +--清空分区p_15。
    +postgres=# ALTER TABLE tpcds.reason_p TRUNCATE PARTITION for ( 13 ) ; 
    +
    +--清空分区表。
    +postgres=# TRUNCATE TABLE tpcds.reason_p ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    + +

    功能描述 

    +

    更新表中的数据。UPDATE修改满足条件的所有行中指定的字段值,WHERE子句声明条件,SET子句指定的字段会被修改,没有出现的字段则保持它们的原值。

    +
    +

    注意事项 

    +
    • 要修改表,用户必须对该表有UPDATE权限。
    • 对expression或condition条件里涉及到的任何表要有SELECT权限。
    • 对于列存表,暂时不支持RETURNING子句。
    • 列存表不支持结果不确定的更新(non-deterministic update)。试图对列存表用多行数据更新一行时会报错。
    • 列存表的更新操作,旧记录空间不会回收,需要执行VACUUM FULL table_name进行清理。
    • 对于列存复制表,暂不支持UPDATE操作。
    +
    +

    示例 

    +
    --直接更新所有记录的值。
    +postgres=# UPDATE student1 SET classno = classno*2 ; 
    +
    +

    语法格式 

    + +

    参数说明 

    +]]>
    +
    +
    \ No newline at end of file diff --git a/code/datastudio/db_assistant/operationList.html b/code/datastudio/db_assistant/operationList.html new file mode 100644 index 0000000000000000000000000000000000000000..5d8fbd98be81ede757568819999f7d4e8db4861a --- /dev/null +++ b/code/datastudio/db_assistant/operationList.html @@ -0,0 +1,66 @@ + + + + + + SQL助手 + + + + + + + + + + + +
    +
    +
    语法
    +
    操作列表
    + +
    +
    +
    +
    +

    通过操作列表,您只需要知道自己要“做什么”,就可以快速找到所需命令,而不需要事先知道命令名称。

    +
    选择您要做哪类操作?
    +
    +
    +
    + + + +
    + + +
    + + + +
    + \ No newline at end of file diff --git a/code/datastudio/src/Common-collection/.classpath b/code/datastudio/src/Common-collection/.classpath new file mode 100644 index 0000000000000000000000000000000000000000..81cf73a05f3b1b8734939f3e8ef3c2357e1fa8ae --- /dev/null +++ b/code/datastudio/src/Common-collection/.classpath @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/code/datastudio/src/Common-collection/.gitignore b/code/datastudio/src/Common-collection/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ddc25c7fcd00a3a38f67eabde7efb88c26a8c3a8 --- /dev/null +++ b/code/datastudio/src/Common-collection/.gitignore @@ -0,0 +1,3 @@ +/bin/ +/.settings/ +/target/ diff --git a/code/datastudio/src/Common-collection/.project b/code/datastudio/src/Common-collection/.project new file mode 100644 index 0000000000000000000000000000000000000000..d736bfc914d90fb178b545a97823824e3d7df8ba --- /dev/null +++ b/code/datastudio/src/Common-collection/.project @@ -0,0 +1,34 @@ + + + Common-collection + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/code/datastudio/src/Common-collection/META-INF/MANIFEST.MF b/code/datastudio/src/Common-collection/META-INF/MANIFEST.MF new file mode 100644 index 0000000000000000000000000000000000000000..fe4cc044f0069a1289c3aac2e334008ec131a173 --- /dev/null +++ b/code/datastudio/src/Common-collection/META-INF/MANIFEST.MF @@ -0,0 +1,26 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Common-collection +Bundle-SymbolicName: Common-collection +Bundle-Version: 1.0.0 +Export-Package: org.apache.commons.collections4, + org.apache.commons.collections4.trie, + org.apache.commons.compress, + org.apache.commons.math3.util, + org.apache.poi, + org.apache.poi.hpsf, + org.apache.poi.hssf.usermodel, + org.apache.poi.ooxml, + org.apache.poi.ss.usermodel, + org.apache.poi.util, + org.apache.poi.xssf.streaming, + org.apache.poi.xssf.usermodel, + org.apache.xmlbeans, + org.openxmlformats.schemas.spreadsheetml.x2006.main +Bundle-ClassPath: xmlbeans-3.1.0.jar, + poi-4.1.2.jar, + poi-ooxml-4.1.2.jar, + poi-ooxml-schemas-4.1.2.jar, + commons-collections4-4.4.jar, + commons-compress-1.21.jar, + commons-math3-3.6.1.jar diff --git a/code/datastudio/src/Common-collection/META-INF/maven/org.apache.commons/commons-collections4/pom.properties b/code/datastudio/src/Common-collection/META-INF/maven/org.apache.commons/commons-collections4/pom.properties new file mode 100644 index 0000000000000000000000000000000000000000..be1c860eefe472f983fa6bb66de2728d8e1e7c39 --- /dev/null +++ b/code/datastudio/src/Common-collection/META-INF/maven/org.apache.commons/commons-collections4/pom.properties @@ -0,0 +1,5 @@ +#Generated by Maven +#Wed Nov 25 22:54:27 CET 2015 +version=4.1 +groupId=org.apache.commons +artifactId=commons-collections4 diff --git a/code/datastudio/src/Common-collection/META-INF/maven/org.apache.commons/commons-collections4/pom.xml b/code/datastudio/src/Common-collection/META-INF/maven/org.apache.commons/commons-collections4/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..5ae7f526512c8f5d5b2bd53a9a9d24cfe4c44c1b --- /dev/null +++ b/code/datastudio/src/Common-collection/META-INF/maven/org.apache.commons/commons-collections4/pom.xml @@ -0,0 +1,731 @@ + + + + + org.apache.commons + commons-parent + 38 + + 4.0.0 + org.apache.commons + commons-collections4 + 4.1 + Apache Commons Collections + + 2001 + The Apache Commons Collections package contains types that extend and augment the Java Collections Framework. + + http://commons.apache.org/proper/commons-collections/ + + + jira + http://issues.apache.org/jira/browse/COLLECTIONS + + + + scm:svn:http://svn.apache.org/repos/asf/commons/proper/collections/trunk + scm:svn:https://svn.apache.org/repos/asf/commons/proper/collections/trunk + http://svn.apache.org/viewvc/commons/proper/collections/trunk + + + + + Matt Benson + mbenson + + + James Carman + jcarman + + + Stephen Colebourne + scolebourne + + + Robert Burrell Donkin + rdonkin + + + Morgan Delagrange + morgand + + + Gary D. Gregory + ggregory + + + Matthew Hawthorne + matth + + + Dipanjan Laha + dlaha + + + Geir Magnusson + geirm + + + Luc Maisonobe + luc + + + Craig McClanahan + craigmcc + + + Thomas Neidhart + tn + + + Adrian Nistor + adriannistor + + + Phil Steitz + psteitz + + + Arun M. Thomas + amamment + + + Rodney Waldhoff + rwaldhoff + + + Henri Yandell + bayard + + + + + + Rafael U. C. Afonso + + + Max Rydahl Andersen + + + Avalon + + + Federico Barbieri + + + Jeffrey Barnes + + + Nicola Ken Barozzi + + + Arron Bates + + + Sebastian Bazley + + + Benjamin Bentmann + + + Ola Berg + + + Sam Berlin + + + Christopher Berry + + + Nathan Beyer + + + Rune Peter Bjørnstad + + + Janek Bogucki + + + Maarten Brak + + + Dave Bryson + + + Chuck Burdick + + + Julien Buret + + + Josh Cain + + + Jonathan Carlson + + + Ram Chidambaram + + + Steve Clark + + + Benoit Corne + + + Eric Crampton + + + Dimiter Dimitrov + + + Peter Donald + + + Steve Downey + + + Rich Dougherty + + + Tom Dunham + + + Stefano Fornari + + + Andrew Freeman + + + Gerhard Froehlich + + + Goran Hacek + + + David Hay + + + Mario Ivankovits + + + Paul Jack + + + Eric Johnson + + + Kent Johnson + + + Marc Johnson + + + Roger Kapsi + + + Nissim Karpenstein + + + Shinobu Kawai + + + Stephen Kestle + + + Mohan Kishore + + + Simon Kitching + + + Thomas Knych + + + Serge Knystautas + + + Peter KoBek + + + Jordan Krey + + + Olaf Krische + + + Guilhem Lavaux + + + Paul Legato + + + David Leppik + + + Berin Loritsch + + + Hendrik Maryns + + + Stefano Mazzocchi + + + Brian McCallister + + + David Meikle + + + Steven Melzer + + + Leon Messerschmidt + + + Mauricio S. Moura + + + Kasper Nielsen + + + Stanislaw Osinski + + + Alban Peignier + + + Mike Pettypiece + + + Steve Phelps + + + Ilkka Priha + + + Jonas Van Poucke + + + Will Pugh + + + Herve Quiroz + + + Daniel Rall + + + Robert Ribnitz + + + Huw Roberts + + + Henning P. Schmiedehausen + + + Joerg Schmuecker + + + Howard Lewis Ship + + + Joe Raysa + + + Jeff Rodriguez + + + Ashwin S + + + Jordane Sarda + + + Thomas Schapitz + + + Jon Schewe + + + Andreas Schlosser + + + Christian Siefkes + + + Michael Smith + + + Stephen Smith + + + Jan Sorensen + + + Jon S. Stevens + + + James Strachan + + + Leo Sutic + + + Radford Tam + + + Chris Tilden + + + Neil O'Toole + + + Jeff Turner + + + Kazuya Ujihara + + + Thomas Vahrst + + + Jeff Varszegi + + + Ralph Wagner + + + Hollis Waite + + + David Weinrich + + + Dieter Wimberger + + + Serhiy Yevtushenko + + + Sai Zhang + + + Jason van Zyl + + + Geoff Schoeman + + + Goncalo Marques + + + + + + junit + junit + 4.11 + test + + + org.easymock + easymock + 3.2 + test + + + + + + apache.website + Apache Commons Site + ${commons.deployment.protocol}://people.apache.org/www/commons.apache.org/${commons.componentid} + + + + + UTF-8 + UTF-8 + 1.6 + 1.6 + + + collections4 + + + 4.1 + (Java 6.0+) + + + 3.2.2 + (Requires Java 1.3 or later) + + commons-collections-${commons.release.2.version} + + COLLECTIONS + 12310465 + + RC2 + 2.9.1 + + collections + https://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-collections + site-content + + + 2.9.1 + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*Test.java + + + **/*$* + **/TestUtils.java + **/Abstract*.java + **/BulkTest.java + + + + + maven-assembly-plugin + + + src/assembly/bin.xml + src/assembly/src.xml + + gnu + + + + maven-checkstyle-plugin + ${checkstyle.version} + + ${basedir}/src/conf/checkstyle.xml + false + + + + org.apache.maven.plugins + maven-scm-publish-plugin + + + javadocs + + + + + + + + + + org.apache.maven.plugins + maven-changes-plugin + ${commons.changes.version} + + + %URL%/%ISSUE% + + + false + Fix Version,Key,Summary,Type,Resolution,Status + + Key DESC,Type,Fix Version DESC + Fixed + Resolved,Closed + + Bug,New Feature,Task,Improvement,Wish,Test + ${commons.release.version} + 500 + + + + + changes-report + jira-report + + + + + + maven-checkstyle-plugin + ${checkstyle.version} + + ${basedir}/src/conf/checkstyle.xml + false + ${basedir}/src/conf/checkstyle-suppressions.xml + + + + + checkstyle + + + + + + org.codehaus.mojo + clirr-maven-plugin + ${commons.clirr.version} + + ${minSeverity} + + + + org.codehaus.mojo + findbugs-maven-plugin + 2.5.5 + + Normal + Default + ${basedir}/src/conf/findbugs-exclude-filter.xml + + + + maven-pmd-plugin + 2.7.1 + + ${maven.compiler.target} + + + + + pmd + cpd + + + + + + org.apache.rat + apache-rat-plugin + + + site-content/**/* + src/test/resources/data/test/* + maven-eclipse.xml + .travis.yml + + + + + + + + + setup-checkout + + + site-content + + + + + + org.apache.maven.plugins + maven-antrun-plugin + 1.7 + + + prepare-checkout + pre-site + + run + + + + + + + + + + + + + + + + + + + + + + + + + + + + travis + + + env.TRAVIS + true + + + + true + + + + + org.jacoco + jacoco-maven-plugin + ${commons.jacoco.version} + + + prepare-agent + + prepare-agent + + + + + + org.eluder.coveralls + coveralls-maven-plugin + 3.1.0 + + + + + + + diff --git a/code/datastudio/src/Common-collection/build.properties b/code/datastudio/src/Common-collection/build.properties new file mode 100644 index 0000000000000000000000000000000000000000..62f2f56224bd03cc44350c5a69d15c787bf18427 --- /dev/null +++ b/code/datastudio/src/Common-collection/build.properties @@ -0,0 +1,9 @@ +output.. = . +bin.includes = META-INF/,\ + xmlbeans-3.1.0.jar,\ + poi-4.1.2.jar,\ + poi-ooxml-4.1.2.jar,\ + poi-ooxml-schemas-4.1.2.jar,\ + commons-collections4-4.4.jar,\ + commons-compress-1.21.jar,\ + commons-math3-3.6.1.jar diff --git a/code/datastudio/src/Common-collection/pom.xml b/code/datastudio/src/Common-collection/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..359902fe39bafdb7bb477c31fde09b0f4746f268 --- /dev/null +++ b/code/datastudio/src/Common-collection/pom.xml @@ -0,0 +1,13 @@ + + + 4.0.0 + + org.opengauss.plide.build + GAUSS_MPP_DB_IDE + 1.0.0-SNAPSHOT + + Common-collection + eclipse-plugin + 1.0.0 + diff --git a/code/datastudio/src/JSQLParser/.classpath b/code/datastudio/src/JSQLParser/.classpath new file mode 100644 index 0000000000000000000000000000000000000000..1d3bd4a03cfcab125cdea43bb9ab75af64785586 --- /dev/null +++ b/code/datastudio/src/JSQLParser/.classpath @@ -0,0 +1,5 @@ + + + + + diff --git a/code/datastudio/src/JSQLParser/.project b/code/datastudio/src/JSQLParser/.project new file mode 100644 index 0000000000000000000000000000000000000000..1f6e44d4389509e07f235d81320b0e3898cffa41 --- /dev/null +++ b/code/datastudio/src/JSQLParser/.project @@ -0,0 +1,34 @@ + + + JSQLParser + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/code/datastudio/src/JSQLParser/META-INF/MANIFEST.MF b/code/datastudio/src/JSQLParser/META-INF/MANIFEST.MF new file mode 100644 index 0000000000000000000000000000000000000000..7e448154666863afe4bd223b8f1f1488d7cabf36 --- /dev/null +++ b/code/datastudio/src/JSQLParser/META-INF/MANIFEST.MF @@ -0,0 +1,38 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: JSQLParser +Bundle-SymbolicName: JSQLParser +Bundle-Version: 1.0.0 +Bundle-RequiredExecutionEnvironment: JavaSE-11 +Export-Package: net.sf.jsqlparser, + net.sf.jsqlparser.expression, + net.sf.jsqlparser.expression.operators.arithmetic, + net.sf.jsqlparser.expression.operators.conditional, + net.sf.jsqlparser.expression.operators.relational, + net.sf.jsqlparser.parser, + net.sf.jsqlparser.schema, + net.sf.jsqlparser.statement, + net.sf.jsqlparser.statement.alter, + net.sf.jsqlparser.statement.create.index, + net.sf.jsqlparser.statement.create.table, + net.sf.jsqlparser.statement.create.view, + net.sf.jsqlparser.statement.delete, + net.sf.jsqlparser.statement.drop, + net.sf.jsqlparser.statement.execute, + net.sf.jsqlparser.statement.insert, + net.sf.jsqlparser.statement.merge, + net.sf.jsqlparser.statement.replace, + net.sf.jsqlparser.statement.select, + net.sf.jsqlparser.statement.truncate, + net.sf.jsqlparser.statement.update, + net.sf.jsqlparser.statement.upsert, + net.sf.jsqlparser.util.cnfexpression, + net.sf.jsqlparser.util.deparser, + net.sf.jsqlparser.statement.values, + net.sf.jsqlparser.statement.alter.sequence, + net.sf.jsqlparser.statement.comment, + net.sf.jsqlparser.statement.create.schema, + net.sf.jsqlparser.statement.create.sequence, + net.sf.jsqlparser.statement.grant +Bundle-ClassPath: jsqlparser-3.2.jar, + . diff --git a/code/datastudio/src/JSQLParser/META-INF/maven/com.github.jsqlparser/jsqlparser/pom.properties b/code/datastudio/src/JSQLParser/META-INF/maven/com.github.jsqlparser/jsqlparser/pom.properties new file mode 100644 index 0000000000000000000000000000000000000000..e958f1f58e9de28a398d80e69b7c8f49db48ccf9 --- /dev/null +++ b/code/datastudio/src/JSQLParser/META-INF/maven/com.github.jsqlparser/jsqlparser/pom.properties @@ -0,0 +1,5 @@ +#Generated by org.apache.felix.bundleplugin +#Thu Jun 29 23:23:43 CEST 2017 +version=1.0.0 +groupId=com.github.jsqlparser +artifactId=JSQLParser diff --git a/code/datastudio/src/JSQLParser/META-INF/maven/com.github.jsqlparser/jsqlparser/pom.xml b/code/datastudio/src/JSQLParser/META-INF/maven/com.github.jsqlparser/jsqlparser/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..6165a3dbb9f73c39d99d6c2719eab8f8f434f2fd --- /dev/null +++ b/code/datastudio/src/JSQLParser/META-INF/maven/com.github.jsqlparser/jsqlparser/pom.xml @@ -0,0 +1,443 @@ + + 4.0.0 + com.github.jsqlparser + JSQLParser + 1.0.0 + JSQLParser library + 2004 + + JSQLParser + + bundle + https://github.com/JSQLParser/JSqlParser + + + + GNU Library or Lesser General Public License (LGPL) V2.1 + http://www.gnu.org/licenses/lgpl-2.1.html + repo + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + + commons-io + commons-io + 2.4 + test + + + junit + junit + 4.12 + test + + + org.hamcrest + hamcrest-library + 1.3 + test + + + org.mockito + mockito-core + 2.7.22 + test + + + + + + Tobias Warneke + t.warneke@gmx.net + + + + + + sonatype-nexus-staging + https://oss.sonatype.org/service/local/staging/deploy/maven2 + + + sonatype-nexus-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + + + + scm:git:https://github.com/JSQLParser/JSqlParser.git + scm:git:ssh://git@github.com:JSQLParser/JSqlParser.git + https://github.com/JSQLParser/JSqlParser.git + jsqlparser-1.1 + + + + GitHub Issues + https://github.com/JSQLParser/JSqlParser/issues + + + + + + maven-compiler-plugin + 3.3 + + 1.6 + 1.6 + true + + -Xlint:all + + ${project.build.sourceEncoding} + + + + org.codehaus.mojo + javacc-maven-plugin + 2.6 + + + javacc + generate-sources + + jjtree-javacc + + + + + true + true + true + + + + net.java.dev.javacc + javacc + 7.0.2 + + + + + org.apache.maven.plugins + maven-eclipse-plugin + 2.9 + + + /target/generated-sources/javacc + + + + + org.apache.maven.plugins + maven-resources-plugin + 2.6 + + ${project.build.sourceEncoding} + + + + org.codehaus.mojo + license-maven-plugin + 1.6 + + false + false + false + + + + first + + update-file-header + + process-sources + + lgpl_v2_1 + + src/main/java + + + + + + + org.apache.maven.plugins + maven-release-plugin + 2.5.3 + + true + false + forked-path + + + + org.apache.maven.scm + maven-scm-provider-gitexe + 1.9.5 + + + + + org.apache.maven.plugins + maven-source-plugin + 2.4 + + + attach-sources + + jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.3 + + + attach-javadocs + + ${javadoc.opts} + + + jar + + + + + + maven-site-plugin + 3.3 + + + attach-descriptor + + attach-descriptor + + + + + en + + + + org.eluder.coveralls + coveralls-maven-plugin + 3.1.0 + + + org.codehaus.mojo + cobertura-maven-plugin + 2.7 + + xml + 256m + + + net/sf/jsqlparser/parser/*.class + net/sf/jsqlparser/JSQLParserException.class + + + + + + org.apache.felix + maven-bundle-plugin + 3.0.1 + true + + + org.apache.maven.plugins + maven-surefire-plugin + 2.15 + + + + + + + + org.apache.maven.plugins + maven-surefire-report-plugin + 2.16 + + ${project.reporting.outputDirectory}/testresults + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.3 + + true + + + + html + + javadoc + + + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.7 + + + org.apache.maven.plugins + maven-jxr-plugin + 2.3 + + true + + + + org.codehaus.mojo + cobertura-maven-plugin + 2.6 + + true + %{project.reporting.outputDirectory}/cobertura + + + + org.codehaus.mojo + findbugs-maven-plugin + 2.5.3 + + + org.codehaus.mojo + javacc-maven-plugin + 2.6 + + + + + + + sign-release-artifacts + + + performRelease + true + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.4 + + + sign-artifacts + verify + + sign + + + f22e0543 + + + + + + + + + doclint-java8-disable + + [1.8,) + + + -Xdoclint:none + + + + check.sources + + + !skipCheckSources + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 2.17 + + + verify-style + process-classes + + check + + + + + true + true + ${project.build.sourceDirectory} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + com.puppycrawl.tools + checkstyle + 6.19 + + + + + + + + + + UTF-8 + + + JSqlParser parses an SQL statement and translate it into a hierarchy of Java classes. + The generated hierarchy can be navigated using the Visitor Pattern. + diff --git a/code/datastudio/src/JSQLParser/build.properties b/code/datastudio/src/JSQLParser/build.properties new file mode 100644 index 0000000000000000000000000000000000000000..2cbc8e2d2f7ee5f8215203db2d28729ab8a53b9e --- /dev/null +++ b/code/datastudio/src/JSQLParser/build.properties @@ -0,0 +1,4 @@ +source.. = . +output.. = . +bin.includes = META-INF/,\ + jsqlparser-3.2.jar diff --git a/code/datastudio/src/JSQLParser/pom.xml b/code/datastudio/src/JSQLParser/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..80129eb9f05585271f5c8cdd6072139a4f01105f --- /dev/null +++ b/code/datastudio/src/JSQLParser/pom.xml @@ -0,0 +1,13 @@ + + + 4.0.0 + + org.opengauss.plide.build + GAUSS_MPP_DB_IDE + 1.0.0-SNAPSHOT + + JSQLParser + eclipse-plugin + 1.0.0 + diff --git a/code/datastudio/src/StartDataStudio.bat b/code/datastudio/src/StartDataStudio.bat new file mode 100644 index 0000000000000000000000000000000000000000..1a7aeb9fd676690a9fcc9883425db2ffa9bfdad0 --- /dev/null +++ b/code/datastudio/src/StartDataStudio.bat @@ -0,0 +1,276 @@ +@ECHO OFF +IF NOT DEFINED IS_MINIMIZED set IS_MINIMIZED=1 && start "" /min "%~dpnx0" %* && exit +SET PATH=%PATH%;%SystemRoot%\system32\WindowsPowerShell\v1.0;C:\Windows\winsxs\x86_microsoft-windows-w..ommand-line-utility_31bf3856ad364e35_6.1.7600.16385_none_a1802b822e2a878c; +SETLOCAL ENABLEEXTENSIONS +ECHO Checking for OS Name.............. +For /F "usebackq tokens=2 delims=:" %%i in (`systeminfo /FO "LIST" ^| Findstr /B /C:"OS Name:"`) DO SET OS_NAME=%%i +Echo %OS_NAME% + +SET OS_LANG=ENG +FOR /F "tokens=2 delims==" %%G in ('wmic os get OSLanguage /Value') DO SET OS_LANG=%%G + IF /I "%OS_LANG%" EQU "1033" ( + SET LANG=ENG + ) + IF /I "%OS_LANG%" EQU "4" ( + SET LANG=CHZ + ) + IF /I "%OS_LANG%" EQU "31748" ( + SET LANG=CHZ + ) + IF /I "%OS_LANG%" EQU "1028" ( + SET LANG=CHZ + ) + IF /I "%OS_LANG%" EQU "2052" ( + SET LANG=CHZ + ) + IF /I "%OS_LANG%" EQU "3076" ( + SET LANG=CHZ + ) + IF /I "%OS_LANG%" EQU "4100" ( + SET LANG=CHZ + ) + IF /I "%OS_LANG%" EQU "5124" ( + SET LANG=CHZ + ) + +IF NOT EXIST """..\Data Studio.ini""" IF "%LANG%" == "ENG" ( + + START /MIN CMD /c "powershell.exe [Reflection.Assembly]::LoadWithPartialName("""System.Windows.Forms""");[Windows.Forms.MessageBox]::show("""Data Studio.ini file does not exist""","""Data Studio""",0,48)>nul" + Exit + ) + +IF NOT EXIST """..\Data Studio.ini""" IF "%LANG%" == "CHZ" ( + + START /MIN CMD /c "powershell.exe [Reflection.Assembly]::LoadWithPartialName("""System.Windows.Forms""");[Windows.Forms.MessageBox]::show("""Data Studio.ini ļ ""","""Data Studio""",0,48)>nul" + Exit + ) + +ECHO Checking for Java Compatibility.............. + +:: Check Data Studio Version is 32 bit or 64 bit +SET DS_BIT=0 +FOR /F "tokens=*" %%G in ('findstr /C:"x86_64" "..\Data Studio.ini"') DO SET DS_VERSION=%%G + IF /I "%DS_VERSION%" EQU "" ( + SET DS_BIT=32 + ECHO "DS VERSION is 32 Bit" + ) ELSE ( + SET DS_BIT=64 + ECHO "DS VERSION is 64 Bit" + ) + +:: Step2 - Get the OS_VERSION (32 Bit or 64 Bit); +SET OS_BIT=0 +FOR /F "tokens=2 delims=:" %%G in ('Systeminfo ^| Findstr "x64-based"') DO SET OS_VERSION=64bit + IF /I "%OS_VERSION%" EQU "64bit" ( + SET OS_BIT=64 + ECHO "OS VERSION is 64 Bit" + ) ELSE ( + SET OS_BIT=32 + ECHO "OS VERSION is 32 Bit" + ) + + +:JAVA_BIT_CHECK + :: Step4 - Get the Java Version using wmic and check if it 64 Bit + Echo Checking for Java 8 64 bit Version ................. + SET JAVA_BIT_64=0 + FOR /F "tokens=*" %%G in ('wmic product get name ^, version ^| findstr /B /C:"Java" ^| findstr "8" ^| findstr "64-bit"') DO SET JAVA_VERSION=%%G + + IF /I NOT "%JAVA_VERSION%" == "" ( + SET JAVA_BIT_64=64 + ECHO "Has Java 8 with 64 bit" + GOTO JAVA8_32BIT_CHECK + + ) + + +:JAVA8_32BIT_CHECK + + SET JAVA_BIT_32=0 + + Echo Checking for Java 8 32 bit Version ................. + FOR /F "tokens=*" %%G in ('wmic product get name ^, version ^| findstr /B /C:"Java" ^| findstr "8" ^| findstr /V "64-bit" ^| findstr /V "Java\ Auto"') DO SET JAVA_VERSION1=%%G + + IF /I NOT "%JAVA_VERSION1%" == "" ( + + SET JAVA_BIT_32=32 + REM ECHO %JAVA_BIT_32% + ECHO "Has Java 8 with 32 bit" + GOTO CHECK_LANG + ) + + + IF %JAVA_BIT_64% == 0 IF %JAVA_BIT_32% == 0 ( + GOTO JAVA_LOWER_CHECK + ) + GOTO CHECK_LANG + +:JAVA_LOWER_CHECK + SET JAVA_BIT=0 + Echo Checking for Java minimum version .............. + + + FOR /F "tokens=*" %%G in ('wmic product get name ^, version ^| findstr /B /C:"Java" ^| findstr /V "8"') DO SET JAVA_LOWER_VERSION=%%G + + IF /I NOT "%JAVA_LOWER_VERSION%" == "" IF "%LANG%" == "ENG" ( + + @echo off + START /MIN CMD /c "powershell.exe [Reflection.Assembly]::LoadWithPartialName("""System.Windows.Forms""");[Windows.Forms.MessageBox]::show("""Data Studio is supported with minimum Java Version of 1.8. `n`nInstall Java version 1.8 in order to use Data Studio.""", """Unsupported Java Version""",0,48)>nul" + GOTO EXIT + ) + IF /I NOT "%JAVA_LOWER_VERSION%" == "" IF "%LANG%" == "CHZ" ( + + @echo off + START /MIN CMD /c "powershell.exe [Reflection.Assembly]::LoadWithPartialName("""System.Windows.Forms""");[Windows.Forms.MessageBox]::show("""֧Data StudioJava汾Ϊ1.8`n`n ʹ Data Studio ǰ谲װ Java 1.8 """, """ ָ֧ Java 汾 """,0,48)>nul" + GOTO EXIT + ) + + +:CHECK_LANG + + + echo Langauge is %LANG% + + IF /I "%LANG%" EQU "ENG" ( + GOTO PRINT_MSG_ENG + ) ELSE ( + GOTO PRINT_MSG_CHZ + ) + TIMEOUT /T 5 + GOTO EXIT + + + +:PRINT_MSG_ENG + +::Invalid scenarios +:: Java 32 Bit and Java 64 bit is installed in machine + + IF /I %JAVA_BIT_64% == %DS_BIT% IF %OS_BIT% == 64 ( + + Goto runDS + GOTO EXIT + ) + IF /I %JAVA_BIT_32% == %DS_BIT% IF %OS_BIT% == 64 ( + Goto runDS + GOTO EXIT + ) + IF /I %JAVA_BIT_32% == %DS_BIT% IF %OS_BIT% == 32 ( + GOTO runDS + GOTO EXIT + ) + + + IF %JAVA_BIT_64% == 64 IF %DS_BIT% == 32 IF %OS_BIT% == 64 ( + + Echo "OS is %OS_BIT% , Java 1.8 %JAVA_BIT_64% Bit Data Studio %DS_BIT% Bit" + START /MIN /B CMD /C "powershell.exe [Reflection.Assembly]::LoadWithPartialName("""System.Windows.Forms""");[Windows.Forms.MessageBox]::show("""You are attempting to run 32-bit Data Studio on: `n`n . 64 bit OS `n . %OS_NAME% `n . Java 1.8 64-bit JDK ^(Incompatible^) `n`n Please install Java 1.8 32-bit """, """Unsupported Java Version""",0,48)>nul" + GOTO EXIT + ) + + IF %JAVA_BIT_32% == 32 IF %DS_BIT% == 64 IF %OS_BIT% == 64 ( + + Echo "OS is %OS_BIT% , Java 1.8 %JAVA_BIT_32% Bit Data Studio %DS_BIT% Bit" + START /MIN CMD /C "powershell.exe [Reflection.Assembly]::LoadWithPartialName("""System.Windows.Forms""");[Windows.Forms.MessageBox]::show("""You are attempting to run 64-bit Data Studio on: `n`n . 64 bit OS `n . %OS_NAME% `n . Java 1.8 32-bit JDK ^(Incompatible^) `n`n Please install Java 1.8 64-bit """, """Unsupported Java Version""",0,48)>nul" + GOTO EXIT + ) + + IF %JAVA_BIT_32% == 32 IF %DS_BIT% == 64 IF %OS_BIT% == 32 ( + + Echo "OS is %OS_BIT% , Java 1.8 %JAVA_BIT_32% Bit Data Studio %DS_BIT% Bit" + START /MIN CMD /C "powershell.exe [Reflection.Assembly]::LoadWithPartialName("""System.Windows.Forms""");[Windows.Forms.MessageBox]::show("""You are attempting to run 64-bit Data Studio on: `n`n . 32 bit OS `n . %OS_NAME% `n . DS Version 64 Bit ^(Incompatible^) `n`n Please install 32 bit DS """, """Unsupported DS Version""",0,48)>nul" + GOTO EXIT + ) + + + ::Valid scenarios + + IF %JAVA_BIT_64% == 64 IF %DS_BIT% == 64 IF %OS_BIT% == 64 ( + Echo "OS is %OS_BIT% , Java 1.8 %JAVA_BIT_64% Bit Data Studio %DS_BIT% Bit" + GOTO runDS + GOTO EXIT + ) + + IF %JAVA_BIT_32% == 32 IF %DS_BIT% == 32 IF %OS_BIT% == 32 ( + Echo "OS is %OS_BIT% , Java 1.8 %JAVA_BIT_32% Bit Data Studio %DS_BIT% Bit " + GOTO runDS + GOTO EXIT + ) + IF %JAVA_BIT_32% == 32 IF %DS_BIT% == 32 IF %OS_BIT% == 64 ( + Echo "OS is %OS_BIT% , Java 1.8 %JAVA_BIT_32% Bit Data Studio %DS_BIT% Bit " + GOTO runDS + GOTO EXIT + ) + +:PRINT_MSG_CHZ + +::Invalid scenarios +:: Java 32 Bit and Java 64 bit is installed in machine + + IF /I %JAVA_BIT_64% == %DS_BIT% IF %OS_BIT% == 64 ( + Goto runDS + GOTO EXIT + ) + IF /I %JAVA_BIT_32% == %DS_BIT% IF %OS_BIT% == 64 ( + Goto runDS + GOTO EXIT + ) + IF /I %JAVA_BIT_32% == %DS_BIT% IF %OS_BIT% == 32 ( + GOTO runDS + GOTO EXIT + ) + + + IF %JAVA_BIT_64% == 64 IF %DS_BIT% == 32 IF %OS_BIT% == 64 ( + + Echo "OS is %OS_BIT% , Java 1.8 %JAVA_BIT_64% Bit Data Studio %DS_BIT% Bit" + START /MIN /B CMD /C "powershell.exe [Reflection.Assembly]::LoadWithPartialName("""System.Windows.Forms""");[Windows.Forms.MessageBox]::show("""ͼ»32λData Studio`n`n . 64 λϵͳ `n . %OS_NAME% `n . 64λJava 1.8 JDK ^^ `n`n ʹ64λData Studio """, """ָ֧ Data Studio 汾""",0,48)>nul" + GOTO EXIT + ) + + IF %JAVA_BIT_32% == 32 IF %DS_BIT% == 64 IF %OS_BIT% == 64 ( + + Echo "OS is %OS_BIT% , Java 1.8 %JAVA_BIT_32% Bit Data Studio %DS_BIT% Bit" + START /MIN CMD /C "powershell.exe [Reflection.Assembly]::LoadWithPartialName("""System.Windows.Forms""");[Windows.Forms.MessageBox]::show("""ͼ»64λData Studio `n`n . 64λϵͳ `n . %OS_NAME% `n . 32λJava 1.8 JDK ^^`n`n 밲װ64λJava 1.8 """, """ָ֧ Java 汾""",0,48)>nul" + GOTO EXIT + ) + + REM ADDED NEW SCENARIO FOR JAVA 32 BIT AND DS 64 BIT AND OS 32 BIT + IF %JAVA_BIT_32% == 32 IF %DS_BIT% == 64 IF %OS_BIT% == 32 ( + + Echo "OS is %OS_BIT% , Java 1.8 %JAVA_BIT_32% Bit Data Studio %DS_BIT% Bit" + START /MIN CMD /C "powershell.exe [Reflection.Assembly]::LoadWithPartialName("""System.Windows.Forms""");[Windows.Forms.MessageBox]::show("""ͼ»64λData Studio `n`n . 32λϵͳ `n . %OS_NAME% `n . 32λJava 1.8 JDK ^^`n`n ʹ32λData Studio """, """ָ֧ Data Studio 汾""",0,48)>nul" + GOTO EXIT + ) + REM ADDED NEW SCENARIO +::Valid scenarios + + IF %JAVA_BIT_64% == 64 IF %DS_BIT% == 64 IF %OS_BIT% == 64 ( + Echo "OS is %OS_BIT% , Java 1.8 %JAVA_BIT_64% Bit Data Studio %DS_BIT% Bit" + GOTO runDS + GOTO EXIT + ) + + IF %JAVA_BIT_32% == 32 IF %DS_BIT% == 32 IF %OS_BIT% == 32 ( + Echo "OS is %OS_BIT% , Java 1.8 %JAVA_BIT_32% Bit Data Studio %DS_BIT% Bit " + GOTO runDS + GOTO EXIT + ) + IF %JAVA_BIT_32% == 32 IF %DS_BIT% == 32 IF %OS_BIT% == 64 ( + Echo "OS is %OS_BIT% , Java 1.8 %JAVA_BIT_32% Bit Data Studio %DS_BIT% Bit " + GOTO runDS + GOTO EXIT + ) + +:runDS + Echo "Launching Data Studio" + CD .. + call START "" "Data Studio.exe" + TIMEOUT /T 5 + GOTO EXIT + +@ECHO ON +:EXIT +Exit + + \ No newline at end of file diff --git a/code/datastudio/src/commons-csv/.classpath b/code/datastudio/src/commons-csv/.classpath new file mode 100644 index 0000000000000000000000000000000000000000..8b86a462099b2299803ea807ad95ca1a35f52c7c --- /dev/null +++ b/code/datastudio/src/commons-csv/.classpath @@ -0,0 +1,5 @@ + + + + + diff --git a/code/datastudio/src/commons-csv/.project b/code/datastudio/src/commons-csv/.project new file mode 100644 index 0000000000000000000000000000000000000000..d3686dcfbf292dcd81e8d97cc7ff518e2ad33135 --- /dev/null +++ b/code/datastudio/src/commons-csv/.project @@ -0,0 +1,34 @@ + + + commons-csv + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/code/datastudio/src/commons-csv/META-INF/MANIFEST.MF b/code/datastudio/src/commons-csv/META-INF/MANIFEST.MF new file mode 100644 index 0000000000000000000000000000000000000000..5688e569ac911494fd7a3a1b045a547362757864 --- /dev/null +++ b/code/datastudio/src/commons-csv/META-INF/MANIFEST.MF @@ -0,0 +1,9 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: 4 +Bundle-SymbolicName: commons-csv +Bundle-Version: 1.0.0 +Bundle-RequiredExecutionEnvironment: JavaSE-11 +Export-Package: org.apache.commons.csv +Bundle-ClassPath: ., + commons-csv-1.9.0.jar diff --git a/code/datastudio/src/commons-csv/build.properties b/code/datastudio/src/commons-csv/build.properties new file mode 100644 index 0000000000000000000000000000000000000000..cac2cbd1ff27b20094390e40f8863a3a3b045dc4 --- /dev/null +++ b/code/datastudio/src/commons-csv/build.properties @@ -0,0 +1,4 @@ +source.. = . +output.. = . +bin.includes = META-INF/,\ + commons-csv-1.9.0.jar diff --git a/code/datastudio/src/commons-csv/pom.xml b/code/datastudio/src/commons-csv/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..f5c43e61de113d22744e4b78db72d7d7b276724b --- /dev/null +++ b/code/datastudio/src/commons-csv/pom.xml @@ -0,0 +1,34 @@ + + + 4.0.0 + + org.opengauss.plide.build + GAUSS_MPP_DB_IDE + 1.0.0-SNAPSHOT + + commons-csv + eclipse-plugin + + + 1.0.0 + diff --git a/code/datastudio/src/copyExternalsToBuild.bat b/code/datastudio/src/copyExternalsToBuild.bat new file mode 100644 index 0000000000000000000000000000000000000000..b6b8bc23cecdfb242edf6fd0a83753a963c352c8 --- /dev/null +++ b/code/datastudio/src/copyExternalsToBuild.bat @@ -0,0 +1,258 @@ +set SOURCE=..\..\.. +set DEST=.\ +set TEST=..\testcode\LLT\ + +call mvn dependency:copy-dependencies -f %SOURCE%\3rd_src\pom.xml +::0 Delete the old folders +rmdir /Q /S %DEST%\org.opengauss.mppdbide.repository\tools +rmdir /Q /S ..\docs +rmdir /Q /S %DEST%\..\build +rmdir /Q /S %DEST%\db_assistant + +xcopy %SOURCE%\platform\Gauss200\gs_jdbc\gsjdbc4.jar %DEST%\org.opengauss.mppdbide.presentation\src-test\. +xcopy %SOURCE%\3rd_src\target\dependency\hamcrest-api-1.0.jar %DEST%\org.opengauss.mppdbide.presentation\src-test\. +xcopy %SOURCE%\3rd_src\target\dependency\junit-4.11.jar %DEST%\org.opengauss.mppdbide.presentation\src-test\. +xcopy %SOURCE%\3rd_src\target\dependency\log4j-1.2.15.jar %DEST%\org.opengauss.mppdbide.presentation\src-test\. +xcopy %SOURCE%\3rd_src\target\dependency\commons-logging-1.0.4.jar %DEST%\org.opengauss.mppdbide.presentation\src-test\. +xcopy %SOURCE%\3rd_src\target\dependency\oro-2.0.8.jar %DEST%\org.opengauss.mppdbide.presentation\src-test\. +xcopy %SOURCE%\3rd_src\target\dependency\jdom-2.0.2.jar %DEST%\org.opengauss.mppdbide.presentation\src-test\. +xcopy %SOURCE%\3rd_src\target\dependency\mockrunner-jdbc-2.0.6.jar %DEST%\org.opengauss.mppdbide.presentation\src-test\. +xcopy %SOURCE%\3rd_src\target\dependency\mockrunner-core-2.0.6.jar %DEST%\org.opengauss.mppdbide.presentation\src-test\. +xcopy %SOURCE%\3rd_src\target\dependency\xml-apis-1.0.b2.jar %DEST%\org.opengauss.mppdbide.presentation\src-test\. +xcopy %SOURCE%\3rd_src\target\dependency\cglib-nodep-3.3.0.jar %DEST%\org.opengauss.mppdbide.presentation\src-test\. +xcopy %SOURCE%\3rd_src\target\dependency\easymock-4.3.jar %DEST%\org.opengauss.mppdbide.presentation\src-test\. +xcopy %SOURCE%\3rd_src\target\dependency\objenesis-3.2.jar %DEST%\org.opengauss.mppdbide.presentation\src-test\. +xcopy %SOURCE%\3rd_src\target\dependency\commons-codec-1.15.jar %DEST%\org.opengauss.mppdbide.presentation\src-test\. +xcopy %SOURCE%\3rd_src\target\dependency\commons-lang3-3.12.0.jar %DEST%\org.opengauss.mppdbide.presentation\src-test\. +xcopy %SOURCE%\3rd_src\target\dependency\gson-2.8.6.jar %DEST%\org.opengauss.mppdbide.presentation\src-test\. + +::1. Copy the external files from platform, 3rd Src to respective src folders +xcopy %SOURCE%\3rd_src\target\dependency\commons-collections4-4.4.jar %DEST%\Common-collection\. /Y /S /E +xcopy %SOURCE%\3rd_src\target\dependency\poi-4.1.2.jar %DEST%\Common-collection\. /Y /S /E +xcopy %SOURCE%\3rd_src\target\dependency\poi-ooxml-4.1.2.jar %DEST%\Common-collection\. /Y /S /E +xcopy %SOURCE%\3rd_src\target\dependency\poi-ooxml-schemas-4.1.2.jar %DEST%\Common-collection\. /Y /S /E +xcopy %SOURCE%\3rd_src\target\dependency\xmlbeans-3.1.0.jar %DEST%\Common-collection\. /Y /S /E +xcopy %SOURCE%\3rd_src\target\dependency\commons-compress-1.21.jar %DEST%\Common-collection\. /Y /S /E +xcopy %SOURCE%\3rd_src\target\dependency\commons-math3-3.6.1.jar %DEST%\Common-collection\. /Y /S /E +xcopy %SOURCE%\3rd_src\target\dependency\commons-csv-1.9.0.jar %DEST%\commons-csv\. /Y /S /E +xcopy %SOURCE%\3rd_src\target\dependency\commons-io-2.11.0.jar %DEST%\org.opengauss.mppdbide.bl\. +xcopy %SOURCE%\3rd_src\target\dependency\jsqlparser-3.2.jar %DEST%\JSQLParser\. /Y /S /E +xcopy %SOURCE%\3rd_src\target\dependency\antlr4-runtime-4.9.2.jar %DEST%\org.opengauss.mppdbide.parser\. /Y /S /E +xcopy %SOURCE%\3rd_src\target\dependency\log4j-api-2.17.1.jar %DEST%\org.opengauss.mppdbide.utils\. /Y /S /E +xcopy %SOURCE%\3rd_src\target\dependency\log4j-core-2.17.1.jar %DEST%\org.opengauss.mppdbide.utils\. /Y /S /E +xcopy %SOURCE%\3rd_src\target\dependency\gson-2.8.6.jar %DEST%\org.opengauss.mppdbide.bl\. /Y /S /E +xcopy %SOURCE%\3rd_src\target\dependency\commons-lang3-3.12.0.jar %DEST%\org.opengauss.mppdbide.bl\. /Y /S /E +xcopy %SOURCE%\3rd_src\target\dependency\gson-2.8.6.jar %DEST%\org.opengauss.mppdbide.explainplan\. /Y /S /E +xcopy %SOURCE%\3rd_src\target\dependency\gson-2.8.6.jar %DEST%\org.opengauss.mppdbide.view\. /Y /S /E +xcopy %SOURCE%\3rd_src\target\dependency\guava-30.1.1-jre.jar %DEST%\org.opengauss.mppdbide.view\. /Y /S /E +xcopy %SOURCE%\3rd_src\target\dependency\javafx-base-18-ea+2-win.jar %DEST%\org.opengauss.mppdbide.view\. /Y /S /E +xcopy %SOURCE%\3rd_src\target\dependency\javafx-controls-18-ea+2-win.jar %DEST%\org.opengauss.mppdbide.view\. /Y /S /E +xcopy %SOURCE%\3rd_src\target\dependency\javafx-graphics-18-ea+2-win.jar %DEST%\org.opengauss.mppdbide.view\. /Y /S /E +xcopy %SOURCE%\platform\Gauss200\gs_jdbc\gsjdbc4.jar %DEST%\org.opengauss.dbdriver.jdbc.gauss\. /Y /S /E + +rmdir /Q /S %TEST%\org.opengauss.mppdbide.adapter.test.fragment\lib +mkdir %TEST%\org.opengauss.mppdbide.adapter.test.fragment\lib +xcopy %SOURCE%\3rd_src\target\dependency\commons-logging-1.0.4.jar %TEST%\org.opengauss.mppdbide.adapter.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\oro-2.0.8.jar %TEST%\org.opengauss.mppdbide.adapter.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\jdom-2.0.2.jar %TEST%\org.opengauss.mppdbide.adapter.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\xml-apis-1.0.b2.jar %TEST%\org.opengauss.mppdbide.adapter.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\hamcrest-api-1.0.jar %TEST%\org.opengauss.mppdbide.adapter.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\easymock-4.3.jar %TEST%\org.opengauss.mppdbide.adapter.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\gson-2.8.6.jar %TEST%\org.opengauss.mppdbide.adapter.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\log4j-1.2.15.jar %TEST%\org.opengauss.mppdbide.adapter.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\mockrunner-jdbc-2.0.6.jar %TEST%\org.opengauss.mppdbide.adapter.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\mockrunner-core-2.0.6.jar %TEST%\org.opengauss.mppdbide.adapter.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\commons-codec-1.15.jar %TEST%\org.opengauss.mppdbide.adapter.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\log4j-1.2.15.jar %TEST%\org.opengauss.mppdbide.adapter.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\org.eclipse.osgi-3.9.1.v20130814-1242.jar %TEST%\org.opengauss.mppdbide.adapter.test.fragment\lib\. +xcopy %SOURCE%\platform\Gauss200\gs_jdbc\gsjdbc4.jar %TEST%\org.opengauss.mppdbide.adapter.test.fragment\lib\. + +rmdir /Q /S %TEST%\org.opengauss.mppdbide.bl.debug.test.fragment\lib +mkdir %TEST%\org.opengauss.mppdbide.bl.debug.test.fragment\lib +xcopy %SOURCE%\3rd_src\target\dependency\commons-logging-1.0.4.jar %TEST%\org.opengauss.mppdbide.bl.debug.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\oro-2.0.8.jar %TEST%\org.opengauss.mppdbide.bl.debug.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\jdom-2.0.2.jar %TEST%\org.opengauss.mppdbide.bl.debug.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\xml-apis-1.0.b2.jar %TEST%\org.opengauss.mppdbide.bl.debug.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\hamcrest-api-1.0.jar %TEST%\org.opengauss.mppdbide.bl.debug.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\easymock-4.3.jar %TEST%\org.opengauss.mppdbide.bl.debug.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\gson-2.8.6.jar %TEST%\org.opengauss.mppdbide.bl.debug.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\log4j-1.2.15.jar %TEST%\org.opengauss.mppdbide.bl.debug.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\mockrunner-jdbc-2.0.6.jar %TEST%\org.opengauss.mppdbide.bl.debug.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\mockrunner-core-2.0.6.jar %TEST%\org.opengauss.mppdbide.bl.debug.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\junit-4.11.jar %TEST%\org.opengauss.mppdbide.bl.debug.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\commons-io-2.11.0.jar %TEST%\org.opengauss.mppdbide.bl.debug.test.fragment\lib\. + +rmdir /Q /S %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib +mkdir %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib +xcopy %SOURCE%\3rd_src\target\dependency\commons-logging-1.0.4.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\oro-2.0.8.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\jdom-2.0.2.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\jsqlparser-3.2.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\xml-apis-1.0.b2.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\hamcrest-api-1.0.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\easymock-4.3.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\gson-2.8.6.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\log4j-1.2.15.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\junit-4.11.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\jsqlparser-3.2.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\org.eclipse.osgi-3.9.1.v20130814-1242.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\commons-io-2.11.0.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\powermock-api-mockito-1.6.6.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\powermock-module-testng-common-1.6.6.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\powermock-api-mockito-common-1.6.6.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\powermock-api-support-1.6.6.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\powermock-module-testng-1.6.6.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\powermock-core-1.6.6.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\powermock-api-easymock-1.6.6.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\powermock-classloading-base-1.6.6.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\powermock-module-junit4-legacy-1.6.6.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\powermock-module-javaagent-1.6.6.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\powermock-module-junit4-1.6.6.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\powermock-module-junit4-common-1.6.6.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\powermock-module-junit4-rule-agent-1.6.6.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\powermock-module-testng-agent-1.6.6.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\powermock-reflect-1.6.6.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\bsh-2.0b4.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\cglib-nodep-3.3.0.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\javassist-3.20.0-GA.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\jcommander-1.27.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\mockito-all-1.10.19.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\objenesis-3.2.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\snakeyaml-1.30.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\platform\Gauss200\gs_jdbc\gsjdbc4.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. +xcopy %SOURCE%\platform\Gauss200\gs_jdbc\mockrunner-jdbc.jar %TEST%\org.opengauss.mppdbide.bl.test.fragment\lib\. + +rmdir /Q /S %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib +mkdir %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib +xcopy %SOURCE%\3rd_src\target\dependency\commons-logging-1.0.4.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\jdom-2.0.2.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\mockrunner-jdbc-2.0.6.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\mockrunner-core-2.0.6.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\xml-apis-1.0.b2.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\gson-2.8.6.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\platform\Gauss200\gs_jdbc\gsjdbc4.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\hamcrest-api-1.0.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\jsqlparser-3.2.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\junit-4.11.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\log4j-1.2.15.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\commons-io-2.11.0.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\objenesis-3.2.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\easymock-4.3.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\objenesis-3.2.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\oro-2.0.8.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\org.eclipse.core.contenttype-3.4.100.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\org.eclipse.core.jobs-3.5.100.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\org.eclipse.core.runtime-3.7.0.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\org.eclipse.e4.core.services-2.0.100.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\org.eclipse.e4.core.di-1.8.100.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\org.eclipse.equinox.app-1.3.100.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\org.eclipse.equinox.common-3.6.0.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\org.eclipse.equinox.preferences-3.6.1.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\org.eclipse.equinox.registry-3.6.100.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\org.eclipse.osgi-3.9.1.v20130814-1242.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\org.eclipse.osgi.services-3.5.100.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\runtime_registry_compatibility-4.3.1.jar %TEST%\org.opengauss.mppdbide.bl.windows.test.fragment\lib\. + +rmdir /Q /S %TEST%\org.opengauss.mppdbide.editor.extension.test.fragment\lib +mkdir %TEST%\org.opengauss.mppdbide.editor.extension.test.fragment\lib +xcopy %SOURCE%\3rd_src\target\dependency\antlr4-runtime-4.9.2.jar %TEST%\org.opengauss.mppdbide.editor.extension.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\log4j-1.2.15.jar %TEST%\org.opengauss.mppdbide.editor.extension.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\commons-codec-1.15.jar %TEST%\org.opengauss.mppdbide.editor.extension.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\hamcrest-api-1.0.jar %TEST%\org.opengauss.mppdbide.editor.extension.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\junit-4.11.jar %TEST%\org.opengauss.mppdbide.editor.extension.test.fragment\lib\. + +rmdir /Q /S %TEST%\org.opengauss.mppdbide.explainplan.test.fragment\lib +mkdir %TEST%\org.opengauss.mppdbide.explainplan.test.fragment\lib +xcopy %SOURCE%\3rd_src\target\dependency\commons-logging-1.0.4.jar %TEST%\org.opengauss.mppdbide.explainplan.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\oro-2.0.8.jar %TEST%\org.opengauss.mppdbide.explainplan.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\jdom-2.0.2.jar %TEST%\org.opengauss.mppdbide.explainplan.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\xml-apis-1.0.b2.jar %TEST%\org.opengauss.mppdbide.explainplan.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\hamcrest-api-1.0.jar %TEST%\org.opengauss.mppdbide.explainplan.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\easymock-4.3.jar %TEST%\org.opengauss.mppdbide.explainplan.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\gson-2.8.6.jar %TEST%\org.opengauss.mppdbide.explainplan.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\log4j-1.2.15.jar %TEST%\org.opengauss.mppdbide.explainplan.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\commons-codec-1.15.jar %TEST%\org.opengauss.mppdbide.explainplan.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\junit-4.11.jar %TEST%\org.opengauss.mppdbide.explainplan.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\mockrunner-jdbc-2.0.6.jar %TEST%\org.opengauss.mppdbide.explainplan.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\mockrunner-core-2.0.6.jar %TEST%\org.opengauss.mppdbide.explainplan.test.fragment\lib\. + +rmdir /Q /S %TEST%\org.opengauss.mppdbide.parser.test.fragment\lib +mkdir %TEST%\org.opengauss.mppdbide.parser.test.fragment\lib +xcopy %SOURCE%\3rd_src\target\dependency\commons-logging-1.0.4.jar %TEST%\org.opengauss.mppdbide.parser.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\oro-2.0.8.jar %TEST%\org.opengauss.mppdbide.parser.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\jdom-2.0.2.jar %TEST%\org.opengauss.mppdbide.parser.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\xml-apis-1.0.b2.jar %TEST%\org.opengauss.mppdbide.parser.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\hamcrest-api-1.0.jar %TEST%\org.opengauss.mppdbide.parser.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\easymock-4.3.jar %TEST%\org.opengauss.mppdbide.parser.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\gson-2.8.6.jar %TEST%\org.opengauss.mppdbide.parser.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\log4j-1.2.15.jar %TEST%\org.opengauss.mppdbide.parser.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\commons-codec-1.15.jar %TEST%\org.opengauss.mppdbide.parser.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\junit-4.11.jar %TEST%\org.opengauss.mppdbide.parser.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\antlr4-runtime-4.9.2.jar %TEST%\org.opengauss.mppdbide.parser.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\mockrunner-jdbc-2.0.6.jar %TEST%\org.opengauss.mppdbide.parser.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\mockrunner-core-2.0.6.jar %TEST%\org.opengauss.mppdbide.parser.test.fragment\lib\. + +rmdir /Q /S %TEST%\org.opengauss.mppdbide.presentation.windows.test.fragment\lib +mkdir %TEST%\org.opengauss.mppdbide.presentation.windows.test.fragment\lib +xcopy %SOURCE%\3rd_src\target\dependency\commons-logging-1.0.4.jar %TEST%\org.opengauss.mppdbide.presentation.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\oro-2.0.8.jar %TEST%\org.opengauss.mppdbide.presentation.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\jdom-2.0.2.jar %TEST%\org.opengauss.mppdbide.presentation.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\mockrunner-jdbc-2.0.6.jar %TEST%\org.opengauss.mppdbide.presentation.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\mockrunner-core-2.0.6.jar %TEST%\org.opengauss.mppdbide.presentation.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\xml-apis-1.0.b2.jar %TEST%\org.opengauss.mppdbide.presentation.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\gson-2.8.6.jar %TEST%\org.opengauss.mppdbide.presentation.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\commons-collections4-4.4.jar %TEST%\org.opengauss.mppdbide.presentation.windows.test.fragment\lib\. +xcopy %SOURCE%\platform\Gauss200\gs_jdbc\gsjdbc4.jar %TEST%\org.opengauss.mppdbide.presentation.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\hamcrest-api-1.0.jar %TEST%\org.opengauss.mppdbide.presentation.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\jsqlparser-3.2.jar %TEST%\org.opengauss.mppdbide.presentation.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\log4j-1.2.15.jar %TEST%\org.opengauss.mppdbide.presentation.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\commons-codec-1.15.jar %TEST%\org.opengauss.mppdbide.presentation.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\commons-io-2.11.0.jar %TEST%\org.opengauss.mppdbide.presentation.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\poi-4.1.2.jar %TEST%\org.opengauss.mppdbide.presentation.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\poi-ooxml-4.1.2.jar %TEST%\org.opengauss.mppdbide.presentation.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\poi-ooxml-schemas-4.1.2.jar %TEST%\org.opengauss.mppdbide.presentation.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\xmlbeans-3.1.0.jar %TEST%\org.opengauss.mppdbide.presentation.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\junit-4.11.jar %TEST%\org.opengauss.mppdbide.presentation.windows.test.fragment\lib\. + +rmdir /Q /S %TEST%\org.opengauss.mppdbide.util.windows.test.fragment\lib +mkdir %TEST%\org.opengauss.mppdbide.util.windows.test.fragment\lib +xcopy %SOURCE%\3rd_src\target\dependency\commons-logging-1.0.4.jar %TEST%\org.opengauss.mppdbide.util.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\oro-2.0.8.jar %TEST%\org.opengauss.mppdbide.util.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\jdom-2.0.2.jar %TEST%\org.opengauss.mppdbide.util.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\mockrunner-jdbc-2.0.6.jar %TEST%\org.opengauss.mppdbide.util.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\mockrunner-core-2.0.6.jar %TEST%\org.opengauss.mppdbide.util.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\xml-apis-1.0.b2.jar %TEST%\org.opengauss.mppdbide.util.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\gson-2.8.6.jar %TEST%\org.opengauss.mppdbide.util.windows.test.fragment\lib\. +xcopy %SOURCE%\platform\Gauss200\gs_jdbc\gsjdbc4.jar %TEST%\org.opengauss.mppdbide.util.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\hamcrest-api-1.0.jar %TEST%\org.opengauss.mppdbide.util.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\jsqlparser-3.2.jar %TEST%\org.opengauss.mppdbide.util.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\junit-4.11.jar %TEST%\org.opengauss.mppdbide.util.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\log4j-1.2.15.jar %TEST%\org.opengauss.mppdbide.util.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\commons-codec-1.15.jar %TEST%\org.opengauss.mppdbide.util.windows.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\commons-io-2.11.0.jar %TEST%\org.opengauss.mppdbide.util.windows.test.fragment\lib\. + +rmdir /Q /S %TEST%\org.opengauss.mppdbide.utils.test.fragment\lib +mkdir %TEST%\org.opengauss.mppdbide.utils.test.fragment\lib +xcopy %SOURCE%\3rd_src\target\dependency\commons-logging-1.0.4.jar %TEST%\org.opengauss.mppdbide.utils.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\oro-2.0.8.jar %TEST%\org.opengauss.mppdbide.utils.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\jdom-2.0.2.jar %TEST%\org.opengauss.mppdbide.utils.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\xml-apis-1.0.b2.jar %TEST%\org.opengauss.mppdbide.utils.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\hamcrest-api-1.0.jar %TEST%\org.opengauss.mppdbide.utils.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\easymock-4.3.jar %TEST%\org.opengauss.mppdbide.utils.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\gson-2.8.6.jar %TEST%\org.opengauss.mppdbide.utils.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\log4j-1.2.15.jar %TEST%\org.opengauss.mppdbide.utils.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\commons-codec-1.15.jar %TEST%\org.opengauss.mppdbide.utils.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\junit-4.11.jar %TEST%\org.opengauss.mppdbide.utils.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\jsqlparser-3.2.jar %TEST%\org.opengauss.mppdbide.utils.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\commons-io-2.11.0.jar %TEST%\org.opengauss.mppdbide.utils.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\mockrunner-jdbc-2.0.6.jar %TEST%\org.opengauss.mppdbide.utils.test.fragment\lib\. +xcopy %SOURCE%\3rd_src\target\dependency\mockrunner-core-2.0.6.jar %TEST%\org.opengauss.mppdbide.utils.test.fragment\lib\. + +mkdir %DEST%\org.opengauss.mppdbide.repository\tools +mkdir %DEST%\db_assistant + +xcopy %DEST%\..\db_assistant %DEST%\db_assistant /Y /E +xcopy %SOURCE%\code\datastudio\src\StartDataStudio.bat %DEST%\org.opengauss.mppdbide.repository\tools\. +mkdir ..\docs +xcopy %SOURCE%\information\datastudio ..\docs\. /Y /S /E +mkdir %DEST%\..\build diff --git a/code/datastudio/src/copyExternalsToBuild.sh b/code/datastudio/src/copyExternalsToBuild.sh new file mode 100644 index 0000000000000000000000000000000000000000..9c2d20c883895edcb0e20838729024cbc16d52b1 --- /dev/null +++ b/code/datastudio/src/copyExternalsToBuild.sh @@ -0,0 +1,259 @@ +#!/bin/bash +SOURCE=../../.. +DEST=./ +TEST=../testcode/LLT/ + +mvn dependency:copy-dependencies -f $SOURCE/3rd_src/pom.xml +#::0 Delete the old folders +rm -rf $DEST/org.opengauss.mppdbide.repository/tools +rm -rf ../docs +rm -rf $DEST/../build +rm -rf $DEST/db_assistant + +cp $SOURCE/platform/Gauss200/gs_jdbc/gsjdbc4.jar $DEST/org.opengauss.mppdbide.presentation/src-test/. +cp $SOURCE/3rd_src/target/dependency/hamcrest-api-1.0.jar $DEST/org.opengauss.mppdbide.presentation/src-test/. +cp $SOURCE/3rd_src/target/dependency/junit-4.11.jar $DEST/org.opengauss.mppdbide.presentation/src-test/. +cp $SOURCE/3rd_src/target/dependency/log4j-1.2.15.jar $DEST/org.opengauss.mppdbide.presentation/src-test/. +cp $SOURCE/3rd_src/target/dependency/commons-logging-1.0.4.jar $DEST/org.opengauss.mppdbide.presentation/src-test/. +cp $SOURCE/3rd_src/target/dependency/oro-2.0.8.jar $DEST/org.opengauss.mppdbide.presentation/src-test/. +cp $SOURCE/3rd_src/target/dependency/jdom-2.0.2.jar $DEST/org.opengauss.mppdbide.presentation/src-test/. +cp $SOURCE/3rd_src/target/dependency/mockrunner-jdbc-2.0.6.jar $DEST/org.opengauss.mppdbide.presentation/src-test/. +cp $SOURCE/3rd_src/target/dependency/mockrunner-core-2.0.6.jar $DEST/org.opengauss.mppdbide.presentation/src-test/. +cp $SOURCE/3rd_src/target/dependency/xml-apis-1.0.b2.jar $DEST/org.opengauss.mppdbide.presentation/src-test/. +cp $SOURCE/3rd_src/target/dependency/cglib-nodep-3.3.0.jar $DEST/org.opengauss.mppdbide.presentation/src-test/. +cp $SOURCE/3rd_src/target/dependency/easymock-4.3.jar $DEST/org.opengauss.mppdbide.presentation/src-test/. +cp $SOURCE/3rd_src/target/dependency/objenesis-3.2.jar $DEST/org.opengauss.mppdbide.presentation/src-test/. +cp $SOURCE/3rd_src/target/dependency/commons-codec-1.15.jar $DEST/org.opengauss.mppdbide.presentation/src-test/. +cp $SOURCE/3rd_src/target/dependency/commons-lang3-3.12.0.jar $DEST/org.opengauss.mppdbide.presentation/src-test/. +cp $SOURCE/3rd_src/target/dependency/gson-2.8.6.jar $DEST/org.opengauss.mppdbide.presentation/src-test/. + +#::1. Copy the external files from platform, 3rd Src to respective src folders +cp $SOURCE/3rd_src/target/dependency/commons-collections4-4.4.jar $DEST/Common-collection/. +cp $SOURCE/3rd_src/target/dependency/poi-4.1.2.jar $DEST/Common-collection/. +cp $SOURCE/3rd_src/target/dependency/poi-ooxml-4.1.2.jar $DEST/Common-collection/. +cp $SOURCE/3rd_src/target/dependency/poi-ooxml-schemas-4.1.2.jar $DEST/Common-collection/. +cp $SOURCE/3rd_src/target/dependency/xmlbeans-3.1.0.jar $DEST/Common-collection/. +cp $SOURCE/3rd_src/target/dependency/commons-compress-1.21.jar $DEST/Common-collection/. +cp $SOURCE/3rd_src/target/dependency/commons-math3-3.6.1.jar $DEST/Common-collection/. +cp $SOURCE/3rd_src/target/dependency/commons-csv-1.9.0.jar $DEST/commons-csv/. +cp $SOURCE/3rd_src/target/dependency/commons-io-2.11.0.jar $DEST/org.opengauss.mppdbide.bl/. +cp $SOURCE/3rd_src/target/dependency/jsqlparser-3.2.jar $DEST/JSQLParser/. +cp $SOURCE/3rd_src/target/dependency/antlr4-runtime-4.9.2.jar $DEST/org.opengauss.mppdbide.parser/. +cp $SOURCE/3rd_src/target/dependency/log4j-api-2.17.1.jar $DEST/org.opengauss.mppdbide.utils/. +cp $SOURCE/3rd_src/target/dependency/log4j-core-2.17.1.jar $DEST/org.opengauss.mppdbide.utils/. +cp $SOURCE/3rd_src/target/dependency/gson-2.8.6.jar $DEST/org.opengauss.mppdbide.bl/. +cp $SOURCE/3rd_src/target/dependency/commons-lang3-3.12.0.jar $DEST/org.opengauss.mppdbide.bl/. +cp $SOURCE/3rd_src/target/dependency/gson-2.8.6.jar $DEST/org.opengauss.mppdbide.explainplan/. +cp $SOURCE/3rd_src/target/dependency/gson-2.8.6.jar $DEST/org.opengauss.mppdbide.view/. +cp $SOURCE/3rd_src/target/dependency/guava-30.1.1-jre.jar $DEST/org.opengauss.mppdbide.view/. +cp $SOURCE/3rd_src/target/dependency/javafx-base-18-ea+2-win.jar $DEST/org.opengauss.mppdbide.view/. +cp $SOURCE/3rd_src/target/dependency/javafx-controls-18-ea+2-win.jar $DEST/org.opengauss.mppdbide.view/. +cp $SOURCE/3rd_src/target/dependency/javafx-graphics-18-ea+2-win.jar $DEST/org.opengauss.mppdbide.view/. +cp $SOURCE/platform/Gauss200/gs_jdbc/gsjdbc4.jar $DEST/org.opengauss.dbdriver.jdbc.gauss/. + +rm -rf $TEST/org.opengauss.mppdbide.adapter.test.fragment/lib +mkdir $TEST/org.opengauss.mppdbide.adapter.test.fragment/lib +cp $SOURCE/3rd_src/target/dependency/commons-logging-1.0.4.jar $TEST/org.opengauss.mppdbide.adapter.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/oro-2.0.8.jar $TEST/org.opengauss.mppdbide.adapter.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/jdom-2.0.2.jar $TEST/org.opengauss.mppdbide.adapter.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/xml-apis-1.0.b2.jar $TEST/org.opengauss.mppdbide.adapter.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/hamcrest-api-1.0.jar $TEST/org.opengauss.mppdbide.adapter.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/easymock-4.3.jar $TEST/org.opengauss.mppdbide.adapter.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/gson-2.8.6.jar $TEST/org.opengauss.mppdbide.adapter.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/log4j-1.2.15.jar $TEST/org.opengauss.mppdbide.adapter.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/mockrunner-jdbc-2.0.6.jar $TEST/org.opengauss.mppdbide.adapter.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/mockrunner-core-2.0.6.jar $TEST/org.opengauss.mppdbide.adapter.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/commons-codec-1.15.jar $TEST/org.opengauss.mppdbide.adapter.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/log4j-1.2.15.jar $TEST/org.opengauss.mppdbide.adapter.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/org.eclipse.osgi-3.9.1.v20130814-1242.jar $TEST/org.opengauss.mppdbide.adapter.test.fragment/lib/. +cp $SOURCE/platform/Gauss200/gs_jdbc/gsjdbc4.jar $TEST/org.opengauss.mppdbide.adapter.test.fragment/lib/. + +rm -rf $TEST/org.opengauss.mppdbide.bl.debug.test.fragment/lib +mkdir $TEST/org.opengauss.mppdbide.bl.debug.test.fragment/lib +cp $SOURCE/3rd_src/target/dependency/commons-logging-1.0.4.jar $TEST/org.opengauss.mppdbide.bl.debug.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/oro-2.0.8.jar $TEST/org.opengauss.mppdbide.bl.debug.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/jdom-2.0.2.jar $TEST/org.opengauss.mppdbide.bl.debug.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/xml-apis-1.0.b2.jar $TEST/org.opengauss.mppdbide.bl.debug.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/hamcrest-api-1.0.jar $TEST/org.opengauss.mppdbide.bl.debug.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/easymock-4.3.jar $TEST/org.opengauss.mppdbide.bl.debug.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/gson-2.8.6.jar $TEST/org.opengauss.mppdbide.bl.debug.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/log4j-1.2.15.jar $TEST/org.opengauss.mppdbide.bl.debug.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/mockrunner-jdbc-2.0.6.jar $TEST/org.opengauss.mppdbide.bl.debug.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/mockrunner-core-2.0.6.jar $TEST/org.opengauss.mppdbide.bl.debug.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/junit-4.11.jar $TEST/org.opengauss.mppdbide.bl.debug.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/commons-io-2.11.0.jar $TEST/org.opengauss.mppdbide.bl.debug.test.fragment/lib/. + +rm -rf $TEST/org.opengauss.mppdbide.bl.test.fragment/lib +mkdir $TEST/org.opengauss.mppdbide.bl.test.fragment/lib +cp $SOURCE/3rd_src/target/dependency/commons-logging-1.0.4.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/oro-2.0.8.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/jdom-2.0.2.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/jsqlparser-3.2.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/xml-apis-1.0.b2.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/hamcrest-api-1.0.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/easymock-4.3.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/gson-2.8.6.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/log4j-1.2.15.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/junit-4.11.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/jsqlparser-3.2.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/org.eclipse.osgi-3.9.1.v20130814-1242.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/commons-io-2.11.0.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/powermock-api-mockito-1.6.6.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/powermock-module-testng-common-1.6.6.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/powermock-api-mockito-common-1.6.6.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/powermock-api-support-1.6.6.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/powermock-module-testng-1.6.6.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/powermock-core-1.6.6.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/powermock-api-easymock-1.6.6.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/powermock-classloading-base-1.6.6.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/powermock-module-junit4-legacy-1.6.6.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/powermock-module-javaagent-1.6.6.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/powermock-module-junit4-1.6.6.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/powermock-module-junit4-common-1.6.6.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/powermock-module-junit4-rule-agent-1.6.6.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/powermock-module-testng-agent-1.6.6.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/powermock-reflect-1.6.6.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/bsh-2.0b4.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/cglib-nodep-3.3.0.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/javassist-3.20.0-GA.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/jcommander-1.27.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/mockito-all-1.10.19.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/objenesis-3.2.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/snakeyaml-1.30.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/platform/Gauss200/gs_jdbc/gsjdbc4.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. +cp $SOURCE/platform/Gauss200/gs_jdbc/mockrunner-jdbc.jar $TEST/org.opengauss.mppdbide.bl.test.fragment/lib/. + +rm -rf $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib +mkdir $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib +cp $SOURCE/3rd_src/target/dependency/commons-logging-1.0.4.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/jdom-2.0.2.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/mockrunner-jdbc-2.0.6.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/mockrunner-core-2.0.6.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/xml-apis-1.0.b2.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/gson-2.8.6.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/platform/Gauss200/gs_jdbc/gsjdbc4.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/hamcrest-api-1.0.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/jsqlparser-3.2.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/junit-4.11.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/log4j-1.2.15.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/commons-io-2.11.0.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/objenesis-3.2.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/easymock-4.3.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/objenesis-3.2.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/oro-2.0.8.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/org.eclipse.core.contenttype-3.4.100.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/org.eclipse.core.jobs-3.5.100.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/org.eclipse.core.runtime-3.7.0.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/org.eclipse.e4.core.services-2.0.100.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/org.eclipse.e4.core.di-1.8.100.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/org.eclipse.equinox.app-1.3.100.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/org.eclipse.equinox.common-3.6.0.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/org.eclipse.equinox.preferences-3.6.1.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/org.eclipse.equinox.registry-3.6.100.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/org.eclipse.osgi-3.9.1.v20130814-1242.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/org.eclipse.osgi.services-3.5.100.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/runtime_registry_compatibility-4.3.1.jar $TEST/org.opengauss.mppdbide.bl.windows.test.fragment/lib/. + +rm -rf $TEST/org.opengauss.mppdbide.editor.extension.test.fragment/lib +mkdir $TEST/org.opengauss.mppdbide.editor.extension.test.fragment/lib +cp $SOURCE/3rd_src/target/dependency/antlr4-runtime-4.9.2.jar $TEST/org.opengauss.mppdbide.editor.extension.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/log4j-1.2.15.jar $TEST/org.opengauss.mppdbide.editor.extension.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/commons-codec-1.15.jar $TEST/org.opengauss.mppdbide.editor.extension.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/hamcrest-api-1.0.jar $TEST/org.opengauss.mppdbide.editor.extension.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/junit-4.11.jar $TEST/org.opengauss.mppdbide.editor.extension.test.fragment/lib/. + +rm -rf $TEST/org.opengauss.mppdbide.explainplan.test.fragment/lib +mkdir $TEST/org.opengauss.mppdbide.explainplan.test.fragment/lib +cp $SOURCE/3rd_src/target/dependency/commons-logging-1.0.4.jar $TEST/org.opengauss.mppdbide.explainplan.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/oro-2.0.8.jar $TEST/org.opengauss.mppdbide.explainplan.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/jdom-2.0.2.jar $TEST/org.opengauss.mppdbide.explainplan.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/xml-apis-1.0.b2.jar $TEST/org.opengauss.mppdbide.explainplan.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/hamcrest-api-1.0.jar $TEST/org.opengauss.mppdbide.explainplan.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/easymock-4.3.jar $TEST/org.opengauss.mppdbide.explainplan.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/gson-2.8.6.jar $TEST/org.opengauss.mppdbide.explainplan.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/log4j-1.2.15.jar $TEST/org.opengauss.mppdbide.explainplan.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/commons-codec-1.15.jar $TEST/org.opengauss.mppdbide.explainplan.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/junit-4.11.jar $TEST/org.opengauss.mppdbide.explainplan.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/mockrunner-jdbc-2.0.6.jar $TEST/org.opengauss.mppdbide.explainplan.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/mockrunner-core-2.0.6.jar $TEST/org.opengauss.mppdbide.explainplan.test.fragment/lib/. + +rm -rf $TEST/org.opengauss.mppdbide.parser.test.fragment/lib +mkdir $TEST/org.opengauss.mppdbide.parser.test.fragment/lib +cp $SOURCE/3rd_src/target/dependency/commons-logging-1.0.4.jar $TEST/org.opengauss.mppdbide.parser.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/oro-2.0.8.jar $TEST/org.opengauss.mppdbide.parser.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/jdom-2.0.2.jar $TEST/org.opengauss.mppdbide.parser.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/xml-apis-1.0.b2.jar $TEST/org.opengauss.mppdbide.parser.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/hamcrest-api-1.0.jar $TEST/org.opengauss.mppdbide.parser.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/easymock-4.3.jar $TEST/org.opengauss.mppdbide.parser.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/gson-2.8.6.jar $TEST/org.opengauss.mppdbide.parser.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/log4j-1.2.15.jar $TEST/org.opengauss.mppdbide.parser.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/commons-codec-1.15.jar $TEST/org.opengauss.mppdbide.parser.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/junit-4.11.jar $TEST/org.opengauss.mppdbide.parser.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/antlr4-runtime-4.9.2.jar $TEST/org.opengauss.mppdbide.parser.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/mockrunner-jdbc-2.0.6.jar $TEST/org.opengauss.mppdbide.parser.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/mockrunner-core-2.0.6.jar $TEST/org.opengauss.mppdbide.parser.test.fragment/lib/. + +rm -rf $TEST/org.opengauss.mppdbide.presentation.windows.test.fragment/lib +mkdir $TEST/org.opengauss.mppdbide.presentation.windows.test.fragment/lib +cp $SOURCE/3rd_src/target/dependency/commons-logging-1.0.4.jar $TEST/org.opengauss.mppdbide.presentation.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/oro-2.0.8.jar $TEST/org.opengauss.mppdbide.presentation.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/jdom-2.0.2.jar $TEST/org.opengauss.mppdbide.presentation.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/mockrunner-jdbc-2.0.6.jar $TEST/org.opengauss.mppdbide.presentation.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/mockrunner-core-2.0.6.jar $TEST/org.opengauss.mppdbide.presentation.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/xml-apis-1.0.b2.jar $TEST/org.opengauss.mppdbide.presentation.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/gson-2.8.6.jar $TEST/org.opengauss.mppdbide.presentation.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/commons-collections4-4.4.jar $TEST/org.opengauss.mppdbide.presentation.windows.test.fragment/lib/. +cp $SOURCE/platform/Gauss200/gs_jdbc/gsjdbc4.jar $TEST/org.opengauss.mppdbide.presentation.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/hamcrest-api-1.0.jar $TEST/org.opengauss.mppdbide.presentation.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/jsqlparser-3.2.jar $TEST/org.opengauss.mppdbide.presentation.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/log4j-1.2.15.jar $TEST/org.opengauss.mppdbide.presentation.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/commons-codec-1.15.jar $TEST/org.opengauss.mppdbide.presentation.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/commons-io-2.11.0.jar $TEST/org.opengauss.mppdbide.presentation.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/poi-4.1.2.jar $TEST/org.opengauss.mppdbide.presentation.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/poi-ooxml-4.1.2.jar $TEST/org.opengauss.mppdbide.presentation.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/poi-ooxml-schemas-4.1.2.jar $TEST/org.opengauss.mppdbide.presentation.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/xmlbeans-3.1.0.jar $TEST/org.opengauss.mppdbide.presentation.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/junit-4.11.jar $TEST/org.opengauss.mppdbide.presentation.windows.test.fragment/lib/. + +rm -rf $TEST/org.opengauss.mppdbide.util.windows.test.fragment/lib +mkdir $TEST/org.opengauss.mppdbide.util.windows.test.fragment/lib +cp $SOURCE/3rd_src/target/dependency/commons-logging-1.0.4.jar $TEST/org.opengauss.mppdbide.util.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/oro-2.0.8.jar $TEST/org.opengauss.mppdbide.util.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/jdom-2.0.2.jar $TEST/org.opengauss.mppdbide.util.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/mockrunner-jdbc-2.0.6.jar $TEST/org.opengauss.mppdbide.util.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/mockrunner-core-2.0.6.jar $TEST/org.opengauss.mppdbide.util.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/xml-apis-1.0.b2.jar $TEST/org.opengauss.mppdbide.util.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/gson-2.8.6.jar $TEST/org.opengauss.mppdbide.util.windows.test.fragment/lib/. +cp $SOURCE/platform/Gauss200/gs_jdbc/gsjdbc4.jar $TEST/org.opengauss.mppdbide.util.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/hamcrest-api-1.0.jar $TEST/org.opengauss.mppdbide.util.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/jsqlparser-3.2.jar $TEST/org.opengauss.mppdbide.util.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/junit-4.11.jar $TEST/org.opengauss.mppdbide.util.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/log4j-1.2.15.jar $TEST/org.opengauss.mppdbide.util.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/commons-codec-1.15.jar $TEST/org.opengauss.mppdbide.util.windows.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/commons-io-2.11.0.jar $TEST/org.opengauss.mppdbide.util.windows.test.fragment/lib/. + +rm -rf $TEST/org.opengauss.mppdbide.utils.test.fragment/lib +mkdir $TEST/org.opengauss.mppdbide.utils.test.fragment/lib +cp $SOURCE/3rd_src/target/dependency/commons-logging-1.0.4.jar $TEST/org.opengauss.mppdbide.utils.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/oro-2.0.8.jar $TEST/org.opengauss.mppdbide.utils.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/jdom-2.0.2.jar $TEST/org.opengauss.mppdbide.utils.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/xml-apis-1.0.b2.jar $TEST/org.opengauss.mppdbide.utils.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/hamcrest-api-1.0.jar $TEST/org.opengauss.mppdbide.utils.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/easymock-4.3.jar $TEST/org.opengauss.mppdbide.utils.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/gson-2.8.6.jar $TEST/org.opengauss.mppdbide.utils.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/log4j-1.2.15.jar $TEST/org.opengauss.mppdbide.utils.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/commons-codec-1.15.jar $TEST/org.opengauss.mppdbide.utils.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/junit-4.11.jar $TEST/org.opengauss.mppdbide.utils.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/jsqlparser-3.2.jar $TEST/org.opengauss.mppdbide.utils.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/commons-io-2.11.0.jar $TEST/org.opengauss.mppdbide.utils.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/mockrunner-jdbc-2.0.6.jar $TEST/org.opengauss.mppdbide.utils.test.fragment/lib/. +cp $SOURCE/3rd_src/target/dependency/mockrunner-core-2.0.6.jar $TEST/org.opengauss.mppdbide.utils.test.fragment/lib/. + +mkdir $DEST/org.opengauss.mppdbide.repository/tools +mkdir $DEST/db_assistant + +cp -r $DEST/../db_assistant/ $DEST/db_assistant/ +cp $SOURCE/code/datastudio/src/StartDataStudio.bat $DEST/org.opengauss.mppdbide.repository/tools/. +mkdir ../docs +cp -r $SOURCE/information/datastudio/* ../docs/. +mkdir $DEST/../build diff --git a/code/datastudio/src/createBuild.bat b/code/datastudio/src/createBuild.bat new file mode 100644 index 0000000000000000000000000000000000000000..27daf3c993d615f59d8ad5aa25b6f4f0f8ca7521 --- /dev/null +++ b/code/datastudio/src/createBuild.bat @@ -0,0 +1,5 @@ +set SOURCE=..\..\.. +set DEST=.\ + +::1. Copy the external files from platform, 3rd Src to respective src folders +mkdir %DEST%\..\build \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/.classpath b/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/.classpath new file mode 100644 index 0000000000000000000000000000000000000000..bf1c51a19d078f173b582f1564b5dc6d17e12f61 --- /dev/null +++ b/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/.classpath @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/.gitignore b/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ddc25c7fcd00a3a38f67eabde7efb88c26a8c3a8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/.gitignore @@ -0,0 +1,3 @@ +/bin/ +/.settings/ +/target/ diff --git a/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/.project b/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/.project new file mode 100644 index 0000000000000000000000000000000000000000..a66f672dae8ca692b521707f17bda6f61681aae1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/.project @@ -0,0 +1,34 @@ + + + org.opengauss.dbdriver.jdbc.gauss + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/META-INF/MANIFEST.MF b/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/META-INF/MANIFEST.MF new file mode 100644 index 0000000000000000000000000000000000000000..99c1e80992f2d3a8de6ee4bef69ddaf8b52cd152 --- /dev/null +++ b/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/META-INF/MANIFEST.MF @@ -0,0 +1,28 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Gauss +Bundle-SymbolicName: org.opengauss.dbdriver.jdbc.gauss +Bundle-Version: 1.0.0.qualifier +Bundle-RequiredExecutionEnvironment: JavaSE-11 +Export-Package: org.postgresql, + org.postgresql.copy, + org.postgresql.core, + org.postgresql.core.types, + org.postgresql.core.v3, + org.postgresql.ds, + org.postgresql.ds.common, + org.postgresql.fastpath, + org.postgresql.geometric, + org.postgresql.gss, + org.postgresql.jdbc, + org.postgresql.jdbc2, + org.postgresql.jdbc2.optional, + org.postgresql.largeobject, + org.postgresql.log, + org.postgresql.replication, + org.postgresql.ssl, + org.postgresql.ssl.jdbc4, + org.postgresql.util, + org.postgresql.xa +Bundle-ClassPath: ., + gsjdbc4.jar diff --git a/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/META-INF/services/java.sql.Driver b/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/META-INF/services/java.sql.Driver new file mode 100644 index 0000000000000000000000000000000000000000..6f036886fb526215ce64592816ff3dbb3a740e58 --- /dev/null +++ b/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/META-INF/services/java.sql.Driver @@ -0,0 +1 @@ +org.postgresql.Driver diff --git a/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/build.properties b/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/build.properties new file mode 100644 index 0000000000000000000000000000000000000000..c7f7579805b248a583f6389b86ecca691f2a944e --- /dev/null +++ b/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/build.properties @@ -0,0 +1,3 @@ +output.. = . +bin.includes = META-INF/,\ + gsjdbc4.jar diff --git a/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/gsjdbc4.jar b/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/gsjdbc4.jar new file mode 100644 index 0000000000000000000000000000000000000000..e81422018a4a619d5719aa12a77633d5ff2182e4 Binary files /dev/null and b/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/gsjdbc4.jar differ diff --git a/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/pom.xml b/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..7d639ff946a66e7441981b754f853e837b3ca3c5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.dbdriver.jdbc.gauss/pom.xml @@ -0,0 +1,13 @@ + + + 4.0.0 + + org.opengauss.plide.build + GAUSS_MPP_DB_IDE + 1.0.0-SNAPSHOT + + org.opengauss.dbdriver.jdbc.gauss + eclipse-plugin + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/.classpath b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/.classpath new file mode 100644 index 0000000000000000000000000000000000000000..6ae8eb6f0a8021436940397b1574147090eb7259 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/.classpath @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/.gitignore b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ddc25c7fcd00a3a38f67eabde7efb88c26a8c3a8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/.gitignore @@ -0,0 +1,3 @@ +/bin/ +/.settings/ +/target/ diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/.project b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/.project new file mode 100644 index 0000000000000000000000000000000000000000..9b1f9ab3a157c2bd3d98c2054cb32ce0c75555f0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/.project @@ -0,0 +1,34 @@ + + + org.opengauss.mppdbide.adapter.gauss + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/META-INF/MANIFEST.MF b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/META-INF/MANIFEST.MF new file mode 100644 index 0000000000000000000000000000000000000000..159ed92023774b146546acff8fa7c7f80a04d105 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/META-INF/MANIFEST.MF @@ -0,0 +1,20 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: MPPDBIDE_Gauss +Bundle-SymbolicName: org.opengauss.mppdbide.adapter.gauss +Bundle-Version: 1.0.0.qualifier +Bundle-Activator: org.opengauss.mppdbide.adapter.gauss.Activator +Bundle-Vendor: Huawei Technologies +Require-Bundle: org.eclipse.core.runtime;bundle-version="3.15.300", + org.apache.commons.lang;bundle-version="2.6.0", + org.opengauss.mppdbide.util;bundle-version="1.0.0", + org.opengauss.dbdriver.jdbc.gauss;bundle-version="1.0.0" +Bundle-RequiredExecutionEnvironment: JavaSE-11 +Bundle-ActivationPolicy: lazy +Export-Package: org.opengauss.mppdbide.adapter, + org.opengauss.mppdbide.adapter.driver, + org.opengauss.mppdbide.adapter.factory, + org.opengauss.mppdbide.adapter.gauss, + org.opengauss.mppdbide.adapter.keywordssyntax +Bundle-ClassPath: . +Import-Package: org.apache.commons.collections4.trie diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/build.properties b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/build.properties new file mode 100644 index 0000000000000000000000000000000000000000..34d2e4d2dad529ceaeb953bfcdb63c51d69ffed2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/build.properties @@ -0,0 +1,4 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + . diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/compile_plsqlide.adapter.gauss.xml b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/compile_plsqlide.adapter.gauss.xml new file mode 100644 index 0000000000000000000000000000000000000000..439ac2859a5a7ec57e379969fbed97f061153dd4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/compile_plsqlide.adapter.gauss.xml @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/pom.xml b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..f55ea384885cc9834d9a0f4e82bc14778200ac5e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/pom.xml @@ -0,0 +1,12 @@ + + + 4.0.0 + + org.opengauss.plide.build + GAUSS_MPP_DB_IDE + 1.0.0-SNAPSHOT + + org.opengauss.mppdbide.adapter.gauss + eclipse-plugin + diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/AbstractConnectionDriver.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/AbstractConnectionDriver.java new file mode 100644 index 0000000000000000000000000000000000000000..96e44334d9d1f68579dad8a8387096b374231e0c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/AbstractConnectionDriver.java @@ -0,0 +1,190 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter; + +import java.sql.Driver; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Properties; + +import org.opengauss.mppdbide.adapter.keywordssyntax.Keywords; +import org.opengauss.mppdbide.adapter.keywordssyntax.KeywordsToTrieConverter; +import org.opengauss.mppdbide.adapter.keywordssyntax.SQLSyntax; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class AbstractConnectionDriver. + * + * @since 3.0.0 + */ +public abstract class AbstractConnectionDriver implements IConnectionDriver { + private String driverName; + private HashMap toolpathMap; + private Driver jdbcDriver; + private volatile SQLSyntax sqlSyntax; + private final Object lock = new Object(); + private Keywords keywords; + + /** + * Instantiates a new abstract connection driver. + * + * @param dsInstallPath the ds install path + * @param driverType the driver type + */ + public AbstractConnectionDriver() { + } + + /** + * Gets the driver name. + * + * @return the driver name + */ + @Override + public String getDriverName() { + return this.driverName; + } + + /** + * Gets the tool path. + * + * @param toolName the tool name + * @return the tool path + */ + @Override + public String getToolPath(String toolName) { + return this.toolpathMap.get(toolName); + } + + /** + * Gets the JDBC driver. + * + * @return the JDBC driver + */ + @Override + public Driver getJDBCDriver() { + return this.jdbcDriver; + } + + /** + * Gets the driver specific properties. + * + * @return the driver specific properties + */ + @Override + public Properties getDriverSpecificProperties() { + return new Properties(); + } + + + /** + * Sets the driver. + * + * @param dname the new driver + */ + protected void setDriver(String dname) { + this.driverName = dname; + } + + /** + * Sets the tool path map. + * + * @param map the map + */ + protected void setToolPathMap(HashMap map) { + this.toolpathMap = map; + } + + /** + * Sets the JDBC driver. + * + * @param driver the new JDBC driver + */ + public void setJDBCDriver(Driver driver) { + this.jdbcDriver = driver; + } + + /** + * Configure driver details. + * + * @param dsInstallPath the ds install path + * @param driverType the driver type + */ + protected abstract void configureDriverDetails(String dsInstallPath); + + /** + * Gets the protocol mismatch error string. + * + * @return the protocol mismatch error string + */ + public abstract String getProtocolMismatchErrorString(); + + /** + * Extract error code and error msg from server error. + * + * @param exe the e + * @return the string + */ + public String extractErrCodeAdErrMsgFrmServErr(SQLException exe) { + StringBuilder errorBuilder = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + errorBuilder.append(MessageConfigLoader.getProperty(IMessagesConstants.ERR_EDIT_TABLE_COMMIT_FAIL)) + .append(" = "); + errorBuilder.append(exe.getSQLState()); + errorBuilder.append(MPPDBIDEConstants.NEW_LINE_SIGN); + errorBuilder.append(exe.getLocalizedMessage()); + errorBuilder.append(MPPDBIDEConstants.NEW_LINE_SIGN); + return errorBuilder.toString(); + } + + /** + * Load SQL syntax. + * + * @return SQLSyntax sqlSyntax + * + * while Overriding the following method in subclass, method should be made + * thread-safe similar to super class implementation since sql syntax needs + * to be loaded sequentially to not cause mismatch of values between objects + */ + public SQLSyntax loadSQLSyntax() { + keywords = loadKeyWords(); + if (sqlSyntax == null) { + synchronized (lock) { + if (sqlSyntax == null) { + MPPDBIDELoggerUtility.debug("sql syntax convert trie starts"); + sqlSyntax = new SQLSyntax(); + sqlSyntax = KeywordsToTrieConverter.convertKeywordstoTrie(sqlSyntax, keywords); + MPPDBIDELoggerUtility.debug("sql syntax convert trie ends"); + } + } + } + return sqlSyntax; + } + + /** + * Load key words. + * + * @return the keywords + */ + public Keywords loadKeyWords() { + return getKeywordList(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/IConnectionDriver.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/IConnectionDriver.java new file mode 100644 index 0000000000000000000000000000000000000000..8f5e094915b3a9f0970897675911d7d1bab6d4cc --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/IConnectionDriver.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter; + +import java.sql.Driver; +import java.sql.SQLException; +import java.util.List; +import java.util.Properties; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.keywordssyntax.Keywords; +import org.opengauss.mppdbide.adapter.keywordssyntax.SQLSyntax; + +/** + * + * Title: interface + * + * Description: The Interface IConnectionDriver. + * + * @since 3.0.0 + */ +public interface IConnectionDriver { + + /** + * Gets the driver name. + * + * @return the driver name + */ + String getDriverName(); + + /** + * Gets the tool path. + * + * @param toolName the tool name + * @return the tool path + */ + String getToolPath(String toolName); + + /** + * Gets the JDBC driver. + * + * @return the JDBC driver + */ + Driver getJDBCDriver(); + + /** + * Gets the driver specific properties. + * + * @return the driver specific properties + */ + Properties getDriverSpecificProperties(); + + /** + * Extract error code and error msg from server error. + * + * @param excep the excep + * @return the string + */ + String extractErrCodeAdErrMsgFrmServErr(SQLException excep); + + /** + * Gets the keyword list. + * + * @return the keyword list + */ + Keywords getKeywordList(); + + /** + * Gets the SQL syntax. + * + * @return the SQL syntax + */ + SQLSyntax loadSQLSyntax(); + + /** + * check if server DDL support check is already called before. If yes, no + * need to check further. + * + * @return the show DDL support check + */ + default boolean getShowDDLSupportCheck() { + return false; + } + + /** + * Gets the show DDL support. + * + * @return the show DDL support + */ + default boolean getShowDDLSupport() { + return false; + } + + /** + * Gets the show DDL support. + * + * @param conn the conn + * @return the show DDL support + */ + default boolean getShowDDLSupport(DBConnection conn) { + return false; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/IDSSupportToolNames.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/IDSSupportToolNames.java new file mode 100644 index 0000000000000000000000000000000000000000..ffc1ba3efbcaf48e8a49108eff0aea146fdb477b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/IDSSupportToolNames.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter; + +/** + * + * Title: interface + * + * Description: The Interface IDSSupportToolNames. + * + * @since 3.0.0 + */ +public interface IDSSupportToolNames { + String JDBC_JAR_FILE_PATH = "JDBC_JAR_FILE_PATH"; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/driver/DBMSDriverManager.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/driver/DBMSDriverManager.java new file mode 100644 index 0000000000000000000000000000000000000000..3ceb64740d957cf1423414f92276e57aa707a19e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/driver/DBMSDriverManager.java @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.driver; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import org.opengauss.mppdbide.adapter.AbstractConnectionDriver; +import org.opengauss.mppdbide.adapter.factory.ConnectionDriverFactory; +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussDriverWrapper; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: class + * + * Description: The Class DBMSDriverManager. + * + * @since 3.0.0 + */ +public final class DBMSDriverManager { + + private static volatile DBMSDriverManager driverManager; + private static volatile ArrayList knownOLAPDrivers; + private String dsInstallPath; + private static final Object LOCK = new Object(); + + private DBMSDriverManager(String dsInstallPath) { + this.dsInstallPath = dsInstallPath; + + } + + /** + * Gets the connection. + * + * @param props the props + * @param url the url + * @param driverType the driver type + * @return the connection + * @throws SQLException the SQL exception + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public DBConnection getConnection(Properties props, String url, String driverType) + throws SQLException, DatabaseOperationException, DatabaseCriticalException { + switch (driverType) { + case MPPDBIDEConstants.OPENGAUSS: { + getOLAPDriverInstance(this.dsInstallPath); + for (AbstractConnectionDriver driver : knownOLAPDrivers) { + + DBConnection conn = establishOLAPConnection(driver, props, url); + if (null != conn) { + GaussDriverWrapper driverWrapper = setDriverDetails(driver); + conn.setDriver(driverWrapper); + return conn; + } + } + break; + } + + default: { + break; + } + } + return null; + } + + private GaussDriverWrapper setDriverDetails(AbstractConnectionDriver driver) { + GaussDriverWrapper driverWrapper = new GaussDriverWrapper(driver); + ConnectionDriverFactory.getInstance().addDriver(driverWrapper.getDriverName(), driverWrapper); + return driverWrapper; + } + + private static DBConnection establishOLAPConnection(AbstractConnectionDriver driver, Properties props, String url) + throws DatabaseCriticalException, DatabaseOperationException, SQLException { + DBConnection conn = new DBConnection(driver); + if (GaussUtils.isProtocolVersionNeeded(driver)) { + props.setProperty("protocolVersion", "3"); + } + + try { + conn.connectViaDriver(props, url); + + } catch (DatabaseOperationException exp) { + // if error deals with protocol error, then return null + if (exp.getMessage().contains(driver.getProtocolMismatchErrorString()) || exp.getServerMessage() != null + && (exp.getServerMessage().contains(driver.getProtocolMismatchErrorString()) + || exp.getServerMessage().contains("Protocol error."))) { + conn = null; + } else { + throw exp; + } + } + return conn; + } + + /** + * Gets the single instance of DBMSDriverManager. + * + * @param dsInstallPath the ds install path + * @return single instance of DBMSDriverManager + */ + public static DBMSDriverManager getInstance(String dsInstallPath) { + if (driverManager == null) { + synchronized (LOCK) { + if (driverManager == null) { + driverManager = new DBMSDriverManager(dsInstallPath); + } + + } + + } + + return driverManager; + } + + /** + * Gets the OLAP driver instance. + * + * @param dsInstallPath the ds install path + * @return the OLAP driver instance + */ + public static ArrayList getOLAPDriverInstance(String dsInstallPath) { + if (knownOLAPDrivers == null) { + synchronized (LOCK) { + if (knownOLAPDrivers == null) { + knownOLAPDrivers = (ArrayList) loadOLAPDrivers(dsInstallPath); + } + } + } + return knownOLAPDrivers; + + } + + private static List loadOLAPDrivers(String dsInstallPath) { + knownOLAPDrivers = new ArrayList(2); + knownOLAPDrivers.add(Gauss200V1R7Driver.getInstance(dsInstallPath)); + knownOLAPDrivers.add(Gauss200V1R6Driver.getInstance(dsInstallPath)); + return knownOLAPDrivers; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/driver/Gauss200V1R6Driver.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/driver/Gauss200V1R6Driver.java new file mode 100644 index 0000000000000000000000000000000000000000..8ac3871b63dfd10b8136c918ff8d5fdc9a60ce14 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/driver/Gauss200V1R6Driver.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.driver; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.Driver; +import java.util.HashMap; +import java.util.Properties; + +import org.opengauss.mppdbide.adapter.AbstractConnectionDriver; +import org.opengauss.mppdbide.adapter.IDSSupportToolNames; +import org.opengauss.mppdbide.adapter.keywordssyntax.Keywords; +import org.opengauss.mppdbide.adapter.keywordssyntax.KeywordsFactoryProvider; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class Gauss200V1R6Driver. + * + * @since 3.0.0 + */ +public class Gauss200V1R6Driver extends AbstractConnectionDriver { + + private static volatile Gauss200V1R6Driver v1r6Driver; + + /** + * Instantiates a new gauss 200 V 1 R 6 driver. + * + * @param dsInstallPath the ds install path + */ + public Gauss200V1R6Driver(String dsInstallPath) { + configureDriverDetails(dsInstallPath); + + } + + @Override + protected void configureDriverDetails(String dsInstallPath) { + setDriver(MPPDBIDEConstants.GAUSS200V1R6DRIVER); + HashMap hashMap = new HashMap(5); + + setToolPathMap(hashMap); + + org.postgresql.Driver driver = new org.postgresql.Driver(); + setJDBCDriver((Driver) driver); + + } + + @Override + public Properties getDriverSpecificProperties() { + Properties prop = new Properties(); + prop.setProperty("protocolVersion", "3"); + return prop; + } + + /** + * Gets the single instance of Gauss200V1R6Driver. + * + * @param dsInstallPath the ds install path + * @return single instance of Gauss200V1R6Driver + */ + public static AbstractConnectionDriver getInstance(String dsInstallPath) { + if (null == v1r6Driver) { + v1r6Driver = new Gauss200V1R6Driver(dsInstallPath); + } + return v1r6Driver; + } + + @Override + public String getProtocolMismatchErrorString() { + return MessageConfigLoader.getProperty(MPPDBIDEConstants.PROTOCOL_VERSION_ERROR); + } + + /** + * Gets the keyword list. + * + * @return the keyword list + */ + public Keywords getKeywordList() { + return KeywordsFactoryProvider.getKeywordsFactory().getOLAPKeywords(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/driver/Gauss200V1R7Driver.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/driver/Gauss200V1R7Driver.java new file mode 100644 index 0000000000000000000000000000000000000000..7ca21c312a639be6246e47649e3e7e162654388a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/driver/Gauss200V1R7Driver.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.driver; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.Driver; +import java.util.HashMap; +import java.util.Properties; + +import org.opengauss.mppdbide.adapter.AbstractConnectionDriver; +import org.opengauss.mppdbide.adapter.IDSSupportToolNames; +import org.opengauss.mppdbide.adapter.keywordssyntax.Keywords; +import org.opengauss.mppdbide.adapter.keywordssyntax.KeywordsFactoryProvider; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class Gauss200V1R7Driver. + * + * @since 3.0.0 + */ +public class Gauss200V1R7Driver extends AbstractConnectionDriver { + private static volatile Gauss200V1R7Driver v1r7Driver; + + /** + * Instantiates a new gauss 200 V 1 R 7 driver. + * + * @param dsInstallPath the ds install path + */ + public Gauss200V1R7Driver(String dsInstallPath) { + configureDriverDetails(dsInstallPath); + } + + @Override + protected void configureDriverDetails(String dsInstallPath) { + setDriver(MPPDBIDEConstants.GAUSS200V1R7DRIVER); + HashMap hashMap = new HashMap(5); + + setToolPathMap(hashMap); + + org.postgresql.Driver driver = new org.postgresql.Driver(); + setJDBCDriver((Driver) driver); + } + + @Override + public Properties getDriverSpecificProperties() { + Properties prop = new Properties(); + return prop; + } + + /** + * Gets the single instance of Gauss200V1R7Driver. + * + * @param dsInstallPath the ds install path + * @return single instance of Gauss200V1R7Driver + */ + public static AbstractConnectionDriver getInstance(String dsInstallPath) { + if (null == v1r7Driver) { + v1r7Driver = new Gauss200V1R7Driver(dsInstallPath); + } + return v1r7Driver; + } + + @Override + public String getProtocolMismatchErrorString() { + + return MessageConfigLoader.getProperty(MPPDBIDEConstants.PROTOCOL_VERSION_ERROR); + } + + /** + * Gets the keyword list. + * + * @return the keyword list + */ + public Keywords getKeywordList() { + return KeywordsFactoryProvider.getKeywordsFactory().getOLAPKeywords(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/factory/ConnectionDriverFactory.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/factory/ConnectionDriverFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..08acedd1cf4f1de49cbb0546fb84fd79a625d307 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/factory/ConnectionDriverFactory.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.factory; + +import java.util.HashMap; + +import org.opengauss.mppdbide.adapter.IConnectionDriver; + +/** + * Title: ConnectionDriverFactory + * + * Description:A factory for creating ConnectionDriver objects. + * + */ + +public final class ConnectionDriverFactory { + + private static volatile ConnectionDriverFactory obj; + private HashMap driverlookup; + private static final Object LOCK = new Object(); + + /** + * Gets the driver. + * + * @param driverName the driver name + * @return the driver + */ + public IConnectionDriver getDriver(String driverName) { + return driverlookup.get(driverName); + } + + /** + * Adds the driver. + * + * @param driverName the driver name + * @param driver the driver + */ + public void addDriver(String driverName, IConnectionDriver driver) { + driverlookup.put(driverName, driver); + } + + private ConnectionDriverFactory() { + this.driverlookup = new HashMap(5); + } + + /** + * Gets the single instance of ConnectionDriverFactory. + * + * @return single instance of ConnectionDriverFactory + */ + public static ConnectionDriverFactory getInstance() { + if (obj == null) { + synchronized (LOCK) { + if (obj == null) { + obj = new ConnectionDriverFactory(); + } + + } + + } + + return obj; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/factory/DBConnectionFactory.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/factory/DBConnectionFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..a6a7dfe0dea8b369de92c3c999c3d510d78bf0df --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/factory/DBConnectionFactory.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.factory; + +import org.opengauss.mppdbide.adapter.IConnectionDriver; +import org.opengauss.mppdbide.adapter.gauss.DBConnection; + +/** + * Title: DBConnectionFactory + * + * Description: A factory for creating DBConnection objects. + * + */ + +public class DBConnectionFactory { + + /** + * Gets the connection obj. + * + * @param connectionDriver the connection driver + * @return the connection obj + */ + public static DBConnection getConnectionObj(IConnectionDriver connectionDriver) { + return new DBConnection(connectionDriver); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/Activator.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/Activator.java new file mode 100644 index 0000000000000000000000000000000000000000..a20915cb2c5a1f53b78717a2d602d6c37d8d872e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/Activator.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.gauss; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; + +/** + * + * Title: class + * + * Description: The Class Activator. + * + * @since 3.0.0 + */ +public class Activator implements BundleActivator { + + private static BundleContext context; + + /** + * Gets the context. + * + * @return the context + */ + public static BundleContext getContext() { + return context; + } + + /** + * Sets the context. + * + * @param bundleContext the new context + */ + public static void setContext(BundleContext bundleContext) { + Activator.context = bundleContext; + } + + /** + * Start. + * + * @param bundleContext the bundle context + */ + public void start(BundleContext bundleContext) { + setContext(bundleContext); + } + + /** + * Stop. + * + * @param bundleContext the bundle context + */ + public void stop(BundleContext bundleContext) { + setContext(null); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/DBConnection.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/DBConnection.java new file mode 100644 index 0000000000000000000000000000000000000000..ca7157dc20e19ba605b4c25e06e573ecba0d346b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/DBConnection.java @@ -0,0 +1,1028 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.gauss; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.sql.Connection; +import java.sql.Driver; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Locale; +import java.util.Properties; + +import org.postgresql.copy.CopyManager; +import org.postgresql.core.BaseConnection; +import org.postgresql.core.BaseStatement; +import org.postgresql.core.TransactionState; +import org.postgresql.jdbc.PgConnection; + +import org.opengauss.mppdbide.adapter.IConnectionDriver; +import org.opengauss.mppdbide.utils.DsEncodingEnum; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.ILogger; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.GlobaMessageQueueUtil; +import org.opengauss.mppdbide.utils.messaging.MessageQueue; + +/** + * + * Title: class + * + * Description: The Class DBConnection. + * + * @since 3.0.0 + */ +public class DBConnection { + + private static final long DELAY_MILLI = 1000L; + private Connection dbConnection; + private int fetchSize; + private IConnectionDriver dbmsDriver; + private boolean isInOutValueExists = true; + + private static final String SERVER_SUPPORT_DDL_QUERY = "select count(*) from pg_catalog.pg_proc " + + "where proname='pg_get_tabledef';"; + + /** + * Instantiates a new DB connection. + */ + public DBConnection() { + + } + + /** + * Instantiates a new DB connection. + * + * @param dbmsDriver the dbms driver + */ + public DBConnection(IConnectionDriver dbmsDriver) { + this.dbmsDriver = dbmsDriver; + } + + /** + * Instantiates a new DB connection. + * + * @param driver the driver + * @param actualConnection the actual connection + */ + public DBConnection(IConnectionDriver driver, Connection actualConnection) { + this.dbmsDriver = driver; + this.dbConnection = actualConnection; + } + + /** + * sets the setIsInOutValueExists + * + * @param isInOutValueExists the isInOutValueExists + */ + public void setIsInOutValueExists(boolean isInOutValueExists) { + this.isInOutValueExists = isInOutValueExists; + } + + /** + * Gets the setIsInOutValueExists + * + * @return isInOutValueExists the isInOutValueExists + */ + public boolean getIsInOutValueExists() { + return this.isInOutValueExists; + } + + /** + * Gets the fetch size. + * + * @return the fetch size + */ + private int getFetchSize() { + return fetchSize; + } + + /** + * Gets the prepare stmt. + * + * @param qry the qry + * @return the prepare stmt + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public PreparedStatement getPrepareStmt(final String qry) + throws DatabaseCriticalException, DatabaseOperationException { + PreparedStatement stmt = null; + try { + stmt = dbConnection.prepareStatement(qry); + + } catch (SQLException exp) { + GaussUtils.handleCriticalException(exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_STMT_EXCEPTION, exp); + } + + return stmt; + } + + /** + * Close statement. + * + * @param stmt the stmt + */ + public void closeStatement(final Statement stmt) { + try { + if (stmt != null) { + stmt.close(); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("ADAPTER: statement close returned exception.", exception); + } + } + + /** + * Connect via driver. + * + * @param props the props + * @param url the url + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void connectViaDriver(Properties props, String url) + throws DatabaseOperationException, DatabaseCriticalException { + + + Driver driver = dbmsDriver.getJDBCDriver(); + + if (null != driver) { + try { + dbConnection = driver.connect(url, props); + } catch (SQLException excep) { + GaussUtils.handleCriticalException(excep); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_SERVER_CONNECTION_FAILED, + extractErrorCodeAndErrorMsgFromServerError(excep), excep); + } + // Temporary solution to avoid frequent timeout issue. + // Need to be removed in V1R3C20. + setSessionTimeoutToNever(); + setDSEncoding(props); + return; + } + } + + /** + * Db connect. + * + * @param props the props + * @param url the url + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void dbConnect(Properties props, String url) throws DatabaseOperationException, DatabaseCriticalException { + try { + MPPDBIDELoggerUtility.info("ADAPTER: Sending connection request"); + + dbConnection = DriverManager.getConnection(url, props); + + MPPDBIDELoggerUtility.info("ADAPTER: Successfully connected"); + } catch (SQLException excep) { + if (MessageConfigLoader.getProperty(MPPDBIDEConstants.PROTOCOL_VERSION_ERROR) + .equalsIgnoreCase(excep.getMessage())) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.DOMAINNAME_REDIRECT_FAILURE, + MessageConfigLoader.getProperty(MPPDBIDEConstants.PROTOCOL_VERSION_ERROR) + + MPPDBIDEConstants.LINE_SEPARATOR)); + throw new DatabaseOperationException(IMessagesConstants.DOMAINNAME_REDIRECT_FAILURE, + MessageConfigLoader.getProperty(MPPDBIDEConstants.PROTOCOL_VERSION_ERROR) + + MPPDBIDEConstants.LINE_SEPARATOR); + } else { + GaussUtils.handleCriticalException(excep); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_SERVER_CONNECTION_FAILED, excep); + } + } + } + + /** + * Sets the DS encoding. + * + * @param props the new DS encoding + */ + private void setDSEncoding(Properties props) { + String encoding = ""; + String clientEncodingToSet = ""; + + if (props.containsKey(MPPDBIDEConstants.SERVER_ENCODING_KEY)) { + encoding = (String) props.get(MPPDBIDEConstants.SERVER_ENCODING_KEY); + } + + if (DsEncodingEnum.LATIN1.getEncoding().equalsIgnoreCase(encoding)) { + clientEncodingToSet = DsEncodingEnum.LATIN1.getEncoding(); + } else { + encoding = props.getProperty("characterEncoding"); + + for (DsEncodingEnum dsencoding : DsEncodingEnum.values()) { + if (encoding.equals(dsencoding.getEncoding())) { + clientEncodingToSet = dsencoding.getEncoding(); + break; + } + } + } + + executeClientEncoding(clientEncodingToSet); + } + + /** + * Execute client encoding. + * + * @param clientEncodingToSet the client encoding to set + */ + public void executeClientEncoding(String clientEncodingToSet) { + PreparedStatement stmt = null; + + try { + if (!"".equals(clientEncodingToSet)) { + MPPDBIDELoggerUtility.error("No client encoding passed for execution."); + } + + String query = String.format(Locale.ENGLISH, "set client_encoding=\"%s\";", clientEncodingToSet); + stmt = dbConnection.prepareStatement(query); + stmt.execute(); + + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Setting client encoding is failed .", exception); + } finally { + try { + if (null != stmt) { + stmt.close(); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Setting client encoding is failed .", exception); + } + } + } + + /** + * Sets the session timeout to never.Reset the session timeout to 0 + */ + private void setSessionTimeoutToNever() { + try { + execNonSelect("set session_timeout=0"); + } catch (DatabaseOperationException e) { + // Not necessary to report error when fails. Its not a business + // blocker. + MPPDBIDELoggerUtility.warn("Unable set session timeout to infinity."); + } catch (DatabaseCriticalException e) { + MPPDBIDELoggerUtility.warn("Unable set session timeout to infinity."); + } + + } + + /** + * Gets the connection. + * + * @return the connection + */ + public Connection getConnection() { + return dbConnection; + } + + /** + * Checks if is closed. + * + * @return true, if is closed + * @throws DatabaseOperationException the database operation exception + */ + public boolean isClosed() throws DatabaseOperationException { + try { + return dbConnection.isClosed(); + } catch (SQLException exp) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_SERVER_CONNECTION_FAILED), exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_SERVER_CONNECTION_FAILED, exp); + } + } + + /** + * Checks if is transaction open. + * + * @param serverVersion the server version + * @return true, if is transaction open + * @throws SQLException the SQL exception + */ + public boolean isTransactionOpen(String serverVersion) throws SQLException { + boolean state = false; + if (dbConnection instanceof PgConnection) { + PgConnection aConn = (PgConnection) dbConnection; + TransactionState transactionState = aConn.getTransactionState(); + + switch (transactionState) { + case OPEN: + case FAILED: { + state = true; + break; + } + default: { + state = false; + break; + } + } + } + + return state; + } + + /** + * Cancel query. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void cancelQuery() throws DatabaseCriticalException, DatabaseOperationException { + Statement stmt = null; + + try { + stmt = dbConnection.createStatement(); + MPPDBIDELoggerUtility.info("ADAPTER: Sending cancle request"); + stmt.cancel(); + MPPDBIDELoggerUtility.info("ADAPTER: Cancle successfully executed"); + } catch (SQLException exp) { + GaussUtils.handleCriticalException(exp); + MPPDBIDELoggerUtility.error("ADAPTER: cancel query returned exception.", exp); + } finally { + try { + if (null != stmt) { + stmt.close(); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("ADAPTER: statement close returned exception.", exception); + } + } + + try { + stmt = dbConnection.createStatement(); + stmt.execute("select 1"); + stmt.cancel(); + } catch (SQLException e) { + // No need to handle the exception + // this code is added because + // the server is trying to the cancel the statement if the cancel is + // not done on previous operation + MPPDBIDELoggerUtility.info("SQL Exception occured during cancel query"); + } finally { + try { + if (null != stmt) { + stmt.close(); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("ADAPTER: statement close returned exception.", exception); + } + } + + } + + /** + * Disconnect. + */ + public void disconnect() { + try { + MPPDBIDELoggerUtility.info("ADAPTER: Disconecting from server"); + if (null != dbConnection && !dbConnection.isClosed()) { + dbConnection.close(); + } + MPPDBIDELoggerUtility.info("ADAPTER: Connection closed"); + + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("ADAPTER: disconnect returned exception", exception); + } + } + + /** + * Exec select and get first val. + * + * @param query the query + * @return the string + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public String execSelectAndGetFirstVal(String query) throws DatabaseCriticalException, DatabaseOperationException { + ResultSet rs = null; + PreparedStatement stmt = getPrepareStmt(query); + + try { + MPPDBIDELoggerUtility.perf(MPPDBIDEConstants.ADAPTER, ILogger.PERF_EXECUTE_STMT, true); + rs = stmt.executeQuery(); + MPPDBIDELoggerUtility.perf(MPPDBIDEConstants.ADAPTER, ILogger.PERF_EXECUTE_STMT, false); + + if (rs.next()) { + String val = rs.getString(1); + return val; + } + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID)); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } catch (SQLException exp) { + GaussUtils.handleCriticalException(exp); + + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_EXECUTE_FUN_PROC_TRIG_QUERY_FAILED, + extractErrorCodeAndErrorMsgFromServerError(exp), exp); + } finally { + closeResultSet(rs); + closeStatement(stmt); + } + + } + + /** + * Exec select and return rs. + * + * @param query the query + * @return the result set + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public ResultSet execSelectAndReturnRs(String query) throws DatabaseCriticalException, DatabaseOperationException { + PreparedStatement stmt = getPrepareStmt(query); + + try { + ResultSet rs = setFetchSizeAndExecuteQuery(stmt); + return rs; + } catch (SQLException exp) { + handleSqlException(stmt, exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_EXECUTE_FUN_PROC_TRIG_QUERY_FAILED, + extractErrorCodeAndErrorMsgFromServerError(exp), exp); + } catch (OutOfMemoryError e1) { + closeStatement(stmt); + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_OUT_OF_MEMORY_OCCURED), + e1); + throw new DatabaseCriticalException(IMessagesConstants.ERR_OUT_OF_MEMORY_OCCURED, e1); + } + + } + + /** + * Exec select and return rs. + * + * @return the sql state + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public boolean execSelectAndReturnAdmin() throws DatabaseCriticalException, DatabaseOperationException { + String query = "select pg_tablespace_location(oid) as location from pg_tablespace;"; + PreparedStatement stmt = getPrepareStmt(query); + ResultSet rs = null; + try { + rs = stmt.executeQuery(); + return true; + } catch (SQLException exp) { + // throws exception if user has no previlege for pg_tablespace_location function + // This also concludes user is not an admin + if (exp.getSQLState().equals("42501")) { + return false; + } else { + return true; + } + } finally { + closeResultSet(rs); + } + } + + private void handleSqlException(PreparedStatement stmt, SQLException exp) throws DatabaseCriticalException { + closeStatement(stmt); + GaussUtils.handleCriticalException(exp); + } + + /** + * Exec select for search. + * + * @param query the query + * @param parameter the parameter + * @return the result set + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public ResultSet execSelectForSearch(String query, String parameter) + throws DatabaseCriticalException, DatabaseOperationException { + PreparedStatement stmt = null; + try { + stmt = getPrepareStmt(query); + // For regular expression we don't need parameter so we are passing + // parameter empty string + if (!parameter.trim().isEmpty()) { + stmt.setString(1, parameter); + } + ResultSet rs = setFetchSizeAndExecuteQuery(stmt); + return rs; + } catch (SQLException eexp) { + handleSqlException(stmt, eexp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_EXECUTE_FUN_PROC_TRIG_QUERY_FAILED, + extractErrorCodeAndErrorMsgFromServerError(eexp), eexp); + } catch (OutOfMemoryError exp) { + closeStatement(stmt); + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_OUT_OF_MEMORY_OCCURED), + exp); + throw new DatabaseCriticalException(IMessagesConstants.ERR_OUT_OF_MEMORY_OCCURED, exp); + } + } + + /** + * Exec select for search 2 parmeters. + * + * @param query the query + * @param parameter the parameter + * @param parameter2 the parameter 2 + * @return the result set + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public ResultSet execSelectForSearch2Parmeters(String query, String parameter, String parameter2) + throws DatabaseCriticalException, DatabaseOperationException { + PreparedStatement stmt = null; + try { + stmt = getPrepareStmt(query); + // For regular expression we don't need parameter so we are passing + // parameter empty string + if (!parameter.trim().isEmpty()) { + stmt.setString(1, parameter); + stmt.setString(2, parameter2); + } + ResultSet rs = setFetchSizeAndExecuteQuery(stmt); + return rs; + } catch (SQLException eex2) { + handleSqlException(stmt, eex2); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_EXECUTE_FUN_PROC_TRIG_QUERY_FAILED, + extractErrorCodeAndErrorMsgFromServerError(eex2), eex2); + } catch (OutOfMemoryError exp) { + closeStatement(stmt); + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_OUT_OF_MEMORY_OCCURED), + exp); + throw new DatabaseCriticalException(IMessagesConstants.ERR_OUT_OF_MEMORY_OCCURED, exp); + } + } + + /** + * Sets the fetch size and execute query. + * + * @param stmt the stmt + * @return the result set + * @throws SQLException the SQL exception + */ + private ResultSet setFetchSizeAndExecuteQuery(PreparedStatement stmt) throws SQLException { + MPPDBIDELoggerUtility.perf(MPPDBIDEConstants.ADAPTER, ILogger.PERF_EXECUTE_STMT, true); + stmt.setFetchSize(getFetchSize()); + ResultSet rs = stmt.executeQuery(); + MPPDBIDELoggerUtility.perf(MPPDBIDEConstants.GUI, ILogger.PERF_EXECUTE_STMT, false); + return rs; + } + + /** + * Exec select to export CSV. + * + * @param query the query + * @param preferenceCount the preference count + * @return the result set + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public ResultSet execSelectToExportCSV(String query, int preferenceCount) + throws DatabaseCriticalException, DatabaseOperationException { + + PreparedStatement stmt = null; + ResultSet rs = null; + boolean isExpOccurred = false; + try { + stmt = getPrepareStmt(query); + stmt.setFetchSize(preferenceCount); + + MPPDBIDELoggerUtility.perf(MPPDBIDEConstants.ADAPTER, ILogger.PERF_EXECUTE_STMT, true); + rs = stmt.executeQuery(); + MPPDBIDELoggerUtility.perf(MPPDBIDEConstants.GUI, ILogger.PERF_EXECUTE_STMT, false); + return rs; + } catch (SQLException exp) { + isExpOccurred = true; + + GaussUtils.handleCriticalException(exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_EXECUTE_FUN_PROC_TRIG_QUERY_FAILED, + extractErrorCodeAndErrorMsgFromServerError(exp), exp); + } catch (OutOfMemoryError expe) { + isExpOccurred = true; + + throw new DatabaseCriticalException(IMessagesConstants.ERR_OUT_OF_MEMORY_OCCURED, expe); + } finally { + + if (isExpOccurred) { + try { + closeResultSet(rs); + } finally { + closeStatement(stmt); + } + } + } + } + + /** + * Exec import table data. + * + * @param query the query + * @param fileStream the file stream + * @return the long + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public long execImportTableData(String query, FileInputStream fileStream) + throws DatabaseCriticalException, DatabaseOperationException { + long totalRows = 0; + try { + CopyManager cm = new CopyManager((BaseConnection) dbConnection); + totalRows = cm.copyIn(query, fileStream); + } catch (SQLException excep) { + commitConnection(IMessagesConstants.ERR_IMPORT_TABLE_TO_CSV); + GaussUtils.handleCriticalException(excep); + throw new DatabaseOperationException(IMessagesConstants.ERR_IMPORT_TABLE_TO_CSV, + extractErrorCodeAndErrorMsgFromServerError(excep), excep); + } catch (IOException eexp) { + commitConnection(IMessagesConstants.ERR_IMPORT_TABLE_TO_CSV); + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_IMPORT_TABLE_TO_CSV), + eexp); + throw new DatabaseOperationException(IMessagesConstants.ERR_IMPORT_TABLE_TO_CSV, eexp); + } + return totalRows; + } + + /** + * Exec export data. + * + * @param query the query + * @param fileOutStream the file out stream + * @return the long + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public long execExportData(String query, FileOutputStream fileOutStream) + throws DatabaseCriticalException, DatabaseOperationException { + long totalRows = 0; + try { + CopyManager cm = new CopyManager((BaseConnection) dbConnection); + totalRows = cm.copyOut(query, fileOutStream); + } catch (SQLException exe) { + commitConnection(IMessagesConstants.ERR_EXPORT_TABLE); + GaussUtils.handleCriticalException(exe); + throw new DatabaseOperationException(IMessagesConstants.ERR_EXPORT_TABLE, + extractErrorCodeAndErrorMsgFromServerError(exe), exe); + } catch (IOException exp) { + commitConnection(IMessagesConstants.ERR_EXPORT_TABLE); + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.IO_EXCEPTION_WHILE_EXPORT), + exp); + throw new DatabaseOperationException(IMessagesConstants.IO_EXCEPTION_WHILE_EXPORT, exp); + } + return totalRows; + } + + /** + * Checks if is connected. + * + * @return true, if is connected + */ + private boolean isConnected() { + try { + return (null != dbConnection) ? !dbConnection.isClosed() : false; + + } catch (SQLException e) { + return false; + } + } + + /** + * Commit connection. + * + * @param error the error + * @throws DatabaseOperationException the database operation exception + */ + public void commitConnection(String error) throws DatabaseOperationException { + if (!isConnected()) { + return; + } + + try { + if (!dbConnection.getAutoCommit()) { + dbConnection.commit(); + dbConnection.setAutoCommit(true); + } + } catch (SQLException e1) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(error), e1); + throw new DatabaseOperationException(error, e1); + } + } + + /** + * Exec non select. + * + * @param query the query + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void execNonSelect(final String query) throws DatabaseOperationException, DatabaseCriticalException { + PreparedStatement stmt = null; + try { + stmt = dbConnection.prepareStatement(query); + registerNoticeListner(stmt, GlobaMessageQueueUtil.getInstance().getMessageQueue()); + MPPDBIDELoggerUtility.perf("EXECUTION", ILogger.PERF_EXECUTE_STMT, true); + stmt.execute(); + MPPDBIDELoggerUtility.perf("EXECUTION", ILogger.PERF_EXECUTE_STMT, false); + + } catch (SQLException excep) { + GaussUtils.handleCriticalException(excep); + try { + if (!dbConnection.getAutoCommit()) { + dbConnection.rollback(); + } + } catch (SQLException e1) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_QUERY_EXECUTION_FAILED), e1); + throw new DatabaseOperationException(IMessagesConstants.ERR_QUERY_EXECUTION_FAILED, + extractErrorCodeAndErrorMsgFromServerError(e1), excep); + } + + throw new DatabaseOperationException(IMessagesConstants.ERR_QUERY_EXECUTION_FAILED, + extractErrorCodeAndErrorMsgFromServerError(excep), excep); + } finally { + + try { + if (!dbConnection.getAutoCommit()) { + dbConnection.commit(); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Statement close failed for execNonselect", exception); + // no need to do anytihng + } + try { + + if (null != stmt) { + stmt.close(); + } + + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Statement close failed for execNonselect ", exception); + // no need to do anytihng + } + } + } + + /** + * Exec query with msg queue. + * + * @param query the query + * @param queue the queue + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void execQueryWithMsgQueue(final String query, MessageQueue queue) + throws DatabaseOperationException, DatabaseCriticalException { + PreparedStatement stmt = null; + try { + stmt = dbConnection.prepareStatement(query); + registerNoticeListner(stmt, queue); + MPPDBIDELoggerUtility.perf("EXECUTION", ILogger.PERF_EXECUTE_STMT, true); + stmt.execute(); + MPPDBIDELoggerUtility.perf("EXECUTION", ILogger.PERF_EXECUTE_STMT, false); + } catch (SQLException eexc) { + GaussUtils.handleCriticalException(eexc); + throw new DatabaseOperationException(IMessagesConstants.ERR_QUERY_EXECUTION_FAILED, + extractErrorCodeAndErrorMsgFromServerError(eexc), eexc); + } finally { + try { + if (null != stmt) { + stmt.close(); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Statement close failed for execQueryWithMsgQueue", exception); + // no need to do anytihng + } + } + } + + /** + * + * We have added ExecuteTimerForNonSelect timer to cancel query if table is + * locked by any other operation + * + * + * @param query the query + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + + public void execNonSelectForTimeout(final String query) + throws DatabaseOperationException, DatabaseCriticalException { + ExecuteTimerForNonSelect exec = null; + long delay = 24 * 60 * 60 * DELAY_MILLI; // 1 day in ms + + PreparedStatement stmtForTimeout = null; + try { + // Temp fix. Need to find proper fix. + exec = new ExecuteTimerForNonSelect(this, delay); + exec.start(); + stmtForTimeout = dbConnection.prepareStatement(query); + registerNoticeListner(stmtForTimeout, GlobaMessageQueueUtil.getInstance().getMessageQueue()); + MPPDBIDELoggerUtility.perf("EXECUTION", ILogger.PERF_EXECUTE_STMT, true); + stmtForTimeout.execute(); + MPPDBIDELoggerUtility.perf("EXECUTION", ILogger.PERF_EXECUTE_STMT, false); + } catch (SQLException exe) { + GaussUtils.handleCriticalException(exe); + try { + if (!dbConnection.getAutoCommit()) { + dbConnection.rollback(); + } + } catch (SQLException e1) { + logAndThrowException(e1); + } + + if (exec.isQueryCanceled()) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_NONSELECT_CANCELLED)); + throw new DatabaseOperationException(IMessagesConstants.ERR_NONSELECT_CANCELLED); + } + logAndThrowException(exe); + } finally { + if (null != exec) { + exec.stop(); + } + try { + if (!dbConnection.getAutoCommit()) { + dbConnection.commit(); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Statement close failed.", exception); + } + try { + if (null != stmtForTimeout) { + stmtForTimeout.close(); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Statement close failed.", exception); + } + } + } + + private void logAndThrowException(SQLException e1) throws DatabaseOperationException { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_QUERY_EXECUTION_FAILED, + extractErrorCodeAndErrorMsgFromServerError(e1)), e1); + throw new DatabaseOperationException(IMessagesConstants.ERR_QUERY_EXECUTION_FAILED, + extractErrorCodeAndErrorMsgFromServerError(e1), e1); + } + + /** + * Register Notice listner to read Raise messages and dbms_output + * results.This check is a testability requirement + * + * @param stmt the stmt + * @param messageQueue the message queue + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void registerNoticeListner(Statement stmt, MessageQueue messageQueue) + throws DatabaseCriticalException, DatabaseOperationException { + try { + if (stmt instanceof BaseStatement) { + ((BaseStatement) stmt).addNoticeListener(new GaussMppDbNoticeListner(messageQueue)); + } + } + + catch (SQLException excep) { + GaussUtils.handleCriticalException(excep); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_STMT_EXCEPTION, excep); + } + } + + /** + * Close result set. + * + * @param rs the rs + */ + + public void closeResultSet(ResultSet rs) { + if (null == rs) { + return; + } + + Statement stmt = null; + try { + stmt = rs.getStatement(); + + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Obtaining Statement failure.", exception); + } + try { + rs.close(); + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Statement close failure. Nothing can be done.", exception); + } + closeStatement(stmt); + } + + /** + * Rollback. + */ + public void rollback() { + if (!isConnected()) { + return; + } + + try { + if (!dbConnection.getAutoCommit()) { + dbConnection.rollback(); + dbConnection.setAutoCommit(true); + } + } catch (SQLException e1) { + MPPDBIDELoggerUtility.error("Error while closing the transcation", e1); + } + } + + /** + * Sets the driver. + * + * @param driver the new driver + */ + public void setDriver(IConnectionDriver driver) { + this.dbmsDriver = driver; + } + + /** + * Gets the driver. + * + * @return the driver + */ + public IConnectionDriver getDriver() { + return this.dbmsDriver; + } + + /** + * Sets the connection. + * + * @param connection the new connection + */ + public void setConnection(Connection connection) { + this.dbConnection = connection; + } + + /** + * Extract error code and error msg from server error. + * + * @param eex the e + * @return the string + */ + public String extractErrorCodeAndErrorMsgFromServerError(SQLException eex) { + return this.getDriver().extractErrCodeAdErrMsgFrmServErr(eex); + } + + /** + * Gets the show DDL support from server. + * + * @return the show DDL support from server + */ + public boolean getShowDDLSupportFromServer() { + String count = "0"; + try { + count = execSelectAndGetFirstVal(SERVER_SUPPORT_DDL_QUERY); + } catch (MPPDBIDEException exception) { + MPPDBIDELoggerUtility.error("error while checking show DDL server support", exception); + return false; + } + if (MPPDBIDELoggerUtility.isDebugEnabled()) { + MPPDBIDELoggerUtility + .debug("server does " + ("0".equals(count) ? "not" : "") + " support fetch DDL for tables"); + } + + return !"0".equals(count); + } + + /** + * Checks if is OLAP connection. + * + * @return true, if is OLAP connection + * @Title: isOLAPConnection + * @Description: check connection whether is belonged to OLAP + */ + public boolean isOLAPConnection() { + String driverName = this.getDriver().getDriverName(); + return (driverName.contains(MPPDBIDEConstants.GAUSS200V1R5DRIVER) + || driverName.contains(MPPDBIDEConstants.GAUSS200V1R6DRIVER) + || driverName.contains(MPPDBIDEConstants.GAUSS200V1R7DRIVER)) ? true : false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/Datatype.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/Datatype.java new file mode 100644 index 0000000000000000000000000000000000000000..7aa93501c747c34aca0156f7715f99b6023ad6cd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/Datatype.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.gauss; + +/** + * + * Title: class + * + * Description: The Class Datatype. + * + * @since 3.0.0 + */ +public class Datatype { + private String typename; + private boolean isSupported; + + /** + * Instantiates a new datatype. + * + * @param oid the oid + * @param typename the typename + * @param isSupported the is supported + */ + public Datatype(int oid, String typename, boolean isSupported) { + super(); + this.typename = typename; + this.isSupported = isSupported; + } + + /** + * Gets the typename. + * + * @return the typename + */ + public String getTypename() { + return typename; + } + + /** + * Checks if is supported. + * + * @return true, if is supported + */ + public boolean isSupported() { + return isSupported; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/ExecuteTimerForNonSelect.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/ExecuteTimerForNonSelect.java new file mode 100644 index 0000000000000000000000000000000000000000..02fce0fc2d6b36f6caab3dbf9afe60526199caa5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/ExecuteTimerForNonSelect.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.gauss; + +import java.util.Timer; +import java.util.TimerTask; + +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class ExecuteTimerForNonSelect. + * + * @since 3.0.0 + */ +public class ExecuteTimerForNonSelect { + private DBConnection dbConn; + private Long delay; + private Timer timer; + private boolean isQueryCanceled; + + /** + * Instantiates a new execute timer for non select. + * + * @param dbConnection the db connection + * @param delay the delay + */ + public ExecuteTimerForNonSelect(DBConnection dbConnection, Long delay) { + this.dbConn = dbConnection; + this.delay = delay; + timer = new Timer(); + } + + /** + * Start. + */ + public void start() { + timer.schedule(new TimerTask() { + + @Override + public void run() { + + try { + if (!dbConn.isClosed()) { + dbConn.cancelQuery(); + isQueryCanceled = true; + + } + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("Cancel query failed", exception); + } catch (DatabaseCriticalException exception) { + MPPDBIDELoggerUtility.error("Cancel query failed", exception); + } + + } + }, delay); + } + + /** + * Checks if is query canceled. + * + * @return true, if is query canceled + */ + public boolean isQueryCanceled() { + return isQueryCanceled; + } + + /** + * Stop. + */ + public void stop() { + timer.cancel(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/GaussDatatypeUtils.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/GaussDatatypeUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..076cb5379e183049fb3f66d76dce44ce4e34113c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/GaussDatatypeUtils.java @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.gauss; + +import java.util.HashMap; + +/** + * + * Title: class + * + * Description: The Class GaussDatatypeUtils. + * + * @since 3.0.0 + */ +public class GaussDatatypeUtils { + + private static HashMap datatypeMap = new HashMap(50); + + static { + addDataTypesFirstList(); + addDataTypeSecondList(); + } + + private static void addDataTypeSecondList() { + addDatatype(1002, "char[]", true); + addDatatype(1003, "name[]", true); + addDatatype(1005, "smallint[]", true); + addDatatype(1006, "int2vector[]", false); + addDatatype(1007, "integer[]", true); + addDatatype(1009, "text[]", true); + addDatatype(1010, "tid[]", false); + addDatatype(1011, "xid[]", false); + addDatatype(1012, "cid[]", false); + addDatatype(1013, "oidvector[]", false); + addDatatype(1014, "char[]", true); + addDatatype(1015, "varchar[]", true); + addDatatype(1016, "bigint[]", true); + addDatatype(1028, "oid[]", true); + addDatatype(1042, "char", true); + addDatatype(1043, "varchar", true); + addDatatype(1082, "date", true); + addDatatype(1083, "time", true); + addDatatype(1114, "timestamp", true); + addDatatype(1115, "timestamp[]", true); + addDatatype(1183, "time[]", true); + addDatatype(1184, "timestamp with time zone", true); + addDatatype(1185, "timestamp with time zone[]", true); + addDatatype(1186, "interval", true); + addDatatype(1187, "interval[]", true); + addDatatype(1231, "numeric[]", true); + addDatatype(1266, "time with time zone", true); + addDatatype(1270, "time with time zone[]", true); + addDatatype(1560, "bit", false); + addDatatype(1561, "bit[]", false); + addDatatype(1700, "numeric", true); + addDatatype(1790, "refcursor", true); + addDatatype(2249, "record", true); + addDatatype(2278, "void", true); + } + + private static void addDataTypesFirstList() { + addDatatype(16, "bool", true); + addDatatype(17, "bytea", true); + addDatatype(18, "char", true); + addDatatype(19, "name", true); + addDatatype(20, "bigint", true); + addDatatype(21, "smallint", true); + addDatatype(22, "int2vector", false); + addDatatype(23, "integer", true); + addDatatype(24, "regproc", false); + addDatatype(25, "text", true); + addDatatype(26, "oid", true); + addDatatype(27, "tid", false); + addDatatype(28, "xid", false); + addDatatype(29, "cid", false); + addDatatype(30, "oidvector", false); + addDatatype(114, "json", false); + addDatatype(119, "json[]", false); + addDatatype(142, "xml", false); + addDatatype(143, "xml[]", false); + addDatatype(210, "smgr", false); + addDatatype(600, "point", false); + addDatatype(601, "lseg", false); + addDatatype(602, "path", false); + addDatatype(603, "box", false); + addDatatype(604, "polygon", false); + addDatatype(628, "line", false); + addDatatype(629, "line[]", false); + addDatatype(650, "cidr", false); + addDatatype(700, "real", true); + addDatatype(701, "double precision", true); + addDatatype(718, "circle", false); + addDatatype(719, "circle[]", false); + addDatatype(790, "money", false); + addDatatype(829, "macaddr", false); + addDatatype(869, "inet", false); + addDatatype(1000, "bool[]", false); + addDatatype(1001, "bytea[]", true); + addDatatype(88, "blob", true); + addDatatype(90, "clob", true); + } + + /** + * Adds the datatype. + * + * @param oid the oid + * @param name the name + * @param isSupported the is supported + */ + public static void addDatatype(int oid, String name, boolean isSupported) { + Datatype type = new Datatype(oid, name, isSupported); + + datatypeMap.put(oid, type); + } + + /** + * Convert to client type. + * + * @param typId the typ id + * @return the string + */ + public static String convertToClientType(int typId) { + Datatype datatype = datatypeMap.get(typId); + if (null == datatype) { + return null; + } + + return datatype.getTypename(); + } + + /** + * Checks if is supported. + * + * @param typId the typ id + * @return true, if is supported + */ + public static boolean isSupported(int typId) { + Datatype datatype = datatypeMap.get(typId); + + if (null == datatype) { + return false; + } + + return datatype.isSupported(); + } + + /** + * Gets the datatype hashmap. + * + * @return HashMap the datatype map + */ + public static HashMap getDataTypeHashMap() { + return datatypeMap; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/GaussDriverWrapper.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/GaussDriverWrapper.java new file mode 100644 index 0000000000000000000000000000000000000000..d5b2268f673c6ecb17d4bef32f0ed3f36423b047 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/GaussDriverWrapper.java @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.gauss; + +import java.sql.Driver; +import java.sql.SQLException; +import java.util.List; +import java.util.Properties; + +import org.opengauss.mppdbide.adapter.AbstractConnectionDriver; +import org.opengauss.mppdbide.adapter.IConnectionDriver; +import org.opengauss.mppdbide.adapter.keywordssyntax.Keywords; +import org.opengauss.mppdbide.adapter.keywordssyntax.SQLSyntax; + +/** + * + * Title: class + * + * Description: The Class GaussDriverWrapper. + * + * @since 3.0.0 + */ +public class GaussDriverWrapper implements IConnectionDriver { + private AbstractConnectionDriver driverInstance; + private String driverWrapperName; + private static volatile int driverWrapperCount = 0; + + private boolean isShowDDLSupport = false; + private boolean hasShowDDLSupportCheck = false; + + private static final Object LOCK = new Object(); + + /** + * Gets the unique count. + * + * @return the unique count + */ + private static int getUniqueCount() { + synchronized (LOCK) { + driverWrapperCount++; + } + return driverWrapperCount; + } + + /** + * Instantiates a new gauss driver wrapper. + * + * @param driver the driver + */ + public GaussDriverWrapper(AbstractConnectionDriver driver) { + this.driverInstance = driver; + this.driverWrapperName = this.driverInstance.getDriverName() + String.valueOf(getUniqueCount()); + } + + /** + * Gets the driver instance. + * + * @return the driver instance + */ + public AbstractConnectionDriver getDriverInstance() { + return this.driverInstance; + } + + /** + * Gets the show DDL support. + * + * @return the show DDL support + */ + public boolean getShowDDLSupport() { + return this.isShowDDLSupport; + } + + /** + * Gets the show DDL support. + * + * @param connection the connection + * @return the show DDL support + */ + public boolean getShowDDLSupport(DBConnection connection) { + this.isShowDDLSupport = connection.getShowDDLSupportFromServer(); + this.hasShowDDLSupportCheck = true; + return this.isShowDDLSupport; + } + + /** + * Gets the show DDL support check. + * + * @return the show DDL support check + */ + public boolean getShowDDLSupportCheck() { + return this.hasShowDDLSupportCheck; + } + + @Override + public String getDriverName() { + return this.driverWrapperName; + } + + @Override + public String getToolPath(String toolName) { + return this.driverInstance.getToolPath(toolName); + } + + @Override + public Driver getJDBCDriver() { + return this.driverInstance.getJDBCDriver(); + } + + @Override + public Properties getDriverSpecificProperties() { + return this.driverInstance.getDriverSpecificProperties(); + } + + @Override + public String extractErrCodeAdErrMsgFrmServErr(SQLException eex) { + return this.driverInstance.extractErrCodeAdErrMsgFrmServErr(eex); + } + + @Override + public Keywords getKeywordList() { + return this.driverInstance.getKeywordList(); + } + + @Override + public SQLSyntax loadSQLSyntax() { + + return this.driverInstance.loadSQLSyntax(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/GaussMppDbNoticeListner.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/GaussMppDbNoticeListner.java new file mode 100644 index 0000000000000000000000000000000000000000..cf4fecd2013bb79787cb4184ff24fadae114f347 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/GaussMppDbNoticeListner.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.gauss; + +import java.sql.SQLWarning; + +import org.postgresql.core.NoticeListener; + +import org.opengauss.mppdbide.utils.messaging.IMessageQueue; +import org.opengauss.mppdbide.utils.messaging.Message; +import org.opengauss.mppdbide.utils.messaging.MessageQueue; +import org.opengauss.mppdbide.utils.messaging.MessageType; + +/** + * + * Title: class + * + * Description: The Class GaussMppDbNoticeListner. + * + * @since 3.0.0 + */ +public class GaussMppDbNoticeListner implements NoticeListener { + private IMessageQueue msgQ; + + /** + * Instantiates a new gauss mpp db notice listner. + * + * @param messageQueue the message queue + */ + public GaussMppDbNoticeListner(MessageQueue messageQueue) { + msgQ = messageQueue; + } + + @Override + public void noticeReceived(SQLWarning notice) { + if (null == notice || null == notice.getMessage() || null == msgQ) { + return; + } + + String msgString = notice.getMessage(); + Message msg = new Message(MessageType.NOTICE, msgString); + msgQ.push(msg); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/GaussUtils.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/GaussUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..bb7a8e7a022700b87f9c14c3ccdc0e3feb735d73 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/GaussUtils.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.gauss; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.adapter.AbstractConnectionDriver; +import org.opengauss.mppdbide.adapter.IConnectionDriver; +import org.opengauss.mppdbide.utils.CustomStringUtility; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class GaussUtils. + * + * @since 3.0.0 + */ +public class GaussUtils { + + private static final String CRITICAL_ERROR_57P = "57P"; + private static final String IGNORE_BIND_ERROR = "bind message"; + private static final String IGNORE_FUN_CALL_ERROR = "function call message contains"; + private static final String IGNORE_DESC_ERROR = "invalid DESCRIBE message subtype"; + private static final String SESSION_KILLED = "Session killed"; + + private static final String OBJECT_NOT_FOUND_ERROR = "does not exist"; + + private static List criticalErrorCodeList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + + static { + criticalErrorCodeList.add("08006"); + criticalErrorCodeList.add("08003"); + criticalErrorCodeList.add("08P01"); + criticalErrorCodeList.add("53300"); + criticalErrorCodeList.add("08001"); + } + + /** + * Handle critical exception. + * + * @param excep the e + * @throws DatabaseCriticalException the database critical exception + */ + public static void handleCriticalException(SQLException excep) throws DatabaseCriticalException { + if (excep.getLocalizedMessage() != null && excep.getLocalizedMessage().contains(SESSION_KILLED)) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_BL_EXECUTE_FAILED), + excep); + throw new DatabaseCriticalException(IMessagesConstants.ERR_BL_EXECUTE_FAILED, excep); + } + String sqlState = excep.getSQLState(); + if ((sqlState != null) + && (sqlState.startsWith(CRITICAL_ERROR_57P) || criticalErrorCodeList.contains(sqlState))) { + if ("08P01".equalsIgnoreCase(sqlState) && null != excep.getMessage() + && (excep.getMessage().contains(IGNORE_BIND_ERROR) + || excep.getMessage().contains(IGNORE_FUN_CALL_ERROR) + || excep.getMessage().contains(IGNORE_DESC_ERROR)) + || excep.getMessage().contains("Protocol error.")) { + return; + } + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_BL_EXECUTE_FAILED), + excep); + throw new DatabaseCriticalException(IMessagesConstants.ERR_BL_EXECUTE_FAILED, excep); + } + } + + /** + * Checks if is object not found err. + * + * @param eex the e + * @return true, if is object not found err + */ + public static boolean isObjectNotFoundErr(SQLException eex) { + String sqlState = eex.getSQLState(); + if (sqlState != null && sqlState.equals("42704") && null != eex.getMessage() + && eex.getMessage().contains(OBJECT_NOT_FOUND_ERROR)) { + return true; + } + + return false; + } + + /** + * Checks if is protocol version needed. + * + * @param driver the driver + * @return true, if is protocol version needed + */ + public static boolean isProtocolVersionNeeded(AbstractConnectionDriver driver) { + return (null != driver) && CustomStringUtility.isProtocolVersionNeeded(driver.getDriverName()); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/HandleGaussStringEscaping.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/HandleGaussStringEscaping.java new file mode 100644 index 0000000000000000000000000000000000000000..29c08931c0bbc35b211811e8640fb683ba12f1c9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/HandleGaussStringEscaping.java @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.gauss; + +import java.io.IOException; + +import javax.print.attribute.standard.MediaSize.NA; + +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class HandleGaussStringEscaping. + * + * @since 3.0.0 + */ +public class HandleGaussStringEscaping { + + /** + * Escape literal. + * + * @param sbufParam the sbuf param + * @param valueParam the value param + * @return the string builder + */ + public static StringBuilder escapeLiteral(StringBuilder sbufParam, String valueParam) { + StringBuilder sbuf = sbufParam; + String value = valueParam; + if (value == null) { + return new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + } + if (sbuf == null) { + sbuf = new StringBuilder(value.length() * 11 / 10); // Add 10% for + // escaping. + } + try { + doAppendEscapedLiteral(sbuf, value); + } catch (MPPDBIDEException exception) { + MPPDBIDELoggerUtility.warn(" Error while escaping literal. "); + } + return sbuf; + } + + /** + * Do append escaped literal.With standard_conforming_strings on, escape + * only single-quotes. + * + * @param sbuf the sbuf + * @param value the value + * @throws MPPDBIDEException the MPPDBIDE exception + */ + private static void doAppendEscapedLiteral(Appendable sbuf, String value) throws MPPDBIDEException { + try { + + char ch = '\''; + sbuf.append(ch); + + int length = value.length(); + for (int index = 0; index < length; ++index) { + + ch = value.charAt(index); + + if (ch == '\0') { + MPPDBIDELoggerUtility.error("Zero bytes may not occur in string parameters."); + throw new MPPDBIDEException("Zero bytes may not occur in string parameters."); + } + + if (ch == '\'') { + sbuf.append('\''); + } + + sbuf.append(ch); + } + + sbuf.append('\''); + } catch (IOException e) { + throw new MPPDBIDEException("No IOException expected from StringBuffer or StringBuilder"); + } + } + + /** + * Escape identifier. + * + * @param value the value + * @return the string builder + */ + public static StringBuilder escapeIdentifier(String value) { + StringBuilder sbuf = null; + if (value == null) { + return new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + } + if (sbuf == null) { + // Add 10% for escaping + sbuf = new StringBuilder(2 + value.length() * 11 / 10); + + } + try { + doAppendEscapedIdentifier(sbuf, value); + } catch (MPPDBIDEException exception) { + MPPDBIDELoggerUtility.warn(" Error while escaping identifier name."); + } + return sbuf; + } + + /** + * Common part for appendEscapedIdentifier. + * + * @param sbuf Either StringBuffer or StringBuilder as we do not expect any + * IOException to be thrown. + * @param value value to append + * @throws MPPDBIDEException the MPPDBIDE exception + */ + private static void doAppendEscapedIdentifier(Appendable sbuf, String value) throws MPPDBIDEException { + try { + + char ch = '"'; + sbuf.append(ch); + + int length = value.length(); + + for (int index = 0; index < length; ++index) { + ch = value.charAt(index); + if (ch == '\0') { + MPPDBIDELoggerUtility.error("Zero bytes may not occur in string parameters."); + throw new MPPDBIDEException("Zero bytes may not occur in string parameters."); + } + if (ch == '"') { + sbuf.append(ch); + } + sbuf.append(ch); + } + + sbuf.append('"'); + } catch (IOException e) { + throw new MPPDBIDEException("No IOException expected from StringBuffer or StringBuilder"); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/ObjectBrowserDBConnection.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/ObjectBrowserDBConnection.java new file mode 100644 index 0000000000000000000000000000000000000000..00df9f1e2d7904402da90a150f51a97b75226311 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/ObjectBrowserDBConnection.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.gauss; + +import java.sql.ResultSet; + +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: class + * + * Description: The Class ObjectBrowserDBConnection. + * + */ + +public class ObjectBrowserDBConnection extends DBConnection { + private final Object lock = new Object(); + + @Override + public String execSelectAndGetFirstVal(String query) throws DatabaseCriticalException, DatabaseOperationException { + synchronized (lock) { + return super.execSelectAndGetFirstVal(query); + } + } + + @Override + public ResultSet execSelectAndReturnRs(String query) throws DatabaseCriticalException, DatabaseOperationException { + synchronized (lock) { + return super.execSelectAndReturnRs(query); + } + } + + @Override + public ResultSet execSelectToExportCSV(String query, int preferenceCount) + throws DatabaseCriticalException, DatabaseOperationException { + synchronized (lock) { + return super.execSelectToExportCSV(query, preferenceCount); + } + } + + @Override + public void execNonSelect(String query) throws DatabaseOperationException, DatabaseCriticalException { + synchronized (lock) { + super.execNonSelect(query); + } + } + + @Override + public void execNonSelectForTimeout(String query) throws DatabaseOperationException, DatabaseCriticalException { + synchronized (lock) { + super.execNonSelectForTimeout(query); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/StmtExecutor.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/StmtExecutor.java new file mode 100644 index 0000000000000000000000000000000000000000..796353fca2ece2c3af136fe9744d256d0c199a8f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/gauss/StmtExecutor.java @@ -0,0 +1,913 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.gauss; + +import java.sql.CallableStatement; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.Locale; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.QueryResultType; +import org.opengauss.mppdbide.utils.ResultSetDatatypeMapping; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.ILogger; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.MessageQueue; + +/** + * Title: class Description: The Class StmtExecutor. + * + * @since 3.0.0 + */ +public class StmtExecutor { + private static final String CURSOR_QUERY_PREPEND = "CURSOR %s NO SCROLL FOR %s"; + + private static final String FETCH_QUERY = "FETCH FORWARD %d FROM %s"; + + private static String cursorName = null; + + private static ArrayList outResultList; + + private int nRowsAffected; + + private int colCount; + + private ResultSetMetaData rsMetaData; + + private ResultSet rs; + + private PreparedStatement preparedStmt; + + private Statement stmt; + + private CallableStatement calStmt; + + private String strQry; + + private QueryResultType qryResultType; + + private DBConnection connection; + + private boolean isLastRecordFetched = false; + + private int fetchCount = 0; + + private int regOutParameter = 0; + + private boolean isCursorResultSetType; + + /** + * Gets the query. + * + * @return the query + */ + public String getQuery() { + return strQry; + } + + /** + * Sets the fetch count. + * + * @param fetchCount the new fetch count + */ + public void setFetchCount(int fetchCount) { + this.fetchCount = fetchCount; + } + + /** + * sets the list of out parameter result set + * + * @param outResultList the out param result list + */ + public void setOutResultList(ArrayList outResultList) { + this.outResultList = outResultList; + } + + /** + * get the list of out parameter result set + * + * @return outResultList the out param result list + */ + public static ArrayList getOutResultList() { + return outResultList; + } + + /** + * return true if Callable statement executed + * + * @return return true is callable statement executed + */ + public static boolean isCallableStmtExecuted() { + return (outResultList != null); + } + + /** + * get the no of registered out parameter + * + * @return regOutParameter the no of reg out parameter + */ + public int getRegOutParameter() { + return this.regOutParameter; + } + + /** + * Instantiates a new stmt executor. + * + * @param qry the qry + * @param con the con + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + + public StmtExecutor(String qry, DBConnection con) + throws DatabaseCriticalException, DatabaseOperationException { + strQry = qry; + try { + this.connection = con; + if (!this.connection.isOLAPConnection() && (qry != null && qry.endsWith(";"))) { + qry = qry.substring(0, qry.length() - 1); + } + if (isCALLOrEXECStatement(qry)) { + calStmt = connection.getConnection().prepareCall(qry); + } else { + preparedStmt = connection.getConnection().prepareStatement(qry); + } + } catch (SQLException excep) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_STMT_EXCEPTION), + excep); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_STMT_EXCEPTION, excep); + } + } + + private boolean isCALLOrEXECStatement(String qry) { + return null != qry && (qry.toLowerCase(Locale.ENGLISH).startsWith("exec") + || qry.toLowerCase(Locale.ENGLISH).startsWith("call")) && qry.contains("?"); + } + + /** + * Close result set. + */ + public void closeResultSet() { + try { + if (null != rs) { + rs.close(); + } + } catch (SQLException excep) { + MPPDBIDELoggerUtility.error("ADAPTER: resultset close returned exception"); + } + } + + /** + * Close statement. + */ + public void closeStatement() { + try { + if (stmt != null) { + stmt.close(); + } + if (null != calStmt) { + calStmt.close(); + } + if (null != preparedStmt) { + preparedStmt.close(); + } + } catch (SQLException excep) { + MPPDBIDELoggerUtility.error("ADAPTER: statement close returned exception"); + } + } + + /** + * Commit connection. + */ + public void commitConnection() { + try { + if (!connection.getConnection().getAutoCommit()) { + + connection.getConnection().commit(); + } + connection.getConnection().setAutoCommit(true); + } catch (SQLException excep) { + MPPDBIDELoggerUtility.error("ADAPTER: statement close returned exception"); + } + } + + /** + * Rollback. + */ + public void rollback() { + try { + connection.getConnection().rollback(); + if (!connection.getConnection().getAutoCommit()) { + connection.getConnection().setAutoCommit(true); + } + } catch (SQLException excep) { + MPPDBIDELoggerUtility.error("ADAPTER: statement close returned exception"); + } + } + + /** + * Gets the colum count. + * + * @return the colum count + */ + public int getColumCount() { + return colCount; + } + + /** + * Checks if is query DML. + * + * @return true, if is query DML + */ + private boolean isQueryDML() { + String[] dmlList = {"INSERT ", "UPDATE ", "DELETE "}; + String tempQuery = strQry; + + tempQuery = tempQuery.trim(); + + tempQuery = tempQuery.toUpperCase(Locale.ENGLISH); + + for (int index = 0; index < dmlList.length; index++) { + if (tempQuery.startsWith(dmlList[index])) { + return true; + } + } + + return false; + } + + /** + * Execute. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + + public void execute() throws DatabaseOperationException, DatabaseCriticalException { + boolean retType = false; + try { + MPPDBIDELoggerUtility.info("ADAPTER: Sending user query execution request to server"); + MPPDBIDELoggerUtility.perf("EXECUTION", ILogger.PERF_EXECUTE_STMT, true); + if (preparedStmt != null) { + preparedStmt.setFetchSize(fetchCount); + retType = preparedStmt.execute(); + setOutResultList(null); + } else if (stmt != null) { + retType = handleStmtExecution(); + } else { + retType = handleCallStmtExecution(); + } + + MPPDBIDELoggerUtility.perf("EXECUTION", ILogger.PERF_EXECUTE_STMT, false); + + /* + * This code is to get the last result set of the query, incase of + * multiple sql statements are executed in one shot. Later point of + * time, consider this for implementation + */ + handleQueryResultType(retType); + MPPDBIDELoggerUtility.info("ADAPTER: User query Executed successfully"); + } catch (SQLException excep) { + closeStatement(); + GaussUtils.handleCriticalException(excep); + throw new DatabaseOperationException(IMessagesConstants.ERR_BL_EXECUTE_FAILED, + connection.extractErrorCodeAndErrorMsgFromServerError(excep), excep); + } catch (OutOfMemoryError excep) { + closeStatement(); + MPPDBIDELoggerUtility.error("OutOfMemoryError ocurred"); + throw new DatabaseCriticalException(IMessagesConstants.ERR_MSG_OUT_OF_MEMORY_ERROR_OCCURRED, excep); + } + } + + /** + * handle type of query result + * + * @param retType the return type + * @throws SQLException + */ + private void handleQueryResultType(boolean retType) throws SQLException { + // false means update query + if (!retType) { + qryResultType = QueryResultType.RESULTTYPE_DML; + if (preparedStmt != null) { + nRowsAffected = preparedStmt.getUpdateCount(); + + } else if (stmt != null) { + nRowsAffected = stmt.getUpdateCount(); + } else { + nRowsAffected = calStmt.getUpdateCount(); + } + + // If number of rows affected is 0, then it can be either DDL or + // DML. + if (nRowsAffected == 0) { + if (!isQueryDML()) { + qryResultType = QueryResultType.RESULTTYPE_OTHERS; + } + } + } else { + qryResultType = QueryResultType.RESULTTYPE_RESULTSET; + if (preparedStmt != null) { + rs = preparedStmt.getResultSet(); + } + if (stmt != null) { + rs = stmt.getResultSet(); + } + if (rs != null) { + rsMetaData = rs.getMetaData(); + colCount = rsMetaData.getColumnCount(); + } + } + } + + /** + * handle callable statement execution + * + * @param outResultList the out parameter result list + * @return return true is return type is result set + * @throws SQLException + */ + private boolean handleCallStmtExecution() throws SQLException { + boolean retType = false; + ArrayList outResultLists = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + calStmt.setFetchSize(fetchCount); + calStmt.execute(); + if (!this.connection.getIsInOutValueExists()) { + return false; + } + for (int i = 1; i <= getRegOutParameter(); i++) { + Object rsObj = calStmt.getObject(i); + outResultLists.add(rsObj); + if (rsObj != null) { + if (rsObj instanceof ResultSet) { + rs = (ResultSet) rsObj; + isCursorResultSetType = true; + } + retType = true; + } + } + setOutResultList(outResultLists); + return retType; + } + + /** + * handle Statement execution + * + * @return return true if statement execution + * @throws SQLException + * @throws DatabaseCriticalException + * @throws DatabaseOperationException + */ + private boolean handleStmtExecution() throws SQLException, DatabaseCriticalException, DatabaseOperationException { + stmt.setFetchSize(fetchCount); + startTxn(); + stmt.execute(getCursorQuery()); + rs = stmt.executeQuery(getFetchQuery(1000)); + setUniqCursorName(null); + return true; + } + + /** + * start transaction + * + * @throws DatabaseCriticalException + * @throws DatabaseOperationException + */ + private void startTxn() throws DatabaseCriticalException, DatabaseOperationException { + try { + if (connection.getConnection().getAutoCommit()) { + // if already inside a transaction, no need to reset. + connection.getConnection().setAutoCommit(false); + } + } catch (SQLException ex) { + GaussUtils.handleCriticalException(ex); + throw new DatabaseOperationException(IMessagesConstants.ERR_DATABASE_OPERATION_FAILURE, ex); + } + } + + /** + * fetch query + * + * @param currentFetchSize the current fetch size + * @return the fetch query + */ + private String getFetchQuery(int currentFetchSize) { + return String.format(Locale.ENGLISH, FETCH_QUERY, currentFetchSize, getUniqCursorName()); + } + + /** + * get cursor query + * + * @return the cursor query + */ + private String getCursorQuery() { + return String.format(Locale.ENGLISH, CURSOR_QUERY_PREPEND, getUniqCursorName(), strQry); + } + + /** + * get cursor name + * + * @return cursorName the name of cursor + */ + public String getUniqCursorName() { + if (cursorName == null) { + String timeStamp = new SimpleDateFormat("HHmmssSSS").format(new Date()); + cursorName = "__DS_QRY_CRSR_" + timeStamp + "__"; + } + return cursorName; + } + + /** + * sets cursor name + * + * @param lcursorName the cursor name + */ + public static void setUniqCursorName(String lcursorName) { + cursorName = lcursorName; + } + + /** + * return true if result type is Cursor resultSet + * + * @return isCursorResultSetType true if cursor type resultset + */ + public boolean getCursorResultSetType() { + return this.isCursorResultSetType; + } + + /** + * Gets the column name. + * + * @param col the col + * @return the column name + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public String getColumnName(int col) throws DatabaseOperationException, DatabaseCriticalException { + String colName = null; + try { + if (rsMetaData != null) { + colName = rsMetaData.getColumnLabel(col); + } + } catch (SQLException excep) { + GaussUtils.handleCriticalException(excep); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, excep); + } + return colName; + } + + /** + * Gets the next object record batch. + * + * @param maxFetchCount the max fetch count + * @return the next object record batch + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public Object[][] getNextObjectRecordBatch(int maxFetchCount) + throws DatabaseOperationException, DatabaseCriticalException { + ArrayList rows = new ArrayList<>(); + int columnCount = getColumCount(); + int fetchIndex = 0; + Object[] row; + + try { + // Debug scenario will pass maxFetchCount as -1. If so, fetch + // everything. + while (maxFetchCount < 0 || fetchIndex < maxFetchCount) { + if (null != rs && rs.next()) { + row = new Object[columnCount]; + for (int index = 1; index <= columnCount; index++) { + row[index - 1] = ResultSetDatatypeMapping.getReadColumnValueObject(rs, index); + } + + rows.add(row); + fetchIndex++; + } else { + break; + } + } + } catch (SQLException excep) { + GaussUtils.handleCriticalException(excep); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, excep); + } catch (OutOfMemoryError excep) { + outOfMemoryErrorHandle(excep); + } + if (rows.size() == 0) { + this.isLastRecordFetched = true; + } + return (Object[][]) rows.toArray(new Object[rows.size()][columnCount]); + } + + /** + * Gets the next object record batch. + * + * @param maxFetchCount the max fetch count + * @param columnCount no of column + * @param isFuncProcResultFlow is function or procedure flow + * @param isInputParaVisited is input parameter visited + * @return the next object record batch + * @throws DatabaseOperationException + * @throws DatabaseCriticalException + */ + public Object[][] getNextObjectRecordBatch(int maxFetchCount, int columnCount, boolean isInputParaVisited) + throws DatabaseOperationException, DatabaseCriticalException { + ArrayList valueRows = new ArrayList<>(); + try { + if (!getCursorResultSetType()) { + if (null != rs && rs.next()) { + getFuncProcResultValue(rs, valueRows, + new GetFuncProcResultValueParam(columnCount, calStmt != null, false)); + } + } else { + getFuncProcResultValue(rs, valueRows, + new GetFuncProcResultValueParam(columnCount, calStmt != null, isInputParaVisited)); + } + } catch (SQLException exe) { + GaussUtils.handleCriticalException(exe); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exe); + } catch (OutOfMemoryError exe) { + outOfMemoryErrorHandle(exe); + } + if (valueRows.size() == 0) { + this.isLastRecordFetched = true; + } + return (Object[][]) valueRows.toArray(new Object[valueRows.size()][columnCount]); + } + + /** + * + * Title: class + * + * Description: The Class GetFuncProcResultValueParam. + * + */ + public static class GetFuncProcResultValueParam { + private int columnCount; + + private boolean isCallableStmt; + + private boolean isInputParaVisited; + + public GetFuncProcResultValueParam(int columnCount, boolean isCallableStmt, boolean isInputParaVisited) { + this.columnCount = columnCount; + this.isCallableStmt = isCallableStmt; + this.isInputParaVisited = isInputParaVisited; + } + + public int getColumnCount() { + return columnCount; + } + + public void setColumnCount(int columnCount) { + this.columnCount = columnCount; + } + + public boolean isCallableStmt() { + return isCallableStmt; + } + + public void setCallableStmt(boolean isCallableStmt) { + this.isCallableStmt = isCallableStmt; + } + + public boolean isInputParaVisited() { + return isInputParaVisited; + } + + public void setInputParaVisited(boolean isInputParaVisited) { + this.isInputParaVisited = isInputParaVisited; + } + } + + private void getFuncProcResultValue(ResultSet rs, ArrayList rows, GetFuncProcResultValueParam paramObj) + throws NumberFormatException, DatabaseOperationException, SQLException { + Object[] row = new Object[paramObj.getColumnCount()]; + int colIndex; + boolean isShowCursorPopup = getShowCursorPopup(rs); + for (colIndex = 1; colIndex < paramObj.getColumnCount(); colIndex++) { + row[colIndex - 1] = ResultSetDatatypeMapping.getFuncProcColObjectExceptValue(rs, colIndex, + getCursorResultSetType()); + } + if (isShowCursorPopup) { + row[colIndex - 1] = ResultSetDatatypeMapping.getReadColumnValueObject(rs, + rs.getMetaData().getColumnCount()); + } else if (getCursorResultSetType()) { + row[colIndex - 1] = ResultSetDatatypeMapping.convertResultSetToObject(rs, rs.getMetaData().getColumnCount(), + true, false); + } else { + row[colIndex - 1] = ResultSetDatatypeMapping.getReadColumnValueObject(rs, + rs.getMetaData().getColumnCount()); + } + rows.add(row); + } + + private boolean getShowCursorPopup(ResultSet rs2) throws SQLException { + if (MPPDBIDEConstants.REF_CURSOR.equals(rs.getMetaData().getColumnTypeName(rs.getMetaData().getColumnCount())) + || MPPDBIDEConstants.RECORD + .equals(rs.getMetaData().getColumnTypeName(rs.getMetaData().getColumnCount()))) { + return true; + } + return false; + } + + /** + * Out of memory error handle. + * + * @param exe the e + * @throws DatabaseCriticalException the database critical exception + */ + private void outOfMemoryErrorHandle(OutOfMemoryError exe) throws DatabaseCriticalException { + try { + stmt.close(); + } catch (SQLException excep1) { + MPPDBIDELoggerUtility + .error("After OutOfMemoryError unable" + " to close statement. Will throw critical exception."); + } + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_MSG_OUT_OF_MEMORY_ERROR_OCCURRED), exe); + throw new DatabaseCriticalException(IMessagesConstants.ERR_MSG_OUT_OF_MEMORY_ERROR_OCCURRED, exe); + } + + /** + * Gets the next record batch. + * + * @param count the count + * @return the next record batch + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public String[][] getNextRecordBatch(int count) throws DatabaseOperationException, DatabaseCriticalException { + int fetchcnt = 0; + ArrayList rowset = new ArrayList(MPPDBIDEConstants.RECORD_ARRAY_SIZE); + + try { + String[] row = null; + + while ((-1 == count || fetchcnt < count) && rs.next()) { + row = new String[colCount + 1]; + row[0] = String.valueOf(fetchcnt + 1); + for (int index = 1; index <= colCount; index++) { + row[index] = ResultSetDatatypeMapping.convertStringToValue(rs, index); + } + + rowset.add(row); + fetchcnt++; + } + } catch (SQLException excep) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + excep); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, excep); + } catch (OutOfMemoryError excep) { + outOfMemoryErrorHandle(excep); + } + + return (String[][]) rowset.toArray(new String[rowset.size()][colCount]); + } + + /** + * Gets the result set. + * + * @return the result set + */ + public ResultSet getResultSet() { + return rs; + } + + /** + * Gets the rows affected. + * + * @return the rows affected + */ + public int getRowsAffected() { + return nRowsAffected; + } + + /** + * Gets the result type. + * + * @return the result type + */ + public QueryResultType getResultType() { + return qryResultType; + } + + /** + * Checks if is last record. + * + * @return true, if is last record + * @throws DatabaseOperationException the database operation exception + */ + public boolean isLastRecord() throws DatabaseOperationException { + + try { + if (this.isLastRecordFetched) { + return true; + } + if (rs != null) { + return rs.isLast() || rs.isAfterLast(); + } + return true; + } catch (SQLException excep) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + excep); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, excep); + } + } + + /** + * Register notice listner. + * + * @param messageQueue the message queue + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + + public void registerNoticeListner(MessageQueue messageQueue) + throws DatabaseCriticalException, DatabaseOperationException { + if (null != stmt) { + connection.registerNoticeListner(stmt, messageQueue); + } else if (null != calStmt) { + connection.registerNoticeListner(calStmt, messageQueue); + } else if (null != preparedStmt) { + connection.registerNoticeListner(preparedStmt, messageQueue); + } + } + + /** + * Gets the column data type. + * + * @param index the index + * @return the column data type + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + + public int getColumnDataTypeStmt(int index) throws DatabaseOperationException, DatabaseCriticalException { + try { + if (rs != null && rs.getMetaData() != null) { + return this.rs.getMetaData().getColumnType(index); + } + return 0; + } catch (SQLException excep) { + GaussUtils.handleCriticalException(excep); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, excep); + } + } + + /** + * Gets the column type name. + * + * @param index the index + * @return the column type name + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public String getColumnTypeName(int index) throws DatabaseOperationException, DatabaseCriticalException { + try { + if (rs != null && rs.getMetaData() != null) { + return this.rs.getMetaData().getColumnTypeName(index); + } + return ""; + } catch (SQLException excep) { + // this main MOT error + return ""; + } + } + + /** + * Gets the precision. + * + * @param index the index + * @return the precision + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public int getPrecision(int index) throws DatabaseOperationException, DatabaseCriticalException { + try { + if (rs != null && rs.getMetaData() != null) { + return this.rs.getMetaData().getPrecision(index); + } + return 0; + } catch (SQLException excep) { + GaussUtils.handleCriticalException(excep); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, excep); + } + } + + /** + * Gets the scale. + * + * @param index the index + * @return the scale + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public int getScale(int index) throws DatabaseOperationException, DatabaseCriticalException { + try { + if (rs != null && rs.getMetaData() != null) { + return this.rs.getMetaData().getScale(index); + } + return 0; + } catch (SQLException excep) { + GaussUtils.handleCriticalException(excep); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, excep); + } + } + + /** + * Gets the max length. + * + * @param index the index + * @return the max length + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public int getMaxLength(int index) throws DatabaseOperationException, DatabaseCriticalException { + try { + if (rs != null && rs.getMetaData() != null) { + return this.rs.getMetaData().getColumnDisplaySize(index); + } + return 0; + } catch (SQLException excep) { + GaussUtils.handleCriticalException(excep); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, excep); + } + } + + /** + * Gets the table name. + * + * @param col the col + * @return the table name + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @Title: getTableName + * @Description: (use a sentence to describe the usage of method) + */ + public String getTableName(int col) throws DatabaseOperationException, DatabaseCriticalException { + String tableName = null; + try { + if (rsMetaData != null) { + tableName = rsMetaData.getTableName(col); + } + } catch (SQLException excep) { + GaussUtils.handleCriticalException(excep); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, excep); + } + + return tableName; + } + + /** + * Gets the schema name. + * + * @param col the col + * @return the schema name + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @Title: getTableName + * @Description: (use a sentence to describe the usage of method) + */ + public String getSchemaName(int col) throws DatabaseOperationException, DatabaseCriticalException { + String schemaName = ""; + try { + if (rsMetaData != null) { + schemaName = rsMetaData.getSchemaName(col); + } + } catch (SQLException excep) { + GaussUtils.handleCriticalException(excep); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, excep); + } + + return schemaName; + } + + public CallableStatement getCalStmt() { + return calStmt; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/Keywords.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/Keywords.java new file mode 100644 index 0000000000000000000000000000000000000000..3c7071f98fb061bbfea01e40914296e2958ad247 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/Keywords.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.keywordssyntax; + +/** + * + * Title: class + * + * Description: The Class Keywords. + * + * @since 3.0.0 + */ +public class Keywords implements KeywordsIf { + private String[] reservedkeywords = {"ADD", "ALL", "ANALYZE", "AND", "ANY", "ARRAY", "AS", "ASC", "BEGIN", + "BETWEEN", "BY", "CHECK", "COLLATION", "COLUMN", "COMPRESS", "CONCURRENTLY", "CONNECT", "CONSTRAINT", "CREATE", + "CROSS", "CURRENT", "CURRENT_DATE", "DEFAULT", "DELETE", "DESC", "DESCRIBE", "DISTINCT", "DO", "DROP", "ELSE", + "FALSE", "FOR", "FREEZE", "FROM", "FULL", "FUNCTION", "GRANT", "GROUP", "HAVING", "IDENTIFIED", "ILIKE", "IN", + "INCREMENT", "INDEX", "INNER", "INSERT", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "LEFT", "LEVEL", "LIKE", + "lOCALTIME", "LOCALTIMESTAMP", "LOCK", "MINUS", "MODIFY", "NATURAL", "NOT", "NOTNULL", "NOWAIT", "NULL", "OF", + "ON", "ONLY", "OR", "ORDER", "OUTER", "OVER", "OVERLAPS", "PRIMARY", "PRIVILEGES", "PROCEDURE", "RAW", "RENAME", + "RIGHT", "ROWS", "SELECT", "SESSION", "SET", "SIMILAR", "START", "SYSDATE", "TABLE", "THEN", "TO", "TRIGGER", + "TRUE", "UNION", "UNIQUE", "UNTIL", "UPDATE", "USER", "VERBOSE", "VIEW", "WHERE", "WITH"}; + + private String[] unreservedkeywords = {"AUTHORIZATION", "BIGINT", "BINARY", "BINARY_DOUBLE", "BINARY_INTEGER", + "BIT", "BOOLEAN", "CHARACTER", "COALESCE", "DEC", "DECODE", "EXTRACT", "FLOAT", "GREATEST", "INOUT", "INT", + "INTERVAL", "LEAST", "NATIONAL", "NCHAR", "NONE", "NULLIF", "NUMERIC", "NVARCHAR2", "NVL", "OUT", "OVERLAY", + "POSITION", "PRECISION", "REAL", "ROW", "SETOF", "SMALLDATETIME", "SMALLINT", "SUBSTRING", "TIME", "TIMESTAMP", + "TINYINT", "TREAT", "TRIM", "VARCHAR", "VARCHAR2", "XMLATTRIBUTES", "XMLCONCAT", "XMLELEMENT", "XMLEXISTS", + "XMLFOREST", "XMLPARSE", "XMLPI", "XMLROOT", "XMLSERIALIZE"}; + + private String[] types = {"INTEGER", "BIGINT", "REAL", "DECIMAL", "NUMBER", "CHAR", "VARCHAR", "VARCHAR2", + "DATETIME", "TIMESTAMP", "INTERVAL", "BOOLEAN"}; + + private String[] constants = {"AUTHORIZATION", "BINARY", "COLLATION", "CONCURRENTLY", "CROSS", "CURRENT_SCHEMA", + "FREEZE", "FULL", "ILIKE", "INNER", "ISNULL", "JOIN", "LEFT", "LIKE", "NATURAL", "NOTNULL", "OUTER", "OVER", + "OVERLAPS", "RIGHT", "SIMILAR", "VERBOSE"}; + + private String[] predicates = {"::", "..", ":=", "=>", "=", "<>", "<", ">", "<=", ">=", "||", "!", "!!", "%", "@", + "-", "<<", "&<", "&>", ">>", "<@", "@>", "~=", "&&", ">^", "<^", "@@", "*", "<->", "/", "+", "#=", "#<>", "#<", + "#>", "#<=", "#>=", "", "|/", "||/", "|", "<#>", "~", "!~", "#", "?#", "@-@", "?-", "?|", "^", "~~", "!~~", + "~*", "!~*", "|>>", "<<|", "?||", "?-|", "##", "&", "<<=", ">>=", "~~*", "!~~*", "~<~", "~<=~", "~>=~", "~>~", + "&<|", "|&>", "@@@", "-|-"}; + + @Override + public String[] getReservedKeywords() { + return reservedkeywords.clone(); + } + + @Override + public String[] getUnReservedKeywords() { + return unreservedkeywords.clone(); + } + + @Override + public String[] getUnRetentionKeywords() { + return new String[] {}; + } + + @Override + public String[] getTypes() { + return types.clone(); + } + + @Override + public String[] getConstants() { + return constants.clone(); + } + + @Override + public String[] getPredicates() { + return predicates.clone(); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof Keywords) { + return true; + } else { + return false; + } + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public String[] getDataTypes() { + return new String[] {}; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/KeywordsFactoryIf.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/KeywordsFactoryIf.java new file mode 100644 index 0000000000000000000000000000000000000000..7eb366efa73dadc721443383f25d4bde390f9e3b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/KeywordsFactoryIf.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.keywordssyntax; + +/** + * + * Title: interface + * + * Description: The Interface KeywordsFactoryIf. + * + * @since 3.0.0 + */ +public interface KeywordsFactoryIf { + + /** + * Gets the keywords. + * + * @return the keywords + */ + Keywords getKeywords(); + + /** + * Gets the OLAP keywords. + * + * @return the OLAP keywords + */ + Keywords getOLAPKeywords(); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/KeywordsFactoryImpl.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/KeywordsFactoryImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..087c361f85d47de9e463dbce6c42c1ecf3757fb0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/KeywordsFactoryImpl.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.keywordssyntax; + +/** + * + * Title: class + * + * Description: The Class KeywordsFactoryImpl. + * + * @since 3.0.0 + */ +public class KeywordsFactoryImpl implements KeywordsFactoryIf { + + @Override + public Keywords getKeywords() { + return new Keywords(); + } + + @Override + public Keywords getOLAPKeywords() { + return new OLAPKeywords(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/KeywordsFactoryProvider.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/KeywordsFactoryProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..98e68fa564fa026a44fd64ece20dbb67bc5563f0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/KeywordsFactoryProvider.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.keywordssyntax; + +/** + * + * Title: class + * + * Description: The Class KeywordsFactoryProvider. + * + * @since 3.0.0 + */ +public abstract class KeywordsFactoryProvider { + + /** + * Gets the keywords factory. + * + * @return the keywords factory + */ + public static KeywordsFactoryIf getKeywordsFactory() { + return new KeywordsFactoryImpl(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/KeywordsIf.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/KeywordsIf.java new file mode 100644 index 0000000000000000000000000000000000000000..e6651b103ff0fbcd5419d46e1a71d23ccf4dd54a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/KeywordsIf.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.keywordssyntax; + +/** + * + * Title: interface + * + * Description: The Interface KeywordsIf. + * + * @since 3.0.0 + */ +public interface KeywordsIf { + + /** + * Gets the reserved keywords. + * + * @return the reserved keywords + */ + String[] getReservedKeywords(); + + /** + * Gets the un reserved keywords. + * + * @return the un reserved keywords + */ + String[] getUnReservedKeywords(); + + /** + * Gets the un retention keywords. + * + * @return the un retention keywords + */ + String[] getUnRetentionKeywords(); + + /** + * Gets the types. + * + * @return the types + */ + String[] getTypes(); + + /** + * Gets the constants. + * + * @return the constants + */ + String[] getConstants(); + + /** + * Gets the predicates. + * + * @return the predicates + */ + String[] getPredicates(); + + /** + * Gets the data types. + * + * @return the data types + */ + String[] getDataTypes(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/KeywordsToTrieConverter.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/KeywordsToTrieConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..0c80a91dbec444c8cbc00299dac1235c15cc0b69 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/KeywordsToTrieConverter.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.keywordssyntax; + +/** + * + * Title: class + * + * Description: The Class KeywordsToTrieConverter. + * + * @since 3.0.0 + */ +public class KeywordsToTrieConverter { + + /** + * Convert keywordsto trie. + * + * @param syntax the syntax + * @param keywords the keywords + * @return the SQL syntax + */ + public static SQLSyntax convertKeywordstoTrie(SQLSyntax syntax, KeywordsIf keywords) { + syntax.addKeywordListInTrie(keywords); + return syntax; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/OLAPKeywords.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/OLAPKeywords.java new file mode 100644 index 0000000000000000000000000000000000000000..9367a8c2605e369a02405ec8bbbdb72777083f2b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/OLAPKeywords.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.keywordssyntax; + +/** + * + * Title: class + * + * Description: The Class OLAPKeywords. + * + * @since 3.0.0 + */ +public class OLAPKeywords extends Keywords { + + private String[] olapreservedkeywords = {"ALL", "ANALYSE", "ANALYZE", "AND", "ANY", "ARRAY", "AS", "ASC", + "ASYMMETRIC", "AUTHID", "AUTHORIZATION", "BINARY", "BOTH", "BUCKETS", "CASE", "CAST", "CHECK", "COLLATE", + "COLLATION", "COLUMN", "CONCURRENTLY", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_CATALOG", "CURRENT_DATE", + "CURRENT_ROLE", "CURRENT_SCHEMA", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER", "DEFAULT", "DEFERRABLE", + "DESC", "DISTINCT", "DO", "ELSE", "END", "EXCEPT", "FALSE", "FETCH", "FOR", "FOREIGN", "FREEZE", "FULL", + "FUNCTION", "GRANT", "GROUP", "HAVING", "ILIKE", "IN", "INITIALLY", "INNER", "INTERSECT", "INTO", "IS", + "ISNULL", "JOIN", "LEADING", "LEFT", "LESS", "LIKE", "LIMIT", "LOCALTIME", "LOCALTIMESTAMP", "MAXVALUE", + "MINUS", "MODIFY", "NATURAL", "NLSSORT", "NOT", "NOTNULL", "NULL", "OFFSET", "ON", "ONLY", "OR", "ORDER", + "OUTER", "OVER", "OVERLAPS", "PERFORMANCE", "PLACING", "PRIMARY", "PROCEDURE", "REFERENCES", "REJECT", "RETURN", + "RETURNING", "RIGHT", "SELECT", "SESSION_USER", "SIMILAR", "SOME", "SPLIT", "SYMMETRIC", "SYNONYM", "SYSDATE", + "TABLE", "THEN", "TO", "TRAILING", "TRUE", "UNION", "UNIQUE", "USER", "USING", "VARIADIC", "VERBOSE", "WHEN", + "WHERE", "WINDOW", "WITH", "FROM"}; + + private String[] olapunreservedkeywords = {"ABORT", "ABSOLUTE", "ACCESS", "ACCOUNT", "ACTION", "ADD", "ADMIN", + "AFTER", "AGGREGATE", "ALSO", "ALTER", "ALWAYS", "APP", "ASSERTION", "ASSIGNMENT", "AT", "ATTRIBUTE", + "AUTOEXTEND", "AUTOMAPPED", "BACKWARD", "BARRIER", "BEFORE", "BEGIN", "BETWEEN", "BIGINT", "BINARY_DOUBLE", + "BINARY_INTEGER", "BIT", "BLOB", "BOOLEAN", "BY", "CACHE", "CALL", "CALLED", "CASCADE", "CASCADED", "CATALOG", + "CHAIN", "CHAR", "CHARACTER", "CHARACTERISTICS", "CHECKPOINT", "CLASS", "CLEAN", "CLOB", "CLOSE", "CLUSTER", + "COALESCE", "COMMENT", "COMMENTS", "COMMIT", "COMMITTED", "COMPRESS", "CONFIGURATION", "CONNECTION", + "CONSTRAINTS", "CONTENT", "CONTINUE", "CONVERSION", "COORDINATOR", "COPY", "COST", "CSV", "CURRENT", "CURSOR", + "CYCLE", "DATA", "DATABASE", "DATAFILE", "DATE", "DAY", "DBCOMPATIBILITY", "DEALLOCATE", "DEC", "DECIMAL", + "DECLARE", "DECODE", "DEFAULTS", "DEFERRED", "DEFINER", "DELETE", "DELIMITER", "DELIMITERS", "DELTA", + "DETERMINISTIC", "DICTIONARY", "DIRECT", "DISABLE", "DISCARD", "DISTRIBUTE", "DISTRIBUTION", "DOCUMENT", + "DOMAIN", "DOUBLE", "DROP", "EACH", "ENABLE", "ENCODING", "ENCRYPTED", "ENFORCED", "ENUM", "EOL", "ESCAPE", + "ESCAPING", "EVERY", "EXCHANGE", "EXCLUDE", "EXCLUDING", "EXCLUSIVE", "EXECUTE", "EXISTS", "EXPLAIN", + "EXTENSION", "EXTERNAL", "EXTRACT", "FAMILY", "FILEHEADER", "FIRST", "FIXED", "FLOAT", "FOLLOWING", "FORCE", + "FORMATTER", "FORWARD", "FUNCTIONS", "GLOBAL", "GRANTED", "GREATEST", "HANDLER", "HEADER", "HOLD", "HOUR", + "IDENTIFIED", "IDENTITY", "IF", "IMMEDIATE", "IMMUTABLE", "IMPLICIT", "INCLUDING", "INCREMENT", "INDEX", + "INDEXES", "INHERIT", "INHERITS", "INITIAL", "INITRANS", "INLINE", "INOUT", "INPUT", "INSENSITIVE", "INSERT", + "INSTEAD", "INT", "INTEGER", "INTERVAL", "INVOKER", "ISOLATION", "KEY", "LABEL", "LANGUAGE", "LARGE", "LAST", + "LC_COLLATE", "LC_CTYPE", "LEAKPROOF", "LEAST", "LEVEL", "LISTEN", "LOAD", "LOCAL", "LOCATION", "LOCK", "LOG", + "LOGGING", "LOGIN", "LOOP", "MAPPING", "MATCH", "MATCHED", "MAXEXTENTS", "MAXSIZE", "MAXTRANS", "MERGE", + "MINEXTENTS", "MINUTE", "MINVALUE", "MODE", "MONTH", "MOVE", "MOVEMENT", "NAME", "NAMES", "NATIONAL", "NCHAR", + "NEXT", "NO", "NOCOMPRESS", "NOCYCLE", "NODE", "NOLOGGING", "NOLOGIN", "NOMAXVALUE", "NOMINVALUE", "NONE", + "NOTHING", "NOTIFY", "NOWAIT", "NULLIF", "NULLS", "NUMBER", "NUMERIC", "NUMSTR", "NVARCHAR2", "NVL", "OBJECT", + "OF", "OFF", "OIDS", "OPERATOR", "OPTIMIZATION", "OPTION", "OPTIONS", "OUT", "OVERLAY", "OWNED", "OWNER", + "PARSER", "PARTIAL", "PARTITION", "PARTITIONS", "PASSING", "PASSWORD", "PCTFREE", "PER", "PERCENT", "PLANS", + "POOL", "POSITION", "PRECEDING", "PRECISION", "PREFERRED", "PREFIX", "PREPARE", "PREPARED", "PRESERVE", "PRIOR", + "PRIVILEGE", "PRIVILEGES", "PROCEDURAL", "PROFILE", "QUERY", "QUOTE", "RANGE", "RAW", "READ", "REAL", + "REASSIGN", "REBUILD", "RECHECK", "RECURSIVE", "REF", "REINDEX", "RELATIVE", "RELEASE", "RELOPTIONS", "REMOTE", + "RENAME", "REPEATABLE", "REPLACE", "REPLICA", "RESET", "RESIZE", "RESOURCE", "RESTART", "RESTRICT", "RETURNS", + "REUSE", "REVOKE", "ROLE", "ROLLBACK", "ROW", "ROWS", "RULE", "SAVEPOINT", "SCHEMA", "SCROLL", "SEARCH", + "SECOND", "SECURITY", "SEQUENCE", "SEQUENCES", "SERIALIZABLE", "SERVER", "SESSION", "SET", "SETOF", "SHARE", + "SHOW", "SIMPLE", "SIZE", "SMALLDATETIME", "SMALLINT", "SNAPSHOT", "STABLE", "STANDALONE", "START", "STATEMENT", + "STATISTICS", "STDIN", "STDOUT", "STORAGE", "STORE", "STRICT", "STRIP", "SUBSTRING", "SUPERUSER", + "SYS_REFCURSOR", "SYSID", "SYSTEM", "TABLES", "TABLESPACE", "TEMP", "TEMPLATE", "TEMPORARY", "TEXT", "THAN", + "TIME", "TIMESTAMP", "TINYINT", "TRANSACTION", "TREAT", "TRIGGER", "TRIM", "TRUNCATE", "TRUSTED", "TYPE", + "TYPES", "UNBOUNDED", "UNCOMMITTED", "UNENCRYPTED", "UNKNOWN", "UNLIMITED", "UNLISTEN", "UNLOCK", "UNLOGGED", + "UNTIL", "UNUSABLE", "UPDATE", "VACUUM", "VALID", "VALIDATE", "VALIDATION", "VALIDATOR", "VALUE", "VALUES", + "VARCHAR", "VARCHAR2", "VARYING", "VERSION", "VIEW", "VOLATILE", "WHITESPACE", "WITHOUT", "WORK", "WORKLOAD", + "WRAPPER", "WRITE", "XML", "XMLATTRIBUTES", "XMLCONCAT", "XMLELEMENT", "XMLEXISTS", "XMLFOREST", "XMLPARSE", + "XMLPI", "XMLROOT", "XMLSERIALIZE", "YEAR", "YES", "ZONE"}; + + private String[] olaptypes = {"TINYINT", "SMALLINT", "INTEGER", "BIGINT", "NUMERIC", "DECIMAL", "NUMBER", + "SMALLSERIAL", "SERIAL", "BIGSERIAL", "REAL", "FLOAT4", "DOUBLEPRECISION", "FLOAT8", "FLOAT", "DEC", "INTEGER", + "money", "BOOLEAN", " VARCHAR", "CHARACTER", "VARYING", "CHAR", "CHARACTER", "inet", "macaddr", "bit", + "tsvector", "tsquery", "UUID", "JSON", "NCHAR", "VARCHAR2", "NVARCHAR2", "CLOB", "TEXT", "BLOB", "RAW", "BYTEA", + "DATE", "TIME", "WITHOUT", "ZONE", "WITH", "TIMESTAMP", "SMALLDATETIME", "INTERVAL", "DAY", "SECOND", + "INTERVAL", "reltime", "point", "lseg", "box", "path", "polygon", "circle", "cidr"}; + + @Override + public String[] getReservedKeywords() { + return olapreservedkeywords.clone(); + } + + @Override + public String[] getUnReservedKeywords() { + return olapunreservedkeywords.clone(); + } + + @Override + public String[] getTypes() { + return olaptypes.clone(); + } + + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } + + @Override + public int hashCode() { + return super.hashCode(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/SQLSyntax.java b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/SQLSyntax.java new file mode 100644 index 0000000000000000000000000000000000000000..e257e5faf340ccc269b2990ac39498dd500ff802 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.adapter.gauss/src/org/opengauss/mppdbide/adapter/keywordssyntax/SQLSyntax.java @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.adapter.keywordssyntax; + +import org.apache.commons.collections4.trie.PatriciaTrie; + +/** + * + * Title: class + * + * Description: The Class SQLSyntax. + * + * @since 3.0.0 + */ +public class SQLSyntax { + + private PatriciaTrie reservedkrywords; + private PatriciaTrie unreservedkrywords; + private PatriciaTrie types; + private PatriciaTrie constants; + private PatriciaTrie predicates; + private PatriciaTrie datatypes; + + /** + * Instantiates a new SQL syntax. + */ + public SQLSyntax() { + reservedkrywords = new PatriciaTrie(); + unreservedkrywords = new PatriciaTrie(); + types = new PatriciaTrie(); + constants = new PatriciaTrie(); + predicates = new PatriciaTrie(); + datatypes = new PatriciaTrie(); + } + + /** + * Gets the reservedkrywords. + * + * @return the reservedkrywords + */ + public PatriciaTrie getReservedkrywords() { + return reservedkrywords; + } + + /** + * Gets the unreservedkrywords. + * + * @return the unreservedkrywords + */ + public PatriciaTrie getUnreservedkrywords() { + return this.unreservedkrywords; + } + + /** + * Gets the types. + * + * @return the types + */ + public PatriciaTrie getTypes() { + return this.types; + } + + /** + * Gets the constants. + * + * @return the constants + */ + public PatriciaTrie getConstants() { + return this.constants; + } + + /** + * Gets the predicates. + * + * @return the predicates + */ + public PatriciaTrie getPredicates() { + return this.predicates; + } + + /** + * Clear. + */ + public void clear() { + if (reservedkrywords != null) { + reservedkrywords.clear(); + } + if (unreservedkrywords != null) { + unreservedkrywords.clear(); + } + if (types != null) { + types.clear(); + } + if (constants != null) { + constants.clear(); + } + if (predicates != null) { + predicates.clear(); + } + } + + private PatriciaTrie getDatatypes() { + return this.datatypes; + } + + /** + * addKeywordListInTrie + * + * @param keywords parameter + */ + public void addKeywordListInTrie(KeywordsIf keywords) { + convert(keywords.getReservedKeywords(), getReservedkrywords()); + convert(keywords.getUnReservedKeywords(), getUnreservedkrywords()); + convert(keywords.getUnRetentionKeywords(), getUnreservedkrywords()); + convert(keywords.getConstants(), getConstants()); + convert(keywords.getTypes(), getTypes()); + convert(keywords.getPredicates(), getPredicates()); + convert(keywords.getDataTypes(), getDatatypes()); + } + + private static void convert(String[] keywords, PatriciaTrie keywordTrie) { + for (int index = 0; index < keywords.length; index++) { + keywordTrie.put(keywords[index].trim(), "1"); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/.classpath b/code/datastudio/src/org.opengauss.mppdbide.bl/.classpath new file mode 100644 index 0000000000000000000000000000000000000000..682e4d0ba30be0b8c0d1f79fe9a0864fc9123e86 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/.classpath @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/.gitignore b/code/datastudio/src/org.opengauss.mppdbide.bl/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ddc25c7fcd00a3a38f67eabde7efb88c26a8c3a8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/.gitignore @@ -0,0 +1,3 @@ +/bin/ +/.settings/ +/target/ diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/.project b/code/datastudio/src/org.opengauss.mppdbide.bl/.project new file mode 100644 index 0000000000000000000000000000000000000000..5904de385cbd7043b2231831aaf3458ae270d03c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/.project @@ -0,0 +1,34 @@ + + + org.opengauss.mppdbide.bl + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/META-INF/MANIFEST.MF b/code/datastudio/src/org.opengauss.mppdbide.bl/META-INF/MANIFEST.MF new file mode 100644 index 0000000000000000000000000000000000000000..e9a6cefd62f0fc039d5f81b93454ed4c0e47e7b4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/META-INF/MANIFEST.MF @@ -0,0 +1,47 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: MPPDBIDE_BL +Bundle-SymbolicName: org.opengauss.mppdbide.bl +Bundle-Version: 1.0.0.qualifier +Bundle-Vendor: Huawei Technologies +Bundle-RequiredExecutionEnvironment: JavaSE-11 +Export-Package: org.opengauss.mppdbide.bl, + org.opengauss.mppdbide.bl.adapter.gauss, + org.opengauss.mppdbide.bl.autosave, + org.opengauss.mppdbide.bl.connection, + org.opengauss.mppdbide.bl.contentassist, + org.opengauss.mppdbide.bl.erd.model, + org.opengauss.mppdbide.bl.errorlocator, + org.opengauss.mppdbide.bl.executor;uses:="org.opengauss.mppdbide.bl.serverdatacache,org.opengauss.mppdbide.bl", + org.opengauss.mppdbide.bl.export, + org.opengauss.mppdbide.bl.importexportdata, + org.opengauss.mppdbide.bl.keyword, + org.opengauss.mppdbide.bl.preferences, + org.opengauss.mppdbide.bl.queryparser, + org.opengauss.mppdbide.bl.search, + org.opengauss.mppdbide.bl.serverdatacache;uses:="org.opengauss.mppdbide.bl.executor", + org.opengauss.mppdbide.bl.serverdatacache.connectioninfo, + org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif, + org.opengauss.mppdbide.bl.serverdatacache.groups, + org.opengauss.mppdbide.bl.serverdatacache.helper, + org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption, + org.opengauss.mppdbide.bl.sqlhistory, + org.opengauss.mppdbide.bl.sqlhistory.manager, + org.opengauss.mppdbide.bl.util +Require-Bundle: org.eclipse.core.runtime;bundle-version="3.15.300", + org.eclipse.e4.core.services;bundle-version="2.1.400", + org.eclipse.osgi.services;bundle-version="3.8.0", + Common-collection;bundle-version="1.0.0", + org.opengauss.mppdbide.adapter.gauss;bundle-version="1.0.0", + org.opengauss.mppdbide.util;bundle-version="1.0.0", + org.opengauss.mppdbide.bl, + org.eclipse.core.jobs, + org.eclipse.equinox.registry +Import-Package: org.opengauss.mppdbide.bl.serverdatacache, + org.apache.commons.lang;version="2.6.0", + org.postgresql.jdbc2 +Bundle-ClassPath: ., + gson-2.8.6.jar, + commons-lang3-3.12.0.jar, + commons-io-2.11.0.jar + diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/build.properties b/code/datastudio/src/org.opengauss.mppdbide.bl/build.properties new file mode 100644 index 0000000000000000000000000000000000000000..2658a25dd6eba2b94ff5a9e85b51d1cb43af01a2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/build.properties @@ -0,0 +1,7 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + gson-2.8.6.jar,\ + commons-lang3-3.12.0.jar,\ + commons-io-2.11.0.jar diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/compile_plsqlide.bl.xml b/code/datastudio/src/org.opengauss.mppdbide.bl/compile_plsqlide.bl.xml new file mode 100644 index 0000000000000000000000000000000000000000..4f019fdd73f78ffaf56b686baa190857056dfa65 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/compile_plsqlide.bl.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/pom.xml b/code/datastudio/src/org.opengauss.mppdbide.bl/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..4aeb4dc6fe3d752d2885b12e6abc168585136110 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/pom.xml @@ -0,0 +1,15 @@ + + + + 4.0.0 + + org.opengauss.plide.build + GAUSS_MPP_DB_IDE + 1.0.0-SNAPSHOT + + org.opengauss.mppdbide.bl + eclipse-plugin + diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/IDBConnectionWrapper.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/IDBConnectionWrapper.java new file mode 100644 index 0000000000000000000000000000000000000000..f107125ae045934f103830e5b0cf37bf0d70ba85 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/IDBConnectionWrapper.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl; + +import org.opengauss.mppdbide.bl.serverdatacache.IDebugObject; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: interface + * + * Description: The Interface IDBConnectionWrapper. + * + */ + +public interface IDBConnectionWrapper { + + /** + * Connect. + * + * @param serverInfo the server info + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + void connect(IServerConnectionInfo serverInfo) throws DatabaseOperationException, DatabaseCriticalException; + + /** + * Db disconnect. + */ + void dbDisconnect(); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/IServerObjectBatchOperations.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/IServerObjectBatchOperations.java new file mode 100644 index 0000000000000000000000000000000000000000..13502019705bdf8061635949556580b0a413abbb --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/IServerObjectBatchOperations.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl; + +import org.opengauss.mppdbide.bl.export.EXPORTTYPE; + +/** + * + * Title: interface + * + * Description: The Interface IServerObjectBatchOperations. + * + */ + +public interface IServerObjectBatchOperations { + + /** + * Gets the drop query. + * + * @param isCascade the is cascade + * @return the drop query + */ + public String getDropQuery(boolean isCascade); + + /** + * Gets the object full name. + * + * @return the object full name + */ + public String getObjectFullName(); + + /** + * Gets the object type name. + * + * @return the object type name + */ + public String getObjectTypeName(); + + /** + * Checks if is drop allowed. + * + * @return true, if is drop allowed + */ + public boolean isDropAllowed(); + + /** + * Checks if is export allowed. + * + * @param exportType the export type + * @return true, if is export allowed + */ + public boolean isExportAllowed(EXPORTTYPE exportType); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/adapter/gauss/GaussConnection.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/adapter/gauss/GaussConnection.java new file mode 100644 index 0000000000000000000000000000000000000000..b778d1678b05b30fb157127da991980518caef69 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/adapter/gauss/GaussConnection.java @@ -0,0 +1,281 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.adapter.gauss; + +import java.nio.charset.Charset; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Properties; + +import org.apache.commons.lang.StringUtils; + +import org.opengauss.mppdbide.adapter.IConnectionDriver; +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.bl.IDBConnectionWrapper; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.serverdatacache.IDebugObject; +import org.opengauss.mppdbide.bl.serverdatacache.ObjectParameter; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; +import org.opengauss.mppdbide.bl.util.BLUtils; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.MessageQueue; +import org.opengauss.mppdbide.utils.security.SecureUtil; + +/** + * + * Title: class + * + * Description: The Class GaussConnection. + * + * @since 3.0.0 + */ +public class GaussConnection implements IDBConnectionWrapper { + + private static final int MAX_WAIT_TIME = 100000; + + private DBConnection con; + + private MessageQueue messageQueue; + + /** + * Instantiates a new gauss connection. + * + * @param iConnectionDriver the i connection driver + */ + public GaussConnection(IConnectionDriver iConnectionDriver) { + con = new DBConnection(iConnectionDriver); + } + + + /** + * closeResultSet. + * + * @param rs the rs + */ + + private void closeResultSet(ResultSet rs) { + try { + if (null != rs) { + rs.close(); + } + } catch (SQLException exp) { + MPPDBIDELoggerUtility.error("ADAPTER: statement close returned exception.", exp); + } + } + + /** + * Execute the query and fetch the result. + * + * @param stmt the stmt + * @return the result set + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + private ResultSet executeAndFetch(PreparedStatement stmt) + throws DatabaseOperationException, DatabaseCriticalException { + ResultSet rs = null; + + try { + rs = stmt.executeQuery(); + } catch (SQLException exp) { + GaussUtils.handleCriticalException(exp); + + con.closeStatement(stmt); + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_EXECUTE_FUN_PROC_TRIG_QUERY_FAILED), + exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_EXECUTE_FUN_PROC_TRIG_QUERY_FAILED, exp); + } catch (IndexOutOfBoundsException iobe) { + con.closeStatement(stmt); + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_EXECUTE_FUN_PROC_TRIG_QUERY_FAILED), + iobe); + throw new DatabaseCriticalException(IMessagesConstants.ERR_GUI_EXECUTE_FUN_PROC_TRIG_QUERY_FAILED, iobe); + } + + return rs; + } + + /** + * Gets the version. + * + * @return the version + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + + public String getVersion() throws DatabaseOperationException, DatabaseCriticalException { + ResultSet rs = null; + PreparedStatement stmt = null; + String serverVersion = null; + stmt = con.getPrepareStmt("select * from version();"); + + rs = executeAndFetch(stmt); + + try { + boolean bRetVal = rs.next(); + if (!bRetVal) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID)); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } + + serverVersion = rs.getString("VERSION"); + } catch (SQLException exp) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exp); + } finally { + closeResultSet(rs); + con.closeStatement(stmt); + } + if (serverVersion == null) { + return ""; + } + return serverVersion; + } + + /** + * Gets the server IP. + * + * @return the server IP + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public String getServerIP1() throws DatabaseOperationException, DatabaseCriticalException { + ResultSet rs = null; + String query = "select inet_server_addr();"; + String serverIP = ""; + try { + rs = con.execSelectAndReturnRs(query); + rs.next(); + serverIP = rs.getString(1); + } catch (SQLException exp) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.SERVERIP_TOOLTIP_FAIL), exp); + throw new DatabaseOperationException(IMessagesConstants.SERVERIP_TOOLTIP_FAIL, exp); + } finally { + if (rs != null) { + con.closeResultSet(rs); + } + } + return serverIP; + } + + /** + * disconnect database. + */ + public void dbDisconnect() { + con.disconnect(); + } + + /** + * Connect. + * + * @param serverInformation the server information + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void connect(IServerConnectionInfo serverInformation) + throws DatabaseCriticalException, DatabaseOperationException { + String url = null; + Properties properties = new Properties(); + + properties.setProperty("user", serverInformation.getDsUsername()); + properties.setProperty("password", new String(serverInformation.getPrd())); + properties.setProperty("allowEncodingChanges", "true"); + String dsEncoding = BLPreferenceManager.getInstance().getBLPreference().getDSEncoding(); + if (dsEncoding.isEmpty()) { + dsEncoding = Charset.defaultCharset().toString(); + } + properties.setProperty("characterEncoding", dsEncoding); + properties.setProperty("useUnicode", "true"); + properties.setProperty("ApplicationName", "Data Studio"); + if (con.getDriver() != null) { + properties.putAll(con.getDriver().getDriverSpecificProperties()); + } + + String[] args = BLUtils.getInstance().getPlatformArgs(); + boolean hasLoginTimeout = false; + String loginTimeout = null; + + int len = args.length; + for (int index = 0; index < len; index++) { + if (args[index] != null && args[index].startsWith("-loginTimeout")) { + loginTimeout = args[index].split("=")[1].trim(); + hasLoginTimeout = true; + break; + } + } + + properties.setProperty("loginTimeout", hasLoginTimeout ? loginTimeout : "180"); + + if (serverInformation.isSSLEnabled()) { + properties.setProperty("sslmode", serverInformation.getSSLMode()); + properties.setProperty("sslcert", serverInformation.getClientSSLCertificate()); + properties.setProperty("sslkey", serverInformation.getClientSSLKey()); + properties.setProperty("sslrootcert", serverInformation.getRootCertificate()); + properties.setProperty("sslpassword", new String(serverInformation.getSSLPrd())); + properties.setProperty("ssl", "true"); + } + + url = getUrl(serverInformation); + try { + doConnect(con, properties, url); + } finally { + SecureUtil.cleanKeyString(properties.getProperty("password")); + properties.setProperty("password", ""); + properties.remove("password"); + SecureUtil.cleanKeyString(properties.getProperty("sslpassword")); + properties.setProperty("sslpassword", ""); + properties.remove("sslpassword"); + serverInformation.clearPasrd(); + } + + } + + private String getUrl(IServerConnectionInfo serverInformation) { + if (!StringUtils.isEmpty(serverInformation.getServerIp())) { + return "jdbc:postgresql://" + serverInformation.getServerIp() + ':' + serverInformation.getServerPort() + + '/' + serverInformation.getDatabaseName(); + } else { + return ""; + } + } + + /** + * Do connect. + * + * @param conn the conn + * @param props the props + * @param url the url + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + private void doConnect(DBConnection conn, Properties props, String url) + throws DatabaseOperationException, DatabaseCriticalException { + conn.connectViaDriver(props, url); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/autosave/AutoSaveDbgObjInfo.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/autosave/AutoSaveDbgObjInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..03897a590cc2b4a9eff7e0aa3adf20d31873d0e1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/autosave/AutoSaveDbgObjInfo.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.autosave; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; + +/** + * + * Title: class + * + * Description: The Class AutoSaveDbgObjInfo. + * + */ + +public class AutoSaveDbgObjInfo { + + @SerializedName("oid") + private long oid; + + @SerializedName("name") + private String name; + + @SerializedName("schema") + private String schemaName; + + @SerializedName("objtype") + private OBJECTTYPE objType; + + @SerializedName("isdirty") + private boolean isDirty; + + /** + * Gets the oid. + * + * @return the oid + */ + public long getOid() { + return oid; + } + + /** + * Gets the obj type. + * + * @return the obj type + */ + public OBJECTTYPE getObjType() { + return objType; + } + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Sets the oid. + * + * @param oid the new oid + */ + public void setOid(long oid) { + this.oid = oid; + } + + /** + * Sets the name. + * + * @param name the new name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Gets the schema name. + * + * @return the schema name + */ + public String getSchemaName() { + return schemaName; + } + + /** + * Sets the schema name. + * + * @param schemaName the new schema name + */ + public void setSchemaName(String schemaName) { + this.schemaName = schemaName; + } + + /** + * Sets the obj type. + * + * @param objecttype the new obj type + */ + public void setObjType(OBJECTTYPE objecttype) { + this.objType = objecttype; + } + + /** + * Checks if is dirty. + * + * @return true, if is dirty + */ + public boolean isDirty() { + return isDirty; + } + + /** + * Sets the dirty. + * + * @param isDirty1 the new dirty + */ + public void setDirty(boolean isDirty1) { + this.isDirty = isDirty1; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/autosave/AutoSaveInfo.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/autosave/AutoSaveInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..65c3cc4c476dd44d7f1fc4e598c42c2d9e13caaa --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/autosave/AutoSaveInfo.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.autosave; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import com.google.gson.annotations.SerializedName; + +/** + * + * Title: class + * + * Description: The Class AutoSaveInfo. + * + */ + +public class AutoSaveInfo { + + @SerializedName("version") + private String version; + + @SerializedName("timestamp") + private String timestamp; + + @SerializedName("activeterminal") + private String activeTerminalName; + + @SerializedName("tabinfo") + private List autosaveMD = new ArrayList<>(); + + private static final String VERSIONNO = "1.0.0"; + + /** + * Instantiates a new auto save info. + */ + public AutoSaveInfo() { + this.version = VERSIONNO; + } + + /** + * Gets the timestamp. + * + * @return the timestamp + */ + public String getTimestamp() { + return timestamp; + } + + /** + * Sets the timestamp. + * + * @param timestamp the new timestamp + */ + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } + + /** + * Gets the autosave MD. + * + * @return the autosave MD + */ + public List getAutosaveMD() { + // sending the cloned copy of metadata + return new ArrayList<>(autosaveMD); + } + + /** + * Sets the autosave MD. + * + * @param autosaveMD the new autosave MD + */ + public void setAutosaveMD(List autosaveMD) { + this.autosaveMD = autosaveMD; + } + + /** + * Invalidate. + */ + public void invalidate() { + autosaveMD.clear(); + setVersion(""); + timestamp = ""; + activeTerminalName = ""; + } + + /** + * Adds the auto save metadata. + * + * @param metaData the meta data + */ + public void addAutoSaveMetadata(AutoSaveMetadata metaData) { + autosaveMD.add(metaData); + } + + /** + * Removes the auto save metadata. + * + * @param metaData the meta data + * @return true, if successful + */ + public boolean removeAutoSaveMetadata(AutoSaveMetadata metaData) { + return autosaveMD.remove(metaData); + } + + /** + * Gets the active terminal name. + * + * @return the active terminal name + */ + public String getActiveTerminalName() { + return activeTerminalName; + } + + /** + * Sets the active terminal name. + * + * @param activeTerminalName the new active terminal name + */ + public void setActiveTerminalName(String activeTerminalName) { + this.activeTerminalName = activeTerminalName; + } + + /** + * Gets the meta data. + * + * @param id the id + * @return the meta data + */ + public AutoSaveMetadata getMetaData(String id) { + for (AutoSaveMetadata meta : autosaveMD) { + if (id.equals(meta.getTabID())) { + return meta; + } + } + return null; + + } + + /** + * Gets the version. + * + * @return the version + */ + public String getVersion() { + return version; + } + + /** + * Sets the version. + * + * @param version the new version + */ + public void setVersion(String version) { + this.version = version; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/autosave/AutoSaveMetadata.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/autosave/AutoSaveMetadata.java new file mode 100644 index 0000000000000000000000000000000000000000..5dc52476026dfe20d4c98be77af4e3eccf924090 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/autosave/AutoSaveMetadata.java @@ -0,0 +1,352 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.autosave; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class AutoSaveMetadata. + * + */ + +public class AutoSaveMetadata { + + @SerializedName("database") + private String databaseName; + + @SerializedName("connection") + private String connectionName; + + @SerializedName("terminaltype") + private String type; + + @SerializedName("encrypted") + private boolean isEncrypted; + + @SerializedName("encoding") + private String encoding; + + @SerializedName("filename") + private String fileName; + + @SerializedName("id") + private String tabID; + + @SerializedName("label") + private String tabLabel; + + @SerializedName("tooltip") + private String tabToolTip; + + @SerializedName("timestamp") + private String timestamp; + + @SerializedName("debugobject") + private AutoSaveDbgObjInfo dbgObjInfo; + + private int versionNumber; + + @SerializedName("Verifier") + private byte[] shaval; + + /** + * Gets the database name. + * + * @return the database name + */ + public String getDatabaseName() { + return databaseName; + } + + /** + * Sets the database name. + * + * @param databaseName the new database name + */ + public void setDatabaseName(String databaseName) { + this.databaseName = databaseName; + } + + /** + * Gets the connection name. + * + * @return the connection name + */ + public String getConnectionName() { + return connectionName; + } + + /** + * Sets the connection name. + * + * @param connectionName the new connection name + */ + public void setConnectionName(String connectionName) { + this.connectionName = connectionName; + } + + /** + * Gets the type. + * + * @return the type + */ + public String getType() { + return type; + } + + /** + * Sets the type. + * + * @param type the new type + */ + public void setType(String type) { + this.type = type; + } + + /** + * Checks if is encrypted. + * + * @return true, if is encrypted + */ + public boolean isEncrypted() { + return isEncrypted; + } + + /** + * Sets the encrypted. + * + * @param isEncrypted1 the new encrypted + */ + public void setEncrypted(boolean isEncrypted1) { + this.isEncrypted = isEncrypted1; + } + + /** + * Gets the file name. + * + * @return the file name + */ + public String getAutoSaveFileName() { + return fileName; + } + + /** + * Sets the file name. + * + * @param fileName the new file name + */ + public void setAutoSaveFileName(String fileName) { + this.fileName = fileName; + } + + /** + * Gets the tab ID. + * + * @return the tab ID + */ + public String getTabID() { + return tabID; + } + + /** + * Sets the tab ID. + * + * @param tabID the new tab ID + */ + public void setTabID(String tabID) { + this.tabID = tabID; + } + + /** + * Gets the dbg obj info. + * + * @return the dbg obj info + */ + public AutoSaveDbgObjInfo getDbgObjInfo() { + return dbgObjInfo; + } + + /** + * Sets the dbg obj info. + * + * @param dbgObjInfo the new dbg obj info + */ + public void setDbgObjInfo(AutoSaveDbgObjInfo dbgObjInfo) { + this.dbgObjInfo = dbgObjInfo; + } + + /** + * Gets the tab tool tip. + * + * @return the tab tool tip + */ + public String getTabToolTip() { + return tabToolTip; + } + + /** + * Sets the tab tool tip. + * + * @param tabToolTip the new tab tool tip + */ + public void setTabToolTip(String tabToolTip) { + this.tabToolTip = tabToolTip; + } + + /** + * Gets the tab label. + * + * @return the tab label + */ + public String getTabLabel() { + return tabLabel; + } + + /** + * Sets the tab label. + * + * @param tabLabel the new tab label + */ + public void setTabLabel(String tabLabel) { + this.tabLabel = tabLabel; + } + + /** + * Gets the version number. + * + * @return the version number + */ + public int getVersionNumber() { + return versionNumber; + } + + /** + * Sets the version number. + * + * @param versionNumber the new version number + */ + public void setVersionNumber(int versionNumber) { + this.versionNumber = versionNumber; + } + + @Override + public boolean equals(Object obj) { + if (obj != null && obj instanceof AutoSaveMetadata) { + AutoSaveMetadata meta = (AutoSaveMetadata) obj; + return this.getTabID().equals(meta.getTabID()); + } + return false; + } + + @Override + public int hashCode() { + int hashCode = 0; + char[] charArray = tabID.toCharArray(); + for (int i = 0; i < charArray.length; i++) { + hashCode += charArray[i]; + } + return hashCode; + } + + + /** + * Gets the timestamp. + * + * @return the timestamp + */ + public String getTimestamp() { + return timestamp; + } + + /** + * Sets the timestamp. + * + * @param timestamp the new timestamp + */ + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } + + /** + * Gets the encoding. + * + * @return the encoding + */ + public String getEncoding() { + return encoding; + } + + /** + * Sets the encoding. + * + * @param encoding the new encoding + */ + public void setEncoding(String encoding) { + this.encoding = encoding; + } + + private byte[] getShaval() { + return shaval; + } + + private byte[] calcShaVal() { + String data = getConnectionName() + getDatabaseName() + getAutoSaveFileName() + getTabID() + getTabLabel() + + getTabID(); + try { + final MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); + messageDigest.update(data.getBytes(StandardCharsets.UTF_8)); + return messageDigest.digest(); + } catch (NoSuchAlgorithmException exception) { + MPPDBIDELoggerUtility.error("Encoding file failed", exception); + } + + return new byte[0]; + } + + /** + * Update shaval. + */ + public void updateShaval() { + this.shaval = calcShaVal(); + } + + /** + * Calc and compare. + * + * @return true, if successful + */ + public boolean calcAndCompare() { + if (getShaval() == null) { + return false; + } + + byte[] ary = calcShaVal(); + if (ary == null) { + return false; + } + + return Arrays.equals(ary, getShaval()); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/autosave/AutosaveFileUtility.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/autosave/AutosaveFileUtility.java new file mode 100644 index 0000000000000000000000000000000000000000..3bc21d12a74ce16357e65912f3b555bcbe676107 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/autosave/AutosaveFileUtility.java @@ -0,0 +1,464 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.autosave; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.FilenameFilter; +import org.apache.commons.io.FileUtils; +import java.io.IOException; +import java.io.StringReader; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.nio.file.CopyOption; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; + +import com.google.gson.Gson; +import com.google.gson.JsonIOException; +import com.google.gson.JsonSyntaxException; +import com.google.gson.reflect.TypeToken; +import com.google.gson.stream.JsonReader; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.FileOperationException; +import org.opengauss.mppdbide.utils.files.DSFolderDeleteUtility; +import org.opengauss.mppdbide.utils.files.FilePermissionFactory; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class AutosaveFileUtility. + * + */ + +public class AutosaveFileUtility { + + private String osCurrentUserFolderPath; + private static final String AUTOSAVE_FOLDER = "Autosave"; + + /** + * Instantiates a new autosave file utility. + */ + public AutosaveFileUtility() { + } + + /** + * Creates the folder structure. + * + * @throws FileOperationException the file operation exception + */ + public void createFolderStructure() + throws FileOperationException, DatabaseOperationException { + FilePermissionFactory.getFilePermissionInstance().createFileWithPermission(getAutosaveFolderPath().toString(), + true, null, true); + } + + /** + * Delete folder structure. + * + * @throws FileOperationException the file operation exception + */ + public void deleteFolderStructure() throws FileOperationException { + try { + Files.walkFileTree(getAutosaveFolderPath(), new DSFolderDeleteUtility()); + } catch (IOException exp) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.PRESERVESQL_FOLDERCREATEDELETEEXCEPTION), exp); + throw new FileOperationException(IMessagesConstants.PRESERVESQL_FOLDERCREATEDELETEEXCEPTION); + } + } + + /** + * Gets the autosave folder path. + * + * @return the autosave folder path + */ + public Path getAutosaveFolderPath() { + Path parentPath = Paths.get(osCurrentUserFolderPath, AUTOSAVE_FOLDER); + return parentPath.toAbsolutePath().normalize(); + } + + /** + * Gets the autosave info. + * + * @param file the file + * @param maxTabCnt the max tab cnt + * @return the autosave info + * @throws FileOperationException the file operation exception + */ + public AutoSaveInfo getAutosaveInfo(Path file, int maxTabCnt) throws FileOperationException { + AutoSaveInfo autosaveInfo = null; + try { + if (!Files.exists(file)) { + return null; + } + + // validate files and throws exception if validation failes + validateFile(file); + + byte[] bytes = Files.readAllBytes(file); + // validate byteslength and throws exception if length is 0 + validateBytesLength(bytes.length); + + Gson gson = new Gson(); + String json = new String(bytes, StandardCharsets.UTF_8); + + JsonReader reader = null; + autosaveInfo = new AutoSaveInfo(); + try { + reader = new JsonReader(new StringReader(json)); + reader.beginObject(); + + readJsonFile(maxTabCnt, autosaveInfo, gson, reader); + reader.endObject(); + } finally { + if (reader != null) { + try { + reader.close(); + reader = null; + } catch (IOException exception) { + /* No way to recover from close failure */ + MPPDBIDELoggerUtility.error("Error while closing json reader", exception); + } + } + } + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("getting Auto save info of file failed", exception); + throw new FileOperationException(IMessagesConstants.PRESERVESQL_FILEREADEXCEPTION); + } + + return autosaveInfo; + } + + private void readJsonFile(int maxTabCnt, AutoSaveInfo autosaveInfo, Gson gson, JsonReader reader) + throws IOException, FileOperationException { + while (reader.hasNext()) { + String name = reader.nextName(); + if ("version".equals(name)) { + autosaveInfo.setVersion(reader.nextString()); + } else if ("timestamp".equals(name)) { + autosaveInfo.setTimestamp(reader.nextString()); + } else if ("activeterminal".equals(name)) { + autosaveInfo.setActiveTerminalName(reader.nextString()); + } else if ("tabinfo".equals(name)) { + autosaveInfo.setAutosaveMD(new ArrayList()); + reader.beginArray(); + readTabInfo(maxTabCnt, autosaveInfo, gson, reader); + + reader.endArray(); + } else { + reader.skipValue(); + } + } + } + + private void readTabInfo(int maxTabCnt, AutoSaveInfo autosaveInfo, Gson gson, JsonReader reader) + throws IOException, FileOperationException { + int count = 0; + while (reader.hasNext()) { + // throws Exception when the count is greather than maxTabCnt + checkFileCount(maxTabCnt, count); + + AutoSaveMetadata md = null; + try { + md = gson.fromJson(reader, getTypeForLoad()); + } catch (JsonIOException | JsonSyntaxException exception) { + MPPDBIDELoggerUtility.error("getting Auto save info of file failed", exception); + throw new FileOperationException(IMessagesConstants.PRESERVESQL_JSONEXCEPTION); + } + + autosaveInfo.addAutoSaveMetadata(md); + count++; + } + } + + private void validateBytesLength(int byteslength) throws FileOperationException { + if (byteslength == 0) { + throw new FileOperationException(IMessagesConstants.PRESERVESQL_FILEREADEXCEPTION); + } + } + + private void checkFileCount(int maxTabCnt, int count) throws FileOperationException { + if (count > maxTabCnt) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.PRESERVESQL_JSONEXCEPTION)); + throw new FileOperationException(IMessagesConstants.PRESERVESQL_JSONEXCEPTION); + } + } + + private void validateFile(Path file) throws IOException, FileOperationException { + int maxFileSize = 5242880; + if (Files.isDirectory(file) || Files.isSymbolicLink(file) || !Files.isReadable(file) + || !Files.isRegularFile(file) || Files.size(file) == 0 || Files.size(file) > maxFileSize) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.PRESERVESQL_FILEREADEXCEPTION)); + throw new FileOperationException(IMessagesConstants.PRESERVESQL_FILEREADEXCEPTION); + } + } + + /** + * Save autosave info. + * + * @param autosaveInfo the autosave info + * @param fileName the file name + * @param tempFileName the temp file name + * @throws FileOperationException the file operation exception + */ + public void saveAutosaveInfo(AutoSaveInfo autosaveInfo, String fileName, String tempFileName) + throws FileOperationException { + try { + createFolderStructure(); + Path temp = createAutosaveTempFile(tempFileName); + Gson gson = new Gson(); + Type type = getType(); + String json = gson.toJson(autosaveInfo, type); + Files.write(temp, json.getBytes(StandardCharsets.UTF_8), StandardOpenOption.TRUNCATE_EXISTING); + } catch (IOException | DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("save auto save info failed", exception); + deleteFile(tempFileName); + throw new FileOperationException(IMessagesConstants.PRESERVESQL_FILEWRITEEXCEPTION); + } + rename(tempFileName, fileName); + } + + private Path createAutosaveTempFile(String tempFileName) + throws IOException, FileOperationException, DatabaseOperationException { + Path backup = Paths.get(getAutosaveFolderPath().toString(), tempFileName); + + if (Files.exists(backup)) { + Files.delete(backup); + } + FilePermissionFactory.getFilePermissionInstance().createFileWithPermission(backup.toString(), false, null, + true); + + return backup; + } + + private Type getType() { + return new AutoSaveTypeToken().getType(); + } + + /** + * + * Title: class + * + * Description: The Class AutoSaveTypeToken. + * + */ + private static class AutoSaveTypeToken extends TypeToken { + + } + + private Type getTypeForLoad() { + return new AutoSaveMetaDataTypeToken().getType(); + } + + /** + * + * Title: class + * + * Description: The Class AutoSaveMetaDataTypeToken. + * + */ + private static class AutoSaveMetaDataTypeToken extends TypeToken { + + } + + /** + * Sets the os current user folder path. + * + * @param currentOsUserPath the new os current user folder path + */ + public void setOsCurrentUserFolderPath(String currentOsUserPath) { + this.osCurrentUserFolderPath = currentOsUserPath; + } + + /** + * Gets the autosave info. + * + * @param autosaveFileName the autosave file name + * @param maxTabCnt the max tab cnt + * @return the autosave info + * @throws FileOperationException the file operation exception + */ + public AutoSaveInfo getAutosaveInfo(String autosaveFileName, int maxTabCnt) throws FileOperationException { + return getAutosaveInfo(Paths.get(getAutosaveFolderPath().toString(), autosaveFileName), maxTabCnt); + } + + /** + * Rename. + * + * @param srcFileName the src file name + * @param dstFileName the dst file name + */ + public void rename(String srcFileName, String dstFileName) { + try { + CopyOption[] newOptions = new CopyOption[2]; + newOptions[0] = StandardCopyOption.REPLACE_EXISTING; + newOptions[1] = StandardCopyOption.ATOMIC_MOVE; + Files.move(Paths.get(getAutosaveFolderPath().toString(), srcFileName), + Paths.get(getAutosaveFolderPath().toString(), dstFileName), newOptions); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("rename auto save info file failed", exception); + } + + } + + /** + * Delete stale files. + * + * @param validFileList the valid file list + * @param autoSaveDataFilePattern the auto save data file pattern + */ + public void deleteStaleFiles(final ArrayList validFileList, final String autoSaveDataFilePattern) { + File folder = new File(getAutosaveFolderPath().toString()); + File[] list = folder.listFiles(new FilenameFilter() { + + @Override + public boolean accept(File dir, String name) { + if (name.endsWith(autoSaveDataFilePattern) && !validFileList.contains(name)) { + return true; + } + + return false; + } + }); + + if (list != null) { + for (File item : list) { + try { + Files.walkFileTree(Paths.get(item.getCanonicalPath()), new DSFolderDeleteUtility()); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("Delete auto saved file failed.", exception); + } + } + } + } + + /** + * Delete file. + * + * @param fileName the file name + */ + public void deleteFile(String fileName) { + try { + Files.deleteIfExists(Paths.get(getAutosaveFolderPath().toString(), fileName)); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("Delete auto saved file failed.", exception); + } + } + + /** + * Delete folder structure if empty. + */ + public void deleteFolderStructureIfEmpty() { + try { + Files.delete(getAutosaveFolderPath()); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("Delete auto save folder failed", exception); + } + } + + /** + * Checks if is valid file. + * + * @param fileName the file name + * @param fileLimit long value + * @return true, if is valid file + */ + public boolean isValidFile(String fileName, double fileLimit) { + Path filePath = Paths.get(getAutosaveFolderPath().toString(), fileName); + double fileSizeInMB = FileUtils.sizeOf(filePath.toFile()) / (double) (1024 * 1024); + try { + if (Files.exists(filePath) && !Files.isDirectory(filePath) && !Files.isSymbolicLink(filePath) + && Files.isReadable(filePath) && Files.isRegularFile(filePath) && Files.size(filePath) != 0 + && fileSizeInMB < fileLimit) { + return true; + } + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("Checking if file is valid failed. ", exception); + } + + return false; + } + + /** + * Read. + * + * @param fileName the file name + * @return the byte[] + * @throws FileOperationException the file operation exception + */ + public byte[] read(String fileName, double fileLimit) throws FileOperationException { + Path file = Paths.get(getAutosaveFolderPath().toString(), fileName); + double fileSizeInMB = FileUtils.sizeOf(file.toFile()) / (double) (1024 * 1024); + + if (Files.exists(file) && !Files.isDirectory(file) && !Files.isSymbolicLink(file) && Files.isReadable(file) + && Files.isRegularFile(file) && (fileLimit != 0 && fileSizeInMB < fileLimit)) { + byte[] bytes = null; + try { + bytes = Files.readAllBytes(file); + } catch (IOException exp) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.PRESERVESQL_FILEREADEXCEPTION), exp); + throw new FileOperationException(IMessagesConstants.PRESERVESQL_FILEREADEXCEPTION); + } + + validateBytesLength(bytes.length); + + return bytes; + } + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.PRESERVESQL_FILEREADEXCEPTION)); + throw new FileOperationException(IMessagesConstants.PRESERVESQL_FILEREADEXCEPTION); + } + + /** + * Gets the file output stream. + * + * @param metaData the meta data + * @return the file output stream + * @throws FileOperationException the file operation exception + */ + public FileOutputStream getFileOutputStream(AutoSaveMetadata metaData) throws FileOperationException { + FileOutputStream fileWriter = null; + Path file = Paths.get(getAutosaveFolderPath().toString(), metaData.getAutoSaveFileName()); + + if (!Files.exists(file) || (Files.exists(file) && !Files.isDirectory(file) && !Files.isSymbolicLink(file) + && Files.isReadable(file) && Files.isRegularFile(file))) { + try { + if (Files.exists(file)) { + Files.delete(file); + } + + file = FilePermissionFactory.getFilePermissionInstance().createFileWithPermission(file.toString(), + false, null, true); + fileWriter = new FileOutputStream(file.toFile()); + } catch (IOException | DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("Write to file failed.", exception); + throw new FileOperationException(IMessagesConstants.PRESERVESQL_FILEWRITEEXCEPTION); + } + } + + return fileWriter; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/connection/IConnectionProfileManager.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/connection/IConnectionProfileManager.java new file mode 100644 index 0000000000000000000000000000000000000000..0ff4e1d9d9724f51e087475fd88ee68c822f4619 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/connection/IConnectionProfileManager.java @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.connection; + +import java.io.IOException; +import java.util.List; + +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; +import org.opengauss.mppdbide.utils.exceptions.DataStudioSecurityException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: interface + * + * Description: The Interface IConnectionProfileManager. + * + */ + +public interface IConnectionProfileManager { + + /** + * Delete profile. + * + * @param profile the profile + * @throws DatabaseOperationException the database operation exception + */ + void deleteProfile(IServerConnectionInfo profile) throws DatabaseOperationException; + + /** + * Save profile. + * + * @param profile the profile + * @throws DatabaseOperationException the database operation exception + * @throws DataStudioSecurityException the data studio security exception + */ + void saveProfile(IServerConnectionInfo profile) throws DatabaseOperationException, DataStudioSecurityException; + + /** + * Gets the all profiles. + * + * @return the all profiles + * @throws DatabaseOperationException the database operation exception + * @throws DataStudioSecurityException the data studio security exception + * @throws IOException Signals that an I/O exception has occurred. + */ + List getAllProfiles() + throws DatabaseOperationException, DataStudioSecurityException, IOException; + + /** + * Gets the profile. + * + * @param id the id + * @return the profile + */ + IServerConnectionInfo getProfile(String id); + + /** + * Rename profile. + * + * @param profile the profile + * @throws DatabaseOperationException the database operation exception + * @throws DataStudioSecurityException the data studio security exception + */ + void renameProfile(IServerConnectionInfo profile) throws DatabaseOperationException, DataStudioSecurityException; + + /** + * Clear permanent save pwd. + * + * @throws DatabaseOperationException the database operation exception + * @throws DataStudioSecurityException the data studio security exception + * @throws IOException Signals that an I/O exception has occurred. + */ + void clearPermanentSavePwd() throws DatabaseOperationException, DataStudioSecurityException, IOException; + + /** + * Export connection profiles. + * + * @param profiles the profiles + * @param filePath the file path + * @throws DatabaseOperationException the database operation exception + * @throws DataStudioSecurityException the data studio security exception + */ + void exportConnectionProfiles(List profiles, String filePath) + throws DatabaseOperationException, DataStudioSecurityException; + + /** + * Import connection profiles. + * + * @param path the path + * @param fileSizeLimit the file data size limit + * @return the list + * @throws DatabaseOperationException the database operation exception + */ + List importConnectionProfiles(String path, double fileSizeLimit) + throws DatabaseOperationException; + + /** + * Merge imported profiles. + * + * @param profilesList the profiles list + * @param allProfiles the all profiles + * @throws DatabaseOperationException the database operation exception + */ + void mergeImportedProfiles(List profilesList, List allProfiles) + throws DatabaseOperationException; + + /** + * Replace with imported profiles. + * + * @param profileToDeleted the profile to deleted + * @param profileToBeCreated the profile to be created + * @param allProfiles the all profiles + * @throws DatabaseOperationException the database operation exception + * @throws DataStudioSecurityException the data studio security exception + */ + void replaceWithImportedProfiles(IServerConnectionInfo profileToDeleted, IServerConnectionInfo profileToBeCreated, + List allProfiles) throws DatabaseOperationException, DataStudioSecurityException; + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/contentassist/ContentAssistKeywords.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/contentassist/ContentAssistKeywords.java new file mode 100644 index 0000000000000000000000000000000000000000..825e853ff428d00d1f3f95c9c1dc18b989fbdeec --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/contentassist/ContentAssistKeywords.java @@ -0,0 +1,196 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.contentassist; + +import java.util.Collection; +import java.util.Iterator; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.apache.commons.collections4.trie.PatriciaTrie; + +import org.opengauss.mppdbide.adapter.keywordssyntax.KeywordsFactoryProvider; +import org.opengauss.mppdbide.adapter.keywordssyntax.KeywordsToTrieConverter; +import org.opengauss.mppdbide.adapter.keywordssyntax.SQLSyntax; +import org.opengauss.mppdbide.bl.keyword.KeywordObject; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.DBTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.groups.OLAPObjectList; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ObjectList; + +/** + * + * Title: class ContentAssistKeywords + * + * Description: The Class ContentAssistKeywords. + * + * @since 3.0.0 + */ +public class ContentAssistKeywords { + + private static final Object INSTANCE_LOCK = new Object(); + + private OLAPObjectList olapKeywords; + + private ObjectList defaultKeywords; + + private static volatile ContentAssistKeywords instance = null; + + /** + * Instantiates a new content assist keywords. + */ + private ContentAssistKeywords() { + olapKeywords = new OLAPObjectList(OBJECTTYPE.KEYWORDS, this); + defaultKeywords = new ObjectList(OBJECTTYPE.KEYWORDS, this); + } + + /** + * Load keywords. + * + * @param database the database + */ + public void loadKeywords(Database database) { + if (null == database && defaultKeywords.getSize() == 0) { + fetchKeywords(defaultKeywords, null); + } else if (null != database && database.getDBType() == DBTYPE.OPENGAUSS && olapKeywords.getSize() == 0) { + fetchKeywords(olapKeywords, database); + } + + } + + /** + * Gets the single instance of ContentAssistKeywords. + * + * @param database the database + * @return single instance of ContentAssistKeywords + */ + public static ContentAssistKeywords getInstance() { + if (null == instance) { + synchronized (INSTANCE_LOCK) { + if (null == instance) { + instance = new ContentAssistKeywords(); + } + } + } + return instance; + } + + /** + * Fetch keywords. + * + * @param olapLeywords2 the olap leywords 2 + * @param database the database + */ + private void fetchKeywords(ObjectList olapLeywords2, Database database) { + SQLSyntax syntax = getSQLSyntax(database); + if (null != syntax) { + int counter = 1; + counter = addKeywords(syntax.getReservedkrywords(), counter, olapLeywords2); + counter = addKeywords(syntax.getUnreservedkrywords(), counter, olapLeywords2); + addKeywords(syntax.getConstants(), counter, olapLeywords2); + } + + } + + /** + * Adds the keywords. + * + * @param trie the trie + * @param counter the counter + * @param keywords the keywords + * @return the int + */ + private int addKeywords(PatriciaTrie trie, int counter, ObjectList keywords) { + for (String keyword : trie.keySet()) { + KeywordObject keywordObj = new KeywordObject(counter, keyword, OBJECTTYPE.KEYWORDS, false); + keywords.addItem(keywordObj); + counter++; + } + return counter; + } + + /** + * Gets the SQL syntax. + * + * @param database the database + * @return the SQL syntax + */ + public SQLSyntax getSQLSyntax(Database database) { + SQLSyntax syntax = new SQLSyntax(); + if (null != database) { + syntax = database.getSqlSyntax(); + } else { + syntax = KeywordsToTrieConverter.convertKeywordstoTrie(syntax, + KeywordsFactoryProvider.getKeywordsFactory().getKeywords()); + } + return syntax; + + } + + /** + * Find matching OLAP keyword. + * + * @param prefix the prefix + * @return the sorted map + */ + public SortedMap findMatchingOLAPKeyword(String prefix) { + SortedMap keyWords = new TreeMap(); + keyWords.putAll(olapKeywords.findMatching(prefix)); + return keyWords; + } + + /** + * Find matching default keyword. + * + * @param prefix the prefix + * @return the sorted map + */ + public SortedMap findMatchingDefaultKeyword(String prefix) { + SortedMap keyWords = new TreeMap(); + keyWords.putAll(defaultKeywords.findMatching(prefix)); + return keyWords; + } + + /** + * Clear OLAP keywords. + * + * @param collection the collection + */ + public void clearOLAPKeywords(Collection collection) { + Iterator dbItr = collection.iterator(); + Database db = null; + boolean hasNext = dbItr.hasNext(); + + while (hasNext) { + db = dbItr.next(); + if (db.isConnected() && db.getDBType() == DBTYPE.OPENGAUSS) { + return; + } + hasNext = dbItr.hasNext(); + } + olapKeywords.clear(); + } + + /** + * Clear. + */ + public void clear() { + olapKeywords.clear(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/contentassist/ContentAssistProcesserData.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/contentassist/ContentAssistProcesserData.java new file mode 100644 index 0000000000000000000000000000000000000000..7c30d9ef16807c9cebc1c5ae3198bb35b331d102 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/contentassist/ContentAssistProcesserData.java @@ -0,0 +1,580 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.contentassist; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ForeignTable; +import org.opengauss.mppdbide.bl.serverdatacache.GaussOLAPDBMSObject; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.PartitionTable; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class ContentAssistProcesserData. + * + */ + +public class ContentAssistProcesserData implements ISQLContentAssistProcessor { + + private Database database; + + private List nonLoaded = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + + private ContentAssistUtilIf contentAssistUtil; + + /** + * Gets the content assist util. + * + * @return the content assist util + */ + public ContentAssistUtilIf getContentAssistUtil() { + return contentAssistUtil; + } + + /** + * Instantiates a new content assist processer data. + * + * @param servObj the serv obj + */ + public ContentAssistProcesserData(ServerObject servObj) { + if (servObj instanceof Database) { + this.database = (Database) servObj; + contentAssistUtil = new ContentAssistUtilOLAP(database); + } else if (null == servObj) { + this.database = null; + contentAssistUtil = new ContentAssistUtilDefault(); + } + + } + + /** + * Find exact matching objects. + * + * @param prefixs the prefixs + * @return the sorted map + */ + public LinkedHashMap findExactMatchingObjects(String[] prefixs) { + int prefixLength = prefixs.length; + LinkedHashMap objMap1 = new LinkedHashMap(); + SortedMap objMap = new TreeMap(new AutoSuggestComparator()); + switch (prefixLength) { + case 1: { + objMap = findExactMatchingObjects(prefixs[0]); + objMap = findAllChildObjects(objMap); + break; + } + case 2: { + objMap = findExactMatchingObjects(prefixs[0]); + objMap = findExactMatchingChildObjects(prefixs[1], objMap); + objMap = findAllChildObjects(objMap); + break; + } + default: { + // Ignore other types + break; + } + } + objMap1.putAll(objMap); + return objMap1; + } + + /** + * Find all child objects. + * + * @param parentObjMap the parent obj map + * @return the sorted map + */ + private SortedMap findAllChildObjects(SortedMap parentObjMap) { + SortedMap found = new TreeMap(new AutoSuggestComparator()); + for (ServerObject servObj : parentObjMap.values()) { + if (servObj instanceof GaussOLAPDBMSObject) { + if (!isInsert() && servObj instanceof Namespace) { + Namespace ns = (Namespace) servObj; + found.putAll(ns.findAllChildObjects()); + } else if (servObj instanceof ForeignTable) { + ForeignTable fTable = (ForeignTable) servObj; + found.putAll(fTable.findAllChildObjects()); + } else if (servObj instanceof PartitionTable) { + PartitionTable partitionTable = PartitionTable.class.cast(servObj); + found.putAll(partitionTable.findAllChildObjects()); + } else if (servObj instanceof TableMetaData) { + TableMetaData tbl = (TableMetaData) servObj; + found.putAll(tbl.findAllChildObjects()); + } else if (servObj instanceof ViewMetaData) { + ViewMetaData view = ViewMetaData.class.cast(servObj); + found.putAll(view.findAllChildObjects()); + } + } + if (isInsert()) { + found = contentAssistUtil.getChildObject(found, parentObjMap.size() > 1); + } + if (!servObj.isLoaded() && nonLoaded != null) { + nonLoaded.add(servObj); + } + } + + return found; + } + + /** + * Find case insensitive matching objects. + * + * @param prefixParam the prefix param + * @return the sorted map + */ + public LinkedHashMap findCaseInsensitiveMatchingObjects(String prefixParam) { + String prefix = prefixParam.toLowerCase(Locale.getDefault()); + LinkedHashMap retChildMap = new LinkedHashMap(); + SortedMap retKeywordMap = new TreeMap(new AutoSuggestComparator()); + retKeywordMap.putAll(findPrefixMatchingKeywords(prefix)); + SortedMap retDatatypeMap = new TreeMap(new AutoSuggestComparator()); + retDatatypeMap.putAll(findPrefixMatchingDatatypes(prefix)); + SortedMap retObjMap = new TreeMap(new AutoSuggestComparator()); + retObjMap.putAll(findPrefixMatchingObjects(prefix)); + retChildMap.putAll(retKeywordMap); + retChildMap.putAll(retDatatypeMap); + retChildMap.putAll(retObjMap); + return retChildMap; + } + + /** + * Find case insensitive matching child objects. + * + * @param prefix the prefix + * @param parentObjMap the parent obj map + * @return the sorted map + */ + public SortedMap findCaseInsensitiveMatchingChildObjects(String prefix, + SortedMap parentObjMap) { + SortedMap retChildMap = new TreeMap(new AutoSuggestComparator()); + + retChildMap.putAll(findPrefixMatchingChildObjects(prefix, parentObjMap)); + if (!prefix.contains("\"")) { + String strUpperPrefix = prefix.toUpperCase(Locale.ENGLISH); + String strLowerPrefix = prefix.toLowerCase(Locale.ENGLISH); + if (!prefix.equals(strUpperPrefix)) { + retChildMap.putAll(findPrefixMatchingChildObjects(strUpperPrefix, parentObjMap)); + } + if (!prefix.equals(strLowerPrefix)) { + retChildMap.putAll(findPrefixMatchingChildObjects(strLowerPrefix, parentObjMap)); + } + } + return retChildMap; + } + + /** + * Find prefix matching objects. + * + * @param prefixs the prefixs + * @return the sorted map + */ + public LinkedHashMap findPrefixMatchingObjects(String[] prefixs) { + int prefixLength = prefixs.length; + LinkedHashMap objMap1 = new LinkedHashMap(); + SortedMap objMapChild = null; + SortedMap objMapClmChild = null; + switch (prefixLength) { + case 0: { + objMap1 = findCaseInsensitiveMatchingObjects(""); + break; + } + case 1: { + objMap1 = findCaseInsensitiveMatchingObjects(prefixs[0]); + break; + } + case 2: { + SortedMap objMap = findExactMatchingObjects(prefixs[0]); + objMapClmChild = findCaseInsensitiveMatchingChildObjects(prefixs[1], objMap); + break; + } + case 3: { + objMapChild = findExactMatchingObjects(prefixs[0]); + objMapChild = findExactMatchingChildObjects(prefixs[1], objMapChild); + objMapClmChild = findCaseInsensitiveMatchingChildObjects(prefixs[2], objMapChild); + + break; + } + default: { + // Ignore other types + break; + } + } + if (objMapClmChild != null) { + if (isInsert() && objMapChild != null) { + objMapClmChild = contentAssistUtil.getChildObject(objMapClmChild, objMapChild.size() > 1); + } + objMap1.putAll(objMapClmChild); + } + return objMap1; + } + + /** + * Find prefix matching child objects. + * + * @param prefix the prefix + * @param parentObjMap the parent obj map + * @return the sorted map + */ + private SortedMap findPrefixMatchingChildObjects(String prefix, + SortedMap parentObjMap) { + SortedMap found = new TreeMap(new AutoSuggestComparator()); + for (ServerObject servObj : parentObjMap.values()) { + if (servObj instanceof Namespace) { + Namespace ns = (Namespace) servObj; + found.putAll(ns.findPrefixMatchingChildObjects(prefix)); + } else if (servObj instanceof ForeignTable) { + ForeignTable fTable = (ForeignTable) servObj; + found.putAll(fTable.findMatchingChildObjects(prefix)); + } else if (servObj instanceof PartitionTable) { + PartitionTable partitionTable = PartitionTable.class.cast(servObj); + found.putAll(partitionTable.findMatchingChildObjects(prefix)); + } else if (servObj instanceof TableMetaData) { + TableMetaData tbl = (TableMetaData) servObj; + found.putAll(tbl.findMatchingChildObjects(prefix)); + } else if (servObj instanceof ViewMetaData) { + ViewMetaData view = ViewMetaData.class.cast(servObj); + found.putAll(view.findMatchingChildObject(prefix)); + } + } + return found; + } + + /** + * Find prefix matching keywords. + * + * @param prefix the prefix + * @return the sorted map + */ + public SortedMap findPrefixMatchingKeywords(String prefix) { + + SortedMap keywordObjMap = new TreeMap(new AutoSuggestComparator()); + keywordObjMap.putAll(contentAssistUtil.findMatchingKeywords(prefix)); + return keywordObjMap; + } + + /** + * Find prefix matching datatypes. + * + * @param prefix the prefix + * @return the sorted map + */ + public SortedMap findPrefixMatchingDatatypes(String prefix) { + SortedMap datatypeObjMap = new TreeMap(new AutoSuggestComparator()); + datatypeObjMap.putAll(contentAssistUtil.findMatchingDataypes(prefix)); + return datatypeObjMap; + } + + /** + * Find prefix matching objects. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findPrefixMatchingObjects(String prefix) { + SortedMap objMap = new TreeMap(new AutoSuggestComparator()); + objMap.putAll(contentAssistUtil.findMatchingNamespace(prefix)); + objMap.putAll(contentAssistUtil.findMatchingTables(prefix)); + objMap.putAll(contentAssistUtil.findMatchingViewsObject(prefix)); + objMap.putAll(contentAssistUtil.findMatchingDebugObjects(prefix)); + objMap.putAll(contentAssistUtil.findMatchingSequenceObject(prefix)); + objMap.putAll(contentAssistUtil.findMatchingSynonyms(prefix)); + objMap.putAll(contentAssistUtil.findMatchingTriggerObject(prefix)); + + return objMap; + } + + /** + * Find exact matching child objects. + * + * @param prefix the prefix + * @param objMap the obj map + * @return the sorted map + */ + private SortedMap findExactMatchingChildObjects(String prefix, + SortedMap objMap) { + + SortedMap found = new TreeMap(new AutoSuggestComparator()); + for (ServerObject serverObj : objMap.values()) { + if (serverObj instanceof Namespace) { + Namespace ns = (Namespace) serverObj; + found.putAll(ns.findExactMatchingChildObjects(prefix)); + } else if (serverObj instanceof ForeignTable) { + ForeignTable fTable = (ForeignTable) serverObj; + found.putAll(fTable.findMatchingChildObjects(prefix)); + } else if (serverObj instanceof PartitionTable) { + PartitionTable partitionTable = PartitionTable.class.cast(serverObj); + found.putAll(partitionTable.findMatchingChildObjects(prefix)); + } else if (serverObj instanceof TableMetaData) { + TableMetaData tbl = (TableMetaData) serverObj; + found.putAll(tbl.findMatchingChildObjects(prefix)); + } else if (serverObj instanceof ViewMetaData) { + ViewMetaData view = ViewMetaData.class.cast(serverObj); + found.putAll(view.findMatchingChildObject(prefix)); + } + } + return found; + } + + /** + * Find exact matching objects. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findExactMatchingObjects(String prefix) { + SortedMap objMap = new TreeMap(new AutoSuggestComparator()); + objMap.putAll(contentAssistUtil.findExactMatchingNamespaces(prefix)); + objMap.putAll(contentAssistUtil.findExactMatchingTables(prefix)); + objMap.putAll(contentAssistUtil.findExactMatchingViews(prefix)); + objMap.putAll(contentAssistUtil.findExactMatchingDebugObjects(prefix)); + objMap.putAll(contentAssistUtil.findExactMatchingSequences(prefix)); + objMap.putAll(contentAssistUtil.findExactMatchingSynonyms(prefix)); + objMap.putAll(contentAssistUtil.findExactMatchingTriggers(prefix)); + + return objMap; + + } + + /** + * Gets the non loaded. + * + * @return the non loaded + */ + public List getNonLoaded() { + return nonLoaded; + } + + /** + * Gets the find string. + * + * @param pretext the pretext + * @param workBreakCharList the work break char list + * @return the find string + */ + public String getFindString(String pretext, List workBreakCharList) { + return contentAssistUtil.findString(pretext, workBreakCharList); + } + + /** + * Gets the removd literal escapes and quotes. + * + * @param str the str + * @return the removd literal escapes and quotes + */ + public String getRemovdLiteralEscapesAndQuotes(String str) { + return contentAssistUtil.removeLiteralEscapesAndQuotes(str); + } + + /** + * Gets the split prefix by dots. + * + * @param prefix the prefix + * @return the split prefix by dots + */ + public String[] getSplitPrefixByDots(String prefix) { + return contentAssistUtil.splitPrefixByDots(prefix); + } + + /** + * Find non loaded objects. + * + * @param connection the connection + * @param prefixs the prefixs + * @return the sorted map + * @throws MPPDBIDEException the MPPDBIDE exception + */ + @Override + public LinkedHashMap findNonLoadedObjects(DBConnection connection, String[] prefixs) + throws MPPDBIDEException { + loadDatabaseObjects(connection); + return findExactMatchingObjects(prefixs); + } + + /** + * Load database objects. + * + * @param connection the connection + * @throws MPPDBIDEException the MPPDBIDE exception + */ + private void loadDatabaseObjects(DBConnection connection) throws MPPDBIDEException { + try { + if (nonLoaded == null || nonLoaded.size() <= 0) { + return; + } + for (ServerObject servObj : nonLoaded) { + if (servObj instanceof Namespace) { + loadNamespace(connection, servObj); + } else if (servObj instanceof ForeignTable) { + loadForeignTable(connection, servObj); + } else if (servObj instanceof PartitionTable) { + loadPartitionTable(connection, servObj); + } else if (servObj instanceof TableMetaData) { + loadTableMetadata(connection, servObj); + } else if (servObj instanceof ViewMetaData) { + loadViewMetadata(connection, servObj); + } + } + + } catch (MPPDBIDEException exception) { + MPPDBIDELoggerUtility.error("ContenetAssistProcessor: Load database for content assist failed.", exception); + throw exception; + } + } + + /** + * Load partition table. + * + * @param connection the connection + * @param servObj the serv obj + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void loadPartitionTable(DBConnection connection, ServerObject servObj) + throws DatabaseCriticalException, DatabaseOperationException { + PartitionTable partitionTable = PartitionTable.class.cast(servObj); + if (!partitionTable.isLoaded()) { + partitionTable.refreshTableDetails(connection); + } + } + + /** + * Load view metadata. + * + * @param connection the connection + * @param servObj the serv obj + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + private void loadViewMetadata(DBConnection connection, ServerObject servObj) + throws DatabaseOperationException, DatabaseCriticalException { + ViewMetaData view = ViewMetaData.class.cast(servObj); + if (!view.isLoaded()) { + view.getNamespace().refreshView(view, connection, false); + } + } + + /** + * Load foreign table. + * + * @param connection the connection + * @param servObj the serv obj + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void loadForeignTable(DBConnection connection, ServerObject servObj) + throws DatabaseCriticalException, DatabaseOperationException { + ForeignTable fTable = ForeignTable.class.cast(servObj); + if (!fTable.isLoaded()) { + fTable.refreshTableDetails(connection); + } + } + + /** + * Load table metadata. + * + * @param connection the connection + * @param servObj the serv obj + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void loadTableMetadata(DBConnection connection, ServerObject servObj) + throws DatabaseCriticalException, DatabaseOperationException { + TableMetaData tbl = TableMetaData.class.cast(servObj); + if (!tbl.isLoaded()) { + tbl.refreshTableDetails(connection); + } + } + + /** + * Load namespace. + * + * @param connection the connection + * @param servObj the serv obj + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + private void loadNamespace(DBConnection connection, ServerObject servObj) + throws DatabaseOperationException, DatabaseCriticalException { + Namespace ns = Namespace.class.cast(servObj); + if (!ns.isLoaded()) { + ns.getAllObjectsOnDemand(connection); + ns.getDatabase().getSearchPathHelper().getSearchPath().add(ns.getName()); + } + } + + /** + * + * Title: class + * + * Description: The Class AutoSuggestComparator. + * + */ + public static class AutoSuggestComparator implements Comparator, Serializable { + + private static final long serialVersionUID = 1L; + + /** + * Compare. + * + * @param o1 the o 1 + * @param o2 the o 2 + * @return the int + */ + @Override + public int compare(String o1, String o2) { + + if (o1.equalsIgnoreCase(o2)) { + if (!o1.equals(o2)) { + return o1.compareTo(o2); + } + } + return o1.compareToIgnoreCase(o2); + + } + + } + + /** + * Checks if is insert. + * + * @return true, if is insert + */ + public boolean isInsert() { + return contentAssistUtil.isInsert(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/contentassist/ContentAssistUtil.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/contentassist/ContentAssistUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..d09e2e4dd75f08cfb71ccc7235afe3e5b1172dfe --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/contentassist/ContentAssistUtil.java @@ -0,0 +1,246 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.contentassist; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.apache.commons.collections4.trie.PatriciaTrie; + +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.util.BLUtils; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class ContentAssistUtil. + * + */ + +public abstract class ContentAssistUtil implements ContentAssistUtilIf { + private int posForFindPrefix; + private boolean isInsert = false; + private static final String OPENING_BRACE = "("; + private static final char CLOSING_BRACE = ')'; + private static final char SEMI_COLON = ';'; + private static final String COMMA = ","; + private int minPosition = 0; + + /** + * Gets the matching. + * + * @param trie the trie + * @param prefix the prefix + * @return the matching + */ + public SortedMap getMatching(PatriciaTrie trie, String prefix) { + String prefixShort = null; + if (prefix.length() > 3) { + prefixShort = prefix.substring(0, 2); + } else { + prefixShort = prefix; + } + SortedMap map = getAllObjectWithPrefixCaseInsensitive(trie, prefixShort); + SortedMap serverObjMap = new TreeMap(); + for (ServerObject obj : map.values()) { + serverObjMap.put(obj.getOid(), obj); + } + SortedMap resultMap = new TreeMap(); + for (ServerObject obj : serverObjMap.values()) { + if (obj.getSearchName().toLowerCase(Locale.ENGLISH).startsWith(prefix.toLowerCase(Locale.ENGLISH))) { + resultMap.put(obj.getSearchName(), obj); + } + } + + return (SortedMap) resultMap; + } + + /** + * Gets the all object with prefix case insensitive. + * + * @param trie the trie + * @param text the text + * @return the all object with prefix case insensitive + */ + public SortedMap getAllObjectWithPrefixCaseInsensitive(PatriciaTrie trie, String text) { + SortedMap map = new TreeMap(); + ArrayList prefixList = BLUtils.getAllCombinationsOfPrefix(text); + for (String prefix : prefixList) { + map.putAll(trie.prefixMap(String.valueOf(prefix))); + } + return map; + } + + /** + * Find string. + * + * @param pretext the pretext + * @param workBreakCharList the work break char list + * @return the string + */ + @Override + public String findString(String pretextParam, List workBreakCharList) { + String pretext = pretextParam; + if (pretext.trim().isEmpty()) { + return null; + } + posForFindPrefix = pretext.length() - 1; + minPosition = getMinimumPosition(pretext.length()); + int oldPos = posForFindPrefix; + ArrayList strList = new ArrayList(); + String lowerPretext = pretext.toLowerCase(Locale.ENGLISH); + if (lowerPretext.contains("insert") && lowerPretext.contains("into")) { + if (isValidForInsertStmt(pretext)) { + return validateForInsertStmt(pretext, workBreakCharList, strList); + } else { + ArrayList strList1 = new ArrayList(); + int position = findDefaultString(pretext, workBreakCharList, oldPos, strList1, posForFindPrefix); + char ch; + do { + ch = pretext.charAt(position); + position--; + } while (Character.isWhitespace(ch)); + if (ch == OPENING_BRACE.charAt(0) || ch == COMMA.charAt(0)) { + posForFindPrefix = ++position; + pretext = pretext.substring(0, posForFindPrefix + 1); + + String str = validateForInsertStmt(pretext, workBreakCharList, strList); + if (this.isInsert) { + return str + '.' + strList1.get(0); + } + } else { + findDefaultString(pretext, workBreakCharList, oldPos, strList, posForFindPrefix); + } + } + } else { + findDefaultString(pretext, workBreakCharList, oldPos, strList, posForFindPrefix); + } + return strList.get(0); + + } + + private int getMinimumPosition(int fullTextLength) { + + if (fullTextLength > MPPDBIDEConstants.MAX_PREFIX_SEARCH_LENGTH) { + minPosition = fullTextLength - MPPDBIDEConstants.MAX_PREFIX_SEARCH_LENGTH; + } + return minPosition; + } + + private String validateForInsertStmt(String pretext, List workBreakCharList, ArrayList strList) { + int oldPos; + char ch; + String retStr = null; + if (pretext.endsWith(COMMA)) { + while (posForFindPrefix >= minPosition) { + ch = pretext.charAt(posForFindPrefix); + if (ch == CLOSING_BRACE || ch == SEMI_COLON) { + return MPPDBIDEConstants.INVALID_INSERT; + } + if (ch == OPENING_BRACE.charAt(0)) { + break; + } + --posForFindPrefix; + } + + } + oldPos = getValidString(pretext, workBreakCharList, strList); + while (posForFindPrefix >= minPosition && strList.size() < 3) { + while (posForFindPrefix >= minPosition) { + ch = pretext.charAt(posForFindPrefix); + if (Character.isWhitespace(ch)) { + break; + } + --posForFindPrefix; + } + + retStr = pretext.substring(posForFindPrefix + 1, oldPos); + + retStr = retStr.trim(); + if (!retStr.isEmpty()) { + strList.add(retStr); + } + oldPos = posForFindPrefix; + posForFindPrefix--; + } + + if (strList.size() >= 3 && "INSERT".equalsIgnoreCase(strList.get(2)) + && "INTO".equalsIgnoreCase(strList.get(1))) { + setInsert(true); + } else { + setInsert(false); + return MPPDBIDEConstants.INVALID_INSERT; + } + return strList.get(0); + } + + private boolean isValidForInsertStmt(String pretext) { + return pretext.endsWith(OPENING_BRACE) || pretext.endsWith(COMMA); + } + + private int getValidString(String pretext, List workBreakCharList, ArrayList strList) { + int oldPos; + char ch; + --posForFindPrefix; + oldPos = posForFindPrefix; + while (posForFindPrefix >= 0 && strList.size() <= 0) { + ch = pretext.charAt(posForFindPrefix); + if (!Character.isWhitespace(ch)) { + + posForFindPrefix = findDefaultString(pretext, workBreakCharList, oldPos, strList, posForFindPrefix); + oldPos = posForFindPrefix; + } + --posForFindPrefix; + } + return oldPos; + } + + /** + * Checks if is insert. + * + * @return true, if is insert + */ + public boolean isInsert() { + return isInsert; + } + + /** + * Sets the insert. + * + * @param isInsert the new insert + */ + public void setInsert(boolean isInsert) { + this.isInsert = isInsert; + } + + /** + * Find default string. + * + * @param pretext the pretext + * @param workBreakCharList the work break char list + * @param oldPos the old pos + * @param strList the str list + * @param posForFindPrefix the pos for find prefix + * @return the int + */ + public abstract int findDefaultString(String pretext, List workBreakCharList, int oldPos, + ArrayList strList, int posForFindPrefix); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/contentassist/ContentAssistUtilDefault.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/contentassist/ContentAssistUtilDefault.java new file mode 100644 index 0000000000000000000000000000000000000000..914d0e6fd29f6514019133b247baa44936b23a12 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/contentassist/ContentAssistUtilDefault.java @@ -0,0 +1,281 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.contentassist; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.opengauss.mppdbide.bl.contentassist.ContentAssistProcesserData.AutoSuggestComparator; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; + +/** + * Title: ContentAssistUtilDefault + * + * Description: + * + */ + +public class ContentAssistUtilDefault extends ContentAssistUtil { + + SortedMap defaultMap = new TreeMap(new AutoSuggestComparator()); + + ArrayList prefixParts = new ArrayList(); + + /** + * Find matching namespace. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findMatchingNamespace(String prefix) { + return defaultMap; + } + + /** + * Find matching tables. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findMatchingTables(String prefix) { + return defaultMap; + } + + /** + * Find matching debug objects. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findMatchingDebugObjects(String prefix) { + return defaultMap; + } + + /** + * Find matching views object. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findMatchingViewsObject(String prefix) { + return defaultMap; + } + + /** + * Find matching sequence object. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findMatchingSequenceObject(String prefix) { + return defaultMap; + } + + /** + * Find exact matching sequences. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findExactMatchingSequences(String prefix) { + return defaultMap; + } + + /** + * Find exact matching debug objects. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findExactMatchingDebugObjects(String prefix) { + return defaultMap; + } + + /** + * Find exact matching views. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findExactMatchingViews(String prefix) { + return defaultMap; + } + + /** + * Find exact matching tables. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findExactMatchingTables(String prefix) { + return defaultMap; + } + + /** + * Find exact matching namespaces. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findExactMatchingNamespaces(String prefix) { + return defaultMap; + } + + /** + * Find string. + * + * @param pretext the pretext + * @param workBreakCharList the work break char list + * @return the string + */ + @Override + public String findString(String pretext, List workBreakCharList) { + + if (pretext.trim().isEmpty()) { + return null; + } + int pos = pretext.length() - 1; + char ch = '\0'; + + while (pos >= 0) { + ch = pretext.charAt(pos); + + if (Character.isWhitespace(ch)) { + break; + } + + --pos; + } + String retStr = null; + retStr = pretext.substring(pos + 1); + retStr = retStr.trim(); + + return retStr; + } + + /** + * Remove literal escapes and quotes. + * + * @param str the str + * @return the string + */ + @Override + public String removeLiteralEscapesAndQuotes(String str) { + return str.toUpperCase(Locale.ENGLISH); + } + + /** + * Split prefix by dots. + * + * @param prefix the prefix + * @return the string[] + */ + @Override + public String[] splitPrefixByDots(String prefix) { + prefixParts.add(prefix); + return prefixParts.toArray(new String[prefixParts.size()]); + } + + /** + * Gets the prefix hyper link. + * + * @param prefix the prefix + * @return the prefix hyper link + */ + @Override + public String[] getPrefixHyperLink(String prefix) { + return prefixParts.toArray(new String[5]); + } + + /** + * Find matching keywords. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findMatchingKeywords(String prefix) { + ContentAssistKeywords.getInstance().loadKeywords(null); + return ContentAssistKeywords.getInstance().findMatchingDefaultKeyword(prefix); + } + + /** + * Find matching dataypes. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findMatchingDataypes(String prefix) { + return defaultMap; + } + + /** + * Find default string. + * + * @param pretext the pretext + * @param workBreakCharList the work break char list + * @param oldPos the old pos + * @param strList the str list + * @param posForFindPrefix the pos for find prefix + * @return the int + */ + @Override + public int findDefaultString(String pretext, List workBreakCharList, int oldPos, + ArrayList strList, int posForFindPrefix) { + return 0; + } + + @Override + public SortedMap getChildObject(SortedMap found, + boolean isParentDescNeeded) { + return defaultMap; + } + + @Override + public SortedMap findMatchingTriggerObject(String prefix) { + return defaultMap; + } + + @Override + public SortedMap findExactMatchingTriggers(String prefix) { + return defaultMap; + } + + @Override + public SortedMap findExactMatchingSynonyms(String prefix) { + return defaultMap; + } + + @Override + public SortedMap findMatchingSynonyms(String prefix) { + return defaultMap; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/contentassist/ContentAssistUtilIf.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/contentassist/ContentAssistUtilIf.java new file mode 100644 index 0000000000000000000000000000000000000000..b5801101ee846a0d033a841294717996ac0e21d2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/contentassist/ContentAssistUtilIf.java @@ -0,0 +1,233 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.contentassist; + +import java.util.List; +import java.util.SortedMap; + +import org.apache.commons.collections4.trie.PatriciaTrie; + +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; + +/** + * + * Title: interface + * + * Description: The Interface ContentAssistUtilIf. + * + */ + +public interface ContentAssistUtilIf { + + /** + * Find matching namespace. + * + * @param prefix the prefix + * @return the sorted map + */ + SortedMap findMatchingNamespace(String prefix); + + /** + * Find matching tables. + * + * @param prefix the prefix + * @return the sorted map + */ + SortedMap findMatchingTables(String prefix); + + /** + * Find matching debug objects. + * + * @param prefix the prefix + * @return the sorted map + */ + SortedMap findMatchingDebugObjects(String prefix); + + /** + * Find matching views object. + * + * @param prefix the prefix + * @return the sorted map + */ + SortedMap findMatchingViewsObject(String prefix); + + /** + * Find matching sequence object. + * + * @param prefix the prefix + * @return the sorted map + */ + SortedMap findMatchingSequenceObject(String prefix); + + /** + * Find exact matching sequences. + * + * @param prefix the prefix + * @return the sorted map + */ + SortedMap findExactMatchingSequences(String prefix); + + /** + * Find exact matching debug objects. + * + * @param prefix the prefix + * @return the sorted map + */ + SortedMap findExactMatchingDebugObjects(String prefix); + + /** + * Find exact matching views. + * + * @param prefix the prefix + * @return the sorted map + */ + SortedMap findExactMatchingViews(String prefix); + + /** + * Find exact matching tables. + * + * @param prefix the prefix + * @return the sorted map + */ + SortedMap findExactMatchingTables(String prefix); + + /** + * Find exact matching namespaces. + * + * @param prefix the prefix + * @return the sorted map + */ + SortedMap findExactMatchingNamespaces(String prefix); + + /** + * Find string. + * + * @param pretext the pretext + * @param workBreakCharList the work break char list + * @return the string + */ + String findString(String pretext, List workBreakCharList); + + /** + * Removes the literal escapes and quotes. + * + * @param str the str + * @return the string + */ + String removeLiteralEscapesAndQuotes(String str); + + /** + * Split prefix by dots. + * + * @param prefix the prefix + * @return the string[] + */ + String[] splitPrefixByDots(String prefix); + + /** + * Gets the prefix hyper link. + * + * @param prefix the prefix + * @return the prefix hyper link + */ + String[] getPrefixHyperLink(String prefix); + + /** + * Gets the matching. + * + * @param trie the trie + * @param prefix the prefix + * @return the matching + */ + SortedMap getMatching(PatriciaTrie trie, String prefix); + + /** + * Gets the all object with prefix case insensitive. + * + * @param trie the trie + * @param text the text + * @return the all object with prefix case insensitive + */ + SortedMap getAllObjectWithPrefixCaseInsensitive(PatriciaTrie trie, String text); + + /** + * Find matching keywords. + * + * @param prefix the prefix + * @return the sorted map + */ + SortedMap findMatchingKeywords(String prefix); + + /** + * Find matching dataypes. + * + * @param prefix the prefix + * @return the sorted map + */ + SortedMap findMatchingDataypes(String prefix); + + /** + * Checks if is insert. + * + * @return true, if is insert + */ + boolean isInsert(); + + /** + * Gets the child object. + * + * @param found the found + * @param isParentDescNeeded the is parent desc needed + * @return the child object + */ + SortedMap getChildObject(SortedMap found, boolean isParentDescNeeded); + + /** + * Find matching trigger object. + * + * @param prefix the prefix + * @return the sorted map + */ + SortedMap findMatchingTriggerObject(String prefix); + + /** + * Find exact matching triggers. + * + * @param prefix the prefix + * @return the sorted map + */ + SortedMap findExactMatchingTriggers(String prefix); + + /** + * Find matching synonyms. + * + * @param prefix the prefix + * @return the sorted map + */ + default SortedMap findMatchingSynonyms(String prefix) { + return null; + } + + /** + * Find exact matching synonyms. + * + * @param prefix the prefix + * @return the sorted map + */ + default SortedMap findExactMatchingSynonyms(String prefix) { + return null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/contentassist/ContentAssistUtilOLAP.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/contentassist/ContentAssistUtilOLAP.java new file mode 100644 index 0000000000000000000000000000000000000000..01a9735ace52b4a525473c385dcecef6ae62bf95 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/contentassist/ContentAssistUtilOLAP.java @@ -0,0 +1,565 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.contentassist; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map.Entry; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DebugObjects; +import org.opengauss.mppdbide.bl.serverdatacache.SequenceMetadata; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.SynonymMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ViewColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class ContentAssistUtilOLAP. + * + */ + +public class ContentAssistUtilOLAP extends ContentAssistUtil { + + private Database database; + + private static final char DOT = '.'; + + private static final char DOUBLE_QUOTE = '\"'; + + private static final char ESCAPE_CHAR = '\"'; + + private static final char NEW_LINE_CHAR = MPPDBIDEConstants.LINE_SEPARATOR.length() > 1 + ? MPPDBIDEConstants.LINE_SEPARATOR.charAt(1) + : MPPDBIDEConstants.LINE_SEPARATOR.charAt(0); + + /** + * Instantiates a new content assist util OLAP. + * + * @param servObj the serv obj + */ + public ContentAssistUtilOLAP(ServerObject servObj) { + if (servObj instanceof Database) { + database = (Database) servObj; + } + } + + /** + * Find matching namespace. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findMatchingNamespace(String prefix) { + SortedMap matchedNamespaces = new TreeMap(); + matchedNamespaces.putAll(database.getUserNamespaces().getMatching(prefix)); + matchedNamespaces.putAll(database.getSystemNamespaces().getMatching(prefix)); + return matchedNamespaces; + } + + /** + * Find matching tables. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findMatchingTables(String prefix) { + return getMatching(database.getSearchPoolManager().getTableTrie(), prefix); + } + + /** + * Find matching debug objects. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findMatchingDebugObjects(String prefix) { + return getMatching(database.getSearchPoolManager().getDebugObjectTrie(), prefix); + } + + /** + * Find matching views object. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findMatchingViewsObject(String prefix) { + return getMatching(database.getSearchPoolManager().getViewTrie(), prefix); + } + + /** + * Find matching sequence object. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findMatchingSequenceObject(String prefix) { + return getMatching(database.getSearchPoolManager().getSequenceTrie(), prefix); + } + + /** + * Find matching sequence object. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findMatchingSynonyms(String prefix) { + return getMatching(database.getSearchPoolManager().getSynonymTrie(), prefix); + } + + /** + * Find exact matching sequences. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findExactMatchingSequences(String prefix) { + SortedMap map = database.getSearchPoolManager().getSequenceTrie().prefixMap(prefix); + SortedMap retMap = new TreeMap(); + for (Entry entry : map.entrySet()) { + SequenceMetadata object = entry.getValue(); + if (prefix.equals(object.getName())) { + retMap.put(entry.getKey(), object); + } + } + return retMap; + } + + /** + * Find exact matching debug objects. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findExactMatchingDebugObjects(String prefix) { + + SortedMap map = database.getSearchPoolManager().getDebugObjectTrie().prefixMap(prefix); + SortedMap retMap = new TreeMap(); + for (Entry entry : map.entrySet()) { + DebugObjects object = entry.getValue(); + if (prefix.equals(object.getName())) { + retMap.put(entry.getKey(), object); + } + } + return retMap; + } + + /** + * Find exact matching views. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findExactMatchingViews(String prefix) { + SortedMap map = database.getSearchPoolManager().getViewTrie().prefixMap(prefix); + SortedMap retMap = new TreeMap(); + for (Entry entry : map.entrySet()) { + ViewMetaData object = entry.getValue(); + if (prefix.equals(object.getName())) { + retMap.put(entry.getKey(), object); + } + } + return retMap; + } + + /** + * Find exact matching tables. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findExactMatchingTables(String prefix) { + SortedMap map = database.getSearchPoolManager().getTableTrie().prefixMap(prefix); + SortedMap retMap = new TreeMap(); + + for (Entry entry : map.entrySet()) { + TableMetaData object = entry.getValue(); + if (prefix.equals(object.getName())) { + retMap.put(entry.getKey(), object); + } + } + return retMap; + } + + /** + * Find exact matching sequences. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findExactMatchingSynonyms(String prefix) { + SortedMap map = database.getSearchPoolManager().getSynonymTrie().prefixMap(prefix); + SortedMap retMap = new TreeMap(); + for (Entry entry : map.entrySet()) { + SynonymMetaData object = entry.getValue(); + if (prefix.equals(object.getName())) { + retMap.put(entry.getKey(), object); + } + } + return retMap; + } + + /** + * Find exact matching namespaces. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findExactMatchingNamespaces(String prefix) { + SortedMap exactMatchedNamespaces = new TreeMap(); + exactMatchedNamespaces.putAll(database.getUserNamespaces().getMatchingHyperLink(prefix)); + exactMatchedNamespaces.putAll(database.getSystemNamespaces().getMatchingHyperLink(prefix)); + return exactMatchedNamespaces; + } + + /** + * Checks if is escaped. + * + * @param pretext the pretext + * @param pos the pos + * @return true, if is escaped + */ + private static boolean isEscaped(String pretext, int pos) { + if (0 == pos) { + return false; + } + char ch = pretext.charAt(pos - 1); + return ESCAPE_CHAR == ch; + } + + /** + * Checks if is escaped literal. + * + * @param pretext the pretext + * @param pos the pos + * @return true, if is escaped literal + */ + private boolean isEscapedLiteral(String pretext, int pos) { + if (pretext.length() == (pos + 1)) { + return false; + } + + return ESCAPE_CHAR == pretext.charAt(pos) && DOUBLE_QUOTE == pretext.charAt(pos + 1); + } + + @Override + public int findDefaultString(String pretext, List workBreakCharList, int oldPos, + ArrayList strList, int posForFindPrefix) { + char ch = '\0'; + boolean isLastCharDot = false; + boolean isQuotedString = false; + + while (posForFindPrefix >= 0) { + ch = pretext.charAt(posForFindPrefix); + + if (DOT == ch) { + isLastCharDot = true; + } else if (NEW_LINE_CHAR == ch) { + break; + } else if (isDoubleQuoteAndEscaped(pretext, posForFindPrefix, ch)) { + --posForFindPrefix; + } else if (isLastCharDotOrNotQuotedString(isLastCharDot, isQuotedString) && DOUBLE_QUOTE == ch + && !isEscaped(pretext, posForFindPrefix)) { + isQuotedString = true; + isLastCharDot = false; + } else if (isQuotedString) { + isLastCharDot = false; + if (DOUBLE_QUOTE == ch && !isEscaped(pretext, posForFindPrefix)) { + isQuotedString = false; + } + } else if (isWhitespaceOrContainsWordBreakChar(workBreakCharList, ch)) { + break; + } else { + isLastCharDot = false; + } + + --posForFindPrefix; + } + + String retStr = pretext.substring(posForFindPrefix + 1, oldPos + 1); + retStr = retStr.trim(); + strList.add(retStr); + return posForFindPrefix; + } + + /** + * Checks if is whitespace or contains word break char. + * + * @param workBreakCharList the work break char list + * @param ch the ch + * @return true, if is whitespace or contains word break char + */ + private boolean isWhitespaceOrContainsWordBreakChar(List workBreakCharList, char ch) { + return Character.isWhitespace(ch) || (!workBreakCharList.isEmpty() && workBreakCharList.contains(ch)); + } + + /** + * Checks if is double quote and escaped. + * + * @param pretext the pretext + * @param pos the pos + * @param ch the ch + * @return true, if is double quote and escaped + */ + private boolean isDoubleQuoteAndEscaped(String pretext, int pos, char ch) { + return DOUBLE_QUOTE == ch && isEscaped(pretext, pos); + } + + /** + * Checks if is last char dot or not quoted string. + * + * @param isLastCharDot the is last char dot + * @param isQuotedString the is quoted string + * @return true, if is last char dot or not quoted string + */ + private boolean isLastCharDotOrNotQuotedString(boolean isLastCharDot, boolean isQuotedString) { + return isLastCharDot || !isQuotedString; + } + + /** + * Remove literal escapes and quotes. + * + * @param str the str + * @return the string + */ + @Override + public String removeLiteralEscapesAndQuotes(String str) { + int strLen = str.length(); + StringBuilder blr = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + char ch = '\0'; + int pos = 0; + boolean isLower = false; + boolean isUpper = false; + + if (strLen > 1 && str.charAt(pos) == DOUBLE_QUOTE && str.charAt(strLen - 1) == DOUBLE_QUOTE) { + // Skip the first and last quotes (for quoted strings only) + pos++; + strLen--; + } else { + // Non Quoted strings will be handled as lower case by Gauss, then + // lets convert to lower + isLower = database.isLowerCase(); + isUpper = database.isUpperCase(); + + } + + for (; pos < strLen; pos++) { + ch = str.charAt(pos); + if (ESCAPE_CHAR == ch && isEscapedLiteral(str, pos)) { + // Remove the escape char + pos++; + ch = str.charAt(pos); + } + blr.append(isLower ? Character.toLowerCase(ch) : isUpper ? Character.toUpperCase(ch) : ch); + } + + return blr.toString(); + } + + /** + * Split prefix by dots. + * + * @param prefix the prefix + * @return the string[] + */ + @Override + public String[] splitPrefixByDots(String prefix) { + int prefixLen = prefix.length(); + ArrayList prefixParts = new ArrayList(); + boolean isStartNewPart = true; + boolean isQuotedString = false; + boolean isEscapedByLastChar = false; + StringBuilder blr = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + char ch = '\0'; + + for (int pos = 0; pos < prefixLen; pos++) { + ch = prefix.charAt(pos); + + if (DOT == ch && !isQuotedString) { + // If its not new part already + prefixParts.add(blr.toString()); + // If start of new word then create new string build. + blr = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + isStartNewPart = true; + } else if (ESCAPE_CHAR == ch && isEscapedLiteral(prefix, pos)) { + blr.append(ch); + + // consume next EscapeChar char, no need of maintaining the + // state + blr.append(prefix.charAt(pos)); + pos++; + } else if (isQuotedString) { + if (DOUBLE_QUOTE == ch && !isEscapedByLastChar) { + blr.append(ch); + // Finish of quoted word + prefixParts.add(blr.toString()); + // If start of new word then create new string build. + blr = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + isQuotedString = false; + isStartNewPart = true; + + // consume next DOT char + if ((pos + 1) < prefixLen && DOT == prefix.charAt(pos + 1)) { + pos++; + } + } else { + // Consume the quoted string content + blr.append(ch); + isEscapedByLastChar = false; + isStartNewPart = false; + } + } else if (DOUBLE_QUOTE == ch && !isEscapedByLastChar) { + // Start of a quoted string + isQuotedString = true; + isStartNewPart = true; + blr.append(ch); + } else { + // Consume the unquoted string content + blr.append(ch); + isEscapedByLastChar = false; + isStartNewPart = false; + } + } + + if (!isStartNewPart) { + // If any unfinished content found, added to list. + prefixParts.add(blr.toString()); + } + + return prefixParts.toArray(new String[prefixParts.size()]); + } + + /** + * Gets the prefix hyper link. + * + * @param searchPrefix the search prefix + * @return the prefix hyper link + */ + @Override + public String[] getPrefixHyperLink(String searchPrefix) { + String[] prefixes = searchPrefix.split("\\."); + String quoteRmvdstr = null; + + List arrListolap = new ArrayList(5); + String str = null; + if (searchPrefix.contains("\"")) { + for (int i = 0; i < prefixes.length; i++) { + str = prefixes[i].trim(); + if (str.endsWith("\"")) { + if (str.contains("\"\"")) { + quoteRmvdstr = str.replaceAll("^\"|\"$", ""); + quoteRmvdstr = quoteRmvdstr.replace("\"\"", "\""); + arrListolap.add(quoteRmvdstr); + } else { + if (str.contains("\"")) { + quoteRmvdstr = str.replaceAll("^\"|\"$", ""); + arrListolap.add(quoteRmvdstr); + } + } + } else { + quoteRmvdstr = str; + arrListolap.add(quoteRmvdstr); + } + } + prefixes = arrListolap.toArray(new String[arrListolap.size()]); + } + return prefixes; + } + + /** + * Find matching keywords. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findMatchingKeywords(String prefix) { + ContentAssistKeywords.getInstance().loadKeywords(database); + return ContentAssistKeywords.getInstance().findMatchingOLAPKeyword(prefix); + } + + /** + * Find matching dataypes. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findMatchingDataypes(String prefix) { + return database.findMatchingDatatype(prefix); + } + + @Override + public SortedMap getChildObject(SortedMap found, + boolean isParentDescNeeded) { + SortedMap resultMap = new TreeMap(); + for (ServerObject obj : found.values()) { + if (obj instanceof ColumnMetaData) { + ColumnMetaData clm = (ColumnMetaData) obj; + resultMap.put(clm.getClmNameWithDatatype(isParentDescNeeded), obj); + } else if (obj instanceof ViewColumnMetaData) { + ViewColumnMetaData clm = (ViewColumnMetaData) obj; + resultMap.put(clm.getClmNameWithDatatype(isParentDescNeeded), obj); + } + } + return resultMap; + } + + /** + * Find matching trigger object. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findMatchingTriggerObject(String prefix) { + return new TreeMap(); + } + + /** + * Find exact matching triggers. + * + * @param prefix the prefix + * @return the sorted map + */ + @Override + public SortedMap findExactMatchingTriggers(String prefix) { + return new TreeMap(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/contentassist/ISQLContentAssistProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/contentassist/ISQLContentAssistProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..dbc9e1c893afc08d71860b8183ed6fedc26cc5b4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/contentassist/ISQLContentAssistProcessor.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.contentassist; + +import java.util.LinkedHashMap; +import java.util.SortedMap; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; + +/** + * + * Title: interface + * + * Description: The Interface ISQLContentAssistProcessor. + * + */ + +public interface ISQLContentAssistProcessor { + + /** + * Find prefix matching objects. + * + * @param prefix the prefix + * @return the sorted map + */ + SortedMap findPrefixMatchingObjects(String prefix); + + /** + * Find exact matching objects. + * + * @param prefix the prefix + * @return the sorted map + */ + SortedMap findExactMatchingObjects(String prefix); + + /** + * Find non loaded objects. + * + * @param connection the connection + * @param prefixs the prefixs + * @return the sorted map + * @throws MPPDBIDEException the MPPDBIDE exception + */ + LinkedHashMap findNonLoadedObjects(DBConnection connection, String[] prefixs) + throws MPPDBIDEException; + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/AbstractERAssociation.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/AbstractERAssociation.java new file mode 100644 index 0000000000000000000000000000000000000000..0eb77f50b667cc9e0892f79bf0b6f41e0bee712f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/AbstractERAssociation.java @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.erd.model; + +/** + * Title: AbstractERAssociation + * + * @since 3.0.0 + */ +public abstract class AbstractERAssociation { + /** + * The association. + */ + protected AbstractERConstraint association; + + /** + * The association num. + */ + protected int associationNum; + + /** + * The source entity. + */ + protected AbstractEREntity sourceEntity; + + /** + * The target entity. + */ + protected AbstractEREntity targetEntity; + + /** + * Instantiates a new abstract ER association. + * + * @param association the association + * @param sourceEntity the source entity + * @param targetEntity the target entity + */ + public AbstractERAssociation(AbstractERConstraint association, AbstractEREntity sourceEntity, + AbstractEREntity targetEntity) { + this.association = association; + this.sourceEntity = sourceEntity; + this.targetEntity = targetEntity; + } + + /** + * Gets the association. + * + * @return the association + */ + public AbstractERConstraint getAssociation() { + return association; + } + + /** + * Sets the association. + * + * @param association the new association + */ + public void setAssociation(AbstractERConstraint association) { + this.association = association; + } + + /** + * Gets the association num. + * + * @return the association num + */ + public int getAssociationNum() { + return associationNum; + } + + /** + * Sets the association num. + * + * @param associationNum the new association num + */ + public void setAssociationNum(int associationNum) { + this.associationNum = associationNum; + } + + /** + * Gets the source entity. + * + * @return the source entity + */ + public AbstractEREntity getSourceEntity() { + return sourceEntity; + } + + /** + * Sets the source entity. + * + * @param sourceEntity the new source entity + */ + public void setSourceEntity(AbstractEREntity sourceEntity) { + this.sourceEntity = sourceEntity; + } + + /** + * Gets the target entity. + * + * @return the target entity + */ + public AbstractEREntity getTargetEntity() { + return targetEntity; + } + + /** + * Sets the target entity. + * + * @param targetEntity the new target entity + */ + public void setTargetEntity(AbstractEREntity targetEntity) { + this.targetEntity = targetEntity; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/AbstractERAttribute.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/AbstractERAttribute.java new file mode 100644 index 0000000000000000000000000000000000000000..c610478663e0cbec365276cde2e36eb6e68a4364 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/AbstractERAttribute.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.erd.model; + +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; + +/** + * Title: IERAttribute + * + * @since 3.0.0 + */ +public abstract class AbstractERAttribute extends AbstractERNode { + /** + * The in primary key. + */ + protected boolean inPrimaryKey; + + /** + * The in foreign key. + */ + protected boolean inForeignKey; + + /** + * The comments. + */ + protected String comments; + + /** + * Instantiates a new abstract ER attribute. + * + * @param serverObject the server object + * @param inPrimaryKey the in primary key + * @param inForeignKey the in foreign key + */ + public AbstractERAttribute(ServerObject serverObject, boolean inPrimaryKey, boolean inForeignKey) { + super(serverObject); + this.inPrimaryKey = inPrimaryKey; + this.inForeignKey = inForeignKey; + } + + /** + * Checks if is in primary key. + * + * @return true, if is in primary key + */ + public boolean isInPrimaryKey() { + return inPrimaryKey; + } + + /** + * Checks if is in foreign key. + * + * @return true, if is in foreign key + */ + public boolean isInForeignKey() { + return inForeignKey; + } + + /** + * Gets the data types. + * + * @return the data types + */ + public abstract String getDataTypes(); + + /** + * Gets the comments. + * + * @return the comments + */ + public String getComments() { + return comments; + } + + /** + * Sets the comments. + * + * @param comments the new comments + */ + public void setComments(String comments) { + this.comments = comments; + } + + /** + * Gets the nullability. + * + * @return the nullability + */ + public abstract String getNullability(); + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + return serverObject.getName(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/AbstractERConstraint.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/AbstractERConstraint.java new file mode 100644 index 0000000000000000000000000000000000000000..09bee50cbcc250272f29f28657cd10be55823a3a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/AbstractERConstraint.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.erd.model; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; + +/** + * Title: AbstractERConstraint + * + */ + +public abstract class AbstractERConstraint { + /** + * The cons type. + */ + protected String consType; + + /** + * the column id List. + */ + protected List keyColIndex; + + /** + * Gets the cons type. + * + * @return the cons type + */ + public String getConsType() { + return consType; + } + + /** + * set the cons type. + * + * @param consType the new cons type + */ + public void setConsType(String consType) { + this.consType = consType; + } + + /** + * Sets the constraint info. + * + * @param rs the rs + * @param constraints the constraints + * @throws SQLException the SQL exception + */ + public abstract void setConstraintInfo(ResultSet rs, List constraints) throws SQLException; + + /** + * Gets the keys type full name. + * + * @param keyType the key type + * @return the keys type full name + */ + public static String getKeysTypeFullName(String keyType) { + if ("P".equalsIgnoreCase(keyType)) { + return IERNodeConstants.PRIMARY_KEY; + } else if ("U".equalsIgnoreCase(keyType)) { + return IERNodeConstants.UNIQUE_KEY; + } else { + return IERNodeConstants.FOREIGN_KEY; + } + } + + /** + * Gets the Key columns index. + * + * @return the Key columns index. + */ + public List getKeyColIndex() { + return keyColIndex; + } + + /** + * Sets the Key columns index. + * + * @param keyColIndex the new Key columns index. + */ + public void setKeyColIndex(List keyColIndex) { + this.keyColIndex = keyColIndex; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/AbstractEREntity.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/AbstractEREntity.java new file mode 100644 index 0000000000000000000000000000000000000000..8b7eb7d7c47295b1a0d63bd11ca0caaa4bb7780a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/AbstractEREntity.java @@ -0,0 +1,250 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.erd.model; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * Title: AbstractEREntity + * + * @since 3.0.0 + */ +public abstract class AbstractEREntity extends AbstractERNode { + /** + * The dbcon. + */ + protected DBConnection dbcon; + + /** + * The is current table. + */ + protected boolean isCurrentTable; + + /** + * The attributes. + */ + protected List attributes; + + /** + * The constraints. + */ + protected List constraints; + + /** + * The column comments. + */ + protected Map columnComments; + + /** + * The has column comments. + */ + protected boolean hasColumnComments; + + /** + * The has not null columns. + */ + protected boolean hasNotNullColumns; + + /** + * Instantiates a new abstract ER entity. + * + * @param serverObject the server object + * @param isCurrentTable the is current table + * @param dbcon the dbcon + */ + public AbstractEREntity(ServerObject serverObject, boolean isCurrentTable, DBConnection dbcon) { + super(serverObject); + this.isCurrentTable = isCurrentTable; + this.dbcon = dbcon; + this.attributes = new ArrayList<>(); + this.constraints = new ArrayList<>(); + this.columnComments = new HashMap(); + } + + /** + * Inits the ER entity. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws SQLException the SQL exception + */ + public abstract void initEREntity() throws DatabaseCriticalException, DatabaseOperationException, SQLException; + + /** + * Gets the dbcon. + * + * @return the dbcon + */ + public DBConnection getDbcon() { + return dbcon; + } + + /** + * Gets the attributes. + * + * @return the attributes + */ + public List getAttributes() { + return attributes; + } + + /** + * Adds the attribute. + * + * @param attribute the attribute + */ + public void addAttribute(AbstractERAttribute attribute) { + if (attributes == null) { + attributes = new ArrayList<>(); + } + if (attributes.contains(attribute)) { + throw new IllegalArgumentException("Attribute already present"); + } + attributes.add(attribute); + } + + /** + * filling the contraints info for EREntity. + * + * @param dbcon the dbcon + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + protected abstract void fillConstraints(DBConnection dbcon) + throws DatabaseCriticalException, DatabaseOperationException; + + /** + * filling the column comments info for EREntity. + * + * @param dbcon the dbcon + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws SQLException the SQL exception + */ + public abstract void fillColumnComments(DBConnection dbcon) + throws DatabaseCriticalException, DatabaseOperationException, SQLException; + + /** + * filling the attributes info for EREntity. + */ + protected abstract void fillAttributes(); + + /** + * Gets the fully qualified name. + * + * @return the fully qualified name + */ + public abstract String getFullyQualifiedName(); + + /** + * Gets the table comments. + * + * @return the table comments + */ + public abstract String getTableComments(); + + /** + * Checks if is current table. + * + * @return true, if is current table + */ + public boolean isCurrentTable() { + return isCurrentTable; + } + + /** + * Gets the column comments. + * + * @return the column comments + */ + public Map getColumnComments() { + return columnComments; + } + + /** + * Gets the constraints. + * + * @return the constraints + */ + public List getConstraints() { + return constraints; + } + + /** + * Sets the has column comments. + */ + public void setHasColumnComments() { + for (AbstractERAttribute attribute : attributes) { + if (attribute.getComments() != null) { + this.hasColumnComments = true; + return; + } + } + + this.hasColumnComments = false; + } + + /** + * Sets the has not null columns. + */ + public void setHasNotNullColumns() { + for (AbstractERAttribute attribute : attributes) { + if (attribute.getNullability().equals("NOT NULL")) { + this.hasNotNullColumns = true; + return; + } + } + + this.hasNotNullColumns = false; + } + + /** + * Checks if is checks for column comments. + * + * @return true, if is checks for column comments + */ + public boolean isHasColumnComments() { + return hasColumnComments; + } + + /** + * Checks if is checks for not null columns. + * + * @return true, if is checks for not null columns + */ + public boolean isHasNotNullColumns() { + return hasNotNullColumns; + } + + /** + * Gets the name. + * + * @return the name + */ + @Override + public String getName() { + return serverObject.getName(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/AbstractERNode.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/AbstractERNode.java new file mode 100644 index 0000000000000000000000000000000000000000..72b451f572ed93c1df0815c2e404c949d5fa8201 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/AbstractERNode.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.erd.model; + +/** + * Title: AbstractERNode + * + */ + +public abstract class AbstractERNode { + + /** + * The server object. + */ + protected OBJECT serverObject; + + public AbstractERNode() { + + } + + public AbstractERNode(OBJECT serverObject) { + this.serverObject = serverObject; + } + + /** + * Gets the server object. + * + * @return the server object + */ + public Object getServerObject() { + return serverObject; + } + + /** + * Gets the name. + * + * @return the name + */ + public abstract String getName(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/ERAttribute.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/ERAttribute.java new file mode 100644 index 0000000000000000000000000000000000000000..bfd6956f657a82b32edc6f14590b856c22302b07 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/ERAttribute.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.erd.model; + +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; + +/** + * Title: ERAttribute + * + * @since 3.0.0 + */ +public class ERAttribute extends AbstractERAttribute { + + public ERAttribute(ColumnMetaData serverObject, boolean inPrimaryKey, boolean inForeignKey) { + super(serverObject, inPrimaryKey, false); + } + + @Override + public String getNullability() { + return ((ColumnMetaData) serverObject).isNotNull() ? "NOT NULL" : ""; + } + + @Override + public ColumnMetaData getServerObject() { + return (ColumnMetaData) serverObject; + } + + @Override + public String getDataTypes() { + return ((ColumnMetaData) serverObject).getDisplayDatatype(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/ERConstraint.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/ERConstraint.java new file mode 100644 index 0000000000000000000000000000000000000000..6025775ca145925bcaa401896200873217953136 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/ERConstraint.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.erd.model; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * Title: ERConstraint + */ + +public class ERConstraint extends AbstractERConstraint { + + @Override + public void setConstraintInfo(ResultSet rs, List constraints) throws SQLException { + ERConstraint keyData = new ERConstraint(); + keyData.setConsType(getKeysTypeFullName(rs.getString(IERNodeConstants.OLAP_CONSTRAINT_TYPE))); + keyData.setKeyColIndex(getKeyColIndexFormStr(rs.getString(IERNodeConstants.OLAP_COLUMN_LIST))); + constraints.add(keyData); + } + + /** + * + * @Title: getKeyColIndexFormStr + * @Description: transform the string colList to List + * @param colList: the column id list string query from db. + * @return keyColList : the column id list. + * + */ + public List getKeyColIndexFormStr(String colList) { + List keyColList = new ArrayList<>(); + if (colList != null) { + String colString = colList.substring(1, colList.length() - 1); + String[] colIndexList = colString.split("\\" + MPPDBIDEConstants.COMMA_SEPARATE); + for (String str : colIndexList) { + keyColList.add(Long.valueOf(str)); + } + } + + return keyColList; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/EREntity.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/EREntity.java new file mode 100644 index 0000000000000000000000000000000000000000..cb7219e8497a9dd08f10e9c1c03bf4c49d880ccf --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/EREntity.java @@ -0,0 +1,198 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.erd.model; + +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.groups.OLAPObjectList; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * Title: EREntity + */ + +public class EREntity extends AbstractEREntity { + + private String tableComments; + + /** + * Instantiates a new ER entity. + * + * @param serverObject the server object + * @param isCurrentTable the is current table + * @param dbcon the dbcon + */ + public EREntity(TableMetaData serverObject, boolean isCurrentTable, DBConnection dbcon) { + super(serverObject, isCurrentTable, dbcon); + } + + /** + * Inits the ER entity. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws SQLException the SQL exception + */ + @Override + public void initEREntity() throws DatabaseCriticalException, DatabaseOperationException, SQLException { + fillConstraints(dbcon); + fillTableComments(dbcon); + fillColumnComments(dbcon); + fillAttributes(); + setHasColumnComments(); + setHasNotNullColumns(); + } + + /** + * filling the column comments info for EREntity. + * + * @param dbcon the dbcon + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws SQLException the SQL exception + */ + @Override + public void fillColumnComments(DBConnection dbcon) + throws DatabaseCriticalException, DatabaseOperationException, SQLException { + String olapTableConstraintDetailsQuery = ERQueryBuilder.getOLAPColumnCommentsQuery(serverObject); + ResultSet rs = dbcon.execSelectAndReturnRs(olapTableConstraintDetailsQuery); + boolean hasNext = false; + try { + hasNext = rs.next(); + while (hasNext) { + columnComments.put(rs.getString(IERNodeConstants.OLAP_ATTRIBUTE_NAME), + rs.getString(IERNodeConstants.OLAP_DESCRIPTION)); + hasNext = rs.next(); + } + } catch (SQLException sqlException) { + GaussUtils.handleCriticalException(sqlException); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, sqlException); + } finally { + dbcon.closeResultSet(rs); + } + } + + /** + * Fill table comments. + * + * @param dbcon the dbcon + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void fillTableComments(DBConnection dbcon) throws DatabaseCriticalException, DatabaseOperationException { + String olapTableConstraintDetailsQuery = ERQueryBuilder.getOLAPTableCommentsQuery(serverObject); + ResultSet rs = dbcon.execSelectAndReturnRs(olapTableConstraintDetailsQuery); + boolean hasNext = false; + try { + hasNext = rs.next(); + while (hasNext) { + tableComments = rs.getString(IERNodeConstants.OLAP_DESCRIPTION); + hasNext = rs.next(); + } + } catch (SQLException sqlException) { + GaussUtils.handleCriticalException(sqlException); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, sqlException); + } finally { + dbcon.closeResultSet(rs); + } + } + + /** + * filling the attributes info for EREntity. + */ + @Override + public void fillAttributes() { + OLAPObjectList columns = getServerObject().getColumns(); + for (ColumnMetaData column : columns.getList()) { + boolean inPrimaryKey = false; + for (AbstractERConstraint constraint : getConstraints()) { + ERConstraint cons = (ERConstraint) constraint; + if (cons.getConsType().equals(IERNodeConstants.PRIMARY_KEY) + && cons.getKeyColIndex().contains(column.getOid())) { + inPrimaryKey = true; + break; + } + } + ERAttribute attribute = new ERAttribute(column, inPrimaryKey, false); + attribute.setComments(columnComments.get(attribute.getName())); + this.addAttribute(attribute); + } + } + + /** + * Fill constraints. + * + * @param dbcon the dbcon + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + @Override + public void fillConstraints(DBConnection dbcon) throws DatabaseCriticalException, DatabaseOperationException { + String olapTableConstraintDetails = ERQueryBuilder.getOLAPTableConstraintDetailsQuery(serverObject); + ResultSet rs = dbcon.execSelectAndReturnRs(olapTableConstraintDetails); + boolean hasNext = false; + try { + hasNext = rs.next(); + while (hasNext) { + ERConstraint constraint = new ERConstraint(); + constraint.setConstraintInfo(rs, constraints); + hasNext = rs.next(); + } + } catch (SQLException exp) { + GaussUtils.handleCriticalException(exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exp); + } finally { + dbcon.closeResultSet(rs); + } + } + + /** + * Gets the table comments. + * + * @return the table comments + */ + public String getTableComments() { + return tableComments; + } + + /** + * Gets the server object. + * + * @return the server object + */ + @Override + public TableMetaData getServerObject() { + return (TableMetaData) serverObject; + } + + /** + * Gets the fully qualified name. + * + * @return the fully qualified name + */ + @Override + public String getFullyQualifiedName() { + return ((TableMetaData) serverObject).getNameSpaceName() + "." + getName(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/ERQueryBuilder.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/ERQueryBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..fcef79e64d34c8d808607bd7b54813774ddb7f52 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/ERQueryBuilder.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.erd.model; + +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; + +/** + * Title: ERQueryBuilder + * + * @since 3.0.0 + */ +public class ERQueryBuilder { + /** + * Gets the olap column constraints info query. + * + * @param type the type + * @return the olap column constraints info query + */ + public static String getOLAPTableConstraintDetailsQuery(ServerObject serverObject) { + return "SELECT c.contype as constrainttype, c.conkey as columnlist" + + " FROM pg_constraint c where c.conrelid = " + serverObject.getOid() + ";"; + } + + /** + * Gets the olap table comments info query. + * + * @param type the type + * @return the olap table comments info query + */ + public static String getOLAPColumnCommentsQuery(ServerObject serverObject) { + return "SELECT a.attrelid,a.attname ,d.objsubid, d.description FROM pg_description d " + + "left join pg_attribute a on (d.objoid = a.attrelid and a.attnum = d.objsubid)" + " where d.objoid = " + + serverObject.getOid() + ';'; + } + + /** + * Gets the olap column comments info query. + * + * @param type the type + * @return the olap column constraints info query + */ + public static String getOLAPTableCommentsQuery(ServerObject serverObject) { + return "SELECT d.description FROM pg_description d " + "where d.objoid = " + serverObject.getOid() + + " and d.objsubid = 0;"; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/IERNodeConstants.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/IERNodeConstants.java new file mode 100644 index 0000000000000000000000000000000000000000..69cf8e52639c56f4f443eeede0c9004cbbcc8a43 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/erd/model/IERNodeConstants.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.erd.model; + +/** + * Title: ERNodeConstants + * + */ + +public interface IERNodeConstants { + + /** + * The primary key. + */ + String PRIMARY_KEY = "Primary key"; + + /** + * The unique key. + */ + String UNIQUE_KEY = "Unique key"; + + /** + * The foreign key. + */ + String FOREIGN_KEY = "Foreign key"; + + /** + * the Graph node property LABEL. + */ + String LABEL = "element-label"; + + /** + * the Graph node property NODE_PROPERTY. + */ + String NODE_PROPERTY = "node-property"; + + /** + * The owner name. + */ + String OWNER = "OWNER"; + + /** + * The table name. + */ + String TABLE_NAME = "TABLE_NAME"; + + /** + * The constraint name. + */ + String CONSTRAINT_NAME = "CONSTRAINT_NAME"; + + /** + * The constraint type. + */ + String CONSTRAINT_TYPE = "CONSTRAINT_TYPE"; + + /** + * the Foreign key constraint's referenced owner name. + */ + String R_OWNER = "R_OWNER"; + + /** + * The r table name. + */ + String R_TABLE_NAME = "R_TABLE_NAME"; + + /** + * the Foreign key constraint's referenced constraint name. + */ + String R_CONSTRAINT_NAME = "R_CONSTRAINT_NAME"; + + /** + * The col list. + */ + String COL_LIST = "COL_LIST"; + + /** + * the column name. + */ + String COLUMN_NAME = "COLUMN_NAME"; + + /** + * The comments. + */ + String COMMENTS = "COMMENTS"; + + /** + * The CHAR_USED + */ + String CHAR_USED = "CHAR_USED"; + + /** + * The constraint type. + */ + String OLAP_CONSTRAINT_TYPE = "constrainttype"; + + /** + * The column list. + */ + String OLAP_COLUMN_LIST = "columnlist"; + + /** + * The attribute name. + */ + String OLAP_ATTRIBUTE_NAME = "attname"; + + /** + * The description. + */ + String OLAP_DESCRIPTION = "description"; + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/errorlocator/AbstractErrorLocator.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/errorlocator/AbstractErrorLocator.java new file mode 100644 index 0000000000000000000000000000000000000000..58bed6addd18009983c4e89a96463199691c8b93 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/errorlocator/AbstractErrorLocator.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.errorlocator; + +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; + +/** + * + * Title: class + * + * Description: The Class AbstractErrorLocator. + * + */ + +public abstract class AbstractErrorLocator implements IErrorLocator { + + @Override + public int textStartOffset(String query, String text, int searchOffset) { + int qryStartOffset; + String[] qry = query.split(MPPDBIDEConstants.LINE_SEPARATOR); + qryStartOffset = text.indexOf(qry[0], searchOffset); + return qryStartOffset; + } + + @Override + public int textEndOffset(String query, String text, int searchOffset) { + int qryStartOffset = textStartOffset(query, text, searchOffset); + + // In some cases the end offset is 1 more than the actual + // length of the query itself. Added a safety condition + int qryEndOffset = qryStartOffset + query.length(); + if (qryEndOffset > text.length()) { + qryEndOffset = text.length(); + } + return qryEndOffset; + } + + /** + * error Line Number. + * + * @param qryStartOffset the qry start offset + * @param errorPos the error pos + * @return the int + */ + @Override + public abstract int errorLineNumber(int qryStartOffset, int errorPos); + + /** + * error Position. + * + * @param query the query + * @param qryStartOffset the qry start offset + * @param qryEndOffset the qry end offset + * @param startLineNo the start line no + * @param endLineNo the end line no + * @param exp the exp + * @return the int + */ + @Override + public abstract int errorPosition(String query, int qryStartOffset, int qryEndOffset, int startLineNo, + int endLineNo, MPPDBIDEException exp); + + /** + * error Message. + * + * @param text the text + * @param errorPos the error pos + * @param qryStartOffset the qry start offset + * @param qryEndOffset the qry end offset + * @return the string + */ + @Override + public abstract String errorMessage(String text, int errorPos, int qryStartOffset, int qryEndOffset); + + /** + * server Error Message. + * + * @param exp the exp + * @return the string + */ + @Override + public abstract String serverErrorMessage(MPPDBIDEException exp); + + /** + * Identify pos from qry err string. + * + * @param qryErrString the qry err string + * @return the int + */ + protected int identifyPosFromQryErrString(String qryErrString) { + int pos = 0; + + if (qryErrString.contains(" ")) { + + pos = qryErrString.indexOf(' '); + } + + else if (qryErrString.contains(MPPDBIDEConstants.LINE_SEPARATOR)) { + + pos = qryErrString.indexOf(MPPDBIDEConstants.LINE_SEPARATOR); + } + + else if (qryErrString.contains(";")) { + + pos = qryErrString.indexOf(';'); + } else { + pos = qryErrString.length(); + } + return pos; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/errorlocator/ErrorLocator.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/errorlocator/ErrorLocator.java new file mode 100644 index 0000000000000000000000000000000000000000..3153623e6fb115e83e904d23f2dc96a5b2afa906 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/errorlocator/ErrorLocator.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.errorlocator; + +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; + +/** + * + * Title: class + * + * Description: The Class ErrorLocator. + * + */ + +public class ErrorLocator extends AbstractErrorLocator { + + private static final String ERROR_POSITION_IDENTIFIER = "Position:"; + + @Override + public int errorPosition(String query, int qryStartOffset, int qryEndOffset, int startLineNo, int endLineNo, + MPPDBIDEException exp) { + String findPos = exp.getServerMessage(); + int errorPos = qryEndOffset - qryStartOffset; + errorPos++; + if (null != findPos) { + + int idx = findPos.lastIndexOf(ERROR_POSITION_IDENTIFIER); + + if (idx != -1) { + String newStr = findPos.substring(idx + ERROR_POSITION_IDENTIFIER.length()); + + if (newStr.contains(MPPDBIDEConstants.LINE_SEPARATOR)) { + newStr = newStr.substring(0, newStr.indexOf(MPPDBIDEConstants.LINE_SEPARATOR)); + } + + try { + errorPos = Integer.parseInt(newStr.trim()); + } catch (NumberFormatException ex) { + errorPos = qryEndOffset - qryStartOffset; + errorPos++; + } + } + } + + if (errorPos > query.length()) { + errorPos = query.length(); + } + + return errorPos + qryStartOffset; + } + + @Override + public String serverErrorMessage(MPPDBIDEException exp) { + return exp.getServerMessage(); + } + + @Override + public int errorLineNumber(int qryStartOffset, int errorPos) { + int errorLineNo = errorPos; + return errorLineNo; + } + + @Override + public String errorMessage(String text, int errorPos, int qryStartOffset, int qryEndOffset) { + String qryStr = text.substring(qryStartOffset, qryEndOffset); + + String qryErrString = qryStr.substring((errorPos - qryStartOffset) - 1); + int pos = identifyPosFromQryErrString(qryErrString); + String errorString = qryErrString.substring(0, pos); + + return errorString; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/errorlocator/IErrorLocator.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/errorlocator/IErrorLocator.java new file mode 100644 index 0000000000000000000000000000000000000000..72bf13af965762cf15d26254f18f2a8e154365e5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/errorlocator/IErrorLocator.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.errorlocator; + +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; + +/** + * + * Title: interface + * + * Description: The Interface IErrorLocator. + */ + +public interface IErrorLocator { + + /** + * Text start offset. + * + * @param query the query + * @param text the text + * @param searchOffset the search offset + * @return the int + */ + int textStartOffset(String query, String text, int searchOffset); + + /** + * Text end offset. + * + * @param query the query + * @param text the text + * @param qryStartOffset the qry start offset + * @param qryEndOffset the qry end offset + * @param searchOffset the search offset + * @return the int + */ + int textEndOffset(String query, String text, int searchOffset); + + /** + * Error line number. + * + * @param qryStartOffset the qry start offset + * @param errorPos the error pos + * @return the int + */ + int errorLineNumber(int qryStartOffset, int errorPos); + + /** + * Error position. + * + * @param query the query + * @param qryStartOffset the qry start offset + * @param qryEndOffset the qry end offset + * @param startLineNo the start line no + * @param endLineNo the end line no + * @param exp the exp + * @return the int + */ + int errorPosition(String query, int qryStartOffset, int qryEndOffset, int startLineNo, int endLineNo, + MPPDBIDEException exp); + + /** + * Error message. + * + * @param text the text + * @param errorPos the error pos + * @param qryStartOffset the qry start offset + * @param qryEndOffset the qry end offset + * @return the string + */ + String errorMessage(String text, int errorPos, int qryStartOffset, int qryEndOffset); + + /** + * Server error message. + * + * @param exp the exp + * @return the string + */ + String serverErrorMessage(MPPDBIDEException exp); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/executor/AbstractExecutor.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/executor/AbstractExecutor.java new file mode 100644 index 0000000000000000000000000000000000000000..5ae79bf0f1ad1c978131673cf19eefc483be1fab --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/executor/AbstractExecutor.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.executor; + +import org.opengauss.mppdbide.adapter.IConnectionDriver; +import org.opengauss.mppdbide.bl.serverdatacache.IDebugObject; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; +import org.opengauss.mppdbide.bl.util.ExecTimer; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.exceptions.UnknownException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: AbstractExecutor + * + * Description: AbstractExecutor + * + * @since 3.0.0 + */ +public abstract class AbstractExecutor implements ExecutorWrapper { + + /** + * The target executor. + */ + protected TargetExecutor targetExecutor; + + /** + * The is critical failure cleanup in progress. + */ + protected volatile boolean isCriticalFailureCleanupInProgress; + + /** + * Connect to server. + * + * @param serverInfo the server info + * @param iConnectionDriver the i connection driver + * @throws UnknownException the unknown exception + * @throws MPPDBIDEException the MPPDBIDE exception + */ + @Override + public void connectToServer(IServerConnectionInfo serverInfo, IConnectionDriver iConnectionDriver) + throws UnknownException, MPPDBIDEException { + try { + // Create target executor and connects to server. + targetExecutor = new TargetExecutor(); + targetExecutor.connect(serverInfo, iConnectionDriver); + MPPDBIDELoggerUtility.debug("Executor: Connected to target executor."); + + } catch (MPPDBIDEException exp) { + handleConnectFailure(); + throw exp; + } catch (Exception exp) { + handleConnectFailure(); + throw new UnknownException(IMessagesConstants.ERR_BL_CONNECT_FAILED, exp); + } + + } + + /** + * * Handle connection failure, performs the following operations: 1) Try + * disconnecting debug/query/target executor and 2) Log in case of + * exception. When to call - connectToServer failure case + */ + private void handleConnectFailure() { + + // Check if target executor is created. + if (null != targetExecutor) { + // Disconnect target executor's connection. + targetExecutor.disconnect(); + targetExecutor = null; + } + } + + /** + * Disconnect. + */ + public abstract void disconnect(); + + /** + * Gets the query exectuion string. + * + * @param dbgobj the dbgobj + * @return the query exectuion string + * @throws DatabaseOperationException the database operation exception + */ + public void getQueryExectuionString(IDebugObject dbgobj) throws DatabaseOperationException { + checkIsCriticalExceptionOccurred(); + + MPPDBIDELoggerUtility.debug("Executor: Get execution string."); + targetExecutor.getQueryExectuionString(dbgobj); + } + + /** + * Check is critical exception occurred. + * + * @throws DatabaseOperationException the database operation exception + */ + public void checkIsCriticalExceptionOccurred() throws DatabaseOperationException { + if (isCriticalFailureCleanupInProgress) { + if (MPPDBIDELoggerUtility.isDebugEnabled()) { + MPPDBIDELoggerUtility.debug("Executor: critical exception " + + "cleanup is already in progress, so skipping the" + " current operation."); + } + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_BL_SERVER_CONNECTION_FAILED)); + throw new DatabaseOperationException(IMessagesConstants.ERR_BL_SERVER_CONNECTION_FAILED); + } + } + + /** + * Fetch server IP. + * + * @return the string + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public String fetchServerIP() throws DatabaseOperationException, DatabaseCriticalException { + return null; + } + + /** + * Gets the server version. + * + * @return the server version + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public String getServerVersion() throws DatabaseOperationException, DatabaseCriticalException { + return null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/executor/Executor.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/executor/Executor.java new file mode 100644 index 0000000000000000000000000000000000000000..6de107dad6dfb8b7815f0a54577dabd2465b3b92 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/executor/Executor.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.executor; + +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class Executor. + * + */ + +public class Executor extends AbstractExecutor { + + /** + * Instantiates a new executor. + * + * @param db the db + */ + public Executor() { + } + + /** + * Gets the server version. + * + * @return the server version + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public String getServerVersion() throws DatabaseOperationException, DatabaseCriticalException { + return targetExecutor.getServerVersion(); + } + + /** + * Fetch server IP. + * + * @return the string + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public String fetchServerIP() throws DatabaseOperationException, DatabaseCriticalException { + return targetExecutor.fetchServerIP(); + } + + /** + * Disconnect. + */ + public void disconnect() { + MPPDBIDELoggerUtility.info("Executor: Disconnecting debug connection."); + + MPPDBIDELoggerUtility.info("Executor: Disconnecting target connection."); + // Disconnecting target Executor. + if (null != targetExecutor) { + disconnectTargetExecutor(); + } + MPPDBIDELoggerUtility.info("Executor: Disconnecting query connection."); + } + + private void disconnectTargetExecutor() { + addLoggerForDisconnectTargetExec(); + targetExecutor.disconnect(); + targetExecutor = null; + } + + private void addLoggerForDisconnectTargetExec() { + if (MPPDBIDELoggerUtility.isInfoEnabled()) { + MPPDBIDELoggerUtility.info("Executor: Skipping set debug off" + " to avoid crash"); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/executor/ExecutorWrapper.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/executor/ExecutorWrapper.java new file mode 100644 index 0000000000000000000000000000000000000000..1694d54d132b96be39ceb7ea0c52f3945ef8b223 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/executor/ExecutorWrapper.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.executor; + +import org.opengauss.mppdbide.adapter.IConnectionDriver; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.exceptions.UnknownException; + +/** + * + * Title: ExecutorWrapper + * + * Description:ExecutorWrapper + * + * @since 3.0.0 + */ +public interface ExecutorWrapper { + + /** + * Connect to server. + * + * @param serverInfo the server info + * @param iConnectionDriver the i connection driver + * @throws UnknownException the unknown exception + * @throws MPPDBIDEException the MPPDBIDE exception + */ + void connectToServer(IServerConnectionInfo serverInfo, IConnectionDriver iConnectionDriver) + throws UnknownException, MPPDBIDEException; + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/executor/TargetExecutor.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/executor/TargetExecutor.java new file mode 100644 index 0000000000000000000000000000000000000000..f074c4a06973b9e6334c3d5e34d9d5373c46d4df --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/executor/TargetExecutor.java @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.executor; + +import java.util.ArrayList; + +import org.opengauss.mppdbide.adapter.IConnectionDriver; +import org.opengauss.mppdbide.bl.adapter.gauss.GaussConnection; +import org.opengauss.mppdbide.bl.serverdatacache.IDebugObject; +import org.opengauss.mppdbide.bl.serverdatacache.ObjectParameter; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class TargetExecutor. + * + */ + +public class TargetExecutor { + + private GaussConnection connection; + private boolean isConnected; + private final Object targetConnectionLock = new Object(); + + /** + * Connect. + * + * @param connectionInfo the connection info + * @param iConnectionDriver the i connection driver + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public void connect(IServerConnectionInfo connectionInfo, IConnectionDriver iConnectionDriver) + throws MPPDBIDEException { + + MPPDBIDELoggerUtility.debug("TargetExecutor: connecting to server."); + try { + synchronized (targetConnectionLock) { + connection = new GaussConnection(iConnectionDriver); + connection.connect(connectionInfo); + + isConnected = true; + } + } catch (MPPDBIDEException exp) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_BL_CONNECT_FAILED), exp); + throw new MPPDBIDEException(IMessagesConstants.ERR_BL_CONNECT_FAILED, exp); + } + + } + + /** + * Disconnect. + */ + public void disconnect() { + MPPDBIDELoggerUtility.debug("TargetExecutor: disconnecting from server."); + synchronized (targetConnectionLock) { + if (isConnected) { + connection.dbDisconnect(); + } + + isConnected = false; + } + + } + + /** + * Gets the query exectuion string. + * + * @param dbgobj the dbgobj + * @return the query exectuion string + * @throws DatabaseOperationException the database operation exception + */ + public void getQueryExectuionString(IDebugObject dbgobj) throws DatabaseOperationException { + MPPDBIDELoggerUtility.debug("Get query execution string."); + String needExecuteSqlString = null; + synchronized (targetConnectionLock) { + needExecuteSqlString = getOLAPQueryStatementString(dbgobj); + dbgobj.setExecutionQuery(needExecuteSqlString); + } + } + + /** + * Gets the OLAP query statement string. + * + * @param dbgobj the dbgobj + * @return the OLAP query statement string + * @Title: getOLAPQueryStatementString + * @Description: get OLAP Query Statement + */ + private String getOLAPQueryStatementString(IDebugObject dbgobj) { + StringBuilder template = new StringBuilder("SELECT"); + ArrayList templateParameters = dbgobj.getTemplateParameters(); + template.append(" "); + template.append("\"" + dbgobj.getNamespace().getName() + "\"").append("."); + template.append(ServerObject.getQualifiedObjectName(dbgobj.getName())); + + template.append("("); + + if (null != templateParameters && templateParameters.size() > 0) { + ObjectParameter param = null; + boolean isFirstParam = true; + String argValue = null; + int paramSize = templateParameters.size(); + + for (int i1 = 0; i1 < paramSize; i1++) { + param = templateParameters.get(i1); + + switch (param.getType()) { + case IN: + case INOUT: { + if (!isFirstParam) { + template.append(", "); + } + + argValue = param.getValue(); + + if (MPPDBIDEConstants.UNKNOWN_DATATYPE_STR.equals(param.getDataType())) { + template.append(argValue); + } else { + if (null != argValue) { + appendTemplate(template, param, argValue); + } + } + + break; + } + default: { + break; + } + } + + isFirstParam = false; + } + } + + template.append(")"); + return template.toString(); + } + + private void appendTemplate(StringBuilder template, ObjectParameter param, String argValue) { + if ("null".equalsIgnoreCase(argValue)) { + template.append("null"); + } else { + if (argValue.charAt(0) != '\'') { + template.append("'").append(argValue).append("'"); + } else { + template.append(argValue); + } + appendDataTypeForTemplate(param.getDataType(), template); + } + } + + /** + * Append data type for template. + * + * @param dataType the param + * @param template the template + */ + private void appendDataTypeForTemplate(String dataType, StringBuilder template) { + if (null != dataType && ("char".equalsIgnoreCase(dataType) || "bpchar".equalsIgnoreCase(dataType))) { + template.append("::").append("varchar"); + } else { + template.append("::").append(dataType); + } + } + + /** + * Gets the server version. + * + * @return the server version + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + + public String getServerVersion() throws DatabaseOperationException, DatabaseCriticalException { + MPPDBIDELoggerUtility.debug("TargetExecutor: Get server version."); + synchronized (targetConnectionLock) { + return connection.getVersion(); + } + } + + /** + * Fetch server IP. + * + * @return the string + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public String fetchServerIP() throws DatabaseOperationException, DatabaseCriticalException { + MPPDBIDELoggerUtility.debug("TargetExecutor: Get server IP."); + synchronized (targetConnectionLock) { + return connection.getServerIP1(); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/BatchExportDDLFilter.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/BatchExportDDLFilter.java new file mode 100644 index 0000000000000000000000000000000000000000..d3efa78bbb9906b6dda45eec82eda94c188e5c77 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/BatchExportDDLFilter.java @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.export; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CodingErrorAction; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.Predicate; + +import org.apache.commons.io.input.BOMInputStream; + +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.MaxLineBufferedReader; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.FileOperationException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class BatchExportDDLFilter. + * + */ + +public class BatchExportDDLFilter { + + private static final int MAX_LINE_LEN = 8192; + final BufferedOutputStream bfs; + String encoding = null; + + private static final String[] LINESTOREMOVE = {"PostgreSQL database dump", "Dumped from database version", + "Dumped by gs_dump version", "SET statement_timeout", "SET client_encoding", "SET standard_conforming_strings", + "SET check_function_bodies", "SET client_min_messages", "SET default_with_oids"}; + /* + * if any line in LINESTOREMOVE has length grater than MAX_CHAR_LEN, + * accept() function has to change + */ + private static final String SINGLE_LINE_COMMENT_PREFIX = "--"; + + private static boolean stringContainsItemFromList(final String inputStr) { + return Arrays.stream(LINESTOREMOVE).parallel().anyMatch(new Predicate() { + + @Override + public boolean test(String str) { + return inputStr.contains(str); + } + }); + } + + /** + * Instantiates a new batch export DDL filter. + * + * @param fs the fs + */ + public BatchExportDDLFilter(BufferedOutputStream fs) { + this.bfs = fs; + String fileEncoding = BLPreferenceManager.getInstance().getBLPreference().getFileEncoding(); + encoding = fileEncoding.isEmpty() ? Charset.defaultCharset().name() : fileEncoding; + } + + private boolean test(String line) { + return !stringContainsItemFromList(line) && !line.equals(SINGLE_LINE_COMMENT_PREFIX); + } + + private void accept(List lines) throws IOException { + boolean testfail = false; + for (String str : lines) { + if (!test(str)) { + testfail = true; + } + } + if (testfail) { + return; + } + for (String s : lines) { + byte[] bytes = s.getBytes(encoding); + bfs.write(bytes); + } + + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append(MPPDBIDEConstants.LINE_SEPARATOR); + byte[] bytes = sb.toString().getBytes(encoding); + bfs.write(bytes); + } + + /** + * Removes the comments. + * + * @param filepath the filepath + * @throws FileOperationException the file operation exception + */ + public void removeComments(String filepath) throws FileOperationException { + File file = new File(filepath); + + FileInputStream input = null; + MaxLineBufferedReader mf = null; + try { + input = new FileInputStream(file); + mf = readFile(input); + } catch (IOException e) { + MPPDBIDELoggerUtility.debug("BatchExportDDLFilter: Error while removing comments"); + throw new FileOperationException(IMessagesConstants.ERR_IO_ERROR_EXPORT); + } catch (DatabaseOperationException e) { + MPPDBIDELoggerUtility.debug("BatchExportDDLFilter: Error while removing comments"); + throw new FileOperationException(IMessagesConstants.ERR_IO_ERROR_EXPORT); + } finally { + try { + if (mf != null) { + mf.close(); + } + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("BatchExportDDLFilter: Error while closing max line buffered reader", + exception); + } + + try { + if (input != null) { + input.close(); + } + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("BatchExportDDLFilter: Error while closing stream", exception); + } + + try { + Files.deleteIfExists(Paths.get(filepath)); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("BatchExportDDLFilter: Error while deleting file", exception); + } + } + } + + private MaxLineBufferedReader readFile(FileInputStream input) throws DatabaseOperationException, IOException { + MaxLineBufferedReader mf = null; + CharsetDecoder decoder = Charset.forName(encoding).newDecoder(); + if (decoder != null) { + decoder.onMalformedInput(CodingErrorAction.IGNORE); + BOMInputStream bomInputStream = new BOMInputStream(input); + InputStreamReader reader = new InputStreamReader(bomInputStream, decoder); + mf = new MaxLineBufferedReader(reader, MAX_LINE_LEN); + + String line; + List readlines = new ArrayList(5); + + do { + line = mf.readMaxLenLine(); + if (line == null) { + break; + } + readlines.add(line); + while (!mf.isWholeLine()) { + line = mf.readMaxLenLine(); + if (line == null) { + break; + } + readlines.add(line); + } + this.accept(readlines); + readlines.clear(); + + } while (true); + } + return mf; + } + + /** + * Close output stream. + */ + public void closeOutputStream() { + if (this.bfs != null) { + try { + this.bfs.close(); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("byte array outputStream not closed", exception); + } + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/EXPORTTYPE.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/EXPORTTYPE.java new file mode 100644 index 0000000000000000000000000000000000000000..d05e10e33f6245e4fa3906f9a14c440e2a17cfce --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/EXPORTTYPE.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.export; + +/** + * + * Title: enum + * + * Description: The Enum EXPORTTYPE. + * + */ + +public enum EXPORTTYPE { + SQL_DATA, SQL_DDL, SQL_DDL_DATA +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/ExportGrantRevokeQueries.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/ExportGrantRevokeQueries.java new file mode 100644 index 0000000000000000000000000000000000000000..e7d2ebdc60bd44ccd30b52ea9e2cf06a6906dae7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/ExportGrantRevokeQueries.java @@ -0,0 +1,481 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.export; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Locale; + +import org.apache.commons.lang.StringUtils; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: ExportGrantRevokeQueries + * + * Description: + * + */ + +public class ExportGrantRevokeQueries implements IExportGrantRevokePriv { + private String objectName; + private String subName; + private String objType; + private String acls; + private String owner; + private String prefix; + private boolean foundOwnerPrivs = false; + + /** + * ExportGrantRevokeQueries constructor + */ + public ExportGrantRevokeQueries(String objectName, String subName, String objType, String prefix) { + this.objectName = objectName; + this.subName = subName; + this.objType = objType; + this.prefix = prefix; + } + + /** + * executeToGetRelAclQuery execute query for getting acl + * + * @param oid object oid + * @param nsId namespaceid + * @param conn connetion + * @param objName name + * @return long owner oid + */ + public long executeToGetRelAclQuery(long oid, long nsId, DBConnection conn, String objName) { + String query = String.format(Locale.ENGLISH, + "select relacl,relowner from pg_catalog.pg_class where oid=%d and relname='%s' and relnamespace=%d", + oid, objName, nsId); + Statement stmt = null; + ResultSet rs = null; + long ownerId = -1; + try { + stmt = conn.getConnection().createStatement(); + rs = stmt.executeQuery(query); + while (rs.next()) { + this.acls = rs.getString("relacl"); + ownerId = rs.getInt("relowner"); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Errpr occured while fetching information about role and acl for object"); + } finally { + try { + if (stmt != null) { + stmt.close(); + } + if (rs != null) { + rs.close(); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Errpr occured while fetching information about role and acl for object"); + } + } + return ownerId; + } + + /** + * get Acl information for namespace + * + * @param namespaceName name + * @param conn connection + * @return oid for owner + */ + public long executeToGetRelAclQueryForNamespace(String namespaceName, DBConnection conn) { + String query = String.format(Locale.ENGLISH, "select nspowner,nspacl from pg_namespace where nspname='%s';", + namespaceName); + Statement stmt = null; + ResultSet rs = null; + long ownerId = 0; + try { + stmt = conn.getConnection().createStatement(); + rs = stmt.executeQuery(query); + while (rs.next()) { + this.acls = rs.getString("nspacl"); + ownerId = rs.getInt("nspowner"); + } + } catch (SQLException exc) { + MPPDBIDELoggerUtility.error("Errpr occured while fetching information about role and acl for object"); + } finally { + try { + if (stmt != null) { + stmt.close(); + } + if (rs != null) { + rs.close(); + } + } catch (SQLException exc) { + MPPDBIDELoggerUtility.error("Errpr occured while fetching information about role and acl for object"); + } + } + return ownerId; + } + + /** + * getGrantRevokeQueries get queries Here acls will come as String for + * example {dsuser=arwdDxt/dsuser,avinash=a*rwDx/dsuser,aaa=arwdDxt/dsuser} + * + * @return string queries + */ + public String getGrantRevokeQueries() { + if (this.acls == null) { + return ""; + } + if (this.acls.length() == 0) { + return ""; + } + if (StringUtils.isEmpty(this.owner)) { + this.owner = null; + } + StringBuilder builder = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + builder.append(String.format(Locale.ENGLISH, "%sREVOKE ALL", prefix)); + if (this.subName != null && !StringUtils.isEmpty(this.subName)) { + builder.append(String.format(Locale.ENGLISH, "(%s)", this.subName)); + } + builder.append(String.format(Locale.ENGLISH, " ON %s %s FROM PUBLIC;", this.objType, this.objectName)); + builder.append(MPPDBIDEConstants.LINE_SEPARATOR); + ArrayList list = parseAcl(this.acls); + builder = addGrantRevokeQueries(list, builder); + return builder.toString(); + } + + /** + * In this method we are checking privCode and replacing it with privilege + * string according to object type. + * + * @param privParameter privilege parameter + * @return PrivilegeParameters parameter + */ + private PrivilegeParameters addPrevilegeMap(PrivilegeParameters privParameterParam) { + PrivilegeParameters privParameter = privParameterParam; + switch (this.objType) { + case "TABLE": + case "SEQUENCE": + privParameter = getPrivParameterForTableSeq(privParameter); + break; + case "FUNCTION": + case "FUNCTIONS": + privParameter = getPrivilegeString('X', PRIV_EXECUTE, privParameter); + break; + case "LANGUAGE": + privParameter = getPrivilegeString('U', PRIV_USAGE, privParameter); + break; + case "SCHEMA": + privParameter = getPrivilegeString('C', PRIV_CREATE, privParameter); + privParameter = getPrivilegeString('U', PRIV_USAGE, privParameter); + break; + case "TYPE": + case "TYPES": + privParameter = getPrivilegeString('U', PRIV_USAGE, privParameter); + break; + default: + return privParameter; + } + getFinalPrivParameter(privParameter); + return privParameter; + } + + private void getFinalPrivParameter(PrivilegeParameters privParameter) { + if (privParameter.isAllWithGo()) { + privParameter.setPriviledgeBuff(resetPrivlegeBuff(privParameter.getPriviledgeBuff())); + privParameter.setPrevilegeWithGrantBuff(resetPrivlegeBuff(privParameter.getPrevilegeWithGrantBuff())); + privParameter.getPrevilegeWithGrantBuff().append("ALL"); + if (subName != null) { + privParameter.getPriviledgeBuff().append(String.format(Locale.ENGLISH, "(%s)", subName)); + } + } + if (privParameter.isAllWithoutGo()) { + privParameter.setPrevilegeWithGrantBuff(resetPrivlegeBuff(privParameter.getPrevilegeWithGrantBuff())); + privParameter.setPriviledgeBuff(resetPrivlegeBuff(privParameter.getPriviledgeBuff())); + privParameter.getPriviledgeBuff().append("ALL"); + if (subName != null) { + privParameter.getPrevilegeWithGrantBuff().append(String.format(Locale.ENGLISH, "(%s)", subName)); + } + } + } + + private PrivilegeParameters getPrivParameterForTableSeq(PrivilegeParameters privParameterParam) { + PrivilegeParameters privParameter = privParameterParam; + getPrivilegeString('r', "SELECT", privParameter); + + if ("SEQUENCE".equals(objType) || "SEQUENCES".equals(objType)) { + /* sequence only */ + privParameter = getPrivilegeString('U', PRIV_USAGE, privParameter); + } else { + /* table only */ + privParameter = getPrivilegeString('a', PRIV_INSERT, privParameter); + privParameter = getPrivilegeString('x', PRIV_REFERENCES, privParameter); + } + if (subName == null && "TABLE".equals(objType)) { + privParameter = getPrivilegeString('d', PRIV_DELETE, privParameter); + privParameter = getPrivilegeString('t', PRIV_TRIGGER, privParameter); + privParameter = getPrivilegeString('D', PRIV_TRUNCATE, privParameter); + } + privParameter = getPrivilegeString('w', PRIV_UPDATE, privParameter); + return privParameter; + } + + private StringBuffer resetPrivlegeBuff(StringBuffer buff) { + if (buff != null) { + if (!buff.toString().trim().equals("")) { + buff.delete(0, buff.length()); + } else { + return new StringBuffer(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + } + } + return buff; + } + + /** + * addGrantRevokeQueries add grant revoke queries + * + * @param list acl list + * @param builder query builder + */ + public StringBuilder addGrantRevokeQueries(ArrayList list, StringBuilder builder) { + for (int i = 0; i < list.size(); i++) { + // loop through aclArray to parse aclString to get grantee,privilege + // and grantor .Example for aclString is dsuser=arwdDxt/dsuser + String aclString = list.get(i); + String grantee = ""; + + String privCode = ""; + String privGrantorStr = ""; + + if (StringUtils.isEmpty(aclString)) { + continue; + } + // Here we are spliting with '=' to get grantee ..String before '=' + // is grantee + String[] strArray = aclString.split("="); + if (strArray.length == 1) { + grantee = aclString; + } else if (strArray.length > 1) { + grantee = strArray[0]; + privGrantorStr = strArray[1]; + } else { + continue; + } + if (grantee.startsWith("\"") && grantee.endsWith("\"")) { + grantee = grantee.substring(1, grantee.length() - 1); + } + // AS per above example grantee=dsuser and + // privGrantorStr=arwdDxt/dsuser + // Here are spliting privGrantorStr to get privCode and + // grantor..privCode=arwdDxt and grantor=dsuser + String grantor = ""; + String[] strPrivArray = privGrantorStr.split("/"); + if (strPrivArray.length == 1) { + privCode = aclString; + } + if (strPrivArray.length > 1) { + privCode = strPrivArray[0]; + grantor = strPrivArray[1]; + } + String priviledge = ""; + String previlegeWithGrant = ""; + PrivilegeParameters privParameter = new PrivilegeParameters(); + privParameter.setPrivString(privCode); + privParameter = addPrevilegeMap(privParameter); + priviledge = privParameter.getPriviledgeBuff().toString().trim(); + previlegeWithGrant = privParameter.getPrevilegeWithGrantBuff().toString().trim(); + if (priviledge.endsWith(",")) { + priviledge = priviledge.substring(0, priviledge.length() - 1); + } + if (previlegeWithGrant.endsWith(",")) { + previlegeWithGrant = previlegeWithGrant.substring(0, previlegeWithGrant.length() - 1); + } + + getGrantRevokeQueries(builder, grantee, priviledge, previlegeWithGrant, grantor); + } + return builder; + } + + private void getGrantRevokeQueries(StringBuilder builder, String grantee, String priviledge, + String previlegeWithGrant, String grantorParam) { + String grantor = grantorParam; + if (grantor.isEmpty() && owner != null) { + grantor = owner; + } + if (!priviledge.isEmpty() || !previlegeWithGrant.isEmpty()) { + if (owner != null && grantor.equals(owner) && grantee.equals(owner)) { + addQueriresOnSameOwnerAndGrantee(builder, grantee, priviledge, previlegeWithGrant); + } else { + addQuerirsOnOwnerAndGranteeDiff(builder, grantee, priviledge, previlegeWithGrant); + } + } + if (!foundOwnerPrivs && owner != null) { + builder.append(String.format(Locale.ENGLISH, "%sREVOKE ALL", prefix)); + if (subName != null) { + builder.append(String.format(Locale.ENGLISH, "(%s)", subName)); + } + builder.append(String.format(Locale.ENGLISH, " ON %s %s FROM %s;", objType, this.objectName, owner)); + builder.append(MPPDBIDEConstants.LINE_SEPARATOR); + } + } + + private void addQuerirsOnOwnerAndGranteeDiff(StringBuilder builder, String grantee, String priviledge, + String previlegeWithGrant) { + if (!priviledge.isEmpty()) { + builder.append(String.format(Locale.ENGLISH, "%sGRANT %s ON %s %s TO ", prefix, priviledge, objType, + this.objectName)); + + if (grantee.isEmpty()) { + builder.append("PUBLIC;"); + builder.append(MPPDBIDEConstants.LINE_SEPARATOR); + } else { + builder.append(String.format(Locale.ENGLISH, "%s;", grantee)); + builder.append(MPPDBIDEConstants.LINE_SEPARATOR); + } + } + if (!previlegeWithGrant.isEmpty()) { + builder.append(String.format(Locale.ENGLISH, "%sGRANT %s ON %s %s TO ", prefix, previlegeWithGrant, objType, + this.objectName)); + if (grantee.isEmpty()) { + builder.append("PUBLIC"); + + } else { + builder.append(String.format(Locale.ENGLISH, "%s", grantee)); + } + builder.append(" WITH GRANT OPTION;"); + builder.append(MPPDBIDEConstants.LINE_SEPARATOR); + } + } + + private void addQueriresOnSameOwnerAndGrantee(StringBuilder builder, String grantee, String priviledge, + String previlegeWithGrant) { + foundOwnerPrivs = true; + if (!previlegeWithGrant.equals("ALL")) { + builder.append(String.format(Locale.ENGLISH, "%s REVOKE ALL", prefix)); + if (subName != null) { + builder.append(String.format(Locale.ENGLISH, "(%s)", subName)); + } + builder.append(String.format(Locale.ENGLISH, " ON %s %s FROM %s;", objType, this.objectName, grantee)); + builder.append(MPPDBIDEConstants.LINE_SEPARATOR); + if (!priviledge.isEmpty()) { + builder.append(String.format(Locale.ENGLISH, "%sGRANT %s ON %s %s TO %s;", prefix, priviledge, objType, + this.objectName, grantee)); + builder.append(MPPDBIDEConstants.LINE_SEPARATOR); + } + if (!previlegeWithGrant.isEmpty()) { + builder.append(String.format(Locale.ENGLISH, "%sGRANT %s ON %s %s TO %s WITH GRANT OPTION;", prefix, + previlegeWithGrant, objType, this.objectName, grantee)); + builder.append(MPPDBIDEConstants.LINE_SEPARATOR); + } + } + } + + private PrivilegeParameters getPrivilegeString(char chr, String code, PrivilegeParameters privParameter) { + String privCode = privParameter.getPrivString(); + // Here we are checking if character passed (char) is available in + // privCode + // ..if available then we are adding respective Privilege string (code) + int index = privCode.indexOf(chr); + if (index != -1) { + // Here we are checking if if charcter in privCode is followed by * + // then it should add to GRANT WITH OPTION. So adding it in another + // StringBuffer + if (index < (privCode.length() - 1) && privCode.charAt(index + 1) == '*') { + privParameter.getPrevilegeWithGrantBuff().append(code); + privParameter.getPrevilegeWithGrantBuff().append(","); + if (subName != null) { + privParameter.getPrevilegeWithGrantBuff().append(String.format(Locale.ENGLISH, "(%s)", subName)); + } + privParameter.setAllWithoutGo(false); + } else { + privParameter.getPriviledgeBuff().append(code); + privParameter.getPriviledgeBuff().append(","); + if (subName != null) { + privParameter.getPriviledgeBuff().append(String.format(Locale.ENGLISH, "(%s)", subName)); + } + privParameter.setAllWithGo(false); + } + } else { + privParameter.setAllWithoutGo(false); + privParameter.setAllWithGo(false); + } + return privParameter; + } + + /** + * Here we are parsing acls string and changing to list of acls + * + * @param acl example + * {dsuser=arwdDxt/dsuser,avinash=a*rwDx/dsuser,aaa=arwdDxt/dsuser} + * @return array of acls + */ + private ArrayList parseAcl(String aclParam) { + String acl = aclParam; + ArrayList aclList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + if (acl == null) { + return aclList; + } + + acl = acl.trim(); + int aclLength = acl.length(); + if (aclLength < 2 || !acl.startsWith("{") || !acl.endsWith("}")) { + return aclList; + } + acl = acl.substring(1, aclLength - 1); + String[] aclArray = acl.split(","); + for (int i = 0; i < aclArray.length; i++) { + aclList.add(aclArray[i]); + } + return aclList; + } + + /** + * getOwnerName get owner name + * + * @param oid owner id + * @param conn connection + * @throws DatabaseOperationException + */ + public void getOwnerName(long oid, DBConnection conn) throws DatabaseOperationException { + String query = String.format(Locale.ENGLISH, "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =%d", oid); + Statement stmt = null; + ResultSet rs = null; + try { + stmt = conn.getConnection().createStatement(); + rs = stmt.executeQuery(query); + while (rs.next()) { + this.owner = rs.getString("rolname"); + } + } catch (SQLException exc) { + MPPDBIDELoggerUtility.error("Error occured while fetching owner name for object name"); + throw new DatabaseOperationException(IMessagesConstants.ERROR_WHILE_FETCHING_OWNER_NAME, exc); + } finally { + try { + if (stmt != null) { + stmt.close(); + } + if (rs != null) { + rs.close(); + } + } catch (SQLException exc) { + MPPDBIDELoggerUtility.error("Error occured while fetching owner name for object name"); + } + } + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/ExportManager.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/ExportManager.java new file mode 100644 index 0000000000000000000000000000000000000000..f2d9fd530e665f76bb6c3f1858034d3907bef6a7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/ExportManager.java @@ -0,0 +1,691 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.export; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DebugObjects; +import org.opengauss.mppdbide.bl.serverdatacache.ForeignTable; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.SequenceMetadata; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TriggerMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DataStudioSecurityException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.files.FilePermissionFactory; +import org.opengauss.mppdbide.utils.files.ISetFilePermission; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.observer.DSEventTable; +import org.opengauss.mppdbide.utils.observer.DSEventWithCount; +import org.opengauss.mppdbide.utils.observer.IDSGridUIListenable; + +/** + * + * Title: class + * + * Description: The Class ExportManager. + * + */ + +public class ExportManager implements IExportManager { + + private DSEventTable eventTable = null; + private static final byte[] UTF8_BOM = new byte[] {(byte) 0XEF, (byte) 0xBB, (byte) 0xBF}; + private boolean isCancel = false; + + /** + * Instantiates a new export manager. + */ + public ExportManager() { + } + + private void checkAndThrowCancelException() throws DatabaseOperationException { + if (this.isCancel) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_CANCEL_ON_USER_REQUEST)); + throw new DatabaseOperationException(IMessagesConstants.EXPORT_CANCEL_ON_USER_REQUEST); + } + } + + /** + * Sets the event table. + * + * @param tab the new event table + */ + public void setEventTable(DSEventTable tab) { + this.eventTable = tab; + } + + @Override + public void exportSqlToFile(String path, EXPORTTYPE type, ServerObject object, boolean isTablespaceOption, + File workingDir) throws DatabaseOperationException, DatabaseCriticalException, DataStudioSecurityException { + checkAndThrowCancelException(); + exportDatabaseObjectsFromSystemTables(path, type, object, workingDir, "", isTablespaceOption); + } + + private void exportDatabaseObjectsFromSystemTables(String path, EXPORTTYPE type, ServerObject object, + File workingDir, String encryptedPwd, boolean isTablespaceOption) throws DatabaseOperationException { + Path createdFilePath = null; + Database db = object.getDatabase(); + try { + Path exportFilePath = Paths + .get(String.format(Locale.ENGLISH, "%s%s%S", workingDir.getCanonicalPath(), File.separator, path)) + .normalize(); + ISetFilePermission withPermission = FilePermissionFactory.getFilePermissionInstance(); + createdFilePath = withPermission.createFileWithPermission(exportFilePath.toString(), false, null, false); + + isPretendBom(createdFilePath); + DBConnection conn = getDbConnection(db, encryptedPwd); + exportDatabseObjects(type, object, createdFilePath, conn, isTablespaceOption); + releaseConnection(db, conn); + } catch (MPPDBIDEException exp) { + if (createdFilePath != null) { + deleteFileOnException(createdFilePath); + } + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_FAIL_PROCESS_INTRUPTED_FOR_OBJ, ""), exp); + throw new DatabaseOperationException(IMessagesConstants.EXPORT_FAIL_PROCESS_INTRUPTED_FOR_OBJ, + exp.getServerMessage()); + } catch (IOException exp) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_FAIL_DISK_WRITE_ERROR), exp); + throw new DatabaseOperationException(IMessagesConstants.EXPORT_FAIL_DISK_WRITE_ERROR, exp); + } + } + + private void exportDatabseObjects(EXPORTTYPE type, ServerObject object, Path createdFilePath, DBConnection conn, + boolean isTablespaceOption) throws DatabaseOperationException, DatabaseCriticalException, IOException, + UnsupportedEncodingException, MPPDBIDEException { + ArrayList objList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + if (object instanceof Namespace) { + Namespace ns = (Namespace) object; + exportNamespaceDdl(createdFilePath, conn, ns); + exportDebugObjDdl(conn, createdFilePath, ns); + exportTableDdl(type, conn, createdFilePath, ns, isTablespaceOption); + exportSequenceDDLOwenedBy(type, conn, createdFilePath, ns); + exportViewDdl(conn, createdFilePath, ns); + exportSequenceDdl(type, conn, createdFilePath, ns); + } else if (object instanceof TableMetaData) { + objList.add((TableMetaData) object); + writeTableObjectDDL(objList, createdFilePath, type, conn, isTablespaceOption); + } else if (object instanceof ViewMetaData) { + objList.add((ViewMetaData) object); + writeViewObjectDDL(objList, createdFilePath, conn); + } else if (object instanceof SequenceMetadata) { + objList.add((SequenceMetadata) object); + writeSequenceObjectDDL(objList, createdFilePath, type, conn); + } else { + return; + } + } + + private void exportSequenceDDLOwenedBy(EXPORTTYPE type, DBConnection conn, Path createdFilePath, Namespace ns) + throws DatabaseOperationException, UnsupportedEncodingException, IOException { + ArrayList objList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + objList.addAll(ns.getSequenceGroup().getSortedServerObjectList()); + String fileEncodingName = getFileEncoding(); + for (ServerObject fobj : objList) { + SequenceMetadata seqObject = (SequenceMetadata) fobj; + StandardOpenOption fileMode = StandardOpenOption.APPEND; + String seqDDL = seqObject.getSequenceQwnedByDDL(conn); + if (!seqDDL.trim().isEmpty()) { + addSeqOwnedByHeader(createdFilePath, fileMode, seqObject, fileEncodingName); + Files.write(createdFilePath, seqDDL.getBytes(fileEncodingName), fileMode); + } + if (eventTable != null) { + eventTable + .sendEvent(new DSEventWithCount(IDSGridUIListenable.LISTEN_BATCHEXPORT_DDL_SUCCESS, seqObject)); + } + } + objList.clear(); + } + + private void exportSequenceDdl(EXPORTTYPE type, DBConnection conn, Path createdFilePath, Namespace ns) + throws DatabaseOperationException, IOException, UnsupportedEncodingException, DatabaseCriticalException { + ArrayList objList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + objList.addAll(ns.getSequenceGroup().getSortedServerObjectList()); + writeSequenceObjectDDL(objList, createdFilePath, type, conn); + objList.clear(); + } + + private void exportViewDdl(DBConnection conn, Path createdFilePath, Namespace ns) + throws MPPDBIDEException, IOException, UnsupportedEncodingException { + ArrayList objList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + objList.addAll(ns.getViewGroup().getSortedServerObjectList()); + writeViewObjectDDL(objList, createdFilePath, conn); + objList.clear(); + } + + private void exportTableDdl(EXPORTTYPE type, DBConnection conn, Path createdFilePath, Namespace ns, + boolean isTablespaceOption) throws MPPDBIDEException, IOException, UnsupportedEncodingException { + ArrayList objList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + objList.addAll(ns.getTables().getSortedServerObjectList()); + objList.addAll(ns.getForeignTablesGroup().getSortedServerObjectList()); + writeTableObjectDDL(objList, createdFilePath, type, conn, false); + objList.clear(); + } + + private void exportDebugObjDdl(DBConnection conn, Path createdFilePath, Namespace ns) + throws DatabaseOperationException, DatabaseCriticalException, IOException, UnsupportedEncodingException { + ArrayList objList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + objList.addAll(ns.getFunctions().getSortedServerObjectList()); + writeDebugObjectDDL(objList, createdFilePath, conn); + objList.clear(); + } + + private void exportNamespaceDdl(Path createdFilePath, DBConnection conn, Namespace ns) + throws DatabaseOperationException, DatabaseCriticalException, IOException, UnsupportedEncodingException { + if (!ns.isLoaded()) { + ns.getAllObjectsOnDemand(ns.getDatabase().getConnectionManager().getObjBrowserConn()); + } + addNamespaceHeader(createdFilePath, ns); + addNamespaceComments(createdFilePath, ns, conn); + addAclDDL(createdFilePath, ns, conn, "SCHEMA"); + } + + private void addNamespaceComments(Path createdFilePath, Namespace ns, DBConnection conn) + throws DatabaseOperationException, UnsupportedEncodingException, IOException, DatabaseCriticalException { + String fileEncodingName = getFileEncoding(); + StandardOpenOption fileMode = StandardOpenOption.APPEND; + String comments = ns.getNamespceComments(conn); + if (!comments.isEmpty()) { + String commHeader = MPPDBIDEConstants.LINE_SEPARATOR + + MPPDBIDEConstants.LINE_SEPARATOR + String.format(Locale.ENGLISH, + "-- Name: SCHEMA %s; Type: COMMENT; Schema: -; Owner: -" + "", ns.getDisplayName()) + + MPPDBIDEConstants.LINE_SEPARATOR + MPPDBIDEConstants.LINE_SEPARATOR; + Files.write(createdFilePath, commHeader.getBytes(fileEncodingName), fileMode); + Files.write(createdFilePath, comments.getBytes(fileEncodingName), fileMode); + } + String str = MPPDBIDEConstants.LINE_SEPARATOR + MPPDBIDEConstants.LINE_SEPARATOR + + String.format(Locale.ENGLISH, "SET search_path = %s ;", ns.getDisplayName()) + + MPPDBIDEConstants.LINE_SEPARATOR + MPPDBIDEConstants.LINE_SEPARATOR; + Files.write(createdFilePath, str.getBytes(fileEncodingName), fileMode); + } + + private void deleteFileOnException(Path createdFilePath) { + try { + Files.deleteIfExists(createdFilePath); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("ExportManager: delete files on exception failed", exception); + } + } + + private void addDebugObjectHeader(Path createdFilePath, StandardOpenOption fileMode, DebugObjects dbgObject, + String fileEncoding) throws IOException, UnsupportedEncodingException { + String header = MPPDBIDEConstants.LINE_SEPARATOR + MPPDBIDEConstants.LINE_SEPARATOR + "--" + + MPPDBIDEConstants.LINE_SEPARATOR + "-- Name: " + dbgObject.getName() + "; Type: " + + dbgObject.getTypeLabel() + "; Schema: " + dbgObject.getNamespace().getName() + ";" + + MPPDBIDEConstants.LINE_SEPARATOR + "--" + MPPDBIDEConstants.LINE_SEPARATOR + + MPPDBIDEConstants.LINE_SEPARATOR; + Files.write(createdFilePath, header.getBytes(fileEncoding), fileMode); + } + + private void writeDebugObjectDDL(ArrayList objList, Path createdFilePath, DBConnection conn) + throws DatabaseOperationException, DatabaseCriticalException, IOException, UnsupportedEncodingException { + DebugObjects dbgObject = null; + StandardOpenOption fileMode = StandardOpenOption.APPEND; + String fileEncodingName = getFileEncoding(); + for (ServerObject fobj : objList) { + dbgObject = (DebugObjects) fobj; + dbgObject.refreshSourceCode(); + + addDebugObjectHeader(createdFilePath, fileMode, dbgObject, fileEncodingName); + fileMode = StandardOpenOption.APPEND; + Files.write(createdFilePath, dbgObject.getSourceCode().getCode().getBytes(fileEncodingName), fileMode); + addAclDDL(createdFilePath, dbgObject, conn, "FUNCTION"); + if (eventTable != null) { + eventTable + .sendEvent(new DSEventWithCount(IDSGridUIListenable.LISTEN_BATCHEXPORT_DDL_SUCCESS, dbgObject)); + } + } + } + + private void writeTriggerDDL(ArrayList objList, Path createdFilePath, DBConnection conn) + throws DatabaseOperationException, DatabaseCriticalException, IOException, UnsupportedEncodingException { + TriggerMetaData trigger = null; + StandardOpenOption fileMode = StandardOpenOption.APPEND; + String fileEncodingName = getFileEncoding(); + for (ServerObject fobj : objList) { + trigger = (TriggerMetaData) fobj; + String header = trigger.getHeader(); + Files.write(createdFilePath, header.getBytes(fileEncodingName), fileMode); + fileMode = StandardOpenOption.APPEND; + Files.write(createdFilePath, trigger.getDdlMsg().getBytes(fileEncodingName), fileMode); + if (eventTable != null) { + eventTable + .sendEvent(new DSEventWithCount(IDSGridUIListenable.LISTEN_BATCHEXPORT_DDL_SUCCESS, trigger)); + } + } + } + + /* + * Add BOM (Byte Order Mark) for UTF8 encoding. + */ + private static boolean isPrependBomForUtf8(String encodingName) { + return "UTF8".equalsIgnoreCase(encodingName) || "UTF-8".equalsIgnoreCase(encodingName); + } + + /** + * Prepend bom for utf 8. + * + * @param encodingName the encoding name + * @param fileOutStream the file out stream + * @throws DatabaseOperationException the database operation exception + */ + public static void prependBomForUtf8(String encodingName, FileOutputStream fileOutStream) + throws DatabaseOperationException { + if (isPrependBomForUtf8(encodingName)) { + try { + fileOutStream.write(UTF8_BOM); + fileOutStream.flush(); + } catch (IOException exp) { + throw new DatabaseOperationException(IMessagesConstants.IO_EXCEPTION_WHILE_EXPORT, exp); + } + } + } + + @Override + public void exportSqlToFile(ExportParameters expParameter) + throws DatabaseOperationException, DatabaseCriticalException, DataStudioSecurityException { + checkAndThrowCancelException(); + // Validate the type of export. + ServerObject serverObject = expParameter.getServerObject(); + exportDatabaseObjectsFromSystemTables(expParameter.getPath(), expParameter.getExportType(), serverObject, + expParameter.getWorkingDir(), expParameter.getPassword(), false); + } + + /** + * Export sql to files. + * + * @param expParameter the exp parameter + * @return the list + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws DataStudioSecurityException the data studio security exception + */ + public List exportSqlToFiles(ExportParameters expParameter) + throws DatabaseOperationException, DatabaseCriticalException, DataStudioSecurityException { + String basepath = expParameter.getPath(); + + List paths = new ArrayList(4); + try { + paths = exportSqlToFiles(basepath, expParameter.getExportType(), expParameter.getServerObjList(), + expParameter.isTablespaceOption(), expParameter.getWorkingDir(), expParameter.getPassword()); + return paths; + } catch (DatabaseOperationException | DatabaseCriticalException | DataStudioSecurityException exp) { + deleteTempFiles(paths); + throw exp; + } + } + + @Override + public void cancel() { + this.isCancel = true; + } + + @Override + public List exportSqlToFiles(String basepath, EXPORTTYPE type, ArrayList objects, + boolean isTablespaceOption, File workingDir, String encryptedPwd) + throws DatabaseOperationException, DatabaseCriticalException, DataStudioSecurityException { + checkAndThrowCancelException(); + List paths = new ArrayList(4); + try { + int count = 0; + Path createdFilePath = createTemporaryFile(basepath, workingDir, paths, count); + isPretendBom(createdFilePath); + exportDDLUsingSystemTable(type, objects, encryptedPwd, createdFilePath, isTablespaceOption); + return paths; + } catch (DatabaseOperationException | DatabaseCriticalException exp) { + deleteTempFiles(paths); + throw exp; + } catch (IOException exp) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_FAIL_DISK_WRITE_ERROR), exp); + throw new DatabaseOperationException(IMessagesConstants.EXPORT_FAIL_DISK_WRITE_ERROR, exp); + } catch (MPPDBIDEException exp) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_FAIL_DISK_WRITE_ERROR), exp); + throw new DatabaseOperationException(IMessagesConstants.EXPORT_FAIL_DISK_WRITE_ERROR, exp); + } + } + + private void exportDDLUsingSystemTable(EXPORTTYPE type, ArrayList objects, String encryptedPwd, + Path createdFilePath, boolean isTablespaceOption) throws IOException, DatabaseOperationException, + DatabaseCriticalException, UnsupportedEncodingException, MPPDBIDEException { + Database db = objects.get(0).getDatabase(); + MPPDBIDELoggerUtility.info("Export DDL by system table"); + + DBConnection conn = getDbConnection(db, encryptedPwd); + if (objects.get(0) instanceof DebugObjects) { + writeDebugObjectDDL(objects, createdFilePath, conn); + } + if (objects.get(0) instanceof TriggerMetaData) { + writeTriggerDDL(objects, createdFilePath, conn); + } + if (objects.get(0) instanceof TableMetaData) { + writeTableObjectDDL(objects, createdFilePath, type, conn, isTablespaceOption); + } + if (objects.get(0) instanceof ViewMetaData) { + writeViewObjectDDL(objects, createdFilePath, conn); + } + if (objects.get(0) instanceof SequenceMetadata) { + writeSequenceObjectDDL(objects, createdFilePath, type, conn); + } + releaseConnection(db, conn); + } + + private Path createTemporaryFile(String basepath, File workingDir, List paths, int count) + throws IOException, DatabaseOperationException { + String path = basepath + "_" + Integer.toString(count); + paths.add(workingDir.toString() + File.separator + path); + Path exportFilePath = Paths + .get(String.format(Locale.ENGLISH, "%s%s%s", workingDir.getCanonicalPath(), File.separator, path)) + .normalize(); + ISetFilePermission withPermission = FilePermissionFactory.getFilePermissionInstance(); + Path createdFilePath = withPermission.createFileWithPermission(exportFilePath.toString(), false, null, false); + return createdFilePath; + } + + private String getFileEncoding() { + String fileEncoding = BLPreferenceManager.getInstance().getBLPreference().getFileEncoding(); + String fileEncodingName = fileEncoding.isEmpty() ? Charset.defaultCharset().name() : fileEncoding; + return fileEncodingName; + } + + private void isPretendBom(Path createdFilePath) throws IOException { + String fileEncoding = BLPreferenceManager.getInstance().getBLPreference().getFileEncoding(); + boolean isPrependBom = isPrependBomForUtf8(fileEncoding); + StandardOpenOption fileMode = StandardOpenOption.TRUNCATE_EXISTING; + if (isPrependBom) { + Files.write(createdFilePath, UTF8_BOM, fileMode); + } + } + + private void writeSequenceObjectDDL(ArrayList objList, Path createdFilePath, EXPORTTYPE type, + DBConnection conn) + throws DatabaseOperationException, IOException, UnsupportedEncodingException, DatabaseCriticalException { + String fileEncodingName = getFileEncoding(); + for (ServerObject fobj : objList) { + SequenceMetadata seqObject = (SequenceMetadata) fobj; + String seqQuery = seqObject.getDDL(seqObject.getDatabase(), conn); + StandardOpenOption fileMode = StandardOpenOption.APPEND; + addServerObjectHeader(createdFilePath, fileMode, seqObject, fileEncodingName); + addSetSchemaQuery(createdFilePath, seqObject.getNamespace(), fileEncodingName); + fileMode = StandardOpenOption.APPEND; + Files.write(createdFilePath, seqQuery.getBytes(fileEncodingName), fileMode); + addAclDDL(createdFilePath, seqObject, conn, "SEQUENCE"); + + addSequenceDataDdl(createdFilePath, type, seqObject, conn); + if (eventTable != null) { + eventTable + .sendEvent(new DSEventWithCount(IDSGridUIListenable.LISTEN_BATCHEXPORT_DDL_SUCCESS, seqObject)); + } + } + } + + private void addSequenceDataDdl(Path createdFilePath, EXPORTTYPE type, SequenceMetadata seqObject, + DBConnection conn) throws IOException, UnsupportedEncodingException, DatabaseOperationException { + String sequenceDDL = ""; + String fileEncodingName = getFileEncoding(); + StandardOpenOption fileMode = StandardOpenOption.APPEND; + if (type.toString().equals("SQL_DDL_DATA")) { + addServerDataHeader(createdFilePath, fileMode, seqObject, fileEncodingName); + fileMode = StandardOpenOption.APPEND; + ExportObjectDataManager exportManager = new ExportObjectDataManager(conn, createdFilePath, + fileEncodingName); + try { + sequenceDDL = exportManager.getSequenceNextValue(seqObject); + } catch (DatabaseCriticalException | DatabaseOperationException exception) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_WHILE_FETCHING_SEQ_VALUE)); + throw new DatabaseOperationException(IMessagesConstants.ERR_WHILE_FETCHING_SEQ_VALUE, exception); + } + Files.write(createdFilePath, sequenceDDL.getBytes(fileEncodingName), fileMode); + } + } + + private void writeViewObjectDDL(ArrayList objList, Path createdFilePath, DBConnection conn) + throws MPPDBIDEException, IOException, UnsupportedEncodingException { + String fileEncodingName = getFileEncoding(); + for (ServerObject fobj : objList) { + ViewMetaData viewObject = (ViewMetaData) fobj; + String viewQuery = viewObject.getDDL(viewObject.getDatabase()); + StandardOpenOption fileMode = StandardOpenOption.APPEND; + addServerObjectHeader(createdFilePath, fileMode, viewObject, fileEncodingName); + addSetSchemaQuery(createdFilePath, viewObject.getNamespace(), fileEncodingName); + fileMode = StandardOpenOption.APPEND; + Files.write(createdFilePath, viewQuery.getBytes(fileEncodingName), fileMode); + addAclDDL(createdFilePath, viewObject, conn, "TABLE"); + if (eventTable != null) { + eventTable.sendEvent( + new DSEventWithCount(IDSGridUIListenable.LISTEN_BATCHEXPORT_DDL_SUCCESS, viewObject)); + } + } + } + + private void writeTableObjectDDL(ArrayList objList, Path createdFilePath, EXPORTTYPE type, + DBConnection conn, boolean isTablespaceOption) + throws MPPDBIDEException, IOException, UnsupportedEncodingException { + String fileEncodingName = getFileEncoding(); + for (ServerObject fobj : objList) { + TableMetaData tableObject = (TableMetaData) fobj; + if (tableObject.getNamespace().getErrorTableList().contains(tableObject.getName())) { + continue; + } + tableObject.fetchDDL(tableObject.getDatabase(), conn); + String tableQuery = tableObject.getSource(); + StandardOpenOption fileMode = StandardOpenOption.APPEND; + + addServerObjectHeader(createdFilePath, fileMode, tableObject, fileEncodingName); + addDefaultTablespaceForTable(createdFilePath, isTablespaceOption, tableObject, fileEncodingName, conn); + fileMode = StandardOpenOption.APPEND; + Files.write(createdFilePath, tableQuery.getBytes(fileEncodingName), fileMode); + addAclDDL(createdFilePath, tableObject, conn, "TABLE"); + exportTableDataDdl(createdFilePath, type, conn, tableObject); + + if (eventTable != null) { + eventTable.sendEvent( + new DSEventWithCount(IDSGridUIListenable.LISTEN_BATCHEXPORT_DDL_SUCCESS, tableObject)); + } + } + } + + private void addDefaultTablespaceForTable(Path createdFilePath, boolean isTablespaceOption, + TableMetaData tableObject, String fileEncodingName, DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException, UnsupportedEncodingException, IOException { + if (isTablespaceOption) { + String tablespaceName = tableObject.getTablespaceForTable(conn); + String query = String.format(Locale.ENGLISH, "SET default_tablespace = %s;", + (tablespaceName == null || tablespaceName.isEmpty()) ? + tableObject.getDatabase().getDBDefaultTblSpc() : tablespaceName) + + MPPDBIDEConstants.LINE_SEPARATOR; + Files.write(createdFilePath, query.getBytes(fileEncodingName), StandardOpenOption.APPEND); + } + } + + private void addSetSchemaQuery(Path createdFilePath, Namespace ns, String fileEncodingName) + throws UnsupportedEncodingException, IOException { + String query = String.format(Locale.ENGLISH, "%sSET search_path = %s ;%s", MPPDBIDEConstants.LINE_SEPARATOR, + ns.getDisplayName(), MPPDBIDEConstants.LINE_SEPARATOR); + Files.write(createdFilePath, query.getBytes(fileEncodingName), StandardOpenOption.APPEND); + } + + private void exportTableDataDdl(Path createdFilePath, EXPORTTYPE type, DBConnection conn, TableMetaData tableObject) + throws IOException, UnsupportedEncodingException, DatabaseCriticalException, DatabaseOperationException, + MPPDBIDEException { + String fileEncodingName = getFileEncoding(); + if (type.toString().equals("SQL_DDL_DATA") && !(tableObject instanceof ForeignTable)) { + addServerDataHeader(createdFilePath, StandardOpenOption.APPEND, tableObject, fileEncodingName); + String query = String.format(Locale.ENGLISH, "Select * from %s ;", tableObject.getDisplayName()); + GenerateCursorExecuteUtil genrateUtil = new GenerateCursorExecuteUtil(tableObject.getDisplayName(), + fileEncodingName, true); + ExportObjectDataManager exportManager = new ExportObjectDataManager(conn, createdFilePath, fileEncodingName, + query, genrateUtil); + exportManager.exportTableData(); + exportManager.cleanData(); + } + } + + private void addAclDDL(Path createdFilePath, ServerObject servObj, DBConnection conn, String objType) + throws IOException, UnsupportedEncodingException, DatabaseCriticalException, DatabaseOperationException { + String fileEncodingName = getFileEncoding(); + StandardOpenOption fileMode = StandardOpenOption.APPEND; + ExportGrantRevokeQueries grantRevokeQueries = new ExportGrantRevokeQueries( + ServerObject.getQualifiedObjectName(servObj.getName()), null, objType, ""); + long ownerId = -1; + ownerId = getOwnerId(servObj, conn, grantRevokeQueries); + if (ownerId != -1) { + grantRevokeQueries.getOwnerName(ownerId, conn); + } + + String grantQueries = grantRevokeQueries.getGrantRevokeQueries(); + if (!grantQueries.isEmpty()) { + addServerObjectAclHeader(createdFilePath, fileMode, servObj); + Files.write(createdFilePath, grantQueries.getBytes(fileEncodingName), fileMode); + } + } + + private long getOwnerId(ServerObject servObj, DBConnection conn, ExportGrantRevokeQueries grantRevokeQueries) { + long ownerId; + if (servObj instanceof Namespace) { + ownerId = grantRevokeQueries.executeToGetRelAclQueryForNamespace(servObj.getDisplayName(), conn); + } else { + ownerId = grantRevokeQueries.executeToGetRelAclQuery(servObj.getOid(), servObj.getNamespace().getOid(), + conn, servObj.getName()); + } + return ownerId; + } + + private DBConnection getDbConnection(Database database, String encryptedPwd) + throws DatabaseCriticalException, DatabaseOperationException { + DBConnection connection = null; + try { + if (!encryptedPwd.isEmpty()) { + database.getServer().setPrd(encryptedPwd); + } + connection = database.getConnectionManager().getFreeConnection(); + database.getServer().clearPrds(); + } catch (MPPDBIDEException exception) { + String msg = exception.getServerMessage() != null ? exception.getServerMessage() : exception.getMessage(); + if (msg.contains("Connection refused")) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.DATABASE_CONNECTION_ERR), + exception); + throw new DatabaseCriticalException(IMessagesConstants.DATABASE_CONNECTION_ERR, exception); + } else { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.DATABASE_CONNECTION_ERR)); + throw new DatabaseOperationException(IMessagesConstants.DATABASE_CONNECTION_ERR); + } + } + return connection; + + } + + private void releaseConnection(Database database, DBConnection dbConn) { + if (dbConn != null && database.getConnectionManager() != null) { + database.getConnectionManager().releaseAndDisconnection(dbConn); + } + } + + private void addServerObjectHeader(Path createdFilePath, StandardOpenOption fileMode, ServerObject dbgObject, + String fileEncoding) throws IOException, UnsupportedEncodingException { + String header = MPPDBIDEConstants.LINE_SEPARATOR + MPPDBIDEConstants.LINE_SEPARATOR + "--" + + MPPDBIDEConstants.LINE_SEPARATOR + "-- Name: " + dbgObject.getName() + "; Type: " + + dbgObject.getTypeLabel() + "; Schema: " + dbgObject.getNamespace().getName() + ";" + + MPPDBIDEConstants.LINE_SEPARATOR + "--" + MPPDBIDEConstants.LINE_SEPARATOR + + MPPDBIDEConstants.LINE_SEPARATOR; + Files.write(createdFilePath, header.getBytes(fileEncoding), fileMode); + } + + private void addSeqOwnedByHeader(Path createdFilePath, StandardOpenOption fileMode, ServerObject dbgObject, + String fileEncoding) throws IOException, UnsupportedEncodingException { + String header = MPPDBIDEConstants.LINE_SEPARATOR + MPPDBIDEConstants.LINE_SEPARATOR + "--" + + MPPDBIDEConstants.LINE_SEPARATOR + "-- Name: " + dbgObject.getName() + "; Type: SEQUENCE OWNED BY " + + "; Schema: " + dbgObject.getNamespace().getName() + ";" + MPPDBIDEConstants.LINE_SEPARATOR + "--" + + MPPDBIDEConstants.LINE_SEPARATOR + MPPDBIDEConstants.LINE_SEPARATOR; + Files.write(createdFilePath, header.getBytes(fileEncoding), fileMode); + } + + private void addServerDataHeader(Path createdFilePath, StandardOpenOption fileMode, ServerObject dbgObject, + String fileEncoding) throws IOException, UnsupportedEncodingException { + String header = MPPDBIDEConstants.LINE_SEPARATOR + MPPDBIDEConstants.LINE_SEPARATOR + "--" + "Data for " + + " Name: " + dbgObject.getName() + "; Type: " + dbgObject.getTypeLabel() + "; Schema: " + + dbgObject.getNamespace().getName() + ";" + MPPDBIDEConstants.LINE_SEPARATOR + "--" + + MPPDBIDEConstants.LINE_SEPARATOR + MPPDBIDEConstants.LINE_SEPARATOR; + Files.write(createdFilePath, header.getBytes(fileEncoding), fileMode); + } + + private void addServerObjectAclHeader(Path createdFilePath, StandardOpenOption fileMode, ServerObject dbgObject) + throws IOException, UnsupportedEncodingException { + String namespaceName = null; + if (dbgObject instanceof Namespace) { + namespaceName = dbgObject.getName(); + } else { + namespaceName = dbgObject.getNamespace().getName(); + } + String header = MPPDBIDEConstants.LINE_SEPARATOR + MPPDBIDEConstants.LINE_SEPARATOR + "--" + " Name: " + + dbgObject.getName() + "; Type: ACL" + "; Schema: " + namespaceName + ";" + + MPPDBIDEConstants.LINE_SEPARATOR + "--" + MPPDBIDEConstants.LINE_SEPARATOR + + MPPDBIDEConstants.LINE_SEPARATOR; + Files.write(createdFilePath, header.getBytes(getFileEncoding()), fileMode); + } + + private void addNamespaceHeader(Path createdFilePath, Namespace namespace) + throws IOException, UnsupportedEncodingException { + StringBuilder builder = new StringBuilder(); + String header = MPPDBIDEConstants.LINE_SEPARATOR + MPPDBIDEConstants.LINE_SEPARATOR + "--" + + MPPDBIDEConstants.LINE_SEPARATOR + "-- Name: " + namespace.getName() + "; Type: " + + namespace.getTypeLabel() + "; Schema: ;" + MPPDBIDEConstants.LINE_SEPARATOR + "--" + + MPPDBIDEConstants.LINE_SEPARATOR + MPPDBIDEConstants.LINE_SEPARATOR; + + builder.append(header); + String query = "CREATE SCHEMA " + namespace.getDisplayName() + ";"; + builder.append(query); + builder.append(MPPDBIDEConstants.LINE_SEPARATOR); + builder.append(MPPDBIDEConstants.LINE_SEPARATOR); + Files.write(createdFilePath, builder.toString().getBytes(getFileEncoding()), StandardOpenOption.APPEND); + } + + private void deleteTempFiles(List paths) { + if (!paths.isEmpty()) { + for (String onefilepath : paths) { + deleteFileOnException(Paths.get(onefilepath)); + } + } + } + +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/ExportObjectDataManager.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/ExportObjectDataManager.java new file mode 100644 index 0000000000000000000000000000000000000000..fa4a2f6d17fe9627ae1cc4de7608d7a6ddc944d4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/ExportObjectDataManager.java @@ -0,0 +1,387 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.export; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.bl.serverdatacache.SequenceMetadata; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.util.ExecTimer; +import org.opengauss.mppdbide.bl.util.IExecTimer; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: ExportObjetDataManager + * + * @since 3.0.0 + */ +public class ExportObjectDataManager { + private static final String CURSOR_QUERY_PREPEND = "CURSOR %s NO SCROLL FOR %s"; + private static final int CURSOR_FETCH_BATCH_SIZE = 1000; + private static final String FETCH_QUERY = "FETCH FORWARD %d FROM %s"; + private static final String CLOSE_QUERY = "CLOSE %s"; + private int fetchSize; + private Statement stmt; + private String cursorName; + private boolean needAutoCommitReset; + private DBConnection dbConn; + private Path path; + private String encoding; + private String exportQuery; + private GenerateCursorExecuteUtil genrateUtil; + private boolean cancelled = false; + + /** + * Constructor ExportObjetDataManager + */ + public ExportObjectDataManager(DBConnection dbConn, Path path, String encoding, String query, + GenerateCursorExecuteUtil genrateUtil) { + this(dbConn, path, encoding); + this.exportQuery = query; + this.genrateUtil = genrateUtil; + } + + /** + * Constructor ExportObjetDataManager + */ + public ExportObjectDataManager(DBConnection dbConn, Path path, String encoding) { + this.dbConn = dbConn; + this.path = path; + this.encoding = encoding; + } + + /** + * exportTableData method + * + * @throws MPPDBIDEException exception + */ + public void exportTableData() throws MPPDBIDEException { + this.fetchSize = -1; + startTxn(); + try { + executeCursor(); + try { + fetchFileRecords(); + } finally { + closeCursor(); + } + } finally { + stopTxn(); + } + } + + /** + * + * + * @param seqObject object + * @return string query + * @throws DatabaseCriticalException exception + * @throws DatabaseOperationException exception + */ + public String getSequenceNextValue(SequenceMetadata seqObject) + throws DatabaseCriticalException, DatabaseOperationException { + boolean called = false; + long nextVal = 0; + String seqDDL; + long maxValue = 0; + long minValue = 0; + String seqMaxQry = String.format(Locale.ENGLISH, + "SELECT start_value, increment_by, max_value, min_value, is_called FROM %s ;", + seqObject.getDisplayName()); + ResultSet rs = null; + try { + this.stmt = getExportConn().createStatement(); + rs = stmt.executeQuery(seqMaxQry); + while (rs.next()) { + maxValue = rs.getLong("max_value"); + minValue = rs.getLong("min_value"); + called = rs.getBoolean("is_called"); + } + nextVal = getSeqNextValue(seqObject); + } catch (SQLException exception) { + GaussUtils.handleCriticalException(exception); + String msg = exception.getMessage(); + if (msg.contains("Sequence reached maximum value")) { + nextVal = maxValue; + called = true; + } + if (msg.contains("Sequence reached minimum value")) { + nextVal = minValue; + called = true; + } + } finally { + try { + if (stmt != null) { + stmt.close(); + } + if (rs != null) { + rs.close(); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility + .error("Error while closing statement or resultset while fetching sequence next value."); + } + } + seqDDL = exportSequenceData(ServerObject.getQualifiedObjectName(seqObject.getName()), nextVal, called); + return seqDDL; + } + + private long getSeqNextValue(SequenceMetadata seqObject) throws SQLException { + String seqQuery = String.format(Locale.ENGLISH, "SELECT pg_catalog.nextval(?)"); + IExecTimer timer = new ExecTimer("Start getting next value for sequence"); + timer.start(); + ResultSet rs = null; + PreparedStatement prStmt = null; + long nextVal = 0; + try { + prStmt = getExportConn().prepareStatement(seqQuery); + prStmt.setString(1, seqObject.getDisplayName()); + rs = prStmt.executeQuery(); + while (rs.next()) { + nextVal = rs.getInt("nextval"); + } + } finally { + try { + if (prStmt != null) { + prStmt.close(); + } + if (rs != null) { + rs.close(); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility + .error("Error while closing statement or resultset while fetching sequence next value."); + } + } + return nextVal; + } + + private void startTxn() throws DatabaseCriticalException, DatabaseOperationException { + try { + if (getExportConn().getAutoCommit()) { + getExportConn().setAutoCommit(false); + this.needAutoCommitReset = true; + } + } catch (SQLException ex) { + GaussUtils.handleCriticalException(ex); + throw new DatabaseOperationException(IMessagesConstants.ERR_DATABASE_OPERATION_FAILURE, ex); + } + } + + private Connection getExportConn() { + return dbConn.getConnection(); + } + + private void executeCursor() throws DatabaseCriticalException, DatabaseOperationException { + IExecTimer timer = new ExecTimer("Start Cursor"); + timer.start(); + try { + this.stmt = getExportConn().createStatement(); + stmt.execute(getCursorQuery()); + } catch (SQLException ex) { + GaussUtils.handleCriticalException(ex); + throw new DatabaseOperationException(IMessagesConstants.ERR_DATABASE_OPERATION_FAILURE, ex); + } finally { + timer.stopAndLogNoException(); + } + } + + private void fetchFileRecords() throws MPPDBIDEException { + IExecTimer timer = new ExecTimer("fetch records"); + timer.start(); + int fetchedBatSize = 0; + int currFetchSize = 0; + int toFethRowCount = 0; + + for (int index = 0; index < this.fetchSize || this.fetchSize < 1;) { + if (this.fetchSize == -1) { + // Fetch All case. + currFetchSize = CURSOR_FETCH_BATCH_SIZE; + } else { + toFethRowCount = this.fetchSize - index; + currFetchSize = toFethRowCount > CURSOR_FETCH_BATCH_SIZE ? CURSOR_FETCH_BATCH_SIZE : toFethRowCount; + } + boolean isFirstBatch = false; + if (fetchedBatSize == 0) { + isFirstBatch = true; + } + fetchedBatSize = fetchSQLFileRecordBatch(currFetchSize, isFirstBatch); + index += fetchedBatSize; + writeToSqlFile(genrateUtil.getOutPutInsertSql().toString()); + genrateUtil.getOutPutInsertSql().delete(0, genrateUtil.getOutPutInsertSql().length()); + genrateUtil.getOutPutInsertSql().setLength(0); + if (fetchedBatSize < currFetchSize) { + timer.stop(); + return; + } + } + timer.stopAndLogNoException(); + } + + private void closeCursor() { + IExecTimer timer = new ExecTimer("close cursor"); + timer.start(); + try { + this.stmt.execute(getCloseCursorQuery()); + } catch (SQLException ex) { + // Ignore. No way to recover from close failure. + MPPDBIDELoggerUtility.error("Error closing a cursor.", ex); + } finally { + dbConn.closeStatement(stmt); + timer.stopAndLogNoException(); + } + } + + private String getCloseCursorQuery() { + return String.format(Locale.ENGLISH, CLOSE_QUERY, getUniqCursorName()); + } + + private String getCursorQuery() { + return String.format(Locale.ENGLISH, CURSOR_QUERY_PREPEND, getUniqCursorName(), exportQuery); + } + + /** + * To be changed to a uniq name. __DS_QRY_CRSR___ + * + * @return the uniq cursor name + */ + public String getUniqCursorName() { + if (null == cursorName) { + String timeStamp = new SimpleDateFormat("HHmmssSSS").format(new Date()); + cursorName = "__DS_GET_EXPORT_DATA_FOR_TABLE_CRSR_" + timeStamp + "__"; + } + + return cursorName; + } + + private void stopTxn() { + if (!needAutoCommitReset) { + return; + } + IExecTimer timer = new ExecTimer("Stop transaction"); + timer.start(); + + try { + Connection sqlConnection = getExportConn(); + // Set auto commit would issue a commit before changing the flag. + // Its a cautious call that "select fns()", might do an DML + // operation and need commit. + sqlConnection.setAutoCommit(true); + } catch (SQLException exception) { + // Ignore. Not mechanism to recover from this failure. + MPPDBIDELoggerUtility.error( + "Stop transaction after query execution failed. " + "No way to recover, and skiping this error", + exception); + } + timer.stopAndLogNoException(); + } + + /** + * writeToSqlFile write queries to file + * + * @param listOFQueries query list + * @throws MPPDBIDEException exception + */ + public void writeToSqlFile(String listOFQueries) throws MPPDBIDEException { + try { + Files.write(path, listOFQueries.getBytes(this.encoding), StandardOpenOption.APPEND); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.DIRTY_GENERATE_INSERT_DIALOG_SAVE_FILE_ERROR), + exception); + throw new MPPDBIDEException( + MessageConfigLoader.getProperty(IMessagesConstants.DIRTY_GENERATE_INSERT_DIALOG_SAVE_FILE_ERROR), + exception); + } + } + + private int fetchSQLFileRecordBatch(int currentFetchSize, boolean isFirstBatch) throws MPPDBIDEException { + ResultSet rs = null; + int recordFetchCounter = 0; + try { + rs = stmt.executeQuery(String.format(Locale.ENGLISH, FETCH_QUERY, currentFetchSize, getUniqCursorName())); + // header + while (rs.next()) { + recordFetchCounter++; + // data + if (!cancelled) { + genrateUtil.getAllRowsCount(rs, isFirstBatch); + if (recordFetchCounter == currentFetchSize) { + break; + } + } else { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.USER_CANCEL_MSG)); + throw new DatabaseOperationException(IMessagesConstants.USER_CANCEL_MSG); + } + } + return recordFetchCounter; + } catch (SQLException ex) { + GaussUtils.handleCriticalException(ex); + throw new DatabaseOperationException(IMessagesConstants.ERR_DATABASE_OPERATION_FAILURE, ex); + } finally { + closeResultSet(rs); + } + } + + private void closeResultSet(ResultSet rs) { + try { + if (null != rs) { + rs.close(); + } + } catch (SQLException ex) { + MPPDBIDELoggerUtility.error("Resultset close failed while materializing the records"); + } + } + + /** + * exportSequenceData export sequence data ddl + * + * @param name seq name + * @param nextValue seq next value + * @param called is end of value + * @return string ddl + */ + public String exportSequenceData(String name, long nextValue, boolean called) { + String queryDDL = String.format(Locale.ENGLISH, "SELECT pg_catalog.setVal('%s',%d,%b);", name, nextValue, + called); + return queryDDL; + } + + /** + * clean data + */ + public void cleanData() { + genrateUtil.cleanOutputInsertSql(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/ExportParameters.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/ExportParameters.java new file mode 100644 index 0000000000000000000000000000000000000000..d349093624d338f462857f9f5c8ba116cce53205 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/ExportParameters.java @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.export; + +import java.io.File; +import java.util.ArrayList; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; + +/** + * + * Title: class + * + * Description: The Class ExportParameters. + * + */ + +public class ExportParameters { + + private String encryptPwd; + private String path; + private Database db; + private EXPORTTYPE type; + private boolean isTablespaceOption; + private ArrayList objList; + File workingDir; + + /** + * Instantiates a new export parameters. + * + * @param pwd the pwd + * @param path the path + * @param db the db + * @param type the type + * @param obj the obj + * @param isTableSpaceOption the is table space option + * @param workingDir the working dir + */ + public ExportParameters(String pwd, String path, Database db, EXPORTTYPE type, ServerObject obj, + boolean isTableSpaceOption, File workingDir) { + this.encryptPwd = pwd; + this.path = path; + this.db = db; + this.type = type; + this.isTablespaceOption = isTableSpaceOption; + this.objList = new ArrayList(1); + objList.add(obj); + this.workingDir = workingDir; + } + + /** + * Instantiates a new export parameters. + * + * @param pwd the pwd + * @param path the path + * @param db the db + * @param type the type + * @param obj the obj + * @param isTableSpaceOption the is table space option + * @param workingDir the working dir + */ + public ExportParameters(String pwd, String path, Database db, EXPORTTYPE type, ArrayList obj, + boolean isTableSpaceOption, File workingDir) { + this.encryptPwd = pwd; + this.path = path; + this.db = db; + this.type = type; + this.isTablespaceOption = isTableSpaceOption; + this.objList = obj; + this.workingDir = workingDir; + } + + /** + * Sets the server object list. + * + * @param objs the new server object list + */ + public void setServerObjectList(ArrayList objs) { + this.objList = objs; + } + + /** + * Gets the password. + * + * @return the password + */ + public String getPassword() { + return encryptPwd; + } + + /** + * Gets the path. + * + * @return the path + */ + public String getPath() { + return path; + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDb() { + return db; + } + + /** + * Gets the export type. + * + * @return the export type + */ + public EXPORTTYPE getExportType() { + return type; + } + + /** + * Gets the server object. + * + * @return the server object + */ + public ServerObject getServerObject() { + return objList.get(0); + } + + /** + * Gets the server obj list. + * + * @return the server obj list + */ + public ArrayList getServerObjList() { + return objList; + } + + /** + * Checks if is tablespace option. + * + * @return true, if is tablespace option + */ + public boolean isTablespaceOption() { + return isTablespaceOption; + } + + /** + * Sets the file path. + * + * @param path2 the new file path + */ + public void setFilePath(String path2) { + this.path = path2; + } + + /** + * Gets the working dir. + * + * @return the working dir + */ + public File getWorkingDir() { + return workingDir; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/GenerateCursorExecuteUtil.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/GenerateCursorExecuteUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..047e6ba1046df8fe889844d8cb15245f831d4d5c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/GenerateCursorExecuteUtil.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.export; + +import java.io.UnsupportedEncodingException; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.utils.ConvertValueToInsertSqlFormat; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.ResultSetDatatypeMapping; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: GenerateCursorExecuteUtil + * + */ + +public class GenerateCursorExecuteUtil { + private List columnDatatype; + private int columnCount; + private List headerList; + private List rows; + private String typeName; + private List columnTypeName; + private String targetValue = null; + private ConvertValueToInsertSqlFormat convertValueToInsertSqlFormat; + private StringBuilder outPutInsertSql; + + private String tableNames; + private String encoding; + private boolean isOLAP; + + /** + * GenerateCursorExecuteUtil generate cursor util + */ + public GenerateCursorExecuteUtil(String tableNames, String encoding, boolean isOLAP) { + this.tableNames = tableNames; + this.encoding = encoding; + this.isOLAP = isOLAP; + + headerList = new ArrayList(); + convertValueToInsertSqlFormat = new ConvertValueToInsertSqlFormat(); + rows = new ArrayList(); + outPutInsertSql = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + } + + /** + * getAllRowsCount get all row + * + * @param rs result set + * @param isFirstBatch is first batch + * @return long count + * @throws DatabaseOperationException db exeception + * @throws SQLException sql exception + * @throws MPPDBIDEException mpp exception + */ + public long getAllRowsCount(ResultSet rs, boolean isFirstBatch) + throws DatabaseOperationException, SQLException, MPPDBIDEException { + long rowsCount = 0; + columnCount = rs.getMetaData().getColumnCount(); + columnDatatype = getColumnDatatype(columnCount, rs); + columnTypeName = getColumnDatatypeName(columnCount, rs); + headerList = getHeaderName(rs); + rows = new ArrayList(); + + int cnt = 0; + boolean suffix = false; + + try { + outPutInsertSql.append("INSERT INTO ").append(tableNames).append(" ("); + for (cnt = 1; cnt <= columnCount; ++cnt) { + suffix = addColumnNames(cnt, suffix); + } + suffix = false; + outPutInsertSql.append(")").append(MPPDBIDEConstants.LINE_SEPARATOR).append(" VALUES ("); + suffix = addInsertValues(rs, suffix); + suffix = false; + outPutInsertSql.append(");").append(MPPDBIDEConstants.LINE_SEPARATOR); + } catch (OutOfMemoryError exception) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_ALL_DATA_NOT_ENOUGH_SPACE), exception); + throw new DatabaseOperationException(IMessagesConstants.EXPORT_ALL_DATA_NOT_ENOUGH_SPACE); + } catch (UnsupportedEncodingException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_EXPORT_TABLE), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_EXPORT_TABLE); + } + rows.clear(); + rowsCount++; + return rowsCount; + } + + private boolean addColumnNames(int cnt, boolean suffixParam) { + boolean suffix = suffixParam; + targetValue = headerList.get(cnt - 1); + if (suffix) { + outPutInsertSql.append(","); + } + outPutInsertSql.append(ServerObject.getQualifiedSimpleObjectName(targetValue)); + suffix = true; + return suffix; + } + + private boolean addInsertValues(ResultSet rs, boolean suffixParam) + throws UnsupportedEncodingException, SQLException { + boolean suffix = suffixParam; + for (int j = 0; j <= columnCount - 1; ++j) { + if (suffix) { + outPutInsertSql.append(","); + } + String rowData = readContent(rs, true, j + 1); + typeName = columnTypeName.get(j); + outPutInsertSql + .append(convertValueToInsertSqlFormat.convertValueToSQL(columnDatatype.get(j), rowData, typeName)); + suffix = true; + } + return suffix; + } + + /** + * Gets the header name. + * + * @param rs the rs + * @return the header name + * @throws SQLException the SQL exception + */ + public List getHeaderName(ResultSet rs) throws SQLException { + headerList = new ArrayList(); + if (rs.getMetaData() != null) { + for (int index = 1; index <= columnCount; index++) { + headerList.add(rs.getMetaData().getColumnName(index)); + } + } + return headerList; + } + + private String readContent(ResultSet rs, boolean needEncode, int index) + throws UnsupportedEncodingException, SQLException { + if (isOLAP && needEncode) { + byte[] content = rs.getBytes(index); + if (null == content) { + return null; + } + return new String(content, encoding); + } else { + return rs.getString(index); + } + } + + /** + * Gets the column datatype. + * + * @param colCount the col count + * @param rs the rs + * @return the column datatype + * @throws SQLException the SQL exception + */ + public List getColumnDatatype(int colCount, ResultSet rs) throws SQLException { + List columnList = new ArrayList(); + if (rs.getMetaData() != null) { + for (int i = 1; i <= colCount; i++) { + columnList.add(rs.getMetaData().getColumnType(i)); + } + } + return columnList; + } + + /** + * Gets the column datatype name. + * + * @param colCount the col count + * @param rs the rs + * @return the column datatype name + * @throws SQLException the SQL exception + */ + private List getColumnDatatypeName(int colCount, ResultSet rs) throws SQLException { + List columnNameList = new ArrayList(); + if (rs.getMetaData() != null) { + for (int index = 1; index <= colCount; index++) { + columnNameList.add(rs.getMetaData().getColumnTypeName(index)); + } + } + return columnNameList; + } + + /** + * @return getOutPutInsertSql sql + */ + public StringBuilder getOutPutInsertSql() { + return outPutInsertSql; + } + + /** + * cleanOutputInsertSql clean sql + */ + public void cleanOutputInsertSql() { + outPutInsertSql = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + } + +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/IExportGrantRevokePriv.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/IExportGrantRevokePriv.java new file mode 100644 index 0000000000000000000000000000000000000000..3827b8132d074e4f7ddf2c03f56471bde24ed9b3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/IExportGrantRevokePriv.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.export; + +/** + * Title: IExportGrantRevokePriv + * + */ + +public interface IExportGrantRevokePriv { + String PRIV_EXECUTE = "EXECUTE"; // 'X' + String PRIV_USAGE = "USAGE"; // 'U' + String PRIV_CREATE = "CREATE"; // 'C' + String PRIV_UPDATE = "UPDATE"; // 'w' + String PRIV_INSERT = "INSERT"; // 'a' + String PRIV_REFERENCES = "REFERENCES"; // 'x' + String PRIV_DELETE = "DELETE"; // 'd' + String PRIV_TRIGGER = "TRIGGER"; // 't' + String PRIV_TRUNCATE = "TRUNCATE"; // 'D' + +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/IExportManager.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/IExportManager.java new file mode 100644 index 0000000000000000000000000000000000000000..c71feb8c8092fb5bbe8bbf92da66c99268ae8348 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/IExportManager.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.export; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.utils.exceptions.DataStudioSecurityException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: interface + * + * Description: The Interface IExportManager. + * + */ + +public interface IExportManager { + + /** + * Export sql to file. + * + * @param path the path + * @param type the type + * @param object the object + * @param isTablespaceOption the is tablespace option + * @param workingDir the working dir + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws DataStudioSecurityException the data studio security exception + */ + void exportSqlToFile(String path, EXPORTTYPE type, ServerObject object, boolean isTablespaceOption, File workingDir) + throws DatabaseOperationException, DatabaseCriticalException, DataStudioSecurityException; + + /** + * Export sql to files. + * + * @param path the path + * @param type the type + * @param object the object + * @param isTablespaceOption the is tablespace option + * @param workingDir the working dir + * @param encryptedPwd encrypted psw + * @return the list + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws DataStudioSecurityException the data studio security exception + */ + List exportSqlToFiles(String path, EXPORTTYPE type, ArrayList object, + boolean isTablespaceOption, File workingDir, String encryptedPwd) + throws DatabaseOperationException, DatabaseCriticalException, DataStudioSecurityException; + + /** + * Export sql to file. + * + * @param expParameter the exp parameter + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws DataStudioSecurityException the data studio security exception + */ + void exportSqlToFile(ExportParameters expParameter) + throws DatabaseOperationException, DatabaseCriticalException, DataStudioSecurityException; + + /** + * Cancel. + */ + void cancel(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/PrivilegeParameters.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/PrivilegeParameters.java new file mode 100644 index 0000000000000000000000000000000000000000..96b5da5fc692723bd4dd88254a85bd7e03d86976 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/export/PrivilegeParameters.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.export; + +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * Title: PrivilegeParameters + * + */ + +public class PrivilegeParameters { + private boolean allWithoutGo = true; + private boolean allWithGo = true; + private String privString; + private StringBuffer priviledgeBuff = new StringBuffer(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + private StringBuffer previlegeWithGrantBuff = new StringBuffer(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + public void setPriviledgeBuff(StringBuffer priviledgeBuff) { + this.priviledgeBuff = priviledgeBuff; + } + + public void setPrevilegeWithGrantBuff(StringBuffer previlegeWithGrantBuff) { + this.previlegeWithGrantBuff = previlegeWithGrantBuff; + } + + public StringBuffer getPriviledgeBuff() { + return priviledgeBuff; + } + + public StringBuffer getPrevilegeWithGrantBuff() { + return previlegeWithGrantBuff; + } + + public boolean isAllWithoutGo() { + return allWithoutGo; + } + + public void setAllWithoutGo(boolean allWithoutGo) { + this.allWithoutGo = allWithoutGo; + } + + public boolean isAllWithGo() { + return allWithGo; + } + + public void setAllWithGo(boolean allWithGo) { + this.allWithGo = allWithGo; + } + + public String getPrivString() { + return privString; + } + + public void setPrivString(String privString) { + this.privString = privString; + } + +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/importexportdata/ImportExportDataExecuter.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/importexportdata/ImportExportDataExecuter.java new file mode 100644 index 0000000000000000000000000000000000000000..3c1d8874833b4189febd83320e1da20941a063ca --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/importexportdata/ImportExportDataExecuter.java @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.importexportdata; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.file.Path; + +import org.apache.commons.io.FileUtils; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.export.ExportManager; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class ImportExportDataExecuter. + * + */ + +public class ImportExportDataExecuter { + + /** + * Export data. + * + * @param path the path + * @param sql the sql + * @param conn the conn + * @param encoding the encoding + * @param fileFormat the file format + * @return the long + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public long exportData(Path path, String sql, DBConnection conn, String encoding, String fileFormat) + throws MPPDBIDEException { + long totalRows = 0; + + FileOutputStream fileOutStream = null; + try { + fileOutStream = new FileOutputStream(path.toString(), true); + if (!MPPDBIDEConstants.BINARY_FILE_FORMAT.equalsIgnoreCase(fileFormat)) { + ExportManager.prependBomForUtf8(encoding, fileOutStream); + } + + totalRows = conn.execExportData(sql, fileOutStream); + } catch (FileNotFoundException exp) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_EXPORT_TABLE), exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_EXPORT_TABLE, exp); + } finally { + if (fileOutStream != null) { + try { + fileOutStream.close(); + } catch (IOException e) { + fileOutStream = null; + + } + } + } + + return totalRows; + } + + /** + * Import tabledata. + * + * @param sql the sql + * @param path the path + * @param conn the conn + * @return the long + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public long importTabledata(String sql, String path, DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + FileInputStream fileStream = null; + long totalRows = 0; + + double fileLimit = BLPreferenceManager.getInstance().getBLPreference().getImportFileSizeInMb(); + double fileSizeInMB = FileUtils.sizeOf(new File(path)) / (double) (1024 * 1024); + + if (fileLimit != 0 && fileSizeInMB > fileLimit) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.FILE_LIMIT_WARNING_MESSAGE)); + throw new DatabaseOperationException(IMessagesConstants.FILE_LIMIT_WARNING_MESSAGE); + } + + try { + fileStream = new FileInputStream(path); + totalRows = conn.execImportTableData(sql, fileStream); + } catch (FileNotFoundException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_EXPORT_TABLE), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_EXPORT_TABLE, exception); + } finally { + try { + if (fileStream != null) { + fileStream.close(); + } + + } catch (IOException ex) { + fileStream = null; + } + + } + + return totalRows; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/keyword/KeywordObject.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/keyword/KeywordObject.java new file mode 100644 index 0000000000000000000000000000000000000000..a3feee5ed6162d289210692c8188db95caa2c0a4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/keyword/KeywordObject.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.keyword; + +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; + +/** + * Title: KeywordObject + * + */ + +public class KeywordObject extends ServerObject { + + /** + * Instantiates a new keyword object. + * + * @param oid the oid + * @param name the name + * @param type the type + * @param privilegeFlag the privilege flag + */ + public KeywordObject(long oid, String name, OBJECTTYPE type, boolean privilegeFlag) { + super(oid, name, type, privilegeFlag); + } + + /** + * Gets the search name. + * + * @return the search name + */ + @Override + public String getSearchName() { + return getName() + " - " + getTypeLabel(); + } + + /** + * Gets the qualified object name. + * + * @return the qualified object name + */ + @Override + public String getQualifiedObjectName() { + return getName(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/preferences/BLPreferenceManager.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/preferences/BLPreferenceManager.java new file mode 100644 index 0000000000000000000000000000000000000000..82433415d50f6eb406901fddbb4c509892f58f0c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/preferences/BLPreferenceManager.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.preferences; + +/** + * + * Title: class + * + * Description: The Class BLPreferenceManager. + * + */ + +public class BLPreferenceManager { + + private static volatile BLPreferenceManager instance = null; + private static final Object LOCK = new Object(); + private IBLPreference systemPrefs = null; + + private BLPreferenceManager() { + } + + /** + * Gets the single instance of BLPreferenceManager. + * + * @return single instance of BLPreferenceManager + */ + public static BLPreferenceManager getInstance() { + if (null == instance) { + synchronized (LOCK) { + if (null == instance) { + instance = new BLPreferenceManager(); + } + } + } + return instance; + + } + + /** + * Gets the BL preference. + * + * @return the BL preference + */ + public IBLPreference getBLPreference() { + return systemPrefs; + } + + /** + * Sets the BL preference. + * + * @param prefs the new BL preference + */ + public void setBLPreference(IBLPreference prefs) { + systemPrefs = prefs; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/preferences/IBLPreference.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/preferences/IBLPreference.java new file mode 100644 index 0000000000000000000000000000000000000000..834f3bdc3fcfe928b42b9f05d94e3fb14f0790f3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/preferences/IBLPreference.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.preferences; + +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: interface + * + * Description: The Interface IBLPreference. + */ + +public interface IBLPreference { + + /** + * Gets the SQL history size. + * + * @return the SQL history size + */ + int getSQLHistorySize(); + + /** + * Gets the SQL query length. + * + * @return the SQL query length + */ + int getSQLQueryLength(); + + /** + * Gets the DS encoding. + * + * @return the DS encoding + */ + String getDSEncoding(); + + /** + * Gets the file encoding. + * + * @return the file encoding + */ + String getFileEncoding(); + + /** + * Checks if is include encoding. + * + * @return true, if is include encoding + */ + boolean isIncludeEncoding(); + + /** + * Get Object Browser lazy rendering object count + * + * @return object count + */ + default int getLazyRenderingObjectCount() { + return MPPDBIDEConstants.DEFAULT_TREE_NODE_COUNT; + }; + + /** + * gets the date format + * + * @return the date format + */ + String getDateFormat(); + + /** + * gets the time format + * + * @return the time format + */ + String getTimeFormat(); + + /** + * gets import file size limit + * + * @return returns the size limit of import file + */ + default int getImportFileSizeInMb() { + return 0; + }; + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/queryparser/IParseContextGetter.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/queryparser/IParseContextGetter.java new file mode 100644 index 0000000000000000000000000000000000000000..0a3f8509a111ef3d0967af476e8594370ea4c2c0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/queryparser/IParseContextGetter.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.queryparser; + +/** + * + * Title: interface + * + * Description: The Interface IParseContextGetter. + * + * @since 3.0.0 + */ +public interface IParseContextGetter { + + /** + * Parses the query. + * + * @param query the query + */ + public void parseQuery(String query); + + /** + * Gets the parses the context. + * + * @return the parses the context + */ + public ParseContext getParseContext(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/queryparser/ParseContext.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/queryparser/ParseContext.java new file mode 100644 index 0000000000000000000000000000000000000000..4373f65ec108de638316a9d8ed8f02259a9ecf2c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/queryparser/ParseContext.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.queryparser; + +import java.util.HashMap; +import java.util.List; + +/** + * + * Title: class + * + * Description: The Class ParseContext. + * + */ + +public class ParseContext { + + private HashMap> aliasToTableNameMap; + + /** + * Instantiates a new parses the context. + */ + public ParseContext() { + aliasToTableNameMap = new HashMap>(1); + } + + /** + * Gets the alias to table name map. + * + * @return the alias to table name map + */ + public HashMap> getAliasToTableNameMap() { + return this.aliasToTableNameMap; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/search/SearchDatabase.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/search/SearchDatabase.java new file mode 100644 index 0000000000000000000000000000000000000000..aff4c4db6e4902c4b6da501d980f0a27577126b2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/search/SearchDatabase.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.search; + +import java.util.List; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.groups.OLAPObjectGroup; + +/** + * + * Title: class + * + * Description: The Class SearchDatabase. + * + */ + +public class SearchDatabase extends Database { + + private OLAPObjectGroup searchNs; + private Database db; + + /** + * Instantiates a new search database. + * + * @param server the server + * @param oid the oid + * @param selectedDb the selected db + */ + public SearchDatabase(Server server, long oid, Database selectedDb) { + super(server, oid, selectedDb.getName()); + this.db = selectedDb; + searchNs = new OLAPObjectGroup(OBJECTTYPE.NAMESPACE_GROUP, this); + + } + + /** + * Gets the db. + * + * @return the db + */ + public Database getDb() { + return this.db; + } + + /** + * Adds the search namespaces. + * + * @param searchNameSpace the search name space + */ + public void addSearchNamespaces(SearchNamespace searchNameSpace) { + this.searchNs.addToGroup(searchNameSpace); + + } + + /** + * Gets the all search name spaces. + * + * @return the all search name spaces + */ + public List getAllSearchNameSpaces() { + + return this.searchNs.getSortedServerObjectList(); + } + + @Override + public boolean equals(Object obj) { + return db.equals(obj); + } + + @Override + public int hashCode() { + + return db.hashCode(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/search/SearchNameMatchEnum.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/search/SearchNameMatchEnum.java new file mode 100644 index 0000000000000000000000000000000000000000..dc6c8e6e01ea50c358b69a3fee7c47b51991793d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/search/SearchNameMatchEnum.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.search; + +/** + * + * Title: enum + * + * Description: The Enum SearchNameMatchEnum. + * + */ + +public enum SearchNameMatchEnum { + CONTAINS, STARTS_WITH, EXACT_WORD, REGULAR_EXPRESSION + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/search/SearchNamespace.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/search/SearchNamespace.java new file mode 100644 index 0000000000000000000000000000000000000000..b7c823b7a6ba7b0075155b9ec6c96adc689665d0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/search/SearchNamespace.java @@ -0,0 +1,259 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.search; + +import java.util.ArrayList; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.SequenceMetadata; +import org.opengauss.mppdbide.bl.serverdatacache.SynonymMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TriggerMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.groups.DebugObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ForeignTableGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.OLAPObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.SequenceObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.SynonymObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.TableObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.TriggerObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ViewObjectGroup; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class SearchNamespace. + * + */ + +public class SearchNamespace extends Namespace { + + private DebugObjectGroup searchFunctions; + private TableObjectGroup searchTables; + private ViewObjectGroup searchViews; + private ForeignTableGroup searchForeigntables; + private SequenceObjectGroup searchsequence; + private SynonymObjectGroup searchSynonym; + private TriggerObjectGroup searchTrigger; + + /** + * Instantiates a new search namespace. + * + * @param oid the oid + * @param name the name + * @param parentDb the parent db + */ + public SearchNamespace(long oid, String name, Database parentDb) { + super(oid, name, parentDb); + + searchFunctions = new DebugObjectGroup(OBJECTTYPE.FUNCTION_GROUP, this); + searchTables = new TableObjectGroup(OBJECTTYPE.TABLE_GROUP, this); + searchViews = new ViewObjectGroup(this); + searchForeigntables = new ForeignTableGroup(OBJECTTYPE.FOREIGN_TABLE_GROUP, this); + searchsequence = new SequenceObjectGroup(OBJECTTYPE.SEQUENCE_GROUP, this); + searchSynonym = new SynonymObjectGroup(OBJECTTYPE.SYNONYM_GROUP, this); + searchTrigger = new TriggerObjectGroup(this); + } + + @Override + public DebugObjectGroup getFunctions() { + return this.searchFunctions; + } + + @Override + public TableObjectGroup getTables() { + return this.searchTables; + } + + /** + * Gets the tables group. + * + * @return the tables group + */ + public TableObjectGroup getTablesGroup() { + return this.searchTables; + } + + @Override + public ViewObjectGroup getViewGroup() { + return this.searchViews; + } + + @Override + public SequenceObjectGroup getSequenceGroup() { + + return this.searchsequence; + } + + @Override + public SynonymObjectGroup getSynonymGroup() { + return this.searchSynonym; + } + + @Override + public TriggerObjectGroup getTriggerObjectGroup() { + return this.searchTrigger; + } + + @Override + public ForeignTableGroup getForeignTablesGroup() { + return this.searchForeigntables; + } + + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } + + @Override + public int hashCode() { + + return super.hashCode(); + } + + @Override + public Object[] getChildren() { + + @SuppressWarnings("rawtypes") + + ArrayList objectGroup = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + if (searchFunctions.getSize() > 0) { + objectGroup.add(this.getFunctions()); + } + if (searchTables.getSize() > 0) { + objectGroup.add(this.getTables()); + } + if (searchViews.getSize() > 0) { + objectGroup.add(this.getViewGroup()); + } + if (searchForeigntables.getSize() > 0) { + objectGroup.add(this.getForeignTablesGroup()); + } + if (searchsequence.getSize() > 0) { + objectGroup.add(this.getSequenceGroup()); + } + if (searchSynonym.getSize() > 0) { + objectGroup.add(this.getSynonymGroup()); + } + if (searchTrigger.getSize() > 0) { + objectGroup.add(this.getTriggerObjectGroup()); + } + + return objectGroup.toArray(); + + } + + @Override + public void addView(ViewMetaData view) { + this.getViewGroup().addToGroup(view); + this.getDatabase().getSearchPoolManager().addviewToSearchPool(view); + } + + /** + * Gets the size. + * + * @return the size + */ + public int getSize() { + int size = this.getFunctions().getSize() + this.getTables().getSize() + this.getViewGroup().getSize() + + this.getForeignTablesGroup().getSize() + this.getSequenceGroup().getSize() + + this.getSynonymGroup().getSize(); + return size; + + } + + @Override + public void addSequence(SequenceMetadata sequence) { + this.getSequenceGroup().addToGroup(sequence); + } + + @Override + public void clearAllObjects() { + if (null != searchFunctions) { + searchFunctions.clear(); + } + if (null != searchTables) { + searchTables.clear(); + } + if (null != searchViews) { + searchViews.clear(); + } + if (null != searchForeigntables) { + searchForeigntables.clear(); + } + if (null != searchsequence) { + searchsequence.clear(); + } + if (null != searchSynonym) { + searchSynonym.clear(); + } + + } + + /** + * Adds the to foreign group. + * + * @param forTable the for table + */ + public void addToForeignGroup(TableMetaData forTable) { + getForeignTablesGroup().addToGroup(forTable); + getDatabase().getSearchPoolManager().addTableToSearchPool(forTable); + } + + /** + * Adds the to sequence group. + * + * @param seq the seq + */ + public void addToSequenceGroup(SequenceMetadata seq) { + getSequenceGroup().addToGroup(seq); + getDatabase().getSearchPoolManager().addsequenceToSearchPool(seq); + } + + /** + * Adds the to synonym group. + * + * @param synonym the syn + */ + public void addToSynonymGroup(SynonymMetaData syn) { + getSynonymGroup().addToGroup(syn); + getDatabase().getSearchPoolManager().addsynonymToSearchPool(syn); + } + + /** + * Adds the to trigger group. + * + * @param triggerMetaData the trigger metadata + */ + public void addToTrigerGroup(TriggerMetaData triggerMetaData) { + getTriggerObjectGroup().addToGroup(triggerMetaData); + getDatabase().getSearchPoolManager().addTriggerToSearchPool(triggerMetaData); + } + + /** + * Adds the view to group. + * + * @param view the view + */ + public void addViewToGroup(ViewMetaData view) { + addView(view); + getDatabase().getSearchPoolManager().addviewToSearchPool(view); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/search/SearchObjectEnum.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/search/SearchObjectEnum.java new file mode 100644 index 0000000000000000000000000000000000000000..196abe0bcfb82f0052688fbfd7100b52ebe9857c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/search/SearchObjectEnum.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.search; + +/** + * + * Title: enum + * + * Description: The Enum SearchObjectEnum. + * + */ + +public enum SearchObjectEnum { + SEARCH_INI, SEARCH_START, SEARCH_END, DATABASELIST_UPDATE, DATABSEITEM_SELECT, NO_DB_SELECTED +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/AccessMethod.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/AccessMethod.java new file mode 100644 index 0000000000000000000000000000000000000000..833538b44f8a36efe7436959a33037cfae3a70cf --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/AccessMethod.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class AccessMethod. + * + */ + +public class AccessMethod extends ServerObject implements GaussOLAPDBMSObject { + + /** + * Instantiates a new access method. + * + * @param oid the oid + * @param name the name + */ + public AccessMethod(long oid, String name) { + super(oid, name, OBJECTTYPE.ACCESSMETHOD, false); + } + + /** + * Convert to access method. + * + * @param rs the rs + * @param server the server + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static void convertToAccessMethod(ResultSet rs, Server server) + throws DatabaseCriticalException, DatabaseOperationException { + try { + long oid = rs.getLong("oid"); + String name = rs.getString("amname"); + AccessMethod am = new AccessMethod(oid, name); + server.addToAccessMethods(am); + } catch (SQLException eexp) { + GaussUtils.handleCriticalException(eexp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, eexp); + } + + } + + /** + * Fetch all access methods. + * + * @param db the db + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static void fetchAllAccessMethods(Database db) throws DatabaseCriticalException, DatabaseOperationException { + int counter = 0; + + String qry = "SELECT oid, amname from pg_am order by oid;"; + ResultSet rs = null; + boolean hasNextRecord = false; + + try { + rs = db.getConnectionManager().execSelectAndReturnRsOnObjBrowserConn(qry); + hasNextRecord = rs.next(); + while (hasNextRecord) { + AccessMethod.convertToAccessMethod(rs, db.getServer()); + counter++; + hasNextRecord = rs.next(); + } + } catch (SQLException sqle) { + try { + GaussUtils.handleCriticalException(sqle); + } catch (DatabaseCriticalException dc) { + throw dc; + } + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + sqle); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, sqle); + } finally { + if (MPPDBIDELoggerUtility.isTraceEnabled()) { + MPPDBIDELoggerUtility + .trace("Total Number of access methods loaded for selected server is : " + counter); + } + + db.getConnectionManager().closeRSOnObjBrowserConn(rs); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/Alias.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/Alias.java new file mode 100644 index 0000000000000000000000000000000000000000..1d4b2aba6435370e4b21114ae78fc49d7cb78106 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/Alias.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: class + * + * Description: The Class Alias. + * + */ + +public class Alias extends ServerObject { + + /** + * Instantiates a new alias. + * + * @param name the name + * @param type the type + */ + public Alias(String name, OBJECTTYPE type) { + super(-1, name, type, false); + } + + @Override + public String getAutoSuggestionName(boolean isAutoSuggest) { + return super.getQualifiedObjectNameHandleQuotes(this.getName()); + } + +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/BatchDropServerObject.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/BatchDropServerObject.java new file mode 100644 index 0000000000000000000000000000000000000000..14ce0b51cb20221f3b73ae698c7640f2d6a86e46 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/BatchDropServerObject.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import org.opengauss.mppdbide.bl.IServerObjectBatchOperations; +import org.opengauss.mppdbide.bl.export.EXPORTTYPE; + +/** + * + * Title: class + * + * Description: The Class BatchDropServerObject. + * + */ + +public abstract class BatchDropServerObject extends ServerObject implements IServerObjectBatchOperations { + + /** + * Instantiates a new batch drop server object. + * + * @param oid the oid + * @param name the name + * @param type the type + * @param privilegeFlag the privilege flag + */ + public BatchDropServerObject(long oid, String name, OBJECTTYPE type, boolean privilegeFlag) { + super(oid, name, type, privilegeFlag); + } + + /** + * Instantiates a new batch drop server object. + * + * @param type the type + */ + public BatchDropServerObject(OBJECTTYPE type) { + super(type); + } + + /** + * get Drop Query. + * + * @param isCascade the is cascade + * @return the drop query + */ + @Override + public abstract String getDropQuery(boolean isCascade); + + @Override + public String getObjectFullName() { + + return getDisplayName(); + } + + @Override + public String getObjectTypeName() { + + return getTypeLabel(); + } + + @Override + public boolean isDropAllowed() { + return true; + } + + @Override + public boolean isExportAllowed(EXPORTTYPE exportType) { + + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ColumnMetaData.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ColumnMetaData.java new file mode 100644 index 0000000000000000000000000000000000000000..c9689710c677793ac8568b4a265c24273ed79817 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ColumnMetaData.java @@ -0,0 +1,940 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: class + * + * Description: The Class ColumnMetaData. + * + */ + +public class ColumnMetaData extends BatchDropServerObject implements GaussOLAPDBMSObject { + + private String dataTypeSchema; + + private TypeMetaData dataType; + + private int lenOrPrecision; + + private int scale; + + private int arrayNDim; /* number of dimensions */ + + private boolean isNotNull; + + private boolean hasDefVal; + + private String attDefString; + + private String defaultValue; + + private String checkConstraintExpr; + + private boolean isUnique; + + private boolean isLoaded; + + private TableMetaData parentTable; + + private String displayDatatypeName; + + private boolean columnCase; + + private boolean isDistributionColm; + + private boolean isFunction; + + private String colDescription; + + /** + * Gets the col description. + * + * @return the col description + */ + public String getColDescription() { + return colDescription; + } + + /** + * Sets the col description. + * + * @param colDescription the new col description + */ + public void setColDescription(String colDescription) { + this.colDescription = colDescription; + } + + /** + * Instantiates a new column meta data. + * + * @param parentTable the parent table + * @param oid the oid + * @param name the name + * @param dataType the data type + */ + public ColumnMetaData(TableMetaData parentTable, long oid, String name, TypeMetaData dataType) { + super(oid, name, OBJECTTYPE.COLUMN_METADATA, false); + this.parentTable = parentTable; + this.dataType = dataType; + this.isLoaded = false; + } + + /** + * Sets the att def string. + * + * @param attrDefStr the new att def string + */ + public void setAttDefString(String attrDefStr) { + this.attDefString = attrDefStr; + } + + /** + * Gets the att def string. + * + * @return the att def string + */ + public String getAttDefString() { + return this.attDefString; + } + + /** + * Gets the len or precision. + * + * @return the len or precision + */ + public int getLenOrPrecision() { + return lenOrPrecision; + } + + /** + * Sets the len or precision. + * + * @param lenOrPrecision the new len or precision + */ + public void setLenOrPrecision(int lenOrPrecision) { + this.lenOrPrecision = lenOrPrecision; + } + + /** + * Gets the scale. + * + * @return the scale + */ + public int getScale() { + return scale; + } + + /** + * Sets the scale. + * + * @param scale the new scale + */ + public void setScale(int scale) { + this.scale = scale; + } + + /** + * Gets the array N dim. + * + * @return the array N dim + */ + public int getArrayNDim() { + return arrayNDim; + } + + /** + * Sets the array N dim. + * + * @param arrayNDim the new array N dim + */ + public void setArrayNDim(int arrayNDim) { + + this.arrayNDim = arrayNDim; + } + + /** + * Gets the default value. + * + * @return the default value + */ + public String getDefaultValue() { + return defaultValue; + } + + /** + * Sets the default value. + * + * @param defaultValue the new default value + */ + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + /** + * Checks if is not null. + * + * @return true, if is not null + */ + public boolean isNotNull() { + return isNotNull; + } + + /** + * Checks if is unique. + * + * @return true, if is unique + */ + public boolean isUnique() { + return isUnique; + } + + /** + * Sets the checks for def val. + * + * @param val the new checks for def val + */ + public void setHasDefVal(boolean val) { + this.hasDefVal = val; + } + + /** + * Gets the checks for def val. + * + * @return the checks for def val + */ + public boolean getHasDefVal() { + return this.hasDefVal; + } + + /** + * Column details. + * + * @param displayColumns the display columns + * @param isCreate the is create + * @return the string[] + */ + public String[] columnDetails(int displayColumns, boolean isCreate) { + StringBuilder query = new StringBuilder(512); + String[] returnValue = new String[4]; + + if (isCreate) { + returnValue[0] = getName(); + } else { + StringBuilder tmpColName = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + String columnName = getName(); + tmpColName.append(columnName); + returnValue[0] = tmpColName.toString(); + } + + query.append(' '); + + appendDataTypeInfoInQuery(isCreate, query); + + for (int i = 0; i < this.arrayNDim; i++) { + query.append("[]"); + } + + returnValue[1] = query.toString(); + + query.setLength(0); + if (this.isNotNull) { + query.append(" NOT NULL"); + } + + if (null != this.defaultValue) { + query.append(" DEFAULT "); + query.append(getIsFunction() ? this.defaultValue : ServerObject.getLiteralName(this.defaultValue)); + } + + if (this.isUnique) { + query.append(" UNIQUE"); + } + + if (null != this.checkConstraintExpr) { + query.append(" CHECK ("); + query.append(this.checkConstraintExpr); + query.append(") "); + } + + returnValue[2] = query.toString(); + returnValue[3] = this.colDescription; + return returnValue; + } + + /** + * Append data type info in query. + * + * @param isCreate the is create + * @param query the query + */ + private void appendDataTypeInfoInQuery(boolean isCreate, StringBuilder query) { + + if (null != this.dataTypeSchema) { + query.append(this.dataTypeSchema); + query.append('.'); + } + + if (!isCreate) { + query.append(this.displayDatatypeName); + } else { + if (null != dataType) { + query.append(this.dataType.getName()); + } + if (this.lenOrPrecision > 0) { + query.append('('); + query.append(this.lenOrPrecision); + if (0 != this.scale) { + query.append(','); + query.append(this.scale); + } + query.append(')'); + } + } + } + + /** + * Sets the data type scheam. + * + * @param dataTypeSchm the new data type scheam + */ + public void setDataTypeScheam(String dataTypeSchm) { + this.dataTypeSchema = dataTypeSchm; + } + + /** + * Gets the data type schema. + * + * @return the data type schema + */ + public String getColDataTypeSchema() { + return dataTypeSchema; + } + + /** + * Sets the pre. + * + * @param len the len + * @param scl the scl + */ + public void setPre(int len, int scl) { + this.lenOrPrecision = len; + this.scale = scl; + } + + /** + * Sets the not null. + * + * @param isNtNull the new not null + */ + public void setNotNull(boolean isNtNull) { + this.isNotNull = isNtNull; + } + + /** + * Sets the unique. + * + * @param isUnqe the new unique + */ + public void setUnique(boolean isUnqe) { + this.isUnique = isUnqe; + } + + /** + * Sets the check constraint. + * + * @param checkConsExpr the new check constraint + */ + public void setCheckConstraint(String checkConsExpr) { + this.checkConstraintExpr = checkConsExpr; + } + + /** + * Gets the check constraint expr. + * + * @return the check constraint expr + */ + public String getCheckConstraintExpr() { + return checkConstraintExpr; + } + + /** + * Form column string. + * + * @param isCreateTable the is create table + * @return the string + */ + public String formColumnString(boolean isCreateTable) { + StringBuilder query = new StringBuilder(512); + boolean isSchemaselected = false; + + query.append(ServerObject.getQualifiedObjectName(getName())); + + query.append(' '); + + if (null != this.dataTypeSchema) { + query.append(ServerObject.getQualifiedObjectName(this.dataTypeSchema)); + query.append('.'); + isSchemaselected = true; + } + + if (null != this.dataType) { + if (isSchemaselected) { + query.append(this.dataType.getDisplayName()); + } else { + query.append(this.dataType.getName()); + } + + } + formPrecisionAndArrayDimensionForQuery(query); + + if (this.isNotNull) { + query.append(" NOT NULL"); + } + + if (null != this.defaultValue) { + query.append(" DEFAULT "); + query.append(getIsFunction() ? this.defaultValue : ServerObject.getLiteralName(this.defaultValue)); + } + + if (this.isUnique) { + if (parentTable.getOrientation() == TableOrientation.ROW) { + query.append(" UNIQUE"); + } + } + + if (null != this.checkConstraintExpr) { + if (parentTable.getOrientation() == TableOrientation.ROW) { + query.append(" CHECK ( "); + query.append(this.checkConstraintExpr); + query.append(" )"); + } + } + + return query.toString(); + } + + /** + * Form precision and array dimension for query. + * + * @param query the query + */ + public void formPrecisionAndArrayDimensionForQuery(StringBuilder query) { + if (0 != this.lenOrPrecision) { + query.append('('); + query.append(this.lenOrPrecision); + if (0 != this.scale) { + query.append(','); + query.append(this.scale); + } + query.append(')'); + } + + for (int index = 0; index < this.arrayNDim; index++) { + if (parentTable.getOrientation() == TableOrientation.ROW) { + query.append("[]"); + } + } + } + + /** + * Exec alter toggle set null. + * + * @param dbConnection the db connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void execAlterToggleSetNull(DBConnection dbConnection) + throws DatabaseOperationException, DatabaseCriticalException { + StringBuilder qry = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + qry.append("ALTER TABLE ").append(parentTable.getDisplayName()).append(" ALTER COLUMN ") + .append(super.getQualifiedObjectName()); + + if (!this.isNotNull) { + qry.append(" SET NOT NULL "); + } else { + qry.append(" DROP NOT NULL "); + } + + dbConnection.execNonSelectForTimeout(qry.toString()); + this.isNotNull = !this.isNotNull; + + } + + /** + * Exec alter default. + * + * @param expr the expr + * @param isFunc the is func + * @param dbConnection the db connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void execAlterDefault(String expr, boolean isFunc, DBConnection dbConnection) + throws DatabaseOperationException, DatabaseCriticalException { + StringBuilder qry = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + qry.append("ALTER TABLE ").append(parentTable.getDisplayName()).append(" ALTER COLUMN ") + .append(super.getQualifiedObjectName()); + + if (null == expr || expr.length() < 1) { + qry.append(" DROP DEFAULT "); + } else { + qry.append(" SET DEFAULT ").append(isFunc ? expr : ServerObject.getLiteralName(expr)); + } + + dbConnection.execNonSelectForTimeout(qry.toString()); + this.isNotNull = !this.isNotNull; + + /* + * if alter query executes successfully, i.e. execution reaches here (no + * exception), then only set expression flag + */ + setIsFunction(isFunc); + + } + + /** + * Gets the parent table. + * + * @return the parent table + */ + public TableMetaData getParentTable() { + return parentTable; + } + + /** + * Exec alter add column. + * + * @param dbConnection the db connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void execAlterAddColumn(DBConnection dbConnection) + throws DatabaseOperationException, DatabaseCriticalException { + StringBuilder qry = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + qry.append("ALTER TABLE ").append(this.getParentTable().getDisplayName()).append(" ADD COLUMN ") + .append(formColumnString(false)).append(MPPDBIDEConstants.SEMICOLON); + qry.append(MPPDBIDEConstants.LINE_SEPARATOR).append(formSetCommentQuery()); + + dbConnection.execNonSelectForTimeout(qry.toString()); + } + + /** + * Sets the description. + * + * @param columnName the column name + * @param desc the desc + * @param dbConnection the db connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void setDescription(String columnName, String desc, DBConnection dbConnection) + throws DatabaseOperationException, DatabaseCriticalException { + StringBuilder query = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + query.append("COMMENT ON COLUMN " + columnName + " IS " + ServerObject.getLiteralName(desc)); + dbConnection.execNonSelectForTimeout(query.toString()); + } + + /** + * Exec drop. + * + * @param dbConnection the db connection + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void execDrop(DBConnection dbConnection) throws DatabaseCriticalException, DatabaseOperationException { + StringBuilder qry = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + qry.append("ALTER TABLE ").append(this.getParentTable().getDisplayName()).append(" DROP COLUMN ") + .append(super.getQualifiedObjectName()).append(";"); + + dbConnection.execNonSelectForTimeout(qry.toString()); + } + + /** + * Exec rename. + * + * @param newName the new name + * @param dbConnection the db connection + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void execRename(String newName, DBConnection dbConnection) + throws DatabaseCriticalException, DatabaseOperationException { + StringBuilder qry = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + qry.append("ALTER TABLE ").append(this.getParentTable().getDisplayName()).append(" RENAME COLUMN ") + .append(super.getQualifiedObjectName()).append(" TO ") + .append(ServerObject.getQualifiedObjectName(newName)); + + dbConnection.execNonSelectForTimeout(qry.toString()); + } + + /** + * Exec change data type. + * + * @param dbConnection the db connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void execChangeDataType(DBConnection dbConnection) + throws DatabaseOperationException, DatabaseCriticalException { + StringBuilder qry = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + boolean isSchemaselected = false; + + qry.append("ALTER TABLE ").append(this.parentTable.getDisplayName()).append(" ALTER COLUMN ") + .append(super.getQualifiedObjectName()).append(" TYPE "); + + if (null != this.dataTypeSchema) { + qry.append(ServerObject.getQualifiedObjectName(this.dataTypeSchema)); + qry.append('.'); + isSchemaselected = true; + } + if (null != this.dataType) { + if (isSchemaselected) { + qry.append(this.dataType.getDisplayName()); + } else { + qry.append(this.dataType.getName()); + } + + } + if (0 != this.lenOrPrecision) { + qry.append('('); + qry.append(this.lenOrPrecision); + if (0 != this.scale) { + qry.append(','); + qry.append(this.scale); + } + qry.append(')'); + } + qry.append(';'); + + dbConnection.execNonSelect(qry.toString()); + + } + + /** + * Gets the data type. + * + * @return the data type + */ + public TypeMetaData getDataType() { + return dataType; + } + + /** + * Sets the data type. + * + * @param typeMetaData the new data type + */ + public void setDataType(TypeMetaData typeMetaData) { + dataType = typeMetaData; + } + + /** + * Checks if is loaded. + * + * @return true, if is loaded + */ + public boolean isLoaded() { + return isLoaded; + } + + /** + * Sets the loaded. + * + * @param isLoad the new loaded + */ + public void setLoaded(boolean isLoad) { + this.isLoaded = isLoad; + } + + /** + * Gets the search name. + * + * @return the search name + */ + @Override + public String getSearchName() { + + return getName() + " - " + getParentDetails(); + } + + /** + * Gets the parent details. + * + * @return the parent details + */ + public String getParentDetails() { + String table = getParentTable().getName(); + String ns = getParentTable().getNamespace().getName(); + return ns + '.' + table + " - " + getTypeLabel(); + + } + + /** + * Gets the parent DB. + * + * @return the parent DB + */ + public Database getParentDB() { + return parentTable.getDatabase(); + } + + /** + * Gets the parent. + * + * @return the parent + */ + public Object getParent() { + return this.parentTable; + } + + /** + * Sets the display datatype. + * + * @param datatypeName the new display datatype + */ + public void setDisplayDatatype(String datatypeName) { + this.displayDatatypeName = datatypeName; + } + + /** + * Gets the display datatype. + * + * @return the display datatype + */ + public String getDisplayDatatype() { + return displayDatatypeName; + } + + /** + * Gets the column case. + * + * @return the column case + */ + public boolean getColumnCase() { + return this.columnCase; + } + + /** + * Sets the column case. + * + * @param colCase the new column case + */ + public void setColumnCase(boolean colCase) { + this.columnCase = colCase; + } + + /** + * Sets the checks if is function. + * + * @param isFunction the new checks if is function + */ + public void setIsFunction(boolean isFunction) { + this.isFunction = isFunction; + } + + /** + * Gets the checks if is function. + * + * @return the checks if is function + */ + public boolean getIsFunction() { + return this.isFunction; + } + + /** + * Checks if is distribution colm. + * + * @return true, if is distribution colm + */ + public boolean isDistributionColm() { + return isDistributionColm; + } + + /** + * Sets the distribution colm. + * + * @param isDistributionColumn the new distribution colm + */ + public void setDistributionColm(boolean isDistributionColumn) { + this.isDistributionColm = isDistributionColumn; + } + + /** + * Gets the database. + * + * @return the database + */ + @Override + public Database getDatabase() { + return this.getParentDB(); + } + + /** + * Equals. + * + * @param obj the obj + * @return true, if successful + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof ColumnMetaData) { + ColumnMetaData otherColMetaData = (ColumnMetaData) obj; + + if (super.equals(obj)) { + return getDataType().equals(otherColMetaData.getDataType()); + } + } + + return false; + } + + /** + * Hash code. + * + * @return the int + */ + @Override + public int hashCode() { + return super.hashCode() + getDataType().hashCode(); + } + + /** + * Gets the object full name. + * + * @return the object full name + */ + @Override + public String getObjectFullName() { + return this.getParentTable().getDisplayName() + "." + this.getDisplayName(); + } + + /** + * Gets the drop query. + * + * @param isCascade the is cascade + * @return the drop query + */ + @Override + public String getDropQuery(boolean isCascade) { + StringBuilder query = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + query.append("ALTER TABLE IF EXISTS ").append(this.getParentTable().getDisplayName()) + .append(" DROP COLUMN IF EXISTS ").append(super.getQualifiedObjectName()); + + if (isCascade) { + query.append(MPPDBIDEConstants.CASCADE); + } + + return query.toString(); + } + + /** + * Checks if is drop allowed. + * + * @return true, if is drop allowed + */ + @Override + public boolean isDropAllowed() { + if (getParent() instanceof ForeignTable) { + return false; + } + return true; + } + + /** + * Gets the data type name. + * + * @return the data type name + */ + public String getDataTypeName() { + return getDataType().getName(); + } + + /** + * Form set comment query. + * + * @return the string + * @Title: formSetCommentQuery + * @Description: generate comment query + */ + public String formSetCommentQuery() { + StringBuilder commentQry = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + commentQry.append("COMMENT ON COLUMN "); + commentQry.append(this.parentTable.getQualifiedName()); + commentQry.append(MPPDBIDEConstants.DOT); + commentQry.append(ServerObject.getQualifiedObjectName(getName())); + commentQry.append(" IS "); + commentQry.append(null == this.colDescription ? "NULL" : ServerObject.getLiteralName(this.colDescription)); + commentQry.append(MPPDBIDEConstants.SEMICOLON); + return commentQry.toString(); + } + + /** + * Gets the clm name with datatype. + * + * @param isParentDescNeeded the is parent desc needed + * @return the clm name with datatype + */ + public String getClmNameWithDatatype(boolean isParentDescNeeded) { + return getName() + " - " + getDataType().getName() + getcolumnPrecisionScale() + + addParentDetails(isParentDescNeeded); + } + + /** + * Gets the column precision scale. + * + * @return the column precision scale + */ + private String getcolumnPrecisionScale() { + StringBuilder strBldr = new StringBuilder(); + if (this.lenOrPrecision > 0) { + strBldr.append('('); + strBldr.append(this.lenOrPrecision); + if (0 != this.scale) { + strBldr.append(','); + strBldr.append(this.scale); + } + strBldr.append(')'); + } + return strBldr.toString(); + } + + /** + * Adds the parent details. + * + * @param isParentDescNeeded the is parent desc needed + * @return the string + */ + private String addParentDetails(boolean isParentDescNeeded) { + if (isParentDescNeeded) { + return " - " + getParentDetails(); + } + return ""; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ColumnUtil.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ColumnUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..ceffe1dcc434cdb5e96166c89d39e24dc48492ab --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ColumnUtil.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + + +/** + * Title: ColumnUtil + * + * @since 3.0.0 + */ +public class ColumnUtil { + /** + * Extract precision scale. + * + * @param rs the rs + * @param col the col + * @throws SQLException the SQL exception + */ + public static void extractPrecisionScale(ResultSet rs, ColumnMetaData col) throws SQLException { + String datatypeName = ""; + String datatypeNameFromSever = ""; + datatypeNameFromSever = col.getDataType().getName(); + int precision = rs.getInt("precision"); + if (precision < 0) { + col.setLenOrPrecision(-1); + return; + } + int len = rs.getInt("length"); + + if (len > 0) { + col.setLenOrPrecision(len); + return; + } + + if (datatypeNameFromSever.startsWith("_")) { + datatypeName = datatypeNameFromSever.substring(1, datatypeNameFromSever.length()); + } else { + datatypeName = datatypeNameFromSever; + } + + if ("bpchar".equals(datatypeName) || "varchar".equals(datatypeName)) { + precision -= 4; + col.setLenOrPrecision(precision); + } else if ("bit".equals(col.getDataType().getName())) { + col.setLenOrPrecision(precision); + } else { + precision -= 4; + col.setLenOrPrecision(precision >> 16); + col.setScale(precision % (1 << 16)); + } + } + + /** + * Convert to column meta data. + * + * @param rs the rs + * @param type the type + * @param tableMetaData the table meta data + * @param database the database + * @return the column meta data + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static ColumnMetaData convertToColumnMetaData(ResultSet rs, TypeMetaData type, TableMetaData tableMetaData, + Database database) throws DatabaseCriticalException, DatabaseOperationException { + try { + ColumnMetaData col = new ColumnMetaData(tableMetaData, rs.getLong("columnidx"), rs.getString("name"), type); + + extractPrecisionScale(rs, col); + + col.setArrayNDim(rs.getInt("dimentions")); + col.setNotNull(rs.getBoolean("notnull")); + col.setHasDefVal(rs.getBoolean("isdefaultvalueavailable")); + col.setAttDefString(rs.getString("attDefStr")); + col.setDefaultValue(rs.getString("default_value")); + col.setLoaded(true); + col.setDisplayDatatype(rs.getString("displayColumns")); + return col; + } catch (SQLException exp) { + GaussUtils.handleCriticalException(exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exp); + } + } + + /** + * Checks if is column name valid. + * + * @param newTempColumn the new temp column + * @return true, if is column name valid + */ + public static boolean isColumnNameValid(ColumnMetaData newTempColumn) { + return null == newTempColumn + || (null == newTempColumn.getName() || newTempColumn.getName().trim().length() == 0); + } + + /** + * Checks if is data type valid. + * + * @param newTempColumn the new temp column + * @return true, if is data type valid + */ + public static boolean isDataTypeValid(ColumnMetaData newTempColumn) { + return null != newTempColumn && null == newTempColumn.getDataType(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ConnectionManager.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ConnectionManager.java new file mode 100644 index 0000000000000000000000000000000000000000..67d513df2e76c3f7c416565a9a2c45afd426022b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ConnectionManager.java @@ -0,0 +1,852 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; + +import org.opengauss.mppdbide.adapter.IConnectionDriver; +import org.opengauss.mppdbide.adapter.driver.DBMSDriverManager; +import org.opengauss.mppdbide.adapter.factory.ConnectionDriverFactory; +import org.opengauss.mppdbide.adapter.factory.DBConnectionFactory; +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.adapter.gauss.ObjectBrowserDBConnection; +import org.opengauss.mppdbide.bl.executor.AbstractExecutor; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.DBTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.bl.util.BLUtils; +import org.opengauss.mppdbide.bl.util.ExecTimer; +import org.opengauss.mppdbide.bl.util.IExecTimer; +import org.opengauss.mppdbide.utils.DsEncodingEnum; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DataStudioSecurityException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.exceptions.UnknownException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; + +/** + * + * Title: class + * + * Description: The Class ConnectionManager. + * + */ + +public class ConnectionManager { + private Server server; + private DBConnection objBrowserConn; + private DBConnection loginNotifConn; + private DBConnection sqlTerminalConn; + private TerminalConnectionPoolManager connPoolManager = null; + private IConnectionDriver connectionDriver; + private EncodingDetail encodingDetail = null; + private DBInternals dbInternals = null; + private String lastSearchPathQuery = null; + + /** + * + * Title: class + * + * Description: The Class TerminalConnectionPoolManager. + * + */ + private static class TerminalConnectionPoolManager { + private final Object poolLock = new Object(); + private List freeTerminalConnections; + private List usedTerminalConnections; + + /** + * The Constant MAX_TERMINAL_CONNECTIONS_ALLOWED. + */ + public static final int MAX_TERMINAL_CONNECTIONS_ALLOWED = 20; + + private static final int MAX_TERMINAL_CONNECTIONS_RETAINED = 1; + + /** + * Instantiates a new terminal connection pool manager. + */ + public TerminalConnectionPoolManager() { + freeTerminalConnections = Collections + .synchronizedList(new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE)); + usedTerminalConnections = Collections + .synchronizedList(new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE)); + } + + /** + * Disconnect terminal cons. + */ + public void disconnectTerminalCons() { + synchronized (poolLock) { + for (DBConnection con : freeTerminalConnections) { + con.disconnect(); + con = null; + } + + for (DBConnection con : usedTerminalConnections) { + con.disconnect(); + con = null; + } + + freeTerminalConnections.clear(); + usedTerminalConnections.clear(); + } + } + + /** + * Removes the connection from pool. + * + * @param conn the conn + * @return true, if successful + */ + public boolean removeConnectionFromPool(DBConnection conn) { + synchronized (poolLock) { + return usedTerminalConnections.remove(conn); + } + } + + /** + * Release and disconnection. + * + * @param conn the conn + */ + public void releaseAndDisconnection(DBConnection conn) { + boolean isRemoved = false; + synchronized (poolLock) { + isRemoved = removeConnectionFromPool(conn); + + if (isRemoved) { + conn.disconnect(); + } + } + } + + /** + * Release connection. + * + * @param conn the conn + * @param savePrdOption the save prd option + */ + public void releaseConnection(DBConnection conn, + org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions savePrdOption) { + boolean isRemoved = false; + synchronized (poolLock) { + if (!savePrdOption.equals(SavePrdOptions.DO_NOT_SAVE)) { + isRemoved = usedTerminalConnections.remove(conn); + + if (isRemoved) { + if (freeTerminalConnections.size() < MAX_TERMINAL_CONNECTIONS_RETAINED) { + freeTerminalConnections.add(conn); + } else { + conn.disconnect(); + } + } + } else { + releaseAndDisconnection(conn); + } + } + + } + + /** + * Adds the to used term pool. + * + * @param conn the conn + */ + public void addToUsedTermPool(DBConnection conn) { + synchronized (poolLock) { + usedTerminalConnections.add(conn); + } + } + + /** + * Gets the new free term conn. + * + * @param dbname the dbname + * @param servername the servername + * @return the new free term conn + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public DBConnection getNewFreeTermConn(String dbname, String servername) throws MPPDBIDEException { + DBConnection conn = null; + synchronized (poolLock) { + if (freeTerminalConnections.size() > 0) { + conn = freeTerminalConnections.get(0); + freeTerminalConnections.remove(conn); + usedTerminalConnections.add(conn); + return conn; + } + + if (usedTerminalConnections.size() >= MAX_TERMINAL_CONNECTIONS_ALLOWED) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty( + IMessagesConstants.DATABASE_CONNECTION_LIMIT_REACHED, MAX_TERMINAL_CONNECTIONS_ALLOWED)); + throw new MPPDBIDEException(IMessagesConstants.DATABASE_CONNECTION_LIMIT_REACHED, + MAX_TERMINAL_CONNECTIONS_ALLOWED, dbname + '@' + servername); + } + } + return null; + } + + /** + * Execute query for all used connections. + * + * @param query the query + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void executeQueryForAllUsedConnections(String query) + throws DatabaseOperationException, DatabaseCriticalException { + synchronized (poolLock) { + /* Set default schema for all used connections in the pool */ + for (DBConnection connectionIter : this.usedTerminalConnections) { + if (!connectionIter.isClosed()) { + connectionIter.execNonSelect(query); + } + } + } + } + } + + /** + * Sets the default schema for all used connections. + * + * @param query the new default schema for all used connections + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void setDefaultSchemaForAllUsedConnections(String query) + throws DatabaseOperationException, DatabaseCriticalException { + + this.connPoolManager.executeQueryForAllUsedConnections(query); + + /* Set default schema for OB and SQL Terminal connections */ + if (null != this.objBrowserConn && !this.objBrowserConn.isClosed()) { + this.objBrowserConn.execNonSelect(query); + } + + if (null != this.sqlTerminalConn && !this.sqlTerminalConn.isClosed()) { + this.sqlTerminalConn.execNonSelect(query); + } + + this.lastSearchPathQuery = query; + } + + /** + * + * Title: class + * + * Description: The Class EncodingDetail. + * + */ + private static class EncodingDetail { + + private String encoding; + + /** + * Update encoding prop. + * + * @param props the props + */ + public void updateEncodingProp(Properties props) { + if (DsEncodingEnum.LATIN1.getEncoding().equalsIgnoreCase(this.encoding)) { + props.setProperty("characterEncoding", DsEncodingEnum.LATIN1.getEncoding()); + } + } + + /** + * Sets the encoding. + * + * @param dbconn the new encoding + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void setEncoding(DBConnection dbconn) throws DatabaseCriticalException, DatabaseOperationException { + this.encoding = DatabaseUtils.getServerEncoding(dbconn); + + if (DsEncodingEnum.LATIN1.getEncoding().equalsIgnoreCase(this.encoding)) { + dbconn.executeClientEncoding(DsEncodingEnum.LATIN1.getEncoding()); + } + } + } + + /** + * + * Title: class + * + * Description: The Class DBInternals. + * + */ + private static class DBInternals { + + Database db; + + /** + * Gets the dbasename. + * + * @return the dbasename + */ + public String getDbasename() { + return db.getName(); + } + + /** + * Gets the db type. + * + * @return the db type + */ + public String getDbType() { + return db.getDabaseType(); + } + + /** + * Instantiates a new DB internals. + * + * @param dbName the db name + * @param type the type + * @param abstractExecutor the ex + * @param id the id + */ + public DBInternals(Database db) { + this.db = db; + } + + /** + * Checks if is DB type OLAP. + * + * @return true, if is DB type OLAP + */ + public boolean isDBTypeOLAP() { + return getDbType().equals(DBTYPE.OPENGAUSS.toString()); + } + } + + /** + * Instantiates a new connection manager. + * + * @param db the db + */ + public ConnectionManager(Database db) { + if (null != db.getServer()) { + this.server = db.getServer(); + } + this.connPoolManager = new TerminalConnectionPoolManager(); + + encodingDetail = new EncodingDetail(); + + dbInternals = new DBInternals(db); + + } + + /** + * Sets the connection driver name. + * + * @param driverName the new connection driver name + */ + private void setConnectionDriverName(String driverName) { + this.server.setDriverName(driverName); + } + + /** + * Gets the free connection. + * + * @return the free connection + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public DBConnection getFreeConnection() throws MPPDBIDEException { + + DBConnection conn = null; + IServerConnectionInfo connectInfo = server.getServerConnectionInfo(dbInternals.getDbasename()); + + try { + conn = connPoolManager.getNewFreeTermConn(dbInternals.getDbasename(), server.getName()); + } catch (MPPDBIDEException exp) { + throw exp; + } + if (null == conn) { + conn = DBConnectionFactory.getConnectionObj(this.getConnectionDriver()); + connPoolManager.addToUsedTermPool(conn); + } + + if (conn != null && conn.getConnection() != null ? conn.isClosed() : true) { + Properties props = connectInfo.composeProperty(server.getDriverName()); + encodingDetail.updateEncodingProp(props); + doConnect(conn, connectInfo.composeUrl(), props); + + ServerUtil.clearPropertyDetails(props); + } + + if (null != this.lastSearchPathQuery && conn != null) { + conn.execNonSelect(this.lastSearchPathQuery); + } + + ServerUtil.clearConnectionInfo(connectInfo); + server.clearPrds(); + + return conn; + } + + /** + * Do connect. + * + * @param conn the conn + * @param url the url + * @param props the props + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + private void doConnect(DBConnection conn, String url, Properties props) + throws DatabaseOperationException, DatabaseCriticalException { + if (conn != null) { + conn.connectViaDriver(props, url); + } + } + + /** + * Do connections to server. + * + * @param connObjects the conn objects + * @param props the props + * @param url the url + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + private void doConnectionsToServer(DBConnection[] connObjects, Properties props, String url) + throws DatabaseOperationException, DatabaseCriticalException { + int connCount = 0; + try { + + IConnectionDriver driver = this.getConnectionDriver(); + if (null == driver) { + driver = getNewDriver(connObjects, props, url, connCount); + + connCount++; + } + connCount = connectViaDriver(connObjects, props, url, connCount, driver); + + } catch (SQLException exp) { + GaussUtils.handleCriticalException(exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_SERVER_CONNECTION_FAILED, exp); + } + + finally { + diconnectConnObjects(connObjects, props, connCount); + } + } + + /** + * Gets the new driver. + * + * @param connObjects the conn objects + * @param props the props + * @param url the url + * @param connCount the i + * @return the new driver + * @throws SQLException the SQL exception + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + private IConnectionDriver getNewDriver(DBConnection[] connObjects, Properties props, String url, int connCount) + throws SQLException, DatabaseOperationException, DatabaseCriticalException { + IConnectionDriver driver; + DBMSDriverManager instance = DBMSDriverManager.getInstance(BLUtils.getInstance().getInstallationLocation()); + DBConnection dbconn = null; + dbconn = instance.getConnection(props, url, dbInternals.getDbType()); + + if (null == dbconn) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_SERVER_CONNECTION_FAILED)); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_SERVER_CONNECTION_FAILED); + } + driver = getDriverAndSetConnection(connObjects, connCount, dbconn); + return driver; + } + + /** + * Diconnect conn objects. + * + * @param connObjects the conn objects + * @param props the props + * @param connCount the i + */ + private void diconnectConnObjects(DBConnection[] connObjects, Properties props, int connCount) { + if (connCount != connObjects.length) { + for (int j1 = 0; j1 < connCount; j1++) { + connObjects[j1].disconnect(); + } + } + SecureUtil.cleanKeyString(props.getProperty("password")); + props.setProperty("password", ""); + props.remove("password"); + } + + /** + * Connect via driver. + * + * @param connObjects the conn objects + * @param props the props + * @param url the url + * @param i the i + * @param driver the driver + * @return the int + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + private int connectViaDriver(DBConnection[] connObjects, Properties props, String url, int indexParam, + IConnectionDriver driver) throws DatabaseOperationException, DatabaseCriticalException { + int index = indexParam; + for (; index < connObjects.length; index++) { + connObjects[index].setDriver(driver); + Properties driverspecific = driver.getDriverSpecificProperties(); + driverspecific.putAll(props); + if (dbInternals.isDBTypeOLAP()) { + encodingDetail.updateEncodingProp(driverspecific); + } + connObjects[index].connectViaDriver(driverspecific, url); + driverspecific.setProperty("password", ""); + driverspecific.remove("password"); + } + return index; + } + + /** + * Gets the driver and set connection. + * + * @param connObjects the conn objects + * @param connCount the i + * @param dbconn the dbconn + * @return the driver and set connection + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private IConnectionDriver getDriverAndSetConnection(DBConnection[] connObjects, int connCount, DBConnection dbconn) + throws DatabaseCriticalException, DatabaseOperationException { + IConnectionDriver driver; + driver = dbconn.getDriver(); + this.connectionDriver = driver; + this.setConnectionDriverName(driver.getDriverName()); + connObjects[connCount].setDriver(driver); + connObjects[connCount].setConnection(dbconn.getConnection()); + + if (dbInternals.isDBTypeOLAP()) { + encodingDetail.setEncoding(dbconn); + } + return driver; + } + + /** + * Connect to gauss. + * + * @param props the props + * @param url the url + * @param type the type + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void connectToGauss(Properties props, String url, DBTYPE type) + throws DatabaseOperationException, DatabaseCriticalException { + DBConnection[] connObjects = null; + int numConnObj; + + numConnObj = 3; + this.loginNotifConn = new DBConnection(); + this.sqlTerminalConn = new DBConnection(); + this.objBrowserConn = new ObjectBrowserDBConnection(); + + boolean allConnected = false; + + connObjects = new DBConnection[numConnObj]; + connObjects[numConnObj - 2] = this.objBrowserConn; + connObjects[numConnObj - 1] = this.sqlTerminalConn; + + if (connObjects.length == 3) { + connObjects[0] = this.loginNotifConn; + } + + try { + doConnectionsToServer(connObjects, props, url); + allConnected = true; + } finally { + if (!allConnected) { + this.loginNotifConn = null; + this.objBrowserConn = null; + this.sqlTerminalConn = null; + } + } + } + + /** + * Release connection. + * + * @param conn the conn + */ + public void releaseConnection(DBConnection conn) { + connPoolManager.releaseConnection(conn, server.getSavePrdOption()); + } + + /** + * Release and disconnection. + * + * @param conn the conn + */ + public void releaseAndDisconnection(DBConnection conn) { + connPoolManager.releaseAndDisconnection(conn); + } + + /** + * Removes the connection from pool. + * + * @param conn the conn + * @return true, if successful + */ + public boolean removeConnectionFromPool(DBConnection conn) { + return connPoolManager.removeConnectionFromPool(conn); + } + + /** + * Disconnect conns. + */ + public void disconnectConns() { + if (null != objBrowserConn) { + objBrowserConn.disconnect(); + } + + if (null != loginNotifConn) { + loginNotifConn.disconnect(); + } + + if (null != sqlTerminalConn) { + sqlTerminalConn.disconnect(); + } + } + + /** + * Disconnect terminal cons. + */ + public void disconnectTerminalCons() { + connPoolManager.disconnectTerminalCons(); + lastSearchPathQuery = null; + } + + /** + * Gets the obj browser conn. + * + * @return the obj browser conn + */ + public DBConnection getObjBrowserConn() { + return objBrowserConn; + } + + /** + * Sets the obj browser conn. + * + * @param objBrowserConn the new obj browser conn + */ + public void setObjBrowserConn(DBConnection objBrowserConn) { + this.objBrowserConn = objBrowserConn; + } + + /** + * Gets the sql terminal conn. + * + * @return the sql terminal conn + */ + public DBConnection getSqlTerminalConn() { + return sqlTerminalConn; + } + + /** + * Gets the connection driver. + * + * @return the connection driver + * @throws DatabaseOperationException the database operation exception + */ + public IConnectionDriver getConnectionDriver() throws DatabaseOperationException { + if (null != this.connectionDriver) { + return connectionDriver; + } + + String driverName = this.server.getDriverName(); + if (null == driverName) { + return null; + } + + IConnectionDriver connDriver = ConnectionDriverFactory.getInstance().getDriver(driverName); + if (null == connDriver) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_BL_GET_DRIVER_VERSION_FAILED)); + throw new DatabaseOperationException(IMessagesConstants.ERR_BL_GET_DRIVER_VERSION_FAILED); + } + return connDriver; + } + + /** + * Cancel all connection queries. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void cancelAllConnectionQueries() throws DatabaseCriticalException, DatabaseOperationException { + + if (null != this.objBrowserConn) { + this.objBrowserConn.cancelQuery(); + } + + if (null != this.loginNotifConn) { + this.loginNotifConn.cancelQuery(); + } + + if (null != this.sqlTerminalConn) { + this.sqlTerminalConn.cancelQuery(); + } + + } + + /* + * API to expose getLastSuccessfulLogin() which is further used to close the + * loginNotifConn + * + */ + + /** + * Gets the successfull login. + * + * @return the successfull login + */ + public DBConnection getSuccessfullLogin() { + return loginNotifConn; + } + + /** + * Execute login details query. + * + * @param qry the qry + * @return the result set + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public ResultSet executeLoginDetailsQuery(String qry) throws DatabaseCriticalException, DatabaseOperationException { + ResultSet rs; + IExecTimer timer = new ExecTimer(LoginNotificationManager.LOGIN_NOTIFICATION); + timer.start(); + + rs = loginNotifConn.execSelectAndReturnRs(qry); + + timer.stop(); + if (MPPDBIDELoggerUtility.isInfoEnabled()) { + MPPDBIDELoggerUtility.info(LoginNotificationManager.LAST_LOGING_SUCCESS_DURATION + timer.getElapsedTime()); + } + return rs; + } + + /** + * Exec select and get first val on obj browser conn. + * + * @param query the query + * @return the string + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public String execSelectAndGetFirstValOnObjBrowserConn(String query) + throws DatabaseCriticalException, DatabaseOperationException { + return objBrowserConn.execSelectAndGetFirstVal(query); + } + + /** + * Exec select and return rs on obj browser conn. + * + * @param qry the qry + * @return the result set + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public ResultSet execSelectAndReturnRsOnObjBrowserConn(String qry) + throws DatabaseCriticalException, DatabaseOperationException { + return this.objBrowserConn.execSelectAndReturnRs(qry); + } + + /** + * Exec select and return true if admin + * + * @return if admin + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public boolean execSelectCheckIfAdmin() throws DatabaseCriticalException, DatabaseOperationException { + return this.objBrowserConn.execSelectAndReturnAdmin(); + } + + /** + * Exec non select on obj browser conn. + * + * @param qry the qry + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void execNonSelectOnObjBrowserConn(String qry) throws DatabaseCriticalException, DatabaseOperationException { + this.objBrowserConn.execNonSelect(qry); + } + + /** + * Close RS on obj browser conn. + * + * @param rs the rs + */ + public void closeRSOnObjBrowserConn(ResultSet rs) { + objBrowserConn.closeResultSet(rs); + } + + /** + * Cancel login query. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void cancelLoginQuery() throws DatabaseCriticalException, DatabaseOperationException { + loginNotifConn.cancelQuery(); + } + + /** + * Checks if is show DDL support by server. + * + * @return true, if is show DDL support by server + */ + public boolean isShowDDLSupportByServer() { + try { + IConnectionDriver driver = getConnectionDriver(); + if (driver != null) { + if (!driver.getShowDDLSupportCheck()) { + return driver.getShowDDLSupport(objBrowserConn); + } + return driver.getShowDDLSupport(); + } + return false; + } catch (MPPDBIDEException exception) { + MPPDBIDELoggerUtility.error("connection error", exception); + return false; + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ConnectionProfileId.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ConnectionProfileId.java new file mode 100644 index 0000000000000000000000000000000000000000..65c4e9e795de5c28dfeb3a3372ff66942e454d96 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ConnectionProfileId.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: class + * + * Description: The Class ConnectionProfileId. + * + */ + +public class ConnectionProfileId { + + private int serverId; + private long databaseId; + + /** + * Instantiates a new connection profile id. + * + * @param serverId the server id + * @param databaseId the database id + */ + public ConnectionProfileId(int serverId, long databaseId) { + this.serverId = serverId; + this.databaseId = databaseId; + } + + /** + * Gets the server id. + * + * @return the server id + */ + public int getServerId() { + return serverId; + } + + /** + * Gets the database id. + * + * @return the database id + */ + public long getDatabaseId() { + return databaseId; + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + return DBConnProfCache.getInstance().getDbForProfileId(this); + } + + /** + * Checks if is equals. + * + * @param obj the obj + * @return true, if is equals + */ + public boolean isEquals(Object obj) { + ConnectionProfileId otherConn = (ConnectionProfileId) obj; + return otherConn.getDatabaseId() == this.databaseId && otherConn.getServerId() == this.serverId; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ConnectionProfileManagerImpl.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ConnectionProfileManagerImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..4eabe7bdc0d99f3971500f45ef157761ab13cbb5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ConnectionProfileManagerImpl.java @@ -0,0 +1,352 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; + +import org.opengauss.mppdbide.bl.connection.IConnectionProfileManager; +import org.opengauss.mppdbide.bl.serverdatacache.ProfileMetaData.ProfileInfo; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.DBTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; +import org.opengauss.mppdbide.bl.sqlhistory.SQLHistoryFactory; +import org.opengauss.mppdbide.bl.sqlhistory.manager.ISqlHistoryManager; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.MemoryCleaner; +import org.opengauss.mppdbide.utils.exceptions.DataStudioSecurityException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.FileOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; + +/** + * + * Title: class + * + * Description: The Class ConnectionProfileManagerImpl. + * + */ + +public final class ConnectionProfileManagerImpl implements IConnectionProfileManager { + + private HashMap profileMap; + private static volatile ConnectionProfileManagerImpl instance; + private ProfileDiskUtility diskUtility; + private static final Object LOCK = new Object(); + + /** + * Gets the exception list. + * + * @return the exception list + */ + public List getExceptionList() { + return diskUtility.getExceptionList(); + } + + /** + * Clear exception list. + */ + public void clearExceptionList() { + diskUtility.clearExceptionList(); + } + + /** + * Instantiates a new connection profile manager impl. + */ + private ConnectionProfileManagerImpl() { + profileMap = new HashMap(1); + setDiskUtility(new ProfileDiskUtility()); + } + + /** + * Gets the disk utility. + * + * @return the disk utility + */ + public ProfileDiskUtility getDiskUtility() { + return diskUtility; + } + + /** + * Checks if is profile map empty. + * + * @return true, if is profile map empty + */ + public boolean isProfileMapEmpty() { + return profileMap.isEmpty(); + } + + /** + * Sets the disk utility. + * + * @param diskUtility the new disk utility + */ + public void setDiskUtility(ProfileDiskUtility diskUtility) { + this.diskUtility = diskUtility; + } + + /** + * Gets the single instance of ConnectionProfileManagerImpl. + * + * @return single instance of ConnectionProfileManagerImpl + */ + public static ConnectionProfileManagerImpl getInstance() { + if (instance == null) { + synchronized (LOCK) { + if (instance == null) { + instance = new ConnectionProfileManagerImpl(); + } + } + } + + return instance; + } + + @Override + public void deleteProfile(IServerConnectionInfo profile) throws DatabaseOperationException { + ISqlHistoryManager historyManager = SQLHistoryFactory.getInstance(); + historyManager.removeHistoryManagementForProfile(profile.getProfileId()); + + if (profileMap.containsKey(profile.getConectionName())) { + getDiskUtility().dropProfileFolder(getDiskUtility().getUserProfileFolderName(profile.getProfileId()), + profile.getConectionName()); + profileMap.remove(profile.getConectionName()); + } + MPPDBIDELoggerUtility.operationInfo("Deleted user profile :" + profile.getProfileId()); + } + + /** + * Generate profile id. + * + * @return the int + */ + private int generateProfileId() { + int profileId = 0; + List profileIds = getDiskUtility().getMetaData().getAllProfileIds(); + if (profileIds.size() > 0) { + Collections.sort(profileIds); + // Get the last element in the list. Implies the highest of all + // values + int localProfileId = profileIds.get(profileIds.size() - 1); + profileId = localProfileId; + } + + return ++profileId; + } + + @Override + public void saveProfile(IServerConnectionInfo profile) + throws DatabaseOperationException, DataStudioSecurityException { + if (profile != null && profile.getConectionName() != null && !("".equals(profile.getConectionName().trim()))) { + + String profId = profile.getProfileId(); + getDiskUtility().writeProfileToDisk(profile); + + ISqlHistoryManager historyManager = SQLHistoryFactory.getInstance(); + String path = getDiskUtility().getHistoryProfilepath(getDiskUtility().getUserProfileFolderName(profId)) + .toString(); + historyManager.doHistoryManagementForProfile(profId, path); + + try { + // load the profiles from HDD after save operation + getAllProfiles(); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_PROFILE_WRITE_INVALID), exception); + } + } + } + + private String generateAndSetProfileId(IServerConnectionInfo profile) { + String conectionName = profile.getConectionName(); + int profileId = getDiskUtility().getMetaData().getProfileId(conectionName); + if (profileId == -1) { + // Profile id doesnt exist. Generate new profileId + profileId = generateProfileId(); + } + String profId = Integer.toString(profileId); + profile.setProfileId(profId); + return profId; + } + + @Override + public void renameProfile(IServerConnectionInfo profile) + throws DatabaseOperationException, DataStudioSecurityException { + getDiskUtility().renameProfileOnDisk(profile); + try { + // load the profiles from HDD after rename operation + getAllProfiles(); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_PROFILE_WRITE_INVALID), + exception); + } + } + + @Override + public IServerConnectionInfo getProfile(String name) { + IServerConnectionInfo connInfo = null; + if (profileMap.containsKey(name)) { + IServerConnectionInfo serverInfo = profileMap.get(name); + if (serverInfo != null) { + connInfo = serverInfo.getClone(); + connInfo.setPrd(serverInfo.getPrd()); + } + } + return connInfo; + } + + @Override + public List getAllProfiles() + throws DatabaseOperationException, DataStudioSecurityException, IOException { + List list = getDiskUtility().getProfiles(); + profileMap.clear(); + + for (IServerConnectionInfo info : list) { + if (info != null) { + profileMap.put(info.getConectionName(), info); + } + } + return list; + } + + /** + * Clear permanent save pwd. + * + * @throws DatabaseOperationException the database operation exception + * @throws DataStudioSecurityException the data studio security exception + * @throws IOException Signals that an I/O exception has occurred. + */ + public void clearPermanentSavePwd() throws DatabaseOperationException, DataStudioSecurityException, IOException { + List list = getAllProfiles(); + for (IServerConnectionInfo info : list) { + info.setPrd(new char[0]); + MemoryCleaner.cleanUpMemory(); + saveProfile(info); + } + } + + @Override + public void exportConnectionProfiles(List profiles, String filePath) + throws DatabaseOperationException, DataStudioSecurityException { + getDiskUtility().writeExportedProfileToDisk(profiles, filePath); + } + + @Override + public List importConnectionProfiles(String path, double fileSizeLimit) + throws DatabaseOperationException { + List readImportedFile; + readImportedFile = getDiskUtility().readImportedFile(path, fileSizeLimit); + return readImportedFile; + } + + @Override + public void mergeImportedProfiles(List profilesList, List allProfiles) + throws DatabaseOperationException { + ProfileDiskUtility diskUtilityProfiles = getDiskUtility(); + try { + for (IServerConnectionInfo info : profilesList) { + diskUtilityProfiles.writeProfileToDisk(info); + // the check is to ensure that no two callers adds the same + // profile multiple times + if (!allProfiles.contains(info)) { + allProfiles.add(info); + } + } + + } catch (DataStudioSecurityException exp) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.ERROR_IMPORTING_CONNECTION_PROFILES), exp); + throw new DatabaseOperationException( + MessageConfigLoader.getProperty(IMessagesConstants.ERROR_IMPORTING_CONNECTION_PROFILES), exp); + } + + } + + @Override + public void replaceWithImportedProfiles(IServerConnectionInfo profToBeDeleted, + IServerConnectionInfo profToBeCreated, List allProfiles) + throws DatabaseOperationException, DataStudioSecurityException { + ProfileDiskUtility diskUtilityProfiles = getDiskUtility(); + deleteProfile(profToBeDeleted); + diskUtilityProfiles.writeProfileToDisk(profToBeCreated); + allProfiles.remove(profToBeDeleted); + allProfiles.add(profToBeCreated); + } + + /** + * Checks if is profile info available in meta data. + * + * @param connName the conn name + * @return true, if is profile info available in meta data + */ + public boolean isProfileInfoAvailableInMetaData(String connName) { + ProfileInfo prof = getDiskUtility().getMetaData().getAllProfiles().get(connName); + return (prof != null); + } + + /** + * Sets the profile path. + * + * @param info the new profile path + * @return path profile path + */ + public String getProfilePath(IServerConnectionInfo info) { + String profilePath = getDiskUtility() + .getConnectionProfilepath(getDiskUtility().getUserProfileFolderName(info.getProfileId())).toString(); + return profilePath; + } + + /** + * Generate security folder inside profile. + * + * @param connInfo the conn info + * @return the path + * @throws IOException Signals that an I/O exception has occurred. + * @throws FileOperationException the file operation exception + * @throws DataStudioSecurityException the data studio security exception + * @throws DatabaseOperationException + */ + public Path generateSecurityFolderInsideProfile(IServerConnectionInfo connInfo) + throws IOException, FileOperationException, DataStudioSecurityException, DatabaseOperationException { + Path folderPath; + String profId; + + /* Get profile Id */ + profId = generateAndSetProfileId(connInfo); + + /* Create folder Structure */ + folderPath = getDiskUtility().createFolderStructure(getDiskUtility().getUserProfileFolderName(profId)); + runPreEncryptionTask(folderPath); + return folderPath; + } + + /** + * runPreEncryptionTask + * + * @param folderPath folder path + * @throws DataStudioSecurityException exception + */ + public void runPreEncryptionTask(Path folderPath) throws DataStudioSecurityException { + SecureUtil secureUtil = new SecureUtil(); + secureUtil.setPackagePath(folderPath.toString()); + secureUtil.runPreEncryptionTask(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ConnectionUtils.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ConnectionUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..c17d689b99fab6020ef8915f0ce6697a0d7f87bd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ConnectionUtils.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.contentassist.ContentAssistKeywords; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.DBTYPE; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class ConnectionUtils. + * + */ + +public class ConnectionUtils { + + /** + * Checks if is aleast one db connected. + * + * @param dbGroup the db group + * @return true, if is aleast one db connected + */ + public static boolean isAleastOneDbConnected(ArrayList dbGroup) { + Iterator dbItr = dbGroup.iterator(); + Database db = null; + boolean hasNext = dbItr.hasNext(); + + while (hasNext) { + db = dbItr.next(); + if (db.isConnected()) { + return true; + } + hasNext = dbItr.hasNext(); + } + + return false; + } + + /** + * Gets the another connection. + * + * @param oid the oid + * @param arrayList the array list + * @return the another connection + * @throws DatabaseOperationException the database operation exception + */ + public static DBConnection getAnotherConnection(long oid, ArrayList arrayList) + throws DatabaseOperationException { + Iterator dbItr = arrayList.iterator(); + boolean hasNext = dbItr.hasNext(); + + Database db = null; + while (hasNext) { + db = dbItr.next(); + if (db.isConnected() && db.getOid() != oid) { + return db.getConnectionManager().getObjBrowserConn(); + } + + hasNext = dbItr.hasNext(); + } + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_MSG_NO_OTHER_CONNECTION)); + throw new DatabaseOperationException(IMessagesConstants.ERR_MSG_NO_OTHER_CONNECTION); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ConstraintMetaData.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ConstraintMetaData.java new file mode 100644 index 0000000000000000000000000000000000000000..8b6504903890aae6924996ad7a19528a4dfc4849 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ConstraintMetaData.java @@ -0,0 +1,639 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: class + * + * Description: The Class ConstraintMetaData. + * + */ + +public class ConstraintMetaData extends BatchDropServerObject implements GaussOLAPDBMSObject { + /** + * this is the constraint type + */ + protected ConstraintType contype; + + /* + * c is check constraint f is foreign key constraint p is primary key + * constraint u is unique constraint x is exclusion constraint + */ + private ConstraintQueryBuilder queryBuilder = null; + private String expr; + private String consDef; + private TableMetaData table; + + /* + * Following are only valid for UNIQUE, PRIMARY KEY, FOREIGN KEY, EXCLUDE + * constraints + */ + private boolean condeferrable; + private boolean condeferred; + + /* + * only valid while creating / validating constraint + */ + private boolean isValidated; + + /* + * Used only for creating index options + */ + private String tableSpace; + + /* + * used only for creating new constraint + */ + private String columnList; + + /* valid only for foreign key constraint */ + private TableMetaData refernceTable; + private IndexMetaData referenceIndex; + + /** + * The on delete action.a = no action, r = restrict, c = cascade, n = set + * null, d = set default + */ + private ForeignKeyActionType onDeleteAction; + private ForeignKeyActionType onUpdateAction; + private ForeignKeyMatchType fkMatchType; + + private Namespace namespace; + private int fillfactor; + private boolean isLoaded; + + /** + * Instantiates a new constraint meta data. + * + * @param oid the oid + * @param name the name + * @param contype the contype + */ + public ConstraintMetaData(long oid, String name, ConstraintType contype) { + super(oid, name, OBJECTTYPE.CONSTRAINT, false); + this.contype = contype; + this.fillfactor = 100; + this.isLoaded = false; + this.queryBuilder = new ConstraintQueryBuilder(); + } + + /** + * Checks if is convalidated. + * + * @return true, if is convalidated + */ + public boolean isConvalidated() { + return isValidated; + } + + /** + * Sets the validated. + * + * @param convalidated the new validated + */ + public void setValidated(boolean convalidated) { + this.isValidated = convalidated; + } + + /** + * Sets the refernce table. + * + * @param refernceTable the new refernce table + */ + public void setRefernceTable(TableMetaData refernceTable) { + this.refernceTable = refernceTable; + } + + /** + * Gets the cons def. + * + * @return the cons def + */ + public String getConsDef() { + return consDef; + } + + /** + * Sets the cons def. + * + * @param consDef the new cons def + */ + public void setConsDef(String consDef) { + this.consDef = consDef; + } + + /** + * Sets the reference index. + * + * @param referenceIndex the new reference index + */ + public void setReferenceIndex(IndexMetaData referenceIndex) { + this.referenceIndex = referenceIndex; + } + + /** + * Sets the fillfactor. + * + * @param fillfactor the new fillfactor + */ + public void setFillfactor(int fillfactor) { + this.fillfactor = fillfactor; + } + + /** + * Gets the constraint fillfactor. + * + * @return the constraint fillfactor + */ + public int getConstraintFillfactor() { + return fillfactor; + } + + /** + * Sets the check constraint expr. + * + * @param expression the new check constraint expr + */ + public void setCheckConstraintExpr(String expression) { + this.expr = expression; + } + + /** + * Gets the check constraint expr. + * + * @return the check constraint expr + */ + public String getCheckConstraintExpr() { + return this.expr; + } + + /** + * Sets the pkey or ukey constraint. + * + * @param colList the col list + * @param tbleSpace the tble space + */ + public void setPkeyOrUkeyConstraint(String colList, String tbleSpace) { + this.columnList = colList; + this.tableSpace = tbleSpace; + } + + /** + * Gets the column list. + * + * @return the column list + */ + public String getColumnList() { + if (null == columnList) { + return ""; + } + return columnList; + } + + /** + * Gets the table space. + * + * @return the table space + */ + public String getTableSpace() { + return tableSpace; + } + + /** + * Sets the deffearable options. + * + * @param deferrable the deferrable + * @param deferred the deferred + */ + public void setDeffearableOptions(boolean deferrable, boolean deferred) { + this.condeferrable = deferrable; + this.condeferred = deferred; + } + + /** + * Sets the exclude where clause expr. + * + * @param excludeWhereClauseExpr the new exclude where clause expr + */ + public void setExcludeWhereClauseExpr(String excludeWhereClauseExpr) { + } + + /** + * Gets the namespace. + * + * @return the namespace + */ + public Namespace getNamespace() { + return namespace; + } + + /** + * Sets the namespace. + * + * @param namespace the new namespace + */ + public void setNamespace(Namespace namespace) { + this.namespace = namespace; + } + + /** + * Gets the table. + * + * @return the table + */ + public TableMetaData getTable() { + return table; + } + + /** + * Sets the table. + * + * @param table the new table + */ + public void setTable(TableMetaData table) { + this.table = table; + } + + /** + * Form constraint string. + * + * @return the string + */ + public String formConstraintString() { + return queryBuilder.formConstraintString(); + } + + /** + * + * Title: class + * + * Description: The Class ConstraintQueryBuilder. + * + */ + private class ConstraintQueryBuilder { + + /** + * Form constraint string. + * + * @return the string + */ + public String formConstraintString() { + StringBuilder query = new StringBuilder(512); + appendQuery(query); + switch (contype) { + case CHECK_CONSTRSINT: { + return formCheckConstraint(query); + } + case PRIMARY_KEY_CONSTRSINT: + case UNIQUE_KEY_CONSTRSINT: + case PARTIAL_CLUSTER_KEY: { + return formPrimaryUniqueConstraint(query); + } + case FOREIGN_KEY_CONSTRSINT: { + return formForeignConstraint(query); + } + default: { + break; + } + } + appendDeferedDeferable(query); + return query.toString(); + } + + private void appendQuery(StringBuilder query) { + if (!getName().isEmpty()) { + query.append("CONSTRAINT "); + query.append(ServerObject.getQualifiedObjectName(getName())); + query.append(' '); + } + } + + /** + * Form foreign constraint.Redundant code removed from inside the method + * + * @param query the query + * @return the string + */ + private String formForeignConstraint(StringBuilder query) { + query.append("FOREIGN KEY ("); + if (columnList != null) { + + query.append(ServerObject.getQualifiedObjectName(columnList)); + + } + query.append(") REFERENCES "); + query.append(ServerObject.getQualifiedObjectName(refernceTable.getNameSpaceName())); + query.append('.'); + query.append(ServerObject.getQualifiedObjectName(refernceTable.getName())); + + if (null != referenceIndex && referenceIndex.getColumnsString().length() > 0) { + query.append(" ("); + query.append(referenceIndex.getColumnsString()); + query.append(") "); + } + + query.append(fkMatchType.getLabel()); + query.append(onDeleteAction.getDeleteLabel()); + query.append(onUpdateAction.getUpdateLabel()); + appendDeferedDeferable(query); + + return query.toString(); + } + + /** + * Form primary unique constraint. + * + * @param query the query + * @return the string + */ + private String formPrimaryUniqueConstraint(StringBuilder query) { + query.append(contype.strType); + query.append(" ("); + if (columnList != null) { + query.append(columnList); + } + query.append(')'); + if (90 != fillfactor) { + query.append("WITH (fillfactor="); + query.append(fillfactor); + query.append(')'); + } + + if (null != tableSpace) { + query.append("USING INDEX TABLESPACE "); + query.append(ServerObject.getQualifiedObjectName(tableSpace)); + } + + appendDeferedDeferable(query); + + return query.toString(); + } + + /** + * Form check constraint. + * + * @param query the query + * @return the string + */ + private String formCheckConstraint(StringBuilder query) { + query.append(contype.strType); + query.append(" ("); + if (expr != null) { + query.append(expr.trim()); + + } + query.append(')'); + return query.toString(); + } + + /** + * Append defered deferable. + * + * @param query the query + */ + private void appendDeferedDeferable(StringBuilder query) { + if (condeferred) { + query.append(" DEFERRABLE INITIALLY DEFERRED"); + } else if (condeferrable) { + query.append(" DEFERRABLE INITIALLY IMMEDIATE"); + } + } + } + + /** + * Sets the rerence options. + * + * @param reftable the reftable + * @param refindex the refindex + */ + public void setRerenceOptions(TableMetaData reftable, IndexMetaData refindex) { + this.refernceTable = reftable; + this.referenceIndex = refindex; + } + + /** + * Sets the fk actions. + * + * @param fkMatchType2 the fk match type 2 + * @param onDeleteAction2 the on delete action 2 + * @param onUpdateAction2 the on update action 2 + */ + public void setFkActions(ForeignKeyMatchType fkMatchType2, ForeignKeyActionType onDeleteAction2, + ForeignKeyActionType onUpdateAction2) { + this.fkMatchType = fkMatchType2; + this.onDeleteAction = onDeleteAction2; + this.onUpdateAction = onUpdateAction2; + } + + /** + * Exec rename constraint. + * + * @param newName the new name + * @param dbConnection the db connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void execRenameConstraint(String newName, DBConnection dbConnection) + throws DatabaseOperationException, DatabaseCriticalException { + StringBuilder qry = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + qry.append("ALTER TABLE ").append(table.getDisplayName()).append(" RENAME CONSTRAINT ") + .append(super.getDisplayName()).append(" TO " + ServerObject.getQualifiedObjectName(newName)); + + dbConnection.execNonSelectForTimeout(qry.toString()); + this.setName(newName); + } + + /** + * Exec validate constraint. + * + * @param dbConnection the db connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void execValidateConstraint(DBConnection dbConnection) + throws DatabaseOperationException, DatabaseCriticalException { + StringBuilder qry = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + qry.append("ALTER TABLE ").append(table.getDisplayName()).append(" VALIDATE CONSTRAINT ") + .append(super.getDisplayName()); + + dbConnection.execNonSelect(qry.toString()); + this.setValidated(true); + + } + + /** + * Exec deferable constraint. + * + * @param dbConnection the db connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void execDeferableConstraint(DBConnection dbConnection) + throws DatabaseOperationException, DatabaseCriticalException { + StringBuilder qry = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + qry.append("SET CONSTRAINTS ").append(table.getDisplayName()).append("DEFERRED").append(';'); + + dbConnection.execNonSelect(qry.toString()); + + this.condeferrable = true; + this.condeferred = true; + } + + /** + * Gets the constraint type. + * + * @return the constraint type + */ + public ConstraintType getConstraintType() { + return contype; + } + + /** + * Checks if is condeferred. + * + * @return true, if is condeferred + */ + public boolean isCondeferred() { + return condeferred; + } + + /** + * Checks if is deferable. + * + * @return true, if is deferable + */ + public boolean isDeferable() { + return condeferrable; + } + + /** + * Exec drop. + * + * @param dbConnection the db connection + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void execDrop(DBConnection dbConnection) throws DatabaseCriticalException, DatabaseOperationException { + StringBuilder query = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + query.append("ALTER TABLE ").append(table.getDisplayName()).append(" DROP CONSTRAINT ") + .append(super.getDisplayName()).append(";"); + + dbConnection.execNonSelectForTimeout(query.toString()); + } + + /** + * Exec alter add constraint. + * + * @param tableMetaData the table meta data + * @param dbConnection the db connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void execAlterAddConstraint(TableMetaData tableMetaData, DBConnection dbConnection) + throws DatabaseOperationException, DatabaseCriticalException { + StringBuilder query = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + query.append("ALTER TABLE ").append(tableMetaData.getDisplayName()).append(" ADD ") + .append(formConstraintString()); + dbConnection.execNonSelectForTimeout(query.toString()); + } + + /** + * Exec alter drop then add constraint. + * + * @param tableMetaData the table meta data + * @param dbConnection the db connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void execAlterDropAndAddConstraint(TableMetaData tableMetaData, DBConnection dbConnection) + throws DatabaseOperationException, DatabaseCriticalException { + StringBuilder query = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + query.append("ALTER TABLE ").append(tableMetaData.getDisplayName()) + .append(" DROP CONSTRAINT ") + .append(super.getDisplayName()) + .append(",") + .append(" ADD ") + .append(formConstraintString()); + dbConnection.execNonSelectForTimeout(query.toString()); + } + + /** + * Checks if is loaded. + * + * @return true, if is loaded + */ + public boolean isLoaded() { + return isLoaded; + } + + /** + * Sets the loaded. + * + * @param isLoad the new loaded + */ + public void setLoaded(boolean isLoad) { + this.isLoaded = isLoad; + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + return table.getDatabase(); + } + + /** + * Gets the parent. + * + * @return the parent + */ + public TableMetaData getParent() { + return table; + + } + + @Override + public String getDropQuery(boolean isCascade) { + return ConstraintMetaDataUtils.getDropQuery(table.getDisplayName(), super.getDisplayName(), isCascade); + } + + @Override + public String getObjectFullName() { + return table.getDisplayName() + "." + getDisplayName(); + } + + @Override + public boolean isDropAllowed() { + if (getParent() instanceof ForeignTable) { + return false; + } + + return true; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ConstraintMetaDataUtils.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ConstraintMetaDataUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..9da70a3f5a5e058d54f8d3a20ec87617df665ead --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ConstraintMetaDataUtils.java @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: interface + * + * Description: The Interface ConstraintMetaDataUtils. + * + */ + +public interface ConstraintMetaDataUtils { + + static final String TABLE_CONSTRAINT_QRY = "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, " + + "c.conname as constraintname ," + + "c.contype as constrainttype, c.condeferrable as deferrable, c.condeferred as deferred, " + + "c.convalidated as validate, " + + "c.conindid as indexid, c.confrelid as fkeytableId, c.confupdtype as updatetype, " + + "c.confdeltype as deletetype, c.confmatchtype as matchtype, " + + "c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, " + + "pg_get_constraintdef(c.oid) as const_def , ts.spcname as tablespace " + + "FROM pg_constraint c LEFT JOIN " + "pg_class t on (t.oid = c.conrelid) " + + "LEFT JOIN pg_index ind ON c.conindid = ind.indexrelid " + + "LEFT JOIN pg_class ci on (ind.indexrelid = ci.oid) " + + "LEFT JOIN pg_tablespace ts ON (ts.oid = ci.reltablespace) " + "WHERE t.relkind = 'r' and t.oid = "; + + /** + * Convert to constraint. + * + * @param rs the rs + * @param parentNS the parent NS + * @param parentTable the parent table + * @param fkeyTable the fkey table + * @param idx the idx + * @return the constraint meta data + * @throws SQLException the SQL exception + */ + public static ConstraintMetaData convertToConstraint(ResultSet rs, Namespace parentNS, TableMetaData parentTable, + TableMetaData fkeyTable, IndexMetaData idx) throws SQLException { + ConstraintMetaData constraint = null; + + long oid = rs.getLong("constraintid"); + String typeStr = rs.getString("constrainttype"); + String name = rs.getString("constraintname"); + + ConstraintType type = getConstraintType(typeStr); + + constraint = new ConstraintMetaData(oid, name, type); + + constraint.setNamespace(parentNS); + + constraint.setTable(parentTable); + constraint.setDeffearableOptions(rs.getBoolean("deferrable"), rs.getBoolean("deferred")); + constraint.setValidated(rs.getBoolean("validate")); + + constraint.setRefernceTable(fkeyTable); + ForeignKeyActionType update = getActionType(rs.getString("updatetype")); + ForeignKeyActionType delete = getActionType(rs.getString("deletetype")); + ForeignKeyMatchType matchType = getMatchType(rs.getString("matchtype")); + constraint.setFkActions(matchType, delete, update); + constraint.setExcludeWhereClauseExpr(rs.getString("expr")); + constraint.setConsDef(rs.getString("const_def")); + constraint.setReferenceIndex(idx); + constraint.setLoaded(true); + + return constraint; + + } + + /** + * Gets the table constraint qry. + * + * @param l1 the l + * @return the table constraint qry + */ + public static String getTableConstraintQry(long l1) { + return TABLE_CONSTRAINT_QRY + l1; + } + + /** + * Gets the constraint type. + * + * @param typeStr the type str + * @return the constraint type + */ + public static ConstraintType getConstraintType(String typeStr) { + if ("c".equals(typeStr)) { + return ConstraintType.CHECK_CONSTRSINT; + } else if ("f".equals(typeStr)) { + return ConstraintType.FOREIGN_KEY_CONSTRSINT; + } else if ("p".equals(typeStr)) { + return ConstraintType.PRIMARY_KEY_CONSTRSINT; + } else if ("u".equals(typeStr)) { + return ConstraintType.UNIQUE_KEY_CONSTRSINT; + } else { + return ConstraintType.EXCLUSION_CONSTRSINT; + } + } + + /** + * Gets the action type. + * + * @param typeStr the type str + * @return the action type + */ + public static ForeignKeyActionType getActionType(String typeStr) { + if ("a".equals(typeStr)) { + return ForeignKeyActionType.FK_NO_ACTION; + } else if ("r".equals(typeStr)) { + return ForeignKeyActionType.FK_RESTRICT; + } else if ("c".equals(typeStr)) { + return ForeignKeyActionType.FK_CASCADE; + } else if ("n".equals(typeStr)) { + return ForeignKeyActionType.FK_SET_NULL; + } else { + return ForeignKeyActionType.FK_SET_DEFAULT; + } + } + + /** + * Gets the match type. + * + * @param typeStr the type str + * @return the match type + */ + public static ForeignKeyMatchType getMatchType(String typeStr) { + if ("f".equals(typeStr)) { + return ForeignKeyMatchType.FK_MATCH_FULL; + } else if ("p".equals(typeStr)) { + return ForeignKeyMatchType.FK_MATCH_PARTIAL; + } else { + return ForeignKeyMatchType.FK_MATCH_SIMPLE; + } + } + + /** + * Gets the drop query. + * + * @param tableName the table name + * @param constraintName the constraint name + * @param isCascade the is cascade + * @return the drop query + */ + public static String getDropQuery(String tableName, String constraintName, boolean isCascade) { + StringBuilder query = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + query.append("ALTER TABLE IF EXISTS ").append(tableName).append(" DROP CONSTRAINT IF EXISTS ") + .append(constraintName); + + if (isCascade) { + query.append(MPPDBIDEConstants.CASCADE); + } + + return query.toString(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ConstraintType.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ConstraintType.java new file mode 100644 index 0000000000000000000000000000000000000000..a61df995f6a8ee728065ca0874efcfd78f6a17ca --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ConstraintType.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: enum + * + * Description: The Enum ConstraintType. + * + */ + +public enum ConstraintType { + CHECK_CONSTRSINT("CHECK"), + UNIQUE_KEY_CONSTRSINT("UNIQUE"), + PRIMARY_KEY_CONSTRSINT("PRIMARY KEY"), + FOREIGN_KEY_CONSTRSINT("FOREIGN KEY"), + PARTIAL_CLUSTER_KEY("PARTIAL CLUSTER KEY"), + EXCLUSION_CONSTRSINT("EXCULSION KEY"); + /** + * strType of Constraint type + */ + public final String strType; + + ConstraintType(String strType) { + this.strType = strType; + } + + /** + * convert string to constraint type + * + * @param strType to convert string + * @return ConstaintType the constraint type + * */ + public static ConstraintType strTypeConvert(String strType) { + try { + return ConstraintType.valueOf(strType); + } catch (IllegalArgumentException | NullPointerException validExp) { + for (ConstraintType constraintType: ConstraintType.values()) { + if (constraintType.strType.equals(strType)) { + return constraintType; + } + } + return EXCLUSION_CONSTRSINT; + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/DBConnProfCache.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/DBConnProfCache.java new file mode 100644 index 0000000000000000000000000000000000000000..7f7856b852cc221bb0d49c4a3249953965c241ca --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/DBConnProfCache.java @@ -0,0 +1,244 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; + +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; +import org.opengauss.mppdbide.bl.util.ExecTimer; +import org.opengauss.mppdbide.bl.util.IExecTimer; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.exceptions.PasswordExpiryException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class DBConnProfCache. + * + */ + +public final class DBConnProfCache { + + private static volatile DBConnProfCache instance = null; + private HashMap servers; + + private ArrayList serverList; // controls the viewer in the OB + private static final Object LOCK = new Object(); + + private DBConnProfCache() { + servers = new HashMap(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + serverList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + } + + /** + * Gets the single instance of DBConnProfCache. + * + * @return single instance of DBConnProfCache + */ + public static DBConnProfCache getInstance() { + if (null == instance) { + synchronized (LOCK) { + if (null == instance) { + instance = new DBConnProfCache(); + } + } + } + return instance; + } + + /** + * Inits the connection profile. + * + * @param serverInfo the server info + * @param status the status + * @return the connection profile id + * @throws DatabaseOperationException the database operation exception + * @throws MPPDBIDEException the MPPDBIDE exception + * @throws PasswordExpiryException the password expiry exception + * @throws OutOfMemoryError the out of memory error + */ + public ConnectionProfileId initConnectionProfile(IServerConnectionInfo serverInfo, IJobCancelStatus status) + throws DatabaseOperationException, MPPDBIDEException, PasswordExpiryException, OutOfMemoryError { + Iterator serversItr = this.servers.values().iterator(); + boolean hasNext = serversItr.hasNext(); + Server server = null; + while (hasNext) { + server = serversItr.next(); + + if (server.getName().equals(serverInfo.getConectionName())) { + MPPDBIDELoggerUtility.error(MessageConfigLoader + .getProperty(IMessagesConstants.ERR_ALREADY_CONNECTION_PROFILE_EXISTS, server.getName())); + throw new DatabaseOperationException(IMessagesConstants.ERR_ALREADY_CONNECTION_PROFILE_EXISTS, + server.getName()); + } + + hasNext = serversItr.hasNext(); + } + // Added for remembering PSWD/PORT ends + + IExecTimer timer = new ExecTimer("New Connection").start(); + Server node = null; + ConnectionProfileId id = null; + + node = new Server(serverInfo); + id = node.createDBConnectionProfile(serverInfo, status); + node.clearPrds(); + timer.stopAndLog(); + this.servers.put(node.getId(), node); + this.serverList.add(0, node); + return id; + } + + /** + * Destroy connection. + * + * @param db the db + */ + public void destroyConnection(Database db) { + MPPDBIDELoggerUtility.info("DBConnProfCache: destroy Connection Profile."); + + if (null != db && db.isConnected()) { + db.destroy(); + } + } + + /** + * Removes the server. + * + * @param serverId the server id + */ + public void removeServer(int serverId) { + if (servers.containsKey(serverId)) { + Server server = servers.get(serverId); + server.close(); + server.destroy(); + servers.remove(serverId); + serverList.remove(server); + } + } + + /** + * Gets the db for profile id. + * + * @param id the id + * @return the db for profile id + */ + public Database getDbForProfileId(ConnectionProfileId id) { + if (id == null) { + return null; + } + Server server = this.servers.get(id.getServerId()); + + if (null == server) { + return null; + } + + return server.getDbById(id.getDatabaseId()); + } + + /** + * Gets the servers. + * + * @return the servers + */ + public Collection getServers() { + return servers.values(); + } + + /** + * Gets the servers list. + * + * @return the servers list + */ + public Collection getServersList() { + return serverList; + } + + /** + * Gets the server by name. + * + * @param name the name + * @return the server by name + */ + public Server getServerByName(String name) { + Iterator srvs = servers.values().iterator(); + boolean hasNext = srvs.hasNext(); + Server server = null; + while (hasNext) { + server = srvs.next(); + if (server != null && server.getName().equals(name)) { + return server; + } + hasNext = srvs.hasNext(); + } + return null; + } + + /** + * Gets the server by id. + * + * @param id the id + * @return the server by id + */ + public Server getServerById(int id) { + return servers.get(id); + } + + /** + * Close all nodes. + */ + public void closeAllNodes() { + Iterator serverItr = servers.values().iterator(); + boolean hasNext = serverItr.hasNext(); + while (hasNext) { + serverItr.next().close(); + hasNext = serverItr.hasNext(); + } + } + + /** + * Gets the all profiles for search. + * + * @param connectionDetails the connection details + * @param connectionMap the connection map + * @return the all profiles for search + */ + public void getAllProfilesForSearch(ArrayList connectionDetails, HashMap connectionMap) { + Iterator serverItr = getServers().iterator(); + boolean serverHasNext = serverItr.hasNext(); + Server servr = null; + int idx = 0; + while (serverHasNext) { + servr = serverItr.next(); + if (servr.isAleastOneDbConnected()) { + connectionDetails.add(servr.getDisplayName()); + connectionMap.put(idx, servr); + idx++; + } + serverHasNext = serverItr.hasNext(); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/DBMSObject.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/DBMSObject.java new file mode 100644 index 0000000000000000000000000000000000000000..10a969047135d0fdf21846137c6d2016f9112c53 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/DBMSObject.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: interface + * + * Description: The Interface DBMSObject. + * + */ + +public interface DBMSObject { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/DBTypeLabelUtil.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/DBTypeLabelUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..cac03d7d21f784fd35cb1b61fd8f7d98092d2e4c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/DBTypeLabelUtil.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.util.HashMap; +import java.util.Map; + +/** + * + * Title: class + * + * Description: The Class DBTypeLabelUtil. + * + */ + +public abstract class DBTypeLabelUtil { + + private static Map objectTypeLabelMap = null; + + /** + * Load object type label map. + */ + private static void loadObjectTypeLabelMap() { + + objectTypeLabelMap = new HashMap(20); + objectTypeLabelMap.put(OBJECTTYPE.COLUMN_METADATA, "Column"); + objectTypeLabelMap.put(OBJECTTYPE.VIEW_COLUMN_METADATA, "Column"); + + objectTypeLabelMap.put(OBJECTTYPE.PLSQLFUNCTION, "Function"); + + objectTypeLabelMap.put(OBJECTTYPE.PROCEDURE, "Procedure"); + + objectTypeLabelMap.put(OBJECTTYPE.NAMESPACE, "Schema"); + + objectTypeLabelMap.put(OBJECTTYPE.FOREIGN_TABLE, "Foreign Table"); + + objectTypeLabelMap.put(OBJECTTYPE.FOREIGN_TABLE_GDS, "Foreign Table"); + + objectTypeLabelMap.put(OBJECTTYPE.FOREIGN_TABLE_HDFS, "Foreign Table"); + + objectTypeLabelMap.put(OBJECTTYPE.FOREIGN_PARTITION_TABLE, "Foreign Partition Table"); + + objectTypeLabelMap.put(OBJECTTYPE.PARTITION_TABLE, "Partition Table"); + + objectTypeLabelMap.put(OBJECTTYPE.TABLEMETADATA, "Table"); + + objectTypeLabelMap.put(OBJECTTYPE.VIEW_META_DATA, "View"); + + objectTypeLabelMap.put(OBJECTTYPE.SQLFUNCTION, "SQL Function"); + + objectTypeLabelMap.put(OBJECTTYPE.CFUNCTION, "C Function"); + + objectTypeLabelMap.put(OBJECTTYPE.SEQUENCE_METADATA_GROUP, "Sequence"); + + objectTypeLabelMap.put(OBJECTTYPE.CONSTRAINT, "Constraint"); + + objectTypeLabelMap.put(OBJECTTYPE.INDEX_METADATA, "Index"); + + objectTypeLabelMap.put(OBJECTTYPE.PARTITION_METADATA, "Partition"); + + objectTypeLabelMap.put(OBJECTTYPE.USER_ROLE, "User/Role"); + objectTypeLabelMap.put(OBJECTTYPE.TYPEMETADATA, "Datatype"); + objectTypeLabelMap.put(OBJECTTYPE.KEYWORDS, "Keywords"); + + objectTypeLabelMap.put(OBJECTTYPE.SYNONYM_METADATA_GROUP, "Synonym"); + objectTypeLabelMap.put(OBJECTTYPE.TRIGGER_GROUP, "TriggerGroup"); + objectTypeLabelMap.put(OBJECTTYPE.TRIGGER_METADATA, "Trigger"); + } + + /** + * Gets the type label. + * + * @param type the type + * @return the type label + */ + public static String getTypeLabel(OBJECTTYPE type) { + if (null == objectTypeLabelMap) { + loadObjectTypeLabelMap(); + } + + return objectTypeLabelMap.getOrDefault(type, type.toString()); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/Database.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/Database.java new file mode 100644 index 0000000000000000000000000000000000000000..5f8d2f967efa56b8fcbf80de0b994c52f495aa07 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/Database.java @@ -0,0 +1,1434 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Properties; +import java.util.Set; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.opengauss.mppdbide.adapter.IConnectionDriver; +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.adapter.keywordssyntax.SQLSyntax; +import org.opengauss.mppdbide.bl.errorlocator.ErrorLocator; +import org.opengauss.mppdbide.bl.errorlocator.IErrorLocator; +import org.opengauss.mppdbide.bl.executor.AbstractExecutor; +import org.opengauss.mppdbide.bl.executor.Executor; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.DBTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.groups.OLAPObjectList; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ObjectList; +import org.opengauss.mppdbide.bl.serverdatacache.groups.SystemNamespaceObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.UserNamespaceObjectGroup; +import org.opengauss.mppdbide.bl.util.BLUtils; +import org.opengauss.mppdbide.bl.util.ExecTimer; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class Database. + * + */ + +public class Database extends ServerObject implements GaussOLAPDBMSObject { + + /** + * + * Title: enum + * + * Description: The Enum RETURNVALUES. + * + */ + protected enum RETURNVALUES { + + SUPPORT_CURSOR, SUPPORT_AUTOCOMMIT, SUPPORT_EXPLAINPLAN, SUPPORT_INSERTRETURN, LOWERCASE, UPPERCASE, + DATABASETYPE + } + + /** + * The return val hash map. + */ + protected HashMap returnValHashMap; + + /** + * The is connected. + */ + protected boolean isConnected; + + private boolean isDebugSupported; + + private boolean isExplainPlanSupported; + + private String dbName; + + /** + * The server verstion. + */ + protected String serverVerstion; + + private String defaultDBTblspc; + + private AbstractExecutor executor; + + private UserNamespaceObjectGroup userNamespaces; + + private SystemNamespaceObjectGroup systemNamespaces; + + private Server server; + + private OLAPObjectList defaultDatatypes; + + private OLAPObjectList orcDatatypes; + + private boolean isLoadingUserNamespaceInProgress; + + private boolean isLoadingSystemNamespaceInProgress; + + private String serverIP; + + + private SearchPoolManager searchPoolManager = null; + + /** + * The connection manager. + */ + protected ConnectionManager connectionManager = null; + + private LoginNotificationManager loginNotifyManager = null; + + /** + * The search path helper. + */ + protected SearchPathHelper searchPathHelper = null; + + private FetchObjHelper fetchQueryHelper = null; + + private DataTypeProvider dataTypeProvider = null; + + /** + * Gets the db name. + * + * @return the db name + */ + public String getDbName() { + return dbName; + } + + /** + * Checks if is show DDL support by server. + * + * @return true, if is show DDL support by server + */ + public boolean isShowDDLSupportByServer() { + return connectionManager.isShowDDLSupportByServer(); + } + + /** + * Inits the return val hash map. + */ + private void initReturnValHashMap() { + returnValHashMap = new HashMap(7); + returnValHashMap.put(RETURNVALUES.SUPPORT_CURSOR, true); + returnValHashMap.put(RETURNVALUES.SUPPORT_AUTOCOMMIT, true); + returnValHashMap.put(RETURNVALUES.SUPPORT_EXPLAINPLAN, true); + returnValHashMap.put(RETURNVALUES.SUPPORT_INSERTRETURN, true); + returnValHashMap.put(RETURNVALUES.LOWERCASE, true); + returnValHashMap.put(RETURNVALUES.UPPERCASE, false); + returnValHashMap.put(RETURNVALUES.DATABASETYPE, DBTYPE.OPENGAUSS); + } + + /** + * Instantiates a new database. + * + * @param server the server + * @param oid the oid + * @param dbName the db name + */ + public Database(Server server, long oid, String dbName) { + // Initial database id will be zero, if not known + super(oid, dbName, OBJECTTYPE.DATABASE, server != null ? server.getPrivilegeFlag() : true); + initReturnValHashMap(); + this.userNamespaces = new UserNamespaceObjectGroup(OBJECTTYPE.USER_NAMESPACE_GROUP, this); + this.systemNamespaces = new SystemNamespaceObjectGroup(OBJECTTYPE.SYSTEM_NAMESPACE_GROUP, this); + this.server = server; + this.dbName = dbName; + this.executor = new Executor(); + this.defaultDatatypes = new OLAPObjectList(OBJECTTYPE.DATATYPE_GROUP, this); + searchPoolManager = new SearchPoolManager(); + + connectionManager = new ConnectionManager(this); + loginNotifyManager = new LoginNotificationManager(this); + searchPathHelper = new SearchPathHelper(connectionManager); + fetchQueryHelper = new FetchObjHelper(); + dataTypeProvider = new DataTypeProvider(); + } + + /** + * Checks if is connected. + * + * @return true, if is connected + */ + public boolean isConnected() { + return isConnected; + } + + /** + * Sets the connected. + * + * @param isConected the new connected + */ + public void setConnected(boolean isConected) { + this.isConnected = isConected; + } + + /** + * Gets the user namespace group. + * + * @return the user namespace group + */ + public UserNamespaceObjectGroup getUserNamespaceGroup() { + return this.getUserNamespaces(); + } + + /** + * Gets the system namespace group. + * + * @return the system namespace group + */ + public SystemNamespaceObjectGroup getSystemNamespaceGroup() { + return this.getSystemNamespaces(); + } + + /** + * Gets the all user name spaces. + * + * @return the all user name spaces + */ + public List getAllUserNameSpaces() { + return getUserNamespaces().getSortedServerObjectList(); + } + + /** + * Gets the all system name spaces. + * + * @return the all system name spaces + */ + public List getAllSystemNameSpaces() { + return getSystemNamespaces().getSortedServerObjectList(); + } + + /** + * Gets the all name spaces. + * + * @return the all name spaces + */ + public ArrayList getAllNameSpaces() { + /* Need to optimize this function */ + List userNamespaceList = getAllUserNameSpaces(); + List systemNamespaceList = getAllSystemNameSpaces(); + ArrayList allNamespaces = new ArrayList(); + allNamespaces.addAll(userNamespaceList); + allNamespaces.addAll(systemNamespaceList); + return allNamespaces; + } + + /** + * Destroy. + */ + public void destroy() { + this.setConnected(false); + MPPDBIDELoggerUtility.info("ConnectionProfile: clear all cache."); + + if (null != executor) { + executor.disconnect(); + } + + connectionManager.disconnectConns(); + connectionManager.disconnectTerminalCons(); + executor = null; + clear(); + } + + /** + * Gets the executor. + * + * @return the executor + */ + public AbstractExecutor getExecutor() { + return this.executor; + } + + /** + * Gets the server version. + * + * @return the server version + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public String getServerVersion() throws DatabaseOperationException, DatabaseCriticalException { + if (serverVerstion == null) { + serverVerstion = executor.getServerVersion(); + } + return serverVerstion; + } + + /** + * Fetch server IP. + * + * @return the string + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public String fetchServerIP() throws DatabaseOperationException, DatabaseCriticalException { + if (serverIP == null) { + serverIP = executor.fetchServerIP(); + } + return serverIP; + } + + /** + * Gets the dabase type. + * + * @return the dabase type + */ + protected String getDabaseType() { + return getDBType().toString(); + } + + /** + * Sets the DB default tbl spc. + * + * @param defaultDBTablespc the new DB default tbl spc + */ + public void setDBDefaultTblSpc(String defaultDBTablespc) { + this.defaultDBTblspc = defaultDBTablespc; + } + + /** + * Gets the DB default tbl spc. + * + * @return the DB default tbl spc + */ + public String getDBDefaultTblSpc() { + return this.defaultDBTblspc; + } + + /** + * Gets the server. + * + * @return the server + */ + public Server getServer() { + return this.server; + } + + /** + * Gets the name space by id. + * + * @param namespaceId the namespace id + * @return the name space by id + * @throws DatabaseOperationException the database operation exception + */ + public Namespace getNameSpaceById(long namespaceId) throws DatabaseOperationException { + Namespace namespace = this.getUserNamespaces().getObjectById(namespaceId); + if (namespace == null) { + namespace = this.getSystemNamespaces().getObjectById(namespaceId); + } + return returnNamespaceAfterExceptionCheck(namespace); + } + + /** + * Gets the name space by name. + * + * @param namespaceName the namespace name + * @return the name space by name + * @throws DatabaseOperationException the database operation exception + */ + public INamespace getNameSpaceByName(String namespaceName) throws DatabaseOperationException { + Namespace namespace = this.getUserNamespaces().get(namespaceName); + if (namespace == null) { + namespace = this.getSystemNamespaces().get(namespaceName); + } + return returnNamespaceAfterExceptionCheck(namespace); + } + + /** + * Gets the schem inclusion list. + * + * @return the schem inclusion list + */ + public Set getSchemInclusionList() { + return this.server.getServerConnectionInfo().getSchemaInclusionList(); + } + + /** + * Sets the client SSL private key. + * + * @param keyFileName the new client SSL private key + */ + public void setClientSSLPrivateKey(String keyFileName) { + this.server.getServerConnectionInfo().setClientSSLPrivateKey(keyFileName); + } + + /** + * Gets the schem exclusion list. + * + * @return the schem exclusion list + */ + public Set getSchemExclusionList() { + return this.server.getServerConnectionInfo().getSchemaExclusionList(); + } + + /** + * Return namespace after exception check. + * + * @param namespace the namespace + * @return the namespace + * @throws DatabaseOperationException the database operation exception + */ + private Namespace returnNamespaceAfterExceptionCheck(Namespace namespace) throws DatabaseOperationException { + if (null == namespace) { + DatabaseOperationException exception = new DatabaseOperationException( + IMessagesConstants.ERR_BL_NO_NAMESPACE_AVAILABLE); + exception.setServerMessage( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_BL_NO_NAMESPACE_AVAILABLE)); + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_BL_NO_NAMESPACE_AVAILABLE)); + throw exception; + } + return namespace; + } + + /** + * Clear all the debug objects from all the namespaces. + */ + protected void clearAllDebugObjects() { + ArrayList namespaceSortedList = this.getAllNameSpaces(); + + Iterator itrNamespace = namespaceSortedList.iterator(); + boolean hasMoreElements = itrNamespace.hasNext(); + Namespace namespace = null; + while (hasMoreElements) { + namespace = itrNamespace.next(); + namespace.clearAllObjects(); + + namespace.clear(); + namespace = null; + + hasMoreElements = itrNamespace.hasNext(); + } + } + + /** + * Clear. + */ + public void clear() { + clearAllDebugObjects(); + this.getUserNamespaces().clear(); + this.getSystemNamespaces().clear(); + getSearchPoolManager().clearTrie(); + defaultDatatypes.clear(); + if (orcDatatypes != null) { + orcDatatypes.clear(); + // When disconnected to make list null. + orcDatatypes = null; + } + } + + /** + * Gets the debug object by id. + * + * @param debugObjectId the debug object id + * @param namepsaceId the namepsace id + * @return the debug object by id + * @throws DatabaseOperationException the database operation exception + */ + public IDebugObject getDebugObjectById(long debugObjectId, long namepsaceId) throws DatabaseOperationException { + MPPDBIDELoggerUtility.debug("ConnectionProfile: get debug object by id."); + DebugObjects object = (DebugObjects) getNameSpaceById(namepsaceId).getDebugObjectById(debugObjectId); + + return object; + } + + /** + * Fetch search path objects. + * + * @param needToGetSearchPath the need to get search path + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws OutOfMemoryError the out of memory error + */ + public void fetchSearchPathObjects(boolean needToGetSearchPath) + throws DatabaseOperationException, DatabaseCriticalException, OutOfMemoryError { + MPPDBIDELoggerUtility.info("ConnectionProfile: refresh all objects."); + NamespaceUtilsBase.fetchAllNamespaces(this); + + if (needToGetSearchPath) { + searchPathHelper.fetchUserSearchPath(server.getUserNameFromServerConnInfo()); + } + } + + /** + * Fetch default datatypes. + * + * @param isReloadDefaultDatatype the is reload default datatype + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void fetchDefaultDatatypes(boolean isReloadDefaultDatatype) + throws DatabaseCriticalException, DatabaseOperationException { + fetchAllDatatypes(); + if (isReloadDefaultDatatype) { + // Creating alias of few pg_catalog datatypes + dataTypeProvider.loadDefaultDatatype(); + } + } + + /** + * + * Title: class + * + * Description: The Class DataTypeProvider. + * + */ + private class DataTypeProvider { + + /** + * Load default datatype. + * + * @throws DatabaseOperationException the database operation exception + */ + public void loadDefaultDatatype() throws DatabaseOperationException { + defaultDatatypes.clear(); + ServerObject servObj = getSystemNamespaces().get("pg_catalog"); + + if (!(servObj instanceof Namespace)) { + return; + } + + String[][] datatypesToBeDisplayed = DatabaseUtils.getdefaultDatatypeList(); + for (int index = 0; index < datatypesToBeDisplayed.length; index++) { + cloneToDifferentDatatype((Namespace) servObj, datatypesToBeDisplayed[index][0], + datatypesToBeDisplayed[index][1], defaultDatatypes); + } + String[] serialDataTypeList = DatabaseUtils.getSerialDatatypeList(); + for (int index = 0; index < serialDataTypeList.length; index++) { + addSerialDatatype((Namespace) servObj, serialDataTypeList[index], defaultDatatypes); + } + /* Frequently used dataType to be maintained here */ + } + + /** + * Load ORC datatype. + * + * @throws DatabaseOperationException the database operation exception + */ + public void loadORCDatatype() throws DatabaseOperationException { + if (orcDatatypes != null) { + return; + } + + orcDatatypes = new OLAPObjectList(OBJECTTYPE.DATATYPE_GROUP, this); + + ServerObject servObj = getSystemNamespaces().get("pg_catalog"); + + if (!(servObj instanceof Namespace)) { + return; + } + + String[][] orcDatatypesToBeDisplayed = DatabaseUtils.getORCDataTypesToBeDisplayed(); + for (int index = 0; index < orcDatatypesToBeDisplayed.length; index++) { + + cloneToDifferentDatatype((Namespace) servObj, orcDatatypesToBeDisplayed[index][0], + orcDatatypesToBeDisplayed[index][1], orcDatatypes); + } + } + } + + /** + * Gets the default datatype. + * + * @return the default datatype + */ + public ObjectList getDefaultDatatype() { + return this.defaultDatatypes; + } + + /** + * Gets the ORC datatype. + * + * @return the ORC datatype + */ + public ObjectList getORCDatatype() { + try { + + dataTypeProvider.loadORCDatatype(); + } catch (DatabaseOperationException databaseOperationException) { + MPPDBIDELoggerUtility.error("Database operation exception", databaseOperationException); + } + return this.orcDatatypes; + } + + /** + * Clone to different datatype. + * + * @param ns the ns + * @param name the name + * @param newName the new name + * @param datatypes the datatypes + * @throws DatabaseOperationException the database operation exception + */ + protected void cloneToDifferentDatatype(Namespace ns, String name, String newName, + ObjectList datatypes) throws DatabaseOperationException { + TypeMetaData type = ns.getTypeByName(name); + if (null == type) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DEFAULT_DATATYPE_NOT_FOUND, name)); + throw new DatabaseOperationException(IMessagesConstants.ERR_DEFAULT_DATATYPE_NOT_FOUND, name); + } + TypeMetaData newType = type.getCloneObjWithName(newName); + + datatypes.addItem(newType); + } + + /** + * Add serial data type. + * + * @param ns the ns + * @param name the name + * @param datatypes the datatypes + */ + protected void addSerialDatatype(Namespace ns, String name, ObjectList datatypes) { + int oid = DatabaseUtils.SERIAL_DATA_TYPE_OID; + TypeMetaData newType = new TypeMetaData(oid, name, ns); + datatypes.addItem(newType); + } + + /** + * Gets the profile id. + * + * @return the profile id + */ + public ConnectionProfileId getProfileId() { + return new ConnectionProfileId(this.server.getId(), getOid()); + } + + /** + * Fetch all tablespace. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void fetchAllTablespace() throws DatabaseCriticalException, DatabaseOperationException { + Tablespace.fetchAllTablespace(this); + } + + /** + * Fetch tablespace meta data. + * + * @param tableOid the table oid + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void fetchTablespaceMetaData(long tableOid) throws DatabaseCriticalException, DatabaseOperationException { + String qry = Tablespace.getTablespaceQuery(tableOid, privilegeFlag); + + ResultSet resultset = connectionManager.execSelectAndReturnRsOnObjBrowserConn(qry); + boolean isAdmin = connectionManager.execSelectCheckIfAdmin(); + try { + boolean hasNext = resultset.next(); + DatabaseUtils.checkExceptionForNoRSorNoAccess(hasNext, privilegeFlag); + while (hasNext) { + Tablespace tablespace = Tablespace.convertToTablesapce(resultset, this.server, isAdmin); + this.server.addToTablespaceGroup(tablespace); + hasNext = resultset.next(); + } + } catch (SQLException exp) { + GaussUtils.handleCriticalException(exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exp); + } finally { + connectionManager.closeRSOnObjBrowserConn(resultset); + } + } + + /** + * Rename database. + * + * @param newName the new name + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void renameDatabase(String newName) throws DatabaseOperationException, DatabaseCriticalException { + fetchQueryHelper.renameDatabase(newName); + } + + /** + * Drop database. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void dropDatabase() throws DatabaseOperationException, DatabaseCriticalException { + fetchQueryHelper.dropDatabase(); + } + + /** + * Hash code. + * + * @return the int + */ + @Override + public int hashCode() { + return MPPDBIDEConstants.PRIME_31 + getName().hashCode() + getServer().hashCode(); + } + + /** + * Equals. + * + * @param obj the obj + * @return true, if successful + */ + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + + if (!(obj instanceof Database)) { + return false; + } + + Database other = (Database) obj; + return getOid() == other.getOid() && getServer().getId() == other.getServer().getId(); + } + + /** + * Gets the server name. + * + * @return the server name + */ + public String getServerName() { + return server.getName(); + } + + /** + * Belongs to. + * + * @param database the database + * @param server2 the server 2 + * @return true, if successful + */ + public boolean belongsTo(Database database, Server server2) { + if (this.getName().equals(database.getName())) { + return this.getServer().belongsTo(null, server2); + } + + return false; + } + + /** + * Checks if is same name. + * + * @param otherDb the other db + * @return true, if is same name + */ + public boolean isSameName(Database otherDb) { + return getDbName().equals(otherDb.getDbName()); + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + return this; + } + + /** + * Checks if is loading namespace in progress. + * + * @return true, if is loading namespace in progress + */ + public boolean isLoadingNamespaceInProgress() { + return isLoadingUserNamespaceInProgress || isLoadingSystemNamespaceInProgress; + } + + /** + * Checks if is loading user namespace in progress. + * + * @return true, if is loading user namespace in progress + */ + public boolean isLoadingUserNamespaceInProgress() { + return isLoadingUserNamespaceInProgress; + } + + /** + * Checks if is loading system namespace in progress. + * + * @return true, if is loading system namespace in progress + */ + public boolean isLoadingSystemNamespaceInProgress() { + return isLoadingSystemNamespaceInProgress; + } + + /** + * Sets the loading namespace in progress. + * + * @param isLoadingNamespaceInProgres the new loading namespace in progress + */ + public void setLoadingNamespaceInProgress(boolean isLoadingNamespaceInProgres) { + this.isLoadingUserNamespaceInProgress = isLoadingNamespaceInProgres; + this.isLoadingSystemNamespaceInProgress = isLoadingNamespaceInProgres; + } + + /** + * Sets the loading user namespace in progress. + * + * @param isLoadingUserNamespaceInProgres the new loading user namespace in + * progress + */ + public void setLoadingUserNamespaceInProgress(boolean isLoadingUserNamespaceInProgres) { + this.isLoadingUserNamespaceInProgress = isLoadingUserNamespaceInProgres; + } + + /** + * Sets the loading system namespace in progress. + * + * @param isLoadingSystemNamespaceInProgres the new loading system namespace + * in progress + */ + public void setLoadingSystemNamespaceInProgress(boolean isLoadingSystemNamespaceInProgres) { + this.isLoadingSystemNamespaceInProgress = isLoadingSystemNamespaceInProgres; + } + + /** + * Gets the display label. + * + * @return the display label + */ + @Override + public String getDisplayLabel() { + return this.getName(); + } + + /** + * Gets the children. + * + * @return the children + */ + @Override + public Object[] getChildren() { + Collection schemas = new ArrayList(2); + schemas.add(this.getSystemNamespaceGroup()); + schemas.add(this.getUserNamespaceGroup()); + return schemas.toArray(); + } + + /** + * Load DB specific contents 1. + * + * @param status the status + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void loadDBSpecificContents1(IJobCancelStatus status) + throws DatabaseOperationException, DatabaseCriticalException { + checkCancelStatusAndAbort(status); + DatabaseHelper.fetchDBOid(this); + checkCancelStatusAndAbort(status); + + fetchSearchPathObjects(true); + try { + DatabaseHelper.fetchTablespaceName(this); + } catch (DatabaseOperationException databaseOperationException) { + MPPDBIDELoggerUtility.none("Skipping the tablespace error"); + } + checkCancelStatusAndAbort(status); + fetchDefaultDatatypes(true); + checkCancelStatusAndAbort(status); + } + + /** + * Load DB specific contents 2. + * + * @param status the status + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void loadDBSpecificContents2(IJobCancelStatus status) + throws DatabaseOperationException, DatabaseCriticalException { + fetchAllTablespace(); + checkCancelStatusAndAbort(status); + AccessMethod.fetchAllAccessMethods(this); + checkCancelStatusAndAbort(status); + fetchSearchPathObjects(true); + try { + DatabaseHelper.fetchTablespaceName(this); + } catch (DatabaseOperationException databaseOperationException) { + MPPDBIDELoggerUtility.none("Skipping the tablespace error"); + } + checkCancelStatusAndAbort(status); + fetchDefaultDatatypes(true); + checkCancelStatusAndAbort(status); + } + + /** + * Check cancel status and abort. + * + * @param cancelStatus the cancel status + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + private void checkCancelStatusAndAbort(IJobCancelStatus cancelStatus) + throws DatabaseOperationException, DatabaseCriticalException { + if (null != cancelStatus && cancelStatus.getCancel()) { + connectionManager.cancelAllConnectionQueries(); + DBConnProfCache.getInstance().destroyConnection(this); + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.USER_CANCEL_MSG)); + throw new DatabaseOperationException(IMessagesConstants.USER_CANCEL_MSG); + } + } + + /** + * Removes the. + * + * @param obj the obj + */ + public void remove(ServerObject obj) { + if (obj instanceof UserNamespace) { + getUserNamespaces().remove((UserNamespace) obj); + } else if (obj instanceof SystemNamespace) { + getSystemNamespaces().remove((SystemNamespace) obj); + } + } + + /** + * Gets the user namespaces. + * + * @return the user namespaces + */ + public UserNamespaceObjectGroup getUserNamespaces() { + return userNamespaces; + } + + /** + * Gets the system namespaces. + * + * @return the system namespaces + */ + public SystemNamespaceObjectGroup getSystemNamespaces() { + return systemNamespaces; + } + + /** + * Gets the DB type. + * + * @return the DB type + */ + public DBTYPE getDBType() { + return (DBTYPE) returnValHashMap.get(RETURNVALUES.DATABASETYPE); + } + + /** + * Checks if is cursor supported. + * + * @return true, if is cursor supported + */ + public boolean isCursorSupported() { + return (boolean) returnValHashMap.get(RETURNVALUES.SUPPORT_CURSOR); + } + + /** + * Checks if is word break special char. + * + * @param ch the ch + * @return true, if is word break special char + */ + public boolean isWordBreakSpecialChar(char ch) { + List charList = DatabaseUtils.getCharacterList(this); + + if (!charList.isEmpty() && charList.contains(ch)) { + return true; + } + return false; + } + + /** + * Checks if is supported explain plan. + * + * @return true, if is supported explain plan + */ + public boolean isSupportedExplainPlan() { + return (boolean) returnValHashMap.get(RETURNVALUES.SUPPORT_EXPLAINPLAN); + } + + /** + * Checks if is support insert returing. + * + * @return true, if is support insert returing + */ + public boolean isSupportInsertReturing() { + return (boolean) returnValHashMap.get(RETURNVALUES.SUPPORT_INSERTRETURN); + } + + /** + * Checks if is lower case. + * + * @return true, if is lower case + */ + public boolean isLowerCase() { + return (boolean) returnValHashMap.get(RETURNVALUES.LOWERCASE); + } + + /** + * Checks if is upper case. + * + * @return true, if is upper case + */ + public boolean isUpperCase() { + return (boolean) returnValHashMap.get(RETURNVALUES.UPPERCASE); + } + + /** + * Gets the search pool manager. + * + * @return the search pool manager + */ + public SearchPoolManager getSearchPoolManager() { + if (null == searchPoolManager) { + searchPoolManager = new SearchPoolManager(); + } + return searchPoolManager; + } + + /** + * Gets the connection manager. + * + * @return the connection manager + */ + public ConnectionManager getConnectionManager() { + if (null == connectionManager) { + connectionManager = new ConnectionManager(this); + } + return connectionManager; + } + + /** + * Gets the login notify manager. + * + * @return the login notify manager + */ + public LoginNotificationManager getLoginNotifyManager() { + if (null == loginNotifyManager) { + loginNotifyManager = new LoginNotificationManager(this); + } + return loginNotifyManager; + } + + /** + * Gets the search path helper. + * + * @return the search path helper + */ + public SearchPathHelper getSearchPathHelper() { + if (null == searchPathHelper) { + searchPathHelper = new SearchPathHelper(getConnectionManager()); + } + return searchPathHelper; + } + + /** + * Fetch all datatypes. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void fetchAllDatatypes() throws DatabaseCriticalException, DatabaseOperationException { + fetchQueryHelper.fetchAllDatatypes(); + } + + /** + * Connect to server. + * + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public void connectToServer() throws MPPDBIDEException { + fetchQueryHelper.connectToServer(); + } + + /** + * + * Title: class + * + * Description: The Class FetchObjHelper. + * + */ + private class FetchObjHelper { + + /** + * Fetch all datatypes. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void fetchAllDatatypes() throws DatabaseCriticalException, DatabaseOperationException { + String qry = "select typ.oid as oid, typ.typname as typname, typ.typnamespace as typnamespace, " + + "typ.typlen as typlen, pg_catalog.format_type(oid,typ.typtypmod) as displaycolumns , " + + " typ.typbyval as typbyval, typ.typtype as typtype, typ.typcategory as typcategory, " + + "typ.typtypmod as typtypmod, " + + "typ.typnotnull as typnotnull, typ.typarray as typarray, des.description as desc " + + "from pg_type typ left join pg_description des on (typ.oid = des.objoid) " + + "where typ.typnamespace in (select oid from pg_namespace where nspname in " + + "('information_schema', 'pg_catalog')) " + "order by typ.typname"; + ResultSet rs = null; + boolean hasMoreResult = false; + + try { + rs = connectionManager.execSelectAndReturnRsOnObjBrowserConn(qry); + hasMoreResult = rs.next(); + + while (hasMoreResult) { + TypeMetaData.convertToTypeMetaData(rs, Database.this, true); + hasMoreResult = rs.next(); + } + } catch (SQLException exceptionSql) { + try { + GaussUtils.handleCriticalException(exceptionSql); + } catch (DatabaseCriticalException dc) { + throw dc; + } + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), exceptionSql); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exceptionSql); + } finally { + connectionManager.closeRSOnObjBrowserConn(rs); + } + } + + /** + * Connect to server. + * + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public void connectToServer() throws MPPDBIDEException { + IServerConnectionInfo connInfo = server.getServerConnectionInfo(getDbName()); + Properties props = connInfo.composeProperty(server.getDriverName()); + + String url = connInfo.composeUrl(); + + try { + connectionManager.connectToGauss(props, url, getDBType()); + + if (null == executor) { + executor = new Executor(); + } + + if (connInfo instanceof ServerConnectionInfo) { + executor.connectToServer((ServerConnectionInfo) connInfo, connectionManager.getConnectionDriver()); + } + + } catch (MPPDBIDEException exp) { + destroy(); + throw exp; + } finally { + ServerUtil.clearPropertyDetails(props); + ServerUtil.clearConnectionInfo(connInfo); + server.clearPrds(); + + } + setConnected(true); + checkForDebugSupport(); + checkExplainPlanSupport(); + } + + private void checkExplainPlanSupport() { + String debugSupportCheckQuery = "EXPLAIN SELECT 1"; + ResultSet rs = null; + try { + rs = connectionManager.getObjBrowserConn().execSelectAndReturnRs(debugSupportCheckQuery); + if (rs.next()) { + isExplainPlanSupported = true; + } else { + isExplainPlanSupported = false; + } + } catch (DatabaseCriticalException | DatabaseOperationException | SQLException exception) { + MPPDBIDELoggerUtility.error("Failed to run explain plan query", exception); + isExplainPlanSupported = false; + } finally { + connectionManager.getObjBrowserConn().closeResultSet(rs); + } + } + + private void checkForDebugSupport() { + String debugSupportCheckQuery = "SELECT count(1) from pg_proc where proname='pldbg_attach_session';"; + ResultSet rs = null; + try { + rs = connectionManager.getObjBrowserConn().execSelectAndReturnRs(debugSupportCheckQuery); + if (rs.next()) { + int procedureCount = rs.getInt(1); + if (procedureCount > 0) { + setDebugSupported(true); + } else { + setDebugSupported(false); + } + } + } catch (DatabaseCriticalException | DatabaseOperationException | SQLException exception) { + MPPDBIDELoggerUtility.error("Failed to check debug support for the database", exception); + setDebugSupported(false); + } finally { + connectionManager.getObjBrowserConn().closeResultSet(rs); + } + } + + /** + * Rename database. + * + * @param newName the new name + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void renameDatabase(String newName) throws DatabaseOperationException, DatabaseCriticalException { + // Need to check more in order to set states here as it will be + // using other connection for renaming + String qry = String.format(Locale.ENGLISH, "ALTER DATABASE \"%s\" RENAME TO %s ;", getName(), + ServerObject.getQualifiedObjectName(newName)); + DBConnection anotherConn = null; + long oid = getOid(); + try { + anotherConn = server.getAnotherConnection(oid); + } catch (DatabaseOperationException databaseOperationException) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_RENAME_NEED_ANOTHER_CON)); + throw new DatabaseOperationException(IMessagesConstants.ERR_RENAME_NEED_ANOTHER_CON); + } + + if (isConnected) { + destroy(); + } + + anotherConn.execNonSelect(qry); + + qry = "SELECT datname FROM PG_DATABASE WHERE OID=" + oid; + dbName = anotherConn.execSelectAndGetFirstVal(qry); + server.removeFromDatabaseGroup(oid); + setName(dbName); + server.addToDatabaseGroup(Database.this); + } + + /** + * Drop database. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void dropDatabase() throws DatabaseOperationException, DatabaseCriticalException { + // Need to check more in order to set states here as it will be + // using other connection for droping + String qry = "drop database " + ServerObject.getQualifiedObjectName(getName()) + ';'; + DBConnection anotherConn = null; + try { + anotherConn = server.getAnotherConnection(getOid()); + } catch (DatabaseOperationException databaseOperationException) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_NO_CONNECTION_AVAILABLE), + databaseOperationException); + throw new DatabaseOperationException(IMessagesConstants.ERR_NO_CONNECTION_AVAILABLE); + } + + destroy(); + anotherConn.execNonSelect(qry); + server.removeDatabase(getOid()); + } + } + + /** + * Gets the sql syntax. + * + * @return the sql syntax + */ + public SQLSyntax getSqlSyntax() { + try { + IConnectionDriver connectionDriver = connectionManager.getConnectionDriver(); + return connectionDriver != null ? connectionDriver.loadSQLSyntax() : null; + } catch (DatabaseOperationException databaseOperationException) { + MPPDBIDELoggerUtility.error("error in getting driver", databaseOperationException); + return null; + } + } + + /** + * Gets the error locator. + * + * @return the error locator + */ + public IErrorLocator getErrorLocator() { + return new ErrorLocator(); + } + + /** + * Checks for support for atomic DDL. + * + * @return true, if successful + */ + public boolean hasSupportForAtomicDDL() { + return true; + } + + /** + * Gets the valid object name. + * + * @param objectName the object name + * @return the valid object name + */ + public String getValidObjectName(String objectName) { + return getQualifiedObjectName(objectName); + } + + /** + * Gets the load limit. + * + * @return the load limit + */ + public int getLoadLimit() { + return this.server.getServerConnectionInfo().getLoadLimit(); + } + + /** + * canChildObjectsLoaded loaded + * + * @return boolean value + */ + public boolean canChildObjectsLoaded() { + return this.server.getServerConnectionInfo().canLoadChildObjects(); + } + + /** + * Gets the default schema name. + * + * @param dbConnection the db connection + * @return the default schema name + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public String getDefaultSchemaName(DBConnection dbConnection) + throws DatabaseOperationException, DatabaseCriticalException { + ArrayList nameSpacearray = getNameSpaceFromSearchPath(dbConnection); + return ServerObject.getQualifiedObjectName(nameSpacearray.get(0)); + } + + /** + * Gets the name space from search path. + * + * @param connection the connection + * @return the name space from search path + */ + private ArrayList getNameSpaceFromSearchPath(DBConnection connection) { + ArrayList nameSpacearray = new ArrayList(); + String userName = this.getServer().getUserName(); + ResultSet resultSet = null; + try { + String searchQuery = MPPDBIDEConstants.SHOW_SEARCHPATH_QUERY; + resultSet = connection.execSelectAndReturnRs(searchQuery); + handleResultSet(nameSpacearray, userName, resultSet); + } catch (DatabaseOperationException | SQLException exception) { + MPPDBIDELoggerUtility.error("Exception occured while getting the namespace from search path", exception); + } catch (DatabaseCriticalException databaseCriticalException) { + MPPDBIDELoggerUtility.error("Exception occured while getting the namespace from search path", + databaseCriticalException); + } finally { + connection.closeResultSet(resultSet); + } + return nameSpacearray; + } + + private void handleResultSet(ArrayList nameSpacearray, String userName, ResultSet resultSet) + throws SQLException { + boolean hasMoreRs = false; + hasMoreRs = resultSet.next(); + if (hasMoreRs) { + String searchPathStr = resultSet.getString(1); + handleSearchString(nameSpacearray, userName, searchPathStr); + } + } + + private void handleSearchString(ArrayList nameSpacearray, String userName, String searchPathStr) { + if (searchPathStr != null) { + String[] searchPathList = searchPathStr.replace("$user", userName).split(","); + for (String str : searchPathList) { + String strTrim = str.trim(); + nameSpacearray.add(BLUtils.getUnQuotedIdentifier(strTrim, "\"")); + } + } else { + nameSpacearray.add(MPPDBIDEConstants.PUBLIC_SCHEMA_NAME); + } + } + + /** + * Find matching datatype. + * + * @param prefix the prefix + * @return the sorted map + */ + public SortedMap findMatchingDatatype(String prefix) { + SortedMap datatypes = new TreeMap(); + datatypes.putAll(defaultDatatypes.findMatching(prefix)); + if (orcDatatypes != null) { + datatypes.putAll(orcDatatypes.findMatching(prefix)); + } + return datatypes; + } + + /** + * Checks if is supported edit do not save option. + * + * @param isAtomic the is atomic + * @return true, if is supported edit do not save option + */ + public boolean isSupportedEditDoNotSaveOption(boolean isAtomic) { + return isAtomic; + } + + public boolean isDebugSupported() { + return isDebugSupported; + } + + public void setDebugSupported(boolean isDebugSupported) { + this.isDebugSupported = isDebugSupported; + } + + public boolean isExplainPlanSupported() { + return isExplainPlanSupported; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/DatabaseHelper.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/DatabaseHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..1767745eb61a7b5a07ebc50e236aebb73ca7ff41 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/DatabaseHelper.java @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class DatabaseHelper. + * + */ + +public class DatabaseHelper { + + private static final String SELECT_PRIVILEGE_QUERY = "select has_database_privilege(%s, 'CONNECT');"; + + /** + * Fetch tablespace name. + * + * @param db the db + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static void fetchTablespaceName(Database db) throws DatabaseCriticalException, DatabaseOperationException { + String query; + query = "SELECT tbs.spcname from pg_tablespace tbs, pg_database db " + + "where tbs.oid = db.dattablespace and db.datname = " + ServerObject.getLiteralName(db.getName()); + + String tblSpc = db.getConnectionManager().execSelectAndGetFirstValOnObjBrowserConn(query); + db.setDBDefaultTblSpc(tblSpc); + } + + /** + * Fetch DB oid. + * + * @param db the db + * @return the long + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static long fetchDBOid(Database db) throws DatabaseCriticalException, DatabaseOperationException { + if (0 != db.getOid()) { + return db.getOid(); + } + + String query; + query = "SELECT oid from pg_database where datname = " + ServerObject.getLiteralName(db.getName()); + + String oidStr = db.getConnectionManager().execSelectAndGetFirstValOnObjBrowserConn(query); + try { + db.setOid(Integer.parseInt(oidStr)); + } catch (NumberFormatException numberFormatException) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_EXECUTE_FUN_PROC_TRIG_QUERY_FAILED), + numberFormatException); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_EXECUTE_FUN_PROC_TRIG_QUERY_FAILED); + } + + return db.getOid(); + } + + /** + * Creates the new schema. + * + * @param schemaName the schema name + * @param db the db + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public static void createNewSchema(String schemaName, Database db) + throws DatabaseOperationException, DatabaseCriticalException { + String qry = String.format(Locale.ENGLISH, "CREATE SCHEMA %s;", + ServerObject.getQualifiedObjectName(schemaName)); + db.getConnectionManager().execNonSelectOnObjBrowserConn(qry); + NamespaceUtils.fetchAllUserNamespaces(db); + } + + /** + * Can be connected. + * + * @param db the db + * @return true, if successful + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static boolean canBeConnected(Database db) throws DatabaseCriticalException, DatabaseOperationException { + final String qry = String.format(Locale.ENGLISH, SELECT_PRIVILEGE_QUERY, + ServerObject.getLiteralName(db.getDbName())); + ResultSet rs = null; + rs = db.getConnectionManager().execSelectAndReturnRsOnObjBrowserConn(qry); + boolean flag = false; + try { + boolean hasNext = rs.next(); + if (hasNext) { + flag = rs.getBoolean(1); + } + } catch (SQLException exp) { + try { + GaussUtils.handleCriticalException(exp); + } catch (DatabaseCriticalException dc) { + throw dc; + } + throw new DatabaseOperationException(IMessagesConstants.ERR_FETCH_DATABASE_OPERATION, exp); + } finally { + db.getConnectionManager().closeRSOnObjBrowserConn(rs); + } + return flag; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/DatabaseUtils.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/DatabaseUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..8abd4e68b7072597067caef92b37a05811515252 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/DatabaseUtils.java @@ -0,0 +1,654 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.adapter.gauss.StmtExecutor; +import org.opengauss.mppdbide.bl.util.ExecTimer; +import org.opengauss.mppdbide.bl.util.IExecTimer; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.JSQLParserUtils; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.MessageQueue; + +/** + * + * Title: class + * + * Description: The Class DatabaseUtils. + * + */ + +public interface DatabaseUtils { + /** + * Serial data type oid + */ + static final int SERIAL_DATA_TYPE_OID = -1; + + /** + * Check cancel status and abort. + * + * @param cancelStatus the cancel status + * @param db the db + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + static void checkCancelStatusAndAbort(IJobCancelStatus cancelStatus, Database db) + throws DatabaseOperationException, DatabaseCriticalException { + if (cancelStatus.getCancel() && db != null) { + db.getConnectionManager().cancelAllConnectionQueries(); + DBConnProfCache.getInstance().destroyConnection(db); + + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.USER_CANCEL_MSG)); + throw new DatabaseOperationException(IMessagesConstants.USER_CANCEL_MSG); + } + } + + /** + * Gets the deadline info. + * + * @param preferenceCount the preference count + * @param db the db + * @return the deadline info + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + static String getDeadlineInfo(int preferenceCount, Database db) + throws DatabaseCriticalException, DatabaseOperationException { + String deadlineValue = null; + ResultSet rs = null; + String qry = "select intervaltonum(gs_password_deadline()) as DEADLINE;"; + + rs = db.getConnectionManager().getObjBrowserConn().execSelectToExportCSV(qry, preferenceCount); + + try { + if (rs.next()) { + deadlineValue = rs.getString("DEADLINE"); + } + } catch (SQLException exp) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exp); + } + // Next Time Transaction needs to be handled. + finally { + db.getConnectionManager().closeRSOnObjBrowserConn(rs); + } + return deadlineValue; + } + + /** + * Gets the notify info. + * + * @param preferenceCount the preference count + * @param database the db + * @return the notify info + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + static int getNotifyInfo(int preferenceCount, Database database) + throws DatabaseCriticalException, DatabaseOperationException { + int notifyValue = 0; + ResultSet resultSet = null; + String qry = "select * from gs_password_notifytime() as NOTIFYTIME;"; + resultSet = database.getConnectionManager().getObjBrowserConn().execSelectToExportCSV(qry, preferenceCount); + try { + if (resultSet.next()) { + notifyValue = resultSet.getInt("NOTIFYTIME"); + } + } catch (SQLException excp) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + excp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, excp); + } + // Next Time Transaction needs to be handled. + finally { + database.getConnectionManager().closeRSOnObjBrowserConn(resultSet); + } + return notifyValue; + } + + /** + * Gets the server encoding. + * + * @param dbconn the dbconn + * @return the server encoding + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + static String getServerEncoding(DBConnection dbconn) throws DatabaseCriticalException, DatabaseOperationException { + String encodingQry = "show server_encoding"; + ResultSet rs = dbconn.execSelectAndReturnRs(encodingQry); + try { + if (rs.next()) { + return rs.getString(1); + } + } catch (SQLException exp) { + GaussUtils.handleCriticalException(exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_STMT_EXCEPTION, exp); + } finally { + dbconn.closeResultSet(rs); + } + + return ""; + } + + /** + * Gets the character list. + * + * @param db the db + * @return the character list + */ + static List getCharacterList(Database db) { + List charList1 = new ArrayList(25); + + charList1.add('.'); + charList1.add('&'); + charList1.add('$'); + charList1.add('*'); + charList1.add('#'); + charList1.add('@'); + charList1.add('+'); + charList1.add('-'); + charList1.add('/'); + charList1.add('<'); + charList1.add('>'); + charList1.add('='); + charList1.add('~'); + charList1.add('!'); + charList1.add('%'); + charList1.add('^'); + charList1.add('|'); + charList1.add('`'); + charList1.add('?'); + charList1.add('('); + charList1.add('['); + charList1.add(','); + + return charList1; + } + + /** + * Execute on query with materializer. + * + * @param query the query + * @param fetchCount the fetch count + * @param conn the conn + * @param messageQueue the message queue + * @param materializer the materializer + * @return the object + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + static Object executeOnQueryWithMaterializer(String query, int fetchCount, DBConnection conn, + MessageQueue messageQueue, IQueryMaterializer materializer) + throws DatabaseCriticalException, DatabaseOperationException { + Connection connection = conn.getConnection(); + boolean isChanged = false; + StmtExecutor stmt = null; + boolean isSelectQuery = false; + boolean isCallableStmt = false; + + try { + if (connection.isClosed()) { + return null; + } + + // On Auto Commit ON fetch size is ignored and it will fetch all + // data at a time and may cause out of memory .So we are setting + // auto commit false for select + // queries .Auto commit will turned ON in finally block if required. + if (query.toLowerCase(Locale.ENGLISH).startsWith("select") && !JSQLParserUtils.isCopyQuery(query)) { + if (connection.getAutoCommit()) { + isSelectQuery = true; + IExecTimer timer = new ExecTimer("Pre AC False"); + timer.start(); + isChanged = true; + connection.setAutoCommit(false); + timer.stop(); + } + } + + stmt = executeQuery(query, conn, messageQueue); + + if (stmt.getCalStmt() != null) { + isCallableStmt = true; + } + + QueryResult queryResult = new QueryResult(stmt, conn, false); + if (null != materializer) { + // Better to materialize the query result before transaction + // rollback. + IExecTimer timer1 = new ExecTimer("Materilizing"); + timer1.start(); + + materializer.materializeQueryResult(queryResult, isCallableStmt); + timer1.stop(); + return materializer.getMaterializedQueryResult(); + } + + // Not expected to come here as this has a single caller. + return queryResult; + } catch (SQLException objSQL) { + handleSQLException(connection, objSQL); + + throw new DatabaseOperationException(IMessagesConstants.ERR_DATABASE_OPERATION_FAILURE, objSQL); + } finally { + executeOnQueryWithMaterializerCleanUp(connection, isChanged, stmt, isSelectQuery); + } + } + + /** + * handles the SQLException + * + * @param connection the connection + * @param objSQL the sql object + */ + static void handleSQLException(Connection connection, SQLException objSQL) { + try { + if (!connection.getAutoCommit()) { + connection.commit(); + } + } catch (SQLException objExp) { + MPPDBIDELoggerUtility.error("Database : Database operation exeception", objExp); + } + MPPDBIDELoggerUtility.error("Database : Database operation exeception", objSQL); + } + + /** + * execute the Query + * + * @param query the query + * @param conn the connection + * @param messageQueue the message queue + * @return StmtExecutor the statement executor + * @throws DatabaseCriticalException the DatabaseCriticalException + * @throws DatabaseOperationException the DatabaseOperationException + * @throws SQLException the SQLException + */ + static StmtExecutor executeQuery(String query, DBConnection conn, MessageQueue messageQueue) + throws DatabaseCriticalException, DatabaseOperationException, SQLException { + StmtExecutor stmt; + IExecTimer timer = new ExecTimer("Executing"); + timer.start(); + + stmt = new StmtExecutor(query, conn); + stmt.setFetchCount(1000); + stmt.registerNoticeListner(messageQueue); + + stmt.execute(); + timer.stop(); + return stmt; + } + + /** + * execute statement On Query With Materializer CleanUp + * + * @param connection the connection + * @param isChanged the boolean flag + * @param stmt the statement + * @param isSelectQuery the boolean flag + */ + static void executeOnQueryWithMaterializerCleanUp(Connection connection, boolean isChanged, StmtExecutor stmt, + boolean isSelectQuery) { + if (isSelectQuery) { + try { + connection.rollback(); + if (null != stmt) { + stmt.closeResultSet(); + stmt.closeStatement(); + } + if (isChanged) { + connection.setAutoCommit(true); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Database operation exeception", exception); + } + } else { + if (stmt != null) { + stmt.closeStatement(); + } + } + } + + /** + * Execute on sql terminal. + * + * @param query the query + * @param fetchCount the fetch count + * @param conn the conn + * @param messageQueue the message queue + * @return the query result + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + static QueryResult executeOnSqlTerminal(String query, int fetchCount, DBConnection conn, MessageQueue messageQueue) + throws DatabaseCriticalException, DatabaseOperationException { + Connection connection = conn.getConnection(); + boolean isChanged = false; + + try { + if (connection.isClosed()) { + return null; + } + + /* + * On Auto Commit ON fetch size is ignored and it will fetch all + * data at a time and may cause out of memory .So we are setting + * auto commit false for select queries .Auto commit will turned ON + * in finally block if required. + */ + if (query.toLowerCase(Locale.ENGLISH).startsWith("select")) { + if (connection.getAutoCommit()) { + isChanged = true; + connection.setAutoCommit(false); + } + } + StmtExecutor stmt = new StmtExecutor(query, conn); + int fetchSize = fetchCount < 1 ? 0 : fetchCount; + stmt.setFetchCount(fetchSize); + stmt.registerNoticeListner(messageQueue); + stmt.execute(); + + return new QueryResult(stmt); + + } catch (SQLException objSQL) { + try { + if (!connection.getAutoCommit()) { + connection.commit(); + } + + } catch (SQLException objExp) { + MPPDBIDELoggerUtility.error("Database operation exeception", objExp); + } + MPPDBIDELoggerUtility.error("Database operation exeception", objSQL); + + throw new DatabaseOperationException(IMessagesConstants.ERR_DATABASE_OPERATION_FAILURE, objSQL); + } finally { + if (isChanged) { + try { + connection.setAutoCommit(true); + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Database operation exeception", exception); + } + } + } + } + + /** + * Execute on sql terminal and dont return resultset + * + * @param query the query + * @param fetchCount the fetch count + * @param conn the conn + * @param messageQueue the message queue + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + static void executeOnSqlTerminalAndReturnNothing(String query, int fetchCount, DBConnection conn, + MessageQueue messageQueue) throws DatabaseCriticalException, DatabaseOperationException { + Connection connection = conn.getConnection(); + boolean isChanged = false; + StmtExecutor statement = null; + + try { + if (connection.isClosed()) { + return; + } + + /* + * On Auto Commit ON fetch size is ignored and it will fetch all + * data at a time and may cause out of memory .So we are setting + * auto commit false for select queries .Auto commit will turned ON + * in finally block if required. + */ + if (query.toLowerCase(Locale.ENGLISH).startsWith("select")) { + if (connection.getAutoCommit()) { + isChanged = true; + connection.setAutoCommit(false); + } + } + statement = new StmtExecutor(query, conn); + int fetchSize = fetchCount < 1 ? 0 : fetchCount; + statement.setFetchCount(fetchSize); + statement.registerNoticeListner(messageQueue); + statement.execute(); + } catch (SQLException objSQL) { + try { + if (!connection.getAutoCommit()) { + connection.commit(); + } + + } catch (SQLException sqlException) { + MPPDBIDELoggerUtility.error("Database operation exeception", sqlException); + } + MPPDBIDELoggerUtility.error("Database operation exeception", objSQL); + + throw new DatabaseOperationException(IMessagesConstants.ERR_DATABASE_OPERATION_FAILURE, objSQL); + } finally { + if (isChanged) { + try { + connection.setAutoCommit(true); + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Database operation exeception", exception); + } + } + if (null != statement) { + statement.closeResultSet(); + statement.closeStatement(); + } + } + } + + /** + * Gets the notif data from RS. + * + * @param rs the rs + * @return the notif data from RS + * @throws SQLException the SQL exception + */ + static NotificationData getNotifDataFromRS(ResultSet rs) throws SQLException { + NotificationData notifData; + notifData = new NotificationData(); + + Timestamp timestamp = rs.getTimestamp(1); + if (timestamp != null) { + String time = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(timestamp); + notifData.setTime(time); + String client = rs.getString(2); + notifData.setClientInfo(client); + } + return notifData; + } + + /** + * Check exception for no R sor no access. + * + * @param hasNext the has next + * @param privilegeFlag the privilege flag + * @throws DatabaseOperationException the database operation exception + */ + static void checkExceptionForNoRSorNoAccess(boolean hasNext, boolean privilegeFlag) + throws DatabaseOperationException { + if (!hasNext) { + if (privilegeFlag) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DENIED_ACCESS_PRIVILEGE)); + throw new DatabaseOperationException(IMessagesConstants.ERR_DENIED_ACCESS_PRIVILEGE); + } else { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.MSG_GUI_OBJECT_MAY_DROPPED)); + throw new DatabaseOperationException(IMessagesConstants.MSG_GUI_OBJECT_MAY_DROPPED); + } + } + } + + /** + * Check exception for no access no renameflow. + * + * @param isRenameFlow the is rename flow + * @param privilegeFlag the privilege flag + * @throws DatabaseOperationException the database operation exception + */ + static void checkExceptionForNoAccessNoRenameflow(boolean isRenameFlow, boolean privilegeFlag) + throws DatabaseOperationException { + if (privilegeFlag) { + if (!isRenameFlow) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DENIED_ACCESS_PRIVILEGE)); + throw new DatabaseOperationException(IMessagesConstants.ERR_DENIED_ACCESS_PRIVILEGE); + } + } else { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.MSG_GUI_OBJECT_MAY_DROPPED)); + throw new DatabaseOperationException(IMessagesConstants.MSG_GUI_OBJECT_MAY_DROPPED); + } + } + + /** + * Gets the ORC data types to be displayed. + * + * @return the ORC data types to be displayed + */ + static String[][] getORCDataTypesToBeDisplayed() { + String[][] orcDataTypes = {{"char", "char"}, {"char", "character"}, {"char", "nchar"}, {"varchar", "varchar"}, + {"varchar", "character varying"}, {"nvarchar2", null}, {"varchar2(n)", null}, {"clob", null}, + {"text", null}, {"int1", "tinyint"}, {"int2", "smallint"}, {"int4", "int"}, {"int8", "bigint"}, + {"date", null}, {"money", null}, {"numeric", null}, {"numeric", "decimal"}, {"float8", "double precision"}, + {"float4", "real"}, {"float", "binary double"}, {"float4", null}, {"float8", null}, {"interval", null}, + {"time", "time without time zone"}, {"timestamp", "timestamp without time zone"}, {"bool", null}, + {"timetz", "time with time zone"}, {"timestamptz", "timestamp with time zone"}, {"smalldatetime", null}, + {"oid", null}}; + return orcDataTypes; + } + + /** + * Gets the default datatype list. + * + * @return the default datatype list + */ + static String[][] getdefaultDatatypeList() { + String[][] defaultDatatype = {{"char", null}, {"varchar", null}, {"text", null}, {"int4", "integer"}, + {"int2", "smallint"}, {"int8", "bigint"}, {"date", null}, {"money", null}, {"numeric", null}, + {"numeric", "decimal"}, {"float8", "double precision"}, {"float4", "real"}, {"interval", null}, + {"time", "time without time zone"}, {"timestamp", "timestamp without time zone"}, {"bool", "boolean"}, + {"bit", null}, {"box", null}, {"bytea", null}, {"cidr", null}, {"circle", null}, {"inet", null}, + {"lseg", null}, {"macaddr", null}, {"path", null}, {"point", null}, {"polygon", null}, + {"timetz", "time with time zone"}, {"timestamptz", "timestamp with time zone"}, {"tsquery", null}, + {"tsvector", null}, {"txid_snapshot", null}, {"uuid", null}, {"varbit", null}, {"xml", null}, + {"clob", null}, {"blob", null}}; + return defaultDatatype; + } + + /** + * Gets the serial datatype list. + * + * @return String[] the serial datatype list + */ + static String[] getSerialDatatypeList() { + String[] serialDatatype = {"smallserial", "serial", "bigserial"}; + return serialDatatype; + } + + /** + * Gets the all DB list in server. + * + * @param db the db + * @return the all DB list in server + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + static ArrayList getAllDBListInServer(Database db) + throws DatabaseCriticalException, DatabaseOperationException { + int oid = 0; + String name = null; + Database newDb = null; + ArrayList dbList = new ArrayList(4); + String qry = "select oid, datname from pg_database where datistemplate='f'"; + if (db.getPrivilegeFlag()) { + qry += " and has_database_privilege(datname, 'CONNECT')"; + } + qry += " order by datname;"; + + ResultSet rs = null; + try { + rs = db.getConnectionManager().execSelectAndReturnRsOnObjBrowserConn(qry); + boolean hasNext = rs.next(); + while (hasNext) { + oid = rs.getInt(1); + name = rs.getString(2); + + newDb = new Database(db.getServer(), oid, name); + newDb.setOid(oid); + + dbList.add(newDb); + hasNext = rs.next(); + } + } catch (SQLException exp) { + try { + GaussUtils.handleCriticalException(exp); + } catch (DatabaseCriticalException dc) { + throw dc; + } + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_FETCH_DATABASE_OPERATION), exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_FETCH_DATABASE_OPERATION, exp); + } finally { + db.getConnectionManager().closeRSOnObjBrowserConn(rs); + } + + return dbList; + } + + /** + * Gets the debug objects. + * + * @param db the db + * @param debugObjectId the debug object id + * @return the debug objects + */ + static DebugObjects getDebugObjects(Database db, long debugObjectId) { + IDebugObject obj = null; + ArrayList namespaceSortedList = db.getAllNameSpaces(); + + Iterator itrNamespace = namespaceSortedList.iterator(); + boolean hasMoreElements = itrNamespace.hasNext(); + Namespace namespace = null; + while (hasMoreElements) { + namespace = itrNamespace.next(); + obj = namespace.getDebugObjectById(debugObjectId); + if (null != obj) { + return (DebugObjects) obj; + } + hasMoreElements = itrNamespace.hasNext(); + } + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/DebugObjects.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/DebugObjects.java new file mode 100644 index 0000000000000000000000000000000000000000..b32769dd9fb27ad0b6ad34e2435683253da0e47a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/DebugObjects.java @@ -0,0 +1,1311 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussDatatypeUtils; +import org.opengauss.mppdbide.bl.export.EXPORTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.DebugObjects.DebugObjectsUtils.GenerateExecutionTemplateParameter; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.IMessagesConstantsOne; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.ILogger; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class DebugObjects. + * + */ + +public class DebugObjects extends BatchDropServerObject implements ObjectChange, GaussOLAPDBMSObject, IDebugObject { + private boolean isDebugable; + private String executeTemplate; + private String executionQuery; + private OBJECTTYPE objectType; + + private ISourceCode sourceCode; + private ObjectParameter[] parameters; + private ArrayList templateParameters; + private ArrayList outParameters; + private ObjectParameter returnType; + private Database db; + private String usageHint; + private Namespace namespace; + private String lang; + + private boolean isSourceLoaded; + private boolean isCodeReloaded; + + private boolean isCurrentTerminal = false; + private boolean isEditTerminalInputValues = false; + + /** + * Instantiates a new debug objects. + */ + public DebugObjects() { + super(OBJECTTYPE.PLSQLFUNCTION); + this.isSourceLoaded = false; + } + + /** + * Gets the usagehint. + * + * @return the usagehint + */ + public String getUsagehint() { + return usageHint; + } + + /** + * Sets the usagehint. + * + * @param usagehint the new usagehint + */ + public void setUsagehint(String usagehint) { + this.usageHint = usagehint; + } + + /** + * Instantiates a new debug objects. + * + * @param id the id + * @param name the name + * @param type the type + * @param db the db + */ + public DebugObjects(long id, String name, OBJECTTYPE type, Database db) { + super(id, name, type, db != null ? db.getPrivilegeFlag() : true); + this.objectType = type; + this.sourceCode = new SourceCode(); + this.db = db; + } + + /** + * Sets the database. + * + * @param db1 the new database + */ + public void setDatabase(Database db1) { + this.db = db1; + } + + /** + * Is the current object debuggable. + * + * @return true, if is debuggable + */ + public boolean isDebuggable() { + return isDebugable; + } + + /** + * Sets the checks if is debuggable. + * + * @param isDebuggable the new checks if is debuggable + */ + public void setIsDebuggable(boolean isDebuggable) { + this.isDebugable = isDebuggable; + } + + /** + * Get type of current debug object. + * + * @return the object type + */ + public OBJECTTYPE getObjectType() { + return objectType; + } + + /** + * Get Execution template for this debug object. + * + * @return the execute template + */ + public String getExecuteTemplate() { + return executeTemplate; + } + + /** + * Get Execution query summary. + * + * @return the string + * @throws DatabaseOperationException the database operation exception + */ + public String prepareExecutionQueryString() throws DatabaseOperationException { + return DebugObjectsUtils.prepareExecutionQueryString(this); + } + + /** + * Sets the execute template. + * + * @param executeTemplate the new execute template + */ + public void setExecuteTemplate(String executeTemplate) { + this.executeTemplate = executeTemplate; + } + + /** + * Set source code object for current debug object. + * + * @param sourceCode the new source code + */ + public void setSourceCode(ISourceCode sourceCode) { + this.sourceCode = sourceCode; + isSourceLoaded = true; + } + + /** + * Get source code object for current debug objects. + * + * @return the source code + */ + public ISourceCode getSourceCode() { + return this.sourceCode; + } + + @Override + public String getSearchName() { + return getDisplayNameWithArgName() + " - " + getNamespace().getName() + " - " + getTypeLabel(); + } + + /** + * Sets the object parameters. + * + * @param parmeters the new object parameters + */ + public void setObjectParameters(ObjectParameter[] parmeters) { + this.parameters = parmeters; + } + + /** + * Gets the object parameters. + * + * @return the object parameters + */ + public ObjectParameter[] getObjectParameters() { + return parameters; + } + + /** + * Gets the template parameters. + * + * @return the templateParameters + */ + public ArrayList getTemplateParameters() { + return templateParameters; + } + + /** + * sets out parameter list + * + * @param outParams the out param list + */ + public void setOutParameters(ArrayList outParams) { + this.outParameters = outParams; + } + + /** + * gets out parameter list + */ + public ArrayList getOutParameters() { + return outParameters; + } + + /** + * Sets the template parameters. + * + * @param templateParameters the templateParameters to set + */ + public void setTemplateParameters(ArrayList templateParameters) { + this.templateParameters = templateParameters; + } + + /** + * Clear template parameter values. + */ + public void clearTemplateParameterValues() { + if (templateParameters != null) { + int size = templateParameters.size(); + clearParameterValue(size); + } + } + + private void clearParameterValue(int size) { + for (int count = 0; count < size; count++) { + templateParameters.get(count).clearValue(); + } + } + + /** + * Sets the object returns. + * + * @param retType the new object returns + */ + public void setObjectReturns(ObjectParameter retType) { + this.returnType = retType; + } + + /** + * Gets the display name. + * + * @param isAutoSuggest the is auto suggest + * @return the display name + */ + public String getDisplayName(boolean isAutoSuggest) { + return DebugObjectsUtils.getDisplayName(isAutoSuggest, getObjectParameters(), getReturnType(), getName(), + super.getDisplayName()); + } + + /** + * Gets the grant revoke name. + * + * @return the grant revoke name + */ + public String getGrantRevokeName() { + StringBuilder grantRevokeName = new StringBuilder(getQualifiedObjectName()); + grantRevokeName.append("("); + + if (null != parameters) { + int paramLen = parameters.length; + appendGrantRevokeName(grantRevokeName, paramLen); + } + + grantRevokeName.append(")"); + return grantRevokeName.toString(); + } + + private void appendGrantRevokeName(StringBuilder grantRevokeName, int paramLen) { + boolean isFirstParam = true; + for (int index = 0; index < paramLen; index++) { + appendComma(isFirstParam, grantRevokeName); + grantRevokeName.append(parameters[index].getType()).append(" ").append(parameters[index].getDataType()); + isFirstParam = false; + } + } + + private void appendComma(boolean isFirstParam, StringBuilder grantRevokeName) { + if (!isFirstParam) { + grantRevokeName.append(", "); + } + } + + /** + * Gets the display name. + * + * @return the display name + */ + public String getDisplayName() { + return getNamespace().getDisplayName() + '.' + super.getDisplayName(); + } + + /** + * Gets the display name with arg name. + * + * @return the display name with arg name + */ + public String getDisplayNameWithArgName() { + return getDisplayName(false); + } + + @Override + public String getWindowTitleName() { + return getDisplayNameWithArgName(); + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + return db; + } + + /** + * Gets the execution query. + * + * @return the execution query + */ + public String getExecutionQuery() { + return executionQuery; + } + + /** + * Sets the execution query. + * + * @param executionQuery the new execution query + */ + public void setExecutionQuery(String executionQuery) { + this.executionQuery = executionQuery; + } + + /** + * Gets the namespace. + * + * @return the namespace + */ + public Namespace getNamespace() { + return this.namespace; + } + + /** + * Sets the namespace. + * + * @param ns the new namespace + */ + public void setNamespace(INamespace ns) { + this.namespace = (Namespace) ns; + this.privilegeFlag = this.namespace.getPrivilegeFlag(); + } + + /** + * Gets the name space id. + * + * @return the name space id + */ + public long getNameSpaceId() { + return this.namespace.getOid(); + } + + /** + * Gets the name space name. + * + * @return the name space name + */ + public String getDbgNameSpaceName() { + return this.namespace.getName(); + } + + /** + * Gets the return type. + * + * @return the return type + */ + public ObjectParameter getReturnType() { + return returnType; + } + + /** + * Refresh source code. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void refreshSourceCode() throws DatabaseOperationException, DatabaseCriticalException { + String funcDefinitionQuery = String.format(Locale.ENGLISH, + "select headerlines, definition from PG_GET_FUNCTIONDEF(%d);", getOid()); + + addSourceCode(); + + if (this.getConnectionManager() != null) { + DBConnection objBrowserConn = this.getConnectionManager().getObjBrowserConn(); + handleNullBrowserConnection(objBrowserConn); + ResultSet funcDefinitionQueryRS = objBrowserConn.execSelectAndReturnRs(funcDefinitionQuery); + handleFuncVersionQryResultSet(objBrowserConn, funcDefinitionQueryRS); + } + } + + private void addSourceCode() { + if (null == this.sourceCode) { + this.sourceCode = new SourceCode(); + } + } + + private void handleFuncVersionQryResultSet(DBConnection objBrowserConn, ResultSet funcDefinitionQueryRS) + throws DatabaseOperationException { + ResultSet funcVersionQueryRS = execFunVersionQuery(objBrowserConn); + addFuncDefQuery(funcDefinitionQueryRS, funcVersionQueryRS); + } + + private ResultSet execFunVersionQuery(DBConnection objBrowserConn) { + String funcVersionQuery = String.format(Locale.ENGLISH, "select xmin1, cmin1 from pldbg_get_funcVer( %d)", + getOid()); + ResultSet funcVersionQueryRS = null; + try { + funcVersionQueryRS = objBrowserConn.execSelectAndReturnRs(funcVersionQuery); + } catch (DatabaseCriticalException | DatabaseOperationException exp) { + MPPDBIDELoggerUtility.error("DEBUG not enabled"); + } + return funcVersionQueryRS; + } + + private void addFuncDefQuery(ResultSet funcDefinitionQueryRS, ResultSet funcVersionQueryRS) + throws DatabaseOperationException { + try { + handleFuncDefQueryRS(funcDefinitionQueryRS, funcVersionQueryRS); + } catch (SQLException e) { + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } finally { + this.getConnectionManager().closeRSOnObjBrowserConn(funcDefinitionQueryRS); + this.getConnectionManager().closeRSOnObjBrowserConn(funcVersionQueryRS); + } + } + + private void handleNullBrowserConnection(DBConnection objBrowserConn) throws DatabaseCriticalException { + if (objBrowserConn == null) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_WHILE_FUNCTION_REFRESH)); + throw new DatabaseCriticalException(IMessagesConstants.ERR_WHILE_FUNCTION_REFRESH); + } + } + + private void handleFuncDefQueryRS(ResultSet funcDefinitionQueryRS, ResultSet funcVersionQueryRS) + throws SQLException, DatabaseOperationException { + handleFuncDefErrorCase(funcDefinitionQueryRS, funcVersionQueryRS); + if (this.sourceCode instanceof SourceCode) { + SourceCode srcCde = ((SourceCode) this.sourceCode); + srcCde.updateCode(funcDefinitionQueryRS); + srcCde.updateVersionNumber(funcVersionQueryRS); + this.isSourceLoaded = true; + } + } + + private void handleFuncDefErrorCase(ResultSet funcDefinitionQueryRS, ResultSet funcVersionQueryRS) + throws SQLException, DatabaseOperationException { + validateFunctionDefQuery(funcDefinitionQueryRS); + validateFunVersionQuery(funcVersionQueryRS); + } + + private void validateFunVersionQuery(ResultSet funcVersionQueryRS) throws SQLException, DatabaseOperationException { + if (validateFuncVersionQueryRS(funcVersionQueryRS)) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_SOURCE_NOT_AVAILABLE)); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_SOURCE_NOT_AVAILABLE); + } + } + + private void validateFunctionDefQuery(ResultSet funcDefinitionQueryRS) + throws SQLException, DatabaseOperationException { + if (!funcDefinitionQueryRS.next()) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_SOURCE_NOT_AVAILABLE)); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_SOURCE_NOT_AVAILABLE); + } + } + + private boolean validateFuncVersionQueryRS(ResultSet funcVersionQueryRS) throws SQLException { + return null != funcVersionQueryRS && !funcVersionQueryRS.next(); + } + + /** + * Generate drop query. + * + * @return the string + */ + public String generateDropQuery() { + boolean cascade = false; + if (returnType != null && "trigger".equalsIgnoreCase(returnType.getDataType())) { + cascade = true; + } + return DebugObjectsUtils.getDropQuery(DebugObjectsUtils.getDropFuncStatement(false), cascade, namespace, + parameters, getName()); + } + + /** + * + * Title: interface + * + * Description: The Interface DebugObjectsUtils. + * + */ + public static interface DebugObjectsUtils { + + static final String DROP_FUNC = "DROP FUNCTION "; + static final String IF_EXISTS = "IF EXISTS "; + + /** + * Convert to object. + * + * @param rs the rs + * @param database the database + * @return the debug objects + * @throws DatabaseOperationException the database operation exception + */ + public static DebugObjects convertToObject(ResultSet rs, Database database) throws DatabaseOperationException { + DebugObjects dbgObj = null; + int procid = 0; + String procname = null; + int rettype = 0; + String argtmodes = null; + String argtypes = null; + String argnames = null; + String lang = null; + boolean allin = false; + OBJECTTYPE objtyp = null; + int nargs = 0; + int namespaceOid = 0; + + try { + procid = rs.getInt("oid"); + procname = rs.getString("objname"); + rettype = rs.getInt("ret"); + argtypes = rs.getString("alltype"); + namespaceOid = rs.getInt("namespace"); + boolean retset = rs.getBoolean("retset"); + if (null == argtypes || retset) { + argtypes = null; + allin = true; + + nargs = rs.getInt("nargs"); + + if (nargs != 0) { + argtypes = rs.getString("argtype"); + } + } + + argnames = rs.getString("argname"); + argtmodes = rs.getString("argmod"); + + lang = rs.getString("lang"); + + if (null == procname) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID)); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } + + } catch (SQLException exp) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exp); + } + objtyp = setDebugObjectType(lang); + + dbgObj = getNewDebugObject(database, procid, procname, rettype, argtmodes, argtypes, argnames, lang, allin, + objtyp, namespaceOid); + return dbgObj; + } + + /** + * Gets the new debug object. + * + * @param database the database + * @param procid the procid + * @param procname the procname + * @param rettype the rettype + * @param argtmodes the argtmodes + * @param argtypes the argtypes + * @param argnames the argnames + * @param lang the lang + * @param allin the allin + * @param objtyp the objtyp + * @param namespaceOid the namespace oid + * @return the new debug object + * @throws DatabaseOperationException the database operation exception + */ + public static DebugObjects getNewDebugObject(Database database, int procid, String procname, int rettype, + String argtmodes, String argtypes, String argnames, String lang, boolean allin, OBJECTTYPE objtyp, + int namespaceOid) throws DatabaseOperationException { + DebugObjects dbgObj; + Namespace ns = null; + ArrayList nsList = new ArrayList<>(); + addPgCatalogNameSpaceToList(database, nsList); + + addInformationSchemaToList(database, nsList); + + dbgObj = setDebugObjParameters(database, procid, procname, argtmodes, argtypes, argnames, allin, objtyp, + nsList); + + setPlSqlReturnType(dbgObj, rettype, nsList); + setIsDebuggable(dbgObj, lang); + + ns = database.getNameSpaceById(namespaceOid); + dbgObj.setNamespace(ns); + dbgObj.setLanguage(lang); + + ns.addDebugObjectToSearchPool(dbgObj); + return dbgObj; + } + + /** + * Sets the pl sql return type. + * + * @param dbgObj the dbg obj + * @param rettype the rettype + * @param nsList the ns list + */ + public static void setPlSqlReturnType(DebugObjects dbgObj, int rettype, ArrayList nsList) { + ObjectParameter proret; + proret = new ObjectParameter(getDataTypeName(rettype, nsList), GaussDatatypeUtils.isSupported(rettype)); + + dbgObj.setObjectReturns(proret); + } + + /** + * Sets the debug obj parameters. + * + * @param database the database + * @param procid the procid + * @param procname the procname + * @param argtmodes the argtmodes + * @param argtypes the argtypes + * @param argnames the argnames + * @param allin the allin + * @param objtyp the objtyp + * @param nsList the ns list + * @return the debug objects + */ + public static DebugObjects setDebugObjParameters(Database database, int procid, String procname, + String argtmodes, String argtypes, String argnames, boolean allin, OBJECTTYPE objtyp, + ArrayList nsList) { + DebugObjects dbgObj; + ObjectParameter[] args; + args = ObjectParameter.getVariables(argtypes, argnames, argtmodes, allin, nsList); + dbgObj = new DebugObjects(procid, procname, objtyp, database); + dbgObj.setObjectParameters(args); + return dbgObj; + } + + /** + * Sets the debug object type. + * + * @param lang the lang + * @return the objecttype + */ + public static OBJECTTYPE setDebugObjectType(String lang) { + OBJECTTYPE objtyp = null; + if (IMessagesConstantsOne.PLPGSQL.equalsIgnoreCase(lang)) { + objtyp = OBJECTTYPE.PLSQLFUNCTION; + } else if (IMessagesConstantsOne.SQL.equalsIgnoreCase(lang)) { + objtyp = OBJECTTYPE.SQLFUNCTION; + } else if (IMessagesConstantsOne.C_FUN.equalsIgnoreCase(lang)) { + objtyp = OBJECTTYPE.CFUNCTION; + } + return objtyp; + } + + /** + * Sets the is debuggable. + * + * @param dbgObj the dbg obj + * @param lang the lang + */ + public static void setIsDebuggable(DebugObjects dbgObj, String lang) { + if (IMessagesConstantsOne.PLPGSQL.equalsIgnoreCase(lang)) { + dbgObj.setIsDebuggable(true); + + } else { + dbgObj.setIsDebuggable(false); + } + } + + /** + * Adds the information schema to list. + * + * @param database the database + * @param nsList the ns list + */ + public static void addInformationSchemaToList(Database database, ArrayList nsList) { + Namespace ns; + try { + INamespace nameSpaceByName = database.getNameSpaceByName("information_schema"); + if (nameSpaceByName instanceof Namespace) { + ns = (Namespace) nameSpaceByName; + nsList.add(ns); + } + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("DebugObjects: converting objects failed.", exception); + } + } + + /** + * Adds the pg catalog name space to list. + * + * @param database the database + * @param nsList the ns list + */ + public static void addPgCatalogNameSpaceToList(Database database, ArrayList nsList) { + Namespace ns; + try { + INamespace nameSpaceByName = database.getNameSpaceByName("pg_catalog"); + if (nameSpaceByName instanceof Namespace) { + ns = (Namespace) nameSpaceByName; + nsList.add(ns); + } + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("DebugObjects: converting objects failed.", exception); + } + } + + /** + * Prepare execution query string. + * + * @param debugObjects the debug objects + * @return the string + * @throws DatabaseOperationException the database operation exception + */ + public static String prepareExecutionQueryString(DebugObjects debugObjects) throws DatabaseOperationException { + debugObjects.getDatabase().getExecutor().getQueryExectuionString(debugObjects); + + return debugObjects.getExecutionQuery(); + } + + /** + * Gets the display name. + * + * @param isAutoSuggest the is auto suggest + * @param parameters the parameters + * @param returnType the return type + * @param dbgObjName the dbg obj name + * @param parentName the parent name + * @return the display name + */ + public static String getDisplayName(boolean isAutoSuggest, ObjectParameter[] parameters, + ObjectParameter returnType, String dbgObjName, String parentName) { + boolean isFirstParam = true; + String name = isAutoSuggest ? parentName : dbgObjName; + StringBuilder displayName = new StringBuilder(name); + + displayName.append("("); + + if (null != parameters) { + + int paramLen = parameters.length; + for (int index = 0; index < paramLen; index++) { + if (!isFirstParam) { + displayName.append(", "); + } + + displayName.append(parameters[index].getDisplayName(isAutoSuggest)); + + isFirstParam = false; + } + } + + displayName.append(")"); + if (!isAutoSuggest) { + if (null != returnType) { + displayName.append(" - ").append(returnType.getDataType()); + } + } + + return displayName.toString(); + } + + static class GenerateExecutionTemplateParameter { + private ArrayList templateParams; + private ArrayList output; + private ArrayList outParams; + + public GenerateExecutionTemplateParameter(ArrayList templateParams, + ArrayList output, ArrayList outParams) { + this.templateParams = templateParams; + this.output = output; + this.outParams = outParams; + } + + public ArrayList getTemplateParams() { + return templateParams; + } + + public void setTemplateParams(ArrayList templateParams) { + this.templateParams = templateParams; + } + + public ArrayList getOutput() { + return output; + } + + public void setOutput(ArrayList output) { + this.output = output; + } + + public ArrayList getOutParams() { + return outParams; + } + + public void setOutParams(ArrayList outParams) { + this.outParams = outParams; + } + } + + /** + * Generate execution template. + * + * @param namespace the namespace + * @param dbgObjName the dbg obj name + * @param params the params + * @param parameterObject the parameter object + * @throws DatabaseOperationException the database operation exception + */ + public static void generateExecutionTemplate(Namespace namespace, String dbgObjName, ObjectParameter[] params, + GenerateExecutionTemplateParameter parameterObject) throws DatabaseOperationException { + boolean hasout = false; + StringBuilder template = new StringBuilder("SELECT"); + StringBuilder usagehint = new StringBuilder(""); + + template.append(" "); + if (namespace != null) { + template.append("\"" + namespace.getName() + "\"").append("."); + } + template.append(ServerObject.getQualifiedObjectName(dbgObjName)); + template.append(MPPDBIDEConstants.LINE_SEPARATOR).append("("); + template.append(MPPDBIDEConstants.LINE_SEPARATOR); + + hasout = createTemplateFromParams(params, parameterObject.getTemplateParams(), template, + parameterObject.getOutParams()); + + if (hasout) { + usagehint.append(MessageConfigLoader.getProperty(IMessagesConstants.EXEC_DEBUG_DIALOG_OUT_PARA_MSG) + + MPPDBIDEConstants.LINE_SEPARATOR); + } + + parameterObject.getOutput().add(template.toString()); + parameterObject.getOutput().add(usagehint.toString()); + } + + /** + * creates the TemplateFromParams + * + * @param params the params + * @param templateParams the templateParams + * @param template the template + * @param outParams the outParams + * @return return true, if is success + * @throws DatabaseOperationException the DatabaseOperationException + */ + public static boolean createTemplateFromParams(ObjectParameter[] params, + ArrayList templateParams, StringBuilder template, + ArrayList outParams) throws DatabaseOperationException { + boolean isFirstParam = true; + boolean hasout = false; + if (null != params) { + + ObjectParameter param = null; + int paramSize = params.length; + + for (int paramIndex = 0; paramIndex < paramSize; paramIndex++) { + param = params[paramIndex]; + + switch (param.getType()) { + case IN: + case INOUT: { + appendInoutParameter(templateParams, template, isFirstParam, param, paramSize, paramIndex); + break; + } + case OUT: { + DefaultParameter defualtParams = changeIntoDefault(param); + outParams.add(defualtParams); + hasout = true; + break; + } + default: { + break; + } + } + isFirstParam = false; + } + } + template.append(MPPDBIDEConstants.LINE_SEPARATOR); + template.append(")"); + template.append(MPPDBIDEConstants.LINE_SEPARATOR); + return hasout; + } + + /** + * changes object parameter into default parameter + * + * @param param the object parameter + * @return the default parameter + */ + static DefaultParameter changeIntoDefault(ObjectParameter param) { + DefaultParameter defaultParam = new DefaultParameter(param.getName(), param.getDataType(), param.getValue(), + param.getType()); + return defaultParam; + } + + /** + * Append inout parameter. + * + * @param templateParams the template params + * @param template the template + * @param isFirstParam the is first param + * @param param the param + * @param paramSize the param size + * @param paramIndex the param index + * @throws DatabaseOperationException the database operation exception + */ + public static void appendInoutParameter(ArrayList templateParams, StringBuilder template, + boolean isFirstParam, ObjectParameter param, int paramSize, int paramIndex) + throws DatabaseOperationException { + String argType; + String argName; + if (!isFirstParam) { + template.append(MPPDBIDEConstants.LINE_SEPARATOR); + } + + argType = param.getDataType(); + argName = param.getName(); + if (null != argType) { + if ("refcursor".equals(argType)) { + MPPDBIDELoggerUtility.error(MessageConfigLoader + .getProperty(IMessagesConstants.ERR_BL_REFCUR_EXECUTION_TEMPLATE_FAILURE)); + throw new DatabaseOperationException(IMessagesConstants.ERR_BL_REFCUR_EXECUTION_TEMPLATE_FAILURE); + } else { + template.append("\t"); + template.append(argType); + if (paramIndex < paramSize - 1) { + template.append(" ,"); + } + template.append(" --"); + template.append(argName); + template.append(" "); + template.append(argType); + } + } + + templateParams.add(param); + } + + /** + * Gets the data type name. + * + * @param rettype the rettype + * @param nsList the ns list + * @return the data type name + */ + static String getDataTypeName(int rettype, ArrayList nsList) { + String convertedDataType = GaussDatatypeUtils.convertToClientType(rettype); + if (null == convertedDataType) { + convertedDataType = TypeMetaDataUtil.getDataTypeFromNamespace(rettype, nsList); + } + + return convertedDataType; + } + + /** + * Gets the drop func statement. + * + * @param ifExists the if exists + * @return the drop func statement + */ + public static String getDropFuncStatement(boolean ifExists) { + return DROP_FUNC + (ifExists ? IF_EXISTS : ""); + } + + /** + * Gets the drop query. + * + * @param dropStatement the drop statement + * @param isCascade the is cascade + * @param namespace the namespace + * @param parameters the parameters + * @param dbgObjName the dbg obj name + * @return the drop query + */ + public static String getDropQuery(String dropStatement, boolean isCascade, Namespace namespace, + ObjectParameter[] parameters, String dbgObjName) { + StringBuilder qry = new StringBuilder(dropStatement); + if (namespace != null) { + qry.append(namespace.getQualifiedObjectName()).append("."); + } + + qry.append(ServerObject.getQualifiedObjectName(dbgObjName)).append("("); + + if (null != parameters) { + + for (int index = 0; index < parameters.length; index++) { + qry.append(parameters[index].updateQuery()); + + if (index < (parameters.length - 1)) { + qry.append(","); + } + } + } + + qry.append(")"); + + if (isCascade) { + qry.append(MPPDBIDEConstants.CASCADE); + } + + return qry.toString(); + } + + /** + * Refresh db object. + * + * @param debugObjects the debug objects + * @return the i debug object + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public static IDebugObject refreshDbObject(DebugObjects debugObjects) throws MPPDBIDEException { + return debugObjects.getParent().refreshDbObject(debugObjects); + } + + } + + /** + * Sets the language. + * + * @param language the new language + */ + private void setLanguage(String language) { + this.lang = language; + } + + /** + * Gets the lang. + * + * @return the lang + */ + public String getLang() { + return lang; + } + + /** + * Generate execution template. + * + * @throws DatabaseOperationException the database operation exception + */ + public void generateExecutionTemplate() throws DatabaseOperationException { + ArrayList templateParams = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + ArrayList outParams = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + ArrayList output = new ArrayList(2); + DebugObjectsUtils.generateExecutionTemplate(namespace, getName(), getObjectParameters(), + new GenerateExecutionTemplateParameter(templateParams, output, outParams)); + setTemplateParameters(templateParams); + setOutParameters(outParams); + setExecuteTemplate(output.get(0)); + setUsagehint(output.get(1)); + } + + /** + * Gets the latest souce code. + * + * @return the latest souce code + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public ISourceCode getLatestSouceCode() throws DatabaseOperationException, DatabaseCriticalException { + if (!this.isSourceLoaded) { + MPPDBIDELoggerUtility.perf(MPPDBIDEConstants.GUI, ILogger.PERF_FETCH_SRC_CODE, true); + try { + refreshSourceCode(); + } finally { + MPPDBIDELoggerUtility.perf(MPPDBIDEConstants.GUI, ILogger.PERF_FETCH_SRC_CODE, false); + } + } + return getSourceCode(); + } + + /** + * Belongs to. + * + * @param database the database + * @param server the server + * @return true, if successful + */ + public boolean belongsTo(Database database, Server server) { + // un-attached debug obj + if (this.getNamespace() == null) { + return false; + } + return this.getNamespace().belongsTo(database, server); + } + + /** + * Can support debug. + * + * @return canSupportDebug + */ + public boolean canSupportDebug() { + if (IMessagesConstantsOne.PLPGSQL.equalsIgnoreCase(getLang())) { + return true; + } + + return false; + } + + @Override + public String getObjectBrowserLabel() { + return getDisplayName(false); + } + + @Override + public Namespace getParent() { + return this.namespace; + } + + /** + * Gets the PL source editor elm id. + * + * @return the PL source editor elm id + */ + public String getPLSourceEditorElmId() { + String sourceEditorElmId = String.valueOf(this.getOid()) + .concat(this.getDatabase().getName() + '@' + this.getDatabase().getServerName() + this.objectType); + return sourceEditorElmId; + } + + /** + * Gets the PL source editor elm tooltip. + * + * @return the PL source editor elm tooltip + */ + public String getPLSourceEditorElmTooltip() { + String sourceEditorElmTooltip = this.getDatabase().getServerName() + " : " + this.getDatabase().getName() + + " : " + this.getNamespace().getName() + " : " + this.getDisplayNameWithArgName(); + return sourceEditorElmTooltip; + } + + @Override + public String getDropQuery(boolean isCascade) { + return DebugObjectsUtils.getDropQuery(DebugObjectsUtils.getDropFuncStatement(true), isCascade, namespace, + parameters, getName()); + } + + @Override + public boolean isExportAllowed(EXPORTTYPE exportType) { + if (exportType == EXPORTTYPE.SQL_DDL) { + return true; + } + return false; + } + + @Override + public boolean isChanged(String latCode) throws DatabaseCriticalException, DatabaseOperationException { + return ((SourceCode) this.sourceCode).isChanged(latCode); + } + + @Override + public String getLatestInfo() throws DatabaseCriticalException, DatabaseOperationException { + SourceCode latestSourceCode = new SourceCode(); + String funcDefinitionQuery = String.format(Locale.ENGLISH, + "select headerlines, definition from PG_GET_FUNCTIONDEF(%d);", getOid()); + + ConnectionManager connectionManager = this.getConnectionManager(); + if (connectionManager != null) { + handleFuncVersionQuery(latestSourceCode, funcDefinitionQuery, connectionManager); + } + return latestSourceCode.getCode(); + } + + private void handleFuncVersionQuery(SourceCode latestSourceCode, String funcDefinitionQuery, + ConnectionManager connectionManager) + throws DatabaseCriticalException, DatabaseOperationException { + ResultSet funcDefinitionQueryRS = connectionManager.execSelectAndReturnRsOnObjBrowserConn(funcDefinitionQuery); + ResultSet funcVersionQueryRS = executeVersionQuery(connectionManager); + addLatestSrcCode(latestSourceCode, connectionManager, funcDefinitionQueryRS, funcVersionQueryRS); + } + + private ResultSet executeVersionQuery(ConnectionManager connectionManager) { + String funcVersionQuery = String.format(Locale.ENGLISH, "select xmin1, cmin1 from pldbg_get_funcVer(%d);", + getOid()); + ResultSet funcVersionQueryRS = null; + try { + funcVersionQueryRS = connectionManager.execSelectAndReturnRsOnObjBrowserConn(funcVersionQuery); + } catch (DatabaseCriticalException | DatabaseOperationException exp) { + MPPDBIDELoggerUtility.error("DEBUG not enabled"); + } + return funcVersionQueryRS; + } + + private void addLatestSrcCode(SourceCode latestSourceCode, ConnectionManager connectionManager, + ResultSet funcDefinitionQueryRS, ResultSet funcVersionQueryRS) throws DatabaseOperationException { + try { + handleLatestSourceCode(latestSourceCode, funcDefinitionQueryRS, funcVersionQueryRS); + } catch (SQLException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exe); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } finally { + connectionManager.closeRSOnObjBrowserConn(funcDefinitionQueryRS); + connectionManager.closeRSOnObjBrowserConn(funcVersionQueryRS); + } + } + + private void handleLatestSourceCode(SourceCode latestSourceCode, ResultSet funcDefinitionQueryRS, + ResultSet funcVersionQueryRS) throws SQLException, DatabaseOperationException { + handleFuncDefErrorCase(funcDefinitionQueryRS, funcVersionQueryRS); + latestSourceCode.updateCode(funcDefinitionQueryRS); + latestSourceCode.updateVersionNumber(funcVersionQueryRS); + } + + @Override + public void handleChange(String obj) { + this.sourceCode.setCode(obj); + } + + @Override + public IDebugObject refreshSelf() throws MPPDBIDEException { + return DebugObjectsUtils.refreshDbObject(this); + } + + @Override + public boolean validateObjectType() { + return true; + } + + @Override + public boolean isCodeReloaded() { + return this.isCodeReloaded; + } + + @Override + public void setCodeReloaded(boolean codeReloaded) { + this.isCodeReloaded = codeReloaded; + + } + + /** + * Sets the setIsCurrentTerminal flag. + * + * @param setIsCurrentTerminal the flag + */ + public void setIsCurrentTerminal(boolean isCurrentTerminal) { + this.isCurrentTerminal = isCurrentTerminal; + } + + /** + * Checks if is current terminal. + * + * @return true, if is current terminal + */ + public boolean getCurrentTerminal() { + return this.isCurrentTerminal; + } + + /** + * Sets the isEditTerminalInputValues flag. + * + * @param isEditTerminalInputValues the flag + */ + public void setIsEditTerminalInputValues(boolean isEditTerminalInputValues) { + this.isEditTerminalInputValues = isEditTerminalInputValues; + } + + /** + * Checks if is TerminalInputValues can be editable. + * + * @return true, if is TerminalInputValues can be editable. + */ + public boolean getEditTerminalInputValues() { + return this.isEditTerminalInputValues; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/DefaultParameter.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/DefaultParameter.java new file mode 100644 index 0000000000000000000000000000000000000000..88c6d461f265fa1e06d645149a9e7f4bd60f488c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/DefaultParameter.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import org.opengauss.mppdbide.bl.serverdatacache.ObjectParameter.PARAMETERTYPE; + +/** + * + * Title: class + * + * Description: The Class DefaultParameter. + * + */ + +public class DefaultParameter { + + private String defaultParameterName; // same as ParameterInputGridLayer.PARAMETER_NAME + + private String defaultParameterType; // same as ParameterInputGridLayer.PARAMETER_TYPE + + private String defaultParameterValue; // same as ParameterInputGridLayer.PARAMETER_VALUE + + private PARAMETERTYPE defaultParameterMode; + + /** + * Instantiates a new default parameter. + * + * @param defaultParameterName the default parameter name + * @param defaultParameterType the default parameter type + * @param defaultParameterValue the default parameter value + * @param defaultParameterMode the default parameter mode + */ + public DefaultParameter(String defaultParameterName, String defaultParameterType, String defaultParameterValue, + PARAMETERTYPE defaultParameterMode) { + this.defaultParameterName = defaultParameterName; + this.defaultParameterType = defaultParameterType; + this.defaultParameterValue = defaultParameterValue; + this.defaultParameterMode = defaultParameterMode; + } + + /** + * Gets the default parameter name. + * + * @return the default parameter name + */ + public String getDefaultParameterName() { + return defaultParameterName; + } + + /** + * Sets the default parameter name. + * + * @param defaultParameterName the new default parameter name + */ + public void setDefaultParameterName(String defaultParameterName) { + this.defaultParameterName = defaultParameterName; + } + + /** + * Gets the default parameter type. + * + * @return the default parameter type + */ + public String getDefaultParameterType() { + return defaultParameterType; + } + + /** + * Sets the default parameter type. + * + * @param defaultParameterType the new default parameter type + */ + public void setDefaultParameterType(String defaultParameterType) { + this.defaultParameterType = defaultParameterType; + } + + /** + * Gets the default parameter value. + * + * @return the default parameter value + */ + public String getDefaultParameterValue() { + return defaultParameterValue; + } + + /** + * Sets the default parameter value. + * + * @param defaultParameterValue the new default parameter value + */ + public void setDefaultParameterValue(String defaultParameterValue) { + this.defaultParameterValue = defaultParameterValue; + } + + /** + * Gets the default parameter mode. + * + * @return the default parameter mode + */ + public PARAMETERTYPE getDefaultParameterMode() { + return defaultParameterMode; + } + + /** + * Sets the default parameter mode. + * + * @param defaultParameterMode the new default parameter mode + */ + public void setDefaultParameterMode(PARAMETERTYPE defaultParameterMode) { + this.defaultParameterMode = defaultParameterMode; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ExportOption.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ExportOption.java new file mode 100644 index 0000000000000000000000000000000000000000..fcd4cac746e217f55931032a12663d5b530122f1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ExportOption.java @@ -0,0 +1,188 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import org.opengauss.mppdbide.utils.EnvirnmentVariableValidator; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * Title: ExportOption + * + * Description: + * + */ + +public class ExportOption { + private String format; + private boolean zip; + private String folderName; + private String fileName; + + /** + * Instantiates a new export option. + * + * @param format the format + * @param zip the zip + * @param foldeName the folde name + * @param fileName the file name + */ + public ExportOption(String format, boolean zip, String foldeName, String fileName) { + this.format = format; + this.zip = zip; + this.folderName = foldeName; + this.fileName = fileName; + } + + /** + * Gets the format. + * + * @return the format + */ + public String getFormat() { + return format; + } + + /** + * Sets the format. + * + * @param format the new format + */ + public void setFormat(String format) { + this.format = format; + } + + /** + * Checks if is zip. + * + * @return true, if is zip + */ + public boolean isZip() { + return zip; + } + + /** + * Sets the zip. + * + * @param zip the new zip + */ + public void setZip(boolean zip) { + this.zip = zip; + } + + /** + * Gets the folder name. + * + * @return the folder name + */ + public String getFolderName() { + return folderName; + } + + /** + * Sets the folder name. + * + * @param folderName the new folder name + */ + public void setFolderName(String folderName) { + this.folderName = folderName; + } + + /** + * Gets the file name. + * + * @return the file name + */ + public String getFileName() { + return fileName; + } + + /** + * Sets the file name. + * + * @param fileName the new file name + */ + public void setFileName(String fileName) { + this.fileName = fileName; + } + + /** + * Gets the file path. + * + * @return file path + * @Title: getFilePath + * @Description: Assembly file path + */ + public String getFilePath() { + return this.folderName + EnvirnmentVariableValidator.validateAndGetFileSeperator() + this.fileName; + } + + /** + * Gets the file path with suffix format. + * + * @return the file path with suffix format + * @Title: getFilePathWithSuffixFormat + * @Description: Assembly file path with format suffix + */ + public String getFilePathWithSuffixFormat() { + String filePath = this.folderName + EnvirnmentVariableValidator.validateAndGetFileSeperator() + this.fileName; + if (zip) { + if (filePath.endsWith(".zip")) { + return filePath; + } + return filePath + ".zip"; + } else { + if ((getFileFormatSuffix().equals(".xls") && filePath.endsWith(".xls")) + || (getFileFormatSuffix().equals(".xlsx") && filePath.endsWith(".xlsx")) + || (getFileFormatSuffix().equals(".txt") && filePath.endsWith(".txt"))) { + return filePath; + } + return filePath + getFileFormatSuffix(); + } + } + + /** + * Gets the file format suffix. + * + * @return the file format suffix + * @Title: getFileFormatSuffix + * @Description: get file format suffix + */ + public String getFileFormatSuffix() { + String suffix = ""; + switch (format) { + case "Excel(xlsx)": { + suffix = ".xlsx"; + break; + } + case "Excel(xls)": { + suffix = ".xls"; + break; + } + case ".sql": { + suffix = ".sql"; + break; + } + case "Text": { + suffix = ".txt"; + break; + } + default: { + break; + } + } + return suffix; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ForeignKeyActionType.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ForeignKeyActionType.java new file mode 100644 index 0000000000000000000000000000000000000000..e723e31099dd36b12c8bc37a7b611c1656ed5524 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ForeignKeyActionType.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: enum + * + * Description: The Enum ForeignKeyActionType. + */ + +public enum ForeignKeyActionType { + FK_NO_ACTION(" ON UPDATE NO ACTION", " ON DELETE NO ACTION"), + FK_RESTRICT(" ON UPDATE RESTRICT", " ON DELETE RESTRICT"), FK_CASCADE(" ON UPDATE CASCADE", " ON DELETE CASCADE"), + FK_SET_NULL(" ON UPDATE SET NULL", " ON DELETE SET NULL"), + FK_SET_DEFAULT(" ON UPDATE SET DEFAULT", " ON DELETE SET DEFAULT"); + + private String updateLabel = ""; + private String deleteLabel = ""; + + /** + * Instantiates a new foreign key action type. + * + * @param updateLabel the update label + * @param deleteLabel the delete label + */ + private ForeignKeyActionType(String updateLabel, String deleteLabel) { + this.updateLabel = updateLabel; + this.deleteLabel = deleteLabel; + } + + /** + * Gets the update label. + * + * @return the update label + */ + public String getUpdateLabel() { + return this.updateLabel; + } + + /** + * Gets the delete label. + * + * @return the delete label + */ + public String getDeleteLabel() { + return this.deleteLabel; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ForeignKeyMatchType.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ForeignKeyMatchType.java new file mode 100644 index 0000000000000000000000000000000000000000..6eb9492177cbaf31db3565be968811d894147f0d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ForeignKeyMatchType.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: enum + * + * Description: The Enum ForeignKeyMatchType. + * + */ + +public enum ForeignKeyMatchType { + FK_MATCH_DEFAULT(""), FK_MATCH_FULL(" MATCH FULL"), FK_MATCH_PARTIAL(" MATCH PARTIAL"), + FK_MATCH_SIMPLE(" MATCH SIMPLE"); + + private String label = ""; + + /** + * Instantiates a new foreign key match type. + * + * @param label the label + */ + private ForeignKeyMatchType(String label) { + this.label = label; + } + + /** + * Gets the label. + * + * @return the label + */ + public String getLabel() { + return this.label; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ForeignPartitionTable.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ForeignPartitionTable.java new file mode 100644 index 0000000000000000000000000000000000000000..086ca168559887be87fc785e2dd811fc5f719f0e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ForeignPartitionTable.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.opengauss.mppdbide.bl.export.EXPORTTYPE; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: class + * + * Description: The Class ForeignPartitionTable. + * + */ + +public class ForeignPartitionTable extends PartitionTable { + + /** + * Instantiates a new foreign partition table. + * + * @param ns the ns + */ + public ForeignPartitionTable(Namespace ns) { + super(ns, OBJECTTYPE.FOREIGN_PARTITION_TABLE); + } + + /** + * Convert to foreign partition table. + * + * @param rs the rs + * @param ns the ns + * @return the partition table + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws SQLException the SQL exception + */ + public static PartitionTable convertToForeignPartitionTable(ResultSet rs, Namespace ns) + throws DatabaseOperationException, DatabaseCriticalException, SQLException { + PartitionTable ptab = new ForeignPartitionTable(ns); + ptab.fillTablePropertiesFromRS(rs); + ptab.setPartKey(rs.getString("partkey")); + + ns.addTableToGivenSearchPool(ptab); + + return ptab; + } + + @Override + public boolean isDropAllowed() { + return false; + } + + @Override + public boolean isExportAllowed(EXPORTTYPE exportType) { + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ForeignTable.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ForeignTable.java new file mode 100644 index 0000000000000000000000000000000000000000..063944878e69d2fd3a7fed358396125a3ae51bd8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ForeignTable.java @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map.Entry; +import java.util.SortedMap; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.bl.export.EXPORTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ForeignTableGroup; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: class + * + * Description: The Class ForeignTable. + * + */ + +public class ForeignTable extends TableMetaData { + + private static final String DROP_QUERY = "DROP FOREIGN TABLE IF EXISTS "; + + /** + * Instantiates a new foreign table. + * + * @param ns the ns + * @param type the type + */ + public ForeignTable(Namespace ns, OBJECTTYPE type) { + super(0, "notablename", ns, null, type); + } + + /** + * Gets the all F tables in schema. + * + * @param conn the conn + * @param ns the ns + * @param oid the oid + * @return the all F tables in schema + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static List getAllFTablesInSchema(DBConnection conn, Namespace ns, long oid) + throws DatabaseCriticalException, DatabaseOperationException { + String qry1 = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, " + + "ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as " + + "desc, xctbl.nodeoids as nodes,tbl.reloptions as reloptions, " + + "frgn.ftoptions, tbl.parttype as parttype, " + "array_to_string(part.partkey,',') as partkey " + + "from pg_class tbl left join pg_partition part on(tbl.oid=part.parentid and part.parttype='r') " + + "left join (select d.description, d.objoid from pg_description d " + + "where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on " + + "(tbl.oid = xctbl.pcrelid) " + + "left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) left join " + + "pg_tablespace ts on ts.oid = tbl.reltablespace " + "where tbl.relkind = 'f'"; + if (ns.getPrivilegeFlag()) { + qry1 += " and has_table_privilege(frgn.ftrelid, 'SELECT')"; + } + qry1 += " and tbl.relnamespace = %d;"; + String qry = String.format(Locale.ENGLISH, qry1, oid); + return getTableInfo(conn, ns, qry); + } + + /** + * Gets the column info. + * + * @param ftabGroup the ftab group + * @param conn the conn + * @param ns the ns + * @param oid the oid + * @return the column info + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static void getColumnInfo(ForeignTableGroup ftabGroup, DBConnection conn, Namespace ns, long oid) + throws DatabaseCriticalException, DatabaseOperationException { + String qry1 = "WITH tbl AS ( select oid as tableid,relnamespace as namespaceid from pg_class where relnamespace = " + + "%dand relkind = 'f' and parttype ='n'), " + + "attr AS ( select c.attnum as columnidx,c.attname as name , pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns,c.atttypid as datatypeoid " + + ",c.attlen as length,c.atttypmod as precision,c.attndims as dimentions,c.attnotnull as notnull,c.atthasdef as isdefaultvalueavailable,c.attrelid as tableoid " + + "from pg_attribute c where c.attrelid in (select tableid from tbl) and c.attisdropped = 'f' and c.attnum > 0), dtype AS (select typ.typnamespace as dtns,oid from pg_type typ " + + "where typ.oid in (select datatypeoid from attr) ), attrdef AS ( select d.adsrc as default_value ,d.adbin as attDefStr ,adrelid,adnum from pg_attrdef d " + + "where d.adrelid in ( select oid from tbl) and d.adnum in( select columnidx from attr))" + + "select t.tableid as tableid ,t.namespaceid as namespaceid,c.columnidx,c.name,c.displaycolumns,c.datatypeoid,typ.dtns,c.length,c.precision,c.dimentions,c.notnull,c.isdefaultvalueavailable," + + "default_value, d.attDefStr FROM tbl t LEFT JOIN attr c ON(t.tableid = c.tableoid) LEFT JOIN attrdef d ON(t.tableid = d.adrelid AND c.columnidx = d.adnum) LEFT JOIN dtype typ ON (c.datatypeoid = typ.oid) ORDER BY t.tableid ,c.columnidx;"; + + String qry = String.format(Locale.ENGLISH, qry1, oid); + PartitionTable.getColumnIndoByExecuteQuery(ftabGroup, conn, ns, qry); + } + + /** + * Gets the table info. + * + * @param conn the conn + * @param ns the ns + * @param qry the qry + * @return the table info + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private static List getTableInfo(DBConnection conn, Namespace ns, String qry) + throws DatabaseCriticalException, DatabaseOperationException { + ResultSet rs = conn.execSelectAndReturnRs(qry); + ArrayList allFtabs = new ArrayList(0); + TableMetaData ftab = null; + try { + String ftOptions = null; + boolean hasNext = rs.next(); + while (hasNext) { + if (!"n".equals(rs.getString("parttype"))) { + ftab = ForeignPartitionTable.convertToForeignPartitionTable(rs, ns); + } else { + ftOptions = rs.getString("ftoptions"); + if (ftOptions == null) { + ftOptions = ""; + } + if (ftOptions.contains("format=orc")) { + ftab = new ForeignTable(ns, OBJECTTYPE.FOREIGN_TABLE_HDFS); + } else { + ftab = new ForeignTable(ns, OBJECTTYPE.FOREIGN_TABLE_GDS); + } + getForeignErrorTable(ftOptions, ns); + ftab.fillTablePropertiesFromRS(rs); + } + + allFtabs.add(ftab); + hasNext = rs.next(); + } + + return allFtabs; + } catch (SQLException exp) { + GaussUtils.handleCriticalException(exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exp); + } finally { + conn.closeResultSet(rs); + } + } + + /** + * getForeignErrorTable table + * + * @param ftOptions option + * @param ns namespace + */ + public static void getForeignErrorTable(String ftOptions, Namespace ns) { + String[] ftOptionsArray = ftOptions.split(","); + for (int i = 0; i < ftOptionsArray.length; i++) { + if (ftOptionsArray[i].contains("error_table")) { + String[] errorTableArray = ftOptionsArray[i].split("="); + String tableName = errorTableArray[1]; + if (tableName.endsWith("}")) { + tableName = tableName.replace('}', ' '); + } + ns.getErrorTableList().add(tableName.trim()); + } + } + } + + @Override + public String getSearchName() { + return getName() + " - " + getNamespace().getName() + " - " + getTypeLabel(); + } + + @Override + public String getDropQuery(boolean isCascade) { + StringBuilder query = new StringBuilder(DROP_QUERY); + query.append(this.getDisplayName()); + + if (isCascade) { + query.append(MPPDBIDEConstants.CASCADE); + } + + return query.toString(); + } + + @Override + public boolean isDropAllowed() { + return false; + } + + @Override + public boolean isExportAllowed(EXPORTTYPE exportType) { + return false; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/GaussOLAPDBMSObject.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/GaussOLAPDBMSObject.java new file mode 100644 index 0000000000000000000000000000000000000000..2266443a3d55f3aea7cd81af101a258d5dba4077 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/GaussOLAPDBMSObject.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: interface + * + * Description: The Interface GaussOLAPDBMSObject. + * + */ + +public interface GaussOLAPDBMSObject extends DBMSObject { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IConnectionProfile.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IConnectionProfile.java new file mode 100644 index 0000000000000000000000000000000000000000..cf58ecc7ffde3755d3b2345ec63a4ca1e4f83a32 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IConnectionProfile.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; + +/** + * + * Title: interface + * + * Description: The Interface IConnectionProfile. + * + * @since 3.0.0 + */ +public interface IConnectionProfile { + + /** + * Gets the server connection info. + * + * @return the server connection info + */ + IServerConnectionInfo getServerConnectionInfo(); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IDebugObject.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IDebugObject.java new file mode 100644 index 0000000000000000000000000000000000000000..3dc740b00f3cd1b31ef4f0acad3c1ec6b184de06 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IDebugObject.java @@ -0,0 +1,359 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.util.ArrayList; + +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; + +/** + * + * Title: interface + * + * Description: The Interface IDebugObject. + * + */ + +public interface IDebugObject { + + /** + * Sets the namespace. + * + * @param namespace the new namespace + */ + void setNamespace(INamespace namespace); + + /** + * Sets the source code. + * + * @param srcCode the new source code + */ + void setSourceCode(ISourceCode srcCode); + + /** + * Gets the PL source editor elm id. + * + * @return the PL source editor elm id + */ + String getPLSourceEditorElmId(); + + /** + * Gets the object type. + * + * @return the object type + */ + OBJECTTYPE getObjectType(); + + /** + * Gets the PL source editor elm tooltip. + * + * @return the PL source editor elm tooltip + */ + String getPLSourceEditorElmTooltip(); + + /** + * Gets the display name with arg name. + * + * @return the display name with arg name + */ + String getDisplayNameWithArgName(); + + /** + * Gets the window title name. + * + * @return the window title name + */ + String getWindowTitleName(); + + /** + * Gets the oid. + * + * @return the oid + */ + long getOid(); + + /** + * Gets the database. + * + * @return the database + */ + Database getDatabase(); + + /** + * Gets the latest souce code. + * + * @return the latest souce code + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + ISourceCode getLatestSouceCode() throws DatabaseOperationException, DatabaseCriticalException; + + /** + * Gets the type. + * + * @return the type + */ + OBJECTTYPE getType(); + + /** + * Gets the source code. + * + * @return the source code + */ + ISourceCode getSourceCode(); + + /** + * Refresh source code. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + void refreshSourceCode() throws DatabaseOperationException, DatabaseCriticalException; + + /** + * Gets the display name. + * + * @param bol the bol + * @return the display name + */ + String getDisplayName(boolean bol); + + /** + * Gets the name space id. + * + * @return the name space id + */ + long getNameSpaceId(); + + /** + * Gets the latest info. + * + * @return the latest info + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + String getLatestInfo() throws DatabaseCriticalException, DatabaseOperationException; + + /** + * Checks if is changed. + * + * @param latestInfo the latest info + * @return true, if is changed + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + boolean isChanged(String latestInfo) throws DatabaseCriticalException, DatabaseOperationException; + + /** + * Gets the display label. + * + * @return the display label + */ + String getDisplayLabel(); + + /** + * Belongs to. + * + * @param database the database + * @param server the server + * @return true, if successful + */ + boolean belongsTo(Database database, Server server); + + /** + * Handle change. + * + * @param latestInfo the latest info + */ + void handleChange(String latestInfo); + + /** + * Gets the lang. + * + * @return the lang + */ + Object getLang(); + + /** + * Can support debug. + * + * @return true, if successful + */ + boolean canSupportDebug(); + + /** + * Gets the name. + * + * @return the name + */ + String getName(); + + /** + * Checks if is debuggable. + * + * @return true, if is debuggable + */ + boolean isDebuggable(); + + /** + * Gets the namespace. + * + * @return the namespace + */ + INamespace getNamespace(); + + /** + * Sets the database. + * + * @param db the new database + */ + void setDatabase(Database db); + + /** + * Gets the display name. + * + * @return the display name + */ + String getDisplayName(); + + /** + * Generate execution template. + * + * @throws DatabaseOperationException the database operation exception + */ + void generateExecutionTemplate() throws DatabaseOperationException; + + /** + * Gets the execute template. + * + * @return the execute template + */ + String getExecuteTemplate(); + + /** + * Gets the usagehint. + * + * @return the usagehint + */ + String getUsagehint(); + + /** + * Gets the template parameters. + * + * @return the template parameters + */ + ArrayList getTemplateParameters(); + + /** + * Clear template parameter values. + */ + void clearTemplateParameterValues(); + + /** + * Sets the template parameters. + * + * @param templateParameters the new template parameters + */ + void setTemplateParameters(ArrayList templateParameters); + + /** + * Sets the execution query. + * + * @param string the new execution query + */ + void setExecutionQuery(String string); + + /** + * Gets the execution query. + * + * @return the execution query + */ + String getExecutionQuery(); + + /** + * Validate object type. + * + * @return true, if successful + */ + boolean validateObjectType(); + + /** + * Prepare execution query string. + * + * @return the string + * @throws DatabaseOperationException the database operation exception + */ + String prepareExecutionQueryString() throws DatabaseOperationException; + + /** + * Refresh self. + * + * @return the i debug object + * @throws MPPDBIDEException the MPPDBIDE exception + */ + IDebugObject refreshSelf() throws MPPDBIDEException; + + /** + * Checks if is code reloaded. + * + * @return true, if is code reloaded + */ + boolean isCodeReloaded(); + + /** + * Sets the code reloaded. + * + * @param isCodeReloaded the new code reloaded + */ + void setCodeReloaded(boolean isCodeReloaded); + + /** + * gets out parameters + * + * @return the out param list + */ + ArrayList getOutParameters(); + + /** + * Sets isCurrentTerminal flag + * + * @param isCurrentTerminal the flag + */ + void setIsCurrentTerminal(boolean isCurrentTerminal); + + /** + * gets the current terminal + * + * @return the current terminal + */ + boolean getCurrentTerminal(); + + /** + * Sets theisEditTerminalInputValues flag + * + * @param isEditTerminalInputValues the flag + */ + void setIsEditTerminalInputValues(boolean isEditTerminalInputValues); + + /** + * gets the isEditTerminalInputValues flag + * + * @return true if TerminalInputValues can be editable + */ + boolean getEditTerminalInputValues(); +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IJobCancelStatus.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IJobCancelStatus.java new file mode 100644 index 0000000000000000000000000000000000000000..456ed027bfb9e727b1d3314b9a3f069a6cc5a04f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IJobCancelStatus.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: interface + * + * Description: The Interface IJobCancelStatus. + * + */ + +public interface IJobCancelStatus { + + /** + * Sets the cancel. + * + * @param isCancel the new cancel + */ + void setCancel(boolean isCancel); + + /** + * Gets the cancel. + * + * @return the cancel + */ + boolean getCancel(); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ILazyLoadObject.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ILazyLoadObject.java new file mode 100644 index 0000000000000000000000000000000000000000..26add896d89ce24adc39dde65ba3af248f503442 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ILazyLoadObject.java @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: interface + * + * Description: The Interface ILazyLoadObject. + * + */ + +public interface ILazyLoadObject { + + /** + * Gets the database. + * + * @return the database + */ + Database getDatabase(); + + /** + * Gets the load status. + * + * @return the load status + */ + LOADSTATUS getLoadStatus(); + + /** + * Sets the load status. + * + * @param status the new load status + */ + void setLoadStatus(LOADSTATUS status); + + /** + * Checks if is loaded. + * + * @return true, if is loaded + */ + default boolean isLoaded() { + return getLoadStatus() == LOADSTATUS.LOADED; + } + + /** + * Sets the loaded. + */ + default void setLoaded() { + setLoadStatus(LOADSTATUS.LOADED); + } + + /** + * Checks if is not loaded. + * + * @return true, if is not loaded + */ + default boolean isNotLoaded() { + return getLoadStatus() == LOADSTATUS.NOT_LOADED; + } + + /** + * Sets the not loaded. + */ + default void setNotLoaded() { + setLoadStatus(LOADSTATUS.NOT_LOADED); + } + + /** + * Checks if is loading in progress. + * + * @return true, if is loading in progress + */ + default boolean isLoadingInProgress() { + return getLoadStatus() == LOADSTATUS.LOADING_IN_PROGRESS; + } + + /** + * Sets the loading in progress. + */ + default void setLoadingInProgress() { + setLoadStatus(LOADSTATUS.LOADING_IN_PROGRESS); + + } + + /** + * Sets the load failed. + */ + default void setLoadFailed() { + setLoadStatus(LOADSTATUS.LOAD_FAILED); + } + + /** + * Checks if is load failed. + * + * @return true, if is load failed + */ + default boolean isLoadFailed() { + return getLoadStatus() == LOADSTATUS.LOAD_FAILED; + } + + /** + * Gets the all objects. + * + * @param conn the conn + * @param status the status + * @return the all objects + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + void getAllObjects(DBConnection conn, JobCancelStatus status) + throws DatabaseOperationException, DatabaseCriticalException; + + /** + * Gets the name. + * + * @return the name + */ + String getName(); + + /** + * Gets the oid. + * + * @return the oid + */ + long getOid(); + + /** + * Gets the server. + * + * @return the server + */ + Server getServer(); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/INamespace.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/INamespace.java new file mode 100644 index 0000000000000000000000000000000000000000..3cd1ed8553cf48d15d8ca6d7474e91af517a260d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/INamespace.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.groups.OLAPObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ObjectGroup; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; + +/** + * + * Title: interface + * + * Description: The Interface INamespace. + * + */ + +public interface INamespace { + + /** + * Gets the functions. + * + * @return the functions + */ + ObjectGroup getFunctions(); + + /** + * Gets the packages. + * + * @return the packages + */ + ObjectGroup getPackages(); + + /** + * Gets the name. + * + * @return the name + */ + String getName(); + + /** + * Gets the qualified object name. + * + * @return the qualified object name + */ + String getQualifiedObjectName(); + + /** + * Refresh debug object group. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + void refreshDebugObjectGroup() throws DatabaseOperationException, DatabaseCriticalException; + + /** + * Gets the database. + * + * @return the database + */ + Database getDatabase(); + + /** + * Gets the debug object by id. + * + * @param oid the oid + * @return the debug object by id + */ + IDebugObject getDebugObjectById(long oid); + + /** + * Drop db object. + * + * @param debugObject the debug object + * @param conn the conn + * @throws MPPDBIDEException the MPPDBIDE exception + */ + void dropDbObject(IDebugObject debugObject, DBConnection conn) throws MPPDBIDEException; + + /** + * Checks if is loaded. + * + * @return true, if is loaded + */ + public boolean isLoaded(); + + /** + * Sets the loaded value non loaded object. + * + * @param objGroup the new loaded value non loaded object + */ + default void setLoadedValueNonLoadedObject(ObjectGroup objGroup) { + for (Object serverObj : objGroup.getChildren()) { + ServerObject serverObject = (ServerObject) serverObj; + serverObject.setLoaded(true); + } + } + + /** + * gets the NewlyCreatedTable + * + * @param tableName the tableName + * @return the server object + */ + ServerObject getNewlyCreatedTable(String tableName); + + /** + * gets the NewlyUpdatedTable + * + * @param tableName the tableName + * @return the server object + */ + ServerObject getNewlyUpdatedTable(String tableName); + + /** + * gets the NewlyCreatedView + * + * @param viewName the viewName + * @return the server object + */ + ServerObject getNewlyCreatedView(String viewName); + + /** + * gets the NewlyUpdatedView + * + * @param viewName the viewName + * @return the server object + */ + ServerObject getNewlyUpdatedView(String viewName); + + /** + * gets the New Create Trigger view + * + * @param triggerName the trigger + * @return the server object + */ + ServerObject getNewlyCreateTrigger(String triggerName); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IPartitionType.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IPartitionType.java new file mode 100644 index 0000000000000000000000000000000000000000..1d12a0b6dcc742a44de27866365082352d45901b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IPartitionType.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** +* +* Title: Interface +* +* Description: The interface IPartitionType +* +*/ +public interface IPartitionType { + /** + * Converts partition type enum value to different method + * + * @param from the input param + * @return the return value + */ + T convert(F from); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IQueryMaterializer.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IQueryMaterializer.java new file mode 100644 index 0000000000000000000000000000000000000000..758ee5d08c2e13826ad9bcb3a95c87c6bfc276ba --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IQueryMaterializer.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.SQLException; + +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: interface + * + * Description: The Interface IQueryMaterializer. + * + */ + +public interface IQueryMaterializer { + + /** + * Materialize query result. + * + * @param irq the irq + * @return the object + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + Object materializeQueryResult(IQueryResult irq) throws DatabaseCriticalException, DatabaseOperationException; + + /** + * Gets the materialized query result. + * + * @return the materialized query result + */ + Object getMaterializedQueryResult(); + + /** + * Materialize query result. + * + * @param irq the irq + * @param isCallableStmt flag that indicates callable statement + * @return the object + * @throws DatabaseCriticalException + * @throws DatabaseOperationException + * @throws SQLException + */ + Object materializeQueryResult(IQueryResult irq, boolean isCallableStmt) + throws DatabaseCriticalException, DatabaseOperationException, SQLException; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IQueryResult.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IQueryResult.java new file mode 100644 index 0000000000000000000000000000000000000000..a3f2a44ea397966807c3281f9acf0f278ead80e1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IQueryResult.java @@ -0,0 +1,243 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.HashMap; +import java.util.Map; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.StmtExecutor; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.QueryResultType; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: interface + * + * Description: The Interface IQueryResult. + * + */ + +public interface IQueryResult { + + /** + * Close stament. + */ + void closeStament(); + + /** + * Rollback. + */ + void rollback(); + + /** + * Commit connection. + */ + void commitConnection(); + + /** + * Gets the rows affected. + * + * @return the rows affected + */ + int getRowsAffected(); + + /** + * Gets the return type. + * + * @return the return type + */ + QueryResultType getReturnType(); + + /** + * Gets the column meta data. + * + * @return the column meta data + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + ResultSetColumn[] getColumnMetaData() throws DatabaseOperationException, DatabaseCriticalException; + + /** + * Gets the next record batch. + * + * @param count the count + * @return the next record batch + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + String[][] getNextRecordBatch(int count) throws DatabaseOperationException, DatabaseCriticalException; + + /** + * Gets the next object record batch. + * + * @param count the count + * @return the next object record batch + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + Object[][] getNextObjectRecordBatch(int count) throws DatabaseOperationException, DatabaseCriticalException; + + /** + * Gets the results set. + * + * @return the results set + */ + ResultSet getResultsSet(); + + /** + * Gets the column count. + * + * @return the column count + * @throws DatabaseOperationException the database operation exception + */ + int getColumnCount() throws DatabaseOperationException; + + /** + * Checks if is end of records reached. + * + * @return true, if is end of records reached + */ + boolean isEndOfRecordsReached(); + + /** + * Gets the column comment of OLAP. + * + * @param connection the connection + * @param stmt the stmt + * @return the column comment of OLAP + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @Title: getColumnCommentOfOLAP + * @Description: get column comment + */ + default Map getColumnCommentOfOLAP(DBConnection connection, Statement stmt) + throws DatabaseOperationException, DatabaseCriticalException { + Map columnComments = new HashMap<>(); + + PreparedStatement prepareStmt = null; + ResultSet commentRs = null; + + try { + if (stmt == null || stmt.isClosed()) { + return columnComments; + } + ResultSetMetaData resultdata = stmt.getResultSet().getMetaData(); + if (connection.isOLAPConnection()) { + StringBuilder queryBuilder = getColumnDescriptionSQL(); + + int columnCount = resultdata.getColumnCount(); + for (int i = 1; i <= columnCount; i++) { + queryBuilder.append("(?,?,?),"); + } + if (columnCount >= 1) { + queryBuilder.deleteCharAt(queryBuilder.length() - 1); + } + queryBuilder.append(");"); + + prepareStmt = connection.getPrepareStmt(queryBuilder.toString()); + + int inColsSize = 3; + for (int clmIndex = 1; clmIndex <= columnCount; clmIndex++) { + prepareStmt.setString(1 + (clmIndex - 1) * inColsSize, resultdata.getSchemaName(clmIndex)); + prepareStmt.setString(2 + (clmIndex - 1) * inColsSize, resultdata.getTableName(clmIndex)); + prepareStmt.setString(3 + (clmIndex - 1) * inColsSize, resultdata.getColumnName(clmIndex)); + } + + commentRs = prepareStmt.executeQuery(); + if (null != commentRs) { + while (commentRs.next()) { + String key = commentRs.getString("schema_name") + commentRs.getString("table_name") + + MPPDBIDEConstants.COLUMN_KEY_SIGN + commentRs.getString("column_name"); + columnComments.put(key, commentRs.getString("description")); + } + } + } + } catch (SQLException exe) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_FETCH_RESULT_SET_COLUMN_COMMENT), exe); + throw new DatabaseOperationException(IMessagesConstants.ERR_FETCH_RESULT_SET_COLUMN_COMMENT); + } finally { + connection.closeStatement(prepareStmt); + connection.closeResultSet(commentRs); + } + + return columnComments; + } + + /** + * gets the column description SQL + * + * @return the query builder + */ + default StringBuilder getColumnDescriptionSQL() { + StringBuilder queryBuilder = new StringBuilder( + "SELECT s.nspname schema_name, " + + " o.relname table_name, " + + " a.attname column_name, " + + " d.description " + + " FROM pg_catalog.pg_class o, " + + " pg_catalog.pg_namespace s, " + + " pg_catalog.pg_attribute a, " + + " pg_catalog.pg_description d " + + " WHERE o.relnamespace = s.oid " + + " and o.oid = a.attrelid " + + " and o.oid = d.objoid " + + " and d.objsubid = a.attnum " + + " and o.relkind in('r', 'v', 'f', 't') " + + " and (s.nspname, o.relname, a.attname) in ("); + return queryBuilder; + } + + /** + * gets the next batch record object + * + * @param count the count + * @param columnCount the column count + * @param isFuncProcResultFlow the function procedure flag + * @param isInputParaVisited the input param visited flag + * @return the object + * @throws DatabaseOperationException + * @throws DatabaseCriticalException + */ + Object[][] getNextObjectRecordBatch(int count, int columnCount, boolean isInputParaVisited, + boolean isFuncProcResultFlow) throws DatabaseOperationException, DatabaseCriticalException; + + /** + * gets the db connection + * + * @return Database connection + */ + DBConnection getConnection(); + + /** + * gets the StmtExecutor + * + * @return the stmt executor + */ + StmtExecutor getStmtExecutor(); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ISequenceMetaData.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ISequenceMetaData.java new file mode 100644 index 0000000000000000000000000000000000000000..88cca55b6f2469257a034211ef2ed805ec0144c1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ISequenceMetaData.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.SQLException; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: interface + * + * Description: The Interface ISequenceMetaData. + * + */ + +public interface ISequenceMetaData { + + /** + * Drop sequence. + * + * @param conn the conn + * @param isAppendCascade the is append cascade + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws SQLException the SQL exception + */ + public void dropSequence(DBConnection conn, boolean isAppendCascade) + throws DatabaseOperationException, DatabaseCriticalException, SQLException; + + /** + * Refresh sequence. + * + * @param dbConnection the db connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void refreshSequence(DBConnection dbConnection) throws DatabaseOperationException, DatabaseCriticalException; + + /** + * Gets the name space. + * + * @return the name space + */ + public INamespace getSeqNameSpace(); + + /** + * Gets the object full name. + * + * @return the object full name + */ + public String getObjectFullName(); + + /** + * Gets the qualified object name. + * + * @return the qualified object name + */ + public String getQualifiedObjectName(); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ISourceCode.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ISourceCode.java new file mode 100644 index 0000000000000000000000000000000000000000..04d9adf8c620842bbb1d279b68cc1bc8f7b1f081 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ISourceCode.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: interface + * + * Description: The Interface ISourceCode. + * + */ + +public interface ISourceCode { + + /** + * Gets the code. + * + * @return the code + */ + String getCode(); + + /** + * Sets the code. + * + * @param obj the new code + */ + void setCode(String obj); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ISynonymMetaData.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ISynonymMetaData.java new file mode 100644 index 0000000000000000000000000000000000000000..4adebc49bfc4e5a19e87325104cb43efe1e45dfe --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ISynonymMetaData.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.SQLException; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: Class + * + * Description: The Interface ISynonymMetaData. + * + * @since 3.0.0 + */ +public interface ISynonymMetaData { + /** + * Drop synonym. + * + * @param conn the conn + * @param isAppendCascade the is append cascade + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws SQLException the SQL exception + */ + void dropSynonym(DBConnection conn, boolean isAppendCascade) + throws DatabaseOperationException, DatabaseCriticalException, SQLException; + + /** + * Refresh sequence. + * + * @param dbConnection the db connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + void refreshSynonym(DBConnection dbConnection) throws DatabaseOperationException, DatabaseCriticalException; + + /** + * Gets the qualified object name. + * + * @return the qualified object name + */ + String getQualifiedObjectName(); + + /** + * Gets the parent. + * + * @return the parent + */ + INamespace getParent(); + + /** + * Gets the database. + * + * @return the database + */ + Database getDatabase(); + + /** + * Gets the server. + * + * @return the server + */ + Server getServer(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ISystemSetting.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ISystemSetting.java new file mode 100644 index 0000000000000000000000000000000000000000..33904d64e7c12840de849bc1a420d0c6fcfd3973 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ISystemSetting.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: interface + * + * Description: The Interface ISystemSetting. + * + */ + +public interface ISystemSetting { + + /** + * Checks if is login allowed on password expiry. + * + * @return true, if is login allowed on password expiry + */ + boolean isLoginAllowedOnPasswordExpiry(); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ITableMetaData.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ITableMetaData.java new file mode 100644 index 0000000000000000000000000000000000000000..8dfbf5559f92cee61ddea2b72a927b7dab000dbb --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ITableMetaData.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; + +/** + * + * Title: interface + * + * Description: The Interface ITableMetaData. + * + */ + +public interface ITableMetaData { + + /** + * Gets the name. + * + * @return the name + */ + String getName(); + + /** + * Gets the name space name. + * + * @return the name space name + */ + String getNameSpaceName(); + + /** + * Gets the database. + * + * @return the database + */ + Database getDatabase(); + + /** + * Gets the server name. + * + * @return the server name + */ + String getServerName(); + + /** + * Exec drop. + * + * @param connection the connection + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + void execDrop(DBConnection connection) throws DatabaseCriticalException, DatabaseOperationException; + + /** + * Gets the parent. + * + * @return the parent + */ + Object getParent(); + + /** + * Checks if is dropped. + * + * @return true, if is dropped + */ + boolean isDropped(); + + /** + * Gets the ddl. + * + * @param db the db + * @return the ddl + * @throws MPPDBIDEException the MPPDBIDE exception + */ + default String getDDL(Database db) throws MPPDBIDEException { + return "-- no DDL"; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IViewMetaData.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IViewMetaData.java new file mode 100644 index 0000000000000000000000000000000000000000..6200c17d733de551a5707b12904de8ee6baa6d58 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IViewMetaData.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; + +/** + * + * Title: interface + * + * Description: The Interface IViewMetaData. + * + */ + +public interface IViewMetaData { + + /** + * Gets the view path qualified name. + * + * @return the view path qualified name + */ + String getViewPathQualifiedName(); + + /** + * Gets the database. + * + * @return the database + */ + Database getDatabase(); + + /** + * Gets the name. + * + * @return the name + */ + String getName(); + + /** + * Gets the qualified object name. + * + * @return the qualified object name + */ + String getQualifiedObjectName(); + + /** + * Gets the namespace name. + * + * @return the namespace name + */ + String getNameSpaceName(); + + /** + * Gets the parent. + * + * @return the parent + */ + ServerObject getParent(); + + /** + * Gets the namespace qualified name. + * + * @return the namespace qualified name + */ + String getNamespaceQualifiedName(); + + /** + * Rename. + * + * @param addInfo the add info + * @param connection the connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + void rename(String addInfo, DBConnection connection) throws DatabaseOperationException, DatabaseCriticalException; + + /** + * Sets the namespace to. + * + * @param addInfo the add info + * @param connection the connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + void setNamespaceTo(String addInfo, DBConnection connection) + throws DatabaseOperationException, DatabaseCriticalException; + + /** + * Drop view. + * + * @param connection the connection + * @param isAppendCascade the is append cascade + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + void dropView(DBConnection connection, boolean isAppendCascade) + throws DatabaseOperationException, DatabaseCriticalException; + + /** + * Checks if is db connected. + * + * @return true, if is db connected + */ + boolean isDbConnected(); + + /** + * Gets the ddl. + * + * @param db the db + * @return the ddl + * @throws MPPDBIDEException the MPPDBIDE exception + */ + String getDDL(Database db) throws MPPDBIDEException; + + /** + * Checks if is view code loaded. + * + * @return true, if is view code loaded + */ + boolean isViewCodeLoaded(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IViewObjectGroups.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IViewObjectGroups.java new file mode 100644 index 0000000000000000000000000000000000000000..c4d13d2f8d6b23b985b9a5fe4c9b6bd38d72c8d1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IViewObjectGroups.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: interface + * + * Description: The Interface IViewObjectGroups. + * + */ + +public interface IViewObjectGroups { + + /** + * Gets the template code. + * + * @return the template code + */ + String getTemplateCode(); + + /** + * Gets the database. + * + * @return the database + */ + Database getDatabase(); + + /** + * Checks if is db connected. + * + * @return true, if is db connected + */ + boolean isDbConnected(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ImportExportOption.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ImportExportOption.java new file mode 100644 index 0000000000000000000000000000000000000000..f4cef2486ee411f4795d13c48ed73b670eb44d0f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ImportExportOption.java @@ -0,0 +1,282 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.util.ArrayList; + +/** + * + * Title: class + * + * Description: The Class ImportExportOption. + * + */ + +public class ImportExportOption { + + private String fileFormat; + private boolean header; + private String quotes; + private String escape; + private String replaceNull; + private String encoding; + private String delimiter; + private boolean zip; + private boolean allColunms; + private ArrayList tablecolumns; + private String cononicalPath; + private boolean isExport; + private String dateSelector; + + /** + * Gets the file format. + * + * @return the file format + */ + public String getFileFormat() { + return fileFormat; + } + + /** + * Sets the file format. + * + * @param fileFormat the new file format + */ + public void setFileFormat(String fileFormat) { + this.fileFormat = fileFormat; + } + + /** + * Checks if is header. + * + * @return true, if is header + */ + public boolean isHeader() { + return header; + } + + /** + * Sets the header. + * + * @param header the new header + */ + public void setHeader(boolean header) { + this.header = header; + } + + /** + * Gets the quotes. + * + * @return the quotes + */ + public String getQuotes() { + return quotes; + } + + /** + * Sets the quotes. + * + * @param quotes the new quotes + */ + public void setQuotes(String quotes) { + this.quotes = quotes; + } + + /** + * Gets the escape. + * + * @return the escape + */ + public String getEscape() { + return escape; + } + + /** + * Sets the escape. + * + * @param escape the new escape + */ + public void setEscape(String escape) { + this.escape = escape; + } + + /** + * Gets the replace null. + * + * @return the replace null + */ + public String getReplaceNull() { + return replaceNull; + } + + /** + * Sets the replace null. + * + * @param replaceNull the new replace null + */ + public void setReplaceNull(String replaceNull) { + this.replaceNull = replaceNull; + } + + /** + * Gets the encoding. + * + * @return the encoding + */ + public String getEncoding() { + return encoding; + } + + /** + * Sets the encoding. + * + * @param encoding the new encoding + */ + public void setEncoding(String encoding) { + this.encoding = encoding; + } + + /** + * Gets the delimiter. + * + * @return the delimiter + */ + public String getDelimiter() { + return delimiter; + } + + /** + * Sets the delimiter. + * + * @param delimiter the new delimiter + */ + public void setDelimiter(String delimiter) { + this.delimiter = delimiter; + } + + /** + * Checks if is all colunms. + * + * @return true, if is all colunms + */ + public boolean isAllColunms() { + return allColunms; + } + + /** + * Sets the all colunms. + * + * @param allColunms the new all colunms + */ + public void setAllColunms(boolean allColunms) { + this.allColunms = allColunms; + } + + /** + * Gets the tablecolumns. + * + * @return the tablecolumns + */ + public ArrayList getTablecolumns() { + return tablecolumns; + } + + /** + * Sets the tablecolumns. + * + * @param selectedColsList the new tablecolumns + */ + public void setTablecolumns(ArrayList selectedColsList) { + this.tablecolumns = selectedColsList; + } + + /** + * Gets the file name. + * + * @return the file name + */ + public String getFileName() { + return cononicalPath; + } + + /** + * Sets the file name. + * + * @param fileName the new file name + */ + public void setFileName(String fileName) { + this.cononicalPath = fileName; + } + + /** + * Checks if is export. + * + * @return true, if is export + */ + public boolean isExport() { + return isExport; + } + + /** + * Sets the export. + * + * @param isExprt the new export + */ + public void setExport(boolean isExprt) { + this.isExport = isExprt; + } + + /** + * Gets the date selector. + * + * @return the date selector + * @Title: getDateSelector + * @Description: Get table import excel date format + */ + public String getDateSelector() { + return dateSelector; + } + + /** + * Sets the date selector. + * + * @param dateSelector the new date selector + * @Title: setDateSelector + * @Description: Set table import excel date format + */ + public void setDateSelector(String dateSelector) { + this.dateSelector = dateSelector; + } + + /** + * Export if compress. + * + * @return true ,if is compress + */ + public boolean getZip() { + return zip; + } + + /** + * Sets the zip. + * + * @param zip the new zip + */ + public void setZip(boolean zip) { + this.zip = zip; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IndexMetaData.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IndexMetaData.java new file mode 100644 index 0000000000000000000000000000000000000000..751a8666aad34a45900c731e757895c046c51820 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IndexMetaData.java @@ -0,0 +1,876 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.text.Normalizer; +import java.text.Normalizer.Form; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.groups.OLAPObjectList; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: class + * + * Description: The Class IndexMetaData. + * + */ + +public class IndexMetaData extends BatchDropServerObject implements GaussOLAPDBMSObject { + + private TableMetaData table; + private boolean isUnique; + private boolean isPrimary; + private boolean isExclusion; + private boolean isImmediate; + private boolean isLastClustered; + private boolean checkxmin; + private boolean isReady; + private ArrayList colExpr; + private Namespace namespace; + + private AccessMethod accessMethod; + private long accessMethId; + private Tablespace tablespace; + private String tblspce; + private int fillFactor; + private String whereExpr; + private String indexdeff; + private Comparator comparator; + private boolean isLoaded; + private static final String DROP_QUERY = "DROP INDEX IF EXISTS "; + private IndexManager indexManager; + private String indexType; + + /** + * Instantiates a new index meta data. + * + * @param oid the oid + * @param name the name + */ + public IndexMetaData(long oid, String name) { + super(oid, name, OBJECTTYPE.INDEX_METADATA, false); + colExpr = new ArrayList(4); + comparator = new IndexedColumnComparator(); + indexManager = new IndexManager(); + this.isLoaded = false; + } + + /** + * Instantiates a new index meta data. + * + * @param name the name + */ + public IndexMetaData(String name) { + super(-1, name, OBJECTTYPE.INDEX_METADATA, false); + colExpr = new ArrayList(4); + comparator = new IndexedColumnComparator(); + this.isLoaded = false; + indexManager = new IndexManager(); + } + + /** + * Gets the table. + * + * @return the table + */ + public TableMetaData getTable() { + return table; + } + + /** + * Sets the table. + * + * @param table the new table + */ + public void setTable(TableMetaData table) { + this.table = table; + } + + /** + * Checks if is unique. + * + * @return true, if is unique + */ + public boolean isUnique() { + return isUnique; + } + + /** + * Sets the unique. + * + * @param isUniq the new unique + */ + public void setUnique(boolean isUniq) { + this.isUnique = isUniq; + } + + /** + * Checks if is primary. + * + * @return true, if is primary + */ + public boolean isPrimary() { + return isPrimary; + } + + /** + * Sets the primary. + * + * @param isPrmry the new primary + */ + public void setPrimary(boolean isPrmry) { + this.isPrimary = isPrmry; + } + + /** + * Checks if is exclusion. + * + * @return true, if is exclusion + */ + public boolean isExclusion() { + return isExclusion; + } + + /** + * Sets the exclusion. + * + * @param isExclusn the new exclusion + */ + public void setExclusion(boolean isExclusn) { + this.isExclusion = isExclusn; + } + + /** + * Checks if is immediate. + * + * @return true, if is immediate + */ + public boolean isImmediate() { + return isImmediate; + } + + /** + * Sets the immediate. + * + * @param isImmediat the new immediate + */ + public void setImmediate(boolean isImmediat) { + this.isImmediate = isImmediat; + } + + /** + * Checks if is last clustered. + * + * @return true, if is last clustered + */ + public boolean isLastClustered() { + return isLastClustered; + } + + /** + * Sets the last clustered. + * + * @param isLastClusterd the new last clustered + */ + public void setLastClustered(boolean isLastClusterd) { + this.isLastClustered = isLastClusterd; + } + + /** + * Checks if is checkxmin. + * + * @return true, if is checkxmin + */ + public boolean isCheckxmin() { + return checkxmin; + } + + /** + * Sets the checkxmin. + * + * @param checkxmin the new checkxmin + */ + public void setCheckxmin(boolean checkxmin) { + this.checkxmin = checkxmin; + } + + /** + * Checks if is ready. + * + * @return true, if is ready + */ + public boolean isReady() { + return isReady; + } + + /** + * Sets the ready. + * + * @param isRdy the new ready + */ + public void setReady(boolean isRdy) { + this.isReady = isRdy; + } + + /** + * Gets the indexed columns. + * + * @return the indexed columns + */ + public ArrayList getIndexedColumns() { + return colExpr; + } + + /** + * Sets the indexed columns. + * + * @param colExprs the new indexed columns + */ + public void setIndexedColumns(ArrayList colExprs) { + this.colExpr = colExprs; + } + + /** + * Gets the namespace. + * + * @return the namespace + */ + public Namespace getNamespace() { + return this.namespace; + } + + /** + * Sets the namespace. + * + * @param namespace the new namespace + */ + public void setNamespace(Namespace namespace) { + this.namespace = namespace; + } + + /** + * Adds the index column. + * + * @param newColExpr the new col expr + */ + private void addIndexColumn(IndexedColumnExpr newColExpr) { + int insertionPoint = Collections.binarySearch(this.colExpr, newColExpr, comparator); + if (insertionPoint < 0) { + insertionPoint = -(insertionPoint + 1); + } + + newColExpr.setPosition(insertionPoint); + this.colExpr.add(insertionPoint, newColExpr); + } + + /** + * Adds the column. + * + * @param col the col + */ + public void addColumn(ColumnMetaData col) { + IndexedColumnExpr columnExpr = new IndexedColumnExpr(IndexedColumnType.COLUMN); + columnExpr.setCol(col); + addIndexColumn(columnExpr); + } + + /** + * Adds the expr. + * + * @param expr the expr + */ + public void addExpr(String expr) { + IndexedColumnExpr columnExpr = new IndexedColumnExpr(IndexedColumnType.EXPRESSION); + columnExpr.setExpr(expr); + addIndexColumn(columnExpr); + } + + /** + * Gets the indexdeff. + * + * @return the indexdeff + */ + public String getIndexdeff() { + return indexdeff; + } + + /** + * Sets the indexdeff. + * + * @param indexdeff the new indexdeff + */ + public void setIndexdeff(String indexdeff) { + this.indexdeff = indexdeff; + } + + /** + * Gets the index type. + * + * @return the index type + */ + public String getIndexType() { + return this.indexType; + } + + /** + * Sets the index type. + * + * @param indexType the new index type + */ + public void setIndexType(String indexType) { + this.indexType = indexType; + } + + /** + * Gets the access method. + * + * @return the access method + */ + public AccessMethod getAccessMethod() { + return this.accessMethod; + } + + /** + * Sets the access method. + * + * @param am the new access method + */ + public void setAccessMethod(AccessMethod am) { + this.accessMethod = am; + } + + /** + * Gets the tablespace. + * + * @return the tablespace + */ + public Tablespace getTablespace() { + return tablespace; + } + + /** + * Sets the tablespace. + * + * @param tablespace the new tablespace + */ + public void setTablespace(Tablespace tablespace) { + this.tablespace = tablespace; + } + + /** + * Gets the fill factor. + * + * @return the fill factor + */ + public int getFillFactor() { + return this.fillFactor; + } + + /** + * Sets the index fill factor. + * + * @param fillFact the new index fill factor + */ + public void setIndexFillFactor(int fillFact) { + this.fillFactor = fillFact; + } + + /** + * Gets the where expr. + * + * @return the where expr + */ + public String getWhereExpr() { + return this.whereExpr; + } + + /** + * Sets the where expr. + * + * @param whereExpr the new where expr + */ + public void setWhereExpr(String whereExpr) { + this.whereExpr = whereExpr; + } + + /** + * Form create query. + * + * @param isCreateTable the is create table + * @return the string + */ + public String formCreateQuery(boolean isCreateTable) { + StringBuilder qry = new StringBuilder("CREATE "); + + if (isUnique()) { + qry.append("UNIQUE "); + } + appendSchemaOrTableNameForIndex(isCreateTable, qry); + + appendAccessMethod(qry); + + qry.append("("); + + appendIndexColumn(qry); + + qry.append(") "); + + if (table instanceof PartitionTable) { + appendIndexType(qry); + } + + appendFillFactor(qry); + + appendTablespace(qry); + + appendWhrExpression(qry); + + qry.append(";"); + return qry.toString(); + + } + + /** + * Append whr expression. + * + * @param qry the qry + */ + private void appendWhrExpression(StringBuilder qry) { + if (null != this.whereExpr && !"".equals(this.whereExpr)) { + qry.append(" WHERE ").append(this.whereExpr); + } + } + + /** + * Append tablespace. + * + * @param qry the qry + */ + private void appendTablespace(StringBuilder qry) { + if (null != this.tablespace) { + qry.append(" TABLESPACE ").append(this.tablespace.getQualifiedObjectName()); + } + } + + /** + * Append fill factor. + * + * @param qry the qry + */ + private void appendFillFactor(StringBuilder qry) { + if (this.table.isRowTableOrientation()) { + // if none of the access method selected or if access method other + // than gin and psort is selected + if ((getAccessMethod() == null + || (!getAccessMethod().getName().equals("gin") && !getAccessMethod().getName().equals("psort")))) { + if (this.fillFactor > 0) { + qry.append("WITH (FILLFACTOR=").append(this.fillFactor).append(")"); + } + } + } + } + + /** + * Append index column. + * + * @param qry the qry + */ + private void appendIndexColumn(StringBuilder qry) { + Iterator colExprItr = this.colExpr.iterator(); + boolean hasNext = colExprItr.hasNext(); + boolean isFirst = true; + String columnExpr = null; + while (hasNext) { + columnExpr = colExprItr.next().toString(); + if (!isFirst) { + qry.append(", "); + } + appendColumnName(qry, columnExpr); + hasNext = colExprItr.hasNext(); + isFirst = false; + } + } + + private void appendColumnName(StringBuilder qry, String columnExpr) { + if (this.isQSimpleObjectName(columnExpr)) { + qry.append(ServerObject.getQualifiedObjectName(columnExpr)); + } else { + qry.append(columnExpr); + } + } + + private boolean isQSimpleObjectName(String columnExpr) { + return !ServerObject.isQualifiedSimpleObjectName(columnExpr) && !columnExpr.contains("("); + } + + /** + * Append index type. + * + * @param qry the qry + */ + private void appendIndexType(StringBuilder qry) { + if (null != this.indexType) { + qry.append(getIndexType()).append(" "); + } + } + + /** + * Append access method. + * + * @param qry the qry + */ + private void appendAccessMethod(StringBuilder qry) { + if (null != this.accessMethod) { + qry.append("USING ").append(getAccessMethod().getName()).append(" "); + } + } + + /** + * Append schema or table name for index. + * + * @param isCreateTable the is create table + * @param qry the qry + */ + private void appendSchemaOrTableNameForIndex(boolean isCreateTable, StringBuilder qry) { + if (!isCreateTable) { + qry.append("INDEX ").append(ServerObject.getQualifiedObjectName(getName())).append(" ON ") + .append(table.getDisplayName()).append(" "); + } else { + qry.append("INDEX ").append(ServerObject.getQualifiedObjectName(getName())).append(" ON ") + .append(getNamespace().getQualifiedObjectName()).append(".") + .append(ServerObject.getQualifiedObjectName(table.getName())).append(" "); + } + } + + /** + * Form drop query. + * + * @param isCreateTable the is create table + * @return the string + */ + public String formDropQuery(boolean isCreateTable) { + return DROP_QUERY + this.getDisplayName() + ';'; + } + + /** + * Drop. + * + * @param conn the conn + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void drop(DBConnection conn) throws DatabaseOperationException, DatabaseCriticalException { + indexManager.drop(conn); + } + + /** + * Rename. + * + * @param newName the new name + * @param conn the conn + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void rename(String newName, DBConnection conn) throws DatabaseOperationException, DatabaseCriticalException { + indexManager.rename(newName, conn); + } + + /** + * Change tablespace. + * + * @param tblspaceName the tblspace name + * @param conn the conn + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void changeTablespace(String tblspaceName, DBConnection conn) + throws DatabaseOperationException, DatabaseCriticalException { + indexManager.changeTablespace(tblspaceName, conn); + } + + /** + * Change fill factor. + * + * @param fillFact the fill fact + * @param conn the conn + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void changeFillFactor(int fillFact, DBConnection conn) + throws DatabaseOperationException, DatabaseCriticalException { + indexManager.changeFillFactor(fillFact, conn); + } + + /** + * Gets the columns string. + * + * @return the columns string + */ + public String getColumnsString() { + return indexManager.getColumnsString(); + } + + /** + * Checks if is loaded. + * + * @return true, if is loaded + */ + public boolean isLoaded() { + return isLoaded; + } + + /** + * Sets the loaded. + * + * @param isLoad the new loaded + */ + public void setLoaded(boolean isLoad) { + this.isLoaded = isLoad; + } + + /** + * Sets the tablespace. + * + * @param tablespace the new tablespace + */ + public void setTablespace(String tablespace) { + if (null != tablespace) { + this.tblspce = tablespace; + } else { + this.tblspce = getDatabase().getDBDefaultTblSpc(); + } + } + + /** + * Gets the tablespc. + * + * @return the tablespc + */ + public String getTablespc() { + return this.tblspce; + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + return this.getTable().getDatabase(); + } + + /** + * Gets the display name. + * + * @return the display name + */ + public String getDisplayName() { + return getNamespace().getDisplayName() + '.' + super.getDisplayName(); + } + + /** + * Gets the parent. + * + * @return the parent + */ + public TableMetaData getParent() { + return table; + + } + + /** + * Gets the where expresionfor property. + * + * @param conn the conn + * @return the where expresionfor property + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public String getwhereExpresionforProperty(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + return indexManager.getwhereExpresionforProperty(conn); + } + + @Override + public String getDropQuery(boolean isCascade) { + StringBuilder query = new StringBuilder(DROP_QUERY); + query.append(this.getDisplayName()); + if (isCascade) { + query.append(MPPDBIDEConstants.CASCADE); + } + return query.toString(); + } + + @Override + public boolean isDropAllowed() { + if (getParent() instanceof ForeignTable) { + return false; + } + + return true; + } + + /** + * get Access Method Id + * + * @return accessMethId the access Method Id + */ + public long getAccessMethId() { + return accessMethId; + } + + /** + * set Access Method Id + * + * @param accessMethId the access Meth Id + */ + public void setAccessMethId(long accessMethId) { + this.accessMethId = accessMethId; + } + + private class IndexManager { + /** + * getwhereExpresionforProperty + * + * @param conn connection + * @return string query + * @throws DatabaseCriticalException exception + * @throws DatabaseOperationException exception + */ + public String getwhereExpresionforProperty(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + String query = String.format(Locale.ENGLISH, + "select pg_get_expr(indpred,%d) from pg_index where indrelid = %d and indexrelid = %d;", + getParent().getOid(), getParent().getOid(), getOid()); + return conn.execSelectAndGetFirstVal(query); + + } + + /** + * Gets the columns string. + * + * @return the columns string + */ + public String getColumnsString() { + StringBuilder colNames = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + boolean isFirst = true; + + ArrayList columns = getIndexedColumns(); + if (null != columns) { + int size = columns.size(); + IndexedColumnExpr column = null; + for (int clmIndex = 0; clmIndex < size; clmIndex++) { + column = columns.get(clmIndex); + isFirst = addColumnNames(colNames, isFirst, column); + } + } + + return colNames.toString(); + } + + private boolean addColumnNames(StringBuilder colNames, boolean isFirstParam, IndexedColumnExpr column) { + boolean isFirst = isFirstParam; + if (validateColumn(column)) { + if (!isFirst) { + colNames.append(","); + } else { + isFirst = false; + } + + colNames.append(ServerObject.getQualifiedObjectName(column.getCol().getName())); + } + return isFirst; + } + + private boolean validateColumn(IndexedColumnExpr column) { + return null != column && column.validateColumn(); + } + + /** + * Change fill factor. + * + * @param fillFact the fill fact + * @param conn the conn + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void changeFillFactor(int fillFact, DBConnection conn) + throws DatabaseOperationException, DatabaseCriticalException { + String qry = String.format(Locale.ENGLISH, "ALTER INDEX %s SET (fillfactor = %d);", getDisplayName(), + fillFact); + conn.execNonSelectForTimeout(qry); + getTable().refresh(conn); + } + + /** + * Change tablespace. + * + * @param tblspaceName the tblspace name + * @param conn the conn + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void changeTablespace(String tblspaceName, DBConnection conn) + throws DatabaseOperationException, DatabaseCriticalException { + String qualifiedTblspaceName = ServerObject.getQualifiedObjectName(tblspaceName); + String qry = String.format(Locale.ENGLISH, "ALTER INDEX %s SET TABLESPACE %s;", getDisplayName(), + qualifiedTblspaceName); + conn.execNonSelectForTimeout(qry); + getTable().refresh(conn); + } + + /** + * Rename. + * + * @param newName the new name + * @param conn the conn + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void rename(String newName, DBConnection conn) + throws DatabaseOperationException, DatabaseCriticalException { + String qry = String.format(Locale.ENGLISH, "ALTER INDEX %s RENAME TO %s ;", getDisplayName(), + ServerObject.getQualifiedObjectName(newName)); + conn.execNonSelectForTimeout(qry); + setName(newName); + getTable().refresh(conn); + } + + /** + * Drop. + * + * @param conn the conn + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void drop(DBConnection conn) throws DatabaseOperationException, DatabaseCriticalException { + String qry = String.format(Locale.ENGLISH, "drop index %s;", getDisplayName()); + conn.execNonSelectForTimeout(qry); + getTable().refresh(conn); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IndexUtil.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IndexUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..5f4caa4aef508656cd55e1837a68ce53a22fac07 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IndexUtil.java @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.text.Normalizer; +import java.text.Normalizer.Form; +import java.util.Iterator; + +import org.opengauss.mppdbide.bl.serverdatacache.groups.OLAPObjectList; + +/** + * Title: IndexUtil + * + * Description: + * + * @since 3.0.0 + */ +public class IndexUtil { + /** + * Gets the column. + * + * @param columnList the column list + * @param idx the idx + * @return the column + */ + private static ColumnMetaData getColumn(OLAPObjectList columnList, int idx) { + Iterator itr = columnList.getList().iterator(); + boolean hasNext = itr.hasNext(); + while (hasNext) { + ColumnMetaData col = itr.next(); + hasNext = itr.hasNext(); + if (col.getOid() == idx) { + return col; + } + } + + return null; + } + + /** + * Convert to index. + * + * @param rs the rs + * @param tableMetaData the table meta data + * @param nameSpc the name spc + * @param columnList the column list + * @return the index meta data + * @throws SQLException the SQL exception + */ + public static IndexMetaData convertToIndex(ResultSet rs, TableMetaData tableMetaData, Namespace nameSpc, + OLAPObjectList columnList) throws SQLException { + long oid = rs.getLong("oid"); + String name = rs.getString("indexname"); + boolean hasNonHiddenCols = false; + + IndexMetaData index = getIndexObject(rs, tableMetaData, nameSpc, oid, name); + + String colListStr = rs.getString("cols"); + if (null != colListStr) { + String[] colList = colListStr.trim().split(" "); + + int colIdxStrLen = colList.length; + hasNonHiddenCols = getAllColumnForINdex(columnList, index, colList, colIdxStrLen); + + addIndexToTableMetadata(tableMetaData, hasNonHiddenCols, index); + } + + getIndexFillFactor(rs, index); + + return index; + } + + private static boolean getAllColumnForINdex(OLAPObjectList columnList, IndexMetaData index, + String[] colList, int colIdxStrLen) { + int colIdx = 0; + boolean hasNonHiddenCols = false; + String colIdxStr = null; + for (int clmIndex = 0; clmIndex < colIdxStrLen; clmIndex++) { + colIdxStr = colList[clmIndex]; + colIdx = Integer.parseInt(colIdxStr); + if (colIdx < 0) { + continue; + } + + hasNonHiddenCols = addIndexInfo(columnList, index, colIdx); + } + return hasNonHiddenCols; + } + + private static boolean addIndexInfo(OLAPObjectList columnList, IndexMetaData index, int colIdx) { + boolean hasNonHiddenCols = false; + if (colIdx == 0) { + index.addExpr(""); + hasNonHiddenCols = true; + } else { + ColumnMetaData col = getColumn(columnList, colIdx); + if (null != col) { + index.addColumn(col); + hasNonHiddenCols = true; + } + } + return hasNonHiddenCols; + } + + private static void addIndexToTableMetadata(TableMetaData tableMetaData, boolean hasNonHiddenCols, + IndexMetaData index) { + /* Indexes on hidden column will be skipped */ + if (hasNonHiddenCols) { + tableMetaData.addIndex(index); + } + } + + private static void getIndexFillFactor(ResultSet rs, IndexMetaData index) throws SQLException { + String storageParams = rs.getString("reloptions"); + if (null != storageParams) { + storageParams = Normalizer.normalize(storageParams, Form.NFKC); + String[] storageParamList = storageParams.trim().split(","); + String storageParam = null; + int storageParamLen = storageParamList.length; + for (int paramndex = 0; paramndex < storageParamLen; paramndex++) { + storageParam = storageParamList[paramndex]; + if (storageParam.startsWith("fillfactor=")) { + String fillFactor = storageParam.substring(11); + index.setIndexFillFactor(Integer.parseInt(fillFactor)); + } + } + } + } + + private static IndexMetaData getIndexObject(ResultSet rs, TableMetaData tableMetaData, Namespace nameSpc, long oid, + String name) throws SQLException { + IndexMetaData index = new IndexMetaData(oid, name); + index.setTable(tableMetaData); + index.setNamespace(nameSpc); + index.setAccessMethId(rs.getLong("accessmethodid")); + index.setUnique(rs.getBoolean("isunique")); + index.setPrimary(rs.getBoolean("isprimary")); + index.setExclusion(rs.getBoolean("isexclusion")); + index.setImmediate(rs.getBoolean("isimmediate")); + index.setLastClustered(rs.getBoolean("isclustered")); + index.setCheckxmin(rs.getBoolean("checkmin")); + index.setReady(rs.getBoolean("isready")); + index.setIndexdeff(rs.getString("indexdef")); + index.setLoaded(true); + + index.setTablespace(rs.getString("tablespace")); + return index; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IndexedColumnComparator.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IndexedColumnComparator.java new file mode 100644 index 0000000000000000000000000000000000000000..1c089faf6e9bc985b5ebc716c8e129f7d3ea5cf6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IndexedColumnComparator.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.io.Serializable; +import java.util.Comparator; + +/** + * + * Title: class + * + * Description: The Class IndexedColumnComparator. + * + */ + +public class IndexedColumnComparator implements Comparator, Serializable { + + private static final long serialVersionUID = 1L; + + @Override + public int compare(IndexedColumnExpr object1, IndexedColumnExpr object2) { + return Integer.compare(object2.getPosition(), object1.getPosition()); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IndexedColumnExpr.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IndexedColumnExpr.java new file mode 100644 index 0000000000000000000000000000000000000000..4fa9e6f3effdcdfd03398cdb610068481befca9a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IndexedColumnExpr.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: class + * + * Description: The Class IndexedColumnExpr. + * + */ + +public class IndexedColumnExpr { + + private int position; + private IndexedColumnType type; + private ColumnMetaData col; + private String expr; + + /** + * Instantiates a new indexed column expr. + * + * @param type the type + */ + public IndexedColumnExpr(IndexedColumnType type) { + this.type = type; + this.position = -1; + } + + /** + * Gets the position. + * + * @return the position + */ + public int getPosition() { + return position; + } + + /** + * Sets the position. + * + * @param position the new position + */ + public void setPosition(int position) { + this.position = position; + } + + /** + * Gets the col. + * + * @return the col + */ + public ColumnMetaData getCol() { + return col; + } + + /** + * Sets the col. + * + * @param col the new col + */ + public void setCol(ColumnMetaData col) { + this.col = col; + } + + /** + * Gets the expr. + * + * @return the expr + */ + public String getExpr() { + return expr; + } + + /** + * Sets the expr. + * + * @param expr the new expr + */ + public void setExpr(String expr) { + this.expr = expr; + } + + /** + * Gets the type. + * + * @return the type + */ + public IndexedColumnType getType() { + return type; + } + + @Override + public String toString() { + if (IndexedColumnType.COLUMN == getType()) { + return getCol().getName(); + } else { + return getExpr(); + } + } + + /** + * Validate column. + * + * @return true, if successful + */ + public boolean validateColumn() { + if (getType().equals(IndexedColumnType.COLUMN) && null != getCol()) { + return true; + } + return false; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IndexedColumnType.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IndexedColumnType.java new file mode 100644 index 0000000000000000000000000000000000000000..99986d95088057b4f3e8737997888d7b96999423 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/IndexedColumnType.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: enum + * + * Description: The Enum IndexedColumnType. + * + */ + +public enum IndexedColumnType { + COLUMN, EXPRESSION +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/JobCancelStatus.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/JobCancelStatus.java new file mode 100644 index 0000000000000000000000000000000000000000..e131cced3c58f7ccf9f718f3af8f02a3ced26c87 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/JobCancelStatus.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: class + * + * Description: The Class JobCancelStatus. + * + */ + +public class JobCancelStatus implements IJobCancelStatus { + + private boolean isCancelled; + + @Override + public void setCancel(boolean isCancel) { + isCancelled = isCancel; + } + + @Override + public boolean getCancel() { + return isCancelled; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/LOADSTATUS.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/LOADSTATUS.java new file mode 100644 index 0000000000000000000000000000000000000000..ec9d0bf8f4070f9f0277fd32d0c98acc679af08a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/LOADSTATUS.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: enum + * + * Description: The Enum LOADSTATUS. + * + */ + +public enum LOADSTATUS { + NOT_LOADED, LOADED, LOADING_IN_PROGRESS, LOAD_FAILED +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/LoginNotificationManager.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/LoginNotificationManager.java new file mode 100644 index 0000000000000000000000000000000000000000..9d1337f64008692e62484dce6561cf17b6c1126c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/LoginNotificationManager.java @@ -0,0 +1,222 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.PasswordExpiryException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class LoginNotificationManager. + * + */ + +public class LoginNotificationManager { + + private Database database; + private static final Object LOGIN_NOTIF_LOCK = new Object(); + + /** + * The Constant LOGIN_NOTIFICATION. + */ + public static final String LOGIN_NOTIFICATION = "login notification"; + + /** + * The Constant LAST_LOGING_SUCCESS_DURATION. + */ + public static final String LAST_LOGING_SUCCESS_DURATION = "Time taken for success query execution for last login notification : "; + + private boolean cancelLastSuccessfulLoginRetrieval; + private boolean cancelFailureLoginAttempts; + + /** + * Instantiates a new login notification manager. + * + * @param db the db + */ + public LoginNotificationManager(Database db) { + this.database = db; + } + + /** + * Gets the last successfull login. + * + * @return the last successfull login + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public NotificationData getLastSuccessfullLogin() throws DatabaseOperationException, DatabaseCriticalException { + // to get the success login + String qry = "SELECT logintime, client_conninfo from login_audit_messages_pid(true)"; + ResultSet rs = null; + NotificationData notifData = null; + try { + + synchronized (LOGIN_NOTIF_LOCK) { + rs = database.getConnectionManager().executeLoginDetailsQuery(qry); + } + if (!cancelLastSuccessfulLoginRetrieval && rs.next()) { + notifData = DatabaseUtils.getNotifDataFromRS(rs); + } + if (cancelLastSuccessfulLoginRetrieval) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.USER_CANCEL)); + throw new DatabaseOperationException(IMessagesConstants.USER_CANCEL); + } + + } catch (SQLException sqlExcept) { + throw new DatabaseOperationException(IMessagesConstants.LAST_LOGING_FAILED_RETREIVAL_DATABASE); + } finally { + postLoginInfoRetrieval(rs, "Database : get last successful login failed."); + } + + return notifData; + } + + /** + * Post login info retrieval. + * + * @param rs the rs + * @param errorMsg the error msg + */ + private void postLoginInfoRetrieval(ResultSet rs, String errorMsg) { + if (null != rs) { + Statement stmt = null; + try { + stmt = rs.getStatement(); + + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Obtaining Statement failure.", exception); + } finally { + try { + rs.close(); + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error(errorMsg, exception); + } + try { + if (stmt != null) { + stmt.close(); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("ADAPTER: statement close returned exception.", exception); + } + } + } + + else { + MPPDBIDELoggerUtility.info("Failed to retrieve login information"); + } + cancelLastSuccessfulLoginRetrieval = false; + } + + /** + * Gets the failure login attempts. + * + * @return the failure login attempts + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public List getFailureLoginAttempts() + throws DatabaseCriticalException, DatabaseOperationException { + // to get the failure login + String qry = "SELECT logintime, client_conninfo from login_audit_messages_pid(false)"; + ResultSet rs = null; + + List failureNotifs = new ArrayList(MPPDBIDEConstants.RECORD_ARRAY_SIZE); + try { + synchronized (LOGIN_NOTIF_LOCK) { + rs = database.getConnectionManager().executeLoginDetailsQuery(qry); + } + while (!cancelFailureLoginAttempts && rs.next()) { + failureNotifs.add(DatabaseUtils.getNotifDataFromRS(rs)); + } + if (cancelFailureLoginAttempts) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.USER_CANCEL)); + throw new DatabaseOperationException(IMessagesConstants.USER_CANCEL); + } + } + + catch (SQLException e) { + throw new DatabaseOperationException(IMessagesConstants.LAST_LOGING_FAILED_RETREIVAL_DATABASE); + } finally { + postLoginInfoRetrieval(rs, "Database: getting failure login attempts failed."); + } + return failureNotifs; + } + + /** + * Cancel last successful login retrieval. + */ + public void cancelLastSuccessfulLoginRetrieval() { + + try { + cancelLastSuccessfulLoginRetrieval = true; + cancelFailureLoginAttempts = true; + synchronized (LOGIN_NOTIF_LOCK) { + database.getConnectionManager().cancelLoginQuery(); + } + + } catch (DatabaseCriticalException e) { + + e.getServerMessage(); + } catch (DatabaseOperationException e) { + + e.getServerMessage(); + } + + } + + /** + * Login on pswd expiry. + * + * @param db the db + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws PasswordExpiryException the password expiry exception + */ + public static void loginOnPswdExpiry(Database db) + throws DatabaseCriticalException, DatabaseOperationException, PasswordExpiryException { + float deadLine = 0; + boolean isLoginAllowedOnPasswordExpiry; + isLoginAllowedOnPasswordExpiry = SystemSetting.getInstance().isLoginAllowedOnPasswordExpiry(); + String deadlineStamp = DatabaseUtils.getDeadlineInfo(MPPDBIDEConstants.FETCH_COUNT, db); + + if (deadlineStamp != null) { + deadLine = Float.parseFloat(deadlineStamp); + } + if (deadLine < 0) { + // isPasswordExpired + if (!isLoginAllowedOnPasswordExpiry) { + db.setConnected(false); + throw new PasswordExpiryException( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_CIPHER_EXPIRED)); + } + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/Namespace.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/Namespace.java new file mode 100644 index 0000000000000000000000000000000000000000..4f00beea1ec3ab2ed578f744eb320d3e45155d49 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/Namespace.java @@ -0,0 +1,2696 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.io.Serializable; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.bl.export.EXPORTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.groups.DebugObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ForeignTableGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.OLAPObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ObjectList; +import org.opengauss.mppdbide.bl.serverdatacache.groups.SequenceObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.SynonymObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.TableObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.TriggerObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ViewObjectGroup; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: class Description: The Class Namespace. + */ + +public class Namespace extends BatchDropServerObject implements GaussOLAPDBMSObject, ILazyLoadObject, INamespace { + + private DebugObjectsManager dbgObjManager = null; + + private TableViewManager tblManager = null; + + private OLAPObjectGroup functions; + + /** + * The db. + */ + protected Database db; + + private TableObjectGroup tables; + + private ViewObjectGroup views; + + private ForeignTableGroup foreigntables; + + private SequenceObjectGroup sequence; + + private SynonymObjectGroup synonyms; + + private TriggerObjectGroup triggerGroups; + + private boolean isSynoymSupported = true; + + private ObjectList types; + + private LOADSTATUS loadStatus; + + private int defaultObjectLoadthreshold = 30000; + + private static final String LOAD_INDEXES = "SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, ci.relnamespace as " + + "namespaceid, " + "ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, " + + "i.indisexclusion as isexclusion," + + " i.indimmediate as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, " + + "i.indisready as isready, " + + "i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions, def.indexdef , " + + "def.tablespace " + "FROM pg_index i" + " LEFT JOIN pg_class t on (t.oid = i.indrelid) " + + "LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) " + + "LEFT JOIN pg_namespace ns on (ci.relnamespace = ns.oid) " + + "LEFT JOIN pg_indexes def on (ci.relname = def.indexname and ns.nspname = def.schemaname)" + + " WHERE t.relkind = 'r' and ci.relnamespace = %d"; + + private static final String QUERY_FOR_ALL_NORMAL_TABLES_BY_NAMESPACE_ID = "select tbl.oid as oid, tbl.relname relname, tbl.relpersistence relpersistence," + + "tbl.reloptions as reloptions, tbl.parttype as parttype, " + + "array_to_string(part.partkey,',') as partkey " + + "from pg_class tbl left join pg_partition part on(tbl.oid=part.parentid and part.parttype='r') " + + "where tbl.relkind = 'r' " + "and tbl.relnamespace = %d"; + + private static final String DROP_QUERY = "DROP SCHEMA IF EXISTS "; + + /** + * The Constant REFRESH_DBG_OBJ_QRY. + */ + public static final String REFRESH_DBG_OBJ_QRY = "SELECT pr.oid oid, pr.proname objname, " + + "pr.pronamespace namespace, " + + "pr.prorettype ret, pr.proallargtypes alltype,pr.pronargs nargs,pr.proargtypes argtype, " + + "pr.proargnames argname,pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, " + + "pr.proisstrict isstrict, pr.proretset retset, pr.procost procost, pr.prorows setrows, " + + "lng.lanname lang " + "FROM pg_proc pr " + "JOIN pg_language lng ON lng.oid=pr.prolang " + + "WHERE lng.lanname in ('plpgsql','sql','c') " + " and oid = %d"; + + /** + * The Constant QUERY_DBG_OBJ_PRIVILEGE. + */ + public static final String QUERY_DBG_OBJ_PRIVILEGE = " and has_function_privilege(pr.oid, 'EXECUTE')"; + private Set errorTableList; + + /** + * Gets the debug object group by type. + * + * @param type the type + * @return the debug object group by type + * @throws DatabaseOperationException the database operation exception + */ + public DebugObjectGroup getDebugObjectGroupByType(OBJECTTYPE type) throws DatabaseOperationException { + MPPDBIDELoggerUtility.debug("ConnectionProfile: get debug group by type."); + switch (type) { + case PLSQLFUNCTION: + case SQLFUNCTION: + case CFUNCTION: + case FUNCTION_GROUP: { + return (DebugObjectGroup) getFunctions(); + } + default: { + return null; + } + } + } + + /** + * Instantiates a new namespace. + * + * @param oid the oid + * @param name the name + * @param parentDb the parent db + */ + public Namespace(long oid, String name, Database parentDb) { + super(oid, name, OBJECTTYPE.NAMESPACE, parentDb != null ? parentDb.getPrivilegeFlag() : true); + this.db = parentDb; + this.dbgObjManager = new DebugObjectsManager(); + this.tblManager = new TableViewManager(); + + functions = new DebugObjectGroup(OBJECTTYPE.FUNCTION_GROUP, this); + + tables = new TableObjectGroup(OBJECTTYPE.TABLE_GROUP, this); + views = new ViewObjectGroup(this); + foreigntables = new ForeignTableGroup(OBJECTTYPE.FOREIGN_TABLE_GROUP, this); + this.types = new ObjectList(OBJECTTYPE.DATATYPE_GROUP, this); + sequence = new SequenceObjectGroup(OBJECTTYPE.SEQUENCE_GROUP, this); + synonyms = new SynonymObjectGroup(OBJECTTYPE.SYNONYM_GROUP, this); + triggerGroups = new TriggerObjectGroup(this); + errorTableList = new HashSet(); + setNotLoaded(); + updateObjectLoadLimit(); + } + + /** + * Update object load limit. + */ + private void updateObjectLoadLimit() { + if (db != null) { + int loadLimit = db.getLoadLimit(); + if (loadLimit >= 0) { + defaultObjectLoadthreshold = loadLimit; + } + } + } + + /** + * Gets the tables. + * + * @return the tables + */ + public TableObjectGroup getTables() { + return this.tables; + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + return this.db; + } + + /** + * Gets the functions. + * + * @return the functions + */ + public OLAPObjectGroup getFunctions() { + return this.functions; + } + + /** + * Gets the types. + * + * @return the types + */ + public ObjectList getTypes() { + return this.types; + } + + /** + * Clear collection. + * + * @param group the group + */ + private void clearCollection(OLAPObjectGroup group) { + if (group != null) { + getDatabase().getSearchPoolManager().clearObject(group); + group.clear(); + + } + } + + /** + * Clear all objects. + */ + public void clearAllObjects() { + clearCollection(functions); + clearCollection(tables); + clearCollection(views); + clearCollection(foreigntables); + clearCollection(sequence); + clearCollection(synonyms); + clearCollection(triggerGroups); + } + + /** + * Clear. + */ + public void clear() { + functions = null; + tables = null; + views = null; + foreigntables = null; + sequence = null; + synonyms = null; + triggerGroups = null; + } + + /** + * get debugobject by id. + * + * @param debugObjectId the debug object id + * @return the debug object by id + */ + public IDebugObject getDebugObjectById(long debugObjectId) { + MPPDBIDELoggerUtility.debug("ConnectionProfile: get debug object by id."); + DebugObjects object = functions.getObjectById(debugObjectId); + + return object; + } + + /** + * Check cancel status and abort. + * + * @param conn the conn + * @param status the status + * @throws DatabaseOperationException the database operation exception + */ + private void checkCancelStatusAndAbort(DBConnection conn, IJobCancelStatus status) + throws DatabaseOperationException { + if (status.getCancel() && null != db) { + try { + conn.cancelQuery(); + } catch (DatabaseCriticalException exception) { + MPPDBIDELoggerUtility.error("Namespace: check cancel status failed", exception); + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("Namespace: check cancel status failed", exception); + } + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.USER_CANCEL_MSG)); + throw new DatabaseOperationException(IMessagesConstants.USER_CANCEL_MSG); + } + } + + /** + * Gets the all objects on demand. + * + * @param conn the conn + * @return the all objects on demand + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void getAllObjectsOnDemand(DBConnection conn) throws DatabaseOperationException, DatabaseCriticalException { + if (getConnectionManager() != null) { + this.shallowLoadDebugableObjects(OBJECTTYPE.OBJECTTYPE_BUTT, getConnectionManager().getObjBrowserConn(), + true); + refreshAllMetadataInNamespaceOnDemand(conn); + refreshSequences(conn); + loadSynonyms(conn); + MPPDBIDELoggerUtility.perf("Namepsace Load done!!"); + setLoaded(); + } + } + + /** + * Refresh sequences. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void refreshSequences(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + MPPDBIDELoggerUtility.perf("Sequence: Stage : 1"); + clearCollection(this.sequence); + if (!privilegeFlag) { + SequenceMetadataUtil.fetchsequence(SequenceMetadataUtil.getAllSequencesByNamespaceIDQuery(this.getOid()), + conn, this.db); + } else { + SequenceMetadataUtil.fetchsequence( + SequenceMetadataUtil.getAllSequencesByNamespace(this.getName(), this.getOid()), conn, this.db); + } + MPPDBIDELoggerUtility.perf("Sequence: Stage : 2/2"); + MPPDBIDELoggerUtility.perf("Total sequences loaded :" + this.sequence.getSize()); + } + + /** + * Can load next level. + * + * @param grp the grp + * @return true, if successful + */ + @SuppressWarnings("rawtypes") + private boolean canLoadNextLevel(OLAPObjectGroup grp) { + return db.canChildObjectsLoaded() && (grp.getSize() > 0 && grp.getSize() < defaultObjectLoadthreshold) ? true + : false; + } + + /** + * Sets the level 3 loaded flag on all tables. + */ + protected void setLevel3LoadedFlagOnAllTables() { + NamespaceUtils.setLevel3LoadedFlag(this.tables.getSortedServerObjectList().iterator()); + NamespaceUtils.setLevel3LoadedFlag(this.foreigntables.getSortedServerObjectList().iterator()); + } + + @Override + public String toString() { + return "Namespace []"; + } + + /** + * Load partition next level. + * + * @param tableObjGrp the table obj grp + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void loadPartitionNextLevel(TableObjectGroup tableObjGrp, DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + PartitionTable.getColumnInfo(tableObjGrp, conn, this, getOid()); + + MPPDBIDELoggerUtility.perf("Partition Table: Stage : 4"); + PartitionTable.getPartitionConstraints(tableObjGrp, conn, this, getOid()); + MPPDBIDELoggerUtility.perf("Partition Table: Stage : 5"); + PartitionTable.getPartitionIndexes(tableObjGrp, conn, this, getOid()); + MPPDBIDELoggerUtility.perf("Partition Table: Stage : 6"); + PartitionTable.getPartitions(tableObjGrp, conn, this, getOid()); + } + + /** + * Expected to be called after refreshTableMetaData() only. Doesn't clear + * columns before fetching. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void fetchColumnMetaData(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + String qry1 = "WITH tbl AS ( select oid as tableid,relnamespace as namespaceid from pg_class where relnamespace = %d" + + "and relkind = 'r' and parttype ='n'), " + + "attr AS ( select c.attnum as columnidx,c.attname as name , pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns,c.atttypid as datatypeoid " + + ",c.attlen as length,c.atttypmod as precision,c.attndims as dimentions,c.attnotnull as notnull,c.atthasdef as isdefaultvalueavailable,c.attrelid as tableoid " + + "from pg_attribute c where c.attrelid in (select tableid from tbl) and c.attisdropped = 'f' and c.attnum > 0), dtype AS (select typ.typnamespace as dtns,oid from pg_type typ " + + "where typ.oid in (select datatypeoid from attr) ), attrdef AS ( select d.adsrc as default_value ,d.adbin as attDefStr ,adrelid,adnum from pg_attrdef d " + + "where d.adrelid in ( select oid from tbl) and d.adnum in( select columnidx from attr))" + + "select t.tableid as tableid ,t.namespaceid as namespaceid,c.columnidx,c.name,c.displaycolumns,c.datatypeoid,typ.dtns,c.length,c.precision,c.dimentions,c.notnull,c.isdefaultvalueavailable," + + "default_value, d.attDefStr FROM tbl t LEFT JOIN attr c ON(t.tableid = c.tableoid) LEFT JOIN attrdef d ON(t.tableid = d.adrelid AND c.columnidx = d.adnum) LEFT JOIN dtype typ ON (c.datatypeoid = typ.oid) ORDER BY t.tableid ,c.columnidx;"; + + ResultSet rs = conn.execSelectAndReturnRs(String.format(Locale.ENGLISH, qry1, this.getOid())); + try { + fetchColumnMetadataFromRs(rs); + + } catch (SQLException exp) { + GaussUtils.handleCriticalException(exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exp); + } finally { + conn.closeResultSet(rs); + } + } + + /** + * Fetch column metadata from rs. + * + * @param rs the rs + * @throws SQLException the SQL exception + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + private void fetchColumnMetadataFromRs(ResultSet rs) + throws SQLException, DatabaseOperationException, DatabaseCriticalException { + boolean hasNext = rs.next(); + while (hasNext) { + long tableId = rs.getLong("tableid"); + TableMetaData table = getTablesGroup().getObjectById(tableId); + long datatypeid = rs.getLong("datatypeoid"); + Namespace nameSpace = getDatabase().getNameSpaceById(rs.getLong("dtns")); + TypeMetaData typeMeta = TypeMetaData.getTypeById(nameSpace, datatypeid); + if (table == null) { + if (!privilegeFlag) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID)); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } + } else { + table.convertToColumnMetaData(rs, typeMeta); + } + + hasNext = rs.next(); + } + } + + /** + * Fetch table column meta data. + * + * @param tableOid the table oid + * @param tablegrp the tablegrp + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void fetchTableColumnMetaData(long tableOid, TableObjectGroup tablegrp, DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + String qry = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, " + + "c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, " + + "c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as " + + "precision, c.attndims as dimentions, " + + "c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, " + + "d.adbin as attDefStr " + + "from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.relkind = 'r') " + + "left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type " + + "typ on (c.atttypid = typ.oid) " + "where c.attisdropped = 'f' and c.attnum > 0 and t.oid = %d" + + " order by t.oid, c.attnum;"; + + ResultSet rs = conn.execSelectAndReturnRs(String.format(Locale.ENGLISH, qry, tableOid)); + try { + boolean hasNext = rs.next(); + while (hasNext) { + convertToColumnMetaData(tablegrp, rs); + hasNext = rs.next(); + } + } catch (SQLException exp) { + GaussUtils.handleCriticalException(exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exp); + } finally { + conn.closeResultSet(rs); + } + } + + /** + * Convert to column meta data. + * + * @param tablegrp the tablegrp + * @param rs the rs + * @throws SQLException the SQL exception + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + private void convertToColumnMetaData(TableObjectGroup tablegrp, ResultSet rs) + throws SQLException, DatabaseOperationException, DatabaseCriticalException { + long tableId = rs.getLong("tableid"); + TableMetaData tbl = tablegrp.getObjectById(tableId); + long datatypeid = rs.getLong("datatypeoid"); + + Namespace dtNamspace = getDatabase().getNameSpaceById(rs.getLong("dtns")); + + TypeMetaData type = TypeMetaData.getTypeById(dtNamspace, datatypeid); + if (tbl == null) { + if (!privilegeFlag) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID)); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } + } else { + tbl.convertToColumnMetaData(rs, type); + } + } + + /** + * Expected to be called after refreshTableMetaData. So will not clear + * constraints. + * + * @param conn the conn + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + private void fetchAllConstraints(DBConnection conn) throws DatabaseOperationException, DatabaseCriticalException { + MPPDBIDELoggerUtility.perf("Loading Table constraints start"); + String qry = "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, " + + "c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, " + + "c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, " + + "c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, " + + "c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, " + + "c.confkey as fkeycolumnlist, " + "pg_get_constraintdef(c.oid) as const_def " + + "FROM pg_constraint c join pg_class cl on c.conrelid = cl.oid where c.connamespace=%d" + + " and cl.parttype not in ('p','v')" + " and c.conrelid <> 0" + ';'; + ResultSet rs = conn.execSelectAndReturnRs(String.format(Locale.ENGLISH, qry, getOid())); + boolean hasNext = false; + + try { + hasNext = rs.next(); + while (hasNext) { + long namespaceid = rs.getLong("namespaceid"); + Namespace ns = getDatabase().getNameSpaceById(namespaceid); + + long tableId = rs.getLong("tableid"); + + TableMetaData tbl = ns.getTablesGroup().getObjectById(tableId); + TableMetaData fkeyTable = ns.getTablesGroup().getObjectById(rs.getLong("fkeytableId")); + if (tbl == null) { + if (!ns.getPrivilegeFlag()) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID)); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } + } else { + tbl.addConstraint(rs, ns, fkeyTable); + } + + hasNext = rs.next(); + } + } catch (SQLException exp) { + GaussUtils.handleCriticalException(exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exp); + } finally { + conn.closeResultSet(rs); + MPPDBIDELoggerUtility.perf("Loading Table constraints ends"); + } + } + + /** + * Fetch constraint for table. + * + * @param tbl the tbl + * @param tblgrp the tblgrp + * @param conn the conn + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void fetchConstraintForTable(TableMetaData tbl, TableObjectGroup tblgrp, DBConnection conn) + throws DatabaseOperationException, DatabaseCriticalException { + String qry = "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, " + + "c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, " + + "c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, " + + "c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, " + + "c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, " + + "c.confkey as fkeycolumnlist, pg_get_constraintdef(c.oid) as const_def " + + "FROM pg_constraint c where c.conrelid = %d" + ';'; + + ResultSet rs = conn.execSelectAndReturnRs(String.format(Locale.ENGLISH, qry, tbl.getOid())); + boolean hasNext = false; + TableMetaData fkeyTable; + + try { + hasNext = rs.next(); + while (hasNext) { + long namespaceid = rs.getLong("namespaceid"); + Namespace ns = getDatabase().getNameSpaceById(namespaceid); + fkeyTable = tblgrp.getObjectById(rs.getLong("fkeytableId")); + tbl.addConstraint(rs, ns, fkeyTable); + hasNext = rs.next(); + } + } catch (SQLException exp) { + GaussUtils.handleCriticalException(exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exp); + } finally { + conn.closeResultSet(rs); + } + } + + /** + * Expected to be called after refreshTableMetaData. So will not clear + * Indexes. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void fetchAllIndexes(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + MPPDBIDELoggerUtility.perf("Loading Indexes starts"); + String qry = String.format(Locale.ENGLISH, LOAD_INDEXES + + " and ci.parttype not in ('p','v') and ci.relkind not in ('I');", + getOid()); + ResultSet resultSet = conn.execSelectAndReturnRs(qry); + boolean hasNext = false; + + try { + hasNext = resultSet.next(); + while (hasNext) { + Namespace ns = this.db.getNameSpaceById(resultSet.getLong("namespaceid")); + TableMetaData table = ns.getTablesGroup().getObjectById(resultSet.getLong("tableId")); + if (table == null) { + if (!privilegeFlag) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID)); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } + } else { + table.addIndex(resultSet); + } + hasNext = resultSet.next(); + } + } catch (SQLException exp) { + GaussUtils.handleCriticalException(exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exp); + } finally { + conn.closeResultSet(resultSet); + MPPDBIDELoggerUtility.perf("Loading Indexes ends"); + } + } + + /** + * Gets the tables group. + * + * @return the tables group + */ + public TableObjectGroup getTablesGroup() { + return this.tables; + } + + /** + * Gets the view group. + * + * @return the view group + */ + public ViewObjectGroup getViewGroup() { + return this.views; + } + + /** + * Gets the sequence group. + * + * @return the sequence group + */ + public SequenceObjectGroup getSequenceGroup() { + return this.sequence; + } + + /** + * Gets the synonym group. + * + * @return the synonym group + */ + public SynonymObjectGroup getSynonymGroup() { + return this.synonyms; + } + + /** + * description: gets the trigger group + * + * @return TriggerObjectGroup the trigger object group + */ + public TriggerObjectGroup getTriggerObjectGroup() { + return this.triggerGroups; + } + + /** + * Gets the type by name. + * + * @param name the name + * @return the type by name + */ + public TypeMetaData getTypeByName(String name) { + ServerObject obj = this.types.get(name); + + // servObj will definately be namespace, but findbugs doesn't detect + // generics. So below fix + if (obj instanceof TypeMetaData) { + return (TypeMetaData) obj; + } + + return null; + } + + /** + * Gets the type by oid. + * + * @param oid the oid + * @return the type by oid + */ + public TypeMetaData getTypeByOid(long oid) { + ServerObject obj = this.types.getObjectById(oid); + + // servObj will definately be namespace, but findbugs doesn't detect + // generics. So below fix + if (obj instanceof TypeMetaData) { + return (TypeMetaData) obj; + } + + return null; + } + + @Override + public int hashCode() { + return MPPDBIDEConstants.PRIME_31 + Long.valueOf(getOid()).hashCode() + getDatabase().hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + + if (obj == null) { + return false; + } + + if (!(obj instanceof Namespace)) { + return false; + } + + Namespace other = (Namespace) obj; + if (getOid() == other.getOid() && getDatabase().equals(other.getDatabase())) { + return true; + + } + return false; + } + + /** + * Adds the table to search pool. + * + * @param table the table + */ + public void addTableToSearchPool(TableMetaData table) { + getTablesGroup().addToGroup(table); + getDatabase().getSearchPoolManager().addTableToSearchPool(table); + + } + + /** + * Adds the table to given search pool. + * + * @param table the table + */ + public void addTableToGivenSearchPool(TableMetaData table) { + if (table instanceof ForeignPartitionTable) { + getForeignTablesGroup().addToGroup(table); + } else { + getTablesGroup().addToGroup(table); + } + getDatabase().getSearchPoolManager().addTableToSearchPool(table); + + } + + /** + * Adds the debug object to search pool. + * + * @param dbgObj the dbg obj + */ + public void addDebugObjectToSearchPool(DebugObjects dbgObj) { + DebugObjectGroup objGroup = (DebugObjectGroup) getFunctions(); + objGroup.addToGroup(dbgObj); + getDatabase().getSearchPoolManager().addDebugObjectToSearchPool(dbgObj); + } + + /** + * Find prefix matching child objects. + * + * @param prefix the prefix + * @return the sorted map + */ + public SortedMap findPrefixMatchingChildObjects(String prefix) { + SortedMap retObj = new TreeMap(); + retObj.putAll(findMatchingTables(prefix)); + retObj.putAll(findMatchingForeignTables(prefix)); + retObj.putAll(findMatchingDebugObjects(prefix)); + retObj.putAll(findMatchingViews(prefix)); + retObj.putAll(findMatchingSequences(prefix)); + retObj.putAll(findMatchingSynonyms(prefix)); + return retObj; + } + + /** + * Find matching hyperlink. + * + * @param prefix the prefix + * @return the sorted map + */ + public SortedMap findMatchingHyperlink(String prefix) { + SortedMap retObj = new TreeMap(); + retObj.putAll(findMatchingTablesHyperLink(prefix)); + retObj.putAll(findMatchingDebugObjectForsHyperLink(prefix)); + retObj.putAll(findMatchingViewsForHyperLink(prefix)); + return retObj; + } + + /** + * Find matching debug object fors hyper link. + * + * @param prefix the prefix + * @return the sorted map + */ + private SortedMap findMatchingDebugObjectForsHyperLink(String prefix) { + return functions.getMatchingHyperLink(prefix); + } + + /** + * Find matching tables hyper link. + * + * @param prefix the prefix + * @return the sorted map + */ + private SortedMap findMatchingTablesHyperLink(String prefix) { + return tables.getMatchingTablesHyperLink(prefix); + } + + /** + * Find matching foreign tables. + * + * @param prefix the prefix + * @return the sorted map + */ + private SortedMap findMatchingForeignTables(String prefix) { + return foreigntables.getMatching(prefix); + } + + /** + * Find matching views for hyper link. + * + * @param prefix the prefix + * @return the sorted map + */ + private SortedMap findMatchingViewsForHyperLink(String prefix) { + return views.getMatchingTablesHyperLink(prefix); + } + + /** + * Find matching tables. + * + * @param prefix the prefix + * @return the sorted map + */ + private SortedMap findMatchingTables(String prefix) { + return tables.getMatching(prefix); + } + + /** + * Find matching views. + * + * @param prefix the prefix + * @return the map + */ + private Map findMatchingViews(String prefix) { + return views.getMatching(prefix); + } + + /** + * Find matching sequences. + * + * @param prefix the prefix + * @return the sorted map + */ + private SortedMap findMatchingSequences(String prefix) { + return sequence.getMatching(prefix); + } + + /** + * Find matching synonyms. + * + * @param prefix the prefix + * @return the sorted map + */ + private SortedMap findMatchingSynonyms(String prefix) { + return synonyms.getMatching(prefix); + } + + /** + * Find matching trigger. + * + * @param String the prefix + * @return SortedMap the sorted map + */ + private SortedMap findMatchingTrigger(String prefix) { + return triggerGroups.getMatching(prefix); + } + + @Override + public String getSearchName() { + return getName() + " - " + getTypeLabel(); + } + + /** + * Find matching debug objects. + * + * @param prefix the prefix + * @return the sorted map + */ + private SortedMap findMatchingDebugObjects(String prefix) { + return functions.getMatching(prefix); + } + + /** + * Adds the view to search pool. + * + * @param view the view + */ + public void addViewInSearchPool(ViewMetaData view) { + db.getSearchPoolManager().addviewToSearchPool(view); + } + + /** + * Adds the views to group. + * + * @param view the view + */ + public void addViewsToGroup(ViewMetaData view) { + views.addToGroup(view); + } + + /** + * Adds the synonym to group. + * + * @param synonym the synonym + */ + public void addSynonymToGroup(SynonymMetaData synonym) { + synonyms.addToGroup(synonym); + } + + public void addTrigerToGroup(TriggerMetaData trigger) { + triggerGroups.addToGroup(trigger); + } + + /** + * Fetch level 2 view column info. + * + * @param conn the conn + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void fetchLevel2ViewColumnInfo(DBConnection conn) + throws DatabaseOperationException, DatabaseCriticalException { + int clmCount = 0; + String query = " WITH tbl AS ( select oid as viewid,relnamespace as namespaceid from pg_class where relnamespace =%d" + + " and relkind = 'v'), attr AS ( select c.attnum as columnidx," + + "c.attname as name , pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns,c.atttypid as datatypeoid ,c.attlen as length,c.atttypmod as precision," + + "c.attndims as dimentions,c.attnotnull as notnull,c.atthasdef as isdefaultvalueavailable,c.attrelid as tableoid from pg_attribute c where c.attrelid in (select viewid from tbl) " + + "and c.attisdropped = 'f' and c.attnum > 0), dtype AS (select typ.typnamespace as dtns,oid from pg_type typ where typ.oid in (select datatypeoid from attr) ), " + + "attrdef AS ( select d.adsrc as default_value ,d.adbin as attDefStr ,adrelid,adnum from pg_attrdef d where d.adrelid in ( select oid from tbl) and d.adnum in( select columnidx from attr))" + + " select t.viewid as viewid ,t.namespaceid as namespaceid,c.columnidx,c.name,c.displaycolumns,c.datatypeoid,typ.dtns,c.length,c.precision,c.dimentions,c.notnull,c.isdefaultvalueavailable," + + "default_value, d.attDefStr FROM tbl t LEFT JOIN attr c ON(t.viewid = c.tableoid) LEFT JOIN attrdef d ON(t.viewid = d.adrelid AND c.columnidx = d.adnum) LEFT JOIN dtype typ ON (c.datatypeoid = typ.oid) ORDER BY t.viewid ,c.columnidx;"; + + ResultSet rs = conn.execSelectAndReturnRs(String.format(Locale.ENGLISH, query, this.getOid())); + try { + boolean hasNext = rs.next(); + while (hasNext) { + long viewId = rs.getLong("viewid"); + long datatypeid = rs.getLong("datatypeoid"); + + Object viewObj = getViewGroup().getObjectById(viewId); + if (null == viewObj) { + if (!privilegeFlag) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID)); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } + } else { + ViewMetaData view = (ViewMetaData) viewObj; + Namespace dtNamspace = this.db.getNameSpaceById(rs.getLong("dtns")); + TypeMetaData type = TypeMetaData.getTypeById(dtNamspace, datatypeid); + + view.addViewColumn(rs, type); + } + clmCount++; + hasNext = rs.next(); + } + } catch (SQLException exp) { + GaussUtils.handleCriticalException(exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exp); + } finally { + if (MPPDBIDELoggerUtility.isTraceEnabled()) { + MPPDBIDELoggerUtility + .trace("Level 3 object loaded for columns :" + clmCount + " Source :Selected Namespace"); + } + conn.closeResultSet(rs); + } + } + + /** + * Fetch view column info. + * + * @param view the view + * @param conn the conn + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void fetchViewColumnInfo(ViewMetaData view, DBConnection conn) + throws DatabaseOperationException, DatabaseCriticalException { + String query = "select v.oid as viewid, v.relnamespace as namespaceid, c.attnum as columnidx, " + + "c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, " + + "c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, " + + "c.atttypmod as precision, c.attndims as dimentions, " + + "c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, " + + "d.adsrc as default_value, d.adbin as attDefStr " + "from pg_class v " + + "left join pg_attribute c on (v.oid = c.attrelid and v.relkind = 'v') " + + "left join pg_attrdef d on (v.oid = d.adrelid and c.attnum = d.adnum) " + + "left join pg_type typ on (c.atttypid = typ.oid) " + "where c.attisdropped = 'f' and c.attnum > 0 " + + "and v.oid = %d" + " order by v.oid, c.attnum"; + + ResultSet rs = conn.execSelectAndReturnRs(String.format(Locale.ENGLISH, query, view.getOid())); + try { + ViewMetaData viewObj = getViewGroup().getObjectById(view.getOid()); + if (null != viewObj) { + addViewColumnInfo(view, rs, viewObj); + } else { + if (!privilegeFlag) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID)); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } + } + } catch (SQLException exp) { + GaussUtils.handleCriticalException(exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exp); + } finally { + conn.closeResultSet(rs); + } + } + + /** + * Adds the view column info. + * + * @param view the view + * @param rs the rs + * @param viewObj the view obj + * @throws SQLException the SQL exception + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + private void addViewColumnInfo(ViewMetaData view, ResultSet rs, ViewMetaData viewObj) + throws SQLException, DatabaseOperationException, DatabaseCriticalException { + boolean hasNext = rs.next(); + if (hasNext) { + long datatypeid = 0; + Namespace dtNamspace = null; + TypeMetaData type = null; + while (hasNext) { + datatypeid = rs.getLong("datatypeoid"); + dtNamspace = this.db.getNameSpaceById(rs.getLong("dtns")); + type = TypeMetaData.getTypeById(dtNamspace, datatypeid); + + viewObj.addViewColumn(rs, type); + + hasNext = rs.next(); + } + // successfully loaded all column info. Setting l3 loaded. + viewObj.setLevel3Loaded(true); + } else { + view.setValid(false); + } + } + + /** + * Gets the server name. + * + * @return the server name + */ + public String getServerName() { + return db.getServerName(); + } + + /** + * Gets the database name. + * + * @return the database name + */ + public String getDatabaseName() { + return db.getName(); + } + + /** + * Adds the view. + * + * @param view the view + */ + public void addView(ViewMetaData view) { + this.views.addToGroup(view); + this.db.getSearchPoolManager().addviewToSearchPool(view); + } + + /** + * Adds the sequence. + * + * @param seq the seq + */ + public void addSequence(SequenceMetadata seq) { + this.sequence.addToGroup(seq); + } + + /** + * Gets the server. + * + * @return the server + */ + public Server getServer() { + return getDatabase().getServer(); + } + + /** + * Belongs to. + * + * @param database the database + * @param server the server + * @return true, if successful + */ + public boolean belongsTo(Database database, Server server) { + return this.getDatabase().belongsTo(database, server); + } + + /** + * Gets the foreign tables group. + * + * @return the foreign tables group + */ + public ForeignTableGroup getForeignTablesGroup() { + return foreigntables; + } + + /** + * Gets the label. + * + * @return the label + */ + public String getLabel() { + String sizeStr = "..."; + if (isLoaded()) { + int size = getFunctions().getSize() + getTablesGroup().getSize() + getViewGroup().getSize() + + getForeignTablesGroup().getSize() + getSequenceGroup().getSize() + getSynonymGroup().getSize(); + sizeStr = Integer.toString(size); + } + + return getName() + " (" + sizeStr + ") "; + } + + @Override + public String getDisplayLabel() { + return this.getLabel(); + } + + @Override + public Object[] getChildren() { + Collection children = new ArrayList(5); + children.add(this.getFunctions()); + children.add(this.getTablesGroup()); + children.add(this.getViewGroup()); + children.add(this.getForeignTablesGroup()); + children.add(this.getSequenceGroup()); + if (isSynoymSupported()) { + children.add(this.getSynonymGroup()); + } + children.add(this.getTriggerObjectGroup()); + return children.toArray(); + } + + /** + * Sets the load failed. + */ + public void setLoadFailed() { + ILazyLoadObject.super.setLoadFailed(); + removefromSearchPath(); + } + + /** + * Removefrom search path. + */ + private void removefromSearchPath() { + db.getSearchPathHelper().removeFromSearchPath(this.getName()); + } + + /** + * Exec rename table. + * + * @param table the table + * @param newName the new name + * @param conn the conn + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void execRenameTable(TableMetaData table, String newName, DBConnection conn) + throws DatabaseOperationException, DatabaseCriticalException { + table.execRename(newName, conn); + refreshTable(table, conn, true); + } + + /** + * Adds the tables to group. + * + * @param table the table + * @param conn the conn + * @param tabletype the tabletype + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void addTablesToGroup(TableMetaData table, DBConnection conn, OBJECTTYPE tabletype) + throws DatabaseCriticalException, DatabaseOperationException { + switch (tabletype) { + case PARTITION_TABLE: { + if (table instanceof PartitionTable) { + if (table instanceof ForeignPartitionTable) { + table.addForeignTableToGroup(table); + loadPartitionNextLevel(foreigntables, conn); + } else { + table.addTableToGroup(table); + loadPartitionNextLevel(tables, conn); + } + } + break; + } + case FOREIGN_TABLE: { + table.addForeignTableToGroup(table); + break; + } + default: { + table.addTableToGroup(table); + table.refreshTableDetails(conn); + break; + } + } + } + + /** + * Adds the foreign table to group. + * + * @param table the table + */ + public void addForeignTableToGroup(TableMetaData table) { + getForeignTablesGroup().addToGroup(table); + } + + /** + * Adds the table to group. + * + * @param table the table + */ + public void addTableToGroup(TableMetaData table) { + getTablesGroup().addToGroup(table); + getDatabase().getSearchPoolManager().addTableToSearchPool(table); + } + + /** + * Removes the table. + * + * @param table the table + * @param tableOid the table oid + * @return the objecttype + */ + private OBJECTTYPE removeTable(TableMetaData table, long tableOid) { + table.clearDetailsCached(); + + getDatabase().getSearchPoolManager().removeTableFromSearchPool(this.tables.getObjectById(tableOid)); + OBJECTTYPE tabletype = table.getType(); + + switch (tabletype) { + case PARTITION_TABLE: { + if (table instanceof PartitionTable) { + if (table instanceof ForeignPartitionTable) { + this.getForeignTablesGroup().removeFromGroup(tableOid); + } else { + this.getTablesGroup().removeFromGroup(tableOid); + } + } + break; + } + case FOREIGN_TABLE: { + this.getForeignTablesGroup().removeFromGroup(tableOid); + break; + } + default: { + this.getTablesGroup().removeFromGroup(tableOid); + break; + } + } + return tabletype; + } + + /** + * Gets the updated namespace. + * + * @param resultSet the result set + * @return the updated namespace + * @throws DatabaseOperationException the database operation exception + * @throws SQLException the SQL exception + */ + private Namespace getUpdatedNamespace(ResultSet resultSet) throws DatabaseOperationException, SQLException { + long namespaceID = resultSet.getLong("relnamespace"); + Namespace namespace = this.getDatabase().getNameSpaceById(namespaceID); + return namespace; + } + + /** + * Gets the children size. + * + * @return the children size + */ + public int getChildrenSize() { + return getFunctions().getSize() + getTablesGroup().getSize() + getViewGroup().getSize() + + getForeignTablesGroup().getSize() + getSequenceGroup().getSize() + getSynonymGroup().getSize() + + getTriggerObjectGroup().getSize(); + } + + /** + * Gets the object browser label. + * + * @return the object browser label + */ + public String getObjectBrowserLabel() { + String sizeStr = ""; + if (isLoaded()) { + int size = getChildrenSize(); + sizeStr = " (" + Integer.toString(size) + ") "; + } + + return getName() + sizeStr; + } + + /** + * Gets the parent. + * + * @return the parent + */ + public Object getParent() { + return this.getDatabase(); + } + + /** + * Gets the searched table. + * + * @param tblId the tbl id + * @param tblName the tbl name + * @return the searched table + */ + public TableMetaData getSearchedTable(int tblId, String tblName) { + TableMetaData tbl = getTablesGroup().getObjectById(tblId); + if (null == tbl) { + tbl = new TableMetaData(tblId, tblName, this, null, OBJECTTYPE.TABLEMETADATA); + addTableToSearchPool(tbl); + } + return tbl; + } + + /** + * Gets the searched partition table. + * + * @param tblId the tbl id + * @param tblName the tbl name + * @return the searched partition table + */ + public PartitionTable getSearchedPartitionTable(int tblId, String tblName) { + PartitionTable parTable = (PartitionTable) getTablesGroup().getObjectById(tblId); + if (null == parTable) { + parTable = (PartitionTable) getForeignTablesGroup().getObjectById(tblId); + } + if (null == parTable) { + parTable = new PartitionTable(this); + parTable.setOid(tblId); + parTable.setName(tblName); + addTableToGroup(parTable); + } + return parTable; + } + + /** + * Gets the searched foreign table. + * + * @param tblId the tbl id + * @param ftOptions the ft options + * @return the searched foreign table + */ + public TableMetaData getSearchedForeignTable(int tblId, String ftOptions) { + TableMetaData forTable = getForeignTablesGroup().getObjectById(tblId); + if (null == forTable) { + if (ftOptions.contains("gsfs")) { + forTable = new ForeignTable(this, OBJECTTYPE.FOREIGN_TABLE_GDS); + } else if (ftOptions.contains("format=orc")) { + forTable = new ForeignTable(this, OBJECTTYPE.FOREIGN_TABLE_HDFS); + } + if (null != forTable) { + addForeignTableToGroup(forTable); + } + } + return forTable; + } + + /** + * Gets the searched sequence. + * + * @param tblId the tbl id + * @param tblName the tbl name + * @return the searched sequence + */ + public SequenceMetadata getSearchedSequence(int tblId, String tblName) { + SequenceMetadata seq = getSequenceGroup().getObjectById(tblId); + if (null == seq) { + seq = SequenceMetadataUtil.getSearchedSequence(this, tblId, tblName); + addSequence(seq); + } + return seq; + } + + /** + * Gets the searched view. + * + * @param tblId the tbl id + * @param tblName the tbl name + * @return the searched view + */ + public ViewMetaData getSearchedView(int tblId, String tblName) { + ViewMetaData viewTable = getViewGroup().getObjectById(tblId); + if (null == viewTable) { + viewTable = new ViewMetaData(tblId, tblName, this, getDatabase()); + addViewsToGroup(viewTable); + } + return viewTable; + } + + /** + * Gets the searched synonym. + * + * @param tblId the tbl id + * @param tblName the tbl name + * @return the searched synonym + */ + public SynonymMetaData getSearchedSynonym(int tblId, String tblName) { + SynonymMetaData synonym = getSynonymGroup().getObjectById(tblId); + if (null == synonym) { + synonym = new SynonymMetaData(tblName, this); + addSynonymToGroup(synonym); + } + return synonym; + } + + /** + * Gets the searched triggers. + * + * @param tblId the tbl id + * @param tblName the tbl name + * @return the searched trigger. + */ + public TriggerMetaData getSearchedTrigger(int tblId, String tblName) { + TriggerMetaData triggerMetaData = getTriggerObjectGroup().getObjectById(tblId); + if (triggerMetaData == null) { + triggerMetaData = new TriggerMetaData(tblId, tblName); + addTrigerToGroup(triggerMetaData); + } + return triggerMetaData; + } + + + /** + * Find exact matching child objects. + * + * @param prefix the prefix + * @return the sorted map + */ + public SortedMap findExactMatchingChildObjects(String prefix) { + SortedMap retObj = new TreeMap(); + retObj.putAll(findExactMatchingTables(prefix)); + retObj.putAll(findExactMatchingForeignTables(prefix)); + retObj.putAll(findExactMatchingDebugObjects(prefix)); + retObj.putAll(findExactMatchingViews(prefix)); + retObj.putAll(findExactMatchingSequences(prefix)); + retObj.putAll(findExactMatchingSynonyms(prefix)); + retObj.putAll(findExactMatchingTrigger(prefix)); + return retObj; + } + + /** + * Find exact matching sequences. + * + * @param prefix the prefix + * @return the sorted map + */ + private SortedMap findExactMatchingSequences(String prefix) { + return sequence.getMatchingHyperLink(prefix); + } + + /** + * Find exact matching synonyms. + * + * @param prefix the prefix + * @return the sorted map + */ + private SortedMap findExactMatchingSynonyms(String prefix) { + return synonyms.getMatchingHyperLink(prefix); + } + + /** + * Find exact matching trigger + * + * @param String the prefix + * @return SortedMap the sorted map + */ + private SortedMap findExactMatchingTrigger(String prefix) { + return triggerGroups.getMatchingHyperLink(prefix); + } + + /** + * Find exact matching views. + * + * @param prefix the prefix + * @return the sorted map + */ + private SortedMap findExactMatchingViews(String prefix) { + return views.getMatchingHyperLink(prefix); + } + + /** + * Find exact matching debug objects. + * + * @param prefix the prefix + * @return the sorted map + */ + private SortedMap findExactMatchingDebugObjects(String prefix) { + return functions.getMatchingHyperLink(prefix); + } + + /** + * Find exact matching foreign tables. + * + * @param prefix the prefix + * @return the sorted map + */ + private SortedMap findExactMatchingForeignTables(String prefix) { + return foreigntables.getMatchingHyperLink(prefix); + } + + /** + * Find exact matching tables. + * + * @param prefix the prefix + * @return the sorted map + */ + public SortedMap findExactMatchingTables(String prefix) { + return tables.getMatchingHyperLink(prefix); + } + + /** + * Find all child objects. + * + * @return the sorted map + */ + public SortedMap findAllChildObjects() { + SortedMap retObj = new TreeMap(); + retObj.putAll(findMatchingTables("")); + retObj.putAll(findMatchingForeignTables("")); + retObj.putAll(findMatchingDebugObjects("")); + retObj.putAll(findMatchingViews("")); + retObj.putAll(findMatchingSequences("")); + retObj.putAll(findMatchingSynonyms("")); + retObj.putAll(findMatchingTrigger("")); + return retObj; + } + + /** + * Gets the all tables for namespace. + * + * @return the all tables for namespace + */ + public ArrayList getAllTablesForNamespace() { + ArrayList tablesList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + tablesList.addAll(tables.getSortedServerObjectList()); + tablesList.addAll(foreigntables.getSortedServerObjectList()); + Collections.sort(tablesList, new NamespaceComparator()); + return tablesList; + } + + /** + * Title: class Description: The Class NamespaceComparator. + * + */ + private static class NamespaceComparator implements Comparator, Serializable { + + private static final long serialVersionUID = 1L; + + @Override + public int compare(TableMetaData o1, TableMetaData o2) { + if (o1.getName().equalsIgnoreCase(o2.getName())) { + if (!o1.getName().equals(o2.getName())) { + return o1.getName().compareTo(o2.getName()); + } + } + return o1.getName().compareToIgnoreCase(o2.getName()); + } + } + + @Override + public String getDropQuery(boolean isCascade) { + StringBuilder query = new StringBuilder(DROP_QUERY); + query.append(this.getDisplayName()); + + if (isCascade) { + query.append(MPPDBIDEConstants.CASCADE); + } + + return query.toString(); + } + + /** + * Removes the. + * + * @param obj the obj + */ + public void remove(ServerObject obj) { + if (obj instanceof ViewMetaData) { + removeFromCollection(views, obj); + } else if (obj instanceof SequenceMetadata) { + removeFromCollection(sequence, obj); + } else if (obj instanceof DebugObjects) { + removeFromCollection(functions, obj); + } else if (obj instanceof ForeignTable || obj instanceof ForeignPartitionTable) { + removeFromCollection(foreigntables, obj); + } else if (obj instanceof TableMetaData || obj instanceof PartitionTable) { + removeFromCollection(tables, obj); + } else if (obj instanceof SynonymMetaData) { + removeFromCollection(synonyms, obj); + } else if (obj instanceof TriggerMetaData) { + removeFromCollection(triggerGroups, obj); + } + } + + /** + * Removes the from collection. + * + * @param group the group + * @param obj the obj + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + private void removeFromCollection(OLAPObjectGroup group, ServerObject obj) { + if (group != null) { + group.remove(obj); + } + } + + @Override + public boolean isExportAllowed(EXPORTTYPE exportType) { + return true; + } + + @Override + public void getAllObjects(DBConnection conn, JobCancelStatus status) + throws DatabaseOperationException, DatabaseCriticalException { + checkCancelStatusAndAbort(conn, status); + shallowLoadDebugableObjects(OBJECTTYPE.OBJECTTYPE_BUTT, db.getConnectionManager().getObjBrowserConn(), false); + checkCancelStatusAndAbort(conn, status); + checkCancelStatusAndAbort(conn, status); + refreshAllViewsInNamespace(conn); + checkCancelStatusAndAbort(conn, status); + refreshTableHirarchy(conn); + checkCancelStatusAndAbort(conn, status); + refreshAllForeignTableMetadataInNamespace(conn); + checkCancelStatusAndAbort(conn, status); + checkCancelStatusAndAbort(conn, status); + refreshSequences(conn); + loadSynonyms(conn); + loadTriggers(conn); + MPPDBIDELoggerUtility.perf(this.getDisplayLabel() + " - Load done!!"); + checkCancelStatusAndAbort(conn, status); + setLevel3LoadedFlagOnAllTables(); + setLoaded(); + } + + /** + * Refresh all views in namespace. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void refreshAllViewsInNamespace(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + tblManager.refreshAllViewsInNamespace(conn); + } + + /** + * Refresh table hirarchy. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void refreshTableHirarchy(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + tblManager.refreshTableHirarchy(conn); + } + + /** + * Refresh all foreign table metadata in namespace. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void refreshAllForeignTableMetadataInNamespace(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + tblManager.refreshAllForeignTableMetadataInNamespace(conn); + } + + /** + * Refresh all metadata in namespace on demand. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void refreshAllMetadataInNamespaceOnDemand(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + tblManager.refreshAllMetadataInNamespaceOnDemand(conn); + } + + /** + * Refresh all table metadata in namespace. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void refreshAllTableMetadataInNamespace(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + tblManager.refreshAllTableMetadataInNamespace(conn); + } + + /** + * Refresh view. + * + * @param view the view + * @param conn the conn + * @param isRenameFlow the is rename flow + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void refreshView(ViewMetaData view, DBConnection conn, boolean isRenameFlow) + throws DatabaseOperationException, DatabaseCriticalException { + tblManager.refreshView(view, conn, isRenameFlow); + } + + /** + * Refresh table. + * + * @param table the table + * @param conn the conn + * @param isRenameFlow the is rename flow + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void refreshTable(TableMetaData table, DBConnection conn, boolean isRenameFlow) + throws DatabaseCriticalException, DatabaseOperationException { + tblManager.refreshTable(table, conn, isRenameFlow); + } + + /** + * Title: class Description: The Class TableViewManager. + */ + private class TableViewManager { + + /** + * Refresh table. + * + * @param table the table + * @param conn the conn + * @param isRenameFlow the is rename flow + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void refreshTable(TableMetaData table, DBConnection conn, boolean isRenameFlow) + throws DatabaseCriticalException, DatabaseOperationException { + long tableOid = table.getOid(); + String qry = table.getSQLForTableMetaDatabyOid(tableOid, isRenameFlow); + ResultSet resultSet = conn.execSelectAndReturnRs(qry); + OBJECTTYPE tabletype = removeTable(table, tableOid); + try { + boolean hasnext = resultSet.next(); + if (hasnext) { + Namespace ns = getUpdatedNamespace(resultSet); + table.setTableNamespace(ns); + table.fillTableMetaFromRS(resultSet); + if (table.isValid()) { + addTablesToGroup(table, conn, tabletype); + } + } else { + table.setValid(false); + if (privilegeFlag && !isRenameFlow) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DENIED_ACCESS_PRIVILEGE)); + throw new DatabaseOperationException(IMessagesConstants.ERR_DENIED_ACCESS_PRIVILEGE); + } else if (!privilegeFlag) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.MSG_GUI_OBJECT_MAY_DROPPED)); + throw new DatabaseOperationException(IMessagesConstants.MSG_GUI_OBJECT_MAY_DROPPED); + } + } + table.setLoaded(true); + } catch (SQLException exp) { + GaussUtils.handleCriticalException(exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exp); + } finally { + conn.closeResultSet(resultSet); + } + } + + /** + * Refresh view. + * + * @param view the view + * @param conn the conn + * @param isRenameFlow the is rename flow + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + private void refreshView(ViewMetaData viewParam, DBConnection conn, boolean isRenameFlow) + throws DatabaseOperationException, DatabaseCriticalException { + ViewMetaData view = viewParam; + long oid = view.getOid(); + db.getSearchPoolManager().removeViewFromSearchPool(view); + views.removeFromGroup(oid); + + view = view.refreshSelfdata(conn, isRenameFlow); + if (view != null) { + view.addviewToSearchPool(view); + view.addViewsToGroup(view); + view.fetchViewColumnInfo(view, conn); + view.setLoaded(true); + } else { + // no self data returned + if (privilegeFlag && !isRenameFlow) { + throw new DatabaseOperationException(IMessagesConstants.ERR_DENIED_ACCESS_PRIVILEGE); + } else { + throw new DatabaseOperationException(IMessagesConstants.MSG_GUI_OBJECT_MAY_DROPPED); + // refreshing a view didnt get any row, means it is dropped + } + } + } + + /** + * Refresh all views in namespace. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void refreshAllViewsInNamespace(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + MPPDBIDELoggerUtility.perf("View: Stage : 1"); + for (ViewMetaData view : views) { + db.getSearchPoolManager().removeViewFromSearchPool(view); + } + MPPDBIDELoggerUtility.perf("View: Stage : 2"); + views.clear(); + MPPDBIDELoggerUtility.perf("View: Stage : 3"); + String query = ViewUtils.getViewQueryByNamespaceId(getOid(), privilegeFlag); + ViewUtils.fetchViews(Namespace.this, query, conn); + MPPDBIDELoggerUtility.perf("Total views loaded :" + views.getSize()); + if (canLoadNextLevel(views)) { + MPPDBIDELoggerUtility.perf("View: Stage : 4"); + fetchLevel2ViewColumnInfo(conn); + setLoadedValueNonLoadedObject(views); + } else { + MPPDBIDELoggerUtility.perf("View: Stage : 4(skip)"); + } + + MPPDBIDELoggerUtility.perf("View: Stage : 5/5"); + } + + /** + * Refresh table hirarchy. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void refreshTableHirarchy(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + MPPDBIDELoggerUtility.perf("Table: Stage : 1"); + clearCollection(tables); + MPPDBIDELoggerUtility.perf("Table: Stage : 2"); + + refreshAllTableMetadataInNamespace(conn); + + MPPDBIDELoggerUtility.perf("Total tables loaded :" + tables.getSize()); + if (canLoadNextLevel(tables)) { + MPPDBIDELoggerUtility.perf("Table: Stage : 3"); + fetchColumnMetaData(conn); + MPPDBIDELoggerUtility.perf("Table: Stage : 4"); + fetchAllConstraints(conn); + MPPDBIDELoggerUtility.perf("Table: Stage : 5"); + fetchAllIndexes(conn); + setLoadedValueNonLoadedObject(tables); + } else { + MPPDBIDELoggerUtility.perf("Table: Stage : 3(skip)"); + MPPDBIDELoggerUtility.perf("Table: Stage : 4(skip)"); + MPPDBIDELoggerUtility.perf("Table: Stage : 5(skip)"); + } + MPPDBIDELoggerUtility.perf("Table: Stage : 6/6"); + } + + /** + * Removes all the tables from the namespace and adds all the tables. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void refreshAllForeignTableMetadataInNamespace(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + List ftables; + boolean isAtleastOnePTPresent = false; + MPPDBIDELoggerUtility.perf("Foreign Table: Stage : 1"); + clearCollection(foreigntables); + ftables = ForeignTable.getAllFTablesInSchema(conn, Namespace.this, getOid()); + MPPDBIDELoggerUtility.perf("Foreign Table: Stage : 2"); + for (TableMetaData ftab : ftables) { + if (ftab instanceof PartitionTable) { + isAtleastOnePTPresent = true; + } + ftab.setLoaded(false); + getForeignTablesGroup().addToGroup(ftab); + getDatabase().getSearchPoolManager().addTableToSearchPool(ftab); + } + MPPDBIDELoggerUtility.perf("Total Foreign Tables loaded :" + getForeignTablesGroup().getSize()); + if (canLoadNextLevel(foreigntables)) { + MPPDBIDELoggerUtility.perf("Foreign Table: Stage : 3"); + ForeignTable.getColumnInfo(getForeignTablesGroup(), conn, Namespace.this, getOid()); + if (isAtleastOnePTPresent) { + loadPartitionNextLevel(foreigntables, conn); + } + } else { + MPPDBIDELoggerUtility.perf("Foreign Table: Stage : 3(skip)"); + } + + MPPDBIDELoggerUtility.perf("Foreign Table: Stage : 4/4"); + } + + /** + * Refresh all metadata in namespace on demand. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void refreshAllMetadataInNamespaceOnDemand(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + String qry = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, " + + "tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions " + "from pg_class tbl " + + "left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) " + + "where tbl.relkind in ('r','v','f') and tbl.parttype in ('n', 'p', 'v') and " + + "tbl.relnamespace = %d"; + if (privilegeFlag) { + qry += " and has_table_privilege(QUOTE_IDENT(%s" + ") || '.' || QUOTE_IDENT(tbl.relname), 'SELECT')"; + } + qry += ";"; + + ResultSet rs = conn.execSelectAndReturnRs( + String.format(Locale.ENGLISH, qry, getOid(), ServerObject.getLiteralName(getName()))); + TableMetaData table = null; + ViewMetaData view = null; + String relkind = null; + try { + boolean hasNext = rs.next(); + while (hasNext) { + relkind = rs.getString("relkind"); + + if ("v".equals(relkind)) { + view = ViewUtils.convertToViewMetaDataOnDemand(rs, getDatabase()); + view.setLoaded(false); + addView(view); + } else { + table = TableMetaData.convertToTableMetadataOnDemand(rs, db); + if (table != null) { + table.setLoaded(false); + if (table instanceof ForeignTable) { + getForeignTablesGroup().addToGroup(table); + } else { + getTablesGroup().addToGroup(table); + } + getDatabase().getSearchPoolManager().addTableToSearchPool(table); + } + } + hasNext = rs.next(); + } + } catch (SQLException exp) { + GaussUtils.handleCriticalException(exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exp); + } finally { + conn.closeResultSet(rs); + } + } + + /** + * Removes all the tables from the namespace and adds all the tables. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void refreshAllTableMetadataInNamespace(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + String baseQuery = String.format(Locale.ENGLISH, QUERY_FOR_ALL_NORMAL_TABLES_BY_NAMESPACE_ID, getOid()); + String qry = TableMetaData.formQueryForTableMetadata(baseQuery, + getDatabase().getServer().isServerCompatibleToNodeGroupPrivilege(), privilegeFlag); + + ResultSet rs = conn.execSelectAndReturnRs(qry); + clearCollection(tables); + try { + boolean hasNext = rs.next(); + boolean isAtleastOnePTPresent = false; + while (hasNext) { + if ("n".equals(rs.getString("parttype"))) { + // regular table + TableMetaData.convertToTableMetadata(rs, Namespace.this); + } else { + // partition table + PartitionTable.convertToPartitionTable(rs, Namespace.this); + isAtleastOnePTPresent = true; + } + hasNext = rs.next(); + } + + if (canLoadNextLevel(tables) && isAtleastOnePTPresent) { + loadPartitionNextLevel(tables, conn); + } + } catch (SQLException exp) { + GaussUtils.handleCriticalException(exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exp); + } finally { + conn.closeResultSet(rs); + } + } + } + + /** + * Refresh debug object. + * + * @param objectId the object id + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void refreshDebugObject(long objectId, DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + dbgObjManager.refreshDebugObject(objectId, conn); + } + + /** + * Shallow load debugable objects. + * + * @param type the type + * @param objBrowserConn the obj browser conn + * @param onDemand the on demand + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void shallowLoadDebugableObjects(OBJECTTYPE type, DBConnection objBrowserConn, boolean onDemand) + throws DatabaseCriticalException, DatabaseOperationException { + dbgObjManager.shallowLoadDebugableObjects(type, objBrowserConn, onDemand); + } + + /** + * Refresh db object. + * + * @param object the object + * @return the i debug object + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public IDebugObject refreshDbObject(IDebugObject object) throws MPPDBIDEException { + return dbgObjManager.refreshDbObject(object); + } + + @Override + public void dropDbObject(IDebugObject debugObject, DBConnection dbconn) throws MPPDBIDEException { + dbgObjManager.dropDbObject(debugObject, dbconn); + } + + /** + * Refresh debug object group. + * + * @param type the type + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void refreshDebugObjectGroup(OBJECTTYPE type) throws DatabaseCriticalException, DatabaseOperationException { + dbgObjManager.refreshDebugObjectGroup(type); + } + + /** + * Refresh debug object group. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void refreshDebugObjectGroup() throws DatabaseOperationException, DatabaseCriticalException { + dbgObjManager.refreshDebugObjectGroup(); + } + + /** + * Title: class Description: The Class DebugObjectsManager. + */ + private class DebugObjectsManager { + + /** + * Refresh debug object. + * + * @param objectId the object id + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void refreshDebugObject(long objectId, DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + String qry1 = Namespace.REFRESH_DBG_OBJ_QRY ; + if (privilegeFlag) { + qry1 += QUERY_DBG_OBJ_PRIVILEGE; + } + String qry = String.format(Locale.ENGLISH, qry1, objectId); + ResultSet rs = conn.execSelectAndReturnRs(qry); + boolean hasNext = false; + db.getSearchPoolManager().removeDebugObjectFromSearchPool(functions.getObjectById(objectId)); + functions.removeFromGroup(objectId); + + try { + hasNext = rs.next(); + if (!hasNext) { + if (privilegeFlag) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DENIED_ACCESS_PRIVILEGE)); + throw new DatabaseOperationException(IMessagesConstants.ERR_DENIED_ACCESS_PRIVILEGE); + } else { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.MSG_GUI_OBJECT_MAY_DROPPED)); + throw new DatabaseOperationException(IMessagesConstants.MSG_GUI_OBJECT_MAY_DROPPED); + } + } + while (hasNext) { + DebugObjects.DebugObjectsUtils.convertToObject(rs, db); + hasNext = rs.next(); + } + refreshDebugObjectGroup(); + } catch (SQLException exp) { + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } finally { + conn.closeResultSet(rs); + } + } + + /** + * Shallow load debugable objects. + * + * @param type the type + * @param objBrowserConn the obj browser conn + * @param onDemand the on demand + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void shallowLoadDebugableObjects(OBJECTTYPE type, DBConnection objBrowserConn, boolean onDemand) + throws DatabaseCriticalException, DatabaseOperationException { + int counter = 0; + String query; + MPPDBIDELoggerUtility.perf("Debug Object: Stage : 1"); + query = NamespaceUtils.getDebugObjectsLoadQuery(type, onDemand, Namespace.this); + ResultSet rs = objBrowserConn.execSelectAndReturnRs(query); + boolean hasNext = false; + + try { + hasNext = rs.next(); + while (hasNext) { + DebugObjects.DebugObjectsUtils.convertToObject(rs, getDatabase()); + counter++; + hasNext = rs.next(); + } + } catch (SQLException exp) { + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } finally { + MPPDBIDELoggerUtility.perf("Debug Object: Stage : 2/2"); + if (MPPDBIDELoggerUtility.isTraceEnabled()) { + MPPDBIDELoggerUtility + .trace("Total number of Debug Objects Loaded for selected database is : " + counter); + } + objBrowserConn.closeResultSet(rs); + } + } + + /** + * Refresh a particular object. + * + * @param object the object + * @return the i debug object + * @throws MPPDBIDEException the MPPDBIDE exception + */ + private IDebugObject refreshDbObject(IDebugObject object) throws MPPDBIDEException { + MPPDBIDELoggerUtility.debug("Namespace: refresh debug object."); + long objectId = object.getOid(); + DebugObjects newObject = null; + DebugObjectGroup objectGroup = null; + + try { + objectGroup = getDebugObjectGroupByType(object.getObjectType()); + if (null != objectGroup && getConnectionManager() != null) { + refreshDebugObject(objectId, getConnectionManager().getObjBrowserConn()); + newObject = objectGroup.getObjectById(objectId); + } + } catch (DatabaseOperationException dbOperationException) { + throw dbOperationException; + } catch (DatabaseCriticalException dbCriticalException) { + throw dbCriticalException; + } + + return newObject; + } + + /** + * Drop db object. + * + * @param debugObject the debug object + * @param dbconn the dbconn + * @throws MPPDBIDEException the MPPDBIDE exception + */ + private void dropDbObject(IDebugObject debugObject, DBConnection dbconn) throws MPPDBIDEException { + MPPDBIDELoggerUtility.debug("Namespace: drop debug object."); + + DebugObjectGroup objectGroup = null; + try { + objectGroup = getDebugObjectGroupByType(debugObject.getObjectType()); + + dbconn.execNonSelect(((DebugObjects) debugObject).generateDropQuery()); + + if (objectGroup != null) { + db.getSearchPoolManager().removeDebugObjectFromSearchPool((DebugObjects) debugObject); + objectGroup.removeFromGroup(debugObject.getOid()); + } + } catch (DatabaseOperationException dbOperationException) { + throw dbOperationException; + } catch (DatabaseCriticalException dbCriticalException) { + throw dbCriticalException; + } + } + + /** + * Refresh a particular object group. + * + * @param type the type + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void refreshDebugObjectGroup(OBJECTTYPE type) + throws DatabaseCriticalException, DatabaseOperationException { + MPPDBIDELoggerUtility.debug("ConnectionProfile: refresh Debug Object Group."); + DebugObjectGroup objectGroup = getDebugObjectGroupByType(type); + clearCollection(objectGroup); + refreshDebugObjectGroup(); + } + + /** + * Refresh debug object group. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + private void refreshDebugObjectGroup() throws DatabaseOperationException, DatabaseCriticalException { + MPPDBIDELoggerUtility.debug("Executor: Refresh debug object group."); + clearCollection(functions); + if (getConnectionManager() != null) { + shallowLoadDebugableObjects(OBJECTTYPE.PLSQLFUNCTION, getConnectionManager().getObjBrowserConn(), + false); + MPPDBIDELoggerUtility.info("Executor: Getting all functions."); + } + } + } + + @Override + public boolean isLoaded() { + return ILazyLoadObject.super.isLoaded(); + } + + @Override + public boolean isLoadingInProgress() { + return ILazyLoadObject.super.isLoadingInProgress(); + } + + @Override + public LOADSTATUS getLoadStatus() { + return this.loadStatus; + } + + @Override + public void setLoadStatus(LOADSTATUS status) { + this.loadStatus = status; + } + + /** + * Gets the packages. + * + * @return the packages + */ + @Override + public ObjectGroup getPackages() { + return null; + } + + @Override + public ServerObject getNewlyCreatedTable(String tableName) { + String query1 = "select tbl.relname relname,tbl.parttype parttype,tbl.relnamespace relnamespace,tbl.oid oid," + + "ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, " + + "xctbl.nodeoids as nodes ,tbl.reloptions as reloptions " + + "from pg_class tbl left join (select d.description, d.objoid from pg_description d " + + "where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl " + + "on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace " + + "where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.relname = '%s' " + + "and tbl.relnamespace= %d"; + String query = String.format(Locale.ENGLISH, query1, tableName, this.getOid()); + DBConnection conn = getDatabase().getConnectionManager().getObjBrowserConn(); + TableMetaData table = null; + ResultSet rs = null; + try { + rs = conn.execSelectAndReturnRs(query); + boolean hasNext = rs.next(); + boolean isAtleastOnePTPresent = false; + if (hasNext) { + if ("p".equalsIgnoreCase(rs.getString("parttype"))) { + table = new PartitionTable(this); + isAtleastOnePTPresent = true; + } else { + table = new TableMetaData(this); + } + table.populateTableMetaData(rs); + table.setLoaded(false); + this.addTableToSearchPool(table); + if (canLoadNextLevel(tables) && isAtleastOnePTPresent) { + loadPartitionNextLevel(tables, conn); + } + table.refreshTableDetails(conn); + return table; + } + } catch (DatabaseCriticalException | DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("Error while getting newly created table from database"); + } catch (SQLException exce) { + MPPDBIDELoggerUtility.error("Error while getting newly created table from database"); + } finally { + conn.closeResultSet(rs); + } + return table; + } + + @Override + public ServerObject getNewlyUpdatedTable(String tableName) { + TableMetaData table = getTablesGroup().get(tableName); + DBConnection dbConn = getDatabase().getConnectionManager().getObjBrowserConn(); + try { + if (null != table) { + refreshTable(table, dbConn, true); + table.refreshTableDetails(dbConn); + } + } catch (DatabaseCriticalException | DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("Error while getting newly updated table from database"); + } + return table; + } + + @Override + public ServerObject getNewlyCreatedView(String viewName) { + String query1 = "SELECT c.oid, n.oid as nspoid, n.nspname AS schemaname, c.relname AS viewname, " + + "pg_get_userbyid(c.relowner) AS viewowner, " + + "c.relkind as relkind " + + "FROM (pg_class c LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace))) WHERE " + + "(c.relkind = 'v'::\"char\") and c.relname='%s' and n.nspname='%s';"; + String query = String.format(Locale.ENGLISH, query1, viewName, this.getName()); + ResultSet rs = null; + boolean hasNext = false; + ViewMetaData view = null; + DBConnection dbConn = null; + Namespace ns = null; + try { + dbConn = getDatabase().getConnectionManager().getObjBrowserConn(); + rs = dbConn.execSelectAndReturnRs(query); + hasNext = rs.next(); + while (hasNext) { + view = ViewUtils.convertToViewMetaData(rs, this); + view.setLoaded(false); + ns = view.getNamespace(); + ns.addView(view); + hasNext = rs.next(); + } + } catch (SQLException exception) { + try { + GaussUtils.handleCriticalException(exception); + } catch (DatabaseCriticalException exc) { + MPPDBIDELoggerUtility.error("Error while getting newly created view from database"); + } + } catch (DatabaseCriticalException | DatabaseOperationException exce) { + MPPDBIDELoggerUtility.error("Error while getting newly created view from database"); + } finally { + if (dbConn != null) { + dbConn.closeResultSet(rs); + } + } + return view; + } + + @Override + public ServerObject getNewlyUpdatedView(String viewName) { + ViewMetaData view = getViewGroup().get(viewName); + DBConnection dbConn = getDatabase().getConnectionManager().getObjBrowserConn(); + try { + refreshView(view, dbConn, true); + } catch (DatabaseOperationException | DatabaseCriticalException exception) { + MPPDBIDELoggerUtility.error("Error while getting newly updated view from database"); + } + return view; + } + + @Override + public ServerObject getNewlyCreateTrigger(String triggerName) { + List triggers ; + TriggerMetaData trigger = null; + try { + DBConnection dbConn = getDatabase().getConnectionManager().getObjBrowserConn(); + triggers = TriggerObjectGroup.fetchTriggerByName(this, dbConn, triggerName); + for (TriggerMetaData tmpTrigger: triggers) { + this.addTrigger(tmpTrigger); + trigger = tmpTrigger; + } + } catch (DatabaseCriticalException exce) { + MPPDBIDELoggerUtility.error("Error while getting newly created view from database"); + } catch (DatabaseOperationException excep) { + MPPDBIDELoggerUtility.error("Error while getting newly created view from database"); + } + return trigger; + } + + /** + * Gets the synonyms. + * + * @return the synonyms + * @Title: getSynonyms + * @Description: get the the synonyms + */ + public OLAPObjectGroup getSynonyms() { + return synonyms; + } + + /** + * Adds the synonym. + * + * @param SynonymMetaData the synonymMetaData + */ + public void addSynonym(SynonymMetaData synonymMetaData) { + synonyms.addToGroup(synonymMetaData); + db.getSearchPoolManager().addsynonymToSearchPool(synonymMetaData); + } + + /** + * Load synonyms. + * + * @param freeConnection the free connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void loadSynonyms(DBConnection freeConnection) throws DatabaseOperationException, DatabaseCriticalException { + try { + SynonymUtil.fetchSynonyms(this, freeConnection); + } catch (MPPDBIDEException exception) { + extractMPPDBIDExeception(exception); + } + } + + /** + * Adds the trigger. + * + * @param TriggerMetaData the trigger + */ + public void addTrigger(TriggerMetaData trigger) { + triggerGroups.addToGroup(trigger); + db.getSearchPoolManager().addTriggerToSearchPool(trigger); + } + + /** + * Load triggers. + * + * @param freeConnection the free connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void loadTriggers(DBConnection freeConnection) throws DatabaseOperationException, DatabaseCriticalException { + try { + TriggerObjectGroup.fetchTriggers(this, freeConnection); + } catch (MPPDBIDEException exception) { + extractMPPDBIDExeception(exception); + } + } + + /** + * Extract MPPDBID exeception. + * + * @param mppDBexception the mpp D bexception + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + private void extractMPPDBIDExeception(MPPDBIDEException mppDBexception) + throws DatabaseOperationException, DatabaseCriticalException { + if (mppDBexception.getServerMessage() != null) { + if (mppDBexception instanceof DatabaseOperationException) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.EXCEPTION_OCCURED_WHILE_FETCHING_OBJECTS), + mppDBexception); + throw new DatabaseOperationException(IMessagesConstants.EXCEPTION_OCCURED_WHILE_FETCHING_OBJECTS, + mppDBexception); + } + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.NAMESPACE_RETRIVE_CRITICAL_ERROR), + mppDBexception); + throw new DatabaseCriticalException(IMessagesConstants.NAMESPACE_RETRIVE_CRITICAL_ERROR, mppDBexception); + } + } + + /** + * isSynoymSupported + * + * @return boolean isSynonym + */ + public boolean isSynoymSupported() { + return isSynoymSupported; + } + + /** + * setSynoymSupported + * + * @param isSynoymSupported boolean + */ + public void setSynoymSupported(boolean isSynoymSupported) { + this.isSynoymSupported = isSynoymSupported; + } + + /** + * validateView + * + * @return boolean value + */ + public boolean validateView(long oid) { + ViewObjectGroup viewGroup = getViewGroup(); + return null == viewGroup || null == viewGroup.getObjectById(oid); + } + + /** + * removeViewFromGroup method + */ + public void removeViewFromGroup(long oid) { + this.getViewGroup().removeFromGroup(oid); + } + + /** + * getTableObjectById + * + * @param oid long + * @return PartitionTable object + * @throws SQLException exception + */ + public PartitionTable getTableObjectById(long oid) throws SQLException { + TableMetaData table = getTablesGroup().getObjectById(oid); + if (table instanceof PartitionTable) { + return (PartitionTable) table; + } + return null; + } + + /** + * getForeignTableById + * + * @param oid value + * @return object partition + * @throws SQLException + */ + public PartitionTable getForeignTableById(long oid) throws SQLException { + TableMetaData table = getForeignTablesGroup().getObjectById(oid); + if (table instanceof PartitionTable) { + return (PartitionTable) table; + } + return null; + } + + /** + * validateAndGetTableObjGrp + * + * @return boolean value + */ + public boolean validateAndGetTableObjGrp(long oId) { + TableObjectGroup group = getTableObjGroup(oId); + return validateTableWithId(group, oId); + } + + /** + * validateTableWithId + * + * @param group grp + * @return boolean + */ + private boolean validateTableWithId(TableObjectGroup group, long oId) { + return null == group || null == group.getObjectById(oId); + } + + /** + * getTableObjGroup + * + * @return table object group + */ + private TableObjectGroup getTableObjGroup(long oId) { + TableObjectGroup group = getTablesGroup(); + if (validateTableWithId(group, oId)) { + group = getForeignTablesGroup(); + } + return group; + } + + /** + * removeTableFRomSearchPool + * + * @param name string + */ + public void removeTableFRomSearchPool(String name) { + getDatabase().getSearchPoolManager().getTableTrie().remove(name); + } + + /** + * getNamespceComments namespace commenst + * + * @param conn connection + * @return string query + * @throws DatabaseOperationException exception + */ + public String getNamespceComments(DBConnection conn) throws DatabaseOperationException { + String query = String.format(Locale.ENGLISH, + " SELECT description FROM pg_catalog.pg_description where objoid=%d", this.getOid()); + ResultSet rs = null; + StringBuilder seqDDL = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + String desc = ""; + try { + rs = conn.execSelectAndReturnRs(query); + while (rs.next()) { + desc = rs.getString("description"); + if (desc != null && !desc.isEmpty()) { + seqDDL.append(String.format(Locale.ENGLISH, "COMMENT ON SCHEMA %s IS '%s' ;", this.getDisplayName(), + desc)); + seqDDL.append(MPPDBIDEConstants.LINE_SEPARATOR); + } + } + } catch (DatabaseCriticalException exception) { + MPPDBIDELoggerUtility.error("error getting free connection", exception); + throw new DatabaseOperationException(IMessagesConstants.CONNECTION_ERR); + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("error getting free connection", exception); + throw new DatabaseOperationException(IMessagesConstants.CONNECTION_ERR); + } finally { + conn.closeResultSet(rs); + MPPDBIDELoggerUtility.debug("fetch DDL done"); + } + return seqDDL.toString(); + } + + /** + * getErrorTableList + * + * @return list error table + */ + public Set getErrorTableList() { + return errorTableList; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/NamespaceUtils.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/NamespaceUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..7f2639c7695deb4f2eca84996daca93083ba0902 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/NamespaceUtils.java @@ -0,0 +1,240 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Iterator; +import java.util.Locale; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: interface + * + * Description: The Interface NamespaceUtils. + * + */ + +public interface NamespaceUtils extends NamespaceUtilsBase { + + /** + * Fetch all user namespaces. + * + * @param db the db + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public static void fetchAllUserNamespaces(Database db) + throws DatabaseOperationException, DatabaseCriticalException { + int counter = 0; + String query = "SELECT oid, nspname from pg_namespace where ((oid >= 16384 or nspname LIKE 'public') " + + "and nspname NOT LIKE 'pg_%')"; + if (db.getPrivilegeFlag()) { + query += " and has_schema_privilege(nspname, 'USAGE')"; + } + query += " ORDER BY nspname;"; + ResultSet rs = null; + int oid = 0; + String name = null; + + try { + rs = db.getConnectionManager().execSelectAndReturnRsOnObjBrowserConn(query); + boolean hasNext = rs.next(); + UserNamespace namespace = null; + db.getUserNamespaces().clear(); + db.getSearchPoolManager().clearTrie(); + while (hasNext) { + oid = rs.getInt("oid"); + name = rs.getString("nspname"); + namespace = new UserNamespace(oid, name, db); + + db.getUserNamespaces().addToGroup(namespace); + counter++; + hasNext = rs.next(); + } + } catch (SQLException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exe); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } finally { + if (MPPDBIDELoggerUtility.isTraceEnabled()) { + MPPDBIDELoggerUtility.trace("Total number of namespace loaded for selected database is " + counter); + } + db.getConnectionManager().closeRSOnObjBrowserConn(rs); + } + } + + /** + * Fetch all system namespaces. + * + * @param db the db + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public static void fetchAllSystemNamespaces(Database db) + throws DatabaseOperationException, DatabaseCriticalException { + int counter = 0; + + String query = "SELECT oid, nspname from pg_namespace where ((oid < 16384 and nspname NOT LIKE 'public') " + + "or nspname LIKE 'pg_%')"; + if (db.getPrivilegeFlag()) { + query += " and has_schema_privilege(nspname, 'USAGE')"; + } + query += " ORDER BY nspname;"; + ResultSet rs = null; + int oid = 0; + String name = null; + + try { + rs = db.getConnectionManager().execSelectAndReturnRsOnObjBrowserConn(query); + boolean hasNext = rs.next(); + SystemNamespace namespace = null; + db.getSystemNamespaces().clear(); + db.getSearchPoolManager().clearTrie(); + while (hasNext) { + oid = rs.getInt("oid"); + name = rs.getString("nspname"); + namespace = new SystemNamespace(oid, name, db); + + db.getSystemNamespaces().addToGroup(namespace); + counter++; + hasNext = rs.next(); + } + } catch (SQLException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exe); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } finally { + if (MPPDBIDELoggerUtility.isTraceEnabled()) { + MPPDBIDELoggerUtility.trace("Total number of namespace loaded for selected database is : " + counter); + } + db.getConnectionManager().closeRSOnObjBrowserConn(rs); + } + } + + /** + * Gets the shallow load qry. + * + * @param ns the ns + * @return the shallow load qry + */ + static String getShallowLoadQry(Namespace ns) { + String privilegeString = (ns != null && ns.getPrivilegeFlag()) ? DBG_PRIVILEGE_FILTER : ""; + String str = getSchemaInfo(ns); + return SHALLOW_LOAD_QUERY + privilegeString + str + SHALLOW_LOAD_ORDERBY_QRY; + } + + /** + * getSchemaInfo schema info + * + * @param ns namespace + * @return string + */ + static String getSchemaInfo(Namespace ns) { + if (ns != null) { + return String.format(Locale.ENGLISH, RESTRICT_TO_SCHEMA, ns.getOid()); + } + return ""; + } + + /** + * Gets the shallow load function qry. + * + * @param ns the ns + * @return the shallow load function qry + */ + static String getShallowLoadFunctionQry(Namespace ns) { + String privilegeString = (ns != null && ns.getPrivilegeFlag()) ? DBG_PRIVILEGE_FILTER : ""; + String str = getSchemaInfo(ns); + return SHALLOW_LOAD_FUNCTION_ONLY + privilegeString + str + SHALLOW_LOAD_ORDERBY_QRY; + } + + /** + * Gets the shallow load qry on demand. + * + * @param ns the ns + * @return the shallow load qry on demand + */ + static String getShallowLoadQryOnDemand(Namespace ns) { + String privilegeString = (ns != null && ns.getPrivilegeFlag()) ? DBG_PRIVILEGE_FILTER : ""; + String str = getSchemaInfo(ns); + return SHALLOW_LOAD_QRY_ON_DEMAND + privilegeString + str + SHALLOW_LOAD_ORDERBY_QRY; + } + + /** + * Gets the shallow load function qry on demand. + * + * @param ns the ns + * @return the shallow load function qry on demand + */ + static String getShallowLoadFunctionQryOnDemand(Namespace ns) { + String privilegeString = (ns != null && ns.getPrivilegeFlag()) ? DBG_PRIVILEGE_FILTER : ""; + String str = getSchemaInfo(ns); + return SHALLOW_LOAD_QRY_ON_DEMAND + privilegeString + str + SHALLOW_LOAD_ORDERBY_QRY; + } + + /** + * Gets the debug objects load query. + * + * @param type the type + * @param onDemand the on demand + * @param ns the ns + * @return the debug objects load query + */ + public static String getDebugObjectsLoadQuery(OBJECTTYPE type, boolean onDemand, Namespace ns) { + String query; + switch (type) { + case PLSQLFUNCTION: { + if (onDemand) { + query = getShallowLoadFunctionQryOnDemand(ns); + } else { + query = getShallowLoadFunctionQry(ns); + } + break; + } + default: { + if (onDemand) { + query = getShallowLoadQryOnDemand(ns); + } else { + query = getShallowLoadQry(ns); + } + break; + } + } + return query; + } + + /** + * Sets the level 3 loaded flag. + * + * @param itr the new level 3 loaded flag + */ + public static void setLevel3LoadedFlag(Iterator itr) { + boolean hasNext = itr.hasNext(); + + while (hasNext) { + TableMetaData table = itr.next(); + table.setLevel3Loaded(true); + hasNext = itr.hasNext(); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/NamespaceUtilsBase.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/NamespaceUtilsBase.java new file mode 100644 index 0000000000000000000000000000000000000000..3c07747950eb2a4df05c16a73dd326e2262d26db --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/NamespaceUtilsBase.java @@ -0,0 +1,290 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Locale; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: interface + * + * Description: The Interface NamespaceUtilsBase. + * + */ + +public interface NamespaceUtilsBase { + + static final String SHALLOW_LOAD_QUERY = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, " + + "pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs,pr.proargtypes argtype, " + + "pr.proargnames argname, " + + "pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, pr.proisstrict isstrict, " + + "pr.proretset retset, " + "pr.procost procost, pr.prorows setrows, lng.lanname lang " + "FROM pg_proc pr " + + "JOIN pg_type typ ON typ.oid=prorettype " + "JOIN pg_namespace typns ON typns.oid=typ.typnamespace " + + "JOIN pg_language lng ON lng.oid=prolang " + "WHERE lng.lanname in ('plpgsql','sql','c')"; + static final String DBG_PRIVILEGE_FILTER = " and has_function_privilege(pr.oid, 'EXECUTE')"; + + static final String SHALLOW_LOAD_ORDERBY_QRY = " ORDER BY objname"; + static final String SHALLOW_LOAD_FUNCTION_ONLY = SHALLOW_LOAD_QUERY; + static final String RESTRICT_TO_SCHEMA = " and pr.pronamespace= %d"; + + static final String SHALLOW_LOAD_QRY_ON_DEMAND = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, " + + "pr.proallargtypes alltype, " + + "pr.pronargs nargs, pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod, " + + "pr.proretset retset, lng.lanname lang " + "FROM pg_proc pr " + "JOIN pg_language lng ON lng.oid=prolang " + + "WHERE lng.lanname in ('plpgsql','sql','c')"; + + /** + * Gets the debug object type by group type. + * + * @param groupType the group type + * @return the debug object type by group type + */ + public static OBJECTTYPE getDebugObjectTypeByGroupType(OBJECTTYPE groupType) { + switch (groupType) { + case FUNCTION_GROUP: { + return OBJECTTYPE.PLSQLFUNCTION; + } + case PROCEDURE_GROUP: { + return OBJECTTYPE.PROCEDURE; + } + default: { + return OBJECTTYPE.OBJECTTYPE_BUTT; + } + } + } + + /** + * Fetch namespace. + * + * @param namespaceId the namespace id + * @param resetChildDetails the reset child details + * @param isRenameFlow the is rename flow + * @param db the db + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static void fetchNamespace(long namespaceId, boolean resetChildDetails, boolean isRenameFlow, Database db) + throws DatabaseCriticalException, DatabaseOperationException { + + String qry = null; + if (db.getPrivilegeFlag() && !isRenameFlow) { + qry = "SELECT oid, nspname from pg_namespace WHERE oid=" + namespaceId + + " and has_schema_privilege(nspname, 'USAGE');"; + } else { + qry = "SELECT oid, nspname from pg_namespace WHERE oid=" + namespaceId + ";"; + } + + ResultSet rs = null; + boolean isSysNamespace = false; + Namespace newNamespace = db.getUserNamespaceGroup().getObjectById(namespaceId); + if (newNamespace == null) { + newNamespace = db.getSystemNamespaceGroup().getObjectById(namespaceId); + isSysNamespace = true; + } + + try { + rs = fetchAndAddNamespaceToDb(namespaceId, resetChildDetails, isRenameFlow, db, qry, isSysNamespace, + newNamespace); + + } catch (SQLException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exe); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } finally { + db.getConnectionManager().closeRSOnObjBrowserConn(rs); + } + } + + /** + * Fetch and add namespace to db. + * + * @param namespaceId the namespace id + * @param resetChildDetails the reset child details + * @param isRenameFlow the is rename flow + * @param db the db + * @param qry the qry + * @param isSysNamespace the is sys namespace + * @param newNamespace the new namespace + * @return the result set + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws SQLException the SQL exception + */ + public static ResultSet fetchAndAddNamespaceToDb(long namespaceId, boolean resetChildDetails, boolean isRenameFlow, + Database db, String qry, boolean isSysNamespace, Namespace newNamespace) + throws DatabaseCriticalException, DatabaseOperationException, SQLException { + ResultSet rs; + rs = db.getConnectionManager().execSelectAndReturnRsOnObjBrowserConn(qry); + boolean hasNext = rs.next(); + + if (hasNext) { + if (newNamespace == null) { + newNamespace = new Namespace(rs.getInt("oid"), rs.getString("nspname"), db); + + } else { + if (isSysNamespace) { + db.getSystemNamespaceGroup().removeFromGroup(namespaceId); + } else { + db.getUserNamespaceGroup().removeFromGroup(namespaceId); + } + + newNamespace.setName(rs.getString("nspname")); + if (resetChildDetails) { + newNamespace.clearAllObjects(); + } + + } + + if (isSysNamespace) { + db.getSystemNamespaceGroup().addToGroup((SystemNamespace) newNamespace); + } else { + db.getUserNamespaceGroup().addToGroup((UserNamespace) newNamespace); + } + + } else { + if (isSysNamespace) { + db.getSystemNamespaceGroup().removeFromGroup(namespaceId); + } else { + db.getUserNamespaceGroup().removeFromGroup(namespaceId); + } + newNamespace.setValid(false); + DatabaseUtils.checkExceptionForNoAccessNoRenameflow(isRenameFlow, db.getPrivilegeFlag()); + } + return rs; + } + + /** + * Gets the namespace list for search. + * + * @param namespacesList the namespaces list + * @param nsMap the ns map + * @param nss the nss + * @return the namespace list for search + */ + public static void getNamespaceListForSearch(ArrayList namespacesList, HashMap nsMap, + ArrayList nss) { + for (int idx = 0; idx < nss.size(); idx++) { + Namespace ns = nss.get(idx); + namespacesList.add(ns.getName()); + nsMap.put(idx, ns); + } + } + + /** + * Fetch all namespaces. + * + * @param db the db + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public static void fetchAllNamespaces(Database db) throws DatabaseOperationException, DatabaseCriticalException { + int counter = 0; + String query = "SELECT oid, nspname from pg_namespace"; + if (db.getPrivilegeFlag()) { + query += " where has_schema_privilege(nspname, 'USAGE')"; + } + query += " ORDER BY nspname;"; + + ResultSet rs = null; + try { + rs = db.getConnectionManager().execSelectAndReturnRsOnObjBrowserConn(query); + boolean hasNext = rs.next(); + db.getUserNamespaces().clear(); + db.getSystemNamespaces().clear(); + db.getSearchPoolManager().clearTrie(); + while (hasNext) { + int oid = rs.getInt("oid"); + String name = rs.getString("nspname"); + if (oid >= 16384 && (!name.contains("pg_")) || name.toLowerCase(Locale.ENGLISH).contains("public")) { + UserNamespace usernamespace = new UserNamespace(oid, name, db); + db.getUserNamespaces().addToGroup(usernamespace); + } else { + SystemNamespace systemnamespace = new SystemNamespace(oid, name, db); + db.getSystemNamespaces().addToGroup(systemnamespace); + } + counter++; + hasNext = rs.next(); + } + } catch (SQLException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exe); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } finally { + if (MPPDBIDELoggerUtility.isTraceEnabled()) { + MPPDBIDELoggerUtility.trace("Total number of namespace loaded is : " + counter); + } + + db.getConnectionManager().closeRSOnObjBrowserConn(rs); + } + } + + /** + * Refresh namespace. + * + * @param namespaceId the namespace id + * @param isDrop the is drop + * @param db the db + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static void refreshNamespace(long namespaceId, boolean isDrop, Database db) + throws DatabaseCriticalException, DatabaseOperationException { + MPPDBIDELoggerUtility.debug("ConnectionProfile: refresh namespace."); + Namespace namespace = db.getNameSpaceById(namespaceId); + namespace.clearAllObjects(); + + if (isDrop) { + db.getUserNamespaces().removeFromGroup(namespaceId); + } else { + fetchNamespace(namespaceId, true, false, db); + } + + } + + /** + * Refresh namespace meta data. + * + * @param namespaceId the namespace id + * @param db the db + * @return the namespace + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static Namespace refreshNamespaceMetaData(long namespaceId, Database db) + throws DatabaseCriticalException, DatabaseOperationException { + MPPDBIDELoggerUtility.debug("ConnectionProfile: refresh namespace metadata."); + + /* + * It is mandatory not to touch/clear any child details. The below line + * is deliberately commented. + */ + + fetchNamespace(namespaceId, false, true, db); + + return db.getNameSpaceById(namespaceId); + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/NotificationData.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/NotificationData.java new file mode 100644 index 0000000000000000000000000000000000000000..243646d934ecd42fc77bcfc454f0a906fbfe1690 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/NotificationData.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: class + * + * Description: The Class NotificationData. + * + */ + +public class NotificationData { + + private String clientInfo; + private String time; + + /** + * Gets the time. + * + * @return the time + */ + public String getTime() { + return time; + } + + /** + * Sets the time. + * + * @param time the new time + */ + public void setTime(String time) { + this.time = time; + } + + /** + * Gets the client info. + * + * @return the client info + */ + public String getClientInfo() { + return clientInfo; + } + + /** + * Sets the client info. + * + * @param client the new client info + */ + public void setClientInfo(String client) { + clientInfo = client; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/OBJECTTYPE.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/OBJECTTYPE.java new file mode 100644 index 0000000000000000000000000000000000000000..b47745f8354e2ba5f0cc715926cf7b9d07a44872 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/OBJECTTYPE.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * Title: enum Description: The Enum OBJECTTYPE. + */ + +public enum OBJECTTYPE { + PLSQLFUNCTION, PROCEDURE, TABLESPACE, TABLEMETADATA, SQLFUNCTION, CFUNCTION, + // DS_ITR0_STRY_013 starts + TYPEMETADATA, KEYWORDS, + // DS_ITR0_STRY_013 ends + NODE, NODEGROUP, ACCESSMETHOD, DATABASE, SQLTERMINAL, NODE_GROUP, FUNCTION_GROUP, PROCEDURE_GROUP, TABLE_GROUP, + NODEGROUP_GROUP, DATABASE_GROUP, TABLESPACE_GROUP, DATATYPE_GROUP, NAMESPACE_GROUP, USER_NAMESPACE_GROUP, + SYSTEM_NAMESPACE_GROUP, COLUMN_GROUP, CONSTRAINT_GROUP, INDEX_GROUP, ACCESSMETHOD_GROUP, OBJECTTYPE_BUTT, NAMESPACE, + USER_NAMESPACE, SYSTEM_NAMESPACE, INDEX_METADATA, COLUMN_METADATA, CONSTRAINT, VIEW_META_DATA, VIEW_GROUP, + VIEW_COLUMN_METADATA, VIEW_COLUMN_GROUP, FOREIGN_TABLE_GROUP, SEQUENCE_GROUP, SYNONYM_GROUP, USER_ROLE_GROUP, + USER_ROLE, PARTITION_TABLE, FOREIGN_PARTITION_TABLE, PARTITION_GROUP, PARTITION_METADATA, FOREIGN_TABLE, + FOREIGN_TABLE_GDS, FOREIGN_TABLE_HDFS, SEQUENCE_METADATA_GROUP, SYNONYM_METADATA_GROUP, ALIAS, + TRIGGER, + TRIGGER_GROUP, TRIGGER_METADATA, + SHOW_MORE_OBJECTS +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ObjectChange.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ObjectChange.java new file mode 100644 index 0000000000000000000000000000000000000000..7485ad5b2c5a54e57e41c5e7e9c542bd71816947 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ObjectChange.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: interface + * + * Description: The Interface ObjectChange. + * + */ + +public interface ObjectChange { + + /** + * Checks if is changed. + * + * @param obj the obj + * @return true, if is changed + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + boolean isChanged(String obj) throws DatabaseCriticalException, DatabaseOperationException; + + /** + * Gets the latest info. + * + * @return the latest info + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + Object getLatestInfo() throws DatabaseCriticalException, DatabaseOperationException; + + /** + * Handle change. + * + * @param obj the obj + */ + void handleChange(String obj); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ObjectParameter.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ObjectParameter.java new file mode 100644 index 0000000000000000000000000000000000000000..fbc8abfd93eb33ee9c761fba44447eaeebbad488 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ObjectParameter.java @@ -0,0 +1,400 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.util.ArrayList; + +import org.opengauss.mppdbide.adapter.gauss.GaussDatatypeUtils; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class ObjectParameter. + * + */ + +public class ObjectParameter { + + /** + * + * Title: enum + * + * Description: The Enum PARAMETERTYPE. + * + */ + public enum PARAMETERTYPE { + IN, OUT, INOUT + }; + + private String datatype; + private String name; + private PARAMETERTYPE type; + private String value; + private boolean isSupportedDatatype; + + /** + * Instantiates a new object parameter. + */ + public ObjectParameter() { + } + + /** + * Instantiates a new object parameter. + * + * @param convertToClientType the convert to client type + * @param supported the supported + */ + public ObjectParameter(String convertToClientType, boolean supported) { + this.datatype = convertToClientType; + this.isSupportedDatatype = supported; + } + + /** + * Gets the datatype. + * + * @return the datatype + */ + public String getDataType() { + return datatype; + } + + /** + * Sets the datatype. + * + * @param datatype the new datatype + */ + public void setDataType(String datatype) { + this.datatype = datatype; + } + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Sets the name. + * + * @param name the new name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Gets the type. + * + * @return the type + */ + public PARAMETERTYPE getType() { + return type; + } + + /** + * Sets the type. + * + * @param type the new type + */ + public void setType(PARAMETERTYPE type) { + this.type = type; + } + + /** + * Sets the value. + * + * @param value the new value + */ + public void setValue(String value) { + this.value = value; + } + + /** + * Gets the value. + * + * @return the value + */ + public String getValue() { + return value; + } + + /** + * Clear value. + */ + public void clearValue() { + value = null; + } + + /** + * Gets the checks if is supported datatype. + * + * @return the checks if is supported datatype + */ + public boolean getIsSupportedDatatype() { + return isSupportedDatatype; + } + + /** + * Sets the checks if is supported datatype. + * + * @param isSupportedDatatype the new checks if is supported datatype + */ + public void setIsSupportedDatatype(boolean isSupportedDatatype) { + this.isSupportedDatatype = isSupportedDatatype; + } + + /** + * Gets the variables. + * + * @param types the types + * @param names the names + * @param modes the modes + * @param allin the allin + * @param nsList the ns list + * @return the variables + */ + public static ObjectParameter[] getVariables(String types, String names, String modes, boolean allin, + ArrayList nsList) { + ArrayList arguments = new ArrayList(MPPDBIDEConstants.VARIABLE_ARRAY_SIZE); + String[] argModes = null; + String[] argTypes = null; + String[] argName = null; + + if (null == types) { + return arguments.toArray(new ObjectParameter[arguments.size()]); + } + + if (allin) { + argTypes = types.split(" "); + } else { + if (containsOpenAndClosedParenthesisInOrder(types)) { + argTypes = types.substring(types.indexOf('{') + 1, types.indexOf('}')).split(","); + } else { + argTypes = types.split(","); + } + } + + argName = getArgName(names, argTypes); + argModes = setArgsMode(modes); + int argLength = argTypes.length; + + addArguments(names, nsList, arguments, argModes, argTypes, argName, argLength); + + return arguments.toArray(new ObjectParameter[arguments.size()]); + } + + /** + * Adds the arguments. + * + * @param names the names + * @param nsList the ns list + * @param arguments the arguments + * @param argModes the arg modes + * @param argTypes the arg types + * @param argName the arg name + * @param argLength the arg length + */ + private static void addArguments(String names, ArrayList nsList, ArrayList arguments, + String[] argModes, String[] argTypes, String[] argName, int argLength) { + ObjectParameter var = null; + int typeid = 0; + String argmode = null; + for (int argIndex = 0; argIndex < argLength; argIndex++) { + var = new ObjectParameter(); + + if (names != null) { + var.setName(argName[argIndex]); + } + + if (null != argModes) { + argmode = argModes[argIndex]; + } else { + argmode = "i"; + } + + if ("o".equals(argmode)) { + var.setType(PARAMETERTYPE.OUT); + } else if ("b".equals(argmode)) { + var.setType(PARAMETERTYPE.INOUT); + } else { + var.setType(PARAMETERTYPE.IN); + } + + try { + typeid = Integer.parseInt(argTypes[argIndex]); + } catch (NumberFormatException exception) { + MPPDBIDELoggerUtility.error("Exception occured while adding the arguments", exception); + } + + var.setDataType(getDataTypeName(typeid, nsList)); + var.setIsSupportedDatatype(GaussDatatypeUtils.isSupported(typeid)); + + arguments.add(var); + } + } + + /** + * Sets the args mode. + * + * @param modes the modes + * @param argModes the arg modes + * @return the string[] + */ + private static String[] setArgsMode(String modes) { + String[] argModes = null; + if (null != modes) { + if (modes.contains("{") && modes.contains("}")) { + argModes = modes.substring(modes.indexOf('{') + 1, modes.indexOf('}')).split(","); + } else { + argModes = modes.split(","); + } + } + return argModes; + } + + /** + * Gets the arg name. + * + * @param names the names + * @param argTypes the arg types + * @return the arg name + */ + private static String[] getArgName(String names, String[] argTypes) { + String[] argName; + argName = new String[argTypes.length]; + if (names != null) { + if (containsOpenAndClosedParenthesisInOrder(names)) { + argName = names.substring(names.indexOf('{') + 1, names.indexOf('}')).split(","); + } else { + argName = names.split(","); + } + } + return argName; + } + + /** + * Contains open and closed parenthesis in order. + * + * @param types the types + * @return true, if successful + */ + private static boolean containsOpenAndClosedParenthesisInOrder(String types) { + return types.contains("{") && types.contains("}") && types.indexOf("}") > types.indexOf("{"); + } + + /** + * Gets the data type name. + * + * @param rettype the rettype + * @param nsList the ns list + * @return the data type name + */ + private static String getDataTypeName(int rettype, ArrayList nsList) { + String convertedDataType = GaussDatatypeUtils.convertToClientType(rettype); + if (null == convertedDataType) { + convertedDataType = TypeMetaDataUtil.getDataTypeFromNamespace(rettype, nsList); + } + + return convertedDataType; + } + + /** + * Update query. + * + * @return the object + */ + public Object updateQuery() { + switch (this.getType()) { + case IN: { + return "IN " + getDataType(); + } + case INOUT: { + return "INOUT " + getDataType(); + } + case OUT: { + return "OUT " + getDataType(); + } + default: { + return getDataType(); + } + } + } + + /** + * Gets the display name with arg name. + * + * @return the display name with arg name + */ + public String getDisplayNameWithArgName() { + StringBuilder displayNameWithArg = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + displayNameWithArg.append(this.getName()); + displayNameWithArg.append(" "); + displayNameWithArg.append(this.getDataType()).append(" "); + switch (this.getType()) { + case OUT: { + displayNameWithArg.append("OUT"); + break; + } + case INOUT: { + displayNameWithArg.append("INOUT"); + break; + } + default: { + displayNameWithArg.append("IN"); + } + } + + return displayNameWithArg.toString(); + } + + /** + * Gets the display name. + * + * @param isAutoSuggest the is auto suggest + * @return the display name + */ + public String getDisplayName(boolean isAutoSuggest) { + StringBuilder displayName = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + displayName.append(this.getDataType()); + if (!isAutoSuggest) { + displayName.append(" "); + switch (this.getType()) { + case OUT: { + displayName.append("OUT"); + break; + } + case INOUT: { + displayName.append("INOUT"); + break; + } + default: { + displayName.append("IN"); + } + } + } + + return displayName.toString(); + + } + +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/PartitionColumnExpr.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/PartitionColumnExpr.java new file mode 100644 index 0000000000000000000000000000000000000000..88514c4171c6c0719b4d13c03eb51a3d37145ac0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/PartitionColumnExpr.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: class + * + * Description: The Class PartitionColumnExpr. + * + */ + +public class PartitionColumnExpr { + + private int position; + private PartitionColumnType type; + private String expr; + private ColumnMetaData col; + + /** + * Instantiates a new partition column expr. + * + * @param type the type + */ + public PartitionColumnExpr(PartitionColumnType type) { + this.type = type; + this.position = -1; + } + + /** + * Gets the position. + * + * @return the position + */ + public int getPosition() { + return position; + } + + /** + * Sets the position. + * + * @param position the new position + */ + public void setPosition(int position) { + this.position = position; + } + + /** + * Gets the expr. + * + * @return the expr + */ + public String getExpr() { + return expr; + } + + /** + * Sets the expr. + * + * @param expr the new expr + */ + public void setExpr(String expr) { + this.expr = expr; + } + + /** + * Gets the col. + * + * @return the col + */ + public ColumnMetaData getCol() { + return col; + } + + /** + * Sets the col. + * + * @param col the new col + */ + public void setCol(ColumnMetaData col) { + this.col = col; + } + + /** + * Gets the type. + * + * @return the type + */ + public PartitionColumnType getType() { + return type; + } + + @Override + public String toString() { + if (PartitionColumnType.COLUMN == getType()) { + return getCol().getName(); + } else { + return getExpr(); + } + } + + /** + * Validate partition column type. + * + * @return true, if successful + */ + public boolean validatePartitionColumnType() { + if (PartitionColumnType.COLUMN == getType()) { + return true; + } + return false; + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/PartitionColumnType.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/PartitionColumnType.java new file mode 100644 index 0000000000000000000000000000000000000000..e85e78bb90b6cb6e8d6329349e57e0ec7a34da45 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/PartitionColumnType.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: enum + * + * Description: The Enum PartitionColumnType. + * + */ + +public enum PartitionColumnType { + COLUMN, EXPRESSION +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/PartitionMetaData.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/PartitionMetaData.java new file mode 100644 index 0000000000000000000000000000000000000000..4956c43a7561b67eeafa40f01e339ecf887755f8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/PartitionMetaData.java @@ -0,0 +1,468 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: class + * + * Description: The Class PartitionMetaData. + * + */ + +public class PartitionMetaData extends BatchDropServerObject implements GaussOLAPDBMSObject { + + private String intervalPartitionExpr = ""; + private PartitionTable pTable; + private String partitionName; + private String partitionValue; + private String partitionType; + private Tablespace ts; + private boolean isRollBack = true; + private ColumnMetaData columnMetadata; + private Map, String>> partitionTypeToMethodMap = + new HashMap, String>>(); + + /** + * Sets the partition type to method map. + */ + public void setPartitionTypeToMethod() { + partitionTypeToMethodMap.put(PartitionTypeEnum.BY_RANGE.getTypeName(), + (list) -> formCreatePartitionsQryByRange(list)); + partitionTypeToMethodMap.put(PartitionTypeEnum.BY_INTERVAL.getTypeName(), + (list) -> formCreatePartitionsQryByInterval(list)); + partitionTypeToMethodMap.put(PartitionTypeEnum.BY_HASH.getTypeName(), + (list) -> formCreatePartitionsQryByHash(list)); + partitionTypeToMethodMap.put(PartitionTypeEnum.BY_LIST.getTypeName(), + (list) -> formCreatePartitionsQryByList(list)); + } + + /** + * Gets the partition type to method map + * + * @return Map, String>> the partition type to method map + */ + public Map, String>> getPartitionTypeToMethod() { + return partitionTypeToMethodMap; + } + + /** + * Gets the partition name. + * + * @return the partition name + */ + public String getPartitionName() { + return partitionName; + } + + /** + * Sets the partition name. + * + * @param partitionName the new partition name + */ + public void setPartitionName(String partitionName) { + this.partitionName = partitionName; + } + + /** + * Gets the partition value. + * + * @return the partition value + */ + public String getPartitionValue() { + return partitionValue; + } + + /** + * Sets the partition value. + * + * @param partitionValue the new partition value + */ + public void setPartitionValue(String partitionValue) { + this.partitionValue = partitionValue; + } + + /** + * Gets the interval partition expr. + * + * @return String the interval partition expr + */ + public String getIntervalPartitionExpr() { + return intervalPartitionExpr; + } + + /** + * Sets the interval partition expr. + * + * @param String the interval partition expr + */ + public void setIntervalPartitionExpr(String intervalPartitionExpr) { + this.intervalPartitionExpr = intervalPartitionExpr; + } + + /** + * Gets the partition values as list. + * + * @return the partition values as list + */ + public List getPartitionValuesAsList() { + return Arrays.asList(partitionValue.split(",", -1)); + } + + /** + * Sets the partition type. + * + * @param partitionType the new partition type + */ + public void setPartitionType(String partitionType) { + this.partitionType = partitionType; + } + + /** + * Gets the partition type. + * + * @return the partition type + */ + public String getPartitionType() { + return this.partitionType; + } + + /** + * Gets the ts. + * + * @return the ts + */ + public Tablespace getTs() { + return ts; + } + + /** + * Gets the tablespace name. + * + * @return the tablespace name + */ + public String getTablespaceName() { + return ts.getName(); + } + + /** + * Checks if is tablespace null. + * + * @return true, if is tablespace null + */ + public boolean isTablespaceNull() { + return ts == null; + } + + /** + * Sets the ts. + * + * @param ts the new ts + */ + public void setTs(Tablespace ts) { + this.ts = ts; + } + + /** + * Gets the column metadata. + * + * @return the column metadata + */ + public ColumnMetaData getColumnMetadata() { + return columnMetadata; + } + + /** + * Sets the column metadata. + * + * @param columnMetadata the new column metadata + */ + public void setColumnMetadata(ColumnMetaData columnMetadata) { + this.columnMetadata = columnMetadata; + } + + /** + * Instantiates a new partition meta data. + * + * @param oid the oid + * @param name the name + * @param partitionTable the partition table + */ + public PartitionMetaData(long oid, String name, PartitionTable partitionTable) { + super(oid, name, OBJECTTYPE.PARTITION_METADATA, false); + this.pTable = partitionTable; + } + + /** + * Instantiates a new partition meta data. + * + * @param name the name + */ + public PartitionMetaData(String name) { + super(-1, name, OBJECTTYPE.PARTITION_METADATA, false); + } + + /** + * Convert to partition meta data. + * + * @param rs the rs + * @param partitionTable the partition table + * @param database the database + * @return the partition meta data + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static PartitionMetaData convertToPartitionMetaData(ResultSet rs, PartitionTable partitionTable, + Database database) throws DatabaseCriticalException, DatabaseOperationException { + + PartitionMetaData part = null; + try { + part = new PartitionMetaData(rs.getLong("partition_id"), rs.getString("partition_name"), partitionTable); + part.setPartitionType(PartitionTypeEnum.getPartitionTypeMap().get(rs.getString("partition_type"))); + } catch (SQLException exp) { + GaussUtils.handleCriticalException(exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exp); + } + return part; + } + + /** + * Gets the parent. + * + * @return the parent + */ + public PartitionTable getParent() { + return this.pTable; + } + + /** + * Sets the parent. + * + * @param partTable the new parent + */ + public void setParent(PartitionTable partTable) { + this.pTable = partTable; + } + + /** + * Exec rename. + * + * @param newName the new name + * @param dbConnection the db connection + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void execRename(String newName, DBConnection dbConnection) + throws DatabaseCriticalException, DatabaseOperationException { + + String qry = String.format(Locale.ENGLISH, "ALTER TABLE %s RENAME PARTITION %s TO %s ;", + this.getParent().getQualifiedName(), getQualifiedObjectName(), + ServerObject.getQualifiedObjectName(newName)); + dbConnection.execNonSelect(qry); + getParent().refreshPartition(dbConnection); + + } + + /** + * Exec drop. + * + * @param dbConnection the db connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void execDrop(DBConnection dbConnection) throws DatabaseOperationException, DatabaseCriticalException { + String qry = String.format(Locale.ENGLISH, "ALTER TABLE %s DROP PARTITION %s", + this.getParent().getDisplayName(), getDisplayName()); + dbConnection.execNonSelect(qry); + this.pTable.getNamespace().refreshTable(this.pTable, dbConnection, false); + if (isRollBack) { + isRollBack = false; + } + } + + /** + * Form create partitions qry. + * + * @param List the partition column expr list + * @return String the partition query string + */ + public String formCreatePartitionsQry(List list) { + setPartitionTypeToMethod(); + return getPartitionTypeToMethod().get(getPartitionType()).convert(list); + } + + /** + * Form create partitions qry by range. + * + * @param List the partition column expr list + * @return String the partition query string + */ + public String formCreatePartitionsQryByRange(List list) { + StringBuilder sbPartition = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sbPartition.append("partition "); + sbPartition.append(ServerObject.getQualifiedObjectName(getPartitionName())); + sbPartition.append(" values less than "); + sbPartition.append("("); + sbPartition.append(composePartitionValuePart(list)); + sbPartition.append(")"); + if (getTs() != null) { + sbPartition.append(" tablespace "); + sbPartition.append(getTs().getDisplayName()); + } + return sbPartition.toString(); + } + + /** + * Form create partitions qry by interval. + * + * @param List the partition column expr list + * @return String the partition query string + */ + public String formCreatePartitionsQryByInterval(List list) { + return formCreatePartitionsQryByRange(list); + } + + /** + * Form create partitions qry by hash. + * + * @param List the partition column expr list + * @return String the partition query string + */ + public String formCreatePartitionsQryByHash(List list) { + StringBuilder sbPartition = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sbPartition.append("partition "); + sbPartition.append(ServerObject.getQualifiedObjectName(getPartitionName())); + if (getTs() != null) { + sbPartition.append(" tablespace "); + sbPartition.append(getTs().getDisplayName()); + } + return sbPartition.toString(); + } + + /** + * Form create partitions qry by list. + * + * @param List the partition column expr list + * @return String the partition query string + */ + public String formCreatePartitionsQryByList(List list) { + StringBuilder sbPartition = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sbPartition.append("partition "); + sbPartition.append(ServerObject.getQualifiedObjectName(getPartitionName())); + sbPartition.append(" values ("); + sbPartition.append(getPartitionValue()); + sbPartition.append(")"); + if (getTs() != null) { + sbPartition.append(" tablespace "); + sbPartition.append(getTs().getDisplayName()); + } + return sbPartition.toString(); + } + + /** + * Compose partition value part. + * + * @param list the list + * @return the string + */ + private String composePartitionValuePart(List list) { + String value = getPartitionValue(); + List splittedColNames = Arrays.asList(value.split(",", -1)); + StringBuilder strbulder = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + if (!splittedColNames.isEmpty()) { + int colIdx = 0; + for (Iterator iterator = splittedColNames.iterator(); iterator.hasNext();) { + String colValue = (String) iterator.next(); + + if (isNumberType(list.get(colIdx).getCol().getDataType().getName(), colValue)) { + strbulder.append(colValue); + } else { + strbulder.append(ServerObject.isQualifiedPartitionValue(colValue)); + } + + strbulder.append(','); + colIdx++; + } + } + + strbulder.deleteCharAt(strbulder.lastIndexOf(",")); + return strbulder.toString(); + } + + /** + * Checks if is number type. + * + * @param datatypeName the datatype name + * @param value the value + * @return true, if is number type + */ + public static boolean isNumberType(String datatypeName, String value) { + String[] numberDatatypes = {"int4", "integer", "int2", "smallint", "int8", "bigint", "numeric", "decimal", + "float8", "double precision", "float4", "real"}; + String[] dateTimeDatatypes = {"date", "interval", "time", "time without time zone", "timetz", + "time with time zone", "timestamptz", "timestamp with time zone"}; + Arrays.sort(numberDatatypes); + Arrays.sort(dateTimeDatatypes); + + if (Arrays.binarySearch(numberDatatypes, datatypeName) >= 0) { + return true; + } + + if (Arrays.binarySearch(dateTimeDatatypes, datatypeName) >= 0 && "MAXVALUE".equalsIgnoreCase(value)) { + return true; + } + + return false; + } + + @Override + public Database getDatabase() { + return pTable.getDatabase(); + } + + @Override + public String getObjectFullName() { + return getParent().getDisplayName() + "." + getDisplayName(); + } + + @Override + public String getDropQuery(boolean isCascade) { + StringBuilder query = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + query.append("ALTER TABLE IF EXISTS ").append(this.getParent().getDisplayName()).append(" DROP PARTITION ") + .append(getDisplayName()); + + // No cascade support + + return query.toString(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/PartitionTable.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/PartitionTable.java new file mode 100644 index 0000000000000000000000000000000000000000..762df9caa1d83b92a25284d7ef40b24c2a2b1e3b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/PartitionTable.java @@ -0,0 +1,979 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.bl.serverdatacache.groups.OLAPObjectList; +import org.opengauss.mppdbide.bl.serverdatacache.groups.PartitionList; +import org.opengauss.mppdbide.bl.serverdatacache.groups.TableObjectGroup; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class PartitionTable. + * + */ + +public class PartitionTable extends TableMetaData { + + private PartitionList partitions; + + private List selCols; + + private String partKey; + + /** + * The Constant PARTITION_INDEX_QUERY. + */ + public static final String PARTITION_INDEX_QUERY = "SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, " + + "ci.relnamespace as namespaceid, " + + "ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, " + + "i.indisexclusion as isexclusion," + + " i.indimmediate as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, " + + "i.indisready as isready, " + + "i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions, def.indexdef, def.tablespace " + + "FROM pg_index i" + " LEFT JOIN pg_class t on (t.oid = i.indrelid) " + + "LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) " + + "LEFT JOIN pg_namespace ns on (ci.relnamespace = ns.oid) " + + "LEFT JOIN pg_indexes def on (ci.relname = def.indexname and ns.nspname = def.schemaname) " + + "WHERE t.relkind in ('r', 'f', 'I') " + "and ci.parttype in ('p','n') "; + + /** + * Instantiates a new partition table. + * + * @param ns the ns + */ + public PartitionTable(Namespace ns) { + super(0, "notablename", ns, null, OBJECTTYPE.PARTITION_TABLE); + this.partitions = new PartitionList(OBJECTTYPE.PARTITION_GROUP, this); + } + + /** + * Instantiates a new partition table. + * + * @param ns the ns + * @param objType the obj type + */ + public PartitionTable(Namespace ns, OBJECTTYPE objType) { + super(0, "notablename", ns, null, objType); + this.partitions = new PartitionList(OBJECTTYPE.PARTITION_GROUP, this); + } + + private String getPartitionType() { + if (this.partitions == null || this.partitions.getSize() <= 0) { + return PartitionTypeEnum.BY_RANGE.getTypeName(); + } + return this.partitions.getList().get(0).getPartitionType(); + } + + private String getIntervalPartitionExpr() { + if (this.partitions == null || this.partitions.getSize() <= 0) { + return ""; + } + int size = this.partitions.getList().size(); + return this.partitions.getList().get(size - 1).getIntervalPartitionExpr(); + } + + /** + * Form partition queries. + * + * @return the string + */ + public String formPartitionQueries() { + StringBuilder query = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + List partList = this.partitions.getList(); + int size = partList.size(); + + appendPartitionColumns(query, size); + + // Adding partitions + for (int index = 0; index < size; index++) { + appendPartitionQuery(query, partList, size, index); + } + + if (size > 0) { + query.append(MPPDBIDEConstants.LINE_SEPARATOR).append(");"); + } + return query.toString(); + } + + private void appendPartitionQuery(StringBuilder query, List partList, int size, int index) { + if (index == size - 1) { + query.append(partList.get(index).formCreatePartitionsQry(getSelColumns())); + } else { + query.append(partList.get(index).formCreatePartitionsQry(getSelColumns())).append(",") + .append(MPPDBIDEConstants.LINE_SEPARATOR); + } + } + + private void appendPartitionColumns(StringBuilder query, int size) { + if (size > 0) { + query.append(MPPDBIDEConstants.LINE_SEPARATOR); + query.append(formCreatePartitionColumnsQry()); + query.append("( ").append(MPPDBIDEConstants.LINE_SEPARATOR); + } + } + + /** + * Form create partition columns qry. + * + * @return the string + */ + private String formCreatePartitionColumnsQry() { + String selCol = null; + List selectedColumns = null; + + StringBuilder sbPartitionCol = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + selectedColumns = getSelColumns(); + if (PartitionTypeEnum.BY_INTERVAL.getTypeName().equals(getPartitionType())) { + sbPartitionCol.append("PARTITION BY RANGE"); + } else { + sbPartitionCol.append("PARTITION " + getPartitionType()); + } + + sbPartitionCol.append("("); + + int size = selectedColumns.size(); + + for (int index = 0; index < size; index++) { + selCol = ServerObject.getQualifiedObjectName(selectedColumns.get(index).toString()); + if (index == size - 1) { + sbPartitionCol.append(selCol); + } else { + sbPartitionCol.append(selCol).append(", "); + } + } + + sbPartitionCol.append(")"); + if (PartitionTypeEnum.BY_INTERVAL.getTypeName().equals(getPartitionType())) { + sbPartitionCol.append(MPPDBIDEConstants.LINE_SEPARATOR); + sbPartitionCol.append("interval ('"); + sbPartitionCol.append(getIntervalPartitionExpr()); + sbPartitionCol.append("')"); + } + + return sbPartitionCol.toString(); + } + + /** + * Gets the oid. + * + * @return the oid + */ + public long getOid() { + return super.getOid(); + } + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + return super.getName(); + } + + /** + * Gets the column info. + * + * @param ptabGroup the ptab group + * @param conn the conn + * @param ns the ns + * @param oid the oid + * @return the column info + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static void getColumnInfo(TableObjectGroup ptabGroup, DBConnection conn, Namespace ns, long oid) + throws DatabaseCriticalException, DatabaseOperationException { + String qry = "WITH tbl AS ( select oid as tableid,relnamespace as namespaceid from pg_class where relnamespace = " + + " %dand relkind <> 'i' and parttype in ('p', 'v')), " + + "attr AS ( select c.attnum as columnidx,c.attname as name , pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns,c.atttypid as datatypeoid " + + ",c.attlen as length,c.atttypmod as precision,c.attndims as dimentions,c.attnotnull as notnull,c.atthasdef as isdefaultvalueavailable,c.attrelid as tableoid " + + "from pg_attribute c where c.attrelid in (select tableid from tbl) and c.attisdropped = 'f' and c.attnum > 0), dtype AS (select typ.typnamespace as dtns,oid from pg_type typ " + + "where typ.oid in (select datatypeoid from attr) ), attrdef AS ( select d.adsrc as default_value ,d.adbin as attDefStr ,adrelid,adnum from pg_attrdef d " + + "where d.adrelid in ( select tableid from tbl) and d.adnum in( select columnidx from attr))" + + "select t.tableid as tableid ,t.namespaceid as namespaceid,c.columnidx,c.name,c.displaycolumns,c.datatypeoid,typ.dtns,c.length,c.precision,c.dimentions,c.notnull,c.isdefaultvalueavailable," + + "default_value, d.attDefStr FROM tbl t LEFT JOIN attr c ON(t.tableid = c.tableoid) LEFT JOIN attrdef d ON(t.tableid = d.adrelid AND c.columnidx = d.adnum) LEFT JOIN dtype typ ON (c.datatypeoid = typ.oid) ORDER BY t.tableid ,c.columnidx;"; + qry = String.format(Locale.ENGLISH, qry, oid); + getColumnIndoByExecuteQuery(ptabGroup, conn, ns, qry); + } + + /** + * Gets the column indo by execute query. + * + * @param ptabGroup the ptab group + * @param conn the conn + * @param ns the ns + * @param qry the qry + * @return the column indo by execute query + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static void getColumnIndoByExecuteQuery(TableObjectGroup ptabGroup, DBConnection conn, Namespace ns, + String qry) throws DatabaseCriticalException, DatabaseOperationException { + ResultSet rs = conn.execSelectAndReturnRs(qry); + try { + boolean hasNext = rs.next(); + while (hasNext) { + hasNext = getColumnDataType(ptabGroup, ns, rs); + } + } catch (SQLException sqlException) { + GaussUtils.handleCriticalException(sqlException); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, sqlException); + } finally { + conn.closeResultSet(rs); + } + } + + private static boolean getColumnDataType(TableObjectGroup ptabGroup, Namespace ns, ResultSet rs) + throws SQLException, DatabaseOperationException, DatabaseCriticalException { + boolean hasNext; + long tableId = rs.getLong("tableid"); + TableMetaData tbl = ptabGroup.getObjectById(tableId); + long datatypeid = rs.getLong("datatypeoid"); + + Namespace dtNamspace = ns.getDatabase().getNameSpaceById(rs.getLong("dtns")); + + TypeMetaData type = TypeMetaData.getTypeById(dtNamspace, datatypeid); + + if (tbl == null) { + validateNamespacePrivilege(ns); + } else { + tbl.convertToColumnMetaData(rs, type); + } + hasNext = rs.next(); + return hasNext; + } + + private static void validateNamespacePrivilege(Namespace ns) throws DatabaseOperationException { + if (!ns.getPrivilegeFlag()) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID)); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } + } + + /** + * Gets the column info. + * + * @param conn the conn + * @return the column info + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void getColumnInfo(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + String qry = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, " + + " pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, " + + " c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod " + + " as precision, c.attndims as dimentions, " + + " c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as " + + " default_value, d.adbin as attDefStr " + " from pg_class t " + + " left join pg_attribute c on (t.oid = c.attrelid and t.parttype in ('p', 'v')) " + + " left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) " + + " left join pg_type typ on (c.atttypid = typ.oid) " + + " where c.attisdropped = 'f' and c.attnum > 0 and t.oid = %d and t.relkind <> 'i' " + + " order by c.attnum;"; + qry = String.format(Locale.ENGLISH, qry, this.getOid()); + ResultSet rs = conn.execSelectAndReturnRs(qry); + + try { + boolean hasNext = rs.next(); + while (hasNext) { + long datatypeid = rs.getLong("datatypeoid"); + + Namespace dtNamspace = this.getDatabase().getNameSpaceById(rs.getLong("dtns")); + + TypeMetaData type = TypeMetaData.getTypeById(dtNamspace, datatypeid); + this.convertToColumnMetaData(rs, type); + + hasNext = rs.next(); + + } + } catch (SQLException sqlException) { + GaussUtils.handleCriticalException(sqlException); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, sqlException); + } finally { + conn.closeResultSet(rs); + } + + } + + /** + * Gets the partition constraints. + * + * @param ptabgroup the ptabgroup + * @param conn the conn + * @param ns the ns + * @param oid the oid + * @return the partition constraints + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static void getPartitionConstraints(TableObjectGroup ptabgroup, DBConnection conn, Namespace ns, long oid) + throws DatabaseCriticalException, DatabaseOperationException { + String qry = "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, " + + "c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, " + + "c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, " + + "c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, " + + "c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, " + + "c.confkey as fkeycolumnlist, " + "pg_get_constraintdef(c.oid) as const_def " + + "FROM pg_constraint c join pg_class cl on c.conrelid = cl.oid where c.connamespace=%d" + + " and cl.parttype in ('p','v')" + " and c.conrelid <> 0" + ';'; + qry = String.format(Locale.ENGLISH, qry, oid); + ResultSet rs = conn.execSelectAndReturnRs(qry); + boolean hasNext = false; + + try { + hasNext = rs.next(); + while (hasNext) { + hasNext = addPartConstraints(ptabgroup, ns, rs); + } + } catch (SQLException sqlException) { + GaussUtils.handleCriticalException(sqlException); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, sqlException); + } finally { + conn.closeResultSet(rs); + } + + } + + private static boolean addPartConstraints(TableObjectGroup ptabgroup, Namespace ns, ResultSet rs) + throws SQLException, DatabaseOperationException { + boolean hasNext; + long namespaceid = rs.getLong("namespaceid"); + Namespace nsp = ns.getDatabase().getNameSpaceById(namespaceid); + + long ptableId = rs.getLong("tableid"); + + TableMetaData ptbl = (TableMetaData) ptabgroup.getObjectById(ptableId); + /* + * ptbl can be null in case of the user doesnt have access privilege to + * ptbl. Since table is the lowest level of object that get filtered by + * privilege, all constraints are fetched + */ + TableMetaData fkeyTable = (TableMetaData) ptabgroup.getObjectById(rs.getLong("fkeytableId")); + if (ptbl == null) { + validateNamespacePrivilege(ns); + } else { + ptbl.addConstraint(rs, nsp, fkeyTable); + } + + hasNext = rs.next(); + return hasNext; + } + + /** + * Gets the partition constraints. + * + * @param conn the conn + * @return the partition constraints + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void getPartitionConstraints(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + String qry = "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, " + + "c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, " + + "c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, " + + "c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, " + + "c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, " + + "c.confkey as fkeycolumnlist, " + "pg_get_constraintdef(c.oid) as const_def " + + "FROM pg_constraint c join pg_class cl on c.conrelid = cl.oid where c.conrelid=%d" + + " and cl.parttype in ('p','v')" + " and c.conrelid <> 0" + ';'; + qry = String.format(Locale.ENGLISH, qry, this.getOid()); + ResultSet rs = conn.execSelectAndReturnRs(qry); + boolean hasNext = false; + + try { + hasNext = rs.next(); + while (hasNext) { + hasNext = addPartitionConstraints(rs); + } + } catch (SQLException sqlException) { + GaussUtils.handleCriticalException(sqlException); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, sqlException); + } finally { + conn.closeResultSet(rs); + } + + } + + private boolean addPartitionConstraints(ResultSet rs) throws SQLException, DatabaseOperationException { + boolean hasNext; + long namespaceid = rs.getLong("namespaceid"); + Namespace nsp = this.getDatabase().getNameSpaceById(namespaceid); + + PartitionTable fkeyTable = nsp.getTableObjectById(rs.getLong("fkeytableId")); + fkeyTable = getForeignTableKey(rs, nsp, fkeyTable); + + this.addConstraint(rs, nsp, fkeyTable); + + hasNext = rs.next(); + return hasNext; + } + + private PartitionTable getForeignTableKey(ResultSet rs, Namespace nsp, PartitionTable fkeyTableParam) + throws SQLException { + PartitionTable fkeyTable = fkeyTableParam; + if (fkeyTable == null) { + fkeyTable = nsp.getForeignTableById(rs.getLong("fkeytableId")); + } + return fkeyTable; + } + + /** + * Gets the partition indexes. + * + * @param ptabGroup the ptab group + * @param conn the conn + * @param ns the ns + * @param oid the oid + * @return the partition indexes + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public static void getPartitionIndexes(TableObjectGroup ptabGroup, DBConnection conn, Namespace ns, long oid) + throws DatabaseOperationException, DatabaseCriticalException { + String query = String.format(Locale.ENGLISH, + PartitionTable.PARTITION_INDEX_QUERY + " and ci.relnamespace = %d;", oid); + + ResultSet resultSet = conn.execSelectAndReturnRs(query); + boolean hasNext = false; + + try { + hasNext = resultSet.next(); + while (hasNext) { + hasNext = addPArtitionTableIndex(ptabGroup, ns, resultSet); + } + } catch (SQLException sqlException) { + GaussUtils.handleCriticalException(sqlException); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, sqlException); + } finally { + conn.closeResultSet(resultSet); + } + + } + + private static boolean addPArtitionTableIndex(TableObjectGroup ptabGroup, Namespace ns, ResultSet resultSet) + throws DatabaseOperationException, SQLException { + boolean hasNext; + ns.getDatabase().getNameSpaceById(resultSet.getLong("namespaceid")); + TableMetaData table = (TableMetaData) ptabGroup.getObjectById(resultSet.getLong("tableId")); + if (table == null) { + validateNamespacePrivilege(ns); + } else { + table.addIndex(resultSet); + } + hasNext = resultSet.next(); + return hasNext; + } + + /** + * Gets the partition indexes. + * + * @param conn the conn + * @return the partition indexes + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + private void getPartitionIndexes(DBConnection conn) throws DatabaseOperationException, DatabaseCriticalException { + String qry = String.format(Locale.ENGLISH, PartitionTable.PARTITION_INDEX_QUERY + + "and ci.relnamespace = %d and tableid= %d;", + this.getNamespace().getOid(), this.getOid()); + ResultSet resultSet = conn.execSelectAndReturnRs(qry); + boolean hasNext = false; + + try { + hasNext = resultSet.next(); + while (hasNext) { + this.addIndex(resultSet); + hasNext = resultSet.next(); + } + } catch (SQLException sqlException) { + GaussUtils.handleCriticalException(sqlException); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, sqlException); + } finally { + conn.closeResultSet(resultSet); + } + } + + /** + * Sets the part key. + * + * @param partKey the new part key + */ + protected void setPartKey(String partKey) { + this.partKey = partKey; + } + + /** + * Gets the part key. + * + * @return the part key + */ + public String getPartKey() { + if (this.partKey != null && !this.getColumnMetaDataList().isEmpty()) { + List splittedColNames = Arrays.asList(this.partKey.split(",")); + StringBuilder str = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + appendColumnName(splittedColNames, str); + str.deleteCharAt(str.length() - 1); + + return str.toString(); + } + return this.partKey; + } + + private void appendColumnName(List splittedColNames, StringBuilder str) { + int index = 0; + for (ColumnMetaData colMetadata : this.getColumnMetaDataList()) { + if (index == splittedColNames.size()) { + break; + } + index = appendColumnName(splittedColNames, str, index, colMetadata); + } + } + + private int appendColumnName(List splittedColNames, StringBuilder str, int indexParam, + ColumnMetaData colMetadata) { + int index = indexParam; + if (colMetadata.getOid() == Integer.parseInt(splittedColNames.get(index))) { + str.append(colMetadata.getName()); + str.append(","); + index++; + } + return index; + } + + /** + * Gets the partitions. + * + * @param ptabGroup the ptab group + * @param conn the conn + * @param ns the ns + * @param oid the oid + * @return the partitions + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static void getPartitions(TableObjectGroup ptabGroup, DBConnection conn, Namespace ns, long oid) + throws DatabaseCriticalException, DatabaseOperationException { + /* + * We get the partition details only for the non HDFS partition tables. + * SO the partition type is restricted to 'p' + */ + String qry = "select p.oid AS partition_id " + ", p.relname AS partition_name," + + " p.partstrategy as partition_type," + " p.parentid AS table_id " + + " from pg_class c, pg_partition p " + " where c.relnamespace = %d and c.parttype = 'p' " + + " and p.parentid = c.oid " + " and p.parttype = 'p' " + " order by p.boundaries;"; + qry = String.format(Locale.ENGLISH, qry, oid); + ResultSet rs = conn.execSelectAndReturnRs(qry); + + try { + boolean hasNext = rs.next(); + while (hasNext) { + hasNext = addPartitionTable(ptabGroup, ns, rs); + } + } catch (SQLException sqlException) { + GaussUtils.handleCriticalException(sqlException); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, sqlException); + } finally { + conn.closeResultSet(rs); + } + + } + + private static boolean addPartitionTable(TableObjectGroup ptabGroup, Namespace ns, ResultSet rs) + throws SQLException, DatabaseOperationException, DatabaseCriticalException { + boolean hasNext; + long tableId = rs.getLong("table_id"); + PartitionTable tbl = (PartitionTable) ptabGroup.getObjectById(tableId); + if (tbl == null) { + validateNamespacePrivilege(ns); + } else { + tbl.convertToPartitionMetaData(rs); + } + + hasNext = rs.next(); + return hasNext; + } + + /** + * Gets the partitions. + * + * @param conn the conn + * @return the partitions + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void getPartitions(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + /* + * We get the partition details only for the non HDFS partition tables. + * SO the partition type is restricted to 'p' + */ + String qry = "select p.oid AS partition_id " + ", p.relname AS partition_name," + + " p.partstrategy as partition_type," + " p.parentid AS table_id " + + " from pg_class c, pg_partition p " + " where c.oid = %d and c.parttype = 'p' " + + " and p.parentid = c.oid " + " and p.parttype = 'p' " + " order by p.boundaries;"; + qry = String.format(Locale.ENGLISH, qry, this.getOid()); + ResultSet rs = conn.execSelectAndReturnRs(qry); + + try { + boolean hasNext = rs.next(); + while (hasNext) { + this.convertToPartitionMetaData(rs); + hasNext = rs.next(); + } + } catch (SQLException sqlException) { + GaussUtils.handleCriticalException(sqlException); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, sqlException); + } finally { + conn.closeResultSet(rs); + } + + } + + /** + * Convert to partition meta data. + * + * @param rs the rs + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void convertToPartitionMetaData(ResultSet rs) throws DatabaseCriticalException, DatabaseOperationException { + if (isLevel3Loaded()) { + return; + } + + PartitionMetaData part = PartitionMetaData.convertToPartitionMetaData(rs, this, getDatabase()); + + getPartitions().addItem(part); + + } + + /** + * Gets the partitions. + * + * @return the partitions + */ + public OLAPObjectList getPartitions() { + return this.partitions; + } + + /** + * Gets the children. + * + * @return children + */ + @Override + public Object[] getChildren() { + Object[] parntObjs = super.getChildren(); + ArrayList abc = new ArrayList(parntObjs.length + 1); + int index = 0; + + index = addObject(parntObjs, abc); + + abc.add(index, this.partitions); + return abc.toArray(); + } + + private int addObject(Object[] parntObjs, ArrayList abc) { + int index; + Object obj; + for (index = 0; index < parntObjs.length; index++) { + obj = parntObjs[index]; + abc.add(index, obj); + } + return index; + } + + @Override + public void execCreate(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + StringBuilder qry = new StringBuilder(formCreateQuery()); + int partitionSize = this.partitions.getSize(); + if (partitionSize > 0) { + qry.deleteCharAt(qry.length() - 1); + qry.append(this.formPartitionQueries()); + } + qry.append(formTableCommentQuery()); + qry.append(formColumnCommentQuery()); + conn.execNonSelect(qry.toString()); + execCreateTAbleQuery(conn); + getNamespace().getNewlyCreatedTable(getName()); + + } + + private void execCreateTAbleQuery(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + int indexSize = 0; + try { + List indexList = this.getIndexes().getList(); + indexSize = indexList.size(); + + for (int i = 0; i < indexSize; i++) { + conn.execNonSelect(indexList.get(i).formCreateQuery(true)); + } + } catch (DatabaseOperationException dbOperationException) { + rollbackTableCreate(indexSize, conn); + throw dbOperationException; + } + } + + @Override + public void execDrop(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + String dropQry = String.format(Locale.ENGLISH, "DROP TABLE %s;", this.getDisplayName()); + conn.execNonSelect(dropQry); + this.getNamespace().removeTableFRomSearchPool(getSearchName()); + this.getNamespace().refreshAllTableMetadataInNamespace(conn); + + if (isRollBack) { + isRollBack = false; + } + } + + /** + * Removes the partition. + * + * @param pos the pos + */ + public void removePartition(int pos) { + + partitions.removeItemByIdx(pos); + } + + /** + * Removes the all partition. + */ + public void removeAllPartition() { + int size = partitions.getSize(); + if (size > 0) { + partitions.clear(); + } + } + + /** + * Gets the namespace. + * + * @return namespace + */ + public Namespace getNamespace() { + return super.getNamespace(); + } + + /** + * Adds the partition. + * + * @param partition the partition + */ + public void addPartition(PartitionMetaData partition) { + partitions.addItem(partition); + } + + /** + * Move partition. + * + * @param index the index + * @param up the up + */ + public void movePartition(int index, boolean up) { + this.partitions.moveItem(index, up); + } + + // CHECKSTYLE:OFF: + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Sets the sel columns. + * + * @param selColumns the new sel columns + */ + public void setSelColumns(List selColumns) { + selCols = selColumns; + } + + /** + * Gets the sel columns. + * + * @return the sel columns + */ + public List getSelColumns() { + return selCols; + } + + /** + * Gets the search name. + * + * @return name + */ + @Override + public String getSearchName() { + + return getName() + " - " + getNamespace().getName() + " - " + getTypeLabel(); + } + + /** + * clearDetailsCached + */ + public void clearDetailsCached() { + super.clearDetailsCached(); + this.getPartitions().clear(); + } + + /** + * Refresh table details. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void refreshTableDetails(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + clearDetailsCached(); + this.getColumnInfo(conn); + this.getPartitionConstraints(conn); + this.getPartitionIndexes(conn); + this.getPartitions(conn); + this.setLevel3Loaded(true); + this.setLoaded(true); + } + + /** + * Refresh partition. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void refreshPartition(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + this.getPartitions().clear(); + setLevel3Loaded(false); + this.getPartitions(conn); + } + + /** + * Checks if is table dropped. + * + * @return isTabelDropped + */ + @Override + public boolean isTableDropped() { + Namespace ns = getNamespace(); + if (null == ns) { + return true; + } + return ns.validateAndGetTableObjGrp(getOid()); + } + + /** + * Removes the. + * + * @param obj the obj + */ + public void remove(ServerObject obj) { + if (obj instanceof PartitionMetaData) { + if (partitions != null) { + partitions.remove((PartitionMetaData) obj); + } + + return; + } + + super.remove(obj); + } + + /** + * Convert to partition table. + * + * @param rs the rs + * @param ns the ns + * @return the partition table + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws SQLException the SQL exception + */ + public static PartitionTable convertToPartitionTable(ResultSet rs, Namespace ns) + throws DatabaseOperationException, DatabaseCriticalException, SQLException { + PartitionTable ptab = new PartitionTable(ns); + ptab.fillTablePropertiesFromRS(rs); + ptab.setPartKey(rs.getString("partkey")); + ptab.setLoaded(false); + ns.addTableToGivenSearchPool(ptab); + + return ptab; + } + + /** + * Checks if is partitions available. + * + * @return true, if is partitions available + */ + public boolean isPartitionsAvailable() { + return getPartitions().getSize() > 0; + } + + /** + * Gets the columns list. + * + * @return the columns list + */ + public ArrayList getColumnsList() { + return this.getColumns().getList(); + } + + /** + * Validate for duplicate name. + * + * @param partName the part name + * @throws DatabaseOperationException the database operation exception + */ + public void validateForDuplicateName(String partName) throws DatabaseOperationException { + OLAPObjectList metaDatas = getPartitions(); + + int size = metaDatas.getSize(); + PartitionMetaData data = null; + for (int index = 0; index < size; index++) { + data = metaDatas.getItem(index); + if (data.getName().trim().equalsIgnoreCase(partName)) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DUPLICATE_PARTITION_NAME)); + throw new DatabaseOperationException(IMessagesConstants.ERR_DUPLICATE_PARTITION_NAME); + } + + } + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/PartitionTypeEnum.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/PartitionTypeEnum.java new file mode 100644 index 0000000000000000000000000000000000000000..472362c0ad9236f9392a73be30974b34d1a2396a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/PartitionTypeEnum.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +/** + * + * Title: enum class + * + * Description: The Class PartitionTypeEnum + * + * @since 3.0.0 + */ +public enum PartitionTypeEnum { + BY_RANGE("r", "BY RANGE"), + BY_INTERVAL("i", "BY INTERVAL"), + BY_LIST("l", "BY LIST"), + BY_HASH("h", "BY HASH"); + + private String typeCode; + private String typeName; + + PartitionTypeEnum(String typeCode, String typeName) { + this.typeCode = typeCode; + this.typeName = typeName; + } + + /** + * Gets the type code + * + * @return String the type code + */ + public String getTypeCode () { + return typeCode; + } + + /** + * Gets the type name + * + * @return String the type name + */ + public String getTypeName() { + return typeName; + } + + /** + * Gets the partition type map + * + * @return Map the partition type map + */ + public static Map getPartitionTypeMap() { + Map partitionTypeMap = new HashMap(); + for (PartitionTypeEnum partType : PartitionTypeEnum.values()) { + partitionTypeMap.put(partType.getTypeCode(), partType.getTypeName()); + } + return partitionTypeMap; + } + + /** + * Gets the partition type name array + * + * @return String[] the partition type name array + */ + public static String[] getPartitionTypeNameArray() { + ArrayList arrayList = new ArrayList(); + for (PartitionTypeEnum part : PartitionTypeEnum.values()) { + arrayList.add(part.getTypeName()); + } + String[] partitionTypeNameArray = new String[arrayList.size()]; + partitionTypeNameArray = (String []) arrayList.toArray(partitionTypeNameArray); + return partitionTypeNameArray; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ProfileDiskUtility.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ProfileDiskUtility.java new file mode 100644 index 0000000000000000000000000000000000000000..3ae16004a52b95d37f7bc1af344dfff84657eac2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ProfileDiskUtility.java @@ -0,0 +1,696 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.io.File; +import java.io.IOException; +import java.io.Serializable; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.StringTokenizer; + +import org.apache.commons.io.FileUtils; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonSyntaxException; +import com.google.gson.reflect.TypeToken; +import org.opengauss.mppdbide.bl.serverdatacache.ProfileMetaData.ProfileInfo; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.DBTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfoJsonValidator; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.connectionupgrade.ConnectionProfileUpgradeManager; +import org.opengauss.mppdbide.bl.util.ExecTimer; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.connectionprofileversion.IConnectionProfileVersions; +import org.opengauss.mppdbide.utils.exceptions.DataStudioSecurityException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.FileOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.files.DSFolderDeleteUtility; +import org.opengauss.mppdbide.utils.files.FilePermissionFactory; +import org.opengauss.mppdbide.utils.files.ISetFilePermission; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; + +/** + * + * Title: class + * + * Description: The Class ProfileDiskUtility. + * + */ + +public class ProfileDiskUtility { + + private static final int CONNECTION_PROPERTIES_SIZE = 2 * 1024 * 1024; + + private static final String PROFILE_FOLDERNAME_PREFIX = "PROFILE"; + + private static List serverList = new ArrayList(2); + + private static List pswdDecFailList = new ArrayList(2); + + private static List exceptionList = new ArrayList(2); + + private String osCurrentUserFolderPath; + private Path profileFolderPath; + private ProfileMetaData metaData; + + /** + * Instantiates a new profile disk utility. + */ + public ProfileDiskUtility() { + this.metaData = new ProfileMetaData(); + } + + /** + * Gets the meta data. + * + * @return the meta data + */ + public ProfileMetaData getMetaData() { + return metaData; + } + + /** + * Sets the meta data. + * + * @param metaData the new meta data + */ + public void setMetaData(ProfileMetaData metaData) { + this.metaData = metaData; + } + + /** + * Gets the user profile folder name. + * + * @param profileId the profile id + * @return the user profile folder name + */ + public String getUserProfileFolderName(String profileId) { + return PROFILE_FOLDERNAME_PREFIX + profileId; + } + + /** + * Write profile to disk. + * + * @param serverInfo the server info + * @throws DatabaseOperationException the database operation exception + * @throws DataStudioSecurityException the data studio security exception + */ + public void writeProfileToDisk(IServerConnectionInfo serverInfo) + throws DatabaseOperationException, DataStudioSecurityException { + Path parentFolder = null; + Path file = null; + try { + + parentFolder = createFolderStructure(getUserProfileFolderName(serverInfo.getProfileId())); + Path propFile = Paths.get(parentFolder.toString(), MPPDBIDEConstants.CONNECTION_PROFILE_NAME); + file = createConnectionPropFileIfNotExists(propFile); + writeProfileToFile(file, serverInfo); + getMetaData().addProfile(serverInfo.getConectionName(), serverInfo.getProfileId(), propFile.toString(), + serverInfo.getVersion()); + + writeProfileMetaFile(); + + } catch (IOException | FileOperationException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_PROFILE_WRITE_DISK), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_PROFILE_WRITE_DISK, exception); + } + MPPDBIDELoggerUtility.operationInfo("Created/Updated user profile :" + serverInfo.getProfileId()); + } + + /** + * Rename profile on disk. + * + * @param serverConnInfo the server info + * @throws DatabaseOperationException the database operation exception + * @throws DataStudioSecurityException the data studio security exception + */ + public void renameProfileOnDisk(IServerConnectionInfo serverConnInfo) + throws DatabaseOperationException, DataStudioSecurityException { + Path parentFolder = null; + Path file = null; + try { + parentFolder = getConnectionProfilepath(getUserProfileFolderName(serverConnInfo.getProfileId())); + Path propFilePath = Paths.get(parentFolder.toString(), MPPDBIDEConstants.CONNECTION_PROFILE_NAME); + file = createConnectionPropFileIfNotExists(propFilePath); + writeProfileToFile(file, serverConnInfo); + getMetaData().addProfile(serverConnInfo.getConectionName(), serverConnInfo.getProfileId(), + propFilePath.toString(), serverConnInfo.getVersion()); + + writeProfileMetaFile(); + } catch (IOException | FileOperationException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_PROFILE_WRITE_DISK), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_PROFILE_WRITE_DISK, exception); + } + MPPDBIDELoggerUtility.operationInfo("Renamed user profile :" + serverConnInfo.getProfileId()); + } + + /** + * Write profile to file. + * + * @param file the file + * @param serverInfo the server info + * @throws IOException Signals that an I/O exception has occurred. + */ + private void writeProfileToFile(Path file, IServerConnectionInfo serverInfo) throws IOException { + List lstServerInfo = new ArrayList(1); + + Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); + Type type = getType(); + lstServerInfo.add(serverInfo); + String json = gson.toJson(lstServerInfo, type); + Files.write(file, json.getBytes(StandardCharsets.UTF_8), StandardOpenOption.TRUNCATE_EXISTING); + } + + /** + * Gets the type. + * + * @return the type + */ + private Type getType() { + return new ProfileTypeToken().getType(); + } + + /** + * + * Title: class + * + * Description: The Class ProfileTypeToken. + * + */ + private static final class ProfileTypeToken extends TypeToken> { + } + + /** + * Read profile from file. + * + * @param profileInfo the profile info + * @return the server connection info + */ + public IServerConnectionInfo readProfileFromFile(ProfileInfo profileInfo) { + Path file = Paths.get(profileInfo.getFilePath()); + IServerConnectionInfo serverInfo = null; + try { + double fileSizeInBytes = FileUtils.sizeOf(file.toFile()); + if (fileSizeInBytes > CONNECTION_PROPERTIES_SIZE) { + MPPDBIDELoggerUtility.error("Error while reading profile file. File size exceeded 2MB"); + throw new DatabaseOperationException(IMessagesConstants.ERR_READING_PROFILE_DATA); + } + + if (Files.isReadable(file)) { + byte[] bytes = Files.readAllBytes(file); + if (bytes.length == 0) { + serverList.add(getServerName(file)); + return null; + } + String json = new String(bytes, StandardCharsets.UTF_8); + if (!ServerConnectionInfoJsonValidator.validateJson(json)) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.IMPORT_PROFILE_INCORRECT_FILE)); + throw new DatabaseOperationException(IMessagesConstants.IMPORT_PROFILE_INCORRECT_FILE); + } + Type type = getType(); + List lstServerInfo = null; + if (!profileInfo.getVersionNo().equals(IConnectionProfileVersions.CONNECTION_PROFILE_CURRENT_VERSION)) { + lstServerInfo = getServerInfoObject(json, type, profileInfo.getVersionNo()); + // update the version in metafile + metaData.updateProfileVersion(profileInfo); + writeProfileToFile(Paths.get(profileInfo.getFilePath()), lstServerInfo.get(0)); + writeProfileMetaFile(); + } else { + Gson gson = new Gson(); + lstServerInfo = gson.fromJson(json, type); + } + file.getParent(); + + if (null != lstServerInfo) { + serverInfo = lstServerInfo.size() > 0 ? lstServerInfo.get(0) : null; + } + + } + } catch (IOException e) { + serverList.add(getServerName(file)); + } catch (JsonSyntaxException e) { + serverList.add(getServerName(file)); + } catch (DatabaseOperationException e) { + serverList.add(getServerName(file)); + } + return serverInfo; + } + + /** + * Gets the server info object. + * + * @param jsonString the json string + * @param type the type + * @param profileVersion the profile version + * @return the server info object + */ + private List getServerInfoObject(String jsonString, Type type, String profileVersion) { + + List upgradedConnectionProfiles = ConnectionProfileUpgradeManager.getInstance() + .getUpgradedConnectionProfiles(jsonString, type, profileVersion); + + return upgradedConnectionProfiles; + } + + /** + * Gets the decrypted prd. + * + * @param serverInfo the server info + * @return the decrypted prd + */ + public IServerConnectionInfo getDecryptedPrd(IServerConnectionInfo serverInfo) { + SecureUtil sec = new SecureUtil(); + String path = ConnectionProfileManagerImpl.getInstance().getProfilePath(serverInfo); + sec.setPackagePath(path); + try { + String prd = new String(serverInfo.getPrd()); + serverInfo.setPrd(sec.decryptPrd(prd)); + prd = null; + } catch (DataStudioSecurityException e) { + serverInfo.clearPasrd(); + } catch (NumberFormatException e) { + serverInfo.clearPasrd(); + } + return serverInfo; + } + + /** + * Gets the server name. + * + * @param file the file + * @return the server name + */ + public String getServerName(Path file) { + Path path = file.getParent(); + String dbName = ""; + if (path != null) { + StringTokenizer st2 = new StringTokenizer(path.toString(), "\\"); + while (st2.hasMoreElements()) { + dbName = (String) st2.nextElement(); + } + } + return dbName; + } + + /** + * Gets the profiles. + * + * @return the profiles + * @throws DatabaseOperationException the database operation exception + * @throws DataStudioSecurityException the data studio security exception + * @throws IOException Signals that an I/O exception has occurred. + */ + public List getProfiles() + throws DatabaseOperationException, DataStudioSecurityException, IOException { + List list = new ArrayList(1); + Map maps = getProfilePaths(); + ServerConnectionInfoComparator comparator = new ServerConnectionInfoComparator(); + final int nonExistingIndex = 0; + + Iterator> entrySet = maps.entrySet().iterator(); + Entry data; + boolean isMetadataChanged = false; + boolean hasNext = entrySet.hasNext(); + + while (hasNext) { + data = entrySet.next(); + IServerConnectionInfo serv = readProfileFromFile(data.getValue()); + if (null != serv) { + int insertionPoint = Collections.binarySearch(list, serv, comparator); + + if (insertionPoint < nonExistingIndex) { + insertionPoint = -(insertionPoint + 1); + } + + if (DBTYPE.OPENGAUSS.equals(serv.getServerDBType())) { + list.add(insertionPoint, serv); + } + } else { + getMetaData().deleteProfile(data.getKey()); + String filePath = data.getValue().getFilePath(); + int lastIndex = filePath.lastIndexOf('\\'); + String profilePath = filePath.substring(0, lastIndex); + deleteFolder(Paths.get(profilePath)); + MPPDBIDELoggerUtility.info("Profile deleted successfully"); + isMetadataChanged = true; + } + + hasNext = entrySet.hasNext(); + } + + if (isMetadataChanged) { + writeProfileMetaFile(); + } + + return list; + } + + /** + * Gets the profile paths. + * + * @return the profile paths + * @throws DatabaseOperationException the database operation exception + */ + private Map getProfilePaths() throws DatabaseOperationException { + Path basePath = Paths.get(getConnctionProfileBasePath().toString(), + MPPDBIDEConstants.CONNECTION_PROFILE_META_FILE); + getMetaData().readFromDisk(basePath.toString()); + return getMetaData().getAllProfiles(); + } + + /** + * Write profile meta file. + * + * @return the path + * @throws DatabaseOperationException the database operation exception + */ + public Path writeProfileMetaFile() throws DatabaseOperationException { + Path basePath = getConnctionProfileBasePath(); + Path metaPath = Paths.get(basePath.toString(), MPPDBIDEConstants.CONNECTION_PROFILE_META_FILE); + if (!Files.exists(metaPath, LinkOption.NOFOLLOW_LINKS)) { + FilePermissionFactory.getFilePermissionInstance().createFileWithPermission(metaPath.toString(), false, null, + true); + } + + getMetaData().writeToDisk(metaPath.toString()); + return metaPath; + } + + /** + * Creates the connection prop file if not exists. + * + * @param propFile the prop file + * @return the path + * @throws IOException Signals that an I/O exception has occurred. + * @throws FileOperationException the file operation exception + */ + private Path createConnectionPropFileIfNotExists(Path propFile) + throws IOException, FileOperationException, DatabaseOperationException { + Path propFileAbsolute = propFile.toAbsolutePath().normalize(); + + if (!Files.exists(propFileAbsolute)) { + return FilePermissionFactory.getFilePermissionInstance() + .createFileWithPermission(propFileAbsolute.toString(), false, null, true); + } + + return propFileAbsolute; + } + + /** + * Creates the folder structure. + * + * @param profileFolderName the profile folder name + * @return the path + * @throws IOException Signals that an I/O exception has occurred. + * @throws FileOperationException the file operation exception + */ + public Path createFolderStructure(String profileFolderName) + throws IOException, FileOperationException, DatabaseOperationException { + if (!Files.exists(getConnctionProfileBasePath())) { + FilePermissionFactory.getFilePermissionInstance() + .createFileWithPermission(getConnctionProfileBasePath().toString(), true, null, true); + } + Path folderPath = getConnectionProfilepath(profileFolderName); + FilePermissionFactory.getFilePermissionInstance().createFileWithPermission(folderPath.toString(), true, null, + true); + return folderPath; + } + + /** + * Gets the connection profilepath. + * + * @param profileFolderName the profile folder name + * @return the connection profilepath + */ + public Path getConnectionProfilepath(String profileFolderName) { + Path parentPath = Paths.get(osCurrentUserFolderPath, MPPDBIDEConstants.PROFILE_BASE_PATH, profileFolderName); + return parentPath.normalize(); + } + + /** + * Gets the history profilepath. + * + * @param profileFolderName the profile folder name + * @return the history profilepath + */ + public Path getHistoryProfilepath(String profileFolderName) { + Path historyPath = Paths.get(osCurrentUserFolderPath, MPPDBIDEConstants.PROFILE_BASE_PATH, profileFolderName, + MPPDBIDEConstants.HISTORY_BASE_PATH); + return historyPath.toAbsolutePath().normalize(); + } + + /** + * Gets the connction profile base path. + * + * @return the connction profile base path + */ + public Path getConnctionProfileBasePath() { + return Paths.get(osCurrentUserFolderPath, MPPDBIDEConstants.PROFILE_BASE_PATH); + } + + /** + * Drop profile folder. + * + * @param profileFolderName the profile folder name + * @param profileName the profile name + * @throws DatabaseOperationException the database operation exception + */ + public void dropProfileFolder(String profileFolderName, String profileName) throws DatabaseOperationException { + // Update metadata file first so, any corruption or failure below will + // have least impact on further executions + getMetaData().deleteProfile(profileName); + writeProfileMetaFile(); + + try { + deleteFolder(getConnectionProfilepath(profileFolderName)); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DROP_CON_PROF_FILE), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_DROP_CON_PROF_FILE, exception); + } + } + + /** + * Delete folder. + * + * @param path the path + * @throws IOException Signals that an I/O exception has occurred. + */ + public void deleteFolder(Path path) throws IOException { + Files.walkFileTree(path, new DSFolderDeleteUtility()); + } + + /** + * + * Title: class + * + * Description: The Class ServerConnectionInfoComparator. + * + */ + private static class ServerConnectionInfoComparator implements Comparator, Serializable { + + private static final long serialVersionUID = 1L; + + @Override + public int compare(IServerConnectionInfo object1, IServerConnectionInfo object2) { + return object1.getConectionName().compareTo(object2.getConectionName()); + } + } + + /** + * Gets the exception list. + * + * @return the exception list + */ + public List getExceptionList() { + StringBuilder server = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + if (!serverList.isEmpty()) { + for (String serverName : serverList) { + server.append(serverName); + server.append(","); + } + server.deleteCharAt(server.length() - 1); + + exceptionList + .add(MessageConfigLoader.getProperty(IMessagesConstants.CONN_PROFILE_ERROR_MSG, server.toString())); + serverList.clear(); + } + + if (!pswdDecFailList.isEmpty()) { + server = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + for (String serverName : pswdDecFailList) { + server.append(serverName); + server.append(","); + } + server.deleteCharAt(server.length() - 1); + exceptionList + .add(MessageConfigLoader.getProperty(IMessagesConstants.CIPHER_DECRYPT_ERROR_MSG, server.toString())); + pswdDecFailList.clear(); + } + + return exceptionList; + } + + /** + * Write exported profile to disk. + * + * @param exportFileList the export file list + * @param filePath the file path + * @throws DatabaseOperationException the database operation exception + */ + public void writeExportedProfileToDisk(List exportFileList, String filePath) + throws DatabaseOperationException { + + Path path = Paths.get(filePath).toAbsolutePath().normalize(); + if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) { + Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); + Type type = getType(); + String json = gson.toJson(exportFileList, type); + try { + FilePermissionFactory.getFilePermissionInstance().createFileWithPermission(path.toString(), false, null, + true); + Files.write(path, json.getBytes(StandardCharsets.UTF_8), StandardOpenOption.TRUNCATE_EXISTING); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("Error while writing exported connection profile to the disk", exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_PROFILE_WRITE_DISK, exception); + } + MPPDBIDELoggerUtility.operationInfo("Exported user profiles"); + } + } + + /** + * Read imported file. + * + * @param path the path + * @param fileSizeLimit the file data size limit + * @return the list + * @throws DatabaseOperationException the database operation exception + */ + public List readImportedFile(String path, double fileSizeLimit) + throws DatabaseOperationException { + try { + Path filePath = Paths.get(path); + File file = new File(path); + double fileSizeInMB = FileUtils.sizeOf(file) / (double) (1024 * 1024); + if (fileSizeLimit != 0 && fileSizeInMB > fileSizeLimit) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.FILE_LIMIT_WARNING_MESSAGE)); + throw new MPPDBIDEException(IMessagesConstants.FILE_LIMIT_WARNING_MESSAGE); + } + List serverInfoList = null; + if (Files.exists(filePath, LinkOption.NOFOLLOW_LINKS)) { + byte[] readAllBytes = Files.readAllBytes(filePath); + String json = new String(readAllBytes, StandardCharsets.UTF_8); + if (!ServerConnectionInfoJsonValidator.validateJson(json)) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.IMPORT_PROFILE_INCORRECT_FILE)); + throw new FileOperationException(IMessagesConstants.IMPORT_PROFILE_INCORRECT_FILE); + } + Gson gson = new Gson(); + serverInfoList = gson.fromJson(json, getType()); + if (serverInfoList != null) { + removeNonOlapProfiles(serverInfoList); + } + + return serverInfoList; + } + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("IO Exception occurred while importing the connection profile", exception); + throw new DatabaseOperationException( + MessageConfigLoader.getProperty(IMessagesConstants.ERROR_IMPORTING_CONNECTION_PROFILES), exception); + } catch (JsonSyntaxException exception) { + MPPDBIDELoggerUtility.error("Json exception occurred while reading the json file", exception); + throw new DatabaseOperationException(IMessagesConstants.IMPORT_PROFILE_INCORRECT_FILE, exception); + } catch (FileOperationException mppdbException) { + MPPDBIDELoggerUtility.error("Invalid file format.", mppdbException); + throw new DatabaseOperationException(IMessagesConstants.IMPORT_PROFILE_INCORRECT_FILE, mppdbException); + } catch (MPPDBIDEException mppdbException) { + MPPDBIDELoggerUtility.error("File Size is more than specified.", mppdbException); + throw new DatabaseOperationException(IMessagesConstants.FILE_LIMIT_WARNING_MESSAGE, mppdbException); + } + MPPDBIDELoggerUtility.operationInfo("Imported user profiles"); + return new ArrayList(); + } + + private void removeNonOlapProfiles(List serverInfoList) { + List deleteList = new ArrayList(1); + for (IServerConnectionInfo info : serverInfoList) { + if (!DBTYPE.OPENGAUSS.equals(info.getServerDBType())) { + deleteList.add(info); + } + } + serverInfoList.removeAll(deleteList); + } + + /** + * Sets the os current user folder path. + * + * @param osCurrentUserFolderPath the new os current user folder path + */ + public void setOsCurrentUserFolderPath(String osCurrentUserFolderPath) { + this.osCurrentUserFolderPath = osCurrentUserFolderPath; + } + + /** + * Gets the os current user folder path. + * + * @return the os current user folder path + */ + public String getOsCurrentUserFolderPath() { + return osCurrentUserFolderPath; + } + + /** + * Gets the profile folder path. + * + * @return the profile folder path + */ + public Path getProfileFolderPath() { + profileFolderPath = getConnctionProfileBasePath(); + return profileFolderPath; + } + + /** + * Clear exception list. + */ + public void clearExceptionList() { + exceptionList.clear(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ProfileMetaData.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ProfileMetaData.java new file mode 100644 index 0000000000000000000000000000000000000000..d9d2d3ce2feac613a2e0017f9bdb5e19b1cea7c9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ProfileMetaData.java @@ -0,0 +1,475 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.io.File; +import java.io.IOException; +import java.io.Serializable; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.io.FileUtils; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.connectionupgrade.ConnectionProfileUpgradeManager; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.connectionprofileversion.IConnectionProfileVersions; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.files.FilePermissionFactory; +import org.opengauss.mppdbide.utils.files.ISetFilePermission; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class ProfileMetaData. + * + */ + +public class ProfileMetaData { + + private static final int NON_EXISTING_INDEX = 0; + private static final int PROFILE_INDEX_SIZE = 12 * 1024 * 1024; + private List profileInfos; + private Gson profileGson; + private ProfileInfoComparator comparator; + private boolean isMetaModified; + + /** + * Instantiates a new profile meta data. + */ + public ProfileMetaData() { + profileInfos = new ArrayList(1); + profileGson = new Gson(); + comparator = new ProfileInfoComparator(); + isMetaModified = false; + } + + /** + * Gets the all profiles. + * + * @return the all profiles + */ + public Map getAllProfiles() { + Map map = new HashMap(1); + ProfileInfo info = null; + int index = 0; + int size = profileInfos.size(); + for (; index < size; index++) { + info = profileInfos.get(index); + map.put(info.getProfileName(), info); + } + + return map; + } + + /** + * Gets the profile id. + * + * @param profileName the profile name + * @return the profile id + */ + public int getProfileId(String profileName) { + for (ProfileInfo info : profileInfos) { + if (profileName.equals(info.getProfileName())) { + return Integer.parseInt(info.profileId); + } + } + return -1; + } + + /** + * Gets the all profile ids. + * + * @return the all profile ids + */ + public List getAllProfileIds() { + List profileIds = new ArrayList(1); + for (ProfileInfo info : profileInfos) { + profileIds.add(Integer.parseInt(info.profileId)); + } + return profileIds; + } + + /** + * Adds the profile. + * + * @param name the name + * @param id the id + * @param path the path + * @param versionNumber the version number + */ + public void addProfile(String name, String id, String path, String versionNumber) { + ProfileInfo profile = getProfileByName(name); + if (profile == null) { + profile = getProfileById(id); + } + if (null != profile) { + if (!path.equals(profile.getFilePath())) { + profile.setFilePath(path); + isMetaModified = true; + } + + if (!name.equals(profile.getProfileName())) { + profile.setProfileName(name); + profile.setVersionNo(versionNumber); + isMetaModified = true; + } + + } else { + ProfileInfo newProfile = new ProfileInfo(name, id, path, versionNumber); + int insertionPoint = Collections.binarySearch(profileInfos, newProfile, comparator); + + if (insertionPoint < NON_EXISTING_INDEX) { + insertionPoint = -(insertionPoint + 1); + } + + profileInfos.add(insertionPoint, newProfile); + isMetaModified = true; + } + } + + /** + * Gets the profile by name. + * + * @param name the name + * @return the profile by name + */ + private ProfileInfo getProfileByName(String name) { + for (ProfileInfo profile : profileInfos) { + if (name.equals(profile.getProfileName())) { + return profile; + } + } + + return null; + } + + /** + * Gets the profile by id. + * + * @param id the id + * @return the profile by id + */ + private ProfileInfo getProfileById(String id) { + for (ProfileInfo profile : profileInfos) { + if (id.equals(profile.getProfileId())) { + return profile; + } + } + + return null; + } + + /** + * Delete profile. + * + * @param name the name + */ + public void deleteProfile(String name) { + ProfileInfo deleteInfo = null; + for (ProfileInfo info : profileInfos) { + if (name.equals(info.getProfileName())) { + deleteInfo = info; + break; + } + } + + if (null != deleteInfo) { + profileInfos.remove(deleteInfo); + isMetaModified = true; + } + } + + /** + * Write to disk. + * + * @param path the path + * @throws DatabaseOperationException the database operation exception + */ + public final void writeToDisk(String path) throws DatabaseOperationException { + String jsonStr = getJsonString(); + ISetFilePermission file = FilePermissionFactory.getFilePermissionInstance(); + Path filePath = Paths.get(path); + if (!Files.exists(filePath, LinkOption.NOFOLLOW_LINKS)) { + filePath = file.createFileWithPermission(path, false, null, true); + } else if (!Files.isWritable(filePath)) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_PROFILE_WRITE_DISK)); + throw new DatabaseOperationException(IMessagesConstants.ERR_PROFILE_WRITE_DISK); + } + + if (!isMetaModified) { + return; + } + + try { + Files.write(filePath, jsonStr.getBytes(StandardCharsets.UTF_8), StandardOpenOption.TRUNCATE_EXISTING); + } catch (IOException exception) { + deleteFileNoThrowError(filePath); + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_WRITING_PROFILE_TO_DISK), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_WRITING_PROFILE_TO_DISK, exception); + } + } + + /** + * Update profile version. + * + * @param info the info + */ + public void updateProfileVersion(ProfileInfo info) { + info.setVersionNo(IConnectionProfileVersions.CONNECTION_PROFILE_CURRENT_VERSION); + isMetaModified = true; + } + + /** + * Read from disk. + * + * @param pathStr the path str + * @throws DatabaseOperationException the database operation exception + */ + public final void readFromDisk(String pathStr) throws DatabaseOperationException { + String stdizedPath = null; + try { + stdizedPath = new File(pathStr).getCanonicalPath(); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_PROFILE_FILE_REACHABLE), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_PROFILE_FILE_REACHABLE, exception); + } + if (null != stdizedPath) { + Path path = Paths.get(stdizedPath); + if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) { + if (!Files.isReadable(path)) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_PROFILE_FILE_REACHABLE)); + throw new DatabaseOperationException(IMessagesConstants.ERR_PROFILE_FILE_REACHABLE); + } + + double fileSizeInBytes = FileUtils.sizeOf(path.toFile()); + if (fileSizeInBytes > PROFILE_INDEX_SIZE) { + MPPDBIDELoggerUtility.error("Error while reading profile file. File size exceeded 12MB"); + throw new DatabaseOperationException(IMessagesConstants.ERR_READING_PROFILE_DATA); + } + + try { + byte[] bytes = Files.readAllBytes(path); + if (bytes.length == 0) { + return; + } + String jsonStr = new String(bytes, StandardCharsets.UTF_8); + parseJsonString(jsonStr); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_READING_PROFILE_DATA), exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_READING_PROFILE_DATA, exception); + } + } + } + + } + + /** + * Gets the json string. + * + * @return the json string + */ + private String getJsonString() { + return profileGson.toJson(profileInfos, getType()); + } + + /** + * Parses the json string. + * + * @param json the json + * @throws DatabaseOperationException the database operation exception + */ + private void parseJsonString(String json) throws DatabaseOperationException { + profileInfos = profileGson.fromJson(json, getType()); + if (profileInfos != null) { + checkVersionCompatibility(); + } + } + + /** + * Check version compatibility. + * + * @throws DatabaseOperationException the database operation exception + */ + private void checkVersionCompatibility() throws DatabaseOperationException { + ConnectionProfileUpgradeManager instance = ConnectionProfileUpgradeManager.getInstance(); + for (ProfileInfo profileInfo : profileInfos) { + + String versionNo = profileInfo.getVersionNo(); + + if (!instance.isVersionAvailable(versionNo) || instance.getVersionIndex(versionNo) > instance + .getVersionIndex(IConnectionProfileVersions.CONNECTION_PROFILE_CURRENT_VERSION)) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.VERSION_NO_INCOMPATIBLE)); + throw new DatabaseOperationException(IMessagesConstants.VERSION_NO_INCOMPATIBLE); + } + + } + } + + /** + * Gets the type. + * + * @return the type + */ + private Type getType() { + return new ProfileTypeToken().getType(); + } + + /** + * + * Title: class + * + * Description: The Class ProfileTypeToken. + * + */ + private static final class ProfileTypeToken extends TypeToken> { + } + + /** + * Delete file no throw error. + * + * @param filePath the file path + */ + private void deleteFileNoThrowError(Path filePath) { + try { + Files.deleteIfExists(filePath); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("ProfileMetaData: delete file failed", exception); + } + } + + /** + * + * Title: class + * + * Description: The Class ProfileInfo. + * + */ + public static final class ProfileInfo { + + private String profileName; + private String profileId; + private String filePath; + private String versionNo; + + private ProfileInfo(String profileName, String profileId, String filePath, String versionNo) { + this.setProfileName(profileName); + this.filePath = filePath; + this.profileId = profileId; + this.versionNo = versionNo; + } + + /** + * Gets the version no. + * + * @return the version no + */ + public String getVersionNo() { + return versionNo; + } + + /** + * Gets the profile name. + * + * @return the profile name + */ + public String getProfileName() { + return profileName; + } + + /** + * Gets the file path. + * + * @return the file path + */ + public String getFilePath() { + return filePath; + } + + /** + * Sets the file path. + * + * @param filePath the new file path + */ + public void setFilePath(String filePath) { + this.filePath = filePath; + } + + /** + * Gets the profile id. + * + * @return the profile id + */ + public String getProfileId() { + return profileId; + } + + /** + * Sets the profile name. + * + * @param profileName the new profile name + */ + public void setProfileName(String profileName) { + this.profileName = profileName; + } + + /** + * Sets the version no. + * + * @param versionNo the new version no + */ + public void setVersionNo(String versionNo) { + this.versionNo = versionNo; + } + } + + /** + * + * Title: class + * + * Description: The Class ProfileInfoComparator. + * + */ + private static class ProfileInfoComparator implements Comparator, Serializable { + + private static final long serialVersionUID = 1L; + + @Override + public int compare(ProfileInfo object1, ProfileInfo object2) { + return object1.getProfileName().compareTo(object2.getProfileName()); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/QueryResult.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/QueryResult.java new file mode 100644 index 0000000000000000000000000000000000000000..baed289ca34eff827a1317055c42dd9c2829aaa9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/QueryResult.java @@ -0,0 +1,298 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.StmtExecutor; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.QueryResultType; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: class Description: The Class QueryResult. + */ + +public class QueryResult implements IQueryResult { + + private StmtExecutor resultStmt; + + private DBConnection connection; + + private boolean fetchCommentFlag = false; + + /** + * Instantiates a new query result. + * + * @param resultStmt the result stmt + */ + public QueryResult(StmtExecutor resultStmt) { + this.resultStmt = resultStmt; + } + + /** + * Instantiates a new query result. + * + * @param resultStmt the result stmt + * @param connection the connection + * @param fetchCommentFlag the fetch comment flag + */ + public QueryResult(StmtExecutor resultStmt, DBConnection connection, boolean fetchCommentFlag) { + this.resultStmt = resultStmt; + this.connection = connection; + this.fetchCommentFlag = fetchCommentFlag; + } + + /** + * Checks if is end of records reached. + * + * @return true, if is end of records reached + * org.opengauss.mppdbide.bl.serverdatacache.IQueryResult#isEndOfRecordsReached + */ + + @Override + public boolean isEndOfRecordsReached() { + try { + return resultStmt.isLastRecord(); + } catch (DatabaseOperationException e) { + // Ignore the exception as its harmless. + return false; + } + } + + /** + * Close stament. + * org.opengauss.mppdbide.bl.serverdatacache.IQueryResult#closeStament() + */ + + @Override + public void closeStament() { + if (resultStmt != null) { + resultStmt.closeResultSet(); + resultStmt.closeStatement(); + resultStmt = null; + } + } + + /** + * Rollback. org.opengauss.mppdbide.bl.serverdatacache.IQueryResult#rollback() + */ + + @Override + public void rollback() { + if (resultStmt != null) { + resultStmt.rollback(); + } + } + + /** + * Gets the rows affected. + * + * @return the rows affected + * org.opengauss.mppdbide.bl.serverdatacache.IQueryResult#getRowsAffected() + */ + + @Override + public int getRowsAffected() { + return resultStmt.getRowsAffected(); + } + + /** + * Gets the statementExecutor. + * + * @return the stmtExecutor + */ + + @Override + public StmtExecutor getStmtExecutor() { + return this.resultStmt; + } + + /** + * Gets the return type. + * + * @return the return type + * org.opengauss.mppdbide.bl.serverdatacache.IQueryResult#getReturnType() + */ + + @Override + public QueryResultType getReturnType() { + if (null == resultStmt) { + return null; + } + return resultStmt.getResultType(); + } + + /** + * Gets the column meta data. + * + * @return the column meta data + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * org.opengauss.mppdbide.bl.serverdatacache.IQueryResult#getColumnMetaData() + */ + @Override + public ResultSetColumn[] getColumnMetaData() throws DatabaseOperationException, DatabaseCriticalException { + Statement statement = null; + try { + statement = resultStmt.getResultSet().isClosed() ? null : resultStmt.getResultSet().getStatement(); + } catch (SQLException exe) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_FETCH_RESULT_SET_COLUMN_COMMENT), exe); + throw new DatabaseOperationException(IMessagesConstants.ERR_FETCH_RESULT_SET_COLUMN_COMMENT); + } + + Map columnComment = new HashMap<>(); + if (statement != null && this.fetchCommentFlag && connection.isOLAPConnection()) { + columnComment = getColumnCommentOfOLAP(connection, statement); + } + + int count = resultStmt.getColumCount(); + ResultSetColumn[] metaData = new ResultSetColumn[count]; + + for (int index = 0; index < count; index++) { + metaData[index] = new ResultSetColumn(index + 1); + metaData[index].collectColumnData(resultStmt, columnComment); + } + return metaData; + } + + /** + * gets the column header name + * + * @param columnCount the column count + * @param columnHeaderName the column header name + * @param isCallableStmt the callable statement flag + * @param isCursorType the cursor type flag + * @return ResultSetColumn the result set column + * @throws DatabaseOperationException + * @throws DatabaseCriticalException + */ + public ResultSetColumn[] getColumnHeaderName(int columnCount, List columnHeaderName, boolean isCallableStmt, + boolean isCursorType) throws DatabaseOperationException, DatabaseCriticalException { + ResultSetColumn[] metaData = new ResultSetColumn[columnCount]; + boolean isStatementNull = false; + ResultSet rs = null; + try { + if (resultStmt.getResultSet() != null) { + rs = resultStmt.getResultSet().isClosed() ? null : resultStmt.getResultSet(); + } else { + isStatementNull = true; + } + + if (resultStmt.getCursorResultSetType()) { + isStatementNull = true; + } + } catch (SQLException exe) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_FETCH_RESULT_SET_COLUMN_COMMENT), exe); + throw new DatabaseOperationException(IMessagesConstants.ERR_FETCH_RESULT_SET_COLUMN_COMMENT); + } + for (int i = 0; i < columnCount; i++) { + metaData[i] = new ResultSetColumn(i + 1); + metaData[i].setColumnHeaderName(rs, columnHeaderName.get(i), i + 1, isCursorType, isStatementNull); + } + return metaData; + } + + /** + * Gets the next record batch. + * + * @param count the count + * @return the next record batch + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * org.opengauss.mppdbide.bl.serverdatacache.IQueryResult#getNextRecordBatch + */ + + @Override + public String[][] getNextRecordBatch(int count) throws DatabaseOperationException, DatabaseCriticalException { + return resultStmt.getNextRecordBatch(count); + } + + /** + * Gets the next object record batch. + * + * @param count the count + * @param columnCount the columnCount + * @param isFuncProcResultFlow the isFuncProcResultFlow + * @param isInputParaVisited the isInputParaVisited + * @return the next object record batch + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public Object[][] getNextObjectRecordBatch(int count, int columnCount, boolean isInputParaVisited, + boolean isFuncProcResultFlow) throws DatabaseOperationException, DatabaseCriticalException { + return resultStmt.getNextObjectRecordBatch(count, columnCount, isInputParaVisited); + } + + /** + * Gets the next object record batch. + * + * @param count the count + * @return the next object record batch + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + @Override + public Object[][] getNextObjectRecordBatch(int count) throws DatabaseOperationException, DatabaseCriticalException { + return resultStmt.getNextObjectRecordBatch(count); + } + + /** + * gets Database connection + */ + @Override + public DBConnection getConnection() { + return this.connection; + } + + /** + * Gets the results set. + * + * @return the results set + */ + @Override + public ResultSet getResultsSet() { + if (resultStmt != null) { + return resultStmt.getResultSet(); + } + return null; + + } + + @Override + public void commitConnection() { + if (null != resultStmt) { + resultStmt.commitConnection(); + } + + } + + @Override + public int getColumnCount() throws DatabaseOperationException { + return resultStmt.getColumCount(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/RefreshCounter.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/RefreshCounter.java new file mode 100644 index 0000000000000000000000000000000000000000..c130c00dbd089b002b027ebca7628c81310b32b0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/RefreshCounter.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: class + * + * Description: The Class RefreshCounter. + * + */ + +public final class RefreshCounter { + + private static volatile RefreshCounter refreshCounter = null; + private int countValue = 1; + private static final Object LOCK = new Object(); + + /** + * Instantiates a new refresh counter. + */ + private RefreshCounter() { + + } + + /** + * Gets the single instance of RefreshCounter. + * + * @return single instance of RefreshCounter + */ + public static RefreshCounter getInstance() { + + if (refreshCounter == null) { + synchronized (LOCK) { + if (refreshCounter == null) { + refreshCounter = new RefreshCounter(); + } + + } + + } + + return refreshCounter; + } + + /** + * Gets the count value. + * + * @return the count value + */ + public int getCountValue() { + return countValue; + } + + /** + * Sets the count value. + * + * @param countValue the new count value + */ + public void setCountValue(int countValue) { + this.countValue = countValue; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ResultSetColumn.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ResultSetColumn.java new file mode 100644 index 0000000000000000000000000000000000000000..4aa1c392f742b64aeb099d2e9e4f0e915be471b8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ResultSetColumn.java @@ -0,0 +1,332 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Types; +import java.util.Map; + +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.adapter.gauss.StmtExecutor; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: class + * + * Description: The Class ResultSetColumn. + * + */ + +public class ResultSetColumn { + + private int columnIndex; + private String columnName; + private String datatypeName; + private int dataType; + private int precision; + private int scale; + private int maxLength; + private String comment; + private String defaultValue; + + /** + * Instantiates a new result set column. + * + * @param columnIndex the column index + */ + public ResultSetColumn(int columnIndex) { + this.columnIndex = columnIndex; + } + + /** + * Gets the column index. + * + * @return the column index + */ + public int getColumnIndex() { + return columnIndex; + } + + /** + * Sets the column index. + * + * @param columnIndex the new column index + */ + public void setColumnIndex(int columnIndex) { + this.columnIndex = columnIndex; + } + + /** + * Gets the datatype name. + * + * @return the datatype name + */ + public String getDataTypeName() { + return datatypeName; + } + + /** + * Sets the datatype name. + * + * @param datatypeName the new datatype name + */ + public void setDatatypeName(String datatypeName) { + this.datatypeName = datatypeName; + } + + /** + * Gets the column name. + * + * @return the column name + */ + public String getColumnName() { + return columnName; + } + + /** + * Sets the column name. + * + * @param columnName the new column name + */ + public void setColumnName(String columnName) { + this.columnName = columnName; + } + + /** + * Gets the data type. + * + * @return the data type + */ + public int getDataType() { + return dataType; + } + + /** + * Sets the data type. + * + * @param dataType the new data type + */ + public void setDataType(int dataType) { + this.dataType = dataType; + } + + /** + * Gets the precision. + * + * @return the precision + */ + public int getPrecision() { + return precision; + } + + /** + * Sets the precision. + * + * @param precession the new precision + */ + public void setPrecision(int precession) { + this.precision = precession; + } + + /** + * Gets the scale. + * + * @return the scale + */ + public int getScale() { + return scale; + } + + /** + * Sets the scale. + * + * @param scale the new scale + */ + public void setScale(int scale) { + this.scale = scale; + } + + /** + * Gets the max length. + * + * @return the max length + */ + public int getMaxLength() { + return maxLength; + } + + /** + * Sets the max length. + * + * @param maxLength the new max length + */ + public void setMaxLength(int maxLength) { + this.maxLength = maxLength; + } + + /** + * Gets the comment. + * + * @return the comment + */ + public String getComment() { + return comment; + } + + /** + * Sets the comment. + * + * @param comment the new comment + */ + public void setComment(String comment) { + this.comment = comment; + } + + /** + * Gets the default value. + * + * @return the defaultValue + */ + public String getDefaultValue() { + return defaultValue; + } + + /** + * Sets the default value. + * + * @param defaultValue the defaultValue to set + */ + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + /** + * Collect column data. + * + * @param resultStmt the result stmt + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void collectColumnData(StmtExecutor resultStmt, Map columnComment) + throws DatabaseOperationException, DatabaseCriticalException { + int index = getColumnIndex(); + setColumnName(resultStmt.getColumnName(index)); + setDataType(resultStmt.getColumnDataTypeStmt(index)); + setDatatypeName(resultStmt.getColumnTypeName(index)); + setPrecision(resultStmt.getPrecision(index)); + setScale(resultStmt.getScale(index)); + setMaxLength(resultStmt.getMaxLength(index)); + } + + /** + * sets the column header name + * + * @param rs the result set + * @param columnHeaderName the column header name + * @param index the index + * @param isCursorType the cursor type + * @param isStatementNull the statement null + * @throws DatabaseCriticalException + * @throws DatabaseOperationException + */ + public void setColumnHeaderName(ResultSet rs, String columnHeaderName, int index, boolean isCursorType, + boolean isStatementNull) throws DatabaseOperationException, DatabaseCriticalException { + if (index <= 3) { + setDataType(Types.VARCHAR); + } else { + if (isStatementNull) { + setDataType(Types.OTHER); + } else { + setValueColumnDataType(rs); + } + } + if (isCursorType) { + setDatatypeName(MPPDBIDEConstants.VAR_CHAR); + } + setColumnName(columnHeaderName); + } + + /** + * sets the data type of value column + * + * @param rs the result set + * @throws DatabaseOperationException + * @throws DatabaseCriticalException + */ + private void setValueColumnDataType(ResultSet rs) throws DatabaseOperationException, DatabaseCriticalException { + if (null == rs) { + return; + } + try { + ResultSetMetaData md = rs.getMetaData(); + if (md != null) { + setDataType(md.getColumnType(md.getColumnCount())); + } + } catch (SQLException exception) { + GaussUtils.handleCriticalException(exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } + } + + /** + * Collect column data. + * + * @param stmt the stmt + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void collectColumnData(Statement stmt, Map columnComment) + throws DatabaseOperationException, DatabaseCriticalException { + try { + ResultSetMetaData md = stmt.getResultSet().getMetaData(); + + if (md != null) { + int index = getColumnIndex(); + setColumnName(md.getColumnLabel(index)); + setDataType(md.getColumnType(index)); + setDatatypeName(md.getColumnTypeName(index)); + setPrecision(md.getPrecision(index)); + setScale(md.getScale(index)); + setMaxLength(md.getColumnDisplaySize(index)); + setComment(columnComment.get(md.getSchemaName(index) + md.getTableName(index) + + MPPDBIDEConstants.COLUMN_KEY_SIGN + md.getColumnName(index))); + } + } catch (SQLException exception) { + GaussUtils.handleCriticalException(exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } + } + + /** + * sets popup column header name + * + * @param cursorPopUpdataType the cursor popup data type object + * @param columnHeaderName the column header name + * @param i the index + */ + public void setPopUpColumnHeaderName(String columnHeaderName, int index) { + setColumnName(columnHeaderName); + setDatatypeName(MPPDBIDEConstants.VAR_CHAR); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SearchPathHelper.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SearchPathHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..ec5dc27fde3771e0cd6cb2db873414b4540ea91c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SearchPathHelper.java @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.bl.util.BLUtils; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class SearchPathHelper. + * + */ + +public class SearchPathHelper { + + ConnectionManager connM = null; + + private List searchPath; + + /** + * Instantiates a new search path helper. + * + * @param connectionManager the connection manager + */ + public SearchPathHelper(ConnectionManager connectionManager) { + connM = connectionManager; + + searchPath = new ArrayList(); + } + + /** + * Gets the search path. + * + * @return the search path + */ + public List getSearchPath() { + return searchPath; + } + + /** + * Removes the from search path. + * + * @param namespace the namespace + */ + public void removeFromSearchPath(String namespace) { + searchPath.remove(namespace); + } + + /** + * Fetch user search path. + * + * @param username the username + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void fetchUserSearchPath(String username) throws DatabaseOperationException, DatabaseCriticalException { + String qry = MPPDBIDEConstants.SHOW_SEARCHPATH_QUERY; + ResultSet rs = null; + boolean hasMoreRs = false; + + try { + rs = connM.execSelectAndReturnRsOnObjBrowserConn(qry); + searchPath.clear(); + hasMoreRs = rs.next(); + if (hasMoreRs) { + addToSearchPath(username, rs); + } + } catch (SQLException exception) { + try { + GaussUtils.handleCriticalException(exception); + } catch (DatabaseCriticalException dc) { + throw dc; + } + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + connM.closeRSOnObjBrowserConn(rs); + } + + } + + /** + * Adds the to search path. + * + * @param username the username + * @param rs the rs + * @throws SQLException the SQL exception + */ + private void addToSearchPath(String username, ResultSet rs) throws SQLException { + String searchPathStr = rs.getString(1); + if (searchPathStr != null) { + String[] searchPathList = searchPathStr.replace("$user", username).split(","); + for (String str : searchPathList) { + String strTrim = str.trim(); + searchPath.add(BLUtils.getUnQuotedIdentifier(strTrim, "\"")); + } + } else { + searchPath.add(MPPDBIDEConstants.PUBLIC_SCHEMA_NAME); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SearchPoolManager.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SearchPoolManager.java new file mode 100644 index 0000000000000000000000000000000000000000..a3f8b8187118ad830453dc3126deeba428e57fa6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SearchPoolManager.java @@ -0,0 +1,344 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.util.Map.Entry; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.apache.commons.collections4.trie.PatriciaTrie; + +import org.opengauss.mppdbide.bl.serverdatacache.groups.ForeignTableGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.OLAPObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.SequenceObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.TableObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ViewObjectGroup; + +/** + * + * Title: class + * + * Description: The Class SearchPoolManager. + * + */ + +public class SearchPoolManager { + + private PatriciaTrie tableTrie; + + private PatriciaTrie debugObjectTrie; + + private PatriciaTrie viewTrie; + + private PatriciaTrie ftableTrie; + + private PatriciaTrie ptableTrie; + + private PatriciaTrie sequenceTrie; + + private PatriciaTrie synonymTrie; + + private PatriciaTrie triggerTrie; + + /** + * Instantiates a new search pool manager. + */ + public SearchPoolManager() { + this.ftableTrie = new PatriciaTrie(); + this.ptableTrie = new PatriciaTrie(); + this.tableTrie = new PatriciaTrie(); + this.debugObjectTrie = new PatriciaTrie(); + this.viewTrie = new PatriciaTrie(); + this.sequenceTrie = new PatriciaTrie(); + this.synonymTrie = new PatriciaTrie(); + this.triggerTrie = new PatriciaTrie(); + } + + /** + * Gets the ftable trie. + * + * @return the ftable trie + */ + public PatriciaTrie getFtableTrie() { + return ftableTrie; + } + + /** + * Gets the ptable trie. + * + * @return the ptable trie + */ + public PatriciaTrie getPtableTrie() { + return ptableTrie; + } + + /** + * Gets the sequence trie. + * + * @return the sequence trie + */ + public PatriciaTrie getSequenceTrie() { + return sequenceTrie; + } + + /** + * Gets the synonym trie. + * + * @return the synonym trie + */ + public PatriciaTrie getSynonymTrie() { + return synonymTrie; + } + + /** + * Gets the debug object trie. + * + * @return the debug object trie + */ + public PatriciaTrie getDebugObjectTrie() { + return debugObjectTrie; + } + + /** + * Gets the view trie. + * + * @return the view trie + */ + public PatriciaTrie getViewTrie() { + return viewTrie; + } + + /** + * Gets the table trie. + * + * @return the table trie + */ + public PatriciaTrie getTableTrie() { + return tableTrie; + } + + /** + * Gets the trigger trie. + * + * @return the trigger trie + */ + public PatriciaTrie getTriggerTrie() { + return triggerTrie; + } + + /** + * Clear trie. + */ + public void clearTrie() { + getTableTrie().clear(); + getDebugObjectTrie().clear(); + getViewTrie().clear(); + getSequenceTrie().clear(); + getSynonymTrie().clear(); + getPtableTrie().clear(); + getFtableTrie().clear(); + getTriggerTrie().clear(); + } + + /** + * Addsequence to search pool. + * + * @param sequence the sequence + */ + public void addsequenceToSearchPool(SequenceMetadata sequence) { + getSequenceTrie().put(sequence.getSearchName(), sequence); + } + + /** + * Addsynonym to search pool. + * + * @param synonym the synonym + */ + public void addsynonymToSearchPool(SynonymMetaData synonym) { + getSynonymTrie().put(synonym.getSearchName(), synonym); + } + + /** + * Add TriggerMetaData to search pool. + * + * @param TriggerMetaData the trigger metadata + */ + public void addTriggerToSearchPool(TriggerMetaData trigger) { + getTriggerTrie().put(trigger.getSearchName(), trigger); + } + + /** + * Removes the object from search pool. + * + * @param searchKey the search key + * @param objectType the object type + */ + public void removeObjectFromSearchPool(String searchKey, OBJECTTYPE objectType) { + switch (objectType) { + case FOREIGN_TABLE: { + if (null == ftableTrie) { + return; + } + if (ftableTrie.containsKey(searchKey)) { + ftableTrie.remove(searchKey); + } + break; + } + case PARTITION_TABLE: { + if (null == ptableTrie) { + return; + } + if (ptableTrie.containsKey(searchKey)) { + ptableTrie.remove(searchKey); + } + break; + } + default: { + break; + } + } + } + + /** + * Adds the debug object to search pool. + * + * @param debugObject the debug object + */ + public void addDebugObjectToSearchPool(DebugObjects debugObject) { + getDebugObjectTrie().put(debugObject.getSearchName(), debugObject); + } + + /** + * Removes the sequence from search pool. + * + * @param sequence the sequence + */ + public void removeSequenceFromSearchPool(SequenceMetadata sequence) { + String searchKey = sequence.getSearchName(); + if (getSequenceTrie().containsKey(searchKey)) { + getSequenceTrie().remove(searchKey); + } + } + + /** + * Removes the synonym from search pool. + * + * @param synonym the synonym + */ + public void removeSynonymFromSearchPool(SynonymMetaData synonym) { + String searchKey = synonym.getSearchName(); + if (getSynonymTrie().containsKey(searchKey)) { + getSynonymTrie().remove(searchKey); + } + } + + /** + * Removes the trigger from search pool. + * + * @param trigger the trigger + */ + public void removeTriggerFromSearchPool(TriggerMetaData trigger) { + String searchKey = trigger.getSearchName(); + if (getTriggerTrie().containsKey(searchKey)) { + getTriggerTrie().remove(searchKey); + } + } + + /** + * Adds the table to search pool. + * + * @param tableName the table name + */ + public void addTableToSearchPool(TableMetaData tableName) { + + getTableTrie().put(tableName.getSearchName(), tableName); + } + + /** + * Addview to search pool. + * + * @param view the view + */ + public void addviewToSearchPool(ViewMetaData view) { + getViewTrie().put(view.getSearchName(), view); + } + + /** + * Removes the view from search pool. + * + * @param view the view + */ + public void removeViewFromSearchPool(ViewMetaData view) { + String searchKey = view.getSearchName(); + if (getViewTrie().containsKey(searchKey)) { + getViewTrie().remove(searchKey); + } + } + + /** + * Removes the table from search pool. + * + * @param table the table + */ + public void removeTableFromSearchPool(TableMetaData table) { + if (null != table) { + String searchKey = table.getSearchName(); + if (getTableTrie().containsKey(searchKey)) { + getTableTrie().remove(searchKey); + } + } + } + + /** + * Removes the debug object from search pool. + * + * @param table the table + */ + public void removeDebugObjectFromSearchPool(DebugObjects table) { + if (null != table) { + String searchKey = table.getSearchName(); + if (getDebugObjectTrie().containsKey(searchKey)) { + getDebugObjectTrie().remove(searchKey); + } + } + } + + /** + * Clear object. + * + * @param group the group + */ + public void clearObject(OLAPObjectGroup group) { + for (ServerObject obj : group) { + if (obj instanceof DebugObjects) { + removeDebugObjectFromSearchPool((DebugObjects) obj); + } else if (obj instanceof ViewMetaData) { + removeViewFromSearchPool((ViewMetaData) obj); + } else if (obj instanceof ForeignTable || obj instanceof PartitionTable) { + removeObjectFromSearchPool(obj.getSearchName(), obj.getType()); + } else if (obj instanceof SequenceMetadata) { + removeSequenceFromSearchPool((SequenceMetadata) obj); + } else if (obj instanceof SynonymMetaData) { + removeSynonymFromSearchPool((SynonymMetaData) obj); + } else if (obj instanceof TableMetaData) { + removeTableFromSearchPool((TableMetaData) obj); + } else if (obj instanceof TriggerMetaData) { + removeTriggerFromSearchPool((TriggerMetaData) obj); + } + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SequenceMetadata.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SequenceMetadata.java new file mode 100644 index 0000000000000000000000000000000000000000..0ff2d0ec48f12aac592319921114aebf5ebc9db5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SequenceMetadata.java @@ -0,0 +1,568 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.export.EXPORTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.groups.SequenceObjectGroup; +import org.opengauss.mppdbide.bl.util.ExecTimer; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class SequenceMetadata. + * + */ + +public class SequenceMetadata extends BatchDropServerObject implements GaussOLAPDBMSObject, ISequenceMetaData { + + private Namespace namespace; + private String owner; + private String sequenceName; + private String minValue; + private String maxValue; + private String startValue; + private String cache; + private boolean cycle; + private String seqTableName; + private String seqColumnName; + private String seqSchemaName; + private String incrementBy; + + private long oid; + + private static final String DROP_QUERY = "DROP SEQUENCE "; + private static final String DROP_QUERY_IF_EXISTS = "DROP SEQUENCE IF EXISTS "; + + /** + * Instantiates a new sequence metadata. + * + * @param oid the oid + * @param name the name + * @param namespace the namespace + */ + public SequenceMetadata(long oid, String name, Namespace namespace) { + super(oid, name, OBJECTTYPE.SEQUENCE_METADATA_GROUP, namespace != null ? namespace.getPrivilegeFlag() : true); + this.namespace = namespace; + this.oid = oid; + } + + /** + * Instantiates a new sequence metadata. + * + * @param nameSpace the name space + */ + public SequenceMetadata(Namespace nameSpace) { + this(0, "nosequence", nameSpace); + } + + @Override + public void dropSequence(DBConnection conn, boolean isAppendCascade) + throws DatabaseOperationException, DatabaseCriticalException { + String query = getDropQueryForOB(isAppendCascade); + conn.execNonSelect(query); + this.namespace.getDatabase().getSearchPoolManager().removeSequenceFromSearchPool(this); + this.namespace.getSequenceGroup().removeFromGroup(oid); + } + + /** + * Sets the owner. + * + * @param owner the new owner + */ + void setOwner(String owner) { + this.owner = owner; + } + + /** + * Gets the sequence owner. + * + * @return the sequence owner + */ + public String getSequenceOwner() { + return owner; + } + + /** + * Gets the namespace. + * + * @return the namespace + */ + public Namespace getNamespace() { + return namespace; + } + + /** + * Gets the sequence name. + * + * @return the sequence name + */ + public String getSequenceName() { + return sequenceName; + } + + /** + * Sets the sequence name. + * + * @param sequenceName the new sequence name + */ + public void setSequenceName(String sequenceName) { + this.sequenceName = sequenceName; + } + + /** + * Checks if is cycle. + * + * @return true, if is cycle + */ + public boolean isCycle() { + return cycle; + } + + /** + * Sets the cycle. + * + * @param cycle the new cycle + */ + public void setCycle(boolean cycle) { + this.cycle = cycle; + } + + /** + * Gets the table name. + * + * @return the table name + */ + public String getTableName() { + return seqTableName; + } + + /** + * Sets the table name. + * + * @param tableName the new table name + */ + public void setTableName(String tableName) { + this.seqTableName = tableName; + } + + /** + * Gets the column name. + * + * @return the column name + */ + public String getColumnName() { + return seqColumnName; + } + + /** + * Sets the column name. + * + * @param columnName the new column name + */ + public void setColumnName(String columnName) { + this.seqColumnName = columnName; + } + + /** + * Gets the schema name. + * + * @return the schema name + */ + public String getSchemaName() { + return seqSchemaName; + } + + /** + * Sets the schema name. + * + * @param schemaName the new schema name + */ + public void setSchemaName(String schemaName) { + this.seqSchemaName = schemaName; + } + + /** + * Gets the min value. + * + * @return the min value + */ + public String getMinValue() { + return minValue; + } + + /** + * Sets the min value. + * + * @param minValue the new min value + */ + public void setMinValue(String minValue) { + this.minValue = minValue; + } + + /** + * Gets the max value. + * + * @return the max value + */ + public String getMaxValue() { + return maxValue; + } + + /** + * Sets the max value. + * + * @param maxValue the new max value + */ + public void setMaxValue(String maxValue) { + this.maxValue = maxValue; + } + + /** + * Gets the start value. + * + * @return the start value + */ + public String getStartValue() { + return startValue; + } + + /** + * Sets the start value. + * + * @param startValue the new start value + */ + public void setStartValue(String startValue) { + this.startValue = startValue; + } + + /** + * Gets the cache size. + * + * @return the cache size + */ + public String getCacheSize() { + return cache; + } + + /** + * Sets the cache. + * + * @param cache the new cache + */ + public void setCache(String cache) { + this.cache = cache; + } + + /** + * Gets the increment by. + * + * @return the increment by + */ + public String getIncrementBy() { + return incrementBy; + } + + /** + * Sets the increment by. + * + * @param incrementBy the new increment by + */ + public void setIncrementBy(String incrementBy) { + this.incrementBy = incrementBy; + } + + /** + * Gets the search name. + * + * @return getSearchName + */ + public String getSearchName() { + return getName() + " - " + getNamespace().getName() + " - " + getTypeLabel(); + } + + @Override + public Object getParent() { + return this.namespace; + } + + @Override + public Database getDatabase() { + return this.namespace.getDatabase(); + } + + /** + * Gets the drop query for OB. + * + * @param isAppendCascade the is append cascade + * @return the drop query for OB + */ + private String getDropQueryForOB(boolean isAppendCascade) { + StringBuilder query = new StringBuilder(DROP_QUERY); + query.append(getNamespace().getQualifiedObjectName()).append('.').append(getQualifiedObjectName()); + + if (isAppendCascade) { + query.append(MPPDBIDEConstants.CASCADE); + } + + return query.toString(); + } + + /** + * Gets the drop query. + * + * @param isAppendCascade the is append cascade + * @return the drop query + */ + public String getDropQuery(boolean isAppendCascade) { + StringBuilder query = new StringBuilder(DROP_QUERY_IF_EXISTS); + query.append(getNamespace().getQualifiedObjectName()).append('.').append(getQualifiedObjectName()); + + if (isAppendCascade) { + query.append(MPPDBIDEConstants.CASCADE); + } + + return query.toString(); + } + + @Override + public void refreshSequence(DBConnection dbConnection) + throws DatabaseOperationException, DatabaseCriticalException { + SequenceMetadataUtil.refresh(getOid(), getNamespace().getDatabase(), this); + + } + + @Override + public INamespace getSeqNameSpace() { + return getNamespace(); + } + + @Override + public boolean isExportAllowed(EXPORTTYPE exportType) { + if (exportType == EXPORTTYPE.SQL_DDL || exportType == EXPORTTYPE.SQL_DDL_DATA) { + return true; + } + return false; + } + + @Override + public String getDisplayName() { + return getNamespace().getDisplayName() + '.' + super.getDisplayName(); + } + + /** + * isTableDropped + * + * @return boolean + */ + public boolean isTableDropped() { + Namespace ns = getNamespace(); + if (null == ns) { + return true; + } + SequenceObjectGroup group = ns.getSequenceGroup(); + return null == group || null == group.getObjectById(getOid()); + } + + /** + * getDDL get sequence DDL + * + * @param database db obj + * @param conn connection + * @return string Ddl + * @throws DatabaseOperationException exception + */ + public String getDDL(Database database, DBConnection conn) throws DatabaseOperationException { + String fetchDDLQueryPrefix = "SELECT sequence_name,start_value, increment_by," + + " CASE WHEN increment_by > 0 AND max_value = %d THEN NULL " + + "WHEN increment_by < 0 AND max_value = -1 THEN NULL ELSE max_value END AS max_value," + + " CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL WHEN increment_by < 0 AND min_value = %s " + + "THEN NULL ELSE min_value END AS min_value, cache_value, is_cycled FROM %s;"; + + ExecTimer timer = new ExecTimer("fetch DDL from server"); + String seqDDL = ""; + ResultSet rs = null; + try { + timer.start(); + rs = conn.execSelectAndReturnRs(String.format(Locale.ENGLISH, fetchDDLQueryPrefix, Integer.MAX_VALUE, + Integer.MIN_VALUE, this.getDisplayName())); + timer.stopAndLogNoException(); + while (rs.next()) { + this.setSequenceName(rs.getString("sequence_name")); + this.setStartValue(rs.getString("start_value")); + this.setIncrementBy(rs.getString("increment_by")); + this.setMaxValue(rs.getString("max_value")); + this.setMinValue(rs.getString("min_value")); + this.setCache(rs.getString("cache_value")); + this.setCycle(rs.getBoolean("is_cycled")); + } + seqDDL = composeQuery(ServerObject.getQualifiedObjectName(this.getSequenceName())); + } catch (DatabaseCriticalException exception) { + MPPDBIDELoggerUtility.error("error getting free connection", exception); + throw new DatabaseOperationException(IMessagesConstants.CONNECTION_ERR); + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("error getting free connection", exception); + throw new DatabaseOperationException(IMessagesConstants.CONNECTION_ERR); + } finally { + conn.closeResultSet(rs); + MPPDBIDELoggerUtility.debug("fetch DDL done"); + } + + return seqDDL; + } + + /** + * getSequenceQwnedByDDL seq qwned DDl + * + * @param conn connection + * @return string query + * @throws DatabaseOperationException exception + */ + public String getSequenceQwnedByDDL(DBConnection conn) throws DatabaseOperationException { + String qury = String.format(Locale.ENGLISH, + "select d.refobjid as tableid,d.refobjsubid as clmidx FROM pg_class c " + + " LEFT JOIN pg_depend d ON (c.relkind = 'S' AND " + + "d.classid = c.tableoid AND d.objid = c.oid AND d.objsubid = 0 AND " + + "d.refclassid = c.tableoid AND d.deptype = 'a') where c.oid=%d", + this.oid); + StringBuilder seqDDL = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + ResultSet rs = null; + long tableOid; + int clmIndex; + try { + rs = conn.execSelectAndReturnRs(qury); + while (rs.next()) { + tableOid = rs.getInt("tableid"); + clmIndex = rs.getInt("clmidx"); + seqDDL.append(getSeqOwnQuery(conn, tableOid, clmIndex)); + } + } catch (DatabaseCriticalException exception) { + MPPDBIDELoggerUtility.error("Error while fetching column details for sequence", exception); + throw new DatabaseOperationException(IMessagesConstants.CONNECTION_ERR); + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Error while fetching column details for sequence", exception); + throw new DatabaseOperationException(IMessagesConstants.CONNECTION_ERR); + } finally { + conn.closeResultSet(rs); + MPPDBIDELoggerUtility.debug("fetch DDL done"); + } + return seqDDL.toString(); + } + + private String getSeqOwnQuery(DBConnection conn, long tableOid, int clmIndex) throws DatabaseOperationException { + String query = String.format(Locale.ENGLISH, + "select relname, attname from pg_class as c" + + " LEFT JOIN pg_catalog.pg_attribute as att ON (c.oid = att.attrelid)" + + " where attrelid = %d and attnum = %d", + tableOid, clmIndex); + ResultSet rs = null; + String queryDDL = ""; + try { + rs = conn.execSelectAndReturnRs(query); + while (rs.next()) { + String tableName = rs.getString("relname"); + String clmName = rs.getString("attname"); + if (tableName != null || clmName != null) { + queryDDL = String.format(Locale.ENGLISH, "ALTER SEQUENCE %s OWNED BY %s.%s ;", + ServerObject.getQualifiedObjectName(this.getName()), + ServerObject.getQualifiedObjectName(tableName), + ServerObject.getQualifiedObjectName(clmName)); + } + } + } catch (DatabaseCriticalException exception) { + MPPDBIDELoggerUtility.error("Error while fetching owner details for sequence", exception); + throw new DatabaseOperationException(IMessagesConstants.CONNECTION_ERR); + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Error while fetching owner details for sequence", exception); + throw new DatabaseOperationException(IMessagesConstants.CONNECTION_ERR); + } finally { + conn.closeResultSet(rs); + MPPDBIDELoggerUtility.debug("fetch DDL done"); + } + return queryDDL; + } + + /** + * Compose query. + * + * @param objectName the object name + * @return the string + */ + public String composeQuery(String objectName) { + StringBuffer queryBuff = new StringBuffer(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + queryBuff.append(" CREATE "); + + queryBuff.append(" SEQUENCE "); + + queryBuff.append(objectName); + if (null != this.getStartValue()) { + queryBuff.append(MPPDBIDEConstants.LINE_SEPARATOR); + queryBuff.append(" START WITH "); + queryBuff.append(this.getStartValue()); + } + if (null != this.getIncrementBy()) { + queryBuff.append(MPPDBIDEConstants.LINE_SEPARATOR); + queryBuff.append(" INCREMENT BY "); + queryBuff.append(this.getIncrementBy()); + } + if (null != this.getMinValue()) { + queryBuff.append(MPPDBIDEConstants.LINE_SEPARATOR); + queryBuff.append(" MINVALUE "); + queryBuff.append(this.getMinValue()); + } else { + queryBuff.append(MPPDBIDEConstants.LINE_SEPARATOR); + queryBuff.append(" NO MINVALUE "); + } + if (null != this.getMaxValue()) { + queryBuff.append(MPPDBIDEConstants.LINE_SEPARATOR); + queryBuff.append(" MAXVALUE "); + queryBuff.append(this.getMaxValue()); + } + + if (null != this.getCacheSize()) { + queryBuff.append(MPPDBIDEConstants.LINE_SEPARATOR); + queryBuff.append(" CACHE "); + queryBuff.append(this.getCacheSize()); + } + if (this.isCycle()) { + queryBuff.append(MPPDBIDEConstants.LINE_SEPARATOR); + queryBuff.append(" CYCLE "); + } + + if (null != this.getTableName() && !this.getTableName().isEmpty()) { + queryBuff.append(MPPDBIDEConstants.LINE_SEPARATOR); + queryBuff.append(" OWNED BY "); + queryBuff.append(ServerObject.getQualifiedObjectName(this.getSchemaName())).append("."); + queryBuff.append(ServerObject.getQualifiedObjectName(this.getTableName())).append("."); + if (null != this.getColumnName() && !this.getColumnName().isEmpty()) { + queryBuff.append(ServerObject.getQualifiedObjectName(this.getColumnName())); + } + } + + queryBuff.append(";"); + return queryBuff.toString(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SequenceMetadataUtil.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SequenceMetadataUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..c2160714b053efc9f8220651cc411256663fcf0b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SequenceMetadataUtil.java @@ -0,0 +1,233 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class SequenceMetadataUtil. + * + */ + +public abstract class SequenceMetadataUtil { + + private static final String QUERY = "select oid,relnamespace,relowner,relname from pg_class where relkind='S' "; + private static final String QUERY_SCHEMA_FILTER = "and relnamespace="; + + private static final String QUERY_OID_FILTER = " and oid=%d"; + private static final String QUERY_PRIVILEGE_OID_FILTER = " and has_sequence_privilege(oid, 'USAGE');"; + + /** + * Sets the query privilege filter namespace. + * + * @param ns the ns + * @return the string + */ + private static String setQueryPrivilegeFilterNamespace(String ns) { + return " and has_sequence_privilege(QUOTE_IDENT(" + ServerObject.getLiteralName(ns) + + ") || '.' || QUOTE_IDENT(relname), 'USAGE');"; + } + + /** + * Gets the all sequences by namespace ID query. + * + * @param ns the ns + * @return the all sequences by namespace ID query + */ + public static String getAllSequencesByNamespaceIDQuery(long ns) { + + return QUERY + QUERY_SCHEMA_FILTER + ns; + } + + /** + * Gets the all sequences by namespace. + * + * @param ns the ns + * @param nsoid the nsoid + * @return the all sequences by namespace + */ + public static String getAllSequencesByNamespace(String ns, long nsoid) { + + return QUERY + QUERY_SCHEMA_FILTER + nsoid + setQueryPrivilegeFilterNamespace(ns) + ";"; + } + + /** + * Gets the refresh query. + * + * @param oid the oid + * @param privilegeFlag the privilege flag + * @return the refresh query + */ + public static String getRefreshQuery(long oid, boolean privilegeFlag) { + + String qry = QUERY + QUERY_OID_FILTER; + if (privilegeFlag) { + qry += QUERY_PRIVILEGE_OID_FILTER; + } else { + qry += ";"; + } + qry = String.format(Locale.ENGLISH, qry, oid); + return qry; + } + + /** + * Fetchsequence. + * + * @param sequenceQuery the sequence query + * @param conn the conn + * @param db the db + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static void fetchsequence(String sequenceQuery, DBConnection conn, Database db) + throws DatabaseCriticalException, DatabaseOperationException { + ResultSet rs = null; + boolean hasNext = false; + SequenceMetadata sequence = null; + Namespace ns = null; + + try { + rs = conn.execSelectAndReturnRs(sequenceQuery); + hasNext = rs.next(); + while (hasNext) { + sequence = convertToSequenceMetaData(rs, db); + ns = sequence.getNamespace(); + ns.addSequence(sequence); + ns.getDatabase().getSearchPoolManager().addsequenceToSearchPool(sequence); + hasNext = rs.next(); + } + } catch (SQLException sqlException) { + GaussUtils.handleCriticalException(sqlException); + + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, sqlException); + } finally { + conn.closeResultSet(rs); + } + } + + /** + * Convert to sequence meta data. + * + * @param rs the rs + * @param db the db + * @return the sequence metadata + * @throws DatabaseOperationException the database operation exception + */ + public static SequenceMetadata convertToSequenceMetaData(ResultSet rs, Database db) + throws DatabaseOperationException { + SequenceMetadata sequence = null; + + try { + + long namespaceId = rs.getLong("relnamespace"); + Namespace namespace = db.getNameSpaceById(namespaceId); + + long oid = rs.getLong("oid"); + String name = rs.getString("relname"); + sequence = new SequenceMetadata(oid, name, namespace); + sequence.setOwner(rs.getString("relowner")); + + return sequence; + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_TO_CONVERT_SEQ_DATA), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_TO_CONVERT_SEQ_DATA, exception); + } + } + + /** + * Gets the searched sequence. + * + * @param namespace the namespace + * @param tblId the tbl id + * @param tblName the tbl name + * @return the searched sequence + */ + public static SequenceMetadata getSearchedSequence(Namespace namespace, int tblId, String tblName) { + SequenceMetadata seq = new SequenceMetadata(tblId, tblName, namespace); + seq.setOwner("relowner"); + return seq; + + } + + // CHECKSTYLE:OFF: + /** + * Refresh. + * + * @param oid the l + * @param database the database + * @param sequenceMdata the sequence mdata + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static void refresh(long oid, Database database, SequenceMetadata sequenceMdata) + throws DatabaseCriticalException, DatabaseOperationException { + + database.getSearchPoolManager() + .removeSequenceFromSearchPool(sequenceMdata.getNamespace().getSequenceGroup().getObjectById(oid)); + sequenceMdata.getNamespace().getSequenceGroup().removeFromGroup(oid); + boolean privilegeFlag = sequenceMdata.getPrivilegeFlag(); + String qry = SequenceMetadataUtil.getRefreshQuery(oid, privilegeFlag); + boolean hasNext = false; + SequenceMetadata sequence = null; + + ResultSet resultset = null; + + try { + resultset = database.getConnectionManager().execSelectAndReturnRsOnObjBrowserConn(qry); + hasNext = resultset.next(); + if (!hasNext) { + sequenceMdata.getNamespace().getDatabase().getSearchPoolManager() + .removeSequenceFromSearchPool(sequenceMdata); + if (privilegeFlag) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DENIED_ACCESS_PRIVILEGE)); + throw new DatabaseOperationException(IMessagesConstants.ERR_DENIED_ACCESS_PRIVILEGE); + } else { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.MSG_GUI_OBJECT_MAY_DROPPED)); + throw new DatabaseOperationException(IMessagesConstants.MSG_GUI_OBJECT_MAY_DROPPED); + // refreshing a sequence didnt get any row, means it is + // dropped + } + } + while (hasNext) { + sequence = SequenceMetadataUtil.convertToSequenceMetaData(resultset, database); + sequenceMdata.getNamespace().addSequence(sequence); + hasNext = resultset.next(); + } + } catch (SQLException sqlException) { + GaussUtils.handleCriticalException(sqlException); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, sqlException); + } finally { + database.getConnectionManager().closeRSOnObjBrowserConn(resultset); + } + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/Server.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/Server.java new file mode 100644 index 0000000000000000000000000000000000000000..cb111b44fadeeef095b4b5b54cd96e55148046d5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/Server.java @@ -0,0 +1,1239 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.groups.DatabaseObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.OLAPObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.TablespaceObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.UserRoleObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.utils.CustomStringUtility; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.MemoryCleaner; +import org.opengauss.mppdbide.utils.exceptions.DataStudioSecurityException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.exceptions.PasswordExpiryException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; + +/** + * + * Title: class + * + * Description: The Class Server. + * + */ + +public class Server implements IConnectionProfile, GaussOLAPDBMSObject { + + // should be static (used to get multiple connections) + private static int sequence; + + /** + * The server id. + */ + protected int serverId; + + /** + * The connection name. + */ + protected String connectionName; + + /** + * The server host. + */ + protected String serverHost; + + /** + * The server port. + */ + protected int serverPort; + private DatabaseObjectGroup dbGroup; + private TablespaceObjectGroup tablespaceGroup; + private OLAPObjectGroup accessMethods; + private IServerConnectionInfo newConfigInfo; + + /** + * The encrpyted profile prd. + */ + protected String encrpytedProfilePrd; + + /** + * The encrpytedssl prd. + */ + protected String encrpytedsslPrd; + private SavePrdOptions savePrdOption; + + /** + * The is support node group privilege. + */ + protected boolean isSupportNodeGroupPrivilege; + private boolean isServerInProgress; + private String driverName; + + /** + * The server version. + */ + protected String serverVersion; + + /** + * The trimmed version. + */ + protected String trimmedVersion; + + /** + * The server IP. + */ + protected String serverIP; + + private boolean privilegeFlag; + private UserRoleObjectGroup userRoleObjectGroup; + + private static final Object LOCK = new Object(); + + private HashMap> defaulParametertMap = new HashMap<>(); + + /** + * Checks if is server in progress. + * + * @return true, if is server in progress + */ + public boolean isServerInProgress() { + return isServerInProgress; + } + + /** + * Sets the server in progress. + * + * @param isServrInProgress the new server in progress + */ + public void setServerInProgress(boolean isServrInProgress) { + this.isServerInProgress = isServrInProgress; + } + + /** + * Instantiates a new server. + * + * @param info the info + * @throws DataStudioSecurityException the data studio security exception + */ + public Server(IServerConnectionInfo info) throws DataStudioSecurityException { + synchronized (LOCK) { + sequence++; + serverId = sequence; + } + this.newConfigInfo = info.getClone(); + this.connectionName = info.getConectionName(); + this.serverHost = info.getServerIp(); + this.serverPort = info.getServerPort(); + this.dbGroup = new DatabaseObjectGroup(OBJECTTYPE.DATABASE_GROUP, this); + this.tablespaceGroup = new TablespaceObjectGroup(OBJECTTYPE.TABLESPACE_GROUP, this); + this.accessMethods = new OLAPObjectGroup(OBJECTTYPE.ACCESSMETHOD_GROUP, this); + savePrdOption = info.getSavePrdOption(); + SecureUtil sec = new SecureUtil(); + String path = ConnectionProfileManagerImpl.getInstance().getProfilePath(info); + sec.setPackagePath(path); + encrpytedProfilePrd = sec.encryptPrd(info.getPrd()); + encrpytedsslPrd = sec.encryptPrd(info.getSSLPrd()); + + newConfigInfo.clearPasrd(); + info.clearPasrd(); + this.privilegeFlag = info.isPrivilegeBasedObAccessEnabled(); + + this.userRoleObjectGroup = new UserRoleObjectGroup(OBJECTTYPE.USER_ROLE_GROUP, this); + } + + /** + * Clear prds. + */ + public void clearPrds() { + if (savePrdOption.equals(SavePrdOptions.DO_NOT_SAVE)) { + encrpytedProfilePrd = ""; + } + } + + /** + * Gets the id. + * + * @return the id + */ + public int getId() { + return serverId; + } + + /** + * Gets the host. + * + * @return the host + */ + public String getHost() { + return serverHost; + } + + /** + * Sets the host. + * + * @param host the new host + */ + public void setHost(String host) { + this.serverHost = host; + } + + /** + * Gets the port. + * + * @return the port + */ + public int getPort() { + return serverPort; + } + + /** + * Sets the port. + * + * @param port the new port + */ + public void setPort(int port) { + this.serverPort = port; + } + + /** + * Gets the db by id. + * + * @param oid the oid + * @return the db by id + */ + public Database getDbById(long oid) { + return this.dbGroup.getObjectById(oid); + } + + /** + * Gets the db by name. + * + * @param name the name + * @return the db by name + */ + public Database getDbByName(String name) { + Iterator dbItr = this.dbGroup.iterator(); + Database db = null; + + boolean hasNext = dbItr.hasNext(); + while (hasNext) { + db = dbItr.next(); + if (name.equals(db.getName())) { + return db; + } + + hasNext = dbItr.hasNext(); + } + + return null; + } + + /** + * Removes the database. + * + * @param oid the oid + */ + public void removeDatabase(long oid) { + this.dbGroup.removeFromGroup(oid); + } + + /** + * Gets the all databases. + * + * @return the all databases + */ + public Collection getAllDatabases() { + return this.dbGroup.getSortedServerObjectList(); + } + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + return this.connectionName; + } + + /** + * Gets the display name. + * + * @return the display name + */ + public String getDisplayName() { + return this.connectionName + " (" + this.serverHost + ':' + this.serverPort + ')'; + } + + /** + * Gets the display name for domain. + * + * @return the display name for domain + */ + public String getDisplayNameForDomain() { + String wrappedHost = null; + int hostLength = this.serverHost.length(); + if (hostLength > 25) { + wrappedHost = this.serverHost.substring(0, 11) + "..." + + this.serverHost.substring(hostLength - 11, hostLength); + } else { + wrappedHost = this.serverHost; + } + return this.connectionName + " (" + wrappedHost + ':' + this.serverPort + ')'; + } + + /** + * Checks if is aleast one db connected. + * + * @return true, if is aleast one db connected + */ + public boolean isAleastOneDbConnected() { + return ConnectionUtils.isAleastOneDbConnected(this.dbGroup.getSortedServerObjectList()); + } + + /** + * Adds the D bto list. + * + * @param db the db + */ + public void addDBtoList(Database db) { + this.dbGroup.addToGroup(db); + } + + /** + * Creates the DB connection profile. + * + * @param serverInfo the server info + * @param status the status + * @return the connection profile id + * @throws MPPDBIDEException the MPPDBIDE exception + * @throws PasswordExpiryException the password expiry exception + * @throws OutOfMemoryError the out of memory error + */ + public ConnectionProfileId createDBConnectionProfile(IServerConnectionInfo serverInfo, IJobCancelStatus status) + throws MPPDBIDEException, PasswordExpiryException, OutOfMemoryError { + + // First time we will not have oid + Database db = new Database(this, 0, serverInfo.getDatabaseName()); + db.connectToServer(); + LoginNotificationManager.loginOnPswdExpiry(db); + + db.loadDBSpecificContents1(status); + parseServerVersion(db.getServerVersion()); + addDBtoList(db); + updateDBList(db); + DatabaseUtils.checkCancelStatusAndAbort(status, db); + db.loadDBSpecificContents2(status); + setServerIP2(db.fetchServerIP()); + DatabaseUtils.checkCancelStatusAndAbort(status, db); + refreshUserRoleObjectGroup(); + + return db.getProfileId(); + } + + /** + * Parses the server version. + * + * @param servVersion the serv version + */ + protected void parseServerVersion(String servVersion) { + this.setServerVersion(servVersion); + isSupportNodeGroupPrivilege = false; + this.trimmedVersion = CustomStringUtility.getFullServerVersionString(serverVersion); + } + + /** + * Update DB list. + * + * @param db the db + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void updateDBList(Database db) throws DatabaseCriticalException, DatabaseOperationException { + Iterator otherDbItr = DatabaseUtils.getAllDBListInServer(db).iterator(); + Database otherDb = null; + boolean hasNext = otherDbItr.hasNext(); + while (hasNext) { + otherDb = otherDbItr.next(); + if (!this.dbGroup.contains(otherDb.getOid())) { + this.dbGroup.addToGroup(otherDb); + } + hasNext = otherDbItr.hasNext(); + } + } + + /** + * Refresh. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws Exception the exception + */ + public void refresh() throws DatabaseOperationException, DatabaseCriticalException, Exception { + Database db = findOneActiveDb(); + refreshDBs(db); + this.tablespaceGroup.clear(); + db.fetchAllTablespace(); + this.accessMethods.clear(); + AccessMethod.fetchAllAccessMethods(db); + } + + /** + * Refresh server IP. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void refreshServerIP() throws DatabaseOperationException, DatabaseCriticalException { + Database db = findOneActiveDb(); + db.fetchServerIP(); + } + + /** + * Fetch server objects. + * + * @throws OutOfMemoryError the out of memory error + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void fetchServerObjects() throws OutOfMemoryError, DatabaseOperationException, DatabaseCriticalException { + refreshServerIP(); + getDatabaseGroup().refresh(); + } + + /** + * Refresh tablespace. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void refreshTablespace() throws DatabaseOperationException, DatabaseCriticalException { + varifyCounter(); + Database db = findOneActiveDb(); + this.tablespaceGroup.clear(); + db.fetchAllTablespace(); + } + + /** + * Varify counter. + */ + public void varifyCounter() { + RefreshCounter refreshCounter = RefreshCounter.getInstance(); + int counter = refreshCounter.getCountValue(); + counter = counter + 1; + RefreshCounter.getInstance().setCountValue(counter); + } + + /** + * Refresh tablespace metadata. + * + * @param oid the oid + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void refreshTablespaceMetadata(Long oid) throws DatabaseOperationException, DatabaseCriticalException { + Database db = findOneActiveDb(); + this.tablespaceGroup.removeFromGroup(oid); + db.fetchTablespaceMetaData(oid); + } + + /** + * Refresh D bs. + * + * @param db the db + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void refreshDBs(Database db) throws DatabaseOperationException, DatabaseCriticalException { + + ArrayList newDbs = DatabaseUtils.getAllDBListInServer(db); + HashMap newDbMap = new HashMap(4); + Iterator newDbItr = newDbs.iterator(); + boolean hasNext = newDbItr.hasNext(); + /* + * Loop through the new db list and create a hashmap for quicker & + * easier access. + */ + hasNext = refreshDbGroup(newDbMap, newDbItr, hasNext); + + Iterator oldDbs = this.dbGroup.getSortedServerObjectList().iterator(); + hasNext = oldDbs.hasNext(); + long oid = 0; + while (hasNext) { + oid = oldDbs.next().getOid(); + oldDbs = refreshEachDatabase(newDbMap, oldDbs, oid); + hasNext = oldDbs.hasNext(); + } + } + + private Iterator refreshEachDatabase(HashMap newDbMap, Iterator oldDbs, + long oid) throws DatabaseOperationException, DatabaseCriticalException, OutOfMemoryError { + Database currDb = null; + Database newDb = null; + if (!newDbMap.containsKey(oid)) { + /* Remove non existing DBs */ + this.dbGroup.getObjectById(oid).destroy(); + this.dbGroup.removeFromGroup(oid); + // Bala issue List #14 start + oldDbs = this.dbGroup.getSortedServerObjectList().iterator(); + // Bala issue List #14 end + } else { + /* + * Update the name & other objects, might have changed via other + * means + */ + newDb = newDbMap.get(oid); + currDb = this.dbGroup.getObjectById(oid); + currDb.setName(newDb.getName()); + + fetchDatabaseObjects(currDb); + } + return oldDbs; + } + + private void fetchDatabaseObjects(Database currDb) + throws DatabaseOperationException, DatabaseCriticalException, OutOfMemoryError { + if (currDb.isConnected()) { + currDb.fetchSearchPathObjects(false); + currDb.fetchDefaultDatatypes(true); + DatabaseHelper.fetchTablespaceName(currDb); + } + } + + private boolean refreshDbGroup(HashMap newDbMap, Iterator newDbItr, boolean hasNext) { + Database currDb; + while (hasNext) { + currDb = newDbItr.next(); + newDbMap.put(currDb.getOid(), currDb); + Database database = this.dbGroup.getObjectById(currDb.getOid()); + /* Add non existing db's in db list. */ + addDatabaseInGroup(currDb, database); + hasNext = newDbItr.hasNext(); + } + return hasNext; + } + + private void addDatabaseInGroup(Database currDb, Database database) { + if (!this.dbGroup.contains(currDb.getOid())) { + this.dbGroup.addToGroup(currDb); + } else { + // We have added this else condition + // ISSUE : If Database is renamed from SQL Terminal then + // Database name is not updated in Ds list ( DB IS NOT GETTING + // CONNECTED) + addIfDBIsDifferent(currDb, database); + } + } + + private void addIfDBIsDifferent(Database currDb, Database database) { + if (!database.isSameName(currDb)) { + dbGroup.remove(currDb); + this.dbGroup.addToGroup(currDb); + } + } + + /** + * Close. + */ + public void close() { + Iterator nodesItr = this.dbGroup.getSortedServerObjectList().iterator(); + boolean hasNext = nodesItr.hasNext(); + Database db = null; + while (hasNext) { + db = nodesItr.next(); + db.destroy(); + hasNext = nodesItr.hasNext(); + } + + this.accessMethods.clear(); + this.tablespaceGroup.clear(); + this.userRoleObjectGroup.clear(); + } + + /** + * Destroy. + */ + public void destroy() { + if (accessMethods != null) { + accessMethods.clear(); + accessMethods = null; + } + + if (tablespaceGroup != null) { + tablespaceGroup.clear(); + tablespaceGroup = null; + } + + this.dbGroup.clear(); + } + + /** + * Creates the database. + * + * @param databaseName the database name + * @param encodingType the encoding type + * @param freedb the freedb + * @param dbConnection the db connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void createDatabase(String databaseName, String encodingType, Database freedb, DBConnection dbConnection) + throws DatabaseOperationException, DatabaseCriticalException { + String qry = null; + + if (!encodingType.isEmpty()) { + qry = "Create database " + ServerObject.getQualifiedObjectName(databaseName) + " encoding='" + encodingType + + "'" + " template =" + "template0" + ';'; + } else { + qry = "Create database " + ServerObject.getQualifiedObjectName(databaseName) + ';'; + } + + dbConnection.execNonSelect(qry); + updateDBList(freedb); + } + + /** + * Creates the tablespace. + * + * @param query the query + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void createTablespace(String query) throws DatabaseOperationException, DatabaseCriticalException { + Database db = findOneActiveDb(); + db.getConnectionManager().execNonSelectOnObjBrowserConn(query); + this.refreshTablespace(); + } + + /** + * Creates the tablespace. + * + * @param query the query + * @param conn the conn + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void createTablespace(String query, DBConnection conn) + throws DatabaseOperationException, DatabaseCriticalException { + conn.execNonSelect(query); + this.refreshTablespace(); + } + + /** + * Find one active db. + * + * @return the database + * @throws DatabaseOperationException the database operation exception + */ + public Database findOneActiveDb() throws DatabaseOperationException { + Iterator dbItr = this.dbGroup.getSortedServerObjectList().iterator(); + boolean hasNext = dbItr.hasNext(); + Database db = null; + + while (hasNext) { + db = dbItr.next(); + if (db.isConnected()) { + return db; + } + + hasNext = dbItr.hasNext(); + } + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_NO_CONNECTION_AVAILABLE)); + throw new DatabaseOperationException(IMessagesConstants.ERR_NO_CONNECTION_AVAILABLE); + } + + /** + * Gets the tablespace group. + * + * @return the tablespace group + */ + public TablespaceObjectGroup getTablespaceGroup() { + return this.tablespaceGroup; + } + + /** + * Gets the database group. + * + * @return the database group + */ + public DatabaseObjectGroup getDatabaseGroup() { + return this.dbGroup; + } + + /** + * Gets the another connection. + * + * @param oid the oid + * @return the another connection + * @throws DatabaseOperationException the database operation exception + */ + public DBConnection getAnotherConnection(long oid) throws DatabaseOperationException { + return ConnectionUtils.getAnotherConnection(oid, this.dbGroup.getSortedServerObjectList()); + } + + /** + * Adds the to access methods. + * + * @param am the am + */ + public void addToAccessMethods(AccessMethod am) { + this.accessMethods.addToGroup(am); + } + + /** + * Removes the from access method. + * + * @param oid the oid + */ + public void removeFromAccessMethod(long oid) { + this.accessMethods.removeFromGroup(oid); + } + + /** + * Gets the access method. + * + * @param oid the oid + * @return the access method + */ + public AccessMethod getAccessMethod(long oid) { + return this.accessMethods.getObjectById(oid); + } + + /** + * Gets the access methods. + * + * @return the access methods + */ + public Collection getAccessMethods() { + return this.accessMethods.getSortedServerObjectList(); + } + + /** + * Sets the server IP 2. + * + * @param serverIP the new server IP 2 + */ + protected void setServerIP2(String serverIP) { + this.serverIP = serverIP; + } + + @Override + public int hashCode() { + final int prime = MPPDBIDEConstants.PRIME_31; + int result = 1; + result = prime * result + ((getHost() == null) ? 0 : getHost().hashCode() + (getPort() + "").hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + + if (obj == null) { + return false; + } + + if (!(obj instanceof Server)) { + return false; + } + Server other = (Server) obj; + return getId() == other.getId(); + } + + /** + * Gets the server connection info. + * + * @param dbname the dbname + * @return the server connection info + * @throws DataStudioSecurityException the data studio security exception + */ + public IServerConnectionInfo getServerConnectionInfo(String dbname) throws DataStudioSecurityException { + IServerConnectionInfo connInfo = this.newConfigInfo.getClone(); + connInfo.setDatabaseName(dbname); + SecureUtil sec = new SecureUtil(); + String path = ConnectionProfileManagerImpl.getInstance().getProfilePath(connInfo); + sec.setPackagePath(path); + connInfo.setPrd(sec.decryptPrd(encrpytedProfilePrd)); + connInfo.setSSLPrd(sec.decryptPrd(encrpytedsslPrd)); + + return connInfo; + } + + /** + * Sets the prd. + * + * @param prd the new prd + */ + public void setPrd(String prd) { + try { + encrpytedProfilePrd = prd; + + IServerConnectionInfo info = newConfigInfo.getClone(); + if (isPermanantOptionSelected()) { + info.setPrd(encrpytedProfilePrd.toCharArray()); + + info.setSavePrdOption(savePrdOption); + ConnectionProfileManagerImpl.getInstance().saveProfile(info); + info.setPrd(new char[0]); + newConfigInfo.setSavePrdOption(savePrdOption); + newConfigInfo.setPrd(encrpytedProfilePrd.toCharArray()); + + } else if (isCurrentSessionSelected()) { + info.setSavePrdOption(savePrdOption); + info.setPrd(new char[0]); + ConnectionProfileManagerImpl.getInstance().saveProfile(info); + newConfigInfo.setSavePrdOption(savePrdOption); + } + } catch (DataStudioSecurityException exception) { + MPPDBIDELoggerUtility.error("Server: set password failed.", exception); + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("Server: set password failed.", exception); + } + } + + private boolean isCurrentSessionSelected() { + return savePrdOption.equals(SavePrdOptions.CURRENT_SESSION_ONLY); + } + + private boolean isPermanantOptionSelected() { + return savePrdOption.equals(SavePrdOptions.PERMANENTLY); + } + + /** + * Sets the save prd option. + * + * @param ordinal the new save prd option + */ + public void setSavePrdOption(int ordinal) { + switch (ordinal) { + case 0: { + savePrdOption = SavePrdOptions.PERMANENTLY; + break; + } + case 1: { + savePrdOption = SavePrdOptions.CURRENT_SESSION_ONLY; + break; + } + default: { + savePrdOption = SavePrdOptions.DO_NOT_SAVE; + } + } + } + + /** + * Gets the save prd option. + * + * @return the save prd option + */ + public SavePrdOptions getSavePrdOption() { + return this.savePrdOption; + } + + /** + * Gets the encrpyted profile prd. + * + * @return the encrpyted profile prd + */ + public String getEncrpytedProfilePrd() { + return this.encrpytedProfilePrd; + } + + /** + * Gets the encrpytedssl prd. + * + * @return the encrpytedssl prd + */ + public String getEncrpytedsslPrd() { + return this.encrpytedsslPrd; + } + + /** + * Persist connection details. + * + * @param info the info + * @throws DatabaseOperationException the database operation exception + * @throws DataStudioSecurityException the data studio security exception + */ + public void persistConnectionDetails(IServerConnectionInfo info) + throws DatabaseOperationException, DataStudioSecurityException { + if (SavePrdOptions.PERMANENTLY.equals(info.getSavePrdOption())) { + info.setPrd(this.getEncrpytedProfilePrd().toCharArray()); + + } + + ConnectionProfileManagerImpl.getInstance().saveProfile(info); + info.clearPasrd(); + + this.newConfigInfo = info.getClone(); + } + + @Override + public IServerConnectionInfo getServerConnectionInfo() { + return newConfigInfo; + } + + /** + * Gets the user name from server conn info. + * + * @return the user name from server conn info + */ + public String getUserNameFromServerConnInfo() { + return newConfigInfo.getDsUsername(); + } + + /** + * Sets the server connection info. + * + * @param info the new server connection info + */ + public void setServerConnectionInfo(IServerConnectionInfo info) { + newConfigInfo = info.getClone(); + this.connectionName = newConfigInfo.getConectionName(); + } + + /** + * Belongs to. + * + * @param object the object + * @param server the server + * @return true, if successful + */ + public boolean belongsTo(Object object, Server server) { + return this.getName().equals(server.getName()); + } + + /** + * Checks if is database refreshin progress. + * + * @return true, if is database refreshin progress + */ + public boolean isDatabaseRefreshinProgress() { + Iterator dbItr = this.dbGroup.getSortedServerObjectList().iterator(); + boolean hasNext = dbItr.hasNext(); + Database db = null; + + while (hasNext) { + db = dbItr.next(); + if (isDBLoadingINProgress(db)) { + return true; + } + + hasNext = dbItr.hasNext(); + } + return false; + } + + private boolean isDBLoadingINProgress(Database db) { + return db.isConnected() && db.isLoadingNamespaceInProgress(); + } + + /** + * Refresh user role object group. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void refreshUserRoleObjectGroup() throws DatabaseOperationException, DatabaseCriticalException { + List userRoles = UserRoleManager.fetchAllUserRoleWithOutSuperUser(this, + this.findOneActiveDb().getConnectionManager().getObjBrowserConn()); + this.userRoleObjectGroup.clear(); + userRoles.stream().forEach(userRole -> this.userRoleObjectGroup.addToGroup(userRole)); + } + + /** + * Gets the children. + * + * @return the children + */ + public Object[] getChildren() { + Collection servers = new ArrayList(4); + servers.add(this.getDatabaseGroup()); + servers.add(this.getTablespaceGroup()); + servers.add(this.userRoleObjectGroup); + + return servers.toArray(); + + } + + /** + * Gets the driver name. + * + * @return the driver name + */ + public String getDriverName() { + return this.driverName; + } + + /** + * Sets the driver name. + * + * @param driverName the new driver name + */ + public void setDriverName(String driverName) { + this.driverName = driverName; + } + + /** + * Checks if is support tablespace relative path. + * + * @return true, if is support tablespace relative path + */ + public boolean isSupportTablespaceRelativePath() { + return true; + } + + /** + * Sets the server version. + * + * @param vers the new server version + */ + public void setServerVersion(String vers) { + this.serverVersion = vers; + } + + /** + * Gets the server version. + * + * @param isTrim the is trim + * @return the server version + */ + public String getServerVersion(boolean isTrim) { + if (isTrim) { + return this.trimmedVersion; + } + + return this.serverVersion; + } + + /** + * Sets the server compatible to node group. use for testing + * + * @param flag the new server compatible to node group + */ + public void setServerCompatibleToNodeGroup(boolean flag) { + isSupportNodeGroupPrivilege = true; + } + + /** + * Checks if is server compatible to node group privilege. + * + * @return true, if is server compatible to node group privilege + */ + public boolean isServerCompatibleToNodeGroupPrivilege() { + return isSupportNodeGroupPrivilege; + } + + /** + * Gets the server IP. + * + * @return the server IP + */ + public String getServerIP2() { + return serverIP; + } + + /** + * Gets the privilege flag. + * + * @return the privilege flag + */ + public boolean getPrivilegeFlag() { + return privilegeFlag; + } + + /** + * Sets the privilege flag. + * + * @param privilegeFlag the new privilege flag + */ + public void setPrivilegeFlag(boolean privilegeFlag) { + this.privilegeFlag = privilegeFlag; + } + + /** + * Gets the user role object group. + * + * @return the user role object group + */ + public UserRoleObjectGroup getUserRoleObjectGroup() { + return userRoleObjectGroup; + } + + /** + * Gets the jdbc connection string prefix. + * + * @return the jdbc connection string prefix + */ + public String getJdbcConnectionStringPrefix() { + return "jdbc:postgresql://"; + } + + /** + * Gets the all databases for search. + * + * @param dataBases the data bases + * @param dBMap the d B map + * @return the all databases for search + */ + public void getAllDatabasesForSearch(ArrayList dataBases, HashMap dBMap) { + Iterator dBs = this.getAllDatabases().iterator(); + + boolean dbHasNext = dBs.hasNext(); + Database databse = null; + int idex = 0; + while (dbHasNext) { + databse = dBs.next(); + if (databse.isConnected()) { + dataBases.add(databse.getName()); + dBMap.put(idex, databse); + idex++; + } + dbHasNext = dBs.hasNext(); + } + } + + /** + * Removes the from database group. + * + * @param oid the oid + */ + public void removeFromDatabaseGroup(long oid) { + dbGroup.removeFromGroup(oid); + } + + /** + * Adds the to database group. + * + * @param obj the obj + */ + public void addToDatabaseGroup(Database obj) { + dbGroup.addToGroup(obj); + } + + /** + * Adds the to tablespace group. + * + * @param obj the obj + */ + public void addToTablespaceGroup(Tablespace obj) { + tablespaceGroup.addToGroup(obj); + } + + /** + * Gets the tablespaces. + * + * @return the tablespaces + */ + public Iterator getTablespaces() { + return this.getTablespaceGroup().getSortedServerObjectList().iterator(); + } + + /** + * Gets the tablespace by id. + * + * @param oid the oid + * @return the tablespace by id + */ + public Tablespace getTablespaceById(long oid) { + return getTablespaceGroup().getObjectById(oid); + } + + /** + * Gets the defaul parametert map. + * + * @return the defaul parametert map + */ + public HashMap> getDefaulParametertMap() { + return defaulParametertMap; + } + + /** + * Sets the defaul parametert map. + * + * @param id the id + * @param debugDefaultList the debug default list + */ + public void setDefaulParametertMap(Long id, ArrayList debugDefaultList) { + defaulParametertMap.put(id, debugDefaultList); + } + + /** + * Gets the user name. + * + * @return the user name + */ + public String getUserName() { + return this.getServerConnectionInfo().getDsUsername(); + } + + /** + * is version after 930. + * + * @return boolean true if after 930 else false + */ + public boolean versionAfter930() { + String serverVersionString = getServerVersion(true); + String compareTrimVersionFor1230 = "PostgreSQL 9.2.4 (GaussDB Kernel V500R001C20 build )"; + if (serverVersionString.equals(compareTrimVersionFor1230)) { + return true; + } + String compareTrimVersion = "openGauss 1.0.0"; + int length = serverVersionString.length() < compareTrimVersion.length() ? + serverVersionString.length() : compareTrimVersion.length(); + String trimVersion = serverVersionString.substring(0, length); + if (trimVersion.compareTo(compareTrimVersion) > 0) { + return true; + } + boolean ret = true; + String version = getServerVersion(false); + try { + String regex = "\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}"; + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); + Matcher matcher = Pattern.compile(regex).matcher(version); + if (matcher.find()) { + String curVersionTime = matcher.group().trim(); + Date curDate = format.parse(curVersionTime); + if (curDate.compareTo(format.parse("2020-08-30 00:00:00")) <= 0) { + ret = false; + } + } + } catch (ParseException dateFormatExecept) { + ret = true; + } + return ret; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ServerObject.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ServerObject.java new file mode 100644 index 0000000000000000000000000000000000000000..e84fcfe7ef039f75127d18196dbfb665314ef068 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ServerObject.java @@ -0,0 +1,541 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import org.opengauss.mppdbide.adapter.gauss.HandleGaussStringEscaping; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.SQLKeywords; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class ServerObject. + * + */ + +public abstract class ServerObject { + + private long oid; + private String name; + private OBJECTTYPE type; + private boolean isValid = true; + + /** + * The is loaded. + */ + protected boolean isLoaded; + + /** + * The privilege flag. + */ + protected boolean privilegeFlag; + + /** + * Sets the privilege flag. + * + * @param privilegeFlag the new privilege flag + */ + public void setPrivilegeFlag(boolean privilegeFlag) { + this.privilegeFlag = privilegeFlag; + } + + /** + * Gets the privilege flag. + * + * @return the privilege flag + */ + public boolean getPrivilegeFlag() { + return this.privilegeFlag; + } + + /** + * Hash code. + * + * @return the int + */ + @Override + public int hashCode() { + final int primeNumber = 31; + int result = 1; + result = getRamdomNumber(primeNumber, result) + ((name == null) ? 0 : name.hashCode()); + + result = getRamdomNumber(primeNumber, result) + (int) (oid ^ (oid >>> 32)); + + result = getRamdomNumber(primeNumber, result) + ((getParent() == null) ? 0 : getParent().hashCode()); + return result; + } + + /** + * Gets the window title name. + * + * @return the window title name + */ + public String getWindowTitleName() { + return name; + } + + /** + * Gets the ramdom number. + * + * @param primeNumber the prime number + * @param result the result + * @return the ramdom number + */ + private int getRamdomNumber(final int primeNumber, int result) { + return primeNumber * result; + } + + /** + * Equals. + * + * @param obj the obj + * @return true, if successful + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + + if (validateObjectForNull(obj)) { + return false; + } + + if (!(obj instanceof ServerObject)) { + return false; + } + + ServerObject other = (ServerObject) obj; + if (validateObjectForNull(name)) { + if (!validateObjectForNull(other.name)) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + + if (oid != other.oid) { + return false; + } + + if (type != other.type) { + return false; + } + + if (validateObjectForNull(getParent())) { + if (!validateObjectForNull(other.getParent())) { + return false; + } + } else if (!getParent().equals(other.getParent())) { + return false; + } + + return true; + } + + /** + * Validate object for null. + * + * @param obj the obj + * @return true, if successful + */ + private boolean validateObjectForNull(Object obj) { + return obj == null; + } + + /** + * Checks if is valid. + * + * @return true, if is valid + */ + public boolean isValid() { + return isValid; + } + + /** + * Sets the valid. + * + * @param isVald the new valid + */ + public void setValid(boolean isVald) { + this.isValid = isVald; + } + + /** + * Instantiates a new server object. + * + * @param type the type + */ + public ServerObject(OBJECTTYPE type) { + this.type = type; + } + + /** + * Instantiates a new server object. + * + * @param oid the oid + * @param name the name + * @param type the type + * @param privilegeFlag the privilege flag + */ + public ServerObject(long oid, String name, OBJECTTYPE type, boolean privilegeFlag) { + this.type = type; + this.oid = oid; + this.name = name; + this.privilegeFlag = privilegeFlag; + } + + /** + * Sets the oid. + * + * @param oid the new oid + */ + public void setOid(long oid) { + this.oid = oid; + } + + /** + * Gets the oid. + * + * @return the oid + */ + public long getOid() { + return oid; + } + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Sets the name. + * + * @param name the new name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Gets the type. + * + * @return the type + */ + public OBJECTTYPE getType() { + return type; + } + + /** + * Gets the type label. + * + * @return the type label + */ + public String getTypeLabel() { + + return DBTypeLabelUtil.getTypeLabel(type); + + } + + /** + * Gets the search name. + * + * @return the search name + */ + public String getSearchName() { + return getQualifiedSimpleObjectName(this.name); + } + + /** + * Gets the display name. + * + * @return the display name + */ + public String getDisplayName() { + return getQualifiedObjectName(); + } + + /** + * Gets the qualified object name. + * + * @return the qualified object name + */ + public String getQualifiedObjectName() { + return getQualifiedObjectName(this.name); + } + + /** + * Gets the qualified object name. + * + * @param objectName the object name + * @return the qualified object name + */ + public static String getQualifiedObjectName(String objectName) { + if (objectName == null) { + return null; + } + if (isKeywordName(objectName)) { + return addQualifiedNameForKeyword(objectName); + } + + return getQualifiedSimpleObjectName(objectName); + + } + + /** + * Gets the qualified simple object name. + * + * @param objectName the object name + * @return the qualified simple object name + */ + public static String getQualifiedSimpleObjectName(String objectName) { + if (isQualifiedSimpleObjectName(objectName)) { + return objectName; + } + return HandleGaussStringEscaping.escapeIdentifier(objectName).toString(); + } + + /** + * Gets the qualified object name handle quotes. + * + * @param objectName the object name + * @return the qualified object name handle quotes + */ + public static String getQualifiedObjectNameHandleQuotes(String objectName) { + if (ServerObject.isQualifiedSimpleObjectNameHandleQuotes(objectName)) { + return objectName; + } + return HandleGaussStringEscaping.escapeIdentifier(objectName).toString(); + } + + /** + * Gets the literal name. + * + * @param objectName the object name + * @return the literal name + */ + public static String getLiteralName(String objectName) { + return HandleGaussStringEscaping.escapeLiteral(null, objectName).toString(); + } + + /** + * Checks if is qualified simple object name. + * + * @param objectName the object name + * @return true, if is qualified simple object name + */ + public static boolean isQualifiedSimpleObjectName(String objectName) { + if (null != objectName && !objectName.isEmpty() && objectName.matches("^[a-z_][a-z|0-9|_|$]*$")) { + return true; + } + + return false; + } + + /** + * Checks if is qualified simple object name handle quotes. + * + * @param objectName the object name + * @return true, if is qualified simple object name handle quotes + */ + public static boolean isQualifiedSimpleObjectNameHandleQuotes(String objectName) { + if (null != objectName && !objectName.isEmpty() && ((objectName.matches("^[A-Z|a-z_][A-Z|a-z|0-9|_|$]*$")) + || (objectName.startsWith("\"") && objectName.endsWith("\"")))) { + return true; + } + + return false; + } + + /** + * Gets the qualified object name split. + * + * @param objectName the object name + * @return the qualified object name split + */ + public String getQualifiedObjectNameSplit(String[] objectName) { + StringBuilder returnString = new StringBuilder(""); + if (null == objectName) { + return null; + } else if (objectName.length == 1) { + returnString.append(ServerObject.getQualifiedObjectNameHandleQuotes(objectName[0])); + } else { + for (int index = 0; index < objectName.length; index++) { + returnString.append(ServerObject.getQualifiedObjectNameHandleQuotes(objectName[index])); + if (index < objectName.length - 1) { + returnString.append("."); + } + } + } + return returnString.toString(); + } + + /** + * Checks if is qualified partition value. + * + * @param objectName the object name + * @return the string + */ + public static String isQualifiedPartitionValue(String objectName) { + if (null == objectName) { + return ""; + } + if (!objectName.isEmpty() && objectName.matches("[A-Za-z0-9_\\-\\.]*")) { + return '\'' + objectName + '\''; + } + return HandleGaussStringEscaping.escapeIdentifier(objectName).toString(); + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + return null; + } + + /** + * Gets the display label. + * + * @return the display label + */ + public String getDisplayLabel() { + + String objName = getName(); + return null == objName || objName.length() < 1 + ? MessageConfigLoader.getProperty(IMessagesConstants.OBJECT_BROWSER_LABEL_MSG) + : objName; + } + + /** + * Gets the children. + * + * @return the children + */ + public Object[] getChildren() { + return new Object[0]; + } + + /** + * Checks if is loading in progress. + * + * @return true, if is loading in progress + */ + public boolean isLoadingInProgress() { + return false; + } + + /** + * Gets the object browser label. + * + * @return the object browser label + */ + public String getObjectBrowserLabel() { + return getDisplayLabel(); + } + + /** + * Gets the parent. + * + * @return the parent + */ + public Object getParent() { + return null; + } + + /** + * Checks if is loaded. + * + * @return true, if is loaded + */ + public boolean isLoaded() { + return true; + } + + /** + * Checks if is keyword name. + * + * @param objectName the object name + * @return true, if is keyword name + */ + public static boolean isKeywordName(String objectName) { + + return SQLKeywords.getKeywords().containsKey(objectName); + + } + + /** + * Adds the qualified name for keyword. + * + * @param objectName the object name + * @return the string + */ + public static String addQualifiedNameForKeyword(String objectName) { + return "\"" + objectName + "\""; + } + + /** + * Gets the namespace. + * + * @return the namespace + */ + public ServerObject getNamespace() { + return null; + + } + + /** + * Gets the auto suggestion name. + * + * @param isAutoSuggest the is auto suggest + * @return the auto suggestion name + */ + public String getAutoSuggestionName(boolean isAutoSuggest) { + return getQualifiedObjectName(); + } + + /** + * Gets the connection manager. + * + * @return the connection manager + */ + public ConnectionManager getConnectionManager() { + if (getDatabase() != null) { + return getDatabase().getConnectionManager(); + } + return null; + } + + /** + * Sets the loaded. + * + * @param isLoaded the new loaded + */ + public void setLoaded(boolean isLoaded) { + this.isLoaded = isLoaded; + } + + public boolean getLoaded() { + return this.isLoaded; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ServerProperty.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ServerProperty.java new file mode 100644 index 0000000000000000000000000000000000000000..1feb548879831940a5b5f9293968517583df78ee --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ServerProperty.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: class + * + * Description: The Class ServerProperty. + * + */ + +public class ServerProperty { + + private String key; + private String value; + private String[] prop; + + /** + * Gets the propery title. + * + * @return the propery title + */ + public String getProperyTitle() { + return "Property-X"; + } + + /** + * Instantiates a new server property. + * + * @param key the key + * @param value the value + */ + public ServerProperty(String key, String value) { + this.key = key; + this.value = value; + } + + /** + * Instantiates a new server property. + * + * @param key the key + * @param value the value + */ + public ServerProperty(String key, double value) { + this(key, "" + value); + } + + /** + * Instantiates a new server property. + * + * @param key the key + * @param value the value + */ + public ServerProperty(String key, long value) { + this(key, "" + value); + } + + /** + * Instantiates a new server property. + * + * @param key the key + * @param value the value + */ + public ServerProperty(String key, int value) { + this(key, "" + value); + } + + /** + * Gets the key. + * + * @return the key + */ + public String getKey() { + return this.key; + } + + /** + * Gets the value. + * + * @return the value + */ + public String getValue() { + return this.value; + } + + /** + * Gets the prop. + * + * @return the prop + */ + public String[] getProp() { + prop = new String[2]; + prop[0] = getKey(); + prop[1] = getValue(); + return prop; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ServerUtil.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ServerUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..3adc0552d91752592d23db114ca5e3f34fa0b60c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ServerUtil.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.util.Properties; + +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; +import org.opengauss.mppdbide.utils.MemoryCleaner; +import org.opengauss.mppdbide.utils.security.SecureUtil; + +/** + * Title: ServerUtil + * + * @since 3.0.0 + */ +public class ServerUtil { + /** + * Clear property details. + * + * @param props the props + */ + public static void clearPropertyDetails(Properties props) { + SecureUtil.cleanKeyString(props.getProperty("password")); + props.setProperty("password", ""); + props.remove("password"); + } + + /** + * Clear connection info. + * + * @param connInfo the conn info + */ + public static void clearConnectionInfo(IServerConnectionInfo connInfo) { + connInfo.clearPasrd(); + + MemoryCleaner.cleanUpMemory(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ShowMoreObject.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ShowMoreObject.java new file mode 100644 index 0000000000000000000000000000000000000000..5b0fbd4ed0082a7cf17f97091d88ce27d60a4fa5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ShowMoreObject.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import org.opengauss.mppdbide.bl.serverdatacache.groups.ObjectGroup; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * Title: ShowMoreObject + * + * Description: + * + */ + +public class ShowMoreObject extends ServerObject { + + private ObjectGroup group; + + /** + * Instantiates a new show more object. + * + * @param type the type + * @param group the group + */ + public ShowMoreObject(OBJECTTYPE type, ObjectGroup group) { + super(type); + this.group = group; + } + + /** + * Gets the children. + * + * @return the children + */ + @Override + public Object[] getChildren() { + return new Object[0]; + } + + /** + * Gets the parent. + * + * @return the parent + */ + @Override + public Object getParent() { + return this.group; + } + + /** + * Gets the display label. + * + * @return the display label + */ + @Override + public String getDisplayLabel() { + return MessageConfigLoader.getProperty(IMessagesConstants.SHOW_MORE_OBJECTS); + } + + /** + * Render next batch of objects onto object browser + */ + public void showNextBatch() { + group.incrementShowObjectCount(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SourceCode.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SourceCode.java new file mode 100644 index 0000000000000000000000000000000000000000..db83cf701b8c3bf68e3b5c21993df5204c7a32d6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SourceCode.java @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class SourceCode. + * + */ + +public class SourceCode implements ISourceCode { + + private String code; + private long versionNumber1; + private long versionNumber2; + private int headerLength; + + /** + * Gets the code. + * + * @return the code + */ + public String getCode() { + return code; + } + + /** + * Sets the code. + * + * @param code the code to set + */ + public void setCode(String code) { + this.code = code; + } + + /** + * Gets the version number 1. + * + * @return the version number 1 + */ + public long getVersionNumber1() { + return versionNumber1; + } + + /** + * Sets the version number 1. + * + * @param versionNumber1 the new version number 1 + */ + public void setVersionNumber1(long versionNumber1) { + this.versionNumber1 = versionNumber1; + } + + /** + * Gets the version number 2. + * + * @return the version number 2 + */ + public long getVersionNumber2() { + return versionNumber2; + } + + /** + * Sets the version number 2. + * + * @param versionNumber2 the new version number 2 + */ + public void setVersionNumber2(long versionNumber2) { + this.versionNumber2 = versionNumber2; + } + + /** + * Gets the header length. + * + * @return the header length + */ + public int getHeaderLength() { + return headerLength; + } + + /** + * Sets the header length. + * + * @param headerLength the new header length + */ + public void setHeaderLength(int headerLength) { + this.headerLength = headerLength; + } + + /** + * Update code. + * + * @param rs the rs + * @throws SQLException the SQL exception + */ + public void updateCode(ResultSet rs) throws SQLException { + StringBuilder fnsSrc = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + this.setHeaderLength(rs.getInt(1)); + String src = rs.getString(2); + if (null != src) { + fnsSrc.append(src.replaceAll("\\$function\\$", "\\$\\$")); + fnsSrc.append(MPPDBIDEConstants.ESCAPE_FORWARDSLASH); + this.setCode(fnsSrc.toString()); + } + } + + /** + * Update version number. + * + * @param rs the rs + * @throws SQLException the SQL exception + */ + public void updateVersionNumber(ResultSet rs) throws SQLException { + if (null != rs) { + this.setVersionNumber1(rs.getLong(1)); + this.setVersionNumber2(rs.getLong(2)); + } + } + + /** + * Gets the source line num from server equivalent. + * + * @param serverEqualentLineNumber the server equalent line number + * @return the source line num from server equivalent + */ + public int getSourceLineNumFromServerEquivalent(int serverEqualentLineNumber) { + return serverEqualentLineNumber - getHeaderLength(); + } + + /** + * Checks if is changed. + * + * @param latCode the lat code + * @return true, if is changed + */ + public boolean isChanged(String latCode) { + String latestCode = latCode; + if (code == null) { + return false; + } + if (code.equals(latestCode)) { + return false; + } + return true; + } + +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SynonymMetaData.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SynonymMetaData.java new file mode 100644 index 0000000000000000000000000000000000000000..898655dfb288077b7811832296066083ab857458 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SynonymMetaData.java @@ -0,0 +1,302 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.SynonymConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: Class + * + * Description: The Class SynonymMetaData. + * + * @since 3.0.0 + */ +public class SynonymMetaData extends BatchDropServerObject implements GaussOLAPDBMSObject, ISynonymMetaData { + /** + * Refresh synonym statement + */ + public static final String REFRESH_SYNONYM_STATEMENT = SynonymUtil.SYNONYM_STATEMENT + + " and schema_name = ? and synonym_name = ?;"; + + private static int virtualId = 1; + private static final Object ID_LOCK = new Object(); + + private Namespace namespace; + private String owner; + private String objectOwner; + private String objectName; + + /** + * Instantiates a new synonym meta data. + * + * @param name the name + * @param Namespace the namespace + */ + public SynonymMetaData(String name, Namespace namespace) { + super(getNextVirtualID(), name, OBJECTTYPE.SYNONYM_METADATA_GROUP, true); + this.namespace = namespace; + } + + /** + * Gets the drop query. + * + * @param isCascade the is cascade + * @return the drop query + */ + @Override + public String getDropQuery(boolean isCascade) { + String dropSynonymQuery = "DROP SYNONYM IF EXISTS "; + StringBuilder query = null; + query = new StringBuilder(dropSynonymQuery); + query.append(namespace.getQualifiedObjectName()).append('.').append(this.getQualifiedObjectName()); + return query.toString(); + } + + /** + * Refresh. + * + * @param dbConnection the db connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void refresh(DBConnection dbConnection) throws DatabaseOperationException, DatabaseCriticalException { + PreparedStatement preparedStatement = null; + ResultSet rs = null; + try { + preparedStatement = dbConnection.getPrepareStmt(REFRESH_SYNONYM_STATEMENT); + preparedStatement.setString(1, namespace.getQualifiedObjectName()); + preparedStatement.setString(2, getQualifiedObjectName()); + rs = preparedStatement.executeQuery(); + if (rs.next()) { + removeSynonym(); + SynonymMetaData synonymMetaData = SynonymUtil.convertToSynonym(this, rs, namespace); + namespace.addSynonym(synonymMetaData); + } else { + removeSynonym(); + } + } catch (SQLException | DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } finally { + dbConnection.closeResultSet(rs); + dbConnection.closeStatement(preparedStatement); + } + } + + /** + * Removes the synonym. + */ + public void removeSynonym() { + this.namespace.getDatabase().getSearchPoolManager().removeSynonymFromSearchPool(this); + this.namespace.getSynonymGroup().removeFromGroup(getOid()); + } + + /** + * Gets the parent. + * + * @return the parent + */ + public Namespace getParent() { + return namespace; + } + + /** + * Gets the database. + * + * @return the database + */ + @Override + public Database getDatabase() { + return namespace.getDatabase(); + } + + /** + * Gets the search name. + * + * @return the search name + */ + @Override + public String getSearchName() { + return getName() + " - " + getParent().getQualifiedObjectName() + " - " + getTypeLabel(); + } + + /** + * Gets the drop name. + * + * @return the drop name + */ + public String getDropName() { + return getParent().getQualifiedObjectName() + '.' + getQualifiedObjectName(); + } + + /** + * Gets the name. + * + * @return the name + */ + @Override + public String getName() { + return super.getName(); + } + + /** + * Gets the window title name. + * + * @return the window title name + */ + @Override + public String getWindowTitleName() { + return namespace.getQualifiedObjectName() + '.' + getName() + '-' + getDatabaseName() + '@' + getServerName(); + } + + /** + * Gets the owner. + * + * @return the owner + * @Title: getOwner + * @Description: get the owner + */ + public String getOwner() { + return owner; + } + + /** + * Sets the owner. + * + * @param owner the owner + * @Title: setOwner + * @Description: set the owner + */ + public void setOwner(String owner) { + this.owner = owner; + } + + /** + * Gets the object owner. + * + * @return the object owner + * @Title: getObjectOwner + * @Description: get the object owner + */ + public String getObjectOwner() { + return objectOwner; + } + + /** + * Sets the object owner. + * + * @param objectOwner the object owner + * @Title: setObejctOwner + * @Description: set the object owner + */ + public void setObjectOwner(String objectOwner) { + this.objectOwner = objectOwner; + } + + /** + * Gets the object name. + * + * @return the object name + * @Title: getObjectName + * @Description: get the object name + */ + public String getObjectName() { + return objectName; + } + + /** + * Sets the object name. + * + * @param objectName the object name + * @Title: setObjectName + * @Description: set the object name + */ + public void setObjectName(String objectName) { + this.objectName = objectName; + } + + /** + * Drop synonym. + * + * @param conn the dbConnection + * @param isCasecade if is casecade + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @Title: dropSynonym + * @Description: drop synonym + */ + public void dropSynonym(DBConnection conn, boolean isCasecade) + throws DatabaseOperationException, DatabaseCriticalException { + conn.execNonSelect(getDropQuery(isCasecade)); + removeSynonym(); + } + + private static int getNextVirtualID() { + int nextId; + synchronized (ID_LOCK) { + nextId = virtualId; + virtualId++; + } + return nextId; + } + + /** + * Gets the server name. + * + * @return the server name + */ + public String getServerName() { + if (namespace == null) { + return ""; + } + return namespace.getServer().getName(); + } + + /** + * Gets the database name. + * + * @return the database name + */ + public String getDatabaseName() { + if (namespace == null) { + return ""; + } + return namespace.getDatabase().getName(); + } + + @Override + public void refreshSynonym(DBConnection dbConnection) throws DatabaseOperationException, DatabaseCriticalException { + } + + @Override + public Server getServer() { + return namespace.getServer(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SynonymUtil.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SynonymUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..4c7d423a4787984be1064e5caac591af6c90ca8d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SynonymUtil.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.SynonymConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: SynonymUtil + * + * Description: + * + */ + +public class SynonymUtil { + /** + * Synonym Statement + */ + public static final String SYNONYM_STATEMENT = "select pgs.synname as synonym_name, pgr.rolname as owner," + + " pgn.nspname" + " as schema_name," + " pgs.synobjname " + + "as table_name from pg_synonym pgs, pg_namespace pgn,pg_roles pgr where" + + " pgn.oid=pgs.synnamespace and pgs.synowner=pgr.oid"; + + /** + * fetch synonym statement + */ + public static final String FETCH_SYNONYM_STATEMENT = SYNONYM_STATEMENT + " and schema_name =?"; + + /** + * Fetch synonyms. + * + * @param Namespace the namespace + * @param dbConnection the db connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @Title: fetchSynonyms + * @Description: Fetch Synonyms. + */ + public static void fetchSynonyms(Namespace namespace, DBConnection dbConnection) + throws DatabaseOperationException, DatabaseCriticalException { + PreparedStatement preparedStatement = null; + ResultSet rs = null; + try { + preparedStatement = dbConnection.getPrepareStmt(FETCH_SYNONYM_STATEMENT); + preparedStatement.setString(1, namespace.getQualifiedObjectName()); + + rs = preparedStatement.executeQuery(); + + namespace.getSynonyms().clear(); + boolean hasNext = rs.next(); + while (hasNext) { + SynonymMetaData synonymMetaData = convertToSynonym(null, rs, namespace); + namespace.addSynonym(synonymMetaData); + hasNext = rs.next(); + } + } catch (DatabaseOperationException | SQLException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exception); + if (exception instanceof SQLException) { + String sqlState = ((SQLException) exception).getSQLState(); + if ("42P01".equalsIgnoreCase(sqlState)) { + namespace.setSynoymSupported(false); + /* + * Synonyms are not supported in this server. Do not throw + * exception in this case + */ + return; + } + } + + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } finally { + if (rs != null) { + dbConnection.closeResultSet(rs); + } + } + } + + /** + * convertToSynonym method + * + * @param synonym meta data + * @param rs resultset + * @param ns namespace + * @return object synonym + * @throws SQLException exception + */ + public static SynonymMetaData convertToSynonym(SynonymMetaData synonym, ResultSet rs, Namespace ns) + throws SQLException { + SynonymMetaData synonymMetaData = synonym; + if (null == synonymMetaData) { + synonymMetaData = new SynonymMetaData(rs.getString(SynonymConstants.SYN_NAME), ns); + } + + synonymMetaData.setName(rs.getString(SynonymConstants.SYN_NAME)); + synonymMetaData.setOwner(rs.getString(SynonymConstants.OWNER.toLowerCase(Locale.ENGLISH))); + synonymMetaData.setObjectOwner(rs.getString(SynonymConstants.SCHEMA_NAME)); + synonymMetaData.setObjectName(rs.getString(SynonymConstants.TAB_NAME)); + return synonymMetaData; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SystemNamespace.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SystemNamespace.java new file mode 100644 index 0000000000000000000000000000000000000000..f1adec5a728befc8615b959265d670b19db991ef --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SystemNamespace.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: class + * + * Description: The Class SystemNamespace. + * + */ + +public class SystemNamespace extends Namespace { + + /** + * Instantiates a new system namespace. + * + * @param oid the oid + * @param name the name + * @param parentDb the parent db + */ + public SystemNamespace(long oid, String name, Database parentDb) { + super(oid, name, parentDb); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SystemSetting.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SystemSetting.java new file mode 100644 index 0000000000000000000000000000000000000000..10b4965d0be6d98af48bb68d0cbedd399df26a59 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/SystemSetting.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: class + * + * Description: The Class SystemSetting. + * + */ + +public class SystemSetting implements ISystemSetting { + + private boolean loginAllowedOnPasswordExpiry; + private static volatile ISystemSetting instance = null; + private static final Object LOCK = new Object(); + + /** + * Gets the single instance of SystemSetting. + * + * @return single instance of SystemSetting + */ + public static ISystemSetting getInstance() { + if (null == instance) { + synchronized (LOCK) { + if (null == instance) { + instance = new SystemSetting(); + } + } + } + return instance; + } + + /** + * Checks if is login allowed on password expiry. + * + * @return true, if is login allowed on password expiry + * org.opengauss.mppdbide.bl.serverdatacache.ISystemSetting# + * isLogginaAllowedOnPasswordExpiry() + */ + @Override + public boolean isLoginAllowedOnPasswordExpiry() { + + return loginAllowedOnPasswordExpiry; + } + + /** + * Sets the login allowed on password expiry. + * + * @param isAllowedOnPasswordExpiry the new login allowed on password expiry + */ + public void setLoginAllowedOnPasswordExpiry(boolean isAllowedOnPasswordExpiry) { + this.loginAllowedOnPasswordExpiry = isAllowedOnPasswordExpiry; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TableMetaData.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TableMetaData.java new file mode 100644 index 0000000000000000000000000000000000000000..1b896a41a06e5623d60afae626d7c1704ed9f67d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TableMetaData.java @@ -0,0 +1,1898 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.Array; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.SortedMap; +import java.util.StringTokenizer; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.bl.export.EXPORTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ColumnList; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ConstraintList; +import org.opengauss.mppdbide.bl.serverdatacache.groups.IndexList; +import org.opengauss.mppdbide.bl.serverdatacache.groups.OLAPObjectList; +import org.opengauss.mppdbide.bl.serverdatacache.groups.TableObjectGroup; +import org.opengauss.mppdbide.bl.util.ExecTimer; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class TableMetaData. + * + */ + +public class TableMetaData extends BatchDropServerObject implements GaussOLAPDBMSObject, ITableMetaData { + + private Namespace nameSpace; + private String tablespaceName; + private boolean isTempTable; + private boolean isUnLoggedTable; + private boolean isIfNotExtists; + private TableOrientation tabOrientation; + private boolean hasOidCol; + private int fillfactor; + + private String distributeOptions; + private String nodeOptions; + + private ColumnList columns; + + /** + * The is roll back. + */ + protected boolean isRollBack = false; + + private boolean isLevel3Loaded; + private boolean isLevel3LoadInProgress; + + /** + * The orc version. + */ + protected String orcVersion; + private List distributionClmList = new ArrayList(10); + + private String source = ""; + + /** + * Table constraints Note: incase of edit all column level constraints are + * also come here as it can't be associates with column + */ + private ConstraintList constraintList; + + /** + * Index List Note: incase of edit all column level unique indexes are also + * come here as it can't be associates with column anymore. + */ + private IndexList indexList; + + private String description; + + /** + * Instantiates a new table meta data. + * + * @param oid the oid + * @param name the name + * @param nameSpace the name space + * @param tableSpace the table space + * @param type the type + */ + public TableMetaData(long oid, String name, Namespace nameSpace, String tableSpace, OBJECTTYPE type) { + super(oid, name, type, nameSpace != null ? nameSpace.getPrivilegeFlag() : true); + + this.nameSpace = nameSpace; + this.tablespaceName = tableSpace; + + this.fillfactor = 100; + + this.columns = new ColumnList(OBJECTTYPE.COLUMN_GROUP, this); + this.constraintList = new ConstraintList(OBJECTTYPE.CONSTRAINT_GROUP, this); + this.indexList = new IndexList(OBJECTTYPE.INDEX_GROUP, this); + this.isLevel3Loaded = false; + this.isLevel3LoadInProgress = false; + } + + /** + * Instantiates a new table meta data. + * + * @param oid the oid + * @param name the name + * @param nameSpace the name space + * @param tableSpace the table space + */ + public TableMetaData(long oid, String name, Namespace nameSpace, String tableSpace) { + this(oid, name, nameSpace, tableSpace, OBJECTTYPE.TABLEMETADATA); + } + + /** + * Instantiates a new table meta data. + * + * @param nameSpace the name space + */ + public TableMetaData(Namespace nameSpace) { + this(0, "notablename", nameSpace, null); + } + + /** + * Gets the source. + * + * @return the source + */ + public String getSource() { + return source; + } + + /** + * Sets the source. + * + * @param source the new source + */ + private void setSource(String source) { + this.source = source; + } + + /** + * Sets the distribute options. + * + * @param distributeOptions the new distribute options + */ + public void setDistributeOptions(String distributeOptions) { + this.distributeOptions = distributeOptions; + } + + /** + * Sets the node options. + * + * @param nodeOptions the new node options + */ + public void setNodeOptions(String nodeOptions) { + this.nodeOptions = nodeOptions; + } + + /** + * Sets the fillfactor. + * + * @param fillfactor the new fillfactor + */ + public void setFillfactor(int fillfactor) { + this.fillfactor = fillfactor; + } + + /** + * Move column. + * + * @param index the index + * @param up the up + */ + public void moveColumn(int index, boolean up) { + this.columns.moveItem(index, up); + } + + /** + * Gets the columns. + * + * @return the columns + */ + public OLAPObjectList getColumns() { + return this.columns; + } + + /** + * Sets the checks for oid. + * + * @param hasOidColumn the new checks for oid + */ + public void setHasOid(boolean hasOidColumn) { + this.hasOidCol = hasOidColumn; + } + + /** + * Sets the tablespace name. + * + * @param tablespaceName the new tablespace name + */ + public void setTablespaceName(String tablespaceName) { + this.tablespaceName = tablespaceName; + } + + /** + * Sets the temp table. + * + * @param isTempTble the new temp table + */ + public void setTempTable(boolean isTempTble) { + this.isTempTable = isTempTble; + } + + /** + * Checks if is un logged table. + * + * @return true, if is un logged table + */ + public boolean isUnLoggedTable() { + return isUnLoggedTable; + } + + /** + * Sets the un logged table. + * + * @param isUnLoggedTble the new un logged table + */ + public void setUnLoggedTable(boolean isUnLoggedTble) { + this.isUnLoggedTable = isUnLoggedTble; + } + + /** + * Sets the description. + * + * @param desc the new description + */ + public void setDescription(String desc) { + this.description = desc; + } + + /** + * Gets the description. + * + * @return the description + */ + public String getDescription() { + return this.description; + } + + /** + * Sets the if exists. + * + * @param isIfNtExtists the new if exists + */ + public void setIfExists(boolean isIfNtExtists) { + this.isIfNotExtists = isIfNtExtists; + } + + /** + * Gets the orientation. + * + * @return the orientation + */ + public TableOrientation getOrientation() { + return this.tabOrientation; + } + + /** + * Sets the orientation. + * + * @param orientation the new orientation + */ + public void setOrientation(TableOrientation orientation) { + this.tabOrientation = orientation; + } + + /** + * Gets the display name. + * + * @return the display name + */ + public String getDisplayName() { + return getNamespace().getDisplayName() + '.' + super.getDisplayName(); + } + + /** + * Gets the bottombar display name. + * + * @return the bottombar display name + */ + public String getBottombarDisplayName() { + return getNamespace().getName() + '.' + super.getName(); + } + + @Override + public String getSearchName() { + return getName() + " - " + getNamespace().getName() + " - " + getTypeLabel(); + } + + /** + * Form create query. + * + * @return the string + */ + public String formCreateQuery() { + StringBuffer query = new StringBuffer(512); + + /* CREATE */ + query.append("CREATE "); + + /* + * [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT + * EXISTS ] + */ + + addUnLoggedTable(query); + + query.append("TABLE "); + + addIfNotExists(query); + + query.append(this.nameSpace.getQualifiedObjectName()); + + query.append('.'); + query.append(ServerObject.getQualifiedObjectName(getName())); + + query.append("(").append(MPPDBIDEConstants.LINE_SEPARATOR).append("\t"); + + appendColumns(query); + + addConstraintsList(query); + + fillWithSection(query); + + /* [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] */ + + addTablespace(query); + + addDistributionType(query); + + addNodeOptions(query); + + query.append(';'); + + return query.toString(); + } + + /** + * Adds the node options. + * + * @param query the query + */ + private void addNodeOptions(StringBuffer query) { + if (null != this.nodeOptions && !this.nodeOptions.isEmpty()) { + query.append(MPPDBIDEConstants.LINE_SEPARATOR); + query.append(ServerObject.getLiteralName(this.nodeOptions)); + } + } + + /** + * Adds the distribution type. + * + * @param query the query + */ + private void addDistributionType(StringBuffer query) { + if (null != this.distributeOptions && !this.distributeOptions.isEmpty()) { + query.append(MPPDBIDEConstants.LINE_SEPARATOR); + query.append("DISTRIBUTE BY "); + query.append(this.distributeOptions); + } + } + + /** + * Adds the tablespace. + * + * @param query the query + */ + private void addTablespace(StringBuffer query) { + if (null != this.tablespaceName) { + query.append(MPPDBIDEConstants.LINE_SEPARATOR); + query.append("TABLESPACE "); + query.append(ServerObject.getQualifiedObjectName(this.tablespaceName)); + } + } + + /** + * Adds the constraints list. + * + * @param query the query + */ + private void addConstraintsList(StringBuffer query) { + int index; + int size = this.constraintList.getSize(); + for (index = 0; index < size; index++) { + query.append(",").append(MPPDBIDEConstants.LINE_SEPARATOR).append("\t"); + query.append(this.constraintList.getItem(index).formConstraintString()); + } + + query.append(")"); + } + + /** + * Adds the if not exists. + * + * @param query the query + */ + private void addIfNotExists(StringBuffer query) { + if (this.isIfNotExtists) { + query.append("IF NOT EXISTS "); + } + } + + /** + * Adds the un logged table. + * + * @param query the query + */ + private void addUnLoggedTable(StringBuffer query) { + if (this.isUnLoggedTable) { + query.append("UNLOGGED "); + } + } + + /** + * Append columns. + * + * @param query the query + */ + private void appendColumns(StringBuffer query) { + int index = 1; + if (this.columns.getSize() > 0) { + query.append(this.columns.getItem(0).formColumnString(true)); + int size = this.columns.getSize(); + + for (; index < size; index++) { + query.append(",").append(MPPDBIDEConstants.LINE_SEPARATOR).append("\t"); + query.append(this.columns.getItem(index).formColumnString(true)); + } + } + } + + /** + * Form table comment query. + * + * @return the string + */ + public String formTableCommentQuery() { + StringBuffer buff = new StringBuffer(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + if ((null != this.description) && (this.description.length() > 0)) { + buff.append(MPPDBIDEConstants.LINE_SEPARATOR).append(this.formSetCommentQuery(true)); + } + return buff.toString(); + } + + @Override + public String getDDL(Database db) throws MPPDBIDEException { + StringBuilder strbldr = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + DBConnection conn = getConnForFetchingDDL(db); + fetchDDL(db, conn); + strbldr.append(getSource()); + db.getConnectionManager().releaseConnection(conn); + return strbldr.toString(); + + } + + /** + * Fetch DDL. + * + * @param db the db + * @param conn TODO + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public void fetchDDL(Database db, DBConnection conn) throws MPPDBIDEException { + String fetchDDLQueryPrefix = "SELECT * FROM pg_get_tabledef"; + ExecTimer timer = new ExecTimer("fetch DDL from server"); + + ResultSet rs = null; + try { + timer.start(); + rs = conn.execSelectAndReturnRs(fetchDDLQueryPrefix + "('" + this.getDisplayName() + "')"); + timer.stopAndLogNoException(); + setDDLSourceCode(rs); + } catch (SQLException sqlException) { + GaussUtils.handleCriticalException(sqlException); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, sqlException); + } finally { + conn.closeResultSet(rs); + MPPDBIDELoggerUtility.debug("fetch DDL done"); + } + } + + private void setDDLSourceCode(ResultSet rs) throws SQLException { + /* + * we do not assume how many rows DDL query result will contain. We + * concatenate 1st column texts for all the result rows and show as the + * DDL + */ + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + while (rs.next()) { + sb.append(rs.getString(1)); + } + this.setSource(sb.toString()); + } + + private DBConnection getConnForFetchingDDL(Database db) throws DatabaseOperationException { + DBConnection conn = null; + try { + conn = db.getConnectionManager().getFreeConnection(); + } catch (MPPDBIDEException exception) { + MPPDBIDELoggerUtility.error("error getting free connection", exception); + throw new DatabaseOperationException(IMessagesConstants.CONNECTION_ERR); + } + return conn; + } + + /** + * Constructs "WITH" section of create table query. + * + * @param query the query + */ + private void fillWithSection(StringBuffer query) { + + if (validateFillFactor()) { + return; + } + + query.append(MPPDBIDEConstants.LINE_SEPARATOR).append("WITH ("); + boolean commaRequired = false; + + commaRequired = addFillFactorIfNotDefaultValue(query); + + commaRequired = addOids(query, commaRequired); + + addForTableOrientation(query, commaRequired); + + query.append(")"); + } + + /** + * Adds the for table orientation. + * + * @param query the query + * @param commaRequired the comma required + */ + private void addForTableOrientation(StringBuffer query, boolean commaRequired) { + if (this.tabOrientation == TableOrientation.COLUMN) { + addComma(query, commaRequired); + + query.append("orientation = column"); + } + } + + /** + * Adds the comma. + * + * @param query the query + * @param commaRequired the comma required + */ + private void addComma(StringBuffer query, boolean commaRequired) { + if (commaRequired) { + query.append(", "); + } + } + + /** + * Adds the oids. + * + * @param query the query + * @param commaRequired the comma required + * @return true, if successful + */ + private boolean addOids(StringBuffer query, boolean commaRequiredParam) { + boolean commaRequired = commaRequiredParam; + if (this.hasOidCol) { + addComma(query, commaRequired); + + query.append("OIDS=TRUE"); + commaRequired = true; + } + return commaRequired; + } + + /** + * Adds the fill factor if not default value. + * + * @param query the query + * @return true, if successful + */ + private boolean addFillFactorIfNotDefaultValue(StringBuffer query) { + boolean commaRequired = false; + if (this.fillfactor != 100) { + query.append("fillfactor=").append(this.fillfactor); + commaRequired = true; + } + return commaRequired; + } + + /** + * Validate fill factor. + * + * @return true, if successful + */ + private boolean validateFillFactor() { + return this.fillfactor == 100 && !this.hasOidCol && isDefaultOrientation(); + } + + /** + * Checks if is default orientation. + * + * @return true, if is default orientation + */ + private boolean isDefaultOrientation() { + return this.tabOrientation == TableOrientation.UNKNOWN || this.tabOrientation == TableOrientation.ROW; + } + + /** + * Form index queries. + * + * @return the string + */ + public String formIndexQueries() { + StringBuilder query = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + int size = this.indexList.getSize(); + + for (int i = 0; i < size; i++) { + query.append(MPPDBIDEConstants.LINE_SEPARATOR); + query.append(this.indexList.getItem(i).formCreateQuery(true)); + } + return query.toString(); + } + + /** + * Convert to table metadata. + * + * @param rs the rs + * @param ns the ns + * @return the table meta data + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public static TableMetaData convertToTableMetadata(ResultSet rs, Namespace ns) + throws DatabaseOperationException, DatabaseCriticalException { + TableMetaData table = null; + + table = new TableMetaData(ns); + table.populateTableMetaData(rs); + table.setLoaded(false); + ns.addTableToSearchPool(table); + + return table; + } + + /** + * Convert to table metadata on demand. + * + * @param rs the rs + * @param db the db + * @return the table meta data + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public static TableMetaData convertToTableMetadataOnDemand(ResultSet rs, Database db) + throws DatabaseOperationException, DatabaseCriticalException { + TableMetaData table = null; + int namespaceOid = 0; + Namespace ns = null; + + try { + namespaceOid = rs.getInt("relnamespace"); + ns = db.getNameSpaceById(namespaceOid); + + table = addTableByType(rs, ns); + if (null != table) { + table.setName(rs.getString("relname")); + table.setOid(rs.getInt("oid")); + } + } catch (SQLException sqlException) { + GaussUtils.handleCriticalException(sqlException); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, sqlException); + } + return table; + } + + /** + * Adds the table by type. + * + * @param rs the rs + * @param ns the ns + * @return the table meta data + * @throws SQLException the SQL exception + */ + private static TableMetaData addTableByType(ResultSet rs, Namespace ns) throws SQLException { + TableMetaData table = null; + String relkind = null; + String parttype = null; + relkind = rs.getString("relkind"); + parttype = rs.getString("parttype"); + if ("r".equals(relkind)) { + table = validateForTableType(ns, parttype); + } else if ("f".equals(relkind)) { + table = addForeignTable(rs, ns, parttype); + } + return table; + } + + /** + * Adds the foreign table. + * + * @param rs the rs + * @param ns the ns + * @param parttype the parttype + * @return the table meta data + * @throws SQLException the SQL exception + */ + private static TableMetaData addForeignTable(ResultSet rs, Namespace ns, String parttype) throws SQLException { + TableMetaData table = null; + if (!("n".equals(parttype))) { + table = new ForeignPartitionTable(ns); + } else { + table = addForeignTableType(rs, ns); + } + return table; + } + + /** + * Adds the foreign table type. + * + * @param rs the rs + * @param ns the ns + * @return the table meta data + * @throws SQLException the SQL exception + */ + private static TableMetaData addForeignTableType(ResultSet rs, Namespace ns) throws SQLException { + TableMetaData table = null; + String ftOptions = rs.getString("ftoptions"); + if (ftOptions.contains("gsfs")) { + table = new ForeignTable(ns, OBJECTTYPE.FOREIGN_TABLE_GDS); + } else if (ftOptions.contains("format=orc")) { + table = new ForeignTable(ns, OBJECTTYPE.FOREIGN_TABLE_HDFS); + } + ForeignTable.getForeignErrorTable(ftOptions, ns); + return table; + } + + /** + * Validate for table type. + * + * @param ns the ns + * @param parttype the parttype + * @return the table meta data + */ + private static TableMetaData validateForTableType(Namespace ns, String parttype) { + TableMetaData table; + if ("n".equals(parttype)) { + table = new TableMetaData(ns); + } else { + table = new PartitionTable(ns); + } + return table; + } + + /** + * Populate table meta data. + * + * @param rs the rs + * @return the table meta data + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public TableMetaData populateTableMetaData(ResultSet rs) + throws DatabaseOperationException, DatabaseCriticalException { + this.fillTablePropertiesFromRS(rs); + return this; + } + + /** + * FillTablePropertiesFromRS - Reads the basic table details from the result + * set. this method is forbidden to call getNext(), as it is controlled by + * the caller + * + * @param reloptions the reloptions + * @return the table orientation + * @throws SQLException the SQL exception + */ + + private static TableOrientation readOrientation(Array reloptions) throws SQLException { + if (null == reloptions) { + return TableOrientation.ROW; + } + + String[] options = (String[]) reloptions.getArray(); + if (options.length > 0) { + return addTableOrientation(options[0]); + } + return TableOrientation.UNKNOWN; + } + + /** + * Adds the table orientation. + * + * @param opt the opt + * @return the table orientation + */ + private static TableOrientation addTableOrientation(String opt) { + if (opt.contains("orientation=column")) { + return TableOrientation.COLUMN; + } else if (opt.contains("orientation=row")) { + return TableOrientation.ROW; + } + return TableOrientation.UNKNOWN; + } + + /** + * FillTablePropertiesFromRS - Reads the basic table details from the result + * set. this method is forbidden to call getNext(), as it is controlled by + * the caller + * + * @param rs - contains the query result (current row) + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + protected void fillTablePropertiesFromRS(ResultSet rs) + throws DatabaseOperationException, DatabaseCriticalException { + + try { + this.setName(rs.getString("relname")); + this.setOid(rs.getInt("oid")); + this.setOrientation(readOrientation(rs.getArray("reloptions"))); + + setTablePersistence(rs); + + } catch (SQLException sqlException) { + GaussUtils.handleCriticalException(sqlException); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, sqlException); + } + + } + + private void setTablePersistence(ResultSet rs) throws SQLException { + String persistence; + persistence = rs.getString("relpersistence"); + if ("t".equals(persistence) || "g".equals(persistence)) { + this.setTempTable(true); + } else if ("u".equals(persistence)) { + this.setUnLoggedTable(true); + } + } + + /** + * Adds the constraint. + * + * @param cons the cons + */ + public void addConstraint(ConstraintMetaData cons) { + constraintList.addItem(cons); + } + + /** + * Gets the namespace. + * + * @return the namespace + */ + public Namespace getNamespace() { + return this.nameSpace; + } + + /** + * Gets the tablespace name. + * + * @return the tablespace name + */ + public String getTablespaceName() { + return this.tablespaceName; + } + + /** + * Removes the constraint. + * + * @param selected the selected + */ + public void removeConstraint(int selected) { + constraintList.removeItemByIdx(selected); + } + + /** + * Adds the index. + * + * @param index the index + */ + public void addIndex(IndexMetaData index) { + indexList.addItem(index); + } + + /** + * Removes the index. + * + * @param pos the pos + */ + public void removeIndex(int pos) { + indexList.removeItemByIdx(pos); + } + + /** + * Gets the constraints. + * + * @return the constraints + */ + public OLAPObjectList getConstraints() { + return this.constraintList; + } + + /** + * Gets the indexes. + * + * @return the indexes + */ + public IndexList getIndexes() { + return this.indexList; + } + + /** + * Gets the index array list. + * + * @return the index array list + */ + public ArrayList getIndexArrayList() { + return this.indexList.getList(); + } + + /** + * Exec rename. + * + * @param newName the new name + * @param dbConnection the db connection + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void execRename(String newName, DBConnection dbConnection) + throws DatabaseCriticalException, DatabaseOperationException { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("ALTER TABLE "); + sb.append(getDisplayName()); + sb.append(" RENAME TO "); + sb.append(ServerObject.getQualifiedObjectName(newName)); + + dbConnection.execNonSelect(sb.toString()); + this.nameSpace.refreshTable(this, dbConnection, true); + } + + /** + * Exec create. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void execCreate(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + StringBuilder buff = new StringBuilder(formCreateQuery()); + + buff.append(formTableCommentQuery()); + buff.append(formColumnCommentQuery()); + int indexSize = 0; + conn.execNonSelect(buff.toString()); + try { + indexSize = this.indexList.getSize(); + + for (int i = 0; i < indexSize; i++) { + conn.execNonSelect(this.indexList.getItem(i).formCreateQuery(true)); + } + } catch (DatabaseOperationException dbOperationException) { + rollbackTableCreate(indexSize, conn); + throw dbOperationException; + } + getNamespace().getNewlyCreatedTable(getName()); + } + + /** + * Rollback table create. + * + * @param indexSize the index size + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + */ + public void rollbackTableCreate(int indexSize, DBConnection conn) throws DatabaseCriticalException { + isRollBack = true; + try { + for (int i = 0; i < indexSize; i++) { + conn.execNonSelect(this.indexList.getItem(i).formDropQuery(true)); + } + execDrop(conn); + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error(" Nothing to do, skip", exception); + } + } + + /** + * Exec drop. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void execDrop(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + String dropQry = String.format(Locale.ENGLISH, "DROP TABLE %s;", this.getDisplayName()); + conn.execNonSelect(dropQry); + this.nameSpace.refreshTableHirarchy(conn); + + if (isRollBack) { + isRollBack = false; + } + } + + /** + * Exec vacumm. + * + * @param dbConnection the db connection + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void execVacumm(DBConnection dbConnection) throws DatabaseCriticalException, DatabaseOperationException { + String qry = String.format(Locale.ENGLISH, "VACUUM %s;", this.getDisplayName()); + dbConnection.execNonSelect(qry); + } + + /** + * Exec analyze. + * + * @param dbConnection the db connection + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void execAnalyze(DBConnection dbConnection) throws DatabaseCriticalException, DatabaseOperationException { + String qry = String.format(Locale.ENGLISH, "ANALYZE %s;", this.getDisplayName()); + dbConnection.execNonSelect(qry); + } + + /** + * Exec reindex. + * + * @param dbConnection the db connection + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void execReindex(DBConnection dbConnection) throws DatabaseCriticalException, DatabaseOperationException { + String qry = String.format(Locale.ENGLISH, "REINDEX TABLE %s;", this.getDisplayName()); + dbConnection.execNonSelectForTimeout(qry); + } + + /** + * Exec truncate. + * + * @param dbConnection the db connection + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void execTruncate(DBConnection dbConnection) throws DatabaseCriticalException, DatabaseOperationException { + String qry = null; + qry = String.format(Locale.ENGLISH, "TRUNCATE TABLE ONLY %s;", this.getDisplayName()); + dbConnection.execNonSelectForTimeout(qry); + } + + /** + * Exec set table space. + * + * @param newTableSpace the new table space + * @param dbConnection the db connection + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void execSetTableSpace(String newTableSpace, DBConnection dbConnection) + throws DatabaseCriticalException, DatabaseOperationException { + String qry = String.format(Locale.ENGLISH, "ALTER TABLE ONLY %s SET TABLESPACE %s", this.getDisplayName(), + getQualifiedObjectName(newTableSpace)); + dbConnection.execNonSelectForTimeout(qry); + } + + /** + * Form set comment query. + * + * @param isCreateTable the is create table + * @return the string + */ + public String formSetCommentQuery(boolean isCreateTable) { + + StringBuilder commentQry = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + commentQry.append("COMMENT ON TABLE "); + commentQry.append(this.getQualifiedName()); + commentQry.append(" IS "); + commentQry.append(null == this.description ? "NULL" : ServerObject.getLiteralName(this.description)); + commentQry.append(";"); + return commentQry.toString(); + + } + + /** + * Exec set table description. + * + * @param newTableDescription the new table description + * @param dbConnection the db connection + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void execSetTableDescription(String newTableDescription, DBConnection dbConnection) + throws DatabaseCriticalException, DatabaseOperationException { + this.description = newTableDescription; + dbConnection.execNonSelect(this.formSetCommentQuery(false)); + } + + /** + * Exec set schema. + * + * @param newSchemaName the new schema name + * @param dbConnection the db connection + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void execSetSchema(String newSchemaName, DBConnection dbConnection) + throws DatabaseCriticalException, DatabaseOperationException { + String qry = String.format(Locale.ENGLISH, "ALTER TABLE ONLY %s SET SCHEMA %s", this.getDisplayName(), + ServerObject.getQualifiedObjectName(newSchemaName)); + dbConnection.execNonSelectForTimeout(qry); + } + + /** + * Exec create index. + * + * @param index the index + * @param dbConnection the db connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void execCreateIndex(IndexMetaData index, DBConnection dbConnection) + throws DatabaseOperationException, DatabaseCriticalException { + String qry = index.formCreateQuery(false); + dbConnection.execNonSelectForTimeout(qry); + } + + /** + * Refresh. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void refresh(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + this.nameSpace.refreshTable(this, conn, false); + } + + @Override + public int hashCode() { + return MPPDBIDEConstants.PRIME_31 + Long.valueOf(getOid()).hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + + if (obj == null) { + return false; + } + + if (!(obj instanceof TableMetaData)) { + return false; + } + + TableMetaData other = (TableMetaData) obj; + if (validateTable(other)) { + return true; + } + return false; + } + + private boolean validateTable(TableMetaData other) { + return getOid() == other.getOid() && getNamespace().equals(other.getNamespace()); + } + + /** + * Checks if is level 3 loaded. + * + * @return true, if is level 3 loaded + */ + public boolean isLevel3Loaded() { + return isLevel3Loaded; + } + + /** + * Sets the level 3 loaded. + * + * @param isLvl3Loaded the new level 3 loaded + */ + public void setLevel3Loaded(boolean isLvl3Loaded) { + this.isLevel3Loaded = isLvl3Loaded; + } + + /** + * Checks if is level 3 load in progress. + * + * @return true, if is level 3 load in progress + */ + public boolean isLevel3LoadInProgress() { + return isLevel3LoadInProgress; + } + + /** + * Sets the level 3 load in progress. + * + * @param isLvl3LoadInProgress the new level 3 load in progress + */ + public void setLevel3LoadInProgress(boolean isLvl3LoadInProgress) { + this.isLevel3LoadInProgress = isLvl3LoadInProgress; + } + + /** + * Find matching child objects. + * + * @param prefix the prefix + * @return the sorted map + */ + public SortedMap findMatchingChildObjects(String prefix) { + return columns.findMatching(prefix); + } + + /** + * Gets the qualified name. + * + * @return the qualified name + */ + public String getQualifiedName() { + return this.getNamespace().getQualifiedObjectName() + '.' + this.getQualifiedObjectName(); + } + + /** + * Gets the server name. + * + * @return the server name + */ + public String getServerName() { + if (nameSpace == null) { + return ""; + } + return nameSpace.getServerName(); + } + + /** + * Gets the database name. + * + * @return the database name + */ + public String getDatabaseName() { + if (nameSpace == null) { + return ""; + } + return nameSpace.getDatabaseName(); + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + return nameSpace.getDatabase(); + } + + /** + * Convert to column meta data. + * + * @param rs the rs + * @param type the type + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws SQLException the SQL exception + */ + public void convertToColumnMetaData(ResultSet rs, TypeMetaData type) + throws DatabaseCriticalException, DatabaseOperationException, SQLException { + if (isLevel3Loaded()) { + return; + } + ColumnMetaData col = ColumnUtil.convertToColumnMetaData(rs, type, this, getDatabase()); + getColumns().addItem(col); + + } + + /** + * Removes the column by idx. + * + * @param editIndex the edit index + */ + public void removeColumnByIdx(int editIndex) { + this.getColumns().removeItemByIdx(editIndex); + } + + /** + * Adds the column at index. + * + * @param newTempColumn the new temp column + * @param editIndex the edit index + */ + public void addColumnAtIndex(ColumnMetaData newTempColumn, int editIndex) { + this.getColumns().addItemAtIndex(newTempColumn, editIndex); + } + + /** + * Adds the column. + * + * @param newTempColumn the new temp column + */ + public void addColumn(ColumnMetaData newTempColumn) { + this.getColumns().addItem(newTempColumn); + + } + + /** + * Gets the column meta data list. + * + * @return the column meta data list + */ + public List getColumnMetaDataList() { + return this.getColumns().getList(); + } + + /** + * Gets the constraint meta data list. + * + * @return the constraint meta data list + */ + public List getConstraintMetaDataList() { + return this.getConstraints().getList(); + } + + /** + * Gets the index meta data list. + * + * @return the index meta data list + */ + public List getIndexMetaDataList() { + return this.getIndexes().getList(); + } + + /** + * Adds the constraint. + * + * @param rs the rs + * @param namespaceOfConstraint the namespace of constraint + * @param fkeyTable the fkey table + * @throws SQLException the SQL exception + */ + public void addConstraint(ResultSet rs, Namespace namespaceOfConstraint, TableMetaData fkeyTable) + throws SQLException { + ConstraintMetaData constraint = null; + + long indexId = rs.getLong("indexid"); + + Iterator indexItr = getIndexArrayList().iterator(); + boolean hasNext = indexItr.hasNext(); + IndexMetaData idx = null; + IndexMetaData idxUsable = null; + while (hasNext) { + idx = indexItr.next(); + if (idx.getOid() == indexId) { + idxUsable = idx; + break; + } + + hasNext = indexItr.hasNext(); + } + + constraint = ConstraintMetaDataUtils.convertToConstraint(rs, namespaceOfConstraint, this, fkeyTable, idxUsable); + addConstraint(constraint); + } + + /** + * Gets the server. + * + * @return the server + */ + public Server getServer() { + return getDatabase().getServer(); + } + + /** + * Clear details cached. + */ + public void clearDetailsCached() { + this.getColumns().clear(); + this.getConstraints().clear(); + this.getIndexes().clear(); + this.setLevel3Loaded(false); + } + + /** + * Adds the index. + * + * @param resultSet the result set + * @throws SQLException the SQL exception + */ + public void addIndex(ResultSet resultSet) throws SQLException { + IndexUtil.convertToIndex(resultSet, this, this.nameSpace, columns); + } + + /** + * Fetch index for table. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void fetchIndexForTable(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + String query = "SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, " + + "ci.relnamespace as namespaceid, " + + "ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, " + + "i.indisexclusion as isexclusion," + + " i.indimmediate as isimmediate, i.indisclustered as isclustered, " + + "i.indcheckxmin as checkmin, i.indisready as isready, " + + "i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions, " + + "def.indexdef , def.tablespace " + "FROM pg_index i" + + " LEFT JOIN pg_class t on (t.oid = i.indrelid) " + "LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) " + + "LEFT JOIN pg_namespace ns on (ci.relnamespace = ns.oid) " + + "LEFT JOIN pg_indexes def on (ci.relname = def.indexname and ns.nspname = def.schemaname)" + + " WHERE t.relkind = 'r' and t.oid = %d;"; + query = String.format(Locale.ENGLISH, query, getOid()); + + ResultSet rs = conn.execSelectAndReturnRs(query); + boolean hasNext = false; + + try { + hasNext = rs.next(); + while (hasNext) { + this.addIndex(rs); + hasNext = rs.next(); + } + } catch (SQLException exception) { + GaussUtils.handleCriticalException(exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + conn.closeResultSet(rs); + } + } + + /** + * Checks if is temp table. + * + * @return true, if is temp table + */ + public boolean isTempTable() { + return isTempTable; + } + + @Override + public Object[] getChildren() { + + Object[] objs = {this.getColumns(), this.getConstraints(), this.getIndexes()}; + return objs; + } + + /** + * Form query for table metadata. + * + * @param queryParam the query param + * @param tableFlag the table flag + * @param privilegeFlag the privilege flag + * @return the string + */ + public static String formQueryForTableMetadata(String queryParam, boolean tableFlag, boolean privilegeFlag) { + String query = queryParam; + if (!privilegeFlag) { + return query + ";"; + } + // this is false for view metadata + if (tableFlag) { + query += " and oid in (" + "select pcrelid from pgxc_class " + + "where has_nodegroup_privilege(pgroup, 'USAGE'))"; + } + // this is for both table and view + return "with x as (" + query + ") select * from x " + "where has_table_privilege(x.oid,'SELECT');"; + } + + /** + * Gets the SQL for table meta databy oid. + * + * @param oid the oid + * @param isRenameFlow the is rename flow + * @return the SQL for table meta databy oid + */ + public String getSQLForTableMetaDatabyOid(long oid, boolean isRenameFlow) { + String query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, " + + "ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, " + + "xctbl.nodeoids as nodes ,tbl.reloptions as reloptions " + + "from pg_class tbl left join (select d.description, d.objoid from pg_description d " + + "where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl " + + "on (tbl.oid = xctbl.pcrelid) " + "left join pg_tablespace ts on ts.oid = tbl.reltablespace " + + "where tbl.relkind = 'r' and " + "tbl.parttype in ('n','p') and tbl.oid = %d"; + query = String.format(Locale.ENGLISH, query, oid); + String qry = TableMetaData.formQueryForTableMetadata(query, + this.getServer().isServerCompatibleToNodeGroupPrivilege(), privilegeFlag && !isRenameFlow); + + return qry; + } + + /** + * Fill table meta from RS. + * + * @param rs the rs + * @return the table meta data + * @throws SQLException the SQL exception + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public TableMetaData fillTableMetaFromRS(ResultSet rs) + throws SQLException, DatabaseOperationException, DatabaseCriticalException { + return populateTableMetaData(rs); + } + + /** + * Refresh table details. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void refreshTableDetails(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + clearDetailsCached(); + this.getNamespace().fetchTableColumnMetaData(this.getOid(), this.getNamespace().getTables(), conn); + this.getNamespace().fetchConstraintForTable(this, this.getNamespace().getTables(), conn); + this.fetchIndexForTable(conn); + this.setLevel3Loaded(true); + this.setLoaded(true); + } + + /** + * Checks if is loaded. + * + * @return true, if is loaded + */ + public boolean isLoaded() { + return super.getLoaded(); + } + + /** + * Sets the name space. + * + * @param ns the new name space + */ + public void setTableNamespace(Namespace ns) { + this.nameSpace = ns; + this.privilegeFlag = ns.getPrivilegeFlag(); + } + + @Override + public Object getParent() { + return this.nameSpace; + } + + /** + * Find all child objects. + * + * @return the sorted map + */ + public SortedMap findAllChildObjects() { + return findMatchingChildObjects(""); + } + + /** + * Validate orientation. + * + * @param orientation the orientation + * @return true, if successful + */ + public boolean validateOrientation(TableOrientation orientation) { + if (getOrientation() == orientation) { + return true; + } + return false; + } + + /** + * isRowTableOrientation + * + * @return boolean value + */ + public boolean isRowTableOrientation() { + return validateOrientation(TableOrientation.ROW); + } + + /** + * Fetch distribution column list. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void fetchDistributionColumnList(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + String getDistributedKey = "select CASE pclocatortype WHEN 'R' THEN 'REPLICATION' WHEN 'H' THEN 'HASH' END as distriute_type, " + + "getdistributekey(%d) as distributekey" + + " from pgxc_class, (SELECT count(*) AS dn_cn FROM pg_catalog.pgxc_node WHERE node_type = 'D') " + + "as nc where pcrelid = %d"; + List distList = new ArrayList(); + String query = String.format(Locale.ENGLISH, getDistributedKey, this.getOid(), this.getOid()); + ResultSet rs = conn.execSelectAndReturnRs(query); + String distriuteType = null; + String distributeClms = null; + try { + boolean hasnext = rs.next(); + if (hasnext) { + distriuteType = rs.getString("distriute_type"); + distributeClms = rs.getString("distributekey"); + addDistribution(distList, distriuteType, distributeClms); + addNewDistribution(distList); + } + } catch (SQLException exception) { + GaussUtils.handleCriticalException(exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + conn.closeResultSet(rs); + } + } + + /** + * Adds the new distribution. + * + * @param distList the dist list + */ + private void addNewDistribution(List distList) { + if (distList.size() > 0) { + distributionClmList.clear(); + distributionClmList = distList; + } + } + + /** + * Adds the distribution. + * + * @param distList the dist list + * @param distriuteType the distriute type + * @param distributeClms the distribute clms + */ + private void addDistribution(List distList, String distriuteType, String distributeClms) { + StringTokenizer token; + if (!"REPLICATION".equals(distriuteType)) { + token = new StringTokenizer(distributeClms, ","); + while (token.hasMoreElements()) { + String object = (String) token.nextElement(); + + addColumnToDistributionList(distList, object); + } + } + } + + /** + * Adds the column to distribution list. + * + * @param distList the dist list + * @param object the object + */ + private void addColumnToDistributionList(List distList, String object) { + for (ColumnMetaData clm : getColumnMetaDataList()) { + if (clm.getName().equals(object.trim())) { + clm.setDistributionColm(true); + distList.add(object); + break; + } + } + } + + /** + * Gets the distribution column list. + * + * @return the distribution column list + */ + public List getDistributionColumnList() { + return distributionClmList; + } + + /** + * Gets the orc version. + * + * @return the orc version + */ + public String getOrcVersion() { + return orcVersion; + } + + /** + * Sets the orc version. + * + * @param orcVersion the new orc version + */ + public void setOrcVersion(String orcVersion) { + this.orcVersion = orcVersion; + } + + /** + * Checks if is table dropped. + * + * @return true, if is table dropped + */ + public boolean isTableDropped() { + Namespace ns = getNamespace(); + if (null == ns) { + return true; + } + + TableObjectGroup group = ns.getTables(); + return null == group || null == group.getObjectById(getOid()); + } + + /** + * Checks if is distribution column. + * + * @param columnIndex the column index + * @return true, if is distribution column + */ + public boolean isDistributionColumn(int columnIndex) { + return getColumnMetaDataList().get(columnIndex).isDistributionColm(); + } + + /** + * Adds the foreign table to group. + * + * @param table the table + */ + public void addForeignTableToGroup(TableMetaData table) { + nameSpace.addForeignTableToGroup(table); + } + + /** + * Adds the table to group. + * + * @param table the table + */ + public void addTableToGroup(TableMetaData table) { + nameSpace.addTableToGroup(table); + } + + @Override + public String getDropQuery(boolean isCascade) { + String dropQuery = "DROP TABLE IF EXISTS "; + StringBuilder query = new StringBuilder(dropQuery); + query.append(this.getDisplayName()); + + if (isCascade) { + query.append(MPPDBIDEConstants.CASCADE); + } + + return query.toString(); + } + + /** + * Removes the. + * + * @param obj the obj + */ + public void remove(ServerObject obj) { + if (obj instanceof ColumnMetaData) { + removeColumns(obj); + } else if (obj instanceof ConstraintMetaData) { + removeConstraints(obj); + } else if (obj instanceof IndexMetaData) { + removeTableIndex(obj); + } + } + + /** + * Removes the table index. + * + * @param obj the obj + */ + private void removeTableIndex(ServerObject obj) { + if (indexList != null) { + indexList.remove((IndexMetaData) obj); + } + } + + /** + * Removes the constraints. + * + * @param obj the obj + */ + private void removeConstraints(ServerObject obj) { + if (constraintList != null) { + constraintList.remove((ConstraintMetaData) obj); + } + } + + /** + * Removes the columns. + * + * @param obj the obj + */ + private void removeColumns(ServerObject obj) { + if (columns != null) { + columns.remove((ColumnMetaData) obj); + } + } + + @Override + public boolean isExportAllowed(EXPORTTYPE exportType) { + return true; + } + + @Override + public String getNameSpaceName() { + return getNamespace().getName(); + } + + @Override + public boolean isDropped() { + return isTableDropped(); + } + + /** + * Form column comment query. + * + * @return the string + * @Title: formColumnCommentQuery + * @Description: generate comment statement for column + */ + public String formColumnCommentQuery() { + StringBuilder query = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + int size = this.columns.getSize(); + for (int i = 0; i < size; i++) { + String colDescription = this.columns.getItem(i).getColDescription(); + appendCommentQuery(query, i, colDescription); + } + return query.toString(); + } + + private void appendCommentQuery(StringBuilder query, int i, String colDescription) { + if (validateClmDescription(colDescription)) { + query.append(MPPDBIDEConstants.LINE_SEPARATOR); + query.append(this.columns.getItem(i).formSetCommentQuery()); + } + } + + private boolean validateClmDescription(String colDescription) { + return null != colDescription && !"".equals(colDescription); + } + + /** + * getTablespaceForTable method + * + * @param conn connection + * @return string string + * @throws DatabaseCriticalException exception + * @throws DatabaseOperationException exception + */ + public String getTablespaceForTable(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + String query = String.format(Locale.ENGLISH, + "select spcname from pg_class as class left join pg_tablespace as tablespace" + + " on class.reltablespace=tablespace.oid where class.oid=%d", + this.getOid()); + ResultSet rs = null; + String tblspaceName = ""; + try { + if (conn == null) { + conn = getConnForFetchingDDL(this.getDatabase()); + } + rs = conn.execSelectAndReturnRs(query); + while (rs.next()) { + tblspaceName = rs.getString("spcname"); + } + } catch (SQLException sqlException) { + GaussUtils.handleCriticalException(sqlException); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, sqlException); + } finally { + if (conn != null) { + conn.closeResultSet(rs); + } + MPPDBIDELoggerUtility.debug("fetch DDL done"); + } + return tblspaceName; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TableOrientation.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TableOrientation.java new file mode 100644 index 0000000000000000000000000000000000000000..06528aa076fc8fb40d617a1637bf9dab51b83fd9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TableOrientation.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: enum + * + * Description: The Enum TableOrientation. + * + */ + +public enum TableOrientation { + ROW, COLUMN, UNKNOWN +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TableValidatorRules.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TableValidatorRules.java new file mode 100644 index 0000000000000000000000000000000000000000..e5f39591fd8dfa28b1293fe492bc40cda62af6a8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TableValidatorRules.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.util.ArrayList; +import java.util.Iterator; + +/** + * + * Title: class + * + * Description: The Class TableValidatorRules. + * + */ + +public final class TableValidatorRules { + + private TableMetaData selTable; + + // : List needs to be updated as and when new pseudo types are added. + // To get the list of pseudo-types run the following query + // select * from pg_type where typtype = 'p'; + private static ArrayList pseudoTypes = new ArrayList(20); + + static { + pseudoTypes.add("any"); + pseudoTypes.add("anyelement"); + pseudoTypes.add("anyarray"); + pseudoTypes.add("anynonarray"); + pseudoTypes.add("anyenum"); + pseudoTypes.add("anyrange"); + pseudoTypes.add("cstring"); + pseudoTypes.add("internal"); + pseudoTypes.add("language_handler"); + pseudoTypes.add("fdw_handler"); + pseudoTypes.add("record"); + pseudoTypes.add("_record"); + pseudoTypes.add("trigger"); + pseudoTypes.add("void"); + pseudoTypes.add("opaque"); + } + + /** + * Instantiates a new table validator rules. + * + * @param tableMetaData the table meta data + */ + public TableValidatorRules(TableMetaData tableMetaData) { + this.selTable = tableMetaData; + } + + /** + * Enable disable. + * + * @return true, if successful + */ + public boolean enableDisable() { + if (null != selTable.getOrientation()) { + + if (selTable.getOrientation() == TableOrientation.ROW) { + return true; + } + + } + return false; + } + + /** + * Gets the data type list. + * + * @param db the db + * @param column the column + * @return the data type list + */ + public ArrayList getDataTypeList(Database db, boolean column) { + ArrayList types = null; + + types = db.getDefaultDatatype().getList(); + + // remove pseudo types when listing data types for column + if (column) { + Iterator objectIter = types.iterator(); + + TypeMetaData typename = null; + boolean hasMore = objectIter.hasNext(); + String name = null; + + while (hasMore) { + typename = objectIter.next(); + name = typename.getName(); + + if (pseudoTypes.contains(name)) { + objectIter.remove(); + } + + hasMore = objectIter.hasNext(); + } + } + + return types; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/Tablespace.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/Tablespace.java new file mode 100644 index 0000000000000000000000000000000000000000..b9e06dd4c38a4ce645f05232ec631479d49c24e0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/Tablespace.java @@ -0,0 +1,405 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.Array; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ObjectGroup; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class Tablespace. + * + */ + +public class Tablespace extends ServerObject implements GaussOLAPDBMSObject { + + private Server server; + + /** + * Gets the server. + * + * @return the server + */ + public Server getServer() { + return server; + } + + private String[] fileOption; + private String location; + private String maxsize; + private TablespaceType tspctype; + private boolean privilege; + private boolean isRelative; + + /** + * Instantiates a new tablespace. + * + * @param oid the oid + * @param name the name + * @param location the location + * @param maxsize the maxsize + * @param options the options + * @param server the server + * @param tspctype the tspctype + * @param privilege the privilege + * @param isRelative the is relative + */ + public Tablespace(long oid, String name, String location, String maxsize, String[] options, Server server, + TablespaceType tspctype, boolean privilege, boolean isRelative) { + super(oid, name, OBJECTTYPE.TABLESPACE, server.getPrivilegeFlag()); + this.setFileOption(options); + this.server = server; + this.location = location; + this.maxsize = maxsize; + this.tspctype = tspctype; + this.privilege = privilege; + this.isRelative = isRelative; + } + + @Override + public Object getParent() { + return this.getServer(); + } + + /** + * Convert to tablesapce. + * + * @param rs the rs + * @param server the server + * @param privilege the privilege + * @return the tablespace + * @throws DatabaseOperationException the database operation exception + */ + public static Tablespace convertToTablesapce(ResultSet rs, Server server, boolean privilege) + throws DatabaseOperationException { + long oid = 0; + String name = null; + String location = null; + String[] options = null; + String maxsize = null; + TablespaceType tspctype = TablespaceType.NORMAL; + try { + oid = rs.getLong("oid"); + name = rs.getString("spcname"); + Array spcOptions = rs.getArray("spcoptions"); + if (spcOptions != null) { + options = (String[]) spcOptions.getArray(); + if (options.length > 0 && "filesystem=hdfs".equalsIgnoreCase(options[0])) { + tspctype = TablespaceType.HDFS; + } + } else { + options = new String[0]; + } + if (privilege) { + location = rs.getString("location"); + } + boolean isRelative = false; + maxsize = rs.getString("spcmaxsize"); + isRelative = rs.getBoolean("relative"); + Tablespace tablespace = new Tablespace(oid, name, location, maxsize, options, server, tspctype, privilege, + isRelative); + return tablespace; + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } + + } + + /** + * Gets the file option. + * + * @return the file option + */ + public String getFileOption() { + int len = fileOption.length; + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + String[] tempStr = null; + String key = null; + for (int index = 0; index < len; index++) { + sb.append(','); + tempStr = fileOption[index].split("=", 2); + key = tempStr[0].trim(); + if ((key.startsWith("cfgpath") || key.startsWith("storepath") || key.startsWith("address")) + && tempStr.length > 1) { + sb.append(tempStr[0]).append('='); + sb.append(ServerObject.getLiteralName(tempStr[1])); + } else { + sb.append(fileOption[index]); + } + } + if (!sb.toString().isEmpty()) { + sb.deleteCharAt(0); + } + + return sb.toString(); + } + + /** + * Sets the file option. + * + * @param options the new file option + */ + private void setFileOption(String[] options) { + if (options != null) { + this.fileOption = options.clone(); + } + } + + /** + * Rename tablespace. + * + * @param newName the new name + * @param connection the connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void renameTablespace(String newName, DBConnection connection) + throws DatabaseOperationException, DatabaseCriticalException { + String qry = createRenameQuery(newName); + connection.execNonSelect(qry); + this.server.refreshTablespace(); + } + + /** + * Drop tablespace. + * + * @param connection the connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void dropTablespace(DBConnection connection) throws DatabaseOperationException, DatabaseCriticalException { + connection.execNonSelect(createDropQuery()); + this.server.refreshTablespace(); + } + + /** + * Sets the tablespace option. + * + * @param query the query + * @param connection the connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void setTablespaceOption(String query, DBConnection connection) + throws DatabaseOperationException, DatabaseCriticalException { + connection.execNonSelect(query); + this.server.refreshTablespace(); + } + + /** + * Sets the tablespace size. + * + * @param newsize the newsize + * @param connection the connection + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void setTablespaceSize(String newsize, DBConnection connection) + throws DatabaseOperationException, DatabaseCriticalException { + String qry = resizeQuery(newsize); + connection.execNonSelect(qry); + this.server.refreshTablespace(); + } + + /** + * Refresh. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws Exception the exception + */ + public void refresh() throws DatabaseCriticalException, DatabaseOperationException, Exception { + this.server.refreshTablespaceMetadata(this.getOid()); + } + + /** + * Gets the ddl. + * + * @return the ddl + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public String getDDL() throws DatabaseOperationException, DatabaseCriticalException { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + if (isRelative) { + sb.append("set enable_absolute_tablespace=off ;"); + } else { + sb.append("set enable_absolute_tablespace=on ;"); + } + sb.append("CREATE TABLESPACE "); + sb.append(this.getDisplayName()); + if (isRelative) { + sb.append(" RELATIVE"); + } + if (!"".equalsIgnoreCase(this.location) && null != this.location) { + sb.append(" LOCATION "); + sb.append(ServerObject.getLiteralName(this.location)); + } + if (null != this.maxsize && !"".equalsIgnoreCase(this.maxsize)) { + sb.append(" MAXSIZE "); + sb.append(ServerObject.getLiteralName(this.maxsize)); + } + if (!getFileOption().trim().isEmpty()) { + sb.append(" WITH "); + sb.append("( "); + sb.append(getFileOption()); + sb.append(" )"); + } + sb.append(" ;"); + return sb.toString(); + } + + /** + * get previlege + * + * @return privilege flag + */ + public boolean getPrivilege() { + return this.privilege; + } + + /** + * Creates the drop query. + * + * @return the string + */ + public String createDropQuery() { + String qry = String.format(Locale.ENGLISH, "DROP TABLESPACE IF EXISTS %s", super.getDisplayName()); + return qry; + } + + /** + * Creates the rename query. + * + * @param newName the new name + * @return the string + */ + public String createRenameQuery(String newName) { + String qry = String.format(Locale.ENGLISH, "ALTER TABLESPACE %s RENAME TO %s ;", super.getDisplayName(), + ServerObject.getQualifiedObjectName(newName)); + return qry; + } + + /** + * Resize query. + * + * @param newSize the new size + * @return the string + */ + public String resizeQuery(String newSize) { + String qry = String.format(Locale.ENGLISH, "ALTER TABLESPACE %s RESIZE MAXSIZE %s", this.getDisplayName(), + ServerObject.getLiteralName(newSize)); + return qry; + } + + /** + * Gets the tablespace type. + * + * @return the tablespace type + */ + public TablespaceType getTablespaceType() { + return this.tspctype; + } + + /** + * Fetch all tablespace. + * + * @param db the db + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static void fetchAllTablespace(Database db) throws DatabaseCriticalException, DatabaseOperationException { + int counter = 0; + String qry = ""; + boolean privilege = db.getConnectionManager().execSelectCheckIfAdmin(); + if (!privilege) { + qry = "select oid,spcname,spcacl," + "spcoptions, spcmaxsize, relative from pg_tablespace"; + if (db.getPrivilegeFlag()) { + qry += " where has_tablespace_privilege(spcname, 'CREATE')"; + } + qry += " order by spcname;"; + } else { + qry = "select oid, pg_tablespace_location(oid) as location ,spcname,spcacl," + + "spcoptions, spcmaxsize, relative from pg_tablespace"; + if (db.getPrivilegeFlag()) { + qry += " where has_tablespace_privilege(spcname, 'CREATE')"; + } + qry += " order by spcname;"; + } + ResultSet rs = null; + boolean hasMoreRs = false; + ObjectGroup tblsGrp = db.getServer().getTablespaceGroup(); + try { + rs = db.getConnectionManager().execSelectAndReturnRsOnObjBrowserConn(qry); + hasMoreRs = rs.next(); + while (hasMoreRs) { + Tablespace tablespace = Tablespace.convertToTablesapce(rs, db.getServer(), privilege); + counter++; + tblsGrp.addToGroup(tablespace); + hasMoreRs = rs.next(); + } + } catch (SQLException exception) { + try { + GaussUtils.handleCriticalException(exception); + } catch (DatabaseCriticalException dc) { + throw dc; + } + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + if (MPPDBIDELoggerUtility.isTraceEnabled()) { + MPPDBIDELoggerUtility.trace("Total number of Tablespaces loaded for selected server is : " + counter); + } + db.getConnectionManager().closeRSOnObjBrowserConn(rs); + } + } + + /** + * Gets the tablespace query. + * + * @param tableOid the table oid + * @param privilegeFlag the privilege flag + * @return the tablespace query + */ + public static String getTablespaceQuery(long tableOid, boolean privilegeFlag) { + String qry = "select oid, pg_tablespace_location(oid) as location, " + + "spcname,spcacl,spcoptions, spcmaxsize, relative from pg_tablespace where oid =%d"; + if (privilegeFlag) { + qry += " and has_tablespace_privilege(oid, 'CREATE')"; + } + qry += ";"; + qry = String.format(Locale.ENGLISH, qry, tableOid); + return qry; + } + +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TablespaceProperties.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TablespaceProperties.java new file mode 100644 index 0000000000000000000000000000000000000000..79ce0b1d2d446540ea0d0924a1b0b1914fd194f8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TablespaceProperties.java @@ -0,0 +1,350 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class TablespaceProperties. + * + */ + +public class TablespaceProperties { + + private String name; + private String location; + private String maxsize; + private String fileOption; + private String seqPageCost; + private String randomPageCost; + private boolean isRelativePath; + private Server server; + + /** + * Instantiates a new tablespace properties. + * + * @param name the name + * @param location the location + * @param maxsize the maxsize + * @param fileoption the fileoption + * @param address the address + * @param cfgpath the cfgpath + * @param dataStorePath the data store path + * @param seqPageCost the seq page cost + * @param randomPageCost the random page cost + * @param isRelativePath the is relative path + */ + public TablespaceProperties(String name, String location, String maxsize, String fileoption, String seqPageCost, + String randomPageCost, boolean isRelativePath) { + this.name = name; + this.location = location; + this.maxsize = maxsize; + this.fileOption = fileoption; + this.seqPageCost = seqPageCost; + this.randomPageCost = randomPageCost; + this.isRelativePath = isRelativePath; + } + + /** + * Instantiates a new tablespace properties. + * + * @param name the name + * @param seqPageCost the seq page cost + * @param randomPageCost the random page cost + */ + public TablespaceProperties(String name, String seqPageCost, String randomPageCost) { + this.name = name; + this.seqPageCost = seqPageCost; + this.randomPageCost = randomPageCost; + } + + /** + * Gets the server. + * + * @return the server + */ + public Server getServer() { + return server; + } + + /** + * Sets the server. + * + * @param server the new server + */ + public void setServer(Server server) { + this.server = server; + } + + /** + * Gets the location. + * + * @return the location + */ + public String getLocation() { + return location; + } + + /** + * Sets the location. + * + * @param location the new location + */ + public void setLocation(String location) { + this.location = location; + } + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Sets the name. + * + * @param name the new name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Gets the maxsize. + * + * @return the maxsize + */ + public String getTsMaxsize() { + return maxsize; + } + + /** + * Sets the maxsize. + * + * @param maxsize the new maxsize + */ + public void setTsMaxsize(String maxsize) { + this.maxsize = maxsize; + } + + /** + * Gets the file option. + * + * @return the file option + */ + public String getFileOption() { + return fileOption; + } + + /** + * Sets the file option. + * + * @param fileOption the new file option + */ + public void setFileOption(String fileOption) { + this.fileOption = fileOption; + } + + /** + * Gets the seq page cost. + * + * @return the seq page cost + */ + public String getSeqPageCost() { + return seqPageCost; + } + + /** + * Sets the seq page cost. + * + * @param seqPageCost the new seq page cost + */ + public void setSeqPageCost(String seqPageCost) { + this.seqPageCost = seqPageCost; + } + + /** + * Gets the random page cost. + * + * @return the random page cost + */ + public String getRandomPageCost() { + return randomPageCost; + } + + /** + * Sets the random page cost. + * + * @param randomPageCost the new random page cost + */ + public void setRandomPageCost(String randomPageCost) { + this.randomPageCost = randomPageCost; + } + + /** + * Builds the query. + * + * @return the string + */ + public String buildQuery() { + StringBuilder selectQuery = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + setEnableAbsTablespace(selectQuery); + selectQuery.append("CREATE TABLESPACE "); + selectQuery.append(ServerObject.getQualifiedObjectName(name)); + setRelativeCluase(selectQuery); + selectQuery.append(" LOCATION "); + selectQuery.append(ServerObject.getLiteralName(location)); + setMaxSize(selectQuery); + + setFileSystem(selectQuery); + if ("".equalsIgnoreCase(randomPageCost) && "".equalsIgnoreCase(seqPageCost)) { + MPPDBIDELoggerUtility.info("Random Cost and seq cost is null"); + } else if ((!"".equalsIgnoreCase(randomPageCost)) && "".equalsIgnoreCase(seqPageCost)) { + selectQuery.append(","); + selectQuery.append(" random_page_cost="); + selectQuery.append(randomPageCost); + } else if ((!"".equalsIgnoreCase(seqPageCost)) && "".equalsIgnoreCase(randomPageCost)) { + selectQuery.append(","); + selectQuery.append(" seq_page_cost="); + selectQuery.append(seqPageCost); + } else if (!("".equalsIgnoreCase(randomPageCost)) && !("".equalsIgnoreCase(seqPageCost))) { + selectQuery.append(","); + selectQuery.append(" random_page_cost="); + selectQuery.append(randomPageCost); + selectQuery.append(","); + selectQuery.append(" seq_page_cost="); + selectQuery.append(seqPageCost); + } + if (!"".equalsIgnoreCase(fileOption)) { + selectQuery.append(");"); + } + String query = selectQuery.toString(); + return query; + } + + /** + * Sets the file system. + * + * @param selectQuery the new file system + */ + private void setFileSystem(StringBuilder selectQuery) { + if (!"".equalsIgnoreCase(fileOption)) { + selectQuery.append(" WITH ("); + selectQuery.append(" filesystem ="); + selectQuery.append(fileOption); + } + } + + /** + * Sets the max size. + * + * @param selectQuery the new max size + */ + private void setMaxSize(StringBuilder selectQuery) { + if (!"".equalsIgnoreCase(maxsize)) { + selectQuery.append(" MAXSIZE "); + selectQuery.append("'"); + selectQuery.append(maxsize); + selectQuery.append("'"); + } + } + + /** + * Sets the relative cluase. + * + * @param selectQuery the new relative cluase + */ + private void setRelativeCluase(StringBuilder selectQuery) { + if (isRelativePath()) { + selectQuery.append(" RELATIVE "); + } + } + + /** + * Sets the enable abs tablespace. + * + * @param selectQuery the new enable abs tablespace + */ + private void setEnableAbsTablespace(StringBuilder selectQuery) { + if (null != server && server.isSupportTablespaceRelativePath()) { + if (isRelativePath()) { + selectQuery.append("set enable_absolute_tablespace=off ;"); + } else { + selectQuery.append("set enable_absolute_tablespace=on ;"); + } + } + } + + /** + * Builds the set option qry. + * + * @return the string + */ + public String buildSetOptionQry() { + StringBuilder query = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + query.append("ALTER TABLESPACE "); + query.append(this.getName()); + if ("".equalsIgnoreCase(this.randomPageCost)) { + query.append(" RESET ("); + query.append("random_page_cost"); + } else { + query.append(" SET ( "); + query.append("random_page_cost="); + query.append(this.randomPageCost); + } + query.append(" );"); + query.append("ALTER TABLESPACE "); + query.append(this.getName()); + if ("".equalsIgnoreCase(this.seqPageCost)) { + query.append(" RESET ("); + query.append("seq_page_cost"); + } else { + query.append(" SET ( "); + query.append("seq_page_cost="); + query.append(this.seqPageCost); + } + query.append(" );"); + + return query.toString(); + } + + /** + * Checks if is relative path. + * + * @return true, if is relative path + */ + public boolean isRelativePath() { + return isRelativePath; + } + + /** + * Sets the relative path. + * + * @param isRelatvPath the new relative path + */ + public void setRelativePath(boolean isRelatvPath) { + this.isRelativePath = isRelatvPath; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TablespaceType.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TablespaceType.java new file mode 100644 index 0000000000000000000000000000000000000000..584e513c8510087a506094be952172273b9acc1c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TablespaceType.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: enum + * + * Description: The Enum TablespaceType. + * + */ + +public enum TablespaceType { + NORMAL, HDFS, UNKNOWN + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TriggerMetaData.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TriggerMetaData.java new file mode 100644 index 0000000000000000000000000000000000000000..79390eceb587b3ac994de40765bf779c7192d36b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TriggerMetaData.java @@ -0,0 +1,267 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.bl.export.EXPORTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.groups.TriggerObjectGroup; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * Title: TriggerMetaData for use + * + * @since 3.0.0 + */ +public class TriggerMetaData extends BatchDropServerObject implements GaussOLAPDBMSObject { + private boolean enable = true; + private long tableoid; + private long funcOid; + private String triggerType; + private String triggerEnable; + private Namespace namespace; + private String ddlMsg = ""; + + public TriggerMetaData(long oid, String name) { + super(oid, name, OBJECTTYPE.TRIGGER_METADATA, false); + } + + @Override + public String getDropQuery(boolean isCascade) { + return String.format(Locale.ENGLISH, "DROP TRIGGER %s ON %s.%s", + ServerObject.getQualifiedObjectName(this.getName()), + getNamespace().getName(), + ServerObject.getQualifiedObjectName(geTableMetaData().getName())); + } + + /** + * drop trigger + * + * @param DBConnection conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void execDrop(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + conn.execNonSelect(getDropQuery(false)); + } + + /** + * enable sql + * + * @param boolean if is enable + * @return String the alter string + */ + public String alterEnableString(boolean enable) { + final String queryFormat = "ALTER TABLE %s.%s %s TRIGGER %s"; + return String.format(Locale.ENGLISH, + queryFormat, + getNamespace().getName(), + ServerObject.getQualifiedObjectName(geTableMetaData().getName()), + enable ? "ENABLE" : "DISABLE", + ServerObject.getQualifiedObjectName(getName()) + ); + } + + /** + * rename sql + * + * @param String the newName + * @param long trigger relid + * @param Namespace the namespace + * @param DBConnection the dbConnection + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void execRename(String newName, long tgrelid, Namespace namespace, DBConnection dbConnection) + throws DatabaseCriticalException, DatabaseOperationException { + StringBuilder sb = new StringBuilder(); + TableMetaData table = namespace.getTablesGroup().getObjectById(tgrelid); + sb.append("ALTER TRIGGER "); + sb.append(getDisplayName()); + sb.append(" ON "); + sb.append(namespace.getName() + "." + table.getName()); + sb.append(" RENAME TO "); + sb.append(ServerObject.getQualifiedObjectName(newName)); + dbConnection.execNonSelect(sb.toString()); + } + + + @Override + public boolean isExportAllowed(EXPORTTYPE exportType) { + return true; + } + + @Override + public Database getDatabase() { + return namespace.getDatabase(); + } + + /** + * description: enable trigger flag or not + * + * @param enable true if enable + */ + public void setEnable(boolean enable) { + this.enable = enable; + } + + /** + * description: get the enable state + * + * @return boolean true if enable + */ + public boolean getEnable() { + return this.enable; + } + + /** + * description: get the table oid + * + * @return long the tableoid + */ + public long getTableoid() { + return tableoid; + } + + /** + * description: set the table oid + * + * @param long the tableoid to set + */ + public void setTableoid(long tableoid) { + this.tableoid = tableoid; + } + + /** + * description: get function oid + * + * @return long the funcOid + */ + public long getFuncOid() { + return funcOid; + } + + /** + * description: set the function oid + * + * @param long the funcOid to set + */ + public void setFuncOid(long funcOid) { + this.funcOid = funcOid; + } + + /** + * description: get the trigger type + * + * @return String the triggerType + */ + public String getTriggerType() { + return triggerType; + } + + /** + * description: set the trigger type + * + * @param String the triggerType to set + */ + public void setTriggerType(String triggerType) { + this.triggerType = triggerType; + } + + /** + * description: get the trigger enable + * + * @return String the triggerEnable + */ + public String getTriggerEnable() { + return triggerEnable; + } + + /** + * description: set the trigger enable + * + * @param String the triggerEnable to set + */ + public void setTriggerEnable(String triggerEnable) { + this.triggerEnable = triggerEnable; + } + + /** + * description: get the namespace + * + * @return Namespace the namespace + */ + public Namespace getNamespace() { + return namespace; + } + + /** + * description: set the namespace + * + * @param Namespace the namespace to set + */ + public void setNamespace(Namespace namespace) { + this.namespace = namespace; + } + + /** + * description: get ddl msg + * + * @return String the msg + */ + public String getDdlMsg() { + return ddlMsg; + } + + /** + * description: set the msg + * + * @param String the msg + */ + public void setDdlMsg(String msg) { + this.ddlMsg = msg; + } + + /** + * description: get the header + * + * @return String the header string + */ + public String getHeader() { + return "--" + + MPPDBIDEConstants.LINE_SEPARATOR + "-- Name: " + getName() + "; Type: " + + getTypeLabel() + "; Schema: " + getNamespace().getName() + ";" + + MPPDBIDEConstants.LINE_SEPARATOR + "--" + MPPDBIDEConstants.LINE_SEPARATOR + + MPPDBIDEConstants.LINE_SEPARATOR; + } + + /** + * description: get the table metadata + * + * @return TableMetaData the table metadata + */ + public TableMetaData geTableMetaData() { + return namespace.getTablesGroup().getObjectById(tableoid); + } + + @Override + public TriggerObjectGroup getParent() { + return namespace.getTriggerObjectGroup(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TypeMetaData.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TypeMetaData.java new file mode 100644 index 0000000000000000000000000000000000000000..742579b6593b298a79d9398b1ddc87c3d52e8560 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TypeMetaData.java @@ -0,0 +1,466 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; + +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class TypeMetaData. + * + */ + +public class TypeMetaData extends ServerObject implements GaussOLAPDBMSObject { + + private Namespace namespace; + + /* Any addition to be added in clone() function */ + private int typelen; + + private boolean isbyval; + + private PgtypeCategory category; + + private PgtypeType pgType; + + private long typtypmod; + + private boolean typnotnull; + + private long typarray; + + private String description; + + private String displayName; + + enum PgtypeCategory { + PGTYPE_CAT_ARRAY, /* A - Array */ + PGTYPE_CAT_BOOLEAN, /* B - Boolean */ + PGTYPE_CAT_COMPOSITE, /* C Composite */ + PGTYPE_CAT_DATA_TIME, /* D Date/time */ + PGTYPE_CAT_ENUM, /* E Enum */ + PGTYPE_CAT_GEOMETRIC, /* G Geometric Do not pull */ + PGTYPE_CAT_NETWORK, /* I Network address Do not pull */ + PGTYPE_CAT_NUMERIC, /* N Numeric */ + PGTYPE_CAT_PSEUDO, /* P Pseudo-types Do not pull */ + PGTYPE_CAT_RANGE, /* R Range types Do not pull */ + PGTYPE_CAT_STRING, /* S String */ + PGTYPE_CAT_TIMESPAN, /* T Timespan */ + PGTYPE_CAT_USER_DEFINED, /* U User-defined */ + PGTYPE_CAT_BIT_STRING, /* V Bit-string */ + PGTYPE_CAT_UNKNOWN /* X unknown type Do not pull */ + } + + enum PgtypeType { + PGTYPE_BASE, /* b base */ + PGTYPE_COMPOSITE, /* c composite */ + PGTYPE_DOMAIN, /* d domain */ + PGTYPE_PSEUDO, /* p pseudo */ + } + + /** + * Instantiates a new type meta data. + * + * @param oid the oid + * @param name the name + * @param namespace the namespace + */ + public TypeMetaData(long oid, String name, Namespace namespace) { + super(oid, name, OBJECTTYPE.TYPEMETADATA, false); + this.namespace = namespace; + } + + /** + * Gets the typelen. + * + * @return the typelen + */ + public int getTypelen() { + return typelen; + } + + /** + * Sets the typelen. + * + * @param typelen the new typelen + */ + private void setTypelen(int typelen) { + this.typelen = typelen; + } + + /** + * Checks if is isbyval. + * + * @return true, if is isbyval + */ + public boolean isIsbyval() { + return isbyval; + } + + /** + * Sets the isbyval. + * + * @param isbyval the new isbyval + */ + private void setIsbyval(boolean isbyval) { + this.isbyval = isbyval; + } + + /** + * Gets the category. + * + * @return the category + */ + public PgtypeCategory getCategory() { + return this.category; + } + + /** + * Sets the categoy. + * + * @param type the new categoy + */ + private void setCategoy(PgtypeCategory type) { + this.category = type; + } + + /** + * Sets the pg type. + * + * @param type the new pg type + */ + private void setPgType(PgtypeType type) { + this.pgType = type; + } + + /** + * Gets the typtypmod. + * + * @return the typtypmod + */ + public long getTyptypmod() { + return typtypmod; + } + + /** + * Sets the typtypmod. + * + * @param typtypmod the new typtypmod + */ + private void setTyptypmod(long typtypmod) { + this.typtypmod = typtypmod; + } + + /** + * Checks if is typnotnull. + * + * @return true, if is typnotnull + */ + public boolean isTypnotnull() { + return typnotnull; + } + + /** + * Sets the typnotnull. + * + * @param typnotnull the new typnotnull + */ + public void setTypnotnull(boolean typnotnull) { + this.typnotnull = typnotnull; + } + + /** + * Gets the typarray. + * + * @return the typarray + */ + public long getTyparray() { + return typarray; + } + + /** + * Sets the typarray. + * + * @param typarray the new typarray + */ + private void setTyparray(long typarray) { + this.typarray = typarray; + } + + /** + * Sets the namespace. + * + * @param ns the new namespace + */ + public void setNamespace(Namespace ns) { + this.namespace = ns; + } + + /** + * Gets the namespace. + * + * @return the namespace + */ + public Namespace getNamespace() { + return this.namespace; + } + + /** + * Gets the description. + * + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * Sets the description. + * + * @param description the new description + */ + private void setDescription(String description) { + this.description = description; + } + + /** + * Gets the PG type. + * + * @param typename the typename + * @return the PG type + */ + public static PgtypeType getPGType(String typename) { + if ("b".equals(typename)) { + return PgtypeType.PGTYPE_BASE; + } else if ("c".equals(typename)) { + return PgtypeType.PGTYPE_COMPOSITE; + } else if ("d".equals(typename)) { + return PgtypeType.PGTYPE_DOMAIN; + } else { + return PgtypeType.PGTYPE_PSEUDO; + } + } + + /** + * Gets the PG type category. + * + * @param typeName the type name + * @return the PG type category + */ + public static PgtypeCategory getPGTypeCategory(String typeName) { + if ("A".equals(typeName)) { + return PgtypeCategory.PGTYPE_CAT_ARRAY; + } else if ("B".equals(typeName)) { + return PgtypeCategory.PGTYPE_CAT_BOOLEAN; + } else if ("C".equals(typeName)) { + return PgtypeCategory.PGTYPE_CAT_COMPOSITE; + } else if ("D".equals(typeName)) { + return PgtypeCategory.PGTYPE_CAT_DATA_TIME; + } else if ("E".equals(typeName)) { + return PgtypeCategory.PGTYPE_CAT_ENUM; + } else if ("G".equals(typeName)) { + return PgtypeCategory.PGTYPE_CAT_GEOMETRIC; + } else if ("I".equals(typeName)) { + return PgtypeCategory.PGTYPE_CAT_NETWORK; + } else if ("N".equals(typeName)) { + return PgtypeCategory.PGTYPE_CAT_NUMERIC; + } else if ("P".equals(typeName)) { + return PgtypeCategory.PGTYPE_CAT_PSEUDO; + } else if ("R".equals(typeName)) { + return PgtypeCategory.PGTYPE_CAT_RANGE; + } else if ("S".equals(typeName)) { + return PgtypeCategory.PGTYPE_CAT_STRING; + } else if ("T".equals(typeName)) { + return PgtypeCategory.PGTYPE_CAT_TIMESPAN; + } else if ("U".equals(typeName)) { + return PgtypeCategory.PGTYPE_CAT_USER_DEFINED; + } else if ("V".equals(typeName)) { + return PgtypeCategory.PGTYPE_CAT_BIT_STRING; + } + + return PgtypeCategory.PGTYPE_CAT_UNKNOWN; + + } + + /** + * Convert to type meta data. + * + * @param rs the rs + * @param db the db + * @param includeDescription the include description + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public static void convertToTypeMetaData(ResultSet rs, Database db, boolean includeDescription) + throws DatabaseOperationException, DatabaseCriticalException { + long oid = 0; + String name = null; + long namespaceOid = 0; + + try { + oid = rs.getLong("oid"); + name = rs.getString("typname"); + namespaceOid = rs.getLong("typnamespace"); + + Namespace ns = db.getNameSpaceById(namespaceOid); + + if (null == ns) { + MPPDBIDELoggerUtility.error("Unable to map few datatype to Namespace."); + throw new DatabaseOperationException("Unable to map few datatype to Namespace."); + } + + TypeMetaData type = new TypeMetaData(oid, name, ns); + type.setIsbyval(rs.getBoolean("typbyval")); + type.setTyparray(rs.getLong("typarray")); + + String dtCatogry = rs.getString("typcategory"); + type.setCategoy(getPGTypeCategory(dtCatogry)); + type.setPgType(getPGType(rs.getString("typtype"))); + type.setTypelen(rs.getInt("typlen")); + type.setTypnotnull(rs.getBoolean("typnotnull")); + type.setTyptypmod(rs.getLong("typtypmod")); + if (includeDescription) { + type.setDescription(rs.getString("desc")); + } + type.setDisplayDatatype(rs.getString("displaycolumns")); + ns.getTypes().addItem(type); + } catch (SQLException exception) { + GaussUtils.handleCriticalException(exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } + } + + /** + * Sets the display datatype. + * + * @param displayDatatypeName the new display datatype + */ + private void setDisplayDatatype(String displayDatatypeName) { + this.displayName = displayDatatypeName; + } + + /** + * Gets the display datatype. + * + * @return the display datatype + */ + public String getDisplayDatatype() { + return displayName; + } + + /** + * Gets the clone obj. + * + * @return the clone obj + */ + protected TypeMetaData getCloneObj() { + TypeMetaData type = new TypeMetaData(getOid(), getName(), this.namespace); + + setTypeDetails(type); + + return type; + } + + /** + * Sets the type details. + * + * @param type the new type details + */ + private void setTypeDetails(TypeMetaData type) { + type.setPgType(this.pgType); + type.setIsbyval(this.isbyval); + type.setTyparray(this.typarray); + type.setTypnotnull(this.typnotnull); + type.setTyptypmod(this.typtypmod); + type.setCategoy(this.category); + type.setTypelen(this.typelen); + type.setDescription(this.description); + type.setPgType(PgtypeType.PGTYPE_PSEUDO); + } + + /** + * Gets the clone obj with name. + * + * @param nameParam the name param + * @return the clone obj with name + */ + public TypeMetaData getCloneObjWithName(String nameParam) { + String name = nameParam; + if (null == name) { + name = getName(); + } + TypeMetaData type = new TypeMetaData(getOid(), name, this.namespace); + + setTypeDetails(type); + + return type; + } + + /** + * Gets the type by id. + * + * @param namespace the namespace + * @param oid the oid + * @return the type by id + */ + public static TypeMetaData getTypeById(Namespace namespace, long oid) { + ArrayList types = namespace.getTypes().getList(); + + for (TypeMetaData type : types) { + if (oid == type.getOid()) { + return type; + } + } + + // If control reaches here, then user has used Complex User defined + // datatypes. We DONOT SUPPORT this type of feature, so just return a + // dummy datatype object, so support errors. + // + return new TypeMetaData(oid, "", namespace); + } + + /** + * Gets the parent. + * + * @return the parent + */ + @Override + public Object getParent() { + return this.namespace; + } + + /** + * Gets the search name. + * + * @return the search name + */ + @Override + public String getSearchName() { + return getName() + " - " + getTypeLabel(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TypeMetaDataUtil.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TypeMetaDataUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..97edf24a72a6d8a97c8e482c7d99674be30d5455 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/TypeMetaDataUtil.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.util.ArrayList; + +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class TypeMetaDataUtil. + * + */ + +public class TypeMetaDataUtil { + + /** + * Gets the data type from namespace. + * + * @param datatypeOid the datatype oid + * @param nsList the ns list + * @return the data type from namespace + */ + public static String getDataTypeFromNamespace(int datatypeOid, ArrayList nsList) { + String convertedDataType = null; + + if (nsList != null) { + for (Namespace ns : nsList) { + convertedDataType = getDataTypeFromNamespace(datatypeOid, ns); + if (convertedDataType != null) { + break; + } + } + } + + if (convertedDataType == null) { + convertedDataType = MPPDBIDEConstants.UNKNOWN_DATATYPE_STR; + } + + return convertedDataType; + } + + /** + * Gets the data type from namespace. + * + * @param rettype the rettype + * @param ns the ns + * @return the data type from namespace + */ + private static String getDataTypeFromNamespace(int rettype, Namespace ns) { + if (ns != null) { + TypeMetaData tmd = ns.getTypeByOid(rettype); + if (tmd != null) { + return tmd.getName(); + } + } + + return null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/UserNamespace.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/UserNamespace.java new file mode 100644 index 0000000000000000000000000000000000000000..265947183ce54fe060875be142a82c35737a49ca --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/UserNamespace.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: class + * + * Description: The Class UserNamespace. + * + */ + +public class UserNamespace extends Namespace { + + private boolean isDrop; + + /** + * Instantiates a new user namespace. + * + * @param oid the oid + * @param name the name + * @param parentDb the parent db + */ + public UserNamespace(long oid, String name, Database parentDb) { + super(oid, name, parentDb); + } + + /** + * Checks if is drop. + * + * @return true, if is drop + */ + public boolean isDrop() { + return isDrop; + } + + /** + * Drop. + * + * @param conn the conn + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void drop(DBConnection conn) throws DatabaseOperationException, DatabaseCriticalException { + isDrop = true; + String qry = String.format(Locale.ENGLISH, "Drop SCHEMA %s;", this.getDisplayName()); + conn.execNonSelect(qry); + NamespaceUtilsBase.refreshNamespace(this.getOid(), isDrop, db); + isDrop = false; + } + + /** + * Rename. + * + * @param newName the new name + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void rename(String newName, DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + String qry = String.format(Locale.ENGLISH, "ALTER SCHEMA %s RENAME TO %s ;", this.getDisplayName(), + ServerObject.getQualifiedObjectName(newName)); + conn.execNonSelect(qry); + NamespaceUtilsBase.refreshNamespaceMetaData(this.getOid(), db); + } + + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } + + @Override + public int hashCode() { + return super.hashCode(); + } + +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/UserRole.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/UserRole.java new file mode 100644 index 0000000000000000000000000000000000000000..70206526d7c5ba7d0e412928beec1df2aeb8f2c7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/UserRole.java @@ -0,0 +1,712 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.util.Date; +import java.util.List; + +import org.opengauss.mppdbide.bl.serverdatacache.groups.UserRoleObjectGroup; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class UserRole. + * + */ + +public class UserRole extends BatchDropServerObject implements GaussOLAPDBMSObject { + + private Boolean rolInherit; + private Boolean rolCreateRole; + private Boolean rolCreateDb; + private Boolean rolCanLogin; + private Boolean rolReplication; + private Boolean rolAuditAdmin; + private Boolean rolSystemAdmin; + private Integer rolConnLimit; + private Date rolValidBegin; + private Date rolValidUntil; + + private String rolResPool; + private Boolean isLock; + private Boolean isUser; + private String comment; + private List parents; + private List members; + private Server server; + + private int spinnerPreSize; + private String cmbResoucePoolName; + private String userGroupName; + private String roleCombo; + private String adminComo; + private Boolean auditAdmin; + private String beginTime; + private String untilTime; + private char[] passwordInput; + private Boolean all; + private Boolean clear; + + private Boolean user; + private Boolean role; + + /** + * Gets the user. + * + * @return the user + */ + public Boolean getUser() { + return user; + } + + /** + * Sets the user. + * + * @param user the new user + */ + public void setUser(Boolean user) { + this.user = user; + } + + /** + * Gets the role. + * + * @return the role + */ + public Boolean getRole() { + return role; + } + + /** + * Sets the role. + * + * @param role the new role + */ + public void setRole(Boolean role) { + this.role = role; + } + + /** + * Gets the all. + * + * @return the all + */ + public Boolean getAll() { + return all; + } + + /** + * Sets the all. + * + * @param all the new all + */ + public void setAll(Boolean all) { + this.all = all; + } + + /** + * Gets the clear. + * + * @return the clear + */ + public Boolean getClear() { + return clear; + } + + /** + * Sets the clear. + * + * @param clear the new clear + */ + public void setClear(Boolean clear) { + this.clear = clear; + } + + private static final String DROP_QUERY = "DROP ROLE IF EXISTS "; + + /** + * Gets the spinner pre size. + * + * @return the spinner pre size + */ + public int getSpinnerPreSize() { + return spinnerPreSize; + } + + /** + * Sets the spinner pre size. + * + * @param spinnerPreSize the new spinner pre size + */ + public void setSpinnerPreSize(int spinnerPreSize) { + this.spinnerPreSize = spinnerPreSize; + } + + /** + * Gets the cmb resouce pool name. + * + * @return the cmb resouce pool name + */ + public String getCmbResoucePoolName() { + return cmbResoucePoolName; + } + + /** + * Sets the cmb resouce pool name. + * + * @param cmbResoucePoolName the new cmb resouce pool name + */ + public void setCmbResoucePoolName(String cmbResoucePoolName) { + this.cmbResoucePoolName = cmbResoucePoolName; + } + + /** + * Gets the user group name. + * + * @return the user group name + */ + public String getUserGroupName() { + return userGroupName; + } + + /** + * Sets the user group name. + * + * @param userGroupName the new user group name + */ + public void setUserGroupName(String userGroupName) { + this.userGroupName = userGroupName; + } + + /** + * Gets the role combo. + * + * @return the role combo + */ + public String getRoleCombo() { + return roleCombo; + } + + /** + * Sets the role combo. + * + * @param roleCombo the new role combo + */ + public void setRoleCombo(String roleCombo) { + this.roleCombo = roleCombo; + } + + /** + * Gets the admin como. + * + * @return the admin como + */ + public String getAdminComo() { + return adminComo; + } + + /** + * Sets the admin como. + * + * @param adminComo the new admin como + */ + public void setAdminComo(String adminComo) { + this.adminComo = adminComo; + } + + /** + * Gets the audit admin. + * + * @return the audit admin + */ + public Boolean getAuditAdmin() { + return auditAdmin; + } + + /** + * Sets the audit admin. + * + * @param auditAdmin the new audit admin + */ + public void setAuditAdmin(Boolean auditAdmin) { + this.auditAdmin = auditAdmin; + } + + /** + * Gets the begin time. + * + * @return the begin time + */ + public String getBeginTime() { + return beginTime; + } + + /** + * Sets the begin time. + * + * @param beginTime the new begin time + */ + public void setBeginTime(String beginTime) { + this.beginTime = beginTime; + } + + /** + * Gets the until time. + * + * @return the until time + */ + public String getUntilTime() { + return untilTime; + } + + /** + * Sets the until time. + * + * @param untilTime the new until time + */ + public void setUntilTime(String untilTime) { + this.untilTime = untilTime; + } + + /** + * Gets the password input. + * + * @return the password input + */ + public char[] getPasswordInput() { + return (char[]) this.passwordInput.clone(); + } + + /** + * Sets the password input. + * + * @param passwordInput the new password input + */ + public void setPasswordInput(char[] passwordInput) { + this.passwordInput = passwordInput.clone(); + } + + /** + * Clear pwd. + */ + public void clearPwd() { + for (int index = 0; index < passwordInput.length; index++) { + passwordInput[index] = 0; + } + } + + /** + * Instantiates a new user role. + */ + public UserRole() { + super(OBJECTTYPE.USER_ROLE); + } + + /** + * Instantiates a new user role. + * + * @param type the type + * @param oid the oid + * @param rolName the rol name + * @param rolInherit the rol inherit + * @param rolCreateRole the rol create role + * @param rolCreateDb the rol create db + * @param rolCanLogin the rol can login + * @param rolReplication the rol replication + * @param rolAuditAdmin the rol audit admin + * @param rolSystemAdmin the rol system admin + * @param rolConnLimit the rol conn limit + * @param rolValidBegin the rol valid begin + * @param rolValidUntil the rol valid until + * @param rolResPool the rol res pool + * @param server the server + */ + public UserRole(OBJECTTYPE type, Long oid, String rolName, Boolean rolInherit, Boolean rolCreateRole, + Boolean rolCreateDb, Boolean rolCanLogin, Boolean rolReplication, Boolean rolAuditAdmin, + Boolean rolSystemAdmin, Integer rolConnLimit, Date rolValidBegin, Date rolValidUntil, String rolResPool, + Server server) { + super(oid, rolName, type, server.getPrivilegeFlag()); + this.rolInherit = rolInherit; + this.rolCreateRole = rolCreateRole; + this.rolCreateDb = rolCreateDb; + this.rolCanLogin = rolCanLogin; + this.rolReplication = rolReplication; + this.rolAuditAdmin = rolAuditAdmin; + this.rolSystemAdmin = rolSystemAdmin; + this.rolConnLimit = rolConnLimit; + this.rolValidBegin = rolValidBegin != null ? (Date) rolValidBegin.clone() : null; + this.rolValidUntil = rolValidUntil != null ? (Date) rolValidUntil.clone() : null; + this.rolResPool = rolResPool; + this.server = server; + } + + /** + * Instantiates a new user role. + * + * @param server the server + */ + public UserRole(Server server) { + this(OBJECTTYPE.USER_ROLE, Long.valueOf(0), null, false, false, false, false, false, false, false, 0, null, + null, null, server); + + } + + @Override + public UserRoleObjectGroup getParent() { + return this.server.getUserRoleObjectGroup(); + } + + /** + * Gets the rol inherit. + * + * @return the rol inherit + */ + public Boolean getRolInherit() { + return rolInherit; + } + + /** + * Sets the rol inherit. + * + * @param rolInherit the new rol inherit + */ + public void setRolInherit(Boolean rolInherit) { + this.rolInherit = rolInherit; + } + + /** + * Gets the rol create role. + * + * @return the rol create role + */ + public Boolean getRolCreateRole() { + return rolCreateRole; + } + + /** + * Sets the rol create role. + * + * @param rolCreateRole the new rol create role + */ + public void setRolCreateRole(Boolean rolCreateRole) { + this.rolCreateRole = rolCreateRole; + } + + /** + * Gets the rol create db. + * + * @return the rol create db + */ + public Boolean getRolCreateDb() { + return rolCreateDb; + } + + /** + * Sets the rol create db. + * + * @param rolCreateDb the new rol create db + */ + public void setRolCreateDb(Boolean rolCreateDb) { + this.rolCreateDb = rolCreateDb; + } + + /** + * Gets the rol can login. + * + * @return the rol can login + */ + public Boolean getRolCanLogin() { + return rolCanLogin; + } + + /** + * Sets the rol can login. + * + * @param rolCanLogin the new rol can login + */ + public void setRolCanLogin(Boolean rolCanLogin) { + this.rolCanLogin = rolCanLogin; + } + + /** + * Gets the rol replication. + * + * @return the rol replication + */ + public Boolean getRolReplication() { + return rolReplication; + } + + /** + * Sets the rol replication. + * + * @param rolReplication the new rol replication + */ + public void setRolReplication(Boolean rolReplication) { + this.rolReplication = rolReplication; + } + + /** + * Gets the rol audit admin. + * + * @return the rol audit admin + */ + public Boolean getRolAuditAdmin() { + return rolAuditAdmin; + } + + /** + * Sets the rol audit admin. + * + * @param rolAuditAdmin the new rol audit admin + */ + public void setRolAuditAdmin(Boolean rolAuditAdmin) { + this.rolAuditAdmin = rolAuditAdmin; + } + + /** + * Gets the rol system admin. + * + * @return the rol system admin + */ + public Boolean getRolSystemAdmin() { + return rolSystemAdmin; + } + + /** + * Sets the rol system admin. + * + * @param rolSystemAdmin the new rol system admin + */ + public void setRolSystemAdmin(Boolean rolSystemAdmin) { + this.rolSystemAdmin = rolSystemAdmin; + } + + /** + * Gets the rol conn limit. + * + * @return the rol conn limit + */ + public Integer getRolConnLimit() { + return rolConnLimit; + } + + /** + * Sets the rol conn limit. + * + * @param rolConnLimit the new rol conn limit + */ + public void setRolConnLimit(Integer rolConnLimit) { + this.rolConnLimit = rolConnLimit; + } + + /** + * Gets the rol valid begin. + * + * @return the rol valid begin + */ + public Date getRolValidBegin() { + return rolValidBegin != null ? (Date) rolValidBegin.clone() : null; + } + + /** + * Sets the rol valid begin. + * + * @param rolValidBegin the new rol valid begin + */ + public void setRolValidBegin(Date rolValidBegin) { + this.rolValidBegin = rolValidBegin != null ? (Date) rolValidBegin.clone() : null; + } + + /** + * Gets the rol valid until. + * + * @return the rol valid until + */ + public Date getRolValidUntil() { + return rolValidUntil != null ? (Date) rolValidUntil.clone() : null; + } + + /** + * Sets the rol valid until. + * + * @param rolValidUntil the new rol valid until + */ + public void setRolValidUntil(Date rolValidUntil) { + this.rolValidUntil = rolValidUntil != null ? (Date) rolValidUntil.clone() : null; + } + + /** + * Gets the rol res pool. + * + * @return the rol res pool + */ + public String getRolResPool() { + return rolResPool; + } + + /** + * Sets the rol res pool. + * + * @param rolResPool the new rol res pool + */ + public void setRolResPool(String rolResPool) { + this.rolResPool = rolResPool; + } + + /** + * Gets the checks if is lock. + * + * @return the checks if is lock + */ + public Boolean getIsLock() { + return isLock; + } + + /** + * Sets the checks if is lock. + * + * @param isLock the new checks if is lock + */ + public void setIsLock(Boolean isLock) { + this.isLock = isLock; + } + + /** + * Gets the comment. + * + * @return the comment + */ + public String getComment() { + return comment; + } + + /** + * Sets the comment. + * + * @param comment the new comment + */ + public void setComment(String comment) { + this.comment = comment; + } + + /** + * Gets the parents. + * + * @return the parents + */ + public List getParents() { + return parents; + } + + /** + * Sets the parents. + * + * @param parents the new parents + */ + public void setParents(List parents) { + this.parents = parents; + } + + /** + * Gets the members. + * + * @return the members + */ + public List getMembers() { + return members; + } + + /** + * Sets the members. + * + * @param members the new members + */ + public void setMembers(List members) { + this.members = members; + } + + /** + * Gets the server. + * + * @return the server + */ + public Server getServer() { + return server; + } + + /** + * Sets the server. + * + * @param server the new server + */ + public void setServer(Server server) { + this.server = server; + } + + @Override + public String getDropQuery(boolean isCascade) { + StringBuilder query = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + query.append("DROP "); + query.append(this.getRolCanLogin() ? "USER " : "ROLE "); + query.append("IF EXISTS "); + query.append(this.getDisplayName()); + if (isCascade) { + query.append(this.getRolCanLogin() ? MPPDBIDEConstants.CASCADE : ""); + } + return query.toString(); + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + + try { + return getServer().findOneActiveDb(); + } catch (DatabaseOperationException exception) { + + MPPDBIDELoggerUtility.error("No Active DataBase.", exception); + } + return null; + + } + + /** + * get is user + * + * @return is user + */ + public Boolean getIsUser() { + return isUser; + } + + /** + * set is user + * + * @param isUser the is user + */ + public void setIsUser(Boolean isUser) { + this.isUser = isUser; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/UserRoleFieldEnum.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/UserRoleFieldEnum.java new file mode 100644 index 0000000000000000000000000000000000000000..23576d5df2ea06481332c3bed7cc435afbb37262 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/UserRoleFieldEnum.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +/** + * + * Title: enum + * + * Description: The Enum UserRoleFieldEnum. + * + */ + +public enum UserRoleFieldEnum { + OID((byte) 1, "oid"), NAME((byte) 2, "name"), ROL_INHERIT((byte) 3, "rolInherit"), + ROL_CREATE_ROLE((byte) 4, "rolCreateRole"), ROL_CREATE_DB((byte) 5, "rolCreateDb"), + ROL_CAN_LOGIN((byte) 6, "rolCanLogin"), ROL_REPLICATION((byte) 7, "rolReplication"), + ROL_AUDIT_ADMIN((byte) 8, "rolAuditAdmin"), ROL_SYSTEM_ADMIN((byte) 9, "rolSystemAdmin"), + ROL_CONN_LIMIT((byte) 10, "rolConnLimit"), ROL_VALID_BEGIN((byte) 11, "rolValidBegin"), + ROL_VALID_UNTIL((byte) 12, "rolValidUntil"), ROL_RES_POOL((byte) 13, "rolResPool"), COMMENT((byte) 14, "comment"), + IS_LOCK((byte) 15, "isLock"), PARENTS((byte) 16, "parents"); + + /** + * The id. + */ + public final byte id; + + /** + * The field name. + */ + public final String fieldName; + + /** + * Instantiates a new user role field enum. + * + * @param id the id + * @param fieldName the field name + */ + private UserRoleFieldEnum(byte id, String fieldName) { + this.id = id; + this.fieldName = fieldName; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/UserRoleManager.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/UserRoleManager.java new file mode 100644 index 0000000000000000000000000000000000000000..9e4ce7e48d2bee676826e1b8823fa46cada651db --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/UserRoleManager.java @@ -0,0 +1,1373 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.text.MessageFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import org.apache.commons.lang3.StringUtils; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: interface + * + * Description: The Interface UserRoleManager. + * + */ + +public interface UserRoleManager { + + /** + * The Constant GET_METHOD_PREFIX. + */ + public static final String GET_METHOD_PREFIX = "get"; + + /** + * The Constant SET_METHOD_PREFIX. + */ + public static final String SET_METHOD_PREFIX = "set"; + + /** + * Fetch all user role. + * + * @param server the server + * @param conn the conn + * @return the list + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static List fetchAllUserRole(Server server, DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + String query = "SELECT rolname,rolcanlogin,oid FROM pg_catalog.pg_roles;"; + List userRoles = UserRoleManagerHidden.fetchUserRoleQuery(server, conn, query); + return userRoles; + } + + /** + * Fetch all user role with out super user. + * + * @param server the server + * @param conn the conn + * @return the list + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static List fetchAllUserRoleWithOutSuperUser(Server server, DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + String query = "SELECT rolname,rolcanlogin,oid FROM pg_catalog.pg_roles WHERE rolsuper = false;"; + List userRoles = UserRoleManagerHidden.fetchUserRoleQuery(server, conn, query); + return userRoles; + } + + /** + * Fetch user role detail info by oid. + * + * @param server the server + * @param conn the conn + * @param userRole the user role + * @return the user role + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public static UserRole fetchUserRoleDetailInfoByOid(Server server, DBConnection conn, UserRole userRole) + throws MPPDBIDEException { + String query = "SELECT rolname,rolinherit,rolcreaterole,rolcreatedb,rolcanlogin,rolreplication" + + ",rolauditadmin,rolsystemadmin,rolconnlimit,rolvalidbegin,rolvaliduntil,oid,rolrespool" + + " FROM pg_catalog.pg_roles WHERE oid = ?::oid;"; + return UserRoleManagerHidden.fetchUserRoleByOid(server, conn, userRole, query); + } + + /** + * Fetch user role simple info by oid. + * + * @param server the server + * @param conn the conn + * @param userRole the user role + * @return the user role + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public static UserRole fetchUserRoleSimpleInfoByOid(Server server, DBConnection conn, UserRole userRole) + throws MPPDBIDEException { + String query = "SELECT rolname,rolcanlogin,oid FROM pg_catalog.pg_roles WHERE oid = ?::oid;"; + return UserRoleManagerHidden.fetchUserRoleByOid(server, conn, userRole, query); + } + + /** + * Fetch all parent. + * + * @param server the server + * @param conn the conn + * @param userRole the user role + * @return the list + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public static List fetchAllParent(Server server, DBConnection conn, UserRole userRole) + throws DatabaseOperationException, DatabaseCriticalException { + List parents = new ArrayList<>(); + String query = "SELECT r.oid, r.rolname FROM pg_catalog.pg_roles r, pg_catalog.pg_auth_members m" + + " WHERE r.oid = m.roleid AND member = ?::oid;"; + ResultSet rs = null; + try { + rs = conn.execSelectForSearch(query, String.valueOf(userRole.getOid())); + while (rs.next()) { + parents.add(UserRoleManagerHidden.convertToUserRole(rs, server)); + } + return parents; + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + conn.closeResultSet(rs); + } + } + + /** + * + * Title: class + * + * Description: The Class UserRoleManagerHidden. + * + */ + static class UserRoleManagerHidden { + + private static final String ROLE_QUERY = "SELECT rolsystemadmin,rolauditadmin,rolcreatedb,rolcreaterole,rolinherit,rolcanlogin,rolreplication," + + "rolconnlimit,rolvalidbegin,rolvaliduntil,rolrespool from pg_roles WHERE oid = %d;"; + private static final String MEMBER_QUERY = "SELECT r.rolname rolname,m.admin_option admin_option FROM pg_auth_members m, " + + "pg_roles r WHERE r.oid = m.member AND m.roleid = %d;"; + private static final String DESCIPTIONQUERY = "SELECT description FROM " + + "PG_SHDESCRIPTION WHERE objoid = %d;"; + + private static List fetchUserRoleQuery(Server server, DBConnection conn, String query) + throws DatabaseCriticalException, DatabaseOperationException { + List userRoles = new ArrayList<>(); + ResultSet rs = null; + try { + rs = conn.execSelectAndReturnRs(query); + while (rs.next()) { + userRoles.add(convertToUserRole(rs, server)); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + conn.closeResultSet(rs); + } + return userRoles; + } + + private static UserRole fetchUserRoleByOid(Server server, DBConnection conn, UserRole userRole, String query) + throws DatabaseCriticalException, DatabaseOperationException, MPPDBIDEException { + ResultSet rs = null; + try { + rs = conn.execSelectForSearch(query, String.valueOf(userRole.getOid())); + while (rs.next()) { + return convertToUserRole(rs, server); + } + MPPDBIDELoggerUtility.error(MessageConfigLoader + .getProperty(IMessagesConstants.ERR_USER_ROLE_IS_NOT_EXIST, String.valueOf(userRole.getOid()))); + throw new MPPDBIDEException(IMessagesConstants.ERR_USER_ROLE_IS_NOT_EXIST, + String.valueOf(userRole.getOid())); + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + conn.closeResultSet(rs); + } + } + + /** + * Convert to user role. + * + * @param rs the rs + * @param server the server + * @return the user role + * @throws SQLException the SQL exception + */ + private static UserRole convertToUserRole(ResultSet rs, Server server) throws SQLException { + return new UserRole(OBJECTTYPE.USER_ROLE, rs.getLong("oid"), rs.getString("rolname"), + isExistColumn(rs, "rolinherit") ? rs.getBoolean("rolinherit") : null, + isExistColumn(rs, "rolcreaterole") ? rs.getBoolean("rolcreaterole") : null, + isExistColumn(rs, "rolcreatedb") ? rs.getBoolean("rolcreatedb") : null, + isExistColumn(rs, "rolcanlogin") ? rs.getBoolean("rolcanlogin") : null, + isExistColumn(rs, "rolreplication") ? rs.getBoolean("rolreplication") : null, + isExistColumn(rs, "rolauditadmin") ? rs.getBoolean("rolauditadmin") : null, + isExistColumn(rs, "rolsystemadmin") ? rs.getBoolean("rolsystemadmin") : null, + isExistColumn(rs, "rolconnlimit") ? rs.getInt("rolconnlimit") : null, + isExistColumn(rs, "rolvalidbegin") ? rs.getDate("rolvalidbegin") : null, + isExistColumn(rs, "rolvaliduntil") ? rs.getDate("rolvaliduntil") : null, + isExistColumn(rs, "rolResPool") ? rs.getString("rolResPool") : null, server); + } + + /** + * Checks if is exist column. + * + * @param rs the rs + * @param name the name + * @return true, if is exist column + */ + private static boolean isExistColumn(ResultSet rs, String name) { + try { + if (rs.findColumn(name) > 0) { + return true; + } + return false; + } catch (SQLException e) { + return false; + } + } + + /** + * Generate parents change preview sql. + * + * @param conn the conn + * @param userRole the user role + * @param userRoleName the user role name + * @return the list + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private static List generateParentsChangePreviewSql(DBConnection conn, UserRole userRole, + String userRoleName) throws DatabaseCriticalException, DatabaseOperationException { + List previewSqls = new ArrayList<>(); + // firstly, revoke all parents + String currentParentsQuery = "SELECT r.rolname FROM pg_catalog.pg_roles r, pg_catalog.pg_auth_members m" + + " WHERE r.oid = m.roleid AND m.member = ?::oid;"; + ResultSet currentParentsRs = null; + + List newParentNames = new ArrayList<>(); + userRole.getParents().stream().forEach(parent -> newParentNames.add(parent.getName())); + + try { + currentParentsRs = conn.execSelectForSearch(currentParentsQuery, String.valueOf(userRole.getOid())); + // if current parents already contains new parent, don't revoke + while (currentParentsRs.next()) { + String currentParentName = currentParentsRs.getString("rolname"); + if (newParentNames.contains(currentParentName)) { + newParentNames.remove(currentParentName); + continue; + } + String revokeQuery = MessageFormat.format("REVOKE {0} FROM {1};", + ServerObject.getQualifiedObjectName(currentParentsRs.getString("rolname")), + ServerObject.getQualifiedObjectName(userRoleName)); + previewSqls.add(revokeQuery); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + conn.closeResultSet(currentParentsRs); + } + + // secondly grant + List grantQuerys = new ArrayList<>(); + newParentNames.stream() + .forEach(newParentName -> grantQuerys.add(MessageFormat.format("GRANT {0} TO {1};", + ServerObject.getQualifiedObjectName(newParentName), + ServerObject.getQualifiedObjectName(userRoleName)))); + previewSqls.addAll(grantQuerys); + + return previewSqls; + } + } + + /** + * Generate property change preview SQL. + * + * @param conn the conn + * @param userRole the user role + * @param userRoleName the user role name + * @return the list + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public static List generatePropertyChangePreviewSQL(DBConnection conn, UserRole userRole, + String userRoleName) throws MPPDBIDEException { + List previewSqls = new ArrayList<>(); + + if (userRoleName == null) { + return previewSqls; + } + StringBuffer strBuf; + if (userRole.getIsUser()) { + strBuf = new StringBuffer("ALTER USER "); + } else { + strBuf = new StringBuffer("ALTER ROLE "); + } + strBuf.append(ServerObject.getQualifiedObjectName(userRoleName)).append(" "); + String initialStr = strBuf.toString(); + + addConnectionLimitSQLStr(userRole, strBuf); + addValidCluaseSQLStr(userRole, strBuf); + + addResourcePoolSQLStr(userRole, strBuf); + addLoginSQLStr(userRole, strBuf); + addCreateRoleSQLStr(userRole, strBuf); + + addCreateDBSQLStr(userRole, strBuf); + + addSysadminSQLStr(userRole, strBuf); + addAuditAdminSQLStr(userRole, strBuf); + addInheritSQLStr(userRole, strBuf); + addReplicationSQLStr(userRole, strBuf); + + // the order of adding sql is base on lock option + addSqlOnLockOption(userRole, userRoleName, previewSqls, strBuf, initialStr); + + addCommentSQLStr(userRole, userRoleName, previewSqls); + + if (userRole.getParents() != null) { + previewSqls.addAll(UserRoleManagerHidden.generateParentsChangePreviewSql(conn, userRole, userRoleName)); + } + + // Rename SQL should be added at last. + addRenameSQLStr(userRole, userRoleName, previewSqls); + + return previewSqls; + } + + /** + * Adds the rename SQL str. + * + * @param userRole the user role + * @param userRoleName the user role name + * @param previewSqls the preview sqls + */ + public static void addRenameSQLStr(UserRole userRole, String userRoleName, List previewSqls) { + if (StringUtils.isNotEmpty(userRole.getName())) { + String renameSql; + if (userRole.getIsUser()) { + renameSql = MessageFormat.format("ALTER USER {0} RENAME TO {1};", + ServerObject.getQualifiedObjectName(userRoleName), userRole.getQualifiedObjectName()); + } else { + renameSql = MessageFormat.format("ALTER ROLE {0} RENAME TO {1};", + ServerObject.getQualifiedObjectName(userRoleName), userRole.getQualifiedObjectName()); + } + previewSqls.add(renameSql); + } + } + + /** + * Adds the comment SQL str. + * + * @param userRole the user role + * @param userRoleName the user role name + * @param previewSqls the preview sqls + */ + public static void addCommentSQLStr(UserRole userRole, String userRoleName, List previewSqls) { + if (userRole.getComment() != null) { + String commentSql; + if (userRole.getIsUser()) { + commentSql = String.format(Locale.ENGLISH, "COMMENT ON USER %s IS %s;", + ServerObject.getQualifiedObjectName(userRoleName), + ServerObject.getLiteralName(userRole.getComment())); + } else { + commentSql = String.format(Locale.ENGLISH, "COMMENT ON ROLE %s IS %s;", + ServerObject.getQualifiedObjectName(userRoleName), + ServerObject.getLiteralName(userRole.getComment())); + } + previewSqls.add(commentSql); + } + } + + /** + * Adds the sql on lock option. + * + * @param userRole the user role + * @param userRoleName the user role name + * @param previewSqls the preview sqls + * @param strBuf the str buf + * @param initialStr the initial str + */ + public static void addSqlOnLockOption(UserRole userRole, String userRoleName, List previewSqls, + StringBuffer strBuf, String initialStr) { + if (userRole.getIsLock() != null) { + // alter user firstly, lock latter + if (userRole.getIsLock()) { + if (!initialStr.equals(strBuf.toString())) { + previewSqls.add(strBuf.toString() + ";"); + } + if (userRole.getIsUser()) { + previewSqls.add(MessageFormat.format("ALTER USER {0} ACCOUNT LOCK;", + ServerObject.getQualifiedObjectName(userRoleName))); + } else { + previewSqls.add(MessageFormat.format("ALTER ROLE {0} ACCOUNT LOCK;", + ServerObject.getQualifiedObjectName(userRoleName))); + } + } + // unlock firstly, alter user latter + else { + if (userRole.getIsUser()) { + previewSqls.add(MessageFormat.format("ALTER USER {0} ACCOUNT UNLOCK;", + ServerObject.getQualifiedObjectName(userRoleName))); + } else { + previewSqls.add(MessageFormat.format("ALTER ROLE {0} ACCOUNT UNLOCK;", + ServerObject.getQualifiedObjectName(userRoleName))); + } + if (!initialStr.equals(strBuf.toString())) { + previewSqls.add(strBuf.toString() + ";"); + } + } + } else { + if (!initialStr.equals(strBuf.toString())) { + previewSqls.add(strBuf.toString() + ";"); + } + } + } + + /** + * Adds the replication SQL str. + * + * @param userRole the user role + * @param strBuf the str buf + */ + public static void addReplicationSQLStr(UserRole userRole, StringBuffer strBuf) { + if (userRole.getRolReplication() != null) { + if (userRole.getRolReplication()) { + strBuf.append("REPLICATION "); + } else { + strBuf.append("NOREPLICATION "); + } + } + } + + /** + * Adds the inherit SQL str. + * + * @param userRole the user role + * @param strBuf the str buf + */ + public static void addInheritSQLStr(UserRole userRole, StringBuffer strBuf) { + if (userRole.getRolInherit() != null) { + if (userRole.getRolInherit()) { + strBuf.append("INHERIT "); + } else { + strBuf.append("NOINHERIT "); + } + } + } + + /** + * Adds the audit admin SQL str. + * + * @param userRole the user role + * @param strBuf the str buf + */ + public static void addAuditAdminSQLStr(UserRole userRole, StringBuffer strBuf) { + if (userRole.getRolAuditAdmin() != null) { + if (userRole.getRolAuditAdmin()) { + strBuf.append("AUDITADMIN "); + } else { + strBuf.append("NOAUDITADMIN "); + } + } + } + + /** + * Adds the sysadmin SQL str. + * + * @param userRole the user role + * @param strBuf the str buf + */ + public static void addSysadminSQLStr(UserRole userRole, StringBuffer strBuf) { + if (userRole.getRolSystemAdmin() != null) { + if (userRole.getRolSystemAdmin()) { + strBuf.append("SYSADMIN "); + } else { + strBuf.append("NOSYSADMIN "); + } + } + } + + /** + * Adds the create DBSQL str. + * + * @param userRole the user role + * @param strBuf the str buf + */ + public static void addCreateDBSQLStr(UserRole userRole, StringBuffer strBuf) { + if (userRole.getRolCreateDb() != null) { + if (userRole.getRolCreateDb()) { + strBuf.append("CREATEDB "); + } else { + strBuf.append("NOCREATEDB "); + } + } + } + + /** + * Adds the create role SQL str. + * + * @param userRole the user role + * @param strBuf the str buf + */ + public static void addCreateRoleSQLStr(UserRole userRole, StringBuffer strBuf) { + if (userRole.getRolCreateRole() != null) { + if (userRole.getRolCreateRole()) { + strBuf.append("CREATEROLE "); + } else { + strBuf.append("NOCREATEROLE "); + } + } + } + + /** + * Adds the login SQL str. + * + * @param userRole the user role + * @param strBuf the str buf + */ + public static void addLoginSQLStr(UserRole userRole, StringBuffer strBuf) { + if (userRole.getRolCanLogin() != null) { + if (userRole.getRolCanLogin()) { + strBuf.append("LOGIN "); + userRole.setIsUser(true); + } else { + strBuf.append("NOLOGIN "); + userRole.setIsUser(false); + } + } + } + + /** + * Adds the resource pool SQL str. + * + * @param userRole the user role + * @param strBuf the str buf + */ + public static void addResourcePoolSQLStr(UserRole userRole, StringBuffer strBuf) { + if (userRole.getRolResPool() != null && !userRole.getRolResPool().isEmpty()) { + String resourcePoolName = ServerObject.getQualifiedObjectName(userRole.getRolResPool()); + resourcePoolName = resourcePoolName.contains("\"") ? resourcePoolName : "'" + resourcePoolName + "'"; + strBuf.append("RESOURCE POOL ").append(resourcePoolName).append(" "); + } + } + + /** + * Adds the valid cluase SQL str. + * + * @param userRole the user role + * @param strBuf the str buf + */ + public static void addValidCluaseSQLStr(UserRole userRole, StringBuffer strBuf) { + if (userRole.getRolValidBegin() != null) { + String formatBeginDate = new SimpleDateFormat(MPPDBIDEConstants.USER_ROLE_DATE_DISPLAY_FORMAT) + .format(userRole.getRolValidBegin()); + strBuf.append("VALID BEGIN '").append(formatBeginDate).append("' "); + } + if (userRole.getRolValidUntil() != null) { + String formatUntilDate = new SimpleDateFormat(MPPDBIDEConstants.USER_ROLE_DATE_DISPLAY_FORMAT) + .format(userRole.getRolValidUntil()); + strBuf.append("VALID UNTIL '").append(formatUntilDate).append("' "); + } + } + + /** + * Adds the connection limit SQL str. + * + * @param userRole the user role + * @param strBuf the str buf + */ + public static void addConnectionLimitSQLStr(UserRole userRole, StringBuffer strBuf) { + if (userRole.getRolConnLimit() != null) { + strBuf.append("CONNECTION LIMIT ").append(userRole.getRolConnLimit()).append(" "); + } + } + + /** + * Gets the ddl. + * + * @param conn the conn + * @param userRole the user role + * @return the ddl + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static String getDDL(DBConnection conn, UserRole userRole) + throws DatabaseCriticalException, DatabaseOperationException { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + final String rolQry = String.format(Locale.ENGLISH, UserRoleManagerHidden.ROLE_QUERY, userRole.getOid()); + + ResultSet roleResultSet = null; + + try { + roleResultSet = conn.execSelectAndReturnRs(rolQry); + boolean hasNext = roleResultSet.next(); + while (hasNext) { + addCreateRoleStr(userRole, sb, roleResultSet); + + addKeywordsInQuery(sb, roleResultSet); + + if (-1 != roleResultSet.getInt("rolconnlimit")) { + sb.append("CONNECTION LIMIT " + roleResultSet.getInt("rolconnlimit") + " "); + } + + if (null != roleResultSet.getDate("rolvalidbegin")) { + sb.append("VALID BEGIN "); + sb.append("'" + roleResultSet.getDate("rolvalidbegin").toString() + "' "); + } + + if (null != roleResultSet.getDate("rolvaliduntil")) { + sb.append("VALID UNTIL "); + sb.append("'" + roleResultSet.getDate("rolvaliduntil").toString() + "' "); + } + + if (roleResultSet.getString("rolrespool").length() > 0) { + sb.append("RESOURCE POOL "); + sb.append("'" + roleResultSet.getString("rolrespool") + "' "); + } + + hasNext = roleResultSet.next(); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + conn.closeResultSet(roleResultSet); + } + + addMemberDDL(conn, userRole, sb); + + return sb.toString(); + } + + /** + * Adds the keywords in query. + * + * @param sb the sb + * @param roleResultSet the role result set + * @throws SQLException the SQL exception + */ + public static void addKeywordsInQuery(StringBuilder sb, ResultSet roleResultSet) throws SQLException { + if (roleResultSet.getBoolean("rolsystemadmin")) { + sb.append("SYSADMIN "); + } + + if (roleResultSet.getBoolean("rolauditadmin")) { + sb.append("AUDITADMIN "); + } + + if (roleResultSet.getBoolean("rolcreatedb")) { + sb.append("CREATEDB "); + } + + if (roleResultSet.getBoolean("rolcreaterole")) { + sb.append("CREATEROLE "); + } + + if (roleResultSet.getBoolean("rolinherit")) { + sb.append("INHERIT "); + } + + if (roleResultSet.getBoolean("rolcanlogin")) { + sb.append("LOGIN "); + } + + if (roleResultSet.getBoolean("rolreplication")) { + sb.append("REPLICATION "); + } + } + + /** + * Adds the create role str. + * + * @param userRole the user role + * @param sb the sb + * @param roleResultSet the role result set + * @throws SQLException the SQL exception + */ + public static void addCreateRoleStr(UserRole userRole, StringBuilder sb, ResultSet roleResultSet) + throws SQLException { + if (roleResultSet.getBoolean("rolcanlogin")) { + sb.append("CREATE USER "); + sb.append(userRole.getQualifiedObjectName() + " "); + } else { + sb.append("CREATE ROLE "); + sb.append(userRole.getQualifiedObjectName() + " "); + } + } + + /** + * Adds the member DDL. + * + * @param conn the conn + * @param userRole the user role + * @param sb the sb + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static void addMemberDDL(DBConnection conn, UserRole userRole, StringBuilder sb) + throws DatabaseCriticalException, DatabaseOperationException { + final String membershipQuery = String.format(Locale.ENGLISH, UserRoleManagerHidden.MEMBER_QUERY, + userRole.getOid()); + List names = new ArrayList<>(); + List admin = new ArrayList<>(); + + executeMemberShipQuery(conn, membershipQuery, names, admin); + + if (!names.isEmpty()) { + sb.append("ROLE "); + sb.append(String.join(",", names) + " "); + } + + if (!admin.isEmpty()) { + sb.append("ADMIN "); + sb.append(String.join(",", admin) + " "); + } + + sb.append("PASSWORD '********'"); + sb.append(";"); + + sb.append(MPPDBIDEConstants.LINE_SEPARATOR); + + addCommentsInQuery(conn, userRole, sb); + } + + /** + * Adds the comments in query. + * + * @param conn the conn + * @param userRole the user role + * @param sb the sb + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static void addCommentsInQuery(DBConnection conn, UserRole userRole, StringBuilder sb) + throws DatabaseCriticalException, DatabaseOperationException { + + ResultSet descriptionResultSet = null; + try { + final String qry = String.format(Locale.ENGLISH, UserRoleManagerHidden.DESCIPTIONQUERY, userRole.getOid()); + descriptionResultSet = conn.execSelectAndReturnRs(qry); + boolean hasNext = descriptionResultSet.next(); + while (hasNext) { + if (descriptionResultSet.getString("description").length() > 0 + && !(descriptionResultSet.getString("description") == null)) { + sb.append("COMMENT ON ROLE "); + sb.append(userRole.getQualifiedObjectName()); + sb.append(" IS "); + sb.append(null == descriptionResultSet.getString("description") ? "NULL" + : ServerObject.getLiteralName(descriptionResultSet.getString("description"))); + sb.append(";"); + + } + hasNext = descriptionResultSet.next(); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + conn.closeResultSet(descriptionResultSet); + } + } + + /** + * Execute member ship query. + * + * @param conn the conn + * @param membershipQuery the membership query + * @param names the names + * @param admin the admin + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static void executeMemberShipQuery(DBConnection conn, final String membershipQuery, List names, + List admin) throws DatabaseCriticalException, DatabaseOperationException { + ResultSet memberResultSet = null; + + try { + memberResultSet = conn.execSelectAndReturnRs(membershipQuery); + boolean hasNext = memberResultSet.next(); + while (hasNext) { + names.add(memberResultSet.getString("rolname")); + if (memberResultSet.getBoolean("admin_option")) { + admin.add(memberResultSet.getString("rolname")); + } + hasNext = memberResultSet.next(); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + conn.closeResultSet(memberResultSet); + } + } + + /** + * Alter user role. + * + * @param conn the conn + * @param sqls the sqls + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public static void alterUserRole(DBConnection conn, List sqls) throws MPPDBIDEException { + for (String sql : sqls) { + conn.execNonSelect(sql); + } + } + + /** + * Fetch description of user role. + * + * @param conn the conn + * @param userRole the user role + * @return the string + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static String fetchDescriptionOfUserRole(DBConnection conn, UserRole userRole) + throws DatabaseCriticalException, DatabaseOperationException { + String query = "SELECT pg_catalog.shobj_description(?::oid, 'pg_authid') description;"; + ResultSet rs = null; + try { + rs = conn.execSelectForSearch(query, String.valueOf(userRole.getOid())); + while (rs.next()) { + return rs.getString("description"); + } + return null; + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + conn.closeResultSet(rs); + } + } + + /** + * Fetch resource pool. + * + * @param conn the conn + * @return the list + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static List fetchResourcePool(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + List resourcePoolNames = new ArrayList<>(); + String query = "SELECT respool_name FROM pg_resource_pool;"; + ResultSet rs = null; + try { + rs = conn.execSelectAndReturnRs(query); + while (rs.next()) { + resourcePoolNames.add(rs.getString("respool_name")); + } + return resourcePoolNames; + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + conn.closeResultSet(rs); + } + } + + /** + * Checks if is sys admin. + * + * @param conn the conn + * @return true, if is sys admin + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static boolean isSysAdmin(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + String query = "SELECT rolsystemadmin FROM pg_catalog.pg_roles WHERE rolname = user;"; + ResultSet rs = null; + try { + rs = conn.execSelectAndReturnRs(query); + while (rs.next()) { + return rs.getBoolean("rolsystemadmin"); + } + return false; + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + conn.closeResultSet(rs); + } + } + + /** + * Gets the user role name by oid. + * + * @param conn the conn + * @param oid the oid + * @return the user role name by oid + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static String getUserRoleNameByOid(DBConnection conn, long oid) + throws DatabaseCriticalException, DatabaseOperationException { + String query = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid = ?::oid;"; + ResultSet rs = null; + try { + rs = conn.execSelectForSearch(query, String.valueOf(oid)); + while (rs.next()) { + return rs.getString(1); + } + return null; + } catch (SQLException exception) { + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + conn.closeResultSet(rs); + } + } + + /** + * Gets the user or role by oid. + * + * @param conn the conn + * @param oid the oid + * @return the user role name by oid + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static boolean getUserRoleLoginByOid(DBConnection conn, long oid) + throws DatabaseCriticalException, DatabaseOperationException { + String query = "SELECT rolcanlogin FROM pg_catalog.pg_roles WHERE oid = ?::oid;"; + ResultSet rs = null; + try { + rs = conn.execSelectForSearch(query, String.valueOf(oid)); + if (rs.next()) { + return rs.getBoolean(1); + } + return false; + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + conn.closeResultSet(rs); + } + } + + /** + * Fetch lock status of user role. + * + * @param conn the conn + * @param userRole the user role + * @return the boolean + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public static Boolean fetchLockStatusOfUserRole(DBConnection conn, UserRole userRole) throws MPPDBIDEException { + String query = "SELECT rolstatus FROM pg_catalog.pg_user_status WHERE roloid = ?::oid;"; + ResultSet rs = null; + try { + rs = conn.execSelectForSearch(query, String.valueOf(userRole.getOid())); + while (rs.next()) { + if (rs.getInt("rolstatus") != 0) { + return true; + } else { + return false; + } + } + MPPDBIDELoggerUtility.error(MessageConfigLoader + .getProperty(IMessagesConstants.ERR_FETCH_USER_ROLE_LOCK_STATUS, userRole.getOid())); + throw new MPPDBIDEException(IMessagesConstants.ERR_FETCH_USER_ROLE_LOCK_STATUS, userRole.getOid()); + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + conn.closeResultSet(rs); + } + } + + /** + * Copy properties. + * + * @param source the source + * @param destination the destination + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public static void copyProperties(UserRole source, UserRole destination) throws MPPDBIDEException { + destination.setOid(source.getOid()); + destination.setName(source.getName()); + destination.setRolConnLimit(source.getRolConnLimit()); + destination.setRolValidBegin(source.getRolValidBegin()); + destination.setRolValidUntil(source.getRolValidUntil()); + destination.setRolResPool(source.getRolResPool()); + destination.setComment(source.getComment()); + destination.setRolCanLogin(source.getRolCanLogin()); + destination.setRolCreateRole(source.getRolCreateRole()); + destination.setRolCreateDb(source.getRolCreateDb()); + destination.setRolSystemAdmin(source.getRolSystemAdmin()); + destination.setRolAuditAdmin(source.getRolAuditAdmin()); + destination.setRolInherit(source.getRolInherit()); + destination.setRolReplication(source.getRolReplication()); + destination.setIsLock(source.getIsLock()); + destination.setParents(source.getParents()); + } + + /** + * Form create query. + * + * @param userRole the user role + * @return the string + */ + public static String formCreateQuery(UserRole userRole) { + StringBuffer query = new StringBuffer(512); + + /* CREATE */ + query.append("CREATE "); + + appendUserKeyword(userRole, query); + + appendRoleKeyword(userRole, query); + + query.append(userRole.getQualifiedObjectName() + " WITH"); + + query.append(MPPDBIDEConstants.LINE_SEPARATOR).append("\t"); + + appendSysadminPermission(userRole, query); + + appendAuditAdminPermission(userRole, query); + + appendCreateDBPermission(userRole, query); + + appendCreateRolePermission(userRole, query); + + appendInheritPermission(userRole, query); + + appendLoginPermission(userRole, query); + + appendReplicationPermission(userRole, query); + + appendConnectionLimit(userRole, query); + + appendValidity(userRole, query); + + appendResourcePool(userRole, query); + // Add the getQualifiedObjectName in createuserrole class for every + // element + appendRoleSQLStr(userRole, query); + // Add the getQualifiedObjectName in createuserrole class for every + // element + addObjectAdminSQLStr(userRole, query); + + addPasswordSQLStr(userRole, query); + + query.append(";"); + + return query.toString(); + } + + /** + * Adds the password SQL str. + * + * @param userRole the user role + * @param query the query + */ + public static void addPasswordSQLStr(UserRole userRole, StringBuffer query) { + char[] password = userRole.getPasswordInput(); + + query.append("PASSWORD "); + query.append("'").append(password).append("'"); + clear(password); + } + + /** + * Adds the object admin SQL str. + * + * @param userRole the user role + * @param query the query + */ + public static void addObjectAdminSQLStr(UserRole userRole, StringBuffer query) { + if (!userRole.getAdminComo().isEmpty()) { + query.append("ADMIN "); + query.append(userRole.getAdminComo() + " "); + query.append(MPPDBIDEConstants.LINE_SEPARATOR).append("\t"); + } + } + + /** + * Append role SQL str. + * + * @param userRole the user role + * @param query the query + */ + public static void appendRoleSQLStr(UserRole userRole, StringBuffer query) { + if (!userRole.getRoleCombo().isEmpty()) { + query.append("ROLE "); + query.append(userRole.getRoleCombo() + " "); + query.append(MPPDBIDEConstants.LINE_SEPARATOR).append("\t"); + } + } + + /** + * Append resource pool. + * + * @param userRole the user role + * @param query the query + */ + public static void appendResourcePool(UserRole userRole, StringBuffer query) { + if (!userRole.getRolResPool().isEmpty() && !"\"\"".equals(userRole.getRolResPool())) { + query.append("RESOURCE POOL "); + query.append("'" + ServerObject.getQualifiedObjectName(userRole.getRolResPool()) + "' "); + query.append(MPPDBIDEConstants.LINE_SEPARATOR).append("\t"); + } + } + + /** + * Append validity. + * + * @param userRole the user role + * @param query the query + */ + public static void appendValidity(UserRole userRole, StringBuffer query) { + if (null != userRole.getBeginTime() && !(userRole.getBeginTime().equals(""))) { + query.append("VALID BEGIN "); + query.append("'" + userRole.getBeginTime() + "' "); + query.append(MPPDBIDEConstants.LINE_SEPARATOR).append("\t"); + } + + if (null != userRole.getUntilTime() && !(userRole.getUntilTime().equals(""))) { + query.append("VALID UNTIL "); + query.append("'" + userRole.getUntilTime() + "' "); + query.append(MPPDBIDEConstants.LINE_SEPARATOR).append("\t"); + } + } + + /** + * Append connection limit. + * + * @param userRole the user role + * @param query the query + */ + public static void appendConnectionLimit(UserRole userRole, StringBuffer query) { + if (null != userRole.getRolConnLimit() && -1 != userRole.getRolConnLimit()) { + query.append("CONNECTION LIMIT "); + query.append(userRole.getRolConnLimit() + " "); + query.append(MPPDBIDEConstants.LINE_SEPARATOR).append("\t"); + } + } + + /** + * Append replication permission. + * + * @param userRole the user role + * @param query the query + */ + public static void appendReplicationPermission(UserRole userRole, StringBuffer query) { + if (userRole.getRolReplication()) { + query.append("REPLICATION "); + query.append(MPPDBIDEConstants.LINE_SEPARATOR).append("\t"); + } + } + + /** + * Append login permission. + * + * @param userRole the user role + * @param query the query + */ + public static void appendLoginPermission(UserRole userRole, StringBuffer query) { + if (userRole.getRolCanLogin()) { + query.append("LOGIN "); + query.append(MPPDBIDEConstants.LINE_SEPARATOR).append("\t"); + } + } + + /** + * Append inherit permission. + * + * @param userRole the user role + * @param query the query + */ + public static void appendInheritPermission(UserRole userRole, StringBuffer query) { + if (userRole.getRolInherit()) { + query.append("INHERIT "); + query.append(MPPDBIDEConstants.LINE_SEPARATOR).append("\t"); + } + } + + /** + * Append create role permission. + * + * @param userRole the user role + * @param query the query + */ + public static void appendCreateRolePermission(UserRole userRole, StringBuffer query) { + if (userRole.getRolCreateRole()) { + query.append("CREATEROLE "); + query.append(MPPDBIDEConstants.LINE_SEPARATOR).append("\t"); + } + } + + /** + * Append create DB permission. + * + * @param userRole the user role + * @param query the query + */ + public static void appendCreateDBPermission(UserRole userRole, StringBuffer query) { + if (userRole.getRolCreateDb()) { + query.append("CREATEDB "); + query.append(MPPDBIDEConstants.LINE_SEPARATOR).append("\t"); + } + } + + /** + * Append audit admin permission. + * + * @param userRole the user role + * @param query the query + */ + public static void appendAuditAdminPermission(UserRole userRole, StringBuffer query) { + if (userRole.getAuditAdmin()) { + query.append("AUDITADMIN "); + query.append(MPPDBIDEConstants.LINE_SEPARATOR).append("\t"); + } + } + + /** + * Append sysadmin permission. + * + * @param userRole the user role + * @param query the query + */ + public static void appendSysadminPermission(UserRole userRole, StringBuffer query) { + if (userRole.getRolSystemAdmin()) { + query.append("SYSADMIN "); + query.append(MPPDBIDEConstants.LINE_SEPARATOR).append("\t"); + } + } + + /** + * Append role keyword. + * + * @param userRole the user role + * @param query the query + */ + public static void appendRoleKeyword(UserRole userRole, StringBuffer query) { + if (userRole.getRole()) { + query.append("ROLE "); + } + } + + /** + * Append user keyword. + * + * @param userRole the user role + * @param query the query + */ + public static void appendUserKeyword(UserRole userRole, StringBuffer query) { + if (userRole.getUser()) { + query.append("USER "); + } + } + + /** + * Form role comment query. + * + * @param userRole the user role + * @return the string + */ + public static String formRoleCommentQuery(UserRole userRole) { + StringBuffer buff = new StringBuffer(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + if ((null != userRole.getComment()) && (userRole.getComment().length() > 0)) { + buff.append(MPPDBIDEConstants.LINE_SEPARATOR).append(formSetCommentQuery(userRole)); + } + return buff.toString(); + } + + /** + * Form set comment query. + * + * @param userRole the user role + * @return the string + */ + public static String formSetCommentQuery(UserRole userRole) { + + StringBuilder commentQry = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + commentQry.append("COMMENT ON ROLE "); + commentQry.append(userRole.getQualifiedObjectName()); + commentQry.append(" IS "); + commentQry.append(null == userRole.getComment() ? "NULL" : ServerObject.getLiteralName(userRole.getComment())); + commentQry.append(";"); + return commentQry.toString(); + + } + + /** + * Exec create. + * + * @param conn the conn + * @param userRole the user role + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static void execCreate(DBConnection conn, UserRole userRole) + throws DatabaseCriticalException, DatabaseOperationException { + StringBuilder buff = new StringBuilder(formCreateQuery(userRole)).append(formRoleCommentQuery(userRole)); + conn.execNonSelect(buff.toString()); + userRole.clearPwd(); + + } + + /** + * Exec drop. + * + * @param conn the conn + * @param userRole the user role + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static void execDrop(DBConnection conn, UserRole userRole) + throws DatabaseCriticalException, DatabaseOperationException { + String dropQry = null; + if (userRole.getRolCanLogin()) { + dropQry = "DROP USER " + userRole.getQualifiedObjectName() + ";"; + } else { + dropQry = "DROP ROLE " + userRole.getQualifiedObjectName() + ";"; + } + conn.execNonSelect(dropQry); + } + + /** + * Clear. + * + * @param passwordInput the password input + */ + public static void clear(char[] passwordInput) { + for (int index = 0; index < passwordInput.length; index++) { + passwordInput[index] = 0; + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ViewColumnMetaData.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ViewColumnMetaData.java new file mode 100644 index 0000000000000000000000000000000000000000..498a2a587fccdb980cda3b3a89618c7e87b636c1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ViewColumnMetaData.java @@ -0,0 +1,456 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: class + * + * Description: The Class ViewColumnMetaData. + * + */ + +public class ViewColumnMetaData extends ServerObject implements GaussOLAPDBMSObject { + + private String dataTypeSchema; + + private TypeMetaData dataType; + + private int scale; + + private int lenOrPrecision; + + private int arrayNDim; + + private String defaultValue; + + private boolean isNotNull; + + private String checkConstraintExpr; + + private boolean isUnique; + + private boolean isLoaded; + + private ViewMetaData parent; + + private String viewDatatype; + + private static final String QUERY_ALTER_DEFAULT_PREFIX = "ALTER VIEW "; + + private static final String QUERY_ALTER_DEFAULT_COMMAND = " ALTER COLUMN "; + + private static final String QUERY_ALTER_DEFAULT_SETVALUE = " SET DEFAULT "; + + private static final String QUERY_ALTER_DEFAULT_REMOVEVALUE = " DROP DEFAULT "; + + /** + * Instantiates a new view column meta data. + * + * @param view the view + * @param oid the oid + * @param name the name + * @param dataType the data type + */ + public ViewColumnMetaData(ViewMetaData view, long oid, String name, TypeMetaData dataType) { + super(oid, name, OBJECTTYPE.VIEW_COLUMN_METADATA, false); + this.parent = view; + this.dataType = dataType; + this.isLoaded = false; + } + + /** + * Gets the database. + * + * @return the database + */ + @Override + public Database getDatabase() { + return parent.getDatabase(); + } + + /** + * Gets the data type schema. + * + * @return the data type schema + */ + public String getDataTypeSchema() { + return dataTypeSchema; + } + + /** + * Sets the data type schema. + * + * @param dataTypeSchema the new data type schema + */ + public void setDataTypeSchema(String dataTypeSchema) { + this.dataTypeSchema = dataTypeSchema; + } + + /** + * Gets the data type. + * + * @return the data type + */ + public TypeMetaData getDataType() { + return dataType; + } + + /** + * Gets the len or precision. + * + * @return the len or precision + */ + public int getLenOrPrecision() { + return lenOrPrecision; + } + + /** + * Sets the len or precision. + * + * @param lenOrPrecision the new len or precision + */ + public void setLenOrPrecision(int lenOrPrecision) { + this.lenOrPrecision = lenOrPrecision; + } + + /** + * Gets the array N dim. + * + * @return the array N dim + */ + public int getArrayNDim() { + return arrayNDim; + } + + /** + * Sets the array N dim. + * + * @param arrayNDim the new array N dim + */ + public void setArrayNDim(int arrayNDim) { + this.arrayNDim = arrayNDim; + } + + /** + * Gets the scale. + * + * @return the scale + */ + public int getScale() { + return scale; + } + + /** + * Sets the scale. + * + * @param scale the new scale + */ + public void setScale(int scale) { + this.scale = scale; + } + + /** + * Checks if is not null. + * + * @return true, if is not null + */ + public boolean isNotNull() { + return isNotNull; + } + + /** + * Sets the not null. + * + * @param isNotNul the new not null + */ + public void setNotNull(boolean isNotNul) { + this.isNotNull = isNotNul; + } + + /** + * Gets the default value. + * + * @return the default value + */ + public String getDefaultValue() { + return defaultValue; + } + + /** + * Sets the default value. + * + * @param defaultValue the new default value + */ + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + /** + * Gets the check constraint expr. + * + * @return the check constraint expr + */ + public String getCheckConstraintExpr() { + return checkConstraintExpr; + } + + /** + * Sets the check constraint expr. + * + * @param checkConstraintExpr the new check constraint expr + */ + public void setCheckConstraintExpr(String checkConstraintExpr) { + this.checkConstraintExpr = checkConstraintExpr; + } + + /** + * Checks if is unique. + * + * @return true, if is unique + */ + public boolean isUnique() { + return isUnique; + } + + /** + * Sets the unique. + * + * @param isUniqe the new unique + */ + public void setUnique(boolean isUniqe) { + this.isUnique = isUniqe; + } + + /** + * Checks if is loaded. + * + * @return true, if is loaded + */ + public boolean isLoaded() { + return isLoaded; + } + + /** + * Sets the loaded. + * + * @param isLoad the new loaded + */ + public void setLoaded(boolean isLoad) { + this.isLoaded = isLoad; + } + + /** + * Gets the parent. + * + * @return the parent + */ + public ViewMetaData getParent() { + return parent; + } + + /** + * Sets the parent. + * + * @param parent the new parent + */ + public void setParent(ViewMetaData parent) { + this.parent = parent; + } + + /** + * Gets the search name. + * + * @return the search name + */ + @Override + public String getSearchName() { + return getName() + " - " + getParentDetails(); + } + + /** + * Gets the parent details. + * + * @return the parent details + */ + public String getParentDetails() { + String view = getParent().getName(); + String ns = getParent().getNamespace().getName(); + return ns + '.' + view + " - " + getTypeLabel(); + + } + + /** + * Convert to view column meta data. + * + * @param rs the rs + * @param view the view + * @param type the type + * @return the view column meta data + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws SQLException the SQL exception + */ + public static ViewColumnMetaData convertToViewColumnMetaData(ResultSet rs, ViewMetaData view, TypeMetaData type) + throws DatabaseCriticalException, DatabaseOperationException, SQLException { + ViewColumnMetaData viewCol = new ViewColumnMetaData(view, rs.getLong("columnidx"), rs.getString("name"), type); + extractPrecisionScale(rs, viewCol); + viewCol.setArrayNDim(rs.getInt("dimentions")); + viewCol.setNotNull(rs.getBoolean("notnull")); + viewCol.setDefaultValue(rs.getString("default_value")); + viewCol.setLoaded(true); + viewCol.setViewDisplayDatatype(rs.getString("displayColumns")); + return viewCol; + } + + /** + * Sets the view display datatype. + * + * @param viewDatatyp the new view display datatype + */ + private void setViewDisplayDatatype(String viewDatatyp) { + this.viewDatatype = viewDatatyp; + } + + /** + * Gets the view display datatype. + * + * @return the view display datatype + */ + public String getViewDisplayDatatype() { + return viewDatatype; + } + + /** + * Extract precision scale. + * + * @param rs the rs + * @param col the col + * @throws SQLException the SQL exception + */ + public static void extractPrecisionScale(ResultSet rs, ViewColumnMetaData col) throws SQLException { + int len = rs.getInt("length"); + + if (len > 0) { + col.setLenOrPrecision(len); + return; + } + + int precision = rs.getInt("precision"); + if (precision < 0) { + col.setLenOrPrecision(-1); + return; + } + if ("bpchar".equals(col.getDataType().getName()) || "varchar".equals(col.getDataType().getName())) { + precision -= 4; + col.setLenOrPrecision(precision); + } else if ("bit".equals(col.getDataType().getName())) { + col.setLenOrPrecision(precision); + } else { + precision -= 4; + col.setLenOrPrecision(precision >> 16); + col.setScale(precision % (1 << 16)); + } + } + + /** + * Sets the default value. + * + * @param newDefaultValue the new default value + * @param conn the conn + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void setDefaultValue(String newDefaultValue, DBConnection conn) + throws DatabaseOperationException, DatabaseCriticalException { + String query = getSetDefaultValueQuery(newDefaultValue); + conn.execNonSelect(query); + } + + /** + * Gets the sets the default value query. + * + * @param newDefaultValue the new default value + * @return the sets the default value query + */ + public String getSetDefaultValueQuery(String newDefaultValue) { + StringBuilder builder = new StringBuilder(QUERY_ALTER_DEFAULT_PREFIX); + ViewMetaData view = getParent(); + builder.append(view.getNamespace().getQualifiedObjectName()).append('.').append(view.getQualifiedObjectName()) + .append(QUERY_ALTER_DEFAULT_COMMAND).append(getQualifiedObjectName()); + + if (newDefaultValue.trim().isEmpty()) { + builder.append(QUERY_ALTER_DEFAULT_REMOVEVALUE); + } else { + builder.append(QUERY_ALTER_DEFAULT_SETVALUE); + + builder.append(ServerObject.getLiteralName(newDefaultValue)); + + } + + return builder.toString(); + } + + /** + * Gets the clm name with datatype. + * + * @param isParentDescNeeded the is parent desc needed + * @return the clm name with datatype + */ + public String getClmNameWithDatatype(boolean isParentDescNeeded) { + return getName() + " - " + getDataType().getName() + getcolumnPrecisionScale() + + addParentDetails(isParentDescNeeded); + } + + /** + * Adds the parent details. + * + * @param isParentDescNeeded the is parent desc needed + * @return the string + */ + private String addParentDetails(boolean isParentDescNeeded) { + if (isParentDescNeeded) { + return " - " + getParentDetails(); + } + return ""; + } + + /** + * Gets the column precision scale. + * + * @return the column precision scale + */ + private String getcolumnPrecisionScale() { + StringBuilder strBuilder = new StringBuilder(); + if (this.lenOrPrecision > 0) { + strBuilder.append('('); + strBuilder.append(this.lenOrPrecision); + if (0 != this.scale) { + strBuilder.append(','); + strBuilder.append(this.scale); + } + strBuilder.append(')'); + } + return strBuilder.toString(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ViewMetaData.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ViewMetaData.java new file mode 100644 index 0000000000000000000000000000000000000000..48290863b622da5b8d1582e954472750c6af9c27 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ViewMetaData.java @@ -0,0 +1,762 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Locale; +import java.util.SortedMap; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.bl.export.EXPORTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ViewColumnList; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ViewObjectGroup; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class ViewMetaData. + * + */ + +public class ViewMetaData extends BatchDropServerObject implements GaussOLAPDBMSObject, IViewMetaData { + + private Namespace namespace; + private String source; + private String owner; + private ViewColumnList columns; + + private static final String CASCADE = " CASCADE"; + private boolean isLevel3Loaded; + private boolean isLevel3LoadInProgress; + private boolean isViewCodeLoaded; + private ViewManager viewManager; + private Database database; + private String relkind = "v"; + + /** + * Instantiates a new view meta data. + * + * @param oid the oid + * @param name the name + * @param namespace the namespace + */ + public ViewMetaData(long oid, String name, Namespace namespace, Database database) { + super(oid, name, OBJECTTYPE.VIEW_META_DATA, validateNamespace(namespace)); + this.namespace = namespace; + this.columns = new ViewColumnList(this); + this.isViewCodeLoaded = false; + this.viewManager = new ViewManager(); + this.database = database; + } + + private static boolean validateNamespace(Namespace namespace) { + return namespace != null ? namespace.getPrivilegeFlag() : true; + } + + /** + * Gets the namespace. + * + * @return the namespace + */ + public Namespace getNamespace() { + return this.namespace; + } + + /** + * Sets the namespace. + * + * @param namespace the new namespace + */ + public void setNamespace(Namespace namespace) { + this.namespace = namespace; + privilegeFlag = namespace.getPrivilegeFlag(); + } + + /** + * Gets the source. + * + * @return the source + */ + public String getSource() { + return this.source; + } + + /** + * Sets the source. + * + * @param source the new source + */ + public void setSource(String source) { + this.source = source; + } + + /** + * Sets the relkind. + * + * @param relkind the new relkind + */ + public void setRelKind(String relkind) { + if (relkind != null) { + if (!relkind.equals("v")) { + this.relkind = "m"; + } + } + } + + /** + * Gets the relkind. + * + * @return the relkind + */ + public String getRelKind() { + return this.relkind; + } + + /** + * Gets the materview String + * + * @return String materview str + */ + public String getMaterViewString() { + return getRelKind().equals("v") ? "" : "MATERIALIZED "; + } + + /** + * get orReplace String + * + * @return String orReplace str + */ + public String getOrReplaceString() { + return getRelKind().equals("v") ? "OR REPLACE " : ""; + } + + /** + * Gets the owner. + * + * @return the owner + */ + public String getOwner() { + return this.owner; + } + + /** + * Sets the owner. + * + * @param owner the new owner + */ + public void setOwner(String owner) { + this.owner = owner; + } + + /** + * Checks if is level 3 loaded. + * + * @return true, if is level 3 loaded + */ + public boolean isLevel3Loaded() { + return isLevel3Loaded; + } + + /** + * Sets the level 3 loaded. + * + * @param isLvl3Loaded the new level 3 loaded + */ + public void setLevel3Loaded(boolean isLvl3Loaded) { + this.isLevel3Loaded = isLvl3Loaded; + } + + /** + * Checks if is level 3 load in progress. + * + * @return true, if is level 3 load in progress + */ + public boolean isLevel3LoadInProgress() { + return isLevel3LoadInProgress; + } + + /** + * Sets the level 3 load in progress. + * + * @param isLvl3LoadInProgress the new level 3 load in progress + */ + public void setLevel3LoadInProgress(boolean isLvl3LoadInProgress) { + this.isLevel3LoadInProgress = isLvl3LoadInProgress; + } + + @Override + public String getSearchName() { + return getName() + " - " + getNamespace().getName() + " - " + getTypeLabel(); + } + + /** + * Gets the columns. + * + * @return the columns + */ + public ViewColumnList getColumns() { + return this.columns; + } + + /** + * Sets the columns. + * + * @param columns the new columns + */ + public void setColumns(ViewColumnList columns) { + this.columns = columns; + } + + /** + * Gets the ddl. + * + * @param db the db + * @return the ddl + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public String getDDL(Database db) throws MPPDBIDEException { + return viewManager.getDDL(db); + } + + /** + * Gets the display name. + * + * @return the display name + */ + public String getDisplayName() { + return getNamespace().getDisplayName() + '.' + super.getDisplayName(); + } + + /** + * Gets the drop query for OB. + * + * @param isAppendCascade the is append cascade + * @return the drop query for OB + */ + public String getDropQueryForOB(boolean isAppendCascade) { + return viewManager.getDropQueryForOB(isAppendCascade); + } + + /** + * Rename. + * + * @param newName the new name + * @param conn the conn + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void rename(String newName, DBConnection conn) throws DatabaseOperationException, DatabaseCriticalException { + viewManager.rename(newName, conn, this); + } + + /** + * Sets the namespace to. + * + * @param userInput the user input + * @param conn the conn + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void setNamespaceTo(String userInput, DBConnection conn) + throws DatabaseOperationException, DatabaseCriticalException { + viewManager.setNamespaceTo(userInput, conn, this); + } + + /** + * Find matching child object. + * + * @param prefix the prefix + * @return the sorted map + */ + public SortedMap findMatchingChildObject(String prefix) { + return columns.findMatching(prefix); + } + + @Override + public int hashCode() { + return MPPDBIDEConstants.PRIME_31 + Long.valueOf(getOid()).hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (null == obj) { + return false; + } + + if (!(obj instanceof ViewMetaData)) { + return false; + } + + ViewMetaData other = (ViewMetaData) obj; + if (validateObjects(other)) { + return true; + } + + return false; + } + + private boolean validateObjects(ViewMetaData other) { + return this.getOid() == other.getOid() && this.getNamespace().equals(other.getNamespace()); + } + + /** + * Adds the view column. + * + * @param rs the rs + * @param type the type + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws SQLException the SQL exception + */ + public void addViewColumn(ResultSet rs, TypeMetaData type) + throws DatabaseCriticalException, DatabaseOperationException, SQLException { + if (isLevel3Loaded()) { + return; + } + + ViewColumnMetaData viewCol = ViewColumnMetaData.convertToViewColumnMetaData(rs, this, type); + this.getColumns().addItem(viewCol); + } + + /** + * Checks if is view code loaded. + * + * @return true, if is view code loaded + */ + public boolean isViewCodeLoaded() { + return this.isViewCodeLoaded; + } + + /** + * Sets the view code loaded. + * + * @param isViewCodeLoad the new view code loaded + */ + public void setViewCodeLoaded(boolean isViewCodeLoad) { + this.isViewCodeLoaded = isViewCodeLoad; + } + + @Override + public Object[] getChildren() { + Object[] objs = {this.getColumns()}; + return objs; + } + + /** + * Refresh selfdata. + * + * @param conn the conn + * @param isRenameFlow the is rename flow + * @return the view meta data + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public ViewMetaData refreshSelfdata(DBConnection conn, boolean isRenameFlow) + throws DatabaseCriticalException, DatabaseOperationException { + return viewManager.refreshSelfdata(conn, isRenameFlow, this); + } + + /** + * Clear details cached. + */ + private void clearDetailsCached() { + this.getColumns().clear(); + this.setLevel3Loaded(false); + } + + /** + * Fill view properties from RS. + * + * @param rs the rs + * @return true, if successful + * @throws SQLException the SQL exception + */ + private boolean fillViewPropertiesFromRS(ResultSet rs) throws SQLException { + boolean isBasePropertyChanged = false; + String name = rs.getString("viewname"); + if (!name.equals(this.getName())) { + this.setName(name); + isBasePropertyChanged = true; + } + this.setOwner(rs.getString("viewowner")); + this.setViewCodeLoaded(false); + return isBasePropertyChanged; + } + + /** + * Checks if is loaded. + * + * @return true, if is loaded + */ + public boolean isLoaded() { + return super.isLoaded; + } + + @Override + public Database getDatabase() { + return this.database; + } + + /** + * Find all child objects. + * + * @return the sorted map + */ + public SortedMap findAllChildObjects() { + return this.findMatchingChildObject(""); + } + + /** + * Addview to search pool. + * + * @param view the view + */ + public void addviewToSearchPool(ViewMetaData view) { + namespace.addViewInSearchPool(view); + } + + /** + * Adds the views to group. + * + * @param view the view + */ + public void addViewsToGroup(ViewMetaData view) { + namespace.addViewsToGroup(view); + } + + /** + * Fetch view column info. + * + * @param view the view + * @param conn the conn + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void fetchViewColumnInfo(ViewMetaData view, DBConnection conn) + throws DatabaseOperationException, DatabaseCriticalException { + namespace.fetchViewColumnInfo(view, conn); + } + + @Override + public String getDropQuery(boolean isAppendCascade) { + return viewManager.getDropQuery(isAppendCascade); + } + + /** + * Removes the. + * + * @param obj the obj + */ + public void remove(ServerObject obj) { + if (obj instanceof ViewColumnMetaData) { + this.removeColumn(obj); + } + } + + private void removeColumn(ServerObject obj) { + if (columns != null) { + columns.remove((ViewColumnMetaData) obj); + } + } + + @Override + public boolean isExportAllowed(EXPORTTYPE exportType) { + if (exportType == EXPORTTYPE.SQL_DDL) { + return true; + } + return false; + } + + @Override + public String getNamespaceQualifiedName() { + return getNamespace().getQualifiedObjectName(); + } + + @Override + public String getViewPathQualifiedName() { + return getNamespace().getQualifiedObjectName() + '.' + getQualifiedObjectName(); + } + + @Override + public String getNameSpaceName() { + return getNamespace().getName(); + } + + @Override + public ServerObject getParent() { + return getNamespace(); + } + + @Override + public void dropView(DBConnection connection, boolean isAppendCascade) + throws DatabaseOperationException, DatabaseCriticalException { + String query = getDropQueryForOB(isAppendCascade); + connection.execNonSelect(query); + this.getDatabase().getSearchPoolManager().removeViewFromSearchPool(this); + this.getNamespace().removeViewFromGroup(getOid()); + } + + @Override + public boolean isDbConnected() { + return this.getDatabase().isConnected(); + } + + /** + * Checks if view is dropped. + * + * @return true, if view is dropped + */ + public boolean isViewDropped() { + Namespace ns = this.getNamespace(); + if (null == ns) { + return true; + } + return ns.validateView(getOid()); + } + + private class ViewManager { + /** + * getDropQuery + * + * @param isAppendCascade boolean + * @return string object + */ + public String getDropQuery(boolean isAppendCascade) { + String dropQuery = String.format(Locale.ENGLISH, + "DROP %sVIEW IF EXISTS ", + getMaterViewString()); + StringBuilder query = new StringBuilder(dropQuery); + query.append(getNamespace().getQualifiedObjectName()).append('.').append(getQualifiedObjectName()); + + if (isAppendCascade) { + query.append(CASCADE); + } + + return query.toString(); + } + + /** + * Refresh selfdata. + * + * @param conn the conn + * @param isRenameFlow the is rename flow + * @return the view meta data + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public ViewMetaData refreshSelfdata(DBConnection conn, boolean isRenameFlow, ViewMetaData viewMetaData) + throws DatabaseCriticalException, DatabaseOperationException { + boolean privilegeFilter = privilegeFlag && !isRenameFlow; + String query = ViewUtils.getViewQuery(viewMetaData.getOid(), privilegeFilter); + ResultSet rs = null; + boolean hasNext = false; + + try { + rs = conn.execSelectAndReturnRs(query); + hasNext = rs.next(); + if (hasNext) { + // the cleared details[column] will loaded after this + // method,where column details are got. + viewMetaData.clearDetailsCached(); + viewMetaData.setNamespace(getUpdatedNamespaceForView(rs)); + viewMetaData.fillViewPropertiesFromRS(rs); + } else { + return null; + } + } catch (SQLException exception) { + GaussUtils.handleCriticalException(exception); + + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + conn.closeResultSet(rs); + } + return viewMetaData; + } + + /** + * Gets the updated namespace for view. + * + * @param rs the rs + * @return the updated namespace for view + * @throws DatabaseOperationException the database operation exception + */ + private Namespace getUpdatedNamespaceForView(ResultSet rs) throws DatabaseOperationException { + Namespace ns = null; + try { + long nsID = rs.getLong("nspoid"); + ns = getDatabase().getNameSpaceById(nsID); + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } + return ns; + } + + /** + * Rename. + * + * @param newName the new name + * @param conn the conn + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void rename(String newName, DBConnection conn, ViewMetaData viewMetaData) + throws DatabaseOperationException, DatabaseCriticalException { + String query = getRenameQuery(newName); + conn.execNonSelect(query); + getNamespace().refreshView(viewMetaData, conn, true); + } + + /** + * Sets the namespace to. + * + * @param userInput the user input + * @param conn the conn + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void setNamespaceTo(String userInput, DBConnection conn, ViewMetaData viewMetaData) + throws DatabaseOperationException, DatabaseCriticalException { + String query = getSchemaSetQuery(userInput); + conn.execNonSelect(query); + getNamespace().refreshView(viewMetaData, conn, false); + } + + /** + * Gets the schema set query. + * + * @param newSchemaName the new schema name + * @return the schema set query + */ + private String getSchemaSetQuery(String newSchemaName) { + return String.format(Locale.ENGLISH, "ALTER %sVIEW %s.%s" + " SET schema %s;", + getMaterViewString(), + getNamespace().getQualifiedObjectName(), getQualifiedObjectName(), + ServerObject.getQualifiedObjectName(newSchemaName)); + + } + + /** + * Gets the rename query. + * + * @param newName the new name + * @return the rename query + */ + private String getRenameQuery(String newName) { + String qry = String.format(Locale.ENGLISH, "ALTER %sVIEW %s.%s RENAME TO %s;", + getMaterViewString(), + getNamespace().getQualifiedObjectName(), getQualifiedObjectName(), + ServerObject.getQualifiedObjectName(newName)); + return qry; + } + + /** + * Gets the drop query for OB. + * + * @param isAppendCascade the is append cascade + * @return the drop query for OB + */ + public String getDropQueryForOB(boolean isAppendCascade) { + String dropQuery = String.format(Locale.ENGLISH, "DROP %sVIEW %s.%s ", + getMaterViewString(), + getNamespace().getQualifiedObjectName(), + getQualifiedObjectName()); + StringBuilder query = new StringBuilder(dropQuery); + + if (isAppendCascade) { + query.append(CASCADE); + } + + return query.toString(); + } + + /** + * Gets the ddl. + * + * @param db the db + * @return the ddl + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public String getDDL(Database db) throws MPPDBIDEException { + if (!isViewCodeLoaded()) { + fetchDDL(db); + } + + StringBuilder strbldr = getViewTemplate(); + return strbldr.toString(); + } + + private StringBuilder getViewTemplate() { + StringBuilder strbldr = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + if (isViewCodeLoaded()) { + strbldr.append(String.format(Locale.ENGLISH, "CREATE %s%sVIEW ", + getOrReplaceString(), getMaterViewString())); + strbldr.append(namespace.getQualifiedObjectName()).append(".").append(getQualifiedObjectName()) + .append(System.lineSeparator()).append("\tAS ").append(System.lineSeparator()) + .append(getSource()); + } + return strbldr; + } + + /** + * Fetch DDL. + * + * @param db the db + * @throws MPPDBIDEException the MPPDBIDE exception + */ + private void fetchDDL(Database db) throws MPPDBIDEException { + DBConnection conn = db.getConnectionManager().getFreeConnection(); + ResultSet rs = null; + try { + rs = fetchViewDDLTemplate(conn); + } catch (SQLException exception) { + GaussUtils.handleCriticalException(exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + conn.closeResultSet(rs); + db.getConnectionManager().releaseConnection(conn); + } + } + + private ResultSet fetchViewDDLTemplate(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException, SQLException { + String fetchSiurceCodeQuery = String.format(Locale.ENGLISH, "SELECT * FROM pg_get_viewdef('%s')", + getDisplayName()); + ResultSet rs = conn.execSelectAndReturnRs(fetchSiurceCodeQuery); + boolean hasNext = rs.next(); + if (hasNext) { + setSource(rs.getString(1)); + setViewCodeLoaded(true); + } + return rs; + } + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ViewUtils.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ViewUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..184d09926e7a3c81134cd97f75a08951223a28c0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/ViewUtils.java @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: ViewUtils + * + * + */ + +public class ViewUtils { + /** + * Convert to view meta data. + * + * @param rs the rs + * @param parentNamespace the parent namespace + * @return the view meta data + * @throws DatabaseOperationException the database operation exception + * @throws OutOfMemoryError the out of memory error + */ + public static ViewMetaData convertToViewMetaData(ResultSet rs, Namespace parentNamespace) + throws DatabaseOperationException, OutOfMemoryError { + ViewMetaData view = null; + + try { + long oid = rs.getLong("oid"); + String name = rs.getString("viewname"); + view = new ViewMetaData(oid, name, parentNamespace, parentNamespace.getDatabase()); + view.setOwner(rs.getString("viewowner")); + view.setRelKind(rs.getString("relkind")); + return view; + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Error while converting view data from resultset.", exception); + throw new DatabaseOperationException("Error while converting view data from resultset.", exception); + } + } + + /** + * Fetch views. + * + * @param parentNamespace the parent namespace + * @param query the query + * @param conn the conn + * @return the view meta data + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static ViewMetaData fetchViews(Namespace parentNamespace, String query, DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + ResultSet rs = null; + boolean hasNext = false; + ViewMetaData view = null; + try { + rs = conn.execSelectAndReturnRs(query); + hasNext = rs.next(); + view = addAllViews(parentNamespace, rs, hasNext); + } catch (SQLException exception) { + GaussUtils.handleCriticalException(exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + conn.closeResultSet(rs); + } + return view; + } + + private static ViewMetaData addAllViews(Namespace parentNamespace, ResultSet rs, boolean hasNextParam) + throws DatabaseOperationException, OutOfMemoryError, SQLException { + Namespace ns = null; + ViewMetaData view = null; + boolean hasNext = hasNextParam; + while (hasNext) { + view = ViewUtils.convertToViewMetaData(rs, parentNamespace); + view.setLoaded(false); + ns = view.getNamespace(); + ns.addView(view); + hasNext = rs.next(); + } + return view; + } + + /** + * Convert to view meta data on demand. + * + * @param rs the rs + * @param db the db + * @return the view meta data + * @throws DatabaseOperationException the database operation exception + * @throws OutOfMemoryError the out of memory error + */ + public static ViewMetaData convertToViewMetaDataOnDemand(ResultSet rs, Database db) + throws DatabaseOperationException, OutOfMemoryError { + ViewMetaData view = null; + + try { + long namespaceId = rs.getLong("relnamespace"); + Namespace namespace = db.getNameSpaceById(namespaceId); + + long oid = rs.getLong("oid"); + String name = rs.getString("relname"); + view = new ViewMetaData(oid, name, namespace, namespace.getDatabase()); + view.setViewCodeLoaded(false); + view.setRelKind(rs.getString("relkind")); + return view; + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Error while converting view data from resultset.", exception); + throw new DatabaseOperationException("Error while converting view data from resultset.", exception); + } + } + + /** + * Gets the view query by namespace id. + * + * @param oid the oid + * @param privilegeFlag the privilege flag + * @return the view query by namespace id + */ + public static String getViewQueryByNamespaceId(long oid, boolean privilegeFlag) { + String queryBySchema = String.format(Locale.ENGLISH, + "SELECT c.oid, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner " + + ", c.relkind as relkind " + + "FROM pg_class c WHERE (c.relkind = 'v'::char or c.relkind = 'm'::char) " + + "and " + "c.relnamespace = %d", + oid); + return TableMetaData.formQueryForTableMetadata(queryBySchema, false, privilegeFlag); + } + + /** + * Gets the view query. + * + * @param oid the oid + * @param privilegeFlag the privilege flag + * @return the view query + */ + public static String getViewQuery(long oid, boolean privilegeFlag) { + String query = String.format(Locale.ENGLISH, + "SELECT c.oid, n.oid as nspoid, n.nspname AS schemaname, c.relname AS viewname, " + + "pg_get_userbyid(c.relowner) AS viewowner " + + "FROM (pg_class c LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace))) " + + "WHERE (c.relkind = 'v'::\"char\" or c.relkind = 'm'::\"char\") " + "and c.oid=%d", + oid); + return TableMetaData.formQueryForTableMetadata(query, false, privilegeFlag); + } + + /** + * Gets the creates the view template. + * + * @param ns the ns + * @return the creates the view template + */ + public static String getCreateViewTemplate(Namespace ns) { + StringBuilder strbldr = new StringBuilder("CREATE (OR REPLACE) [ TEMP | TEMPORARY | MATERIALIZED ] VIEW "); + strbldr.append(ns.getQualifiedObjectName()).append(".").append("") + .append(" [ ( column_name [, ...] ) ] ").append(System.lineSeparator()) + .append("[ WITH ( {view_option_name [= view_option_value]} [, ... ] ) ]").append(System.lineSeparator()) + .append("\tAS ").append(System.lineSeparator()).append("").append(";"); + return strbldr.toString(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/AdvancedServerConnectionInfo.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/AdvancedServerConnectionInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..4a6d39a300d6e2dad004d4c19a25a5fcc262adb6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/AdvancedServerConnectionInfo.java @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.connectioninfo; + +import java.util.LinkedHashSet; +import java.util.Set; + +import com.google.gson.annotations.Expose; + +/** + * + * Title: class + * + * Description: The Class AdvancedServerConnectionInfo. + * + */ + +public final class AdvancedServerConnectionInfo { + + @Expose + private Set schemaExclusionList = new LinkedHashSet(); + @Expose + private Set schemaInclusionList = new LinkedHashSet(); + @Expose + private int loadLimit = 0; + @Expose + private boolean privilegeBasedObAcess; + private Set modifiedSchemaExclusionList = new LinkedHashSet(); + private Set modifiedSchemaInclusionList = new LinkedHashSet(); + @Expose + private boolean canLoadChildObj = true; + + /** + * Gets the schema exclusion list. + * + * @return the schema exclusion list + */ + public Set getSchemaExclusionList() { + return new LinkedHashSet(schemaExclusionList); + } + + /** + * Sets the schema exclusion list. + * + * @param schemaExclusionList the new schema exclusion list + */ + public void setSchemaExclusionList(Set schemaExclusionList) { + this.schemaExclusionList = schemaExclusionList; + this.modifiedSchemaExclusionList.addAll(this.schemaExclusionList); + } + + /** + * Gets the schema inclusion list. + * + * @return the schema inclusion list + */ + public Set getSchemaInclusionList() { + return new LinkedHashSet(schemaInclusionList); + } + + /** + * Sets the schema inclusion list. + * + * @param schemaInclusionList the new schema inclusion list + */ + public void setSchemaInclusionList(Set schemaInclusionList) { + this.schemaInclusionList = schemaInclusionList; + this.modifiedSchemaInclusionList.addAll(this.schemaInclusionList); + } + + /** + * Gets the load limit. + * + * @return the load limit + */ + public int getLoadLimit() { + return loadLimit; + } + + /** + * Sets the load limit. + * + * @param loadLimit the new load limit + */ + public void setLoadLimit(int loadLimit) { + this.loadLimit = loadLimit; + } + + /** + * Checks if is privilege based ob acess. + * + * @return true, if is privilege based ob acess + */ + public boolean isPrivilegeBasedObAcess() { + return privilegeBasedObAcess; + } + + /** + * Sets the privilege based ob acess. + * + * @param privilegeBasedObAcess the new privilege based ob acess + */ + public void setPrivilegeBasedObAcess(boolean privilegeBasedObAcess) { + this.privilegeBasedObAcess = privilegeBasedObAcess; + } + + /** + * getModifiedSchemaExclusionList + * + * @return schema list value + */ + public Set getModifiedSchemaExclusionList() { + return modifiedSchemaExclusionList; + } + + /** + * setModifiedSchemaExclusionList + * + * @param modifiedSchemaExclusionList set value + */ + public void setModifiedSchemaExclusionList(Set modifiedSchemaExclusionList) { + this.modifiedSchemaExclusionList = modifiedSchemaExclusionList; + } + + /** + * getModifiedSchemaInclusionList + * + * @return schema list value + */ + public Set getModifiedSchemaInclusionList() { + return modifiedSchemaInclusionList; + } + + /** + * setModifiedSchemaInclusionList + * + * @param modifiedSchemaInclusionList set value + */ + public void setModifiedSchemaInclusionList(Set modifiedSchemaInclusionList) { + this.modifiedSchemaInclusionList = modifiedSchemaInclusionList; + } + + /** + * isCanLoadChildObj + * + * @return isCanLoadChildObj can load child obj + */ + public boolean isCanLoadChildObj() { + return canLoadChildObj; + } + + /** + * setCanLoadChildObj + * + * @param canLoadChildObj param can load child obj + */ + public void setCanLoadChildObj(boolean canLoadChildObj) { + this.canLoadChildObj = canLoadChildObj; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/DBTYPE.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/DBTYPE.java new file mode 100644 index 0000000000000000000000000000000000000000..557eabe5d374eb283c97cf1e9d0e337390fb03cc --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/DBTYPE.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.connectioninfo; + +/** + * Title: DBTYPE + * + */ + +public enum DBTYPE { + OPENGAUSS +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/GeneralServerConnectionInfo.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/GeneralServerConnectionInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..563f629bc35101204f6c8015c8487d638a2c667c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/GeneralServerConnectionInfo.java @@ -0,0 +1,254 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.connectioninfo; + +import com.google.gson.annotations.Expose; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.utils.security.SecureUtil; + +/** + * + * Title: class + * + * Description: The Class GeneralServerConnectionInfo. + */ + +public final class GeneralServerConnectionInfo { + + @Expose + private String conectionName; + @Expose + private String databaseName; + @Expose + private char[] prd; + @Expose + private boolean isSSLEnabled; + @Expose + private String serverIp; + @Expose + private int serverPort; + @Expose + private String username; + @Expose + private DBTYPE dbType; + @Expose + private SavePrdOptions savePrdOption; + @Expose + private String connctionDriverName; + + /** + * Instantiates a new general server connection info. + */ + public GeneralServerConnectionInfo() { + this.conectionName = ""; + this.databaseName = ""; + this.prd = new char[0]; + this.serverIp = ""; + this.username = ""; + this.savePrdOption = SavePrdOptions.DO_NOT_SAVE; + } + + /** + * Gets the conection name. + * + * @return the conection name + */ + public String getConectionName() { + return conectionName; + } + + /** + * Sets the conection name. + * + * @param conectionName the new conection name + */ + public void setConectionName(String conectionName) { + this.conectionName = conectionName; + } + + /** + * Gets the database name. + * + * @return the database name + */ + public String getDatabaseName() { + return databaseName; + } + + /** + * Sets the database name. + * + * @param databaseName the new database name + */ + public void setDatabaseName(String databaseName) { + this.databaseName = databaseName; + } + + /** + * Gets the prd. + * + * @return the prd + */ + public char[] getPrd() { + if (this.prd == null) { + return new char[0]; + } + return prd.clone(); + } + + /** + * Sets the prd. + * + * @param prd the new prd + */ + public void setPrd(char[] prd) { + this.prd = prd.clone(); + } + + /** + * Checks if is SSL enabled. + * + * @return true, if is SSL enabled + */ + public boolean isSSLEnabled() { + return isSSLEnabled; + } + + /** + * Sets the SSL enabled. + * + * @param isSSLEnable the new SSL enabled + */ + public void setSSLEnabled(boolean isSSLEnable) { + this.isSSLEnabled = isSSLEnable; + } + + /** + * Gets the server ip. + * + * @return the server ip + */ + public String getServerIp() { + return serverIp; + } + + /** + * Sets the server ip. + * + * @param serverIp the new server ip + */ + public void setServerIp(String serverIp) { + this.serverIp = serverIp; + } + + /** + * Gets the server port. + * + * @return the server port + */ + public int getServerPort() { + return serverPort; + } + + /** + * Sets the server port. + * + * @param serverPort the new server port + */ + public void setServerPort(int serverPort) { + this.serverPort = serverPort; + } + + /** + * Gets the username. + * + * @return the username + */ + public String getUsername() { + return username; + } + + /** + * Sets the username. + * + * @param username the new username + */ + public void setUsername(String username) { + this.username = username; + } + + /** + * Gets the db type. + * + * @return the db type + */ + public DBTYPE getDatabaseType() { + return dbType; + } + + /** + * Sets the db type. + * + * @param dbType the new db type + */ + public void setDbType(DBTYPE dbType) { + this.dbType = dbType; + } + + /** + * Gets the save prd option. + * + * @return the save prd option + */ + public SavePrdOptions getSavePrdOption() { + return savePrdOption; + } + + /** + * Sets the save prd option. + * + * @param savePrdOption the new save prd option + */ + public void setSavePrdOption(SavePrdOptions savePrdOption) { + this.savePrdOption = savePrdOption; + } + + /** + * Gets the connction driver name. + * + * @return the connction driver name + */ + public String getConnctionDriverName() { + return connctionDriverName; + } + + /** + * Sets the connction driver name. + * + * @param connctionDriverName the new connction driver name + */ + public void setConnctionDriverName(String connctionDriverName) { + this.connctionDriverName = connctionDriverName; + } + + /** + * Clear pssrd. + */ + public void clearPssrd() { + SecureUtil.clearPassword(this.prd); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/SSLServerConnectionInfo.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/SSLServerConnectionInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..39af758a46afda94f4ca8913d5938dc2cb2d8e63 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/SSLServerConnectionInfo.java @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.connectioninfo; + +import com.google.gson.annotations.Expose; +import org.opengauss.mppdbide.utils.security.SecureUtil; + +/** + * + * Title: class + * + * Description: The Class SSLServerConnectionInfo. + * + */ + +public final class SSLServerConnectionInfo { + + @Expose + private String clSSLCertificatePath; + @Expose + private String clSSLKeyPath; + @Expose + private char[] sslPrd; + @Expose + private String rootCertFilePathText; + @Expose + private String sslMode; + + @Expose(deserialize = false, serialize = false) + private String clSSLPrivateKeyFile = ""; + + /** + * Gets the cl SSL certificate path. + * + * @return the cl SSL certificate path + */ + public String getClSSLCertificatePath() { + return clSSLCertificatePath; + } + + /** + * Sets the cl SSL certificate path. + * + * @param clSSLCertificatePath the new cl SSL certificate path + */ + public void setClSSLCertificatePath(String clSSLCertificatePath) { + this.clSSLCertificatePath = clSSLCertificatePath; + } + + /** + * Gets the cl SSL key path. + * + * @return the cl SSL key path + */ + public String getClSSLKeyPath() { + return clSSLKeyPath; + } + + /** + * Sets the cl SSL key path. + * + * @param clSSLKeyPath the new cl SSL key path + */ + public void setClSSLKeyPath(String clSSLKeyPath) { + this.clSSLKeyPath = clSSLKeyPath; + } + + /** + * Gets the ssl prd. + * + * @return the ssl prd + */ + public char[] getSSLPsrd() { + if (sslPrd == null) { + return new char[0]; + } + return sslPrd.clone(); + } + + /** + * Sets the ssl prd. + * + * @param sslPrd the new ssl prd + */ + public void setSSLPsrd(char[] sslPrd) { + this.sslPrd = sslPrd.clone(); + } + + /** + * Gets the root cert file path text. + * + * @return the root cert file path text + */ + public String getRootCertFilePathText() { + return rootCertFilePathText; + } + + /** + * Sets the root cert file path text. + * + * @param rootCertFilePathText the new root cert file path text + */ + public void setRootCertFilePathText(String rootCertFilePathText) { + this.rootCertFilePathText = rootCertFilePathText; + } + + /** + * Gets the ssl mode. + * + * @return the ssl mode + */ + public String getSSLMode() { + return sslMode; + } + + /** + * Sets the ssl mode. + * + * @param sslMode the new ssl mode + */ + public void setSSLMode(String sslMode) { + this.sslMode = sslMode; + } + + /** + * Gets the cl SSL private key file. + * + * @return the cl SSL private key file + */ + public String getClSSLPrivateKeyFile() { + return clSSLPrivateKeyFile; + } + + /** + * Sets the cl SSL private key file. + * + * @param clSSLPrivateKeyFile the new cl SSL private key file + */ + public void setClSSLPrivateKeyFile(String clSSLPrivateKeyFile) { + this.clSSLPrivateKeyFile = clSSLPrivateKeyFile; + } + + /** + * Clear SSL pssrd. Clear SSL pssrd. + */ + + public void clearSSLPssrd() { + SecureUtil.clearPassword(this.sslPrd); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/ServerConnectionInfo.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/ServerConnectionInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..595fcf3e1e0417bd40927e64c6509f263be6f06e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/ServerConnectionInfo.java @@ -0,0 +1,616 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.connectioninfo; + +import java.nio.charset.Charset; +import java.text.Normalizer; +import java.util.Properties; +import java.util.Set; + +import org.apache.commons.lang3.StringUtils; + +import com.google.gson.annotations.Expose; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.bl.util.BLUtils; +import org.opengauss.mppdbide.utils.CustomStringUtility; +import org.opengauss.mppdbide.utils.DsEncodingEnum; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.connectionprofileversion.IConnectionProfileVersions; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class ServerConnectionInfo. + * + */ + +public class ServerConnectionInfo implements IServerConnectionInfo { + + @Expose + private String profileId; + + private static final int DEFAULT_OBJECT_LOAD_THRESHOLD = 30000; + @Expose + private String databaseVersion = ""; + @Expose + private DBTYPE dbType; + @Expose + private String version; + @Expose + private GeneralServerConnectionInfo general; + @Expose + private SSLServerConnectionInfo ssl; + @Expose + private AdvancedServerConnectionInfo advanced; + + /** + * Instantiates a new server connection info. + */ + public ServerConnectionInfo() { + super(); + this.version = IConnectionProfileVersions.CONNECTION_PROFILE_CURRENT_VERSION; + general = new GeneralServerConnectionInfo(); + ssl = new SSLServerConnectionInfo(); + advanced = new AdvancedServerConnectionInfo(); + } + + @Override + public String getVersion() { + return version; + } + + /** + * Gets the clone. + * + * @return the clone + * org.opengauss.mppdbide.bl.serverdatacache.IServerConnectionInfo#getClone() + */ + + @Override + public ServerConnectionInfo getClone() { + ServerConnectionInfo newInfo = new ServerConnectionInfo(); + newInfo.setConectionName(getConectionName()); + newInfo.setDatabaseName(getDatabaseName()); + newInfo.setSSLEnabled(isSSLEnabled()); + newInfo.setServerIp(getServerIp()); + newInfo.setServerPort(getServerPort()); + newInfo.setSavePrdOption(getSavePrdOption()); + newInfo.setUsername(getDsUsername()); + newInfo.setClientSSLCertificate(getClientSSLCertificate()); + newInfo.setClientSSLKey(getClientSSLKey()); + newInfo.setRootCertificate(getRootCertificate()); + newInfo.setSSLMode(getSSLMode()); + newInfo.setProfileId(this.getProfileId()); + newInfo.setSchemaExclusionList(getSchemaExclusionList()); + newInfo.setSchemaInclusionList(getSchemaInclusionList()); + newInfo.setCanLoadChildObjects(canLoadChildObjects()); + newInfo.setLoadLimit(getLoadLimit()); + newInfo.setDBVersion(this.databaseVersion); + newInfo.setPrivilegeBasedObAccess(isPrivilegeBasedObAccessEnabled()); + newInfo.setDriverName(getDriverName()); + newInfo.setPrd(new char[0]); + newInfo.setSSLPrd(new char[0]); + newInfo.setClientSSLPrivateKey(getClientSSLPrivateKey()); + newInfo.setModifiedSchemaExclusionList(getModifiedSchemaExclusionList()); + newInfo.setModifiedSchemaInclusionList(getModifiedSchemaInclusionList()); + return newInfo; + } + + /** + * Gets the conection name. + * + * @return the conection name + * org.opengauss.mppdbide.bl.serverdatacache.IServerConnectionInfo# + * getConectionName () + */ + + @Override + public String getConectionName() { + return general.getConectionName(); + } + + /** + * Sets the conection name. + * + * @param conectionName the new conection name + * org.opengauss.mppdbide.bl.serverdatacache.IServerConnectionInfo# + * setConectionName (java.lang.String) + */ + @Override + public void setConectionName(String conectionName) { + general.setConectionName(Normalizer.normalize(conectionName, Normalizer.Form.NFD)); + } + + /** + * Gets the database name. + * + * @return the database name + * org.opengauss.mppdbide.bl.serverdatacache.IServerConnectionInfo# + * getDatabaseName () + */ + @Override + public String getDatabaseName() { + return this.general.getDatabaseName(); + } + + /** + * Sets the database name. + * + * @param databaseName the new database name + * org.opengauss.mppdbide.bl.serverdatacache.IServerConnectionInfo# + * setDatabaseName (java.lang.String) + */ + @Override + public void setDatabaseName(String databaseName) { + this.general.setDatabaseName(databaseName); + } + + /** + * Gets the prd. + * + * @return the prd + * org.opengauss.mppdbide.bl.serverdatacache.IServerConnectionInfo#getPrd () + */ + @Override + public char[] getPrd() { + return (char[]) this.general.getPrd(); + } + + /** + * Sets the prd. + * + * @param prd the new prd + * org.opengauss.mppdbide.bl.serverdatacache.IServerConnectionInfo#setPrd + * (char[]) + */ + public void setPrd(char[] prd) { + this.general.setPrd(prd); + } + + @Override + public void clearPasrd() { + this.general.clearPssrd(); + this.ssl.clearSSLPssrd(); + } + + /** + * Gets the server ip. + * + * @return the server ip + * org.opengauss.mppdbide.bl.serverdatacache.IServerConnectionInfo#getServerIp + */ + + @Override + public String getServerIp() { + return this.general.getServerIp(); + } + + /** + * Sets the server ip. + * + * @param serverIp the new server ip + * org.opengauss.mppdbide.bl.serverdatacache.IServerConnectionInfo#setServerIp + * (java.lang.String) + */ + @Override + public void setServerIp(String serverIp) { + this.general.setServerIp(serverIp); + } + + /** + * Gets the server port. + * + * @return the server port + * org.opengauss.mppdbide.bl.serverdatacache.IServerConnectionInfo# + * getServerPort () + */ + + @Override + public int getServerPort() { + return this.general.getServerPort(); + } + + /** + * Sets the server port. + * + * @param serverPort the new server port + * org.opengauss.mppdbide.bl.serverdatacache.IServerConnectionInfo# + * setServerPort (int) + */ + @Override + public void setServerPort(int serverPort) { + this.general.setServerPort(serverPort); + } + + /** + * Gets the ds username. + * + * @return the ds username + * org.opengauss.mppdbide.bl.serverdatacache.IServerConnectionInfo#getUsername + */ + @Override + public String getDsUsername() { + return this.general.getUsername(); + } + + /** + * Sets the username. + * + * @param username the new username + * org.opengauss.mppdbide.bl.serverdatacache.IServerConnectionInfo#setUsername + * (java.lang.String) + */ + @Override + public void setUsername(String username) { + this.general.setUsername(username); + } + + @Override + public boolean isPrivilegeBasedObAccessEnabled() { + return this.advanced.isPrivilegeBasedObAcess(); + } + + @Override + public boolean isSSLEnabled() { + return this.general.isSSLEnabled(); + } + + /** + * Sets the SSL enabled. + * + * @param isSSLEnabld the new SSL enabled + * org.opengauss.mppdbide.bl.serverdatacache.IServerConnectionInfo# + * setSSLEnabled (boolean) + */ + @Override + public void setSSLEnabled(boolean isSSLEnabld) { + this.general.setSSLEnabled(isSSLEnabld); + } + + /** + * Gets the client SSL certificate. + * + * @return the client SSL certificate + */ + public String getClientSSLCertificate() { + return this.ssl.getClSSLCertificatePath(); + } + + /** + * Sets the client SSL certificate. + * + * @param clSSLCertificate the new client SSL certificate + */ + public void setClientSSLCertificate(String clSSLCertificate) { + this.ssl.setClSSLCertificatePath(clSSLCertificate); + } + + /** + * Gets the client SSL key. + * + * @return the client SSL key + */ + public String getClientSSLKey() { + return this.ssl.getClSSLKeyPath(); + } + + /** + * Sets the client SSL key. + * + * @param clSSLKey the new client SSL key + */ + public void setClientSSLKey(String clSSLKey) { + this.ssl.setClSSLKeyPath(clSSLKey); + } + + /** + * Sets the save prd option. + * + * @param savePrdOption the new save prd option + * org.opengauss.mppdbide.bl.serverdatacache.IServerConnectionInfo# + * setSavePrdOption + * (org.opengauss.mppdbide.bl.serverdatacache.Server.SAVE_PRD_OPTIONS) + */ + @Override + public void setSavePrdOption(SavePrdOptions savePrdOption) { + this.general.setSavePrdOption(savePrdOption); + } + + /** + * Sets the save prd option. + * + * @param selIndex the sel index + * @param isPermanentPrdReq the is permanent prd req + * org.opengauss.mppdbide.bl.serverdatacache.IServerConnectionInfo# + * setSavePrdOption(int) + */ + @Override + public void setSavePrdOption(int selIndex, boolean isPermanentPrdReq) { + if (isPermanentPrdReq) { + switch (selIndex) { + case 0: { + setSavePrdOption(SavePrdOptions.PERMANENTLY); + break; + } + case 1: { + setSavePrdOption(SavePrdOptions.CURRENT_SESSION_ONLY); + break; + } + default: { + setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + } + } + } else { + switch (selIndex) { + case 0: { + setSavePrdOption(SavePrdOptions.CURRENT_SESSION_ONLY); + break; + } + default: { + setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + } + } + } + } + + /** + * Gets the save prd option. + * + * @return the save prd option + * org.opengauss.mppdbide.bl.serverdatacache.IServerConnectionInfo# + * getSavePrdOption() + */ + @Override + public SavePrdOptions getSavePrdOption() { + return this.general.getSavePrdOption(); + } + + @Override + public String getProfileId() { + return profileId; + } + + @Override + public void setProfileId(String id) { + profileId = id; + } + + @Override + public String getRootCertificate() { + return this.ssl.getRootCertFilePathText(); + } + + @Override + public void setRootCertificate(String rootCertificatePath) { + this.ssl.setRootCertFilePathText(rootCertificatePath); + } + + @Override + public String getSSLMode() { + return this.ssl.getSSLMode(); + } + + @Override + public void setSSLMode(String sslMod) { + this.ssl.setSSLMode(sslMod); + } + + @Override + public Set getSchemaExclusionList() { + return this.advanced.getSchemaExclusionList(); + } + + @Override + public Set getSchemaInclusionList() { + return this.advanced.getSchemaInclusionList(); + } + + /** + * Sets the schema exclusion list. + * + * @param schemaExclusionList the new schema exclusion list + */ + public void setSchemaExclusionList(Set schemaExclusionList) { + this.advanced.setSchemaExclusionList(schemaExclusionList); + } + + /** + * Sets the schema inclusion list. + * + * @param schemaInclusionList the new schema inclusion list + */ + public void setSchemaInclusionList(Set schemaInclusionList) { + this.advanced.setSchemaInclusionList(schemaInclusionList); + } + + @Override + public int getLoadLimit() { + return this.advanced.getLoadLimit(); + } + + @Override + public void setLoadLimit(int setloadLimitParam) { + int setloadLimit = setloadLimitParam; + if (0 == setloadLimit) { + setloadLimit = DEFAULT_OBJECT_LOAD_THRESHOLD; + } + this.advanced.setLoadLimit(setloadLimit); + } + + @Override + public void setDriverName(String dname) { + this.general.setConnctionDriverName(MessageConfigLoader.getProperty(IMessagesConstants.OPEN_GAUSS)); + setDbType(); + } + + @Override + public String getDriverName() { + return this.general.getConnctionDriverName(); + } + + /** + * Sets the DB version. + * + * @param serverVersion the new DB version + */ + @Override + public void setDBVersion(String serverVersion) { + this.databaseVersion = serverVersion; + } + + /** + * Gets the DB version. + * + * @return the DB version + */ + @Override + public String getDBVersion() { + return this.databaseVersion; + } + + /** + * Sets the privilege based ob access. + * + * @param selection the new privilege based ob access + */ + @Override + public void setPrivilegeBasedObAccess(boolean selection) { + this.advanced.setPrivilegeBasedObAcess(selection); + } + + @Override + public DBTYPE getServerDBType() { + return dbType; + } + + /** + * Sets the db type. + */ + @Override + public void setDbType() { + this.dbType = DBTYPE.OPENGAUSS; + } + + @Override + public Properties composeProperty(String driverName) { + Properties properties = new Properties(); + properties.setProperty("user", getDsUsername()); + properties.setProperty("password", new String(getPrd())); + properties.setProperty("allowEncodingChanges", "true"); + String dsEncoding = BLPreferenceManager.getInstance().getBLPreference().getDSEncoding(); + if (dsEncoding.isEmpty()) { + dsEncoding = Charset.defaultCharset().toString(); + } else if (!dsEncoding.equals(DsEncodingEnum.GBK.getEncoding())) { + dsEncoding = DsEncodingEnum.UTF_8.getEncoding(); + } + + properties.setProperty("characterEncoding", dsEncoding); + properties.setProperty("ApplicationName", "Data Studio"); + if (CustomStringUtility.isProtocolVersionNeeded(driverName)) { + properties.setProperty("protocolVersion", "3"); + } + + String[] arguments = BLUtils.getInstance().getPlatformArgs(); + boolean isLoginTimeout = false; + String loginTimeout = null; + + int len = arguments.length; + for (int argIndex = 0; argIndex < len; argIndex++) { + if (arguments[argIndex] != null && arguments[argIndex].startsWith("-loginTimeout")) { + String[] splitArgs = arguments[argIndex].split("="); + loginTimeout = splitArgs.length > 1 ? splitArgs[1].trim() : ""; + isLoginTimeout = "".equals(loginTimeout) ? false : true; + break; + } + } + + properties.setProperty("loginTimeout", isLoginTimeout ? loginTimeout : "180"); + if (isSSLEnabled()) { + properties.setProperty("sslmode", getSSLMode()); + properties.setProperty("sslcert", getClientSSLCertificate()); + properties.setProperty("sslkey", getClientSSLKey()); + properties.setProperty("sslrootcert", getRootCertificate()); + properties.setProperty("sslpassword", new String(getSSLPrd())); + properties.setProperty("ssl", "true"); + } + + return properties; + } + + @Override + public String composeUrl() { + if (!StringUtils.isEmpty(getServerIp())) { + return "jdbc:postgresql://" + getServerIp() + ':' + getServerPort() + '/' + getDatabaseName(); + } else { + return ""; + } + } + + @Override + public char[] getSSLPrd() { + char[] sslPrd = this.ssl.getSSLPsrd(); + return (char[]) sslPrd.clone(); + } + + @Override + public void setSSLPrd(char[] pword) { + this.ssl.setSSLPsrd(pword); + } + + @Override + public void setClientSSLPrivateKey(String keyFileName) { + this.ssl.setClSSLPrivateKeyFile(keyFileName); + } + + @Override + public String getClientSSLPrivateKey() { + return this.ssl.getClSSLPrivateKeyFile(); + } + + @Override + public Set getModifiedSchemaExclusionList() { + return advanced.getModifiedSchemaExclusionList(); + } + + @Override + public void setModifiedSchemaExclusionList(Set modifiedSchemaExclusionList) { + advanced.setModifiedSchemaExclusionList(modifiedSchemaExclusionList); + } + + @Override + public Set getModifiedSchemaInclusionList() { + return advanced.getModifiedSchemaInclusionList(); + } + + @Override + public void setModifiedSchemaInclusionList(Set modifiedSchemaInclusionList) { + advanced.setModifiedSchemaInclusionList(modifiedSchemaInclusionList); + } + + @Override + public boolean canLoadChildObjects() { + return this.advanced.isCanLoadChildObj(); + } + + @Override + public void setCanLoadChildObjects(boolean canLoadChildObj) { + this.advanced.setCanLoadChildObj(canLoadChildObj); + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/ServerConnectionInfoJsonValidator.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/ServerConnectionInfoJsonValidator.java new file mode 100644 index 0000000000000000000000000000000000000000..178db396a23ab25e9b52a52de68ec873f5b61bfb --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/ServerConnectionInfoJsonValidator.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.connectioninfo; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; + +/** + * Title: ServerConnectionInfoJsonValidator + * + * Description:The Class ServerConnectionInfoJsonValidator. + * + */ + +public final class ServerConnectionInfoJsonValidator { + + /** + * The Constant IP_ADDRESS_PATTERN. + */ + public static final String IP_ADDRESS_PATTERN = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"; + + /** + * The Constant IS_IP_ADDRESS. + */ + public static final String IS_IP_ADDRESS = "^\\d+\\.\\d+\\.\\d+\\.\\d+$"; + + /** + * Instantiates a new server connection info json validator. + */ + private ServerConnectionInfoJsonValidator() { + } + + /** + * Validate json. + * + * @param jsonString the json string + * @return true, if successful + */ + public static boolean validateJson(String jsonString) { + Gson gson = new Gson(); + JsonArray jsonArray = gson.fromJson(jsonString, JsonArray.class); + for (int jsonIndex = 0; jsonIndex < jsonArray.size(); jsonIndex++) { + if (jsonArray.get(jsonIndex).isJsonObject()) { + JsonObject asJsonObject = jsonArray.get(jsonIndex).getAsJsonObject(); + String jsonElement = asJsonObject.has("version") ? asJsonObject.get("version").getAsString() : ""; + if (jsonElement.equals("1.00")) { + return Version1JsonValidator.validate(asJsonObject); + } else if (jsonElement.equals("2.00")) { + return Version2jsonValidator.validate(asJsonObject); + } + + } + } + + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/Version1JsonValidator.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/Version1JsonValidator.java new file mode 100644 index 0000000000000000000000000000000000000000..3aaac651d241f91b76fa86d90f5b251dc4f874f0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/Version1JsonValidator.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.connectioninfo; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +/** + * Title: Version1JsonValidator + * + * Description:The class Version1JsonValidator + * + */ + +public class Version1JsonValidator { + + private static Map jsonFieldMap; + + /** + * Validate. + * + * @param jsonObject the json object + * @return true, if successful + */ + public static boolean validate(JsonObject jsonObject) { + boolean isValid = true; + fillValidFields(); + Set> entrySet = jsonObject.entrySet(); + Iterator> iterator = entrySet.iterator(); + while (iterator.hasNext() && isValid) { + Entry next = iterator.next(); + isValid = isMemberPresent(next.getKey()); + if (next.getKey().equals("serverIp") && null != next.getValue()) { + isValid = validateHostAddress(next.getValue().getAsString()); + } + } + return isValid; + } + + /** + * Fill valid fields. + */ + private static void fillValidFields() { + jsonFieldMap = new HashMap<>(); + jsonFieldMap.put("profileId", "profileId"); + + jsonFieldMap.put("databaseVersion", "databaseVersion"); + jsonFieldMap.put("dbType", "dbType"); + jsonFieldMap.put("version", "version"); + jsonFieldMap.put("general", "general"); + jsonFieldMap.put("conectionName", "conectionName"); + jsonFieldMap.put("databaseName", "databaseName"); + jsonFieldMap.put("prd", "prd"); + jsonFieldMap.put("isSSLEnabled", "isSSLEnabled"); + jsonFieldMap.put("serverIp", "serverIp"); + jsonFieldMap.put("serverPort", "serverPort"); + jsonFieldMap.put("username", "username"); + jsonFieldMap.put("savePrdOption", "savePrdOption"); + jsonFieldMap.put("connctionDriverName", "connctionDriverName"); + jsonFieldMap.put("ssl", "ssl"); + jsonFieldMap.put("clSSLCertificatePath", "clSSLCertificatePath"); + jsonFieldMap.put("clSSLKeyPath", "clSSLKeyPath"); + jsonFieldMap.put("sslPrd", "sslPrd"); + jsonFieldMap.put("rootCertFilePathText", "rootCertFilePathText"); + jsonFieldMap.put("clSSLPrivateKeyFile", "clSSLPrivateKeyFile"); + jsonFieldMap.put("sslMode", "sslMode"); + jsonFieldMap.put("advanced", "advanced"); + jsonFieldMap.put("schemaExclusionList", "schemaExclusionList"); + jsonFieldMap.put("schemaInclusionList", "schemaInclusionList"); + jsonFieldMap.put("loadLimit", "loadLimit"); + jsonFieldMap.put("privilegeBasedObAcess", "privilegeBasedObAcess"); + } + + private static boolean validateHostAddress(String string) { + + Pattern pattern = Pattern.compile(ServerConnectionInfoJsonValidator.IP_ADDRESS_PATTERN); + Matcher matcher = pattern.matcher(string); + if (string.matches(ServerConnectionInfoJsonValidator.IS_IP_ADDRESS)) { + if (!(matcher.matches())) { + return false; + } + } + return true; + } + + private static boolean isMemberPresent(String member) { + + return jsonFieldMap.containsKey(member); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/Version2jsonValidator.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/Version2jsonValidator.java new file mode 100644 index 0000000000000000000000000000000000000000..830c051119e96edd13b1cb467beb33b70bc33449 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/Version2jsonValidator.java @@ -0,0 +1,244 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.connectioninfo; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +/** + * Title: Version2jsonValidator + * + * Description:The class Version2jsonValidator + * + */ + +public class Version2jsonValidator { + + private static Map jsonFieldMap; + private static Map genJsonFieldMap; + private static Map sslJsonFieldMap; + private static Map advJsonFieldMap; + + /** + * Validate. + * + * @param jsonObject the json object + * @return true, if successful + */ + public static boolean validate(JsonObject jsonObject) { + boolean isValid = false; + + isValid = validateVersionAndID(jsonObject); + if (isValid) { + isValid = validateGeneralInfo(jsonObject); + } + if (isValid) { + isValid = validateSSLInfo(jsonObject); + } + if (isValid) { + isValid = validateAdvInfo(jsonObject); + } + + return isValid; + } + + /** + * Validate SSL info. + * + * @param jsonObject the json object + * @return true, if successful + */ + private static boolean validateSSLInfo(JsonObject jsonObject) { + boolean isValidJson = true; + fillValidSSLFields(); + if (isMemberPresent("ssl", jsonFieldMap)) { + JsonObject genJsonObject = jsonObject.get("ssl").getAsJsonObject(); + Set> entrySet = genJsonObject.entrySet(); + Iterator> iterator = entrySet.iterator(); + while (iterator.hasNext() && isValidJson) { + Entry next = iterator.next(); + isValidJson = isMemberPresent(next.getKey(), sslJsonFieldMap); + } + } + + return isValidJson; + + } + + /** + * Validate adv info. + * + * @param obj the obj + * @return true, if successful + */ + private static boolean validateAdvInfo(JsonObject obj) { + + boolean isValidJson = true; + fillValidAdvFields(); + if (isMemberPresent("advanced", jsonFieldMap)) { + JsonObject genJsonObject = obj.get("advanced").getAsJsonObject(); + Set> entrySet = genJsonObject.entrySet(); + Iterator> iterator = entrySet.iterator(); + while (iterator.hasNext() && isValidJson) { + Entry next = iterator.next(); + isValidJson = isMemberPresent(next.getKey(), advJsonFieldMap); + + } + } + + return isValidJson; + + } + + /** + * Validate version and ID. + * + * @param obj the obj + * @return true, if successful + */ + private static boolean validateVersionAndID(JsonObject obj) { + boolean isValidJson = true; + fillValidFields(); + Set> entrySet = obj.entrySet(); + Iterator> iterator = entrySet.iterator(); + while (iterator.hasNext() && isValidJson) { + Entry next = iterator.next(); + isValidJson = isMemberPresent(next.getKey(), jsonFieldMap); + } + + return isValidJson; + } + + /** + * Validate general info. + * + * @param obj the obj + * @return true, if successful + */ + private static boolean validateGeneralInfo(JsonObject obj) { + boolean isValidJson = true; + fillValidGenFields(); + if (isMemberPresent("general", jsonFieldMap)) { + JsonObject genJsonObject = obj.get("general").getAsJsonObject(); + Set> entrySet = genJsonObject.entrySet(); + Iterator> iterator = entrySet.iterator(); + while (iterator.hasNext() && isValidJson) { + Entry next = iterator.next(); + isValidJson = isMemberPresent(next.getKey(), genJsonFieldMap); + if (next.getKey().equals("conectionName") && null != next.getValue()) { + isValidJson = validateHostAddress(next.getValue().getAsString()); + } + } + } + + return isValidJson; + } + + /** + * Validate host address. + * + * @param string the string + * @return true, if successful + */ + private static boolean validateHostAddress(String string) { + + Pattern pattern = Pattern.compile(ServerConnectionInfoJsonValidator.IP_ADDRESS_PATTERN); + Matcher matcher = pattern.matcher(string); + if (string.matches(ServerConnectionInfoJsonValidator.IS_IP_ADDRESS)) { + if (!(matcher.matches())) { + return false; + } + } + return true; + } + + /** + * Fill valid fields. + */ + private static void fillValidFields() { + jsonFieldMap = new HashMap<>(); + jsonFieldMap.put("profileId", "profileId"); + jsonFieldMap.put("databaseVersion", "databaseVersion"); + jsonFieldMap.put("dbType", "dbType"); + jsonFieldMap.put("version", "version"); + jsonFieldMap.put("general", "general"); + jsonFieldMap.put("ssl", "ssl"); + jsonFieldMap.put("advanced", "advanced"); + + } + + /** + * Fill valid gen fields. + */ + private static void fillValidGenFields() { + genJsonFieldMap = new HashMap<>(); + genJsonFieldMap.put("conectionName", "conectionName"); + genJsonFieldMap.put("databaseName", "databaseName"); + genJsonFieldMap.put("prd", "prd"); + genJsonFieldMap.put("isSSLEnabled", "isSSLEnabled"); + genJsonFieldMap.put("serverIp", "serverIp"); + genJsonFieldMap.put("serverPort", "serverPort"); + genJsonFieldMap.put("username", "username"); + genJsonFieldMap.put("savePrdOption", "savePrdOption"); + genJsonFieldMap.put("connctionDriverName", "connctionDriverName"); + } + + /** + * Fill valid SSL fields. + */ + private static void fillValidSSLFields() { + sslJsonFieldMap = new HashMap<>(); + sslJsonFieldMap.put("clSSLCertificatePath", "clSSLCertificatePath"); + sslJsonFieldMap.put("clSSLKeyPath", "clSSLKeyPath"); + sslJsonFieldMap.put("sslPrd", "sslPrd"); + sslJsonFieldMap.put("rootCertFilePathText", "rootCertFilePathText"); + sslJsonFieldMap.put("sslMode", "sslMode"); + sslJsonFieldMap.put("clSSLPrivateKeyFile", "clSSLPrivateKeyFile"); + + } + + /** + * Fill valid adv fields. + */ + private static void fillValidAdvFields() { + advJsonFieldMap = new HashMap<>(); + advJsonFieldMap.put("schemaExclusionList", "schemaExclusionList"); + advJsonFieldMap.put("schemaInclusionList", "schemaInclusionList"); + advJsonFieldMap.put("canLoadChildObj", "canLoadChildObj"); + advJsonFieldMap.put("loadLimit", "loadLimit"); + advJsonFieldMap.put("privilegeBasedObAcess", "privilegeBasedObAcess"); + } + + /** + * Checks if is member present. + * + * @param member the member + * @param fieldMap the field map + * @return true, if is member present + */ + private static boolean isMemberPresent(String member, Map fieldMap) { + + return fieldMap.containsKey(member); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/conif/IServerConnectionInfo.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/conif/IServerConnectionInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..d928f62bf0616e0149604c1d25b6db75e90f14a7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/conif/IServerConnectionInfo.java @@ -0,0 +1,416 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif; + +import java.util.Properties; +import java.util.Set; + +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.DBTYPE; + +/** + * + * Title: interface + * + * Description: The Interface IServerConnectionInfo. + * + */ + +public interface IServerConnectionInfo { + + /** + * Gets the clone. + * + * @return the clone + */ + IServerConnectionInfo getClone(); + + /** + * Gets the conection name. + * + * @return the conection name + */ + String getConectionName(); + + /** + * Sets the conection name. + * + * @param conectionName the new conection name + */ + void setConectionName(String conectionName); + + /** + * Gets the database name. + * + * @return the database name + */ + String getDatabaseName(); + + /** + * Sets the database name. + * + * @param databaseName the new database name + */ + void setDatabaseName(String databaseName); + + /** + * Gets the prd. + * + * @return the prd + */ + char[] getPrd(); + + /** + * Sets the prd. + * + * @param prd the new prd + */ + void setPrd(char[] prd); + + /** + * Clear pasrd. + */ + void clearPasrd(); + + /** + * Gets the server ip. + * + * @return the server ip + */ + String getServerIp(); + + /** + * Sets the server ip. + * + * @param serverIp the new server ip + */ + void setServerIp(String serverIp); + + /** + * Gets the server port. + * + * @return the server port + */ + int getServerPort(); + + /** + * Sets the server port. + * + * @param serverPort the new server port + */ + void setServerPort(int serverPort); + + /** + * Gets the username. + * + * @return the username + */ + String getDsUsername(); + + /** + * Sets the username. + * + * @param username the new username + */ + void setUsername(String username); + + /** + * Checks if is SSL enabled. + * + * @return true, if is SSL enabled + */ + boolean isSSLEnabled(); + + /** + * Sets the SSL enabled. + * + * @param isSSLEnabled the new SSL enabled + */ + void setSSLEnabled(boolean isSSLEnabled); + + /** + * Gets the client SSL certificate. + * + * @return the client SSL certificate + */ + String getClientSSLCertificate(); + + /** + * Sets the client SSL certificate. + * + * @param clSSLCertificatePath the new client SSL certificate + */ + void setClientSSLCertificate(String clSSLCertificatePath); + + /** + * Gets the client SSL key. + * + * @return the client SSL key + */ + String getClientSSLKey(); + + /** + * Sets the client SSL key. + * + * @param clSSLKeyPath the new client SSL key + */ + void setClientSSLKey(String clSSLKeyPath); + + /** + * Gets the SSL prd. + * + * @return the SSL prd + */ + char[] getSSLPrd(); + + /** + * Sets the SSL prd. + * + * @param prd the new SSL prd + */ + void setSSLPrd(char[] prd); + + /** + * Sets the save prd option. + * + * @param savePrdOption the new save prd option + */ + void setSavePrdOption(SavePrdOptions savePrdOption); + + /** + * Sets the save prd option. + * + * @param ordinal the ordinal + * @param isPermanentPrdReq the is permanent prd req + */ + void setSavePrdOption(int ordinal, boolean isPermanentPrdReq); + + /** + * Gets the save prd option. + * + * @return the save prd option + */ + SavePrdOptions getSavePrdOption(); + + /** + * Gets the SSL mode. + * + * @return the SSL mode + */ + String getSSLMode(); + + /** + * Sets the SSL mode. + * + * @param sslMode the new SSL mode + */ + void setSSLMode(String sslMode); + + /** + * Gets the profile id. + * + * @return the profile id + */ + String getProfileId(); + + /** + * Sets the profile id. + * + * @param id the new profile id + */ + void setProfileId(String id); + + /** + * Gets the root certificate. + * + * @return the root certificate + */ + String getRootCertificate(); + + /** + * Sets the root certificate. + * + * @param rootCertificatePath the new root certificate + */ + void setRootCertificate(String rootCertificatePath); + + /** + * Gets the schema exclusion list. + * + * @return the schema exclusion list + */ + Set getSchemaExclusionList(); + + /** + * Gets the schema inclusion list. + * + * @return the schema inclusion list + */ + Set getSchemaInclusionList(); + + /** + * Gets the load limit. + * + * @return the load limit + */ + int getLoadLimit(); + + /** + * Sets the load limit. + * + * @param loadLimit the new load limit + */ + void setLoadLimit(int loadLimit); + + /** + * Checks if is privilege based ob access enabled. + * + * @return true, if is privilege based ob access enabled + */ + public boolean isPrivilegeBasedObAccessEnabled(); + + /** + * Sets the driver name. + * + * @param dname the new driver name + */ + void setDriverName(String dname); + + /** + * Gets the driver name. + * + * @return the driver name + */ + String getDriverName(); + + /** + * Gets the db type. + * + * @return the db type + */ + DBTYPE getServerDBType(); + + /** + * Gets the version. + * + * @return the version + */ + String getVersion(); + + /** + * Compose property. + * + * @param driverName the driver name + * @return the properties + */ + Properties composeProperty(String driverName); + + /** + * Compose url. + * + * @return the string + */ + String composeUrl(); + + /** + * Sets the schema exclusion list. + * + * @param newExcludeList the new schema exclusion list + */ + void setSchemaExclusionList(Set newExcludeList); + + /** + * Sets the client SSL private key. + * + * @param keyFileName the new client SSL private key + */ + void setClientSSLPrivateKey(String keyFileName); + + /** + * Gets the client SSL private key. + * + * @return the client SSL private key + */ + String getClientSSLPrivateKey(); + + /** + * Sets the DB version. + * + * @param serverVersion the new DB version + */ + void setDBVersion(String serverVersion); + + /** + * Gets the DB version. + * + * @return the DB version + */ + String getDBVersion(); + + /** + * Sets the privilege based ob access. + * + * @param selection the new privilege based ob access + */ + void setPrivilegeBasedObAccess(boolean selection); + + /** + * Sets the db type. + */ + void setDbType(); + + /** + * getModifiedSchemaExclusionList + * + * @return schema list + */ + Set getModifiedSchemaExclusionList(); + + /** + * setModifiedSchemaExclusionList + * + * @param modifiedSchemaExclusionList set value + */ + void setModifiedSchemaExclusionList(Set modifiedSchemaExclusionList); + + /** + * getModifiedSchemaInclusionList + * + * @return schema list + */ + Set getModifiedSchemaInclusionList(); + + /** + * setModifiedSchemaInclusionList + * + * @param modifiedSchemaInclusionList set value + */ + void setModifiedSchemaInclusionList(Set modifiedSchemaInclusionList); + + /** + * canLoadChildObjects + * + * @return boolean can load child obj + */ + boolean canLoadChildObjects(); + + /** + * setCanLoadChildObjects + * + * @param canLoadChildObj boolean + */ + void setCanLoadChildObjects(boolean canLoadChildObj); +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/connectionupgrade/ConnectionProfileUpgradeManager.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/connectionupgrade/ConnectionProfileUpgradeManager.java new file mode 100644 index 0000000000000000000000000000000000000000..d3fb13dcfb57ec1aaf060becc2d7533be3f2976a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/connectionupgrade/ConnectionProfileUpgradeManager.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.connectionupgrade; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.Gson; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; +import org.opengauss.mppdbide.utils.connectionprofileversion.IConnectionProfileVersions; + +/** + * + * Title: class + * + * Description: The Class ConnectionProfileUpgradeManager. + * + */ + +public final class ConnectionProfileUpgradeManager { + + private static final Object lock = new Object(); + private static volatile ConnectionProfileUpgradeManager upgrader; + /* + * The versions array should be always kept in the order of the versions + * introduced + */ + private final List versionList; + + private ConnectionProfileUpgradeManager() { + versionList = new ArrayList(); + versionList.add(IConnectionProfileVersions.CONNECTION_PROFILE_FIRST_VERSION); + versionList.add(IConnectionProfileVersions.CONNECTION_PROFILE_SECOND_VERSION); + } + + /** + * Checks if is version available. + * + * @param versionNumber the version number + * @return true, if is version available + */ + public boolean isVersionAvailable(String versionNumber) { + return versionList.contains(versionNumber); + } + + /** + * Gets the version index. + * + * @param version the version + * @return the version index + */ + public int getVersionIndex(String version) { + if (versionList.contains(version)) { + return versionList.indexOf(version); + } + return -1; + } + + /** + * Gets the single instance of ConnectionProfileUpgradeManager. + * + * @return single instance of ConnectionProfileUpgradeManager + */ + public static ConnectionProfileUpgradeManager getInstance() { + if (upgrader == null) { + synchronized (lock) { + + if (upgrader == null) { + upgrader = new ConnectionProfileUpgradeManager(); + } + } + } + return upgrader; + } + + /** + * Gets the upgraded connection profiles. + * + * @param jsonString the json string + * @param type the type + * @param sourceProfileVersion the source profile version + * @return the upgraded connection profiles + */ + public List getUpgradedConnectionProfiles(String jsonString, Type type, + String sourceProfileVersion) { + int sourceVersionIndex = versionList.indexOf(sourceProfileVersion); + int currentDsVersionIndex = versionList.indexOf(IConnectionProfileVersions.CONNECTION_PROFILE_CURRENT_VERSION); + + String upgradeString = jsonString; + + IConnectionProfileUpgrader connectionUpgrader; + for (int versionIndex = sourceVersionIndex; versionIndex < currentDsVersionIndex; versionIndex++) { + connectionUpgrader = ConnectionProfileUpgraderFactory.getConnectionUpgrader(versionList.get(versionIndex)); + if (upgradeString != null && connectionUpgrader != null) { + upgradeString = connectionUpgrader.upgrade(upgradeString); + } + + } + Gson gson = new Gson(); + IServerConnectionInfo fromJson = gson.fromJson(upgradeString, ServerConnectionInfo.class); + List infoList = new ArrayList<>(); + infoList.add(fromJson); + return infoList; + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/connectionupgrade/ConnectionProfileUpgraderFactory.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/connectionupgrade/ConnectionProfileUpgraderFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..1af683a1d52dd8ced10c8e1cff19f6a092459ecc --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/connectionupgrade/ConnectionProfileUpgraderFactory.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.connectionupgrade; + +/** + * Title: ConnectionProfileUpgraderFactory + * + * Description: A factory for creating ConnectionProfileUpgrader objects. + * + */ + +public final class ConnectionProfileUpgraderFactory { + + private ConnectionProfileUpgraderFactory() { + + } + + /** + * Gets the connection upgrader. + * + * @param version the version + * @return the connection upgrader + */ + public static IConnectionProfileUpgrader getConnectionUpgrader(String version) { + + if ("1.00".equals(version)) { + return new UpgradeFromVersion1ToVersion2(); + } + + return null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/connectionupgrade/IConnectionProfileUpgrader.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/connectionupgrade/IConnectionProfileUpgrader.java new file mode 100644 index 0000000000000000000000000000000000000000..4c11ba701e2d94c686cda4eca052fe6874a6b04a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/connectionupgrade/IConnectionProfileUpgrader.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.connectionupgrade; + +/** + * + * Title: interface + * + * Description: The Interface IConnectionProfileUpgrader. + * + */ + +public interface IConnectionProfileUpgrader { + + /** + * Upgrade. + * + * @param jsonString the json string + * @return the string + */ + public String upgrade(String jsonString); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/connectionupgrade/UpgradeFromVersion1ToVersion2.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/connectionupgrade/UpgradeFromVersion1ToVersion2.java new file mode 100644 index 0000000000000000000000000000000000000000..c63654e0309bbfcefabefdfa13ecf0761f3bb986 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/connectioninfo/connectionupgrade/UpgradeFromVersion1ToVersion2.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.connectionupgrade; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; + +/** + * + * Title: class + * + * Description: The Class UpgradeFromVersion1ToVersion2. + * + */ + +public class UpgradeFromVersion1ToVersion2 implements IConnectionProfileUpgrader { + + @Override + public String upgrade(String jsonString) { + Gson gson = new Gson(); + IServerConnectionInfo info = null; + + JsonArray jsonArray = gson.fromJson(jsonString, JsonArray.class); + for (int jsonObjIndex = 0; jsonObjIndex < jsonArray.size(); jsonObjIndex++) { + if (jsonArray.get(jsonObjIndex).isJsonObject()) { + JsonObject asJsonObject = jsonArray.get(jsonObjIndex).getAsJsonObject(); + info = new ServerConnectionInfo(); + + info.setDBVersion(getValue("databaseVersion", asJsonObject)); + info.setProfileId(getValue("profileId", asJsonObject)); + formatToGeneralInfo(asJsonObject, info); + formatToSSLInfo(asJsonObject, info); + formatToAdvancedInfo(asJsonObject, info); + } + } + + String json = gson.toJson(info); + return json; + } + + private void formatToGeneralInfo(JsonObject object, IServerConnectionInfo info) { + + info.setConectionName(getValue("conectionName", object)); + info.setDatabaseName(getValue("databaseName", object)); + info.setServerIp(getValue("serverIp", object)); + info.setServerPort(getIntegerValue("serverPort", object)); + info.setUsername(getValue("username", object)); + info.setSSLEnabled(getBoolValue("isSSLEnabled", object)); + info.setSavePrdOption(getValue("savePrdOption", object).equals("") ? SavePrdOptions.DO_NOT_SAVE + : SavePrdOptions.valueOf(getValue("savePrdOption", object))); + info.setDriverName(getValue("connctionDriverName", object)); + info.setDbType(); + } + + private void formatToSSLInfo(JsonObject object, IServerConnectionInfo info) { + info.setClientSSLCertificate(getValue("clSSLCertificatePath", object)); + info.setClientSSLKey(getValue("clSSLKeyPath", object)); + info.setRootCertificate(getValue("rootCertFilePathText", object)); + info.setSSLMode(getValue("sslMode", object)); + } + + private void formatToAdvancedInfo(JsonObject object, IServerConnectionInfo info) { + info.setLoadLimit(getIntegerValue("loadLimit", object)); + info.setPrivilegeBasedObAccess(getBoolValue("privilegeBasedObAcess", object)); + } + + private String getValue(String key, JsonObject obj) { + if (obj.has(key)) { + return obj.get(key).getAsString(); + } + return ""; + } + + private Integer getIntegerValue(String key, JsonObject obj) { + if (obj.has(key)) { + return obj.get(key).getAsInt(); + } + return 0; + } + + private Boolean getBoolValue(String key, JsonObject obj) { + if (obj.has(key)) { + return obj.get(key).getAsBoolean(); + } + return false; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/ColumnList.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/ColumnList.java new file mode 100644 index 0000000000000000000000000000000000000000..4888041cbc6993db777309d804d7c0c8ad728762 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/ColumnList.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; + +/** + * + * Title: class + * + * Description: The Class ColumnList. + * + */ + +public class ColumnList extends OLAPObjectList { + + @Override + public void addItem(ColumnMetaData item) { + + super.addItem(item); + } + + @Override + public void addItemAtIndex(ColumnMetaData item, int index) { + + super.addItemAtIndex(item, index); + } + + /** + * Instantiates a new column list. + * + * @param type the type + * @param parentObject the parent object + */ + public ColumnList(OBJECTTYPE type, Object parentObject) { + super(type, parentObject); + } + + /** + * Gets the parent. + * + * @return the parent + */ + public TableMetaData getParent() { + return (TableMetaData) super.getParent(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/ConstraintList.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/ConstraintList.java new file mode 100644 index 0000000000000000000000000000000000000000..9028a3ff195c2958e7c3d4e427ebfc4c45aa6118 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/ConstraintList.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; + +/** + * + * Title: class + * + * Description: The Class ConstraintList. + * + */ + +public class ConstraintList extends OLAPObjectList { + + /** + * Instantiates a new constraint list. + * + * @param type the type + * @param parentObject the parent object + */ + public ConstraintList(OBJECTTYPE type, Object parentObject) { + super(type, parentObject); + } + + /** + * Gets the parent. + * + * @return the parent + */ + public TableMetaData getParent() { + return (TableMetaData) super.getParent(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/DatabaseObjectGroup.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/DatabaseObjectGroup.java new file mode 100644 index 0000000000000000000000000000000000000000..0f033e46a85316ffb14954ae2096e9637a104c2b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/DatabaseObjectGroup.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; + +/** + * This class collects the Database objects + * + */ + +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: class + * + * Description: The Class DatabaseObjectGroup. + * + */ + +public class DatabaseObjectGroup extends OLAPObjectGroup { + + private boolean isLoadingDatabaseGroupInProgress; + + /** + * Instantiates a new database object group. + * + * @param type the type + * @param server the server + */ + public DatabaseObjectGroup(OBJECTTYPE type, Server server) { + super(type, server); + } + + /** + * Gets the server. + * + * @return the server + */ + public Server getServer() { + return (Server) getParent(); + } + + /** + * Refresh. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void refresh() throws DatabaseOperationException, DatabaseCriticalException { + Database db = this.getServer().findOneActiveDb(); + this.getServer().refreshDBs(db); + } + + /** + * Checks if is loading database group in progress. + * + * @return true, if is loading database group in progress + */ + public boolean isLoadingDatabaseGroupInProgress() { + return isLoadingDatabaseGroupInProgress; + } + + /** + * Sets the loading database group in progress. + * + * @param status the new loading database group in progress + */ + public void setLoadingDatabaseGroupInProgress(boolean status) { + this.isLoadingDatabaseGroupInProgress = status; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/DebugObjectGroup.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/DebugObjectGroup.java new file mode 100644 index 0000000000000000000000000000000000000000..6cfd6915a8e1f4db66c86c291da1441c0cf90501 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/DebugObjectGroup.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DebugObjects; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; + +/** + * + * Title: class + * + * Description: The Class DebugObjectGroup. + * + */ + +public class DebugObjectGroup extends OLAPObjectGroup { + + /** + * Instantiates a new debug object group. + * + * @param type the type + * @param namespace the namespace + */ + public DebugObjectGroup(OBJECTTYPE type, Namespace namespace) { + super(type, namespace); + } + + @Override + public Namespace getNamespace() { + return (Namespace) getParent(); + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + return getNamespace().getDatabase(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/FilterObject.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/FilterObject.java new file mode 100644 index 0000000000000000000000000000000000000000..12482d44c9a05738eca42cc1a0b08d2960ed8272 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/FilterObject.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +/** + * Title: ObjectBrowserFilter + * + * Description:ObjectBrowserFilter + * + */ + +public class FilterObject { + + private static FilterObject filter_instance = new FilterObject(); + private String filterText = null; + + /** + * Instantiates a new filter object. + */ + private FilterObject() { + } + + /** + * Gets the single instance of FilterObject. + * + * @return single instance of FilterObject + */ + public static FilterObject getInstance() { + return filter_instance; + } + + /** + * Sets the filter text. + * + * @param filterText the new filter text + */ + public void setFilterText(String filterText) { + this.filterText = filterText; + } + + /** + * Gets the filter text. + * + * @return the filter text + */ + public String getFilterText() { + return filterText; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/ForeignTableGroup.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/ForeignTableGroup.java new file mode 100644 index 0000000000000000000000000000000000000000..a70aae809d9205fad08690ad84542535db3d1949 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/ForeignTableGroup.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; + +/** + * + * Title: class + * + * Description: The Class ForeignTableGroup. + * + */ + +public class ForeignTableGroup extends TableObjectGroup { + + /** + * Instantiates a new foreign table group. + * + * @param type the type + * @param nm the nm + */ + public ForeignTableGroup(OBJECTTYPE type, Namespace nm) { + super(type, nm); + } + + /** + * Gets the display label. + * + * @return the display label + */ + public String getDisplayLabel() { + return super.getDisplayLabel(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/IndexList.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/IndexList.java new file mode 100644 index 0000000000000000000000000000000000000000..f99da989e631f8e72b3c55c926324c9b585df9b6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/IndexList.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +import org.opengauss.mppdbide.bl.serverdatacache.IndexMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; + +/** + * + * Title: class + * + * Description: The Class IndexList. + * + */ + +public class IndexList extends OLAPObjectList { + + /** + * Instantiates a new index list. + * + * @param type the type + * @param table the table + */ + public IndexList(OBJECTTYPE type, TableMetaData table) { + super(type, table); + } + + /** + * Gets the parent. + * + * @return the parent + */ + public TableMetaData getParent() { + return (TableMetaData) super.getParent(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/OLAPObjectGroup.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/OLAPObjectGroup.java new file mode 100644 index 0000000000000000000000000000000000000000..d08311a8db9d2e6d8ff379a67cfd0a412bfdaca6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/OLAPObjectGroup.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +import org.opengauss.mppdbide.bl.serverdatacache.GaussOLAPDBMSObject; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; + +/** + * + * Title: class + * + * Description: The Class OLAPObjectGroup. + * + * @param the element type + */ + +public class OLAPObjectGroup extends ObjectGroup implements GaussOLAPDBMSObject { + + /** + * Instantiates a new OLAP object group. + * + * @param type the type + * @param parentObject the parent object + */ + public OLAPObjectGroup(OBJECTTYPE type, Object parentObject) { + super(type, parentObject); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/OLAPObjectList.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/OLAPObjectList.java new file mode 100644 index 0000000000000000000000000000000000000000..6025199880b2862c738f7b5a89fbc788f6fdafef --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/OLAPObjectList.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +import org.opengauss.mppdbide.bl.serverdatacache.GaussOLAPDBMSObject; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; + +/** + * + * Title: class + * + * Description: The Class OLAPObjectList. + * + * @param the element type + */ + +public class OLAPObjectList extends ObjectList implements GaussOLAPDBMSObject { + + /** + * Instantiates a new OLAP object list. + * + * @param type the type + * @param parentObject the parent object + */ + public OLAPObjectList(OBJECTTYPE type, Object parentObject) { + super(type, parentObject); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/ObjectGroup.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/ObjectGroup.java new file mode 100644 index 0000000000000000000000000000000000000000..ffa5b5d15e4e49f43a2bd6c01d3bb827a9881716 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/ObjectGroup.java @@ -0,0 +1,604 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +import java.util.ArrayList; +import java.util.ConcurrentModificationException; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map.Entry; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; + +import org.apache.commons.collections4.trie.PatriciaTrie; +import org.apache.commons.lang3.StringUtils; + +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.INamespace; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.ShowMoreObject; +import org.opengauss.mppdbide.bl.util.BLUtils; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * Title: class Description: The Class ObjectGroup. + * + * @param the generic type + * @since 17 May, 2019 + */ + +public class ObjectGroup implements Iterable { + + /** + * The type. + */ + protected OBJECTTYPE type; + + /** + * The display name. + */ + protected String displayName = ""; + + private ConcurrentHashMap objMap; + + private Object parent; + + private final PatriciaTrie trie; + + private int objectToDisplayCount; + + private IBLPreference blPreference; + + /** + * Instantiates a new object group. + * + * @param type the type + * @param parentObject the parent object + */ + public ObjectGroup(OBJECTTYPE type, Object parentObject) { + this.type = type; + + setDisplayName(type); + objMap = new ConcurrentHashMap(4); + trie = new PatriciaTrie(); + this.parent = parentObject; + blPreference = BLPreferenceManager.getInstance().getBLPreference(); + objectToDisplayCount = blPreference.getLazyRenderingObjectCount(); + } + + /** + * Sets the display name. + * + * @param type the new display name + */ + private void setDisplayName(OBJECTTYPE type) { + setDisplayNameFirst(type); + switch (type) { + case DATATYPE_GROUP: { + this.displayName = MessageConfigLoader.getProperty(IMessagesConstants.DATATYPE_NAME); + break; + } + case ACCESSMETHOD_GROUP: { + this.displayName = MessageConfigLoader.getProperty(IMessagesConstants.ACCESS_METHOD_NAME); + break; + } + case FOREIGN_TABLE_GROUP: { + this.displayName = MessageConfigLoader.getProperty(IMessagesConstants.FOREIGN_TABLE_GROUP); + break; + } + case USER_ROLE_GROUP: { + this.displayName = MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_GROUP_DISPLAY_NAME); + break; + } + default: { + break; + } + } + setDisplayNameForCommons(type); + } + + private void setDisplayNameForCommons(OBJECTTYPE type) { + switch (type) { + case VIEW_GROUP: { + this.displayName = MessageConfigLoader.getProperty(IMessagesConstants.VIEWS_NAME); + break; + } + case SEQUENCE_GROUP: { + this.displayName = MessageConfigLoader.getProperty(IMessagesConstants.SEQUENCE); + break; + } + case SYNONYM_GROUP: { + this.displayName = MessageConfigLoader.getProperty(IMessagesConstants.SYNONYM_GROUP_NAME); + break; + } + case TRIGGER_GROUP: { + this.displayName = MessageConfigLoader.getProperty(IMessagesConstants.TRIGGER_GROUP_NAME); + break; + } + default: { + break; + } + } + } + + /** + * Sets the display name first. + * + * @param type2 the new display name first + */ + private void setDisplayNameFirst(OBJECTTYPE type2) { + switch (type2) { + case TABLESPACE_GROUP: { + this.displayName = MessageConfigLoader.getProperty(IMessagesConstants.TABLESPACES_NAME); + break; + } + case DATABASE_GROUP: { + this.displayName = MessageConfigLoader.getProperty(IMessagesConstants.DATABASES_NAME); + break; + } + case USER_NAMESPACE_GROUP: { + this.displayName = MessageConfigLoader.getProperty(IMessagesConstants.USER_NAMESPACE_NAME); + break; + } + case SYSTEM_NAMESPACE_GROUP: { + this.displayName = MessageConfigLoader.getProperty(IMessagesConstants.SYSTEM_NAMESPACE_NAME); + break; + } + case FUNCTION_GROUP: { + this.displayName = MessageConfigLoader.getProperty(IMessagesConstants.FUNCTION_PROCEDURE_NAME); + break; + } + case TABLE_GROUP: { + this.displayName = MessageConfigLoader.getProperty(IMessagesConstants.TABLES_NAME); + break; + } + default: { + break; + } + } + } + + /** + * Gets the object group type. + * + * @return the object group type + */ + public OBJECTTYPE getObjectGroupType() { + return type; + } + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + return displayName; + } + + /** + * Adds the to group. + * + * @param obj the obj + */ + public void addToGroup(T obj) { + objMap.put(obj.getOid(), obj); + addServerObjectToSortList(obj); + } + + /** + * Removes the from group. + * + * @param oid the oid + */ + public void removeFromGroup(long oid) { + if (objMap.containsKey(oid)) { + T obj = objMap.get(oid); + objMap.remove(oid); + removeServerObjectFromSortList(obj); + } + } + + /** + * Contains. + * + * @param oid the oid + * @return true, if successful + */ + public boolean contains(long oid) { + if (objMap.containsKey(oid)) { + return true; + } + return false; + } + + /** + * Gets the object by id. + * + * @param oid the oid + * @return the object by id + */ + public T getObjectById(long oid) { + return objMap.get(oid); + } + + /** + * Add a server object. + * + * @param object the object + */ + private void addServerObjectToSortList(T object) { + synchronized (trie) { + trie.put(object.getSearchName(), object); + } + } + + /** + * Removes the server object from sort list. + * + * @param object the object + * @return true, if successful + */ + private boolean removeServerObjectFromSortList(T object) { + synchronized (trie) { + trie.remove(object.getSearchName()); + } + + return false; + } + + /** + * Gets the matching. + * + * @param prefix the prefix + * @return the matching + */ + public SortedMap getMatching(String prefix) { + String prefixShort = ""; + if (null != prefix) { + if (prefix.length() > 3) { + prefixShort = prefix.substring(0, 2); + } else { + prefixShort = prefix; + } + } + SortedMap map = getAllObjectWithPrefixCaseInsensitive(prefixShort); + SortedMap serverObjMap = new TreeMap(); + for (ServerObject obj : map.values()) { + serverObjMap.put(obj.getOid(), obj); + } + SortedMap resultMap = new TreeMap(); + for (ServerObject obj : serverObjMap.values()) { + if (prefix != null + && obj.getSearchName().toLowerCase(Locale.ENGLISH).startsWith(prefix.toLowerCase(Locale.ENGLISH))) { + resultMap.put(obj.getSearchName(), obj); + } + } + + return (SortedMap) resultMap; + } + + /** + * Gets the all object with prefix case insensitive. + * + * @param text the text + * @return the all object with prefix case insensitive + */ + private SortedMap getAllObjectWithPrefixCaseInsensitive(String text) { + SortedMap map = new TreeMap(); + ArrayList prefixList = BLUtils.getAllCombinationsOfPrefix(text); + for (String prefix : prefixList) { + map.putAll(trie.prefixMap(String.valueOf(prefix))); + } + return map; + } + + /** + * Gets the. + * + * @param name the name + * @return the t + */ + public T get(String name) { + SortedMap map = getMatching(name); + + for (Entry entry : map.entrySet()) { + T object = entry.getValue(); + if (name.equals(object.getName())) { + return object; + } + } + + return null; + } + + /** + * Gets the matching hyper link. + * + * @param prefix the prefix + * @return the matching hyper link + */ + public SortedMap getMatchingHyperLink(String prefix) { + + SortedMap map = getMatching(prefix); + SortedMap retMap = new TreeMap(); + + for (Entry entry : map.entrySet()) { + T object = entry.getValue(); + if (prefix.equals(object.getName())) { + retMap.put(entry.getKey(), object); + } + } + return retMap; + + } + + /** + * Gets the matching tables hyper link. + * + * @param prefix the prefix + * @return the matching tables hyper link + */ + public SortedMap getMatchingTablesHyperLink(String prefix) { + SortedMap map = new TreeMap(); + Entry entry = trie.select(prefix); + if (null != entry) { + String key = entry.getKey(); + String[] keys = key.split(" "); + String keyToMatch = keys[0]; + if (keyToMatch.equals(prefix)) { + map.put(entry.getKey(), entry.getValue()); + } + } + return map; + + } + + /** + * Gets the sorted server object list. + * + * @return the sorted server object list + */ + + public ArrayList getSortedServerObjectList() { + try { + ArrayList list = new ArrayList(10); + list.addAll(trie.values()); + return list; + } catch (ConcurrentModificationException e) { + return new ArrayList(10); + } + } + + /** + * Clear. + */ + public void clear() { + objMap.clear(); + trie.clear(); + } + + /** + * Gets the size. + * + * @return the size + */ + public int getSize() { + return trie.size(); + } + + /** + * Gets the parent. + * + * @return the parent + */ + public Object getParent() { + return this.parent; + } + + /** + * Iterator. + * + * @return the iterator + */ + @Override + public Iterator iterator() { + return trie.values().iterator(); + } + + /** + * Gets the display label. + * + * @return the display label + */ + public String getDisplayLabel() { + return getName(); + } + + /** + * Gets the children. + * + * @return the children + */ + public Object[] getChildren() { + + List sortedServerObjectList = this.getSortedServerObjectList(); + + String text = FilterObject.getInstance().getFilterText(); + + if (StringUtils.isEmpty(text)) { + return addMoreObjectsOption(sortedServerObjectList); + } + + if (getObjectType()) { + sortedServerObjectList = sortedServerObjectList.stream().filter( + article -> article.getName().toLowerCase(Locale.ENGLISH).contains(text.toLowerCase(Locale.ENGLISH))) + .collect(Collectors.toList()); + } + return addMoreObjectsOption(sortedServerObjectList); + } + + /** + * Add "More Objects.." option for rendering next batch of objects + * + * @param sorted list of all loaded objects + * @return sublist with "More Objects" option + */ + private Object[] addMoreObjectsOption(List sortedServerObjectList) { + + if (sortedServerObjectList.size() >= this.objectToDisplayCount) { + List subList = sortedServerObjectList.subList(0, objectToDisplayCount); + subList.add((T) new ShowMoreObject(OBJECTTYPE.SHOW_MORE_OBJECTS, this)); + return subList.toArray(); + } else { + return sortedServerObjectList.toArray(); + } + + } + + /** + * Increment show object count. + */ + public void incrementShowObjectCount() { + this.objectToDisplayCount += blPreference.getLazyRenderingObjectCount(); + } + + /** + * Gets the object type. + * + * @return the object type + */ + public boolean getObjectType() { + return this.type == OBJECTTYPE.TABLE_GROUP || this.type == OBJECTTYPE.FUNCTION_GROUP + || this.type == OBJECTTYPE.VIEW_GROUP || this.type == OBJECTTYPE.SEQUENCE_GROUP + || this.type == OBJECTTYPE.FOREIGN_TABLE_GROUP || this.type == OBJECTTYPE.INDEX_GROUP + || this.type == OBJECTTYPE.PARTITION_GROUP || this.type == OBJECTTYPE.SYNONYM_GROUP; + } + + /** + * Gets the object browser label. + * + * @return the object browser label + */ + public String getObjectBrowserLabel() { + int size = getSize(); + return getName() + " (" + size + ") "; + } + + /** + * Hash code. + * + * @return the int + */ + @Override + public int hashCode() { + final int prime = MPPDBIDEConstants.PRIME_31; + int result = 1; + result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); + result = prime * result + ((getParent() == null) ? 0 : getParent().hashCode()); + return result; + } + + /** + * Equals. + * + * @param obj the obj + * @return true, if successful + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + + if (obj == null) { + return false; + } + + if (!(obj instanceof ObjectGroup)) { + return false; + } + + ObjectGroup other = (ObjectGroup) obj; + if (getName() == null) { + if (other.getName() != null) { + return false; + } + } else if (!getName().equals(other.getName())) { + return false; + } + + if (getParent() == null) { + if (other.getParent() != null) { + return false; + } + } else if (!getParent().equals(other.getParent())) { + return false; + } + + if (this.type != other.getObjectGroupType()) { + return false; + } + + return true; + } + + /** + * Removes the. + * + * @param obj the obj + */ + public void remove(T obj) { + removeFromGroup(obj.getOid()); + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + + return null; + } + + /** + * Gets the namespace. + * + * @return the namespace + */ + public INamespace getNamespace() { + return null; + } + + /** + * Gets the children without filter. + * + * @return the children without filter + */ + public Object[] getChildrenWithoutFilter() { + return this.getSortedServerObjectList().toArray(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/ObjectList.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/ObjectList.java new file mode 100644 index 0000000000000000000000000000000000000000..9c0f27d2f6189ce11d2dad7c805308d9f7546ddd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/ObjectList.java @@ -0,0 +1,391 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +import java.util.ArrayList; +import java.util.Locale; +import java.util.Map.Entry; +import java.util.Set; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.apache.commons.collections4.trie.PatriciaTrie; + +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.util.BLUtils; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class ObjectList. + * + * @param the generic type + */ + +public class ObjectList { + + /** + * The type. + */ + protected OBJECTTYPE type; + + /** + * The name. + */ + protected String name; + private final ArrayList list; + private Object parent; + private final PatriciaTrie trie; + + /** + * Instantiates a new object list. + * + * @param type the type + * @param parentObject the parent object + */ + public ObjectList(OBJECTTYPE type, Object parentObject) { + this.type = type; + + switch (type) { + case COLUMN_GROUP: { + this.name = MessageConfigLoader.getProperty(IMessagesConstants.COLUMNS_NAME); + break; + } + case CONSTRAINT_GROUP: { + this.name = MessageConfigLoader.getProperty(IMessagesConstants.CONSTRAINTS_NAME); + break; + } + case INDEX_GROUP: { + this.name = MessageConfigLoader.getProperty(IMessagesConstants.INDEXES_NAME); + break; + } + case VIEW_COLUMN_GROUP: { + this.name = MessageConfigLoader.getProperty(IMessagesConstants.VIEW_COLUMNS_NAME); + break; + } + case PARTITION_GROUP: { + this.name = MessageConfigLoader.getProperty(IMessagesConstants.PARTITION_GROUP_NAME); + break; + } + default: { + break; + } + } + + list = new ArrayList(4); + trie = new PatriciaTrie(); + this.parent = parentObject; + } + + /** + * Gets the type. + * + * @return the type + */ + public OBJECTTYPE getType() { + return type; + } + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + return this.name; + } + + /** + * Sets the name. + * + * @param name the new name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Gets the list. + * + * @return the list + */ + public ArrayList getList() { + return list; + } + + /** + * Find matching. + * + * @param prefixOne the prefix + * @return the sorted map + */ + public SortedMap findMatching(String prefixOne) { + String prefixShort = ""; + if (null != prefixOne) { + if (prefixOne.length() > 3) { + prefixShort = prefixOne.substring(0, 2); + } else { + prefixShort = prefixOne; + } + } + SortedMap map = getAllObjectWithPrefixCaseInsensitive(prefixShort); + SortedMap serverObjMap = new TreeMap(); + for (ServerObject obj : map.values()) { + serverObjMap.put(obj.getOid(), obj); + } + SortedMap resultMap = new TreeMap(); + for (ServerObject obj : serverObjMap.values()) { + if (prefixOne != null && obj.getSearchName().toLowerCase(Locale.ENGLISH) + .startsWith(prefixOne.toLowerCase(Locale.ENGLISH))) { + resultMap.put(obj.getSearchName(), obj); + } + } + + return (SortedMap) resultMap; + } + + /** + * Gets the all object with prefix case insensitive. + * + * @param text the text + * @return the all object with prefix case insensitive + */ + private SortedMap getAllObjectWithPrefixCaseInsensitive(String text) { + SortedMap map = new TreeMap(); + ArrayList prefixList = BLUtils.getAllCombinationsOfPrefix(text); + for (String prefix : prefixList) { + map.putAll(trie.prefixMap(String.valueOf(prefix))); + } + return map; + } + + /** + * Move item. + * + * @param index the index + * @param isUp the is up + */ + public void moveItem(int index, boolean isUp) { + T item = this.list.get(index); + int newIndex = isUp ? (index - 1) : (index + 1); + + this.list.remove(index); + this.list.add(newIndex, item); + } + + /** + * Gets the item. + * + * @param index the index + * @return the item + */ + public T getItem(int index) { + return this.list.get(index); + } + + /** + * Adds the item. + * + * @param item the item + */ + public void addItem(T item) { + this.list.add(item); + this.trie.put(item.getSearchName(), item); + } + + /** + * Adds the item at index. + * + * @param item the item + * @param index the index + */ + public void addItemAtIndex(T item, int index) { + if (this.list.size() < index) { + this.list.add(item); + } else { + this.list.add(index, item); + } + this.trie.put(item.getSearchName(), item); + } + + /** + * Removes the item by idx. + * + * @param index the index + */ + public void removeItemByIdx(int index) { + + T item = getItem(index); + this.trie.remove(item.getSearchName()); + this.list.remove(index); + } + + /** + * Removes the. + * + * @param item the item + */ + public void remove(T item) { + if (item != null) { + this.trie.remove(item.getSearchName()); + this.list.remove(item); + } + } + + /** + * Gets the size. + * + * @return the size + */ + public int getSize() { + return this.list.size(); + } + + /** + * Clear. + */ + public void clear() { + this.trie.clear(); + this.list.clear(); + } + + /** + * Gets the parent. + * + * @return the parent + */ + public Object getParent() { + return this.parent; + } + + /** + * Gets the. + * + * @param objName the obj name + * @return the t + */ + public T get(String objName) { + Entry entry = trie.select(objName); + return null == entry ? null : entry.getValue(); + } + + /** + * Gets the object by id. + * + * @param oid the oid + * @return the object by id + */ + public T getObjectById(long oid) { + for (T item : list) { + if (item.getOid() == oid) { + return item; + } + } + + return null; + } + + @Override + public int hashCode() { + final int primeNumber = 31; + int result = 1; + result = getHashCodeForCurrentObject(primeNumber, result); + result = getHashCodeForParentObject(primeNumber, result); + return result; + } + + /** + * Gets the hash code for parent object. + * + * @param primeNumber the prime number + * @param result the result + * @return the hash code for parent object + */ + private int getHashCodeForParentObject(final int primeNumber, int result) { + return getRamdomNumber(primeNumber, result) + (validateObjectForNull(getParent()) ? 0 : getParent().hashCode()); + } + + /** + * Gets the ramdom number. + * + * @param primeNumber the prime number + * @param result the result + * @return the ramdom number + */ + private int getRamdomNumber(final int primeNumber, int result) { + return primeNumber * result; + } + + /** + * Gets the hash code for current object. + * + * @param primeNumber the prime number + * @param result the result + * @return the hash code for current object + */ + private int getHashCodeForCurrentObject(final int primeNumber, int result) { + return getRamdomNumber(primeNumber, result) + (validateObjectForNull(getName()) ? 0 : getName().hashCode()); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + + if (validateObjectForNull(obj)) { + return false; + } + + if (!(obj instanceof ObjectList)) { + return false; + } + + ObjectList other = (ObjectList) obj; + if (validateObjectForNull(getName())) { + if (!validateObjectForNull(other.getName())) { + return false; + } + } else if (!getName().equals(other.getName())) { + return false; + } + + if (validateObjectForNull(getParent())) { + if (!validateObjectForNull(other.getParent())) { + return false; + } + } else if (!getParent().equals(other.getParent())) { + return false; + } + + return true; + } + + /** + * Validate object for null. + * + * @param obj the obj + * @return true, if successful + */ + private boolean validateObjectForNull(Object obj) { + return obj == null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/PartitionList.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/PartitionList.java new file mode 100644 index 0000000000000000000000000000000000000000..d7fd8612eb48aef7d76b19af9d87dba595d984e7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/PartitionList.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.PartitionMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.PartitionTable; + +/** + * + * Title: class + * + * Description: The Class PartitionList. + * + */ + +public class PartitionList extends OLAPObjectList { + + /** + * Instantiates a new partition list. + * + * @param type the type + * @param parentObject the parent object + */ + public PartitionList(OBJECTTYPE type, Object parentObject) { + super(type, parentObject); + } + + /** + * Gets the parent. + * + * @return the parent + */ + public PartitionTable getParent() { + return (PartitionTable) super.getParent(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/SequenceObjectGroup.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/SequenceObjectGroup.java new file mode 100644 index 0000000000000000000000000000000000000000..6c6b19a3004ea5d825eb5684cd8e84632f099bb1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/SequenceObjectGroup.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.SequenceMetadata; + +/** + * + * Title: class + * + * Description: The Class SequenceObjectGroup. + * + */ + +public class SequenceObjectGroup extends OLAPObjectGroup { + + /** + * Instantiates a new sequence object group. + * + * @param type the type + * @param nm the nm + */ + public SequenceObjectGroup(OBJECTTYPE type, Namespace nm) { + super(type, nm); + + } + + /** + * Gets the display label. + * + * @return the display label + */ + public String getDisplayLabel() { + return this.getName() + " (" + this.getSize() + ')'; + } + + /** + * Gets the namespace. + * + * @return the namespace + */ + public Namespace getNamespace() { + return (Namespace) getParent(); + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + return getNamespace().getDatabase(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/SynonymObjectGroup.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/SynonymObjectGroup.java new file mode 100644 index 0000000000000000000000000000000000000000..9b16038120f222818d2905d1bb8eb155851f26c0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/SynonymObjectGroup.java @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.SynonymMetaData; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class SynonymObjectGroup. + * + * @since 3.0.0 + */ +public class SynonymObjectGroup extends OLAPObjectGroup { + private static final String QUERY_FOR_ALL_NORMAL_TABLES_BY_NAMESPACE_ID = "select tbl.relname relname " + + "from pg_class tbl left join pg_partition part on(tbl.oid=part.parentid and part.parttype='r') " + + "where tbl.relkind = 'r' and tbl.relnamespace = %d"; + private static final String QUERY_FOR_ALL_FOREIGN_TABLES_BY_NAMESPACE_ID = "SELECT c.relname AS relname" + + " FROM pg_class c WHERE (c.relkind = 'f' :: char) and c.relnamespace = %d"; + private static final String QUERY_BY_SCHEMA_ID = "SELECT c.relname AS relname FROM pg_class c " + + "WHERE (c.relkind = 'v' :: char or c.relkind = 'm' :: char) and c.relnamespace = %d "; + private static final String QUERY_FOR_ALL_FUNCTIONS_BY_NAMESPACE_ID = "SELECT pr.proname relname " + + "FROM pg_proc pr JOIN pg_type typ ON typ.oid = prorettype JOIN pg_namespace typns " + + "ON typns.oid = typ.typnamespace JOIN pg_language lng ON lng.oid = prolang " + + "and pronamespace = %d and has_function_privilege(pr.oid, 'EXECUTE') ORDER BY relname"; + + private Namespace namespace = null; + private Database database = null; + + /** + * Instantiates a new synonym object group + * + * @param type the type + * @param parentObject the parent object + */ + public SynonymObjectGroup(OBJECTTYPE type, Object parentObject) { + super(type, parentObject); + if (parentObject instanceof Namespace) { + namespace = (Namespace) parentObject; + database = namespace.getDatabase(); + } + } + + + /** + * gets the Database + * + * @return database the database + */ + @Override + public Database getDatabase() { + return this.database; + } + + @Override + public Object getParent() { + return this.namespace; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } + + /** + * Fetch object name. + * + * @param namespace the namespace + * @param dbConnection the db connection + * @param objectOwner the object owner + * @param objectType the object type + * @return the list + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public static List fetchObjectName(Namespace namespace, DBConnection dbConnection, String objectOwner, + String objectType) throws DatabaseOperationException, DatabaseCriticalException { + String fetchObjName = String.format(Locale.ENGLISH, QUERY_FOR_ALL_NORMAL_TABLES_BY_NAMESPACE_ID, + namespace.getOid()) + " UNION " + + String.format(Locale.ENGLISH, QUERY_FOR_ALL_FOREIGN_TABLES_BY_NAMESPACE_ID, namespace.getOid()) + + " UNION " + String.format(Locale.ENGLISH, QUERY_BY_SCHEMA_ID, namespace.getOid()) + " UNION " + + String.format(Locale.ENGLISH, QUERY_FOR_ALL_FUNCTIONS_BY_NAMESPACE_ID, namespace.getOid()); + String fetchObejctNamesStatement = null; + if (objectType.equals(MPPDBIDEConstants.PRIVILEGE_ALL)) { + fetchObejctNamesStatement = String.format(Locale.ENGLISH, fetchObjName, namespace.getOid()); + } else if (objectType.equals(MessageConfigLoader.getProperty(IMessagesConstants.FUNCTION_PROCEDURE_NAME))) { + fetchObejctNamesStatement = String.format(Locale.ENGLISH, QUERY_FOR_ALL_FUNCTIONS_BY_NAMESPACE_ID, + namespace.getOid()); + } else if (objectType.equals(MessageConfigLoader.getProperty(IMessagesConstants.TABLES_NAME))) { + fetchObejctNamesStatement = String.format(Locale.ENGLISH, QUERY_FOR_ALL_NORMAL_TABLES_BY_NAMESPACE_ID, + namespace.getOid()) + " UNION " + + String.format(Locale.ENGLISH, QUERY_FOR_ALL_FOREIGN_TABLES_BY_NAMESPACE_ID, namespace.getOid()); + } else if (objectType.equals(MessageConfigLoader.getProperty(IMessagesConstants.VIEWS_NAME))) { + fetchObejctNamesStatement = String.format(Locale.ENGLISH, QUERY_BY_SCHEMA_ID, namespace.getOid()); + } else { + return new ArrayList(); + } + + ResultSet rs = null; + PreparedStatement preparedStatement = null; + try { + preparedStatement = dbConnection.getPrepareStmt(fetchObejctNamesStatement); + + rs = preparedStatement.executeQuery(); + boolean hasNext = rs.next(); + List objectNameList = new ArrayList<>(); + while (hasNext) { + String objectName = rs.getString("relname"); + objectNameList.add(objectName); + hasNext = rs.next(); + } + return objectNameList; + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } finally { + if (rs != null) { + dbConnection.closeResultSet(rs); + } + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/SystemNamespaceObjectGroup.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/SystemNamespaceObjectGroup.java new file mode 100644 index 0000000000000000000000000000000000000000..f84aaa6043d7026f98cb1e43210bb438b869819e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/SystemNamespaceObjectGroup.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +import java.util.List; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.SystemNamespace; + +/** + * + * Title: class + * + * Description: The Class SystemNamespaceObjectGroup. + * + */ + +public class SystemNamespaceObjectGroup extends OLAPObjectGroup { + + /** + * Instantiates a new system namespace object group. + * + * @param type the type + * @param parentObject the parent object + */ + public SystemNamespaceObjectGroup(OBJECTTYPE type, Database parentObject) { + super(type, parentObject); + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + return (Database) getParent(); + } + + /** + * Gets the object browser label. + * + * @return the object browser label + */ + public String getObjectBrowserLabel() { + int sysNsSize = 0; + List sysNamespaceList = getDatabase().getAllSystemNameSpaces(); + for (Namespace ns : sysNamespaceList) { + if (ns.isLoaded()) { + sysNsSize += ns.getChildrenSize(); + } + } + return getName() + " (" + sysNsSize + ") "; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/TableObjectGroup.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/TableObjectGroup.java new file mode 100644 index 0000000000000000000000000000000000000000..7ecf37c49828c2da2d7d1e63ddc89ec3068f7ca3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/TableObjectGroup.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; + +/** + * + * Title: class + * + * Description: The Class TableObjectGroup. + * + */ + +public class TableObjectGroup extends OLAPObjectGroup { + + /** + * Instantiates a new table object group. + * + * @param type the type + * @param nm the nm + */ + public TableObjectGroup(OBJECTTYPE type, Namespace nm) { + super(type, nm); + } + + @Override + public Namespace getNamespace() { + return (Namespace) getParent(); + } + + /** + * Gets the display label. + * + * @return the display label + */ + public String getDisplayLabel() { + return this.getName() + " (" + this.getSize() + ')'; + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + return getNamespace().getDatabase(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/TablespaceObjectGroup.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/TablespaceObjectGroup.java new file mode 100644 index 0000000000000000000000000000000000000000..29e9885ba0b928f8bdf9d569aa737af1ce012e7f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/TablespaceObjectGroup.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.Tablespace; + +/** + * + * Title: class + * + * Description: The Class TablespaceObjectGroup. + * + */ + +public class TablespaceObjectGroup extends OLAPObjectGroup { + + /** + * Instantiates a new tablespace object group. + * + * @param type the type + * @param server the server + */ + public TablespaceObjectGroup(OBJECTTYPE type, Server server) { + super(type, server); + } + + /** + * Gets the server. + * + * @return the server + */ + public Server getServer() { + return (Server) getParent(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/TriggerObjectGroup.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/TriggerObjectGroup.java new file mode 100644 index 0000000000000000000000000000000000000000..c89d57dc8f4504937a9dba42e0897be34b15af86 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/TriggerObjectGroup.java @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.LinkedList; +import java.util.List; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.TriggerMetaData; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: the class TriggerObjectGroup + * Description: the class TriggerObjectGroup + * + * @since 3.0.0 + */ +public class TriggerObjectGroup extends OLAPObjectGroup { + private static final String QUERY_ALL_TRIGGER = "select t.oid as oid, t.tgrelid as tableoid," + + " t.tgname as name, t.tgfoid as functionoid, t.tgtype as tgtype," + + " t.tgenabled as tgenable," + + " pg_get_triggerdef(t.oid) as ddlmsg" + + " from pg_trigger t, pg_class c" + + " where t.tgrelid = c.oid and c.relnamespace=?"; + + private static final String QUERY_TRIGGER_BY_NAME = QUERY_ALL_TRIGGER + + " and t.tgname = ?"; + private Namespace namespace; + + public TriggerObjectGroup(Object parentObject) { + super(OBJECTTYPE.TRIGGER_GROUP, parentObject); + if (parentObject instanceof Namespace) { + namespace = (Namespace) parentObject; + } + } + + @Override + public Database getDatabase() { + return namespace.getDatabase(); + } + + /** + * description: get namespace + * + * @return Namespace the namespace + */ + public Namespace getNamespace() { + return namespace; + } + + /** + * description: fetch all triggers from database + * + * @param Namespace the namespace + * @param DBConnection the connection + * @throws DatabaseOperationException operation exp + * @throws DatabaseCriticalException critical exp + */ + public static void fetchTriggers(Namespace ns, DBConnection conn) + throws DatabaseOperationException, DatabaseCriticalException { + ns.getTriggerObjectGroup().clear(); + Object[] params = new Object[1]; + params[0] = Long.valueOf(ns.getOid()); + List triggres = fetchTriggers(ns, conn, QUERY_ALL_TRIGGER, params); + for (TriggerMetaData trigger: triggres) { + ns.addTrigger(trigger); + } + } + + /** + * description: fetch all triggers from database by name + * + * @param Namespace the namespace + * @param DBConnection the connection + * @param String the query trigger name + * @return List trigger metadata list + * @throws DatabaseOperationException operation exp + * @throws DatabaseCriticalException critical exp + */ + public static List fetchTriggerByName(Namespace ns, + DBConnection conn, + String name) + throws DatabaseOperationException, DatabaseCriticalException { + Object[] params = new Object[2]; + params[0] = Long.valueOf(ns.getOid()); + params[1] = name; + return fetchTriggers(ns, conn, QUERY_TRIGGER_BY_NAME, params); + } + + /** + * description: fetch all triggers from database + * + * @param Namespace the namespace + * @param DBConnection the connection + * @param String the query sql + * @param Object[] the query params + * @return List trigger metadata list + * @throws DatabaseOperationException operation exp + * @throws DatabaseCriticalException critical exp + */ + public static List fetchTriggers(Namespace ns, + DBConnection conn, + String query, + Object[] params) throws DatabaseOperationException, DatabaseCriticalException { + List resutls = new LinkedList<>(); + try (PreparedStatement ps = conn.getPrepareStmt(query)) { + for (int i = 0, n = params.length; i < n; i ++) { + ps.setObject(i + 1, params[i]); + } + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + TriggerMetaData trigger = parseTrigger(rs, ns); + resutls.add(trigger); + } + } + } catch (DatabaseOperationException | SQLException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exception); + + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } + return resutls; + } + + private static TriggerMetaData parseTrigger(ResultSet rs, Namespace ns) throws SQLException { + long oid = rs.getLong("oid"); + long tableoid = rs.getLong("tableoid"); + String name = rs.getString("name"); + long funcOid = rs.getLong("functionoid"); + String triggerType = rs.getString("tgtype"); + String triggerEnable = rs.getString("tgenable"); + String ddlMsg = rs.getString("ddlmsg"); + TriggerMetaData trigger = new TriggerMetaData(oid, name); + trigger.setNamespace(ns); + trigger.setTableoid(tableoid); + trigger.setFuncOid(funcOid); + trigger.setTriggerType(triggerType); + trigger.setTriggerEnable(triggerEnable); + trigger.setEnable("D".equalsIgnoreCase(triggerEnable) ? false : true); + trigger.setDdlMsg(ddlMsg); + return trigger; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/UserNamespaceObjectGroup.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/UserNamespaceObjectGroup.java new file mode 100644 index 0000000000000000000000000000000000000000..7fc521e7a700b9833ccbaaa9f3e063b08ff795b3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/UserNamespaceObjectGroup.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +import java.util.List; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.UserNamespace; + +/** + * + * Title: class + * + * Description: The Class UserNamespaceObjectGroup. + * + */ + +public class UserNamespaceObjectGroup extends OLAPObjectGroup { + + /** + * Instantiates a new user namespace object group. + * + * @param type the type + * @param parentObject the parent object + */ + public UserNamespaceObjectGroup(OBJECTTYPE type, Database parentObject) { + super(type, parentObject); + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + return (Database) getParent(); + } + + /** + * Gets the object browser label. + * + * @return the object browser label + */ + public String getObjectBrowserLabel() { + int userNsSize = 0; + List userNamespaceList = getDatabase().getAllUserNameSpaces(); + for (Namespace ns : userNamespaceList) { + if (ns.isLoaded()) { + userNsSize += ns.getChildrenSize(); + } + } + return getName() + " (" + userNsSize + ") "; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/UserRoleObjectGroup.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/UserRoleObjectGroup.java new file mode 100644 index 0000000000000000000000000000000000000000..813566d9708fe54261c8707bb12ead91e3562969 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/UserRoleObjectGroup.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.UserRole; + +/** + * + * Title: class + * + * Description: The Class UserRoleObjectGroup. + * + */ + +public class UserRoleObjectGroup extends OLAPObjectGroup { + + /** + * Instantiates a new user role object group. + * + * @param type the type + * @param server the server + */ + public UserRoleObjectGroup(OBJECTTYPE type, Server server) { + super(type, server); + } + + /** + * Gets the server. + * + * @return the server + */ + public Server getServer() { + return (Server) getParent(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/ViewColumnList.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/ViewColumnList.java new file mode 100644 index 0000000000000000000000000000000000000000..f15cdf374f4d0807feb4373f104a56f36774d7d1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/ViewColumnList.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.ViewColumnMetaData; + +/** + * + * Title: class + * + * Description: The Class ViewColumnList. + * + */ + +public class ViewColumnList extends OLAPObjectList { + + /** + * Instantiates a new view column list. + * + * @param parentObject the parent object + */ + public ViewColumnList(Object parentObject) { + super(OBJECTTYPE.VIEW_COLUMN_GROUP, parentObject); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/ViewObjectGroup.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/ViewObjectGroup.java new file mode 100644 index 0000000000000000000000000000000000000000..db48763a74062f8fb3f98ecf6acadcf182880596 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/groups/ViewObjectGroup.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.groups; + +import java.util.SortedMap; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.IViewObjectGroups; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ViewUtils; + +/** + * + * Title: class + * + * Description: The Class ViewObjectGroup. + * + */ + +public class ViewObjectGroup extends OLAPObjectGroup implements IViewObjectGroups { + + /** + * Instantiates a new view object group. + * + * @param parentObject the parent object + */ + public ViewObjectGroup(Object parentObject) { + super(OBJECTTYPE.VIEW_GROUP, parentObject); + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + return ((Namespace) getParent()).getDatabase(); + } + + @Override + public String getTemplateCode() { + Object parent = getParent(); + if (parent instanceof Namespace) { + return ViewUtils.getCreateViewTemplate((Namespace) parent); + } + return ""; + } + + @Override + public boolean isDbConnected() { + Object parent = getParent(); + if (parent instanceof Namespace) { + Namespace ns = (Namespace) parent; + return ns.getDatabase().isConnected(); + } + return false; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/helper/SchemaHelper.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/helper/SchemaHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..7ac157aa17bb6263a4af047b507269e67b630bd5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/helper/SchemaHelper.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.helper; + +import java.util.Set; +import java.util.SortedMap; + +import org.opengauss.mppdbide.bl.contentassist.ContentAssistUtilIf; +import org.opengauss.mppdbide.bl.contentassist.ContentAssistUtilOLAP; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; + +/** + * + * Title: class + * + * Description: The Class SchemaHelper. + * + */ + +public class SchemaHelper { + + /** + * Check for invalid namespaces in include list. + * + * @param db the db + * @return the string + */ + public static String checkForInvalidNamespacesInIncludeList(Database db) { + StringBuffer buff = new StringBuffer(); + Set includeExcludeList = db.getSchemInclusionList(); + matchIncludeExcludeSchemas(buff, includeExcludeList, db); + return buff.length() == 0 ? null : buff.substring(0, buff.length() - 1); + } + + /** + * Check for invalid namespaces in exclude list. + * + * @param db the db + * @return the string + */ + public static String checkForInvalidNamespacesInExcludeList(Database db) { + StringBuffer buff = new StringBuffer(); + Set includeExcludeList = db.getSchemExclusionList(); + matchIncludeExcludeSchemas(buff, includeExcludeList, db); + return buff.length() == 0 ? null : buff.substring(0, buff.length() - 1); + } + + private static void matchIncludeExcludeSchemas(StringBuffer buff, Set includeExcludeList, Database db) { + SortedMap matchedList = null; + ContentAssistUtilIf contentAssistUtil; + for (String namespace : includeExcludeList) { + contentAssistUtil = new ContentAssistUtilOLAP(db); + matchedList = contentAssistUtil.findExactMatchingNamespaces(namespace); + if (matchedList.isEmpty()) { + buff.append(namespace); + buff.append(","); + } + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/savepsswordoption/SavePrdOptions.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/savepsswordoption/SavePrdOptions.java new file mode 100644 index 0000000000000000000000000000000000000000..f4538b2ea4ab4b39514142183c7b530b28c8734c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/serverdatacache/savepsswordoption/SavePrdOptions.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption; + +/** + * + * Title: enum + * + * Description: The Enum SavePrdOptions. + * + */ + +public enum SavePrdOptions { + PERMANENTLY, CURRENT_SESSION_ONLY, DO_NOT_SAVE +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/ExlainQueryExecutionSummary.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/ExlainQueryExecutionSummary.java new file mode 100644 index 0000000000000000000000000000000000000000..e59bf788eafa46f105c6446be7009cb3fd7ec1dd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/ExlainQueryExecutionSummary.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.sqlhistory; + +/** + * + * Title: class + * + * Description: The Class ExlainQueryExecutionSummary. + * + */ + +public class ExlainQueryExecutionSummary extends QueryExecutionSummary { + + private boolean analyse; + + /** + * Instantiates a new exlain query execution summary. + * + * @param dbname the dbname + * @param profileId the profile id + * @param query the query + * @param querySubmitTime the query submit time + */ + public ExlainQueryExecutionSummary(String dbname, String profileId, String query, String querySubmitTime) { + super(dbname, profileId, query, querySubmitTime); + } + + @Override + public boolean isAnalyze() { + return analyse; + } + + @Override + public void setAnalyze(boolean anlyse) { + this.analyse = anlyse; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/IExlainQueryExecutionSummary.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/IExlainQueryExecutionSummary.java new file mode 100644 index 0000000000000000000000000000000000000000..81e20029e50cf114e09bdb9754e1e0d55e283c93 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/IExlainQueryExecutionSummary.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.sqlhistory; + +/** + * + * Title: interface + * + * Description: The Interface IExlainQueryExecutionSummary. + * + */ + +public interface IExlainQueryExecutionSummary extends IQueryExecutionSummary { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/IQueryExecutionSummary.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/IQueryExecutionSummary.java new file mode 100644 index 0000000000000000000000000000000000000000..97b1c9fc65c8f808c2031a55d31bb82d1b5ab9d5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/IQueryExecutionSummary.java @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.sqlhistory; + +import java.util.Date; + +/** + * + * Title: interface + * + * Description: The Interface IQueryExecutionSummary. + * + */ + +public interface IQueryExecutionSummary { + + /** + * Gets the database name. + * + * @return the database name + */ + String getDatabaseName(); + + /** + * Gets the profile id. + * + * @return the profile id + */ + String getProfileId(); + + /** + * Gets the profile name. + * + * @return the profile name + */ + String getProfileName(); + + /** + * Gets the query. + * + * @return the query + */ + String getQuery(); + + /** + * Checks if is query execution success. + * + * @return true, if is query execution success + */ + boolean isQueryExecutionSuccess(); + + /** + * Gets the execution time. + * + * @return the execution time + */ + Date getExecutionTime(); + + /** + * Gets the query start date. + * + * @return the query start date + */ + String getQueryStartDate(); + + /** + * Gets the num records fetched. + * + * @return the num records fetched + */ + int getNumRecordsFetched(); + + /** + * Sets the num records fetched. + * + * @param numRecordsFetched the new num records fetched + */ + void setNumRecordsFetched(int numRecordsFetched); + + /** + * Gets the elapsed time. + * + * @return the elapsed time + */ + String getElapsedTime(); + + /** + * Sets the elapsed time. + * + * @param elapsedTime the new elapsed time + */ + void setElapsedTime(String elapsedTime); + + /** + * Checks if is analyze. + * + * @return true, if is analyze + */ + boolean isAnalyze(); + + /** + * Start query timer. + */ + void startQueryTimer(); + + /** + * Stop query timer. + */ + void stopQueryTimer(); + + /** + * Sets the query execution status. + * + * @param b the new query execution status + */ + void setQueryExecutionStatus(boolean b); + + /** + * Sets the analyze. + * + * @param analyze the new analyze + */ + void setAnalyze(boolean analyze); + + /** + * Sets the query start date. + * + * @param queryStatDate the new query start date + */ + void setQueryStartDate(String queryStatDate); + + /** + * Sets the current query. + * + * @param query the new current query + */ + void setCurrentQuery(String query); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/ISQLHistoryItem.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/ISQLHistoryItem.java new file mode 100644 index 0000000000000000000000000000000000000000..98b2cefcc88dc5f38735143b5376cce733c4019d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/ISQLHistoryItem.java @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.sqlhistory; + +/** + * + * Title: interface + * + * Description: The Interface ISQLHistoryItem. + * + */ + +public interface ISQLHistoryItem { + + /** + * Gets the query. + * + * @return the query + */ + String getQuery(); + + /** + * Sets the query. + * + * @param query the new query + */ + void setQuery(String query); + + /** + * Gets the database name. + * + * @return the database name + */ + String getDatabaseName(); + + /** + * Sets the database name. + * + * @param databaseName the new database name + */ + void setDatabaseName(String databaseName); + + /** + * Gets the profile id. + * + * @return the profile id + */ + String getProfileId(); + + /** + * Sets the profile id. + * + * @param profileId the new profile id + */ + void setProfileId(String profileId); + + /** + * Gets the execution time. + * + * @return the execution time + */ + String getExecutionTime(); + + /** + * Checks if is pinned. + * + * @return true, if is pinned + */ + boolean isPinned(); + + /** + * Sets the pinned. + * + * @param isPinned the new pinned + */ + void setPinned(boolean isPinned); + + /** + * Gets the final status. + * + * @return the final status + */ + boolean getFinalStatus(); + + /** + * Sets the final status. + * + * @param finalStatus the new final status + */ + void setFinalStatus(boolean finalStatus); + + /** + * Gets the result set size. + * + * @return the result set size + */ + int getResultSetSize(); + + /** + * Sets the result set size. + * + * @param resultSetSize the new result set size + */ + void setResultSetSize(int resultSetSize); + + /** + * Gets the elapsed time. + * + * @return the elapsed time + */ + String getElapsedTime(); + + /** + * Sets the elapsed time. + * + * @param elapsedTime the new elapsed time + */ + void setElapsedTime(String elapsedTime); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/QueryExecutionSummary.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/QueryExecutionSummary.java new file mode 100644 index 0000000000000000000000000000000000000000..2334f60e38bc18e019d4e7bb4cb79f71308a8789 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/QueryExecutionSummary.java @@ -0,0 +1,258 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.sqlhistory; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.opengauss.mppdbide.bl.util.ExecTimer; +import org.opengauss.mppdbide.bl.util.IExecTimer; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class QueryExecutionSummary. + * + */ + +public class QueryExecutionSummary implements IQueryExecutionSummary { + + private String databaseName; + private String profileId; + private String query; + private String elapsedTime; + private boolean isQueryExecutionSuccess; + private String queryStartDate; + private int numRecordsFetched; + private IExecTimer timer; + private String profileName; + + /** + * Instantiates a new query execution summary. + * + * @param dbname the dbname + * @param profileId the profile id + * @param query the query + * @param executionResult the execution result + * @param querySubmitTime the query submit time + * @param elaspedTime the elasped time + * @param numRecordsFetched the num records fetched + */ + public QueryExecutionSummary(String dbname, String profileId, String query, boolean executionResult, + String querySubmitTime, long elaspedTime, int numRecordsFetched) { + this.databaseName = dbname; + this.profileId = profileId; + this.query = query; + this.elapsedTime = ExecTimer.getElapsedTimeWithUnits(elaspedTime); + this.isQueryExecutionSuccess = executionResult; + this.queryStartDate = querySubmitTime; + this.numRecordsFetched = numRecordsFetched; + } + + /** + * Instantiates a new query execution summary. + * + * @param dbname the dbname + * @param profileName the profile name + * @param profileID the profile ID + * @param query the query + */ + public QueryExecutionSummary(String dbname, String profileName, String profileID, String query) { + this.databaseName = dbname; + this.profileId = profileID; + this.profileName = profileName; + this.query = query; + this.isQueryExecutionSuccess = false; + this.numRecordsFetched = 0; + } + + /** + * startQueryTimer. + */ + public void startQueryTimer() { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(MPPDBIDEConstants.DATE_FORMAT); + this.queryStartDate = simpleDateFormat.format(new Date()); + this.timer = new ExecTimer("End to end Query execution "); + this.timer.start(); + } + + /** + * stopQueryTimer. + */ + public void stopQueryTimer() { + long timetaken = 0; + try { + this.timer.stop(); + timetaken = this.timer.getElapsedTimeInMs(); + } catch (DatabaseOperationException e) { + /* Nothing to do here */ + MPPDBIDELoggerUtility.none("Nothing to do here"); + } + + finally { + this.setElapsedTime(ExecTimer.getElapsedTimeWithUnits(timetaken)); + } + } + + /** + * Sets the query execution status. + * + * @param isQueryExecutnSuccess the new query execution status + */ + public void setQueryExecutionStatus(boolean isQueryExecutnSuccess) { + this.isQueryExecutionSuccess = isQueryExecutnSuccess; + } + + /** + * Gets the database name. + * + * @return getDatabaseName + */ + public String getDatabaseName() { + return databaseName; + } + + /** + * Gets the profile id. + * + * @return getProfileId + */ + public String getProfileId() { + return profileId; + } + + /** + * Gets the query. + * + * @return getQuery + */ + public String getQuery() { + return query; + } + + /** + * Checks if is query execution success. + * + * @return true, if is query execution success + */ + public boolean isQueryExecutionSuccess() { + return isQueryExecutionSuccess; + } + + /** + * Gets the execution time. + * + * @return getExecutionTime + */ + public Date getExecutionTime() { + + return null; + } + + /** + * Gets the query start date. + * + * @return getQueryStartDate + */ + public String getQueryStartDate() { + return queryStartDate; + } + + /** + * Gets the num records fetched. + * + * @return getNumRecordsFetched + */ + public int getNumRecordsFetched() { + return numRecordsFetched; + } + + /** + * Sets the num records fetched. + * + * @param numRecordsFetched the new num records fetched + */ + public void setNumRecordsFetched(int numRecordsFetched) { + this.numRecordsFetched = numRecordsFetched; + } + + /** + * Gets the elapsed time. + * + * @return the elapsed time + */ + public String getElapsedTime() { + return elapsedTime; + } + + /** + * Sets the elapsed time. + * + * @param elapsedTime the new elapsed time + */ + public void setElapsedTime(String elapsedTime) { + this.elapsedTime = elapsedTime; + } + + /** + * Gets the profile name. + * + * @return getProfileName + */ + @Override + public String getProfileName() { + return this.profileName; + } + + /** + * Checks if is analyze. + * + * @return isAnalyze + */ + @Override + public boolean isAnalyze() { + return false; + } + + /** + * Sets the analyze. + * + * @param analyze the new analyze + */ + @Override + public void setAnalyze(boolean analyze) { + + } + + /** + * Sets the query start date. + * + * @param queryStatDate the new query start date + */ + @Override + public void setQueryStartDate(String queryStatDate) { + this.queryStartDate = queryStatDate; + } + + @Override + public void setCurrentQuery(String query) { + this.query = query; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryCore.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryCore.java new file mode 100644 index 0000000000000000000000000000000000000000..358b439637f7a922462151789d44a6354052c7af --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryCore.java @@ -0,0 +1,452 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.sqlhistory; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.SQLTerminalQuerySplit; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class SQLHistoryCore. + * + */ + +public class SQLHistoryCore { + + // holds the history items that are valid. + private List unpinnedQueryHistory; + + // holds the history items that are pinned. + private List pinnedQueryHistory; + + private SQLHistoryCorePersistence historyPersistence; + + // this lock object is to protect the concurrent access to the lists. + private final Object lockObject = new Object(); + + // holds the max allowed size of the valid list + pinned history items + private int historySize; + + // if true,makes the history details to disk. + private boolean needSupportPersistence; + + private boolean loadingInProgress; + + private ScheduledExecutorService executor; + + private static final int GRACEFULLY_SHUTDOWN_HISTORY = 0; + + private static final long SQL_HISTORY_THREAD_SLEEP_DURATION_IN_MS = 10; + + private int querySizeToStore; + + /** + * Instantiates a new SQL history core. + * + * @param profileName the profile name + * @param path the path + * @param historyRetensionSize the history retension size + * @param queryMaxSize the query max size + * @param needPersistence the need persistence + */ + public SQLHistoryCore(String profileName, String path, int historyRetensionSize, int queryMaxSize, + boolean needPersistence) { + querySizeToStore = queryMaxSize; + historySize = historyRetensionSize; + needSupportPersistence = needPersistence; + + unpinnedQueryHistory = new LinkedList(); + pinnedQueryHistory = new LinkedList(); + + if (needSupportPersistence) { + historyPersistence = new SQLHistoryCorePersistence(path, historySize); + loadingInProgress = true; + + executor = Executors.newSingleThreadScheduledExecutor(); + + Runnable periodicTask = new Runnable() { + + /** + * Run. + */ + public void run() { + doPersistence(); + } + + private void doPersistence() { + if (loadingInProgress) { + performInitailLoad(); + return; + } + + persistHistory(); + } + + private void performInitailLoad() { + try { + List unpinnedQueryHistory1 = historyPersistence.loadValidQueries(); + List pinnedQueryHistory1 = historyPersistence.loadPinnedQueries(); + synchronized (lockObject) { + mergeLists(unpinnedQueryHistory1, unpinnedQueryHistory); + mergeLists(pinnedQueryHistory1, pinnedQueryHistory); + } + + historyPersistence.deleteOlderUnwantedFiles(); + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("Database operation failed.", exception); + } finally { + loadingInProgress = false; + } + } + + private void mergeLists(List srcList, List destList) { + int size = srcList.size(); + for (int i = 0; i < size; i++) { + addItemToList(destList, srcList.get(i)); + } + + } + }; + + executor.scheduleAtFixedRate(periodicTask, 0, 10, TimeUnit.SECONDS); + } + + } + + /** + * Adds the query summary. + * + * @param summary the summary + */ + public void addQuerySummary(QueryExecutionSummary summary) { + if (!validateQuery(summary)) { + SQLHistoryItemDetail newItem = new SQLHistoryItemDetail(summary, querySizeToStore); + addItemToList(unpinnedQueryHistory, newItem); + } + + } + + private boolean validateQuery(QueryExecutionSummary summary) { + String regex = ".*(?i)create\\s*user.*|.*alter\\s*user.*|.*alter\\s*role.*|.*create\\s*role.*" + + "|.*identified\\s*by.*|.*password.*|.*gs_encrypt.*|.*gs_decrypt.*"; + Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE); + String query = SQLTerminalQuerySplit.splitQueryForquotes(summary.getQuery().trim()).toString(); + /* + * Regex is very expensive so cutting down the greedy search expence + */ + if (query.toLowerCase(Locale.ENGLISH).contains("identified") + || query.toLowerCase(Locale.ENGLISH).contains("password") + || query.toLowerCase(Locale.ENGLISH).contains("user") + || query.toLowerCase(Locale.ENGLISH).contains("role") + || query.toLowerCase(Locale.ENGLISH).contains("gs_encrypt") + || query.toLowerCase(Locale.ENGLISH).contains("gs_decrypt")) { + if (pattern.matcher(query).find()) { + return true; + } + } + if (!query.isEmpty() && query.charAt(0) == '/') { + return isOnlyCommentedQuery(query); + } + if (query.charAt(0) == '-') { + return !containsQuery(query); + } else { + return false; + } + } + + private boolean containsQuery(String query) { + String[] actualQuery = null; + actualQuery = query.split(MPPDBIDEConstants.LINE_SEPARATOR); + for (int i = 0; i < actualQuery.length; i++) { + if (!actualQuery[i].isEmpty() && actualQuery[i].charAt(0) != '-') { + return true; + } + } + return false; + } + + private boolean isOnlyCommentedQuery(String query) { + if (query.startsWith("/*") && query.endsWith("*/")) { + return true; + } else { + return false; + } + } + + private void addItemToList(List addToList, SQLHistoryItemDetail newItem) { + synchronized (lockObject) { + int nonExistingIndex = 0; + int insertionPoint = Collections.binarySearch(addToList, newItem, newItem.getComparator()); + + if (insertionPoint < nonExistingIndex) { + insertionPoint = -(insertionPoint + 1); + } + + if (unpinnedQueryHistory.size() + pinnedQueryHistory.size() >= historySize) { + removeOldestHistoryItem(); + } + + if (insertionPoint > addToList.size()) { + insertionPoint = addToList.size(); + } + + if ((unpinnedQueryHistory.size() + pinnedQueryHistory.size() < historySize) || newItem.isPinned()) { + addToList.add(insertionPoint, newItem); + } + } + } + + private void removeOldestHistoryItem() { + if (unpinnedQueryHistory.size() > 0) { + int oldestItemPosition = unpinnedQueryHistory.size() - 1; + SQLHistoryItemDetail oldestItem = unpinnedQueryHistory.get(oldestItemPosition); + + if (needSupportPersistence) { + historyPersistence.addtoDeleteList(oldestItem); + } + + unpinnedQueryHistory.remove(oldestItemPosition); + } + } + + /** + * Sets the pin status. + * + * @param itemToPin the item to pin + * @param needToPin the need to pin + */ + public void setPinStatus(SQLHistoryItem itemToPin, boolean needToPin) { + + if (!(itemToPin instanceof SQLHistoryItemDetail)) { + return; + } + + SQLHistoryItemDetail detailItem = (SQLHistoryItemDetail) itemToPin; + itemToPin.setPinned(needToPin); + if (needToPin) { + synchronized (lockObject) { + boolean isremoved = unpinnedQueryHistory.remove(detailItem); + if (isremoved) { + addItemToList(pinnedQueryHistory, detailItem); + } + } + } else { + /* Unpin */ + synchronized (lockObject) { + pinnedQueryHistory.remove(detailItem); + addItemToList(unpinnedQueryHistory, detailItem); + } + + } + } + + /** + * Gets the all history content. + * + * @return the all history content + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public List getAllHistoryContent() throws MPPDBIDEException { + if (loadingInProgress) { + try { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_BL_SQL_HISTORY_NOT_LOADED)); + throw new MPPDBIDEException(IMessagesConstants.ERR_BL_SQL_HISTORY_NOT_LOADED); + } catch (MPPDBIDEException exe) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_BL_SQL_HISTORY_NOT_LOADED), exe); + throw new MPPDBIDEException(IMessagesConstants.ERR_BL_SQL_HISTORY_NOT_LOADED, exe); + } + } + + List returnList = new LinkedList(); + + synchronized (lockObject) { + returnList.addAll(0, unpinnedQueryHistory); + returnList.addAll(0, pinnedQueryHistory); + } + return returnList; + } + + /** + * Gets the history content. + * + * @param itemCount the item count + * @return the history content + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public List getHistoryContent(int itemCount) throws MPPDBIDEException { + List allHistoryContent = getAllHistoryContent(); + if (allHistoryContent.size() > itemCount) { + return allHistoryContent.subList(0, itemCount); + } else { + return allHistoryContent; + } + } + + /** + * Persist history. + */ + public void persistHistory() { + if (needSupportPersistence) { + List pinnedqueryHistoryToPersist = new LinkedList(); + List unpinnedqueryHistoryToPersist = new LinkedList(); + + synchronized (lockObject) { + pinnedqueryHistoryToPersist.addAll(pinnedQueryHistory); + unpinnedqueryHistoryToPersist.addAll(unpinnedQueryHistory); + } + + historyPersistence.persistHistory(unpinnedqueryHistoryToPersist, pinnedqueryHistoryToPersist); + } + } + + /** + * Cancel persist. + */ + public void cancelPersist() { + if (needSupportPersistence) { + historyPersistence.cancelPersistenceOperation(); + } + } + + /** + * Delete history items. + * + * @param arr the arr + */ + public void deleteHistoryItems(List arr) { + int size = arr.size(); + for (int i = 0; i < size; i++) { + int pos = unpinnedQueryHistory.indexOf(arr.get(i)); + SQLHistoryItemDetail itemToDel = null; + + if (-1 != pos) { + synchronized (lockObject) { + itemToDel = unpinnedQueryHistory.get(pos); + unpinnedQueryHistory.remove(itemToDel); + } + + if (needSupportPersistence) { + historyPersistence.addtoDeleteList(itemToDel); + } + } + + } + + } + + /** + * Destroy. + * + * @param flag the flag + */ + public void destroy(int flag) { + if (needSupportPersistence) { + if (flag == GRACEFULLY_SHUTDOWN_HISTORY) { + + /* + * executor is running,then allow to complete. else trigger + * once. + */ + executor.shutdown(); + } else { + historyPersistence.cancelPersistenceOperation(); + /* if running terminal */ + executor.shutdown(); + + } + while (!executor.isShutdown()) { + boolean exited = false; + try { + exited = executor.awaitTermination(SQL_HISTORY_THREAD_SLEEP_DURATION_IN_MS, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + MPPDBIDELoggerUtility.warn("Warning: InterruptedException occurs but execution can be continue"); + continue; // cant do anything; + } + if (exited) { + break; + } + } + + historyPersistence = null; + } + synchronized (lockObject) { + + pinnedQueryHistory.clear(); + unpinnedQueryHistory.clear(); + } + + } + + /** + * Sets the SQL query size. + * + * @param querySize the new SQL query size + */ + public void setSQLQuerySize(int querySize) { + synchronized (lockObject) { + + this.querySizeToStore = querySize; + } + } + + /** + * Sets the history size. + * + * @param historySize the new history size + */ + public void setHistorySize(int historySize) { + int currentHistorySize = 0; + synchronized (lockObject) { + this.historySize = historySize; + currentHistorySize = pinnedQueryHistory.size() + unpinnedQueryHistory.size(); + } + List listToDelete = new ArrayList<>(); + + if (currentHistorySize > historySize) { + int numToDelete = currentHistorySize - historySize; + if (unpinnedQueryHistory.size() < numToDelete) { + numToDelete = unpinnedQueryHistory.size(); + } + + for (int index = 1; index <= numToDelete; index++) { + listToDelete.add(unpinnedQueryHistory.get(unpinnedQueryHistory.size() - index)); + } + + } + + deleteHistoryItems(listToDelete); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryCorePersistence.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryCorePersistence.java new file mode 100644 index 0000000000000000000000000000000000000000..7ebf4c6d78703939340aa4e421dca742f636ddc8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryCorePersistence.java @@ -0,0 +1,538 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.sqlhistory; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InvalidClassException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.ObjectStreamClass; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.apache.poi.util.BoundedInputStream; + +import com.google.gson.JsonSyntaxException; +import org.opengauss.mppdbide.utils.EnvirnmentVariableValidator; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.files.FilePermissionFactory; +import org.opengauss.mppdbide.utils.files.ISetFilePermission; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class SQLHistoryCorePersistence. + * + */ + +public class SQLHistoryCorePersistence { + + // holds the file names for each valid history item. + private ArrayList validHistoryFiles; + + // holds the file names for each pinned history item. + private ArrayList pinnedHistoryFiles; + + // holds the file names for each history item to be deleted. + private ArrayList tobeDeletedHistoryFiles; + + private final Object deleteListLock = new Object(); + + // if true, indicates that the purge task in the progress. + private boolean isPurgeInProgress = false; + + // if true, will make the purge task stop the operation at the earliest. + private boolean needCancelPurge = false; + + // file name into which validHistoryFiles object is serialized into. + private static final String VALID_HISTORY_DETAILS_METADATA_FILENAME = "v_he.meta"; + + // file name into which pinnedHistoryFiles object is serialized into. + private static final String PINNED_HISTORY_DETAILS_METADATA_FILENAME = "p_he.meta"; + + // file name into which tobeDeletedHistoryFiles object is serialized into. + private static final String TOBE_DELETED_HISTORY_DETAILS_METADATA_FILENAME = "tbd_he.meta"; + + // meta file size max + private static final double META_FILE_MAX_SIZE_IN_KB = 30; + + // history file size max + private static final double HISTORY_FILE_MAX_SIZE_IN_MB = 1; + + // indicates the path into which the history files can be created. + private String path; + + /** + * Instantiates a new SQL history core persistence. + * + * @param persistencepath the persistencepath + * @param historySize the history size + */ + public SQLHistoryCorePersistence(String persistencepath, int historySize) { + validHistoryFiles = new ArrayList(10); + tobeDeletedHistoryFiles = new ArrayList(10); + pinnedHistoryFiles = new ArrayList(10); + + createHistroryFolder(persistencepath); + path = persistencepath; + } + + private void createHistroryFolder(String persistencepath) { + String standardizedPath = null; + try { + standardizedPath = new File(persistencepath).getCanonicalPath(); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("Invalid File Path", exception); + } + if (standardizedPath != null) { + Path filePath = Paths.get(standardizedPath); + if (!Files.exists(filePath, LinkOption.NOFOLLOW_LINKS)) { + ISetFilePermission file = FilePermissionFactory.getFilePermissionInstance(); + try { + file.createFileWithPermission(standardizedPath, true, null, true); + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("folder creation error", exception); + } + } + } + } + + /** + * Addto delete list. + * + * @param historyItem the history item + */ + public void addtoDeleteList(SQLHistoryItemDetail historyItem) { + synchronized (deleteListLock) { + tobeDeletedHistoryFiles.add(historyItem.getFileName()); + } + } + + /** + * Load valid queries. + * + * @return the list + * @throws DatabaseOperationException the database operation exception + */ + public List loadValidQueries() throws DatabaseOperationException { + return loadHistroyItemsFromFileList(validHistoryFiles, path + + EnvirnmentVariableValidator.validateAndGetFileSeperator() + VALID_HISTORY_DETAILS_METADATA_FILENAME); + } + + /** + * Load pinned queries. + * + * @return the list + * @throws DatabaseOperationException the database operation exception + */ + public List loadPinnedQueries() throws DatabaseOperationException { + return loadHistroyItemsFromFileList(pinnedHistoryFiles, path + + EnvirnmentVariableValidator.validateAndGetFileSeperator() + PINNED_HISTORY_DETAILS_METADATA_FILENAME); + } + + private List loadHistroyItemsFromFileList(ArrayList fileListParam, String fileName) + throws DatabaseOperationException { + ArrayList fileList = fileListParam; + List list = new ArrayList(fileList.size()); + String standardizedPath = null; + try { + standardizedPath = new File(fileName).getCanonicalPath(); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("Invalid File Path", exception); + } + if (standardizedPath != null) { + Path filePath = Paths.get(standardizedPath); + if (!Files.exists(filePath, LinkOption.NOFOLLOW_LINKS)) { + ISetFilePermission file = FilePermissionFactory.getFilePermissionInstance(); + file.createFileWithPermission(standardizedPath, false, null, true); + return list; + } else { + double fileSizeInKB = FileUtils.sizeOf(filePath.toFile()) / (double) (1024) ; + if (fileSizeInKB > META_FILE_MAX_SIZE_IN_KB) { + MPPDBIDELoggerUtility.error("Error while reading the SQL History file. File size exceeded 30KB"); + return list; + } + } + + fileList = desearlizeHistoryFileMetaData(fileName); + + if (null != fileList) { + list = loadHistoryitems(fileList); + } + } + return list; + } + + private List loadHistoryitems(ArrayList fileList) { + List historyItems = new ArrayList(fileList.size()); + SQLHistoryItemDetail historyItem = null; + int fileSize = fileList.size(); + for (int index = 0; index < fileSize; index++) { + historyItem = readDetailFromFile( + path + EnvirnmentVariableValidator.validateAndGetFileSeperator() + fileList.get(index)); + if (historyItem != null) { + historyItems.add(historyItem); + } else { + deleteInvalidHistFile(fileList, index); + } + } + return historyItems; + } + + private void deleteInvalidHistFile(ArrayList fileList, int indx) { + String stdizedPath = null; + String pathToDelete = path + EnvirnmentVariableValidator.validateAndGetFileSeperator() + fileList.get(indx); + try { + stdizedPath = new File(pathToDelete).getCanonicalPath(); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("Invalid File Path", exception); + } + try { + Files.deleteIfExists(Paths.get(stdizedPath)); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("Invalid History deleted from file", exception); + } + } + + /** + * + * Title: class + * + * Description: The Class SecuredObjectInputStream. + * + */ + private static class SecuredObjectInputStream extends ObjectInputStream { + + /** + * Instantiates a new secured object input stream. + * + * @param inputStream the input stream + * @throws IOException Signals that an I/O exception has occurred. + */ + public SecuredObjectInputStream(InputStream inputStream) throws IOException { + super(inputStream); + } + + /** + * Resolve class. + * + * @param desc the desc + * @return the class + * @throws IOException Signals that an I/O exception has occurred. + * @throws ClassNotFoundException the class not found exception + */ + @Override + protected Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { + if (desc.getName().equals(SQLHistoryFileMetadata.class.getName()) + || desc.getName().equals(ArrayList.class.getName())) { + return super.resolveClass(desc); + } + throw new InvalidClassException("Unauthorized deserialization attempt", desc.getName()); + } + } + + private void searlizeHistoryFileMetaData(ArrayList topersist, String filename) { + SQLHistoryFileMetadata lSQLHistoryFileMetadata = new SQLHistoryFileMetadata(); + lSQLHistoryFileMetadata.setHisFileMetadata(topersist); + FileOutputStream fos = null; + ObjectOutputStream oos = null; + try { + fos = new FileOutputStream(filename); + oos = new ObjectOutputStream(fos); + oos.writeObject(lSQLHistoryFileMetadata); + } catch (IOException ioe) { + MPPDBIDELoggerUtility.error("io exception caught", ioe); + } finally { + if (oos != null) { + try { + oos.close(); + oos = null; + } catch (IOException exception) { + oos = null; + MPPDBIDELoggerUtility.error("IO operation failed.", exception); + } + } + if (fos != null) { + try { + fos.close(); + fos = null; + } catch (IOException exception) { + fos = null; + MPPDBIDELoggerUtility.error("IO operation failed.", exception); + } + } + + } + } + + private ArrayList desearlizeHistoryFileMetaData(String filename) { + FileInputStream fis = null; + ObjectInputStream ois = null; + BoundedInputStream bis = null; + + try { + fis = new FileInputStream(filename); + bis = new BoundedInputStream(fis, 2097152); + ois = new SecuredObjectInputStream(bis); + Object object = ois.readObject(); + SQLHistoryFileMetadata hisFileMetaData = null; + if (object instanceof SQLHistoryFileMetadata) { + hisFileMetaData = (SQLHistoryFileMetadata) object; + } else { + return new ArrayList(); + } + return hisFileMetaData.getHisFileMetadata(); + } catch (IOException ioe) { + return null; + } catch (ClassNotFoundException exception) { + return null; + } + + finally { + if (ois != null) { + try { + ois.close(); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("IO operation failed.", exception); + ois = null; + } + } + if (fis != null) { + try { + fis.close(); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("IO operation failed.", exception); + fis = null; + } + } + if (bis != null) { + try { + bis.close(); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("IO operation failed.", exception); + bis = null; + } + } + } + } + + /** + * Read detail from file. + * + * @param fileName the file name + * @return the SQL history item detail + */ + public static SQLHistoryItemDetail readDetailFromFile(String fileName) { + FileInputStream fis = null; + BoundedInputStream bis = null; + SQLHistoryItemDetail historyItem = null; + try { + File file = new File(fileName); + if (file.exists()) { + double fileSizeInMB = FileUtils.sizeOf(file) / (double) (1024 * 1024); + if (fileSizeInMB > HISTORY_FILE_MAX_SIZE_IN_MB) { + MPPDBIDELoggerUtility.error("SQL Histrory file size exceeds file limit 1MB ."); + return null; + } + fis = new FileInputStream(fileName); + bis = new BoundedInputStream(fis, 20971520); + byte[] bytes = IOUtils.toByteArray(bis); + if (bytes.length == 0) { + return null; + } + + String fileContent = new String(bytes, StandardCharsets.UTF_8); + historyItem = SQLHistoryItemDetail.getDeserializedContent(fileContent); + } + return historyItem; + } catch (IOException exception) { + return null; + } catch (JsonSyntaxException exception) { + return null; + } finally { + try { + if (fis != null) { + fis.close(); + } + if (bis != null) { + bis.close(); + } + } catch (IOException ex) { + MPPDBIDELoggerUtility.error("IO exception occured while closing files"); + } + } + } + + /** + * Persist history. + * + * @param queryHistory the query history + * @param pinnedQueryHistory the pinned query history + */ + public void persistHistory(List queryHistory, List pinnedQueryHistory) { + + isPurgeInProgress = true; + + persistHistoryList(pinnedQueryHistory, path + EnvirnmentVariableValidator.validateAndGetFileSeperator(), + PINNED_HISTORY_DETAILS_METADATA_FILENAME); + + persistHistoryList(queryHistory, path + EnvirnmentVariableValidator.validateAndGetFileSeperator(), + VALID_HISTORY_DETAILS_METADATA_FILENAME); + + deleteOlderUnwantedFiles(); + + isPurgeInProgress = false; + + } + + /** + * Delete older unwanted files. + */ + public void deleteOlderUnwantedFiles() { + ArrayList deleteFileNameList = new ArrayList(0); + + synchronized (deleteListLock) { + if (tobeDeletedHistoryFiles.size() > 0) { + deleteFileNameList.addAll(tobeDeletedHistoryFiles); + tobeDeletedHistoryFiles.clear(); + } else { + return; + } + } + + purgeDeletedHistoryItems(deleteFileNameList); + synchronized (deleteListLock) { + tobeDeletedHistoryFiles.addAll(deleteFileNameList); + } + + } + + private void purgeDeletedHistoryItems(ArrayList todeleteListToPersist) { + int size = todeleteListToPersist.size(); + searlizeHistoryFileMetaData(todeleteListToPersist, + path + EnvirnmentVariableValidator.validateAndGetFileSeperator() + + TOBE_DELETED_HISTORY_DETAILS_METADATA_FILENAME); + + ArrayList itemsToremove = new ArrayList(size); + for (int cnt = 0; cnt < size; cnt++) { + if (needCancelPurge) { + return; + } + try { + Files.deleteIfExists(Paths.get(path + EnvirnmentVariableValidator.validateAndGetFileSeperator() + + todeleteListToPersist.get(cnt))); + itemsToremove.add(cnt, 1); + } catch (IOException exception) { + itemsToremove.add(cnt, 0); + } + } + + for (int index = itemsToremove.size() - 1; index >= 0; index--) { + if (needCancelPurge) { + return; + } + if (1 == itemsToremove.get(index)) { + todeleteListToPersist.remove(index); + } + + } + + searlizeHistoryFileMetaData(todeleteListToPersist, + path + EnvirnmentVariableValidator.validateAndGetFileSeperator() + + TOBE_DELETED_HISTORY_DETAILS_METADATA_FILENAME); + } + + private void persistHistoryList(List queryHistoryToPersist, String filePath, + String filename) { + ArrayList historyItemFileNames = new ArrayList(queryHistoryToPersist.size()); + int persistSize = queryHistoryToPersist.size(); + + for (int index = 0; index < persistSize; index++) { + if (needCancelPurge) { + return; + } + historyItemFileNames.add(index, queryHistoryToPersist.get(index).getFileName()); + + } + + searlizeHistoryFileMetaData(historyItemFileNames, filePath + filename); + persistEachHistorytItem(queryHistoryToPersist, filePath); + } + + private void persistEachHistorytItem(List queryHistoryToPersist, String workingpath) { + ISetFilePermission withPermission = FilePermissionFactory.getFilePermissionInstance(); + int queryPersistSize = queryHistoryToPersist.size(); + + for (int indx = 0; indx < queryPersistSize; indx++) { + if (needCancelPurge) { + return; + } + persistToFile(withPermission, workingpath + queryHistoryToPersist.get(indx).getFileName(), + queryHistoryToPersist.get(indx).getSerializedContent()); + } + + } + + private boolean persistToFile(ISetFilePermission withPermission, String fileName, String serializedContent) { + + Path pathToSave = Paths.get(fileName); + try { + if (!Files.exists(Paths.get(fileName), LinkOption.NOFOLLOW_LINKS)) { + pathToSave = withPermission.createFileWithPermission(fileName, false, null, true); + } + + Files.write(pathToSave, serializedContent.getBytes(StandardCharsets.UTF_8), + StandardOpenOption.TRUNCATE_EXISTING); + return true; + + } catch (IOException exception) { + return false; + } catch (DatabaseOperationException exception) { + return false; + } + } + + /** + * Cancel persistence operation. + */ + public void cancelPersistenceOperation() { + needCancelPurge = true; + } + + /** + * Checks if is purge in progress. + * + * @return true, if is purge in progress + */ + public boolean isPurgeInProgress() { + return isPurgeInProgress; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryEventListener.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryEventListener.java new file mode 100644 index 0000000000000000000000000000000000000000..75a251a7385e87caf598e4c11f7cb1993e73b752 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryEventListener.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.sqlhistory; + +import org.eclipse.e4.core.services.events.IEventBroker; +import org.osgi.service.event.Event; +import org.osgi.service.event.EventHandler; + +import org.opengauss.mppdbide.bl.sqlhistory.manager.ISqlHistoryManager; + +/** + * Title: SQLHistoryEventListener + * + * Description:The listener interface for receiving SQLHistoryEvent events. The + * class that is interested in processing a SQLHistoryEvent event implements + * this interface, and the object created with that class is registered with a + * component using the component's addSQLHistoryEventListener + * method. When the SQLHistoryEvent event occurs, that object's appropriate + * method is invoked. + * + */ + +public class SQLHistoryEventListener implements EventHandler { + + /** + * The Constant QUERY_EXEC_RESULT. + */ + public static final String QUERY_EXEC_RESULT = "query_execution_result"; + + /** + * Inits the. + * + * @param eventBroker the event broker + */ + public void init(IEventBroker eventBroker) { + eventBroker.subscribe(QUERY_EXEC_RESULT, this); + } + + /** + * Handle event. + * + * @param eventQueryExecutionResult the eventQueryExecutionResult + */ + @Override + public void handleEvent(Event eventQueryExecutionResult) { + if (QUERY_EXEC_RESULT.equals(eventQueryExecutionResult.getTopic())) { + QueryExecutionSummary summary = (QueryExecutionSummary) eventQueryExecutionResult + .getProperty(IEventBroker.DATA); + if (summary != null) { + ISqlHistoryManager histmgr = SQLHistoryManager.getInstance(); + histmgr.addNewQueryExecutionInfo(summary.getProfileId(), summary); + + } + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryFactory.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..b4f90a4eb916f27991181c5f6224e3d3da98c2c4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryFactory.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.sqlhistory; + +import org.opengauss.mppdbide.bl.sqlhistory.manager.ISqlHistoryManager; + +/** + * Title: SQLHistoryFactory + * + */ + +public abstract class SQLHistoryFactory { + + /** + * Gets the single instance of SQLHistoryFactory. + * + * @return single instance of SQLHistoryFactory + */ + public static ISqlHistoryManager getInstance() { + return SQLHistoryManager.getInstance(); + } + + /** + * Gets the new query execution summary. + * + * @param dbname the dbname + * @param profileName the profile name + * @param profileID the profile ID + * @param query the query + * @return the new query execution summary + */ + public static IQueryExecutionSummary getNewQueryExecutionSummary(String dbname, String profileName, + String profileID, String query) { + return new QueryExecutionSummary(dbname, profileName, profileID, query); + } + + /** + * Gets the new exlain query execution summary. + * + * @param dbname the dbname + * @param profileId the profile id + * @param query the query + * @param querySubmitTime the query submit time + * @return the new exlain query execution summary + */ + public static IQueryExecutionSummary getNewExlainQueryExecutionSummary(String dbname, String profileId, + String query, String querySubmitTime) { + return new ExlainQueryExecutionSummary(dbname, profileId, query, querySubmitTime); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryFileMetadata.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryFileMetadata.java new file mode 100644 index 0000000000000000000000000000000000000000..58c5f6e461283def4cdfb158e1b2f3625aa15119 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryFileMetadata.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.sqlhistory; + +import java.io.Serializable; +import java.util.ArrayList; + +/** + * + * Title: SQLHistoryFileMetadata + * + * @since 3.0.0 + */ +public class SQLHistoryFileMetadata implements Serializable { + private static final long serialVersionUID = 3505657588142448599L; + private ArrayList hisFileMetadata = null; + + public ArrayList getHisFileMetadata() { + return hisFileMetadata; + } + + public void setHisFileMetadata(ArrayList hisFileMetadata) { + this.hisFileMetadata = hisFileMetadata; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryItem.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryItem.java new file mode 100644 index 0000000000000000000000000000000000000000..894be2596d358881a94538e39a3a1e311e8d24e0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryItem.java @@ -0,0 +1,281 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.sqlhistory; + +import java.io.Serializable; +import java.text.SimpleDateFormat; +import java.util.Comparator; +import java.util.Date; +import java.util.TimeZone; + +/** + * + * Title: class + * + * Description: The Class SQLHistoryItem. + * + */ + +public class SQLHistoryItem implements ISQLHistoryItem { + + private String query; + private String databaseName; + private String profileId; + private String executionTime; + private String elapsedTime; + private boolean isPinned; + private boolean finalStatus; + private int resultSetSize; + private int querySizeToStore; + + + /** + * Instantiates a new SQL history item. + * + * @param summary the summary + * @param querySize the query size + */ + public SQLHistoryItem(QueryExecutionSummary summary, int querySize) { + this.querySizeToStore = querySize; + String qry = summary.getQuery(); + + setQuery(qry); + this.databaseName = summary.getDatabaseName(); + this.isPinned = false; + this.executionTime = summary.getQueryStartDate(); + this.elapsedTime = summary.getElapsedTime(); + this.finalStatus = summary.isQueryExecutionSuccess(); + this.profileId = summary.getProfileId(); + this.resultSetSize = summary.getNumRecordsFetched(); + } + + /** + * Gets the query. + * + * @return getQuery + */ + public String getQuery() { + return query; + } + + /** + * Sets the query. + * + * @param query the new query + */ + public final void setQuery(String query) { + String qry = query + ';'; + // If 0, then consider storing the complete query + if (querySizeToStore == 0) { + this.query = qry; + } else { + int length = qry.length() <= querySizeToStore ? qry.length() : querySizeToStore; + this.query = qry.substring(0, length); + } + } + + /** + * Gets the database name. + * + * @return getDatabaseName + */ + public String getDatabaseName() { + return databaseName; + } + + /** + * Sets the database name. + * + * @param databaseName the new database name + */ + public void setDatabaseName(String databaseName) { + this.databaseName = databaseName; + } + + /** + * Gets the profile id. + * + * @return getProfileId + */ + public String getProfileId() { + return profileId; + } + + /** + * Sets the profile id. + * + * @param profileId the new profile id + */ + public void setProfileId(String profileId) { + this.profileId = profileId; + } + + /** + * Gets the execution time. + * + * @return getExecutionTime + */ + public String getExecutionTime() { + if (executionTime == null) { + return null; + } + return executionTime; + } + + + /** + * Checks if is pinned. + * + * @return isPinned + */ + public boolean isPinned() { + return isPinned; + } + + /** + * Sets the pinned. + * + * @param isPined the new pinned + */ + public void setPinned(boolean isPined) { + this.isPinned = isPined; + } + + /** + * Gets the final status. + * + * @return getFinalStatus + */ + public boolean getFinalStatus() { + return finalStatus; + } + + /** + * Sets the final status. + * + * @param finalStatus the new final status + */ + public void setFinalStatus(boolean finalStatus) { + this.finalStatus = finalStatus; + } + + /** + * Gets the result set size. + * + * @return getResultSetSize + */ + public int getResultSetSize() { + return resultSetSize; + } + + /** + * Sets the result set size. + * + * @param resultSetSize the new result set size + */ + public void setResultSetSize(int resultSetSize) { + this.resultSetSize = resultSetSize; + } + + /** + * Gets the elapsed time. + * + * @return getElapsedTime + */ + public String getElapsedTime() { + return elapsedTime; + } + + /** + * Sets the elapsed time. + * + * @param elapsedTime the new elapsed time + */ + public void setElapsedTime(String elapsedTime) { + this.elapsedTime = elapsedTime; + } + + /** + * Equals. + * + * @param obj the obj + * @return true, if successful + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (null == obj) { + return false; + } + + if (!(obj instanceof SQLHistoryItem)) { + return false; + } + + SQLHistoryItem compareObj = (SQLHistoryItem) obj; + + if (this.databaseName.equals(compareObj.databaseName) && this.profileId.equals(compareObj.profileId) + && this.query.equals(compareObj.query) && this.executionTime.equals(compareObj.executionTime)) { + return true; + } + + return false; + } + + /** + * Hash code. + * + * @return the int + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + getDatabaseName().hashCode() + getProfileId().hashCode() + getQuery().hashCode() + + (null == getExecutionTime() ? 0 : getExecutionTime().hashCode()); + + return result; + } + + /** + * Gets the comparator. + * + * @return the comparator + */ + public SQLHistoryItemComapartor getComparator() { + return new SQLHistoryItemComapartor(); + } + + /** + * + * Title: class + * + * Description: The Class SQLHistoryItemComapartor. + * + */ + private static class SQLHistoryItemComapartor implements Comparator, Serializable { + + private static final long serialVersionUID = 1L; + + @Override + public int compare(SQLHistoryItem object1, SQLHistoryItem object2) { + // since the latest should be given first + return object2.executionTime.compareTo(object1.executionTime); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryItemDetail.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryItemDetail.java new file mode 100644 index 0000000000000000000000000000000000000000..f2fa6acec6b73e0e0f9b67af78b2c2a1afe70c5b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryItemDetail.java @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.sqlhistory; + +import java.lang.reflect.Type; +import java.text.SimpleDateFormat; +import java.util.Date; + +import com.google.gson.Gson; +import com.google.gson.JsonSyntaxException; +import com.google.gson.reflect.TypeToken; + +/** + * + * Title: class + * + * Description: The Class SQLHistoryItemDetail. + * + */ + +public class SQLHistoryItemDetail extends SQLHistoryItem { + + private String fileName; + + /** + * Instantiates a new SQL history item detail. + * + * @param summary the summary + * @param querySize the query size + */ + public SQLHistoryItemDetail(QueryExecutionSummary summary, int querySize) { + super(summary, querySize); + setDestinationFileName(); + } + + private void setDestinationFileName() { + Date date = new Date(); + SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyyHHmmssSSS"); + this.fileName = dateFormat.format(date) + ".hist"; + } + + /** + * Gets the file name. + * + * @return the file name + */ + public final String getFileName() { + return fileName; + } + + /** + * Gets the serialized content. + * + * @return the serialized content + */ + public String getSerializedContent() { + Gson gson = new Gson(); + Type type = new SQLHistoryItemTypeToken().getType(); + return gson.toJson(this, type); + } + + /** + * Gets the deserialized content. + * + * @param string the string + * @return the deserialized content + * @throws JsonSyntaxException the json syntax exception + */ + public static SQLHistoryItemDetail getDeserializedContent(String string) throws JsonSyntaxException { + if (null == string || string.isEmpty()) { + return null; + } + Gson gson = new Gson(); + Type type = new TypeToken() { + }.getType(); + SQLHistoryItemDetail historyItem = gson.fromJson(string, type); + return historyItem; + } + + /** + * + * Title: class + * + * Description: The Class SQLHistoryItemTypeToken. + * + */ + private static final class SQLHistoryItemTypeToken extends TypeToken { + } + + @Override + public int hashCode() { + return super.hashCode() + fileName.hashCode(); + } + + @Override + public boolean equals(Object obj) { + + if (null == obj) { + return false; + } + + if (!(obj instanceof SQLHistoryItemDetail)) { + return false; + } + + if (!super.equals(obj)) { + return false; + } + if (this == obj) { + return true; + } + + SQLHistoryItemDetail other = (SQLHistoryItemDetail) obj; + if (fileName == null) { + if (other.fileName != null) { + return false; + } + } else if (!fileName.equals(other.fileName)) { + return false; + } + + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryManager.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryManager.java new file mode 100644 index 0000000000000000000000000000000000000000..2cf6949551c0903a26d3c6780e8a9f89a5e577b9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/SQLHistoryManager.java @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.sqlhistory; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; + +import org.eclipse.e4.core.services.events.IEventBroker; + +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.sqlhistory.manager.ISqlHistoryManager; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; + +/** + * + * Title: class + * + * Description: The Class SQLHistoryManager. + * + */ + +public final class SQLHistoryManager implements ISqlHistoryManager { + + private static volatile SQLHistoryManager hismgr; + private HashMap profileHistroy; + private int historyRetensionSize; + + private static final int GRACEFULLY_SHUTDOWN_HISTORY = 0; + private static final int ABORT_SHUTDOWN_HISTORY = 1; + private static final Object LOCK = new Object(); + private int queryMaxSize; + + private SQLHistoryManager() { + profileHistroy = new HashMap(10); + historyRetensionSize = BLPreferenceManager.getInstance().getBLPreference().getSQLHistorySize(); + queryMaxSize = BLPreferenceManager.getInstance().getBLPreference().getSQLQueryLength(); + } + + /** + * Gets the single instance of SQLHistoryManager. + * + * @return single instance of SQLHistoryManager + */ + public static ISqlHistoryManager getInstance() { + if (hismgr == null) { + + synchronized (LOCK) { + if (hismgr == null) { + hismgr = new SQLHistoryManager(); + } + + } + } + + return hismgr; + } + + /** + * Inits the. + * + * @param eventBroker the event broker + */ + public void init(IEventBroker eventBroker) { + SQLHistoryEventListener hisListener = new SQLHistoryEventListener(); + hisListener.init(eventBroker); + } + + @Override + public List getHistoryContent(String profileId, int itemCount) throws MPPDBIDEException { + + SQLHistoryCore profHistoryCore = profileHistroy.get(profileId); + if (null != profHistoryCore) { + return profHistoryCore.getAllHistoryContent(); + } else { + return new LinkedList(); + } + + } + + @Override + public void deleteHistoryItems(List arr) { + SQLHistoryCore profHistoryCore = profileHistroy.get(arr.get(0).getProfileId()); + profHistoryCore.deleteHistoryItems(arr); + } + + @Override + public boolean setPinStatus(SQLHistoryItem item, boolean needToPin) { + if (null != item) { + SQLHistoryCore profHistoryCore = profileHistroy.get(item.getProfileId()); + profHistoryCore.setPinStatus(item, needToPin); + return true; + } + return false; + } + + @Override + public void setHistoryRetensionSize(int size) { + historyRetensionSize = size; + for (SQLHistoryCore core : profileHistroy.values()) { + core.setHistorySize(size); + } + + } + + @Override + public void addNewQueryExecutionInfo(String profileId, QueryExecutionSummary summary) { + SQLHistoryCore profHistoryCore = profileHistroy.get(profileId); + if (null != profHistoryCore) { + profHistoryCore.addQuerySummary(summary); + } + } + + @Override + public void doHistoryManagementForProfile(String profileId, String path) { + SQLHistoryCore sqlHistoryCore = profileHistroy.get(profileId); + if (sqlHistoryCore == null) { + SQLHistoryCore core = new SQLHistoryCore(profileId, path, historyRetensionSize, queryMaxSize, true); + profileHistroy.put(profileId, core); + } + + } + + @Override + public void stopHistoryManagementForProfile(String profileId) { + SQLHistoryCore core = profileHistroy.remove(profileId); + if (core == null) { + return; + } + + core.destroy(GRACEFULLY_SHUTDOWN_HISTORY); + } + + /** + * Remove the history for the profile from disk and memory. + * + * @param profileId the profile id + */ + @Override + public void removeHistoryManagementForProfile(String profileId) { + SQLHistoryCore core = profileHistroy.remove(profileId); + if (core == null) { + return; + } + core.destroy(ABORT_SHUTDOWN_HISTORY); + } + + @Override + public void purgeHistory(String profileId) { + SQLHistoryCore profHistoryCore = profileHistroy.get(profileId); + if (profHistoryCore == null) { + return; + } + profHistoryCore.persistHistory(); + } + + /** + * Purge historybefore close. + */ + public void purgeHistorybeforeClose() { + for (SQLHistoryCore profHistoryCore : profileHistroy.values()) { + if (profHistoryCore != null) { + profHistoryCore.persistHistory(); + } + } + + } + + @Override + public void setSQLQuerySize(Integer queryLength) { + this.queryMaxSize = queryLength; + for (SQLHistoryCore core : profileHistroy.values()) { + core.setSQLQuerySize(queryLength); + } + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/manager/ISqlHistoryManager.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/manager/ISqlHistoryManager.java new file mode 100644 index 0000000000000000000000000000000000000000..846d5f1ee210d10b52e7b3fb46924ad217d8cebb --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/sqlhistory/manager/ISqlHistoryManager.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.sqlhistory.manager; + +import java.util.List; + +import org.eclipse.e4.core.services.events.IEventBroker; + +import org.opengauss.mppdbide.bl.sqlhistory.QueryExecutionSummary; +import org.opengauss.mppdbide.bl.sqlhistory.SQLHistoryItem; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; + +/** + * + * Title: interface + * + * Description: The Interface ISqlHistoryManager. + * + */ + +public interface ISqlHistoryManager { + + /** + * Gets the history content. + * + * @param profileId the profile id + * @param itemCount the item count + * @return the history content + * @throws MPPDBIDEException the MPPDBIDE exception + */ + List getHistoryContent(String profileId, int itemCount) throws MPPDBIDEException; + + /** + * Delete history items. + * + * @param arr the arr + */ + void deleteHistoryItems(List arr); + + /** + * Sets the pin status. + * + * @param item the item + * @param needToPin the need to pin + * @return true, if successful + */ + boolean setPinStatus(SQLHistoryItem item, boolean needToPin); + + /** + * Sets the history retension size. + * + * @param size the new history retension size + */ + void setHistoryRetensionSize(int size); + + /** + * Adds the new query execution info. + * + * @param profileId the profile id + * @param executionItem the execution item + */ + void addNewQueryExecutionInfo(String profileId, QueryExecutionSummary executionItem); + + /** + * Do history management for profile. + * + * @param profileId the profile id + * @param path the path + */ + void doHistoryManagementForProfile(String profileId, String path); + + /** + * Removes the history management for profile. + * + * @param profileId the profile id + */ + void removeHistoryManagementForProfile(String profileId); + + /** + * Purge history. + * + * @param profileId the profile id + */ + void purgeHistory(String profileId); + + /** + * Stop history management for profile. + * + * @param profileId the profile id + */ + void stopHistoryManagementForProfile(String profileId); + + /** + * Purge historybefore close. + */ + void purgeHistorybeforeClose(); + + /** + * Sets the SQL query size. + * + * @param queryLength the new SQL query size + */ + void setSQLQuerySize(Integer queryLength); + + /** + * Inits the. + * + * @param eventBroker the event broker + */ + void init(IEventBroker eventBroker); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/util/BLUtils.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/util/BLUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..e10ccd1815ffcac017a447f2ec4c56c48a2755d7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/util/BLUtils.java @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.util; + +import java.util.ArrayList; + +/** + * + * Title: class + * + * Description: The Class BLUtils. + * + */ + +public final class BLUtils implements IBLUtils { + + private String[] args; + private String installationLocation = "."; + private static volatile IBLUtils instance; + private static final Object LOCK = new Object(); + + private BLUtils() { + + } + + /** + * Gets the single instance of BLUtils. + * + * @return single instance of BLUtils + */ + public static IBLUtils getInstance() { + if (instance == null) { + synchronized (LOCK) { + if (instance == null) { + instance = new BLUtils(); + } + } + } + + return instance; + } + + /** + * Sets the platform args. + * + * @param arguments the new platform args + */ + @Override + public void setPlatformArgs(String[] arguments) { + this.args = arguments.clone(); + } + + /** + * Gets the platform args. + * + * @return getPlatformArgs + */ + @Override + public String[] getPlatformArgs() { + if (args != null) { + return args.clone(); + } else { + return new String[0]; + } + + } + + /** + * Gets the installation location. + * + * @return the installation location + */ + @Override + public String getInstallationLocation() { + return installationLocation; + } + + /** + * Gets the un quoted identifier. + * + * @param str the str + * @param quote the quote + * @return the un quoted identifier + */ + public static String getUnQuotedIdentifier(String str, String quote) { + if (str.startsWith(quote) && str.endsWith(quote)) { + return str.substring(quote.length(), str.length() - quote.length()); + } + return str; + } + + /** + * Gets the all combinations of prefix. + * + * @param prefix the prefix + * @return the all combinations of prefix + */ + public static ArrayList getAllCombinationsOfPrefix(String prefix) { + ArrayList prefixList = new ArrayList(10); + char[] chars = prefix.toCharArray(); + char[] permutation = null; + int number = ((Double) (Math.pow(2, chars.length))).intValue(); + for (int index = 0; index < number; index++) { + permutation = new char[chars.length]; + for (int jindex = 0; jindex < chars.length; jindex++) { + permutation[jindex] = (isBitSet(index, jindex)) ? Character.toUpperCase(chars[jindex]) : chars[jindex]; + } + prefixList.add(String.valueOf(permutation)); + } + + return prefixList; + + } + + private static boolean isBitSet(int num, int offset) { + return (num >> offset & 1) != 0; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/util/DebugObjectGauss200Utils.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/util/DebugObjectGauss200Utils.java new file mode 100644 index 0000000000000000000000000000000000000000..98f54eedef747865e81d580ccd78ad1c7668e55f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/util/DebugObjectGauss200Utils.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.util; + +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class DebugObjectGauss200Utils. + * + */ + +public class DebugObjectGauss200Utils { + // Create Template C Function + + /** + * Gets the new function object template. + * + * @param objectRetType the object ret type + * @param namespace the namespace + * @param command the command + * @return the new function object template + */ + public static String getNewFunctionObjectTemplate(String objectRetType, String namespace, String command) { + StringBuilder sqlTemplate = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + sqlTemplate.append("CREATE [OR REPLACE] FUNCTION "); + + if (!"".equals(namespace)) { + sqlTemplate.append(namespace).append('.'); + } + + sqlTemplate.append("function_name ([ parameter datatype[,parameter datatype] ])"); + sqlTemplate.append(MPPDBIDEConstants.LINE_SEPARATOR); + sqlTemplate.append(MPPDBIDEConstants.LINE_SEPARATOR); + + sqlTemplate.append("\tRETURNS " + objectRetType); + + sqlTemplate.append(MPPDBIDEConstants.LINE_SEPARATOR); + + if ("c".equals(command)) { + sqlTemplate.append("\tLANGUAGE C"); + } else { + sqlTemplate.append("\tLANGUAGE SQL"); + } + + sqlTemplate.append(MPPDBIDEConstants.LINE_SEPARATOR); + sqlTemplate.append(MPPDBIDEConstants.LINE_SEPARATOR); + + if ("c".equals(command)) { + sqlTemplate.append("AS"); + sqlTemplate.append(MPPDBIDEConstants.LINE_SEPARATOR); + sqlTemplate.append(MPPDBIDEConstants.LINE_SEPARATOR); + + sqlTemplate.append("\t\'/*iso file path and name*/\',$$/*function name*/$$"); + sqlTemplate.append(MPPDBIDEConstants.LINE_SEPARATOR); + sqlTemplate.append(MPPDBIDEConstants.ESCAPE_FORWARDSLASH); + } else { + sqlTemplate.append("AS $$"); + sqlTemplate.append(MPPDBIDEConstants.LINE_SEPARATOR); + sqlTemplate.append(MPPDBIDEConstants.LINE_SEPARATOR); + + sqlTemplate.append("\t/*executable_section*/"); + sqlTemplate.append(MPPDBIDEConstants.LINE_SEPARATOR); + sqlTemplate.append(MPPDBIDEConstants.LINE_SEPARATOR); + + sqlTemplate.append("$$"); + sqlTemplate.append(MPPDBIDEConstants.LINE_SEPARATOR); + sqlTemplate.append(MPPDBIDEConstants.ESCAPE_FORWARDSLASH); + } + + return sqlTemplate.toString(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/util/ExecTimer.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/util/ExecTimer.java new file mode 100644 index 0000000000000000000000000000000000000000..dfd227caa59ec9d08c70ccaf362db6819b77453f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/util/ExecTimer.java @@ -0,0 +1,220 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.util; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class ExecTimer. + * + */ + +public class ExecTimer implements IExecTimer { + + private String activityName; + private long startTime; + private long stopTime; + private static final String TIME_UNIT = " ms"; + + /** + * Instantiates a new exec timer. + * + * @param name the name + */ + public ExecTimer(String name) { + this.activityName = name; + startTime = 0; + stopTime = 0; + } + + @Override + public IExecTimer start() { + startTime = System.currentTimeMillis(); + stopTime = 0; + if (MPPDBIDELoggerUtility.isTraceEnabled()) { + MPPDBIDELoggerUtility.trace("Timer started for :" + activityName); + } + + return this; + } + + @Override + public void stop() throws DatabaseOperationException { + this.stopTime = System.currentTimeMillis(); + if (0 == startTime) { + MPPDBIDELoggerUtility.error("ExecTimer not started."); + throw new DatabaseOperationException("ExecTimer not started."); + } + } + + @Override + public void logTime() throws DatabaseOperationException { + if (0 == startTime || 0 == stopTime) { + MPPDBIDELoggerUtility.error("ExecTimer not started."); + throw new DatabaseOperationException("ExecTimer not started."); + } + + long elapsedTime = stopTime - startTime; + if (MPPDBIDELoggerUtility.isTraceEnabled()) { + MPPDBIDELoggerUtility.trace("ExecTimer [" + this.activityName + "] " + elapsedTime + TIME_UNIT); + } + } + + @Override + public void stopAndLog() throws DatabaseOperationException { + this.stop(); + this.logTime(); + } + + @Override + public void stopAndLogNoException() { + try { + stopAndLog(); + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("Timer stop failed while execute cursor.", exception); + } + } + + /** + * Checks if is timer stop. + * + * @return true, if is timer stop + */ + @Override + public boolean isTimerStop() { + if (this.stopTime != 0) { + return true; + } + return false; + } + + /** + * Gets the elapsed time. + * + * @return the elapsed time + * @throws DatabaseOperationException the database operation exception + */ + @Override + public String getElapsedTime() throws DatabaseOperationException { + if (0 == startTime || 0 == stopTime) { + MPPDBIDELoggerUtility.error("ExecTimer not started."); + throw new DatabaseOperationException("ExecTimer not started."); + } + + long elapsedTime = stopTime - startTime; + long diffDays = elapsedTime / (24 * 60 * 60 * 1000); + long diffHours = elapsedTime / (60 * 60 * 1000) % 24; + long diffMinutes = elapsedTime / (60 * 1000) % 60; + long diffSeconds = elapsedTime / 1000 % 60; + + StringBuilder str = calculateElapsedTime(elapsedTime, diffDays, diffHours, diffMinutes, diffSeconds); + + return str.toString(); + } + + /** + * Calculate elapsed time. + * + * @param elapsedTime the elapsed time + * @param diffDays the diff days + * @param diffHours the diff hours + * @param diffMinutes the diff minutes + * @param diffSeconds the diff seconds + * @return the string builder + */ + private static StringBuilder calculateElapsedTime(long elapsedTime, long diffDays, long diffHours, long diffMinutes, + long diffSeconds) { + StringBuilder str = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + if (diffDays > 0) { + str.append(diffDays + " days"); + } + + if (diffHours > 0) { + str.append(str.length() > 0 ? ", " : " "); + str.append(diffHours + " hours"); + } + + if (diffMinutes > 0) { + str.append(str.length() > 0 ? ", " : " "); + str.append(diffMinutes + " mins"); + } + + if (diffSeconds > 0) { + str.append(str.length() > 0 ? ", " : " "); + str.append(diffSeconds + " sec"); + } + if (elapsedTime >= 0 && diffSeconds <= 0 && diffMinutes <= 0 && diffHours <= 0 && diffDays <= 0) { + str.append(elapsedTime + " ms"); + } + return str; + } + + /** + * Gets the elapsed time with units. + * + * @param totalTime the total time + * @return the elapsed time with units + */ + public static String getElapsedTimeWithUnits(long totalTime) { + + long elapsedTime = totalTime; + long diffSeconds = elapsedTime / 1000 % 60; + long diffMinutes = elapsedTime / (60 * 1000) % 60; + long diffHours = elapsedTime / (60 * 60 * 1000) % 24; + long diffDays = elapsedTime / (24 * 60 * 60 * 1000); + + StringBuilder elapsedTmUnits = calculateElapsedTime(elapsedTime, diffDays, diffHours, diffMinutes, diffSeconds); + + return elapsedTmUnits.toString(); + } + + /** + * Gets the elapsed time in ms. + * + * @return the elapsed time in ms + * @throws DatabaseOperationException the database operation exception + */ + @Override + public long getElapsedTimeInMs() throws DatabaseOperationException { + if (0 == startTime || 0 == stopTime) { + MPPDBIDELoggerUtility.error("ExecTimer not started."); + throw new DatabaseOperationException("ExecTimer not started."); + } + + long elapsedTime = stopTime - startTime; + return elapsedTime; + } + + @Override + public String getDynamicElapsedTime(boolean isVisible) { + if (this.startTime == 0) { + return ""; + } + + long now = System.currentTimeMillis(); + if (isVisible) { + return getElapsedTimeWithUnits(now - this.startTime); + } + return ""; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/util/IBLUtils.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/util/IBLUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..e921d9f92242e431dd52618aa51598624d026fc8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/util/IBLUtils.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.util; + +/** + * + * Title: interface + * + * Description: The Interface IBLUtils. + * + */ + +public interface IBLUtils { + + /** + * Sets the platform args. + * + * @param arguments the new platform args + */ + void setPlatformArgs(String[] arguments); + + /** + * Gets the platform args. + * + * @return the platform args + */ + String[] getPlatformArgs(); + + /** + * Gets the installation location. + * + * @return the installation location + */ + String getInstallationLocation(); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/util/IExecTimer.java b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/util/IExecTimer.java new file mode 100644 index 0000000000000000000000000000000000000000..a94f62ccb9e145b642d7138da6ceec48a46b9f90 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.bl/src/org/opengauss/mppdbide/bl/util/IExecTimer.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.bl.util; + +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: interface + * + * Description: The Interface IExecTimer. + */ + +public interface IExecTimer { + + /** + * Start. + * + * @return the i exec timer + */ + IExecTimer start(); + + /** + * Stop. + * + * @throws DatabaseOperationException the database operation exception + */ + void stop() throws DatabaseOperationException; + + /** + * Log time. + * + * @throws DatabaseOperationException the database operation exception + */ + void logTime() throws DatabaseOperationException; + + /** + * Stop and log. + * + * @throws DatabaseOperationException the database operation exception + */ + void stopAndLog() throws DatabaseOperationException; + + /** + * Stop and log no exception. + */ + void stopAndLogNoException(); + + /** + * Checks if is timer stop. + * + * @return true, if is timer stop + */ + boolean isTimerStop(); + + /** + * Gets the elapsed time. + * + * @return the elapsed time + * @throws DatabaseOperationException the database operation exception + */ + String getElapsedTime() throws DatabaseOperationException; + + /** + * Gets the elapsed time in ms. + * + * @return the elapsed time in ms + * @throws DatabaseOperationException the database operation exception + */ + long getElapsedTimeInMs() throws DatabaseOperationException; + + /** + * Gets the dynamic elapsed time. + * + * @param isVisible the is visible + * @return the dynamic elapsed time + */ + String getDynamicElapsedTime(boolean isVisible); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/.classpath b/code/datastudio/src/org.opengauss.mppdbide.debuger/.classpath new file mode 100644 index 0000000000000000000000000000000000000000..751c8f2e504c40d1c41ebbd87d8f8968529e9c30 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/.gitignore b/code/datastudio/src/org.opengauss.mppdbide.debuger/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..0f630157f4bf530f9697788f383cabaab83dc2e8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/.gitignore @@ -0,0 +1,2 @@ +/target/ +/bin/ diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/.project b/code/datastudio/src/org.opengauss.mppdbide.debuger/.project new file mode 100644 index 0000000000000000000000000000000000000000..b9597e072afeb5f5483569fb2b7e7865b7aa0a95 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/.project @@ -0,0 +1,34 @@ + + + org.opengauss.mppdbide.debuger + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.m2e.core.maven2Nature + org.eclipse.jdt.core.javanature + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/META-INF/MANIFEST.MF b/code/datastudio/src/org.opengauss.mppdbide.debuger/META-INF/MANIFEST.MF new file mode 100644 index 0000000000000000000000000000000000000000..2a29a9e20ed5a232f17618256d37a9cb0e1212a3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/META-INF/MANIFEST.MF @@ -0,0 +1,28 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: MPPDBIDE_Debuger +Bundle-SymbolicName: org.opengauss.mppdbide.debuger +Bundle-Version: 1.0.0.qualifier +Bundle-Vendor: Huawei Technologie +Bundle-Activator: org.opengauss.mppdbide.debuger.Activator +Require-Bundle: org.eclipse.core.runtime;bundle-version="3.15.300", + org.apache.commons.lang;bundle-version="2.6.0", + org.opengauss.mppdbide.adapter.gauss;bundle-version="1.0.0", + org.opengauss.mppdbide.util;bundle-version="1.0.0" +Bundle-RequiredExecutionEnvironment: JavaSE-11 +Export-Package: org.opengauss.mppdbide.common, + org.opengauss.mppdbide.debuger, + org.opengauss.mppdbide.debuger.annotation, + org.opengauss.mppdbide.debuger.dao, + org.opengauss.mppdbide.debuger.debug, + org.opengauss.mppdbide.debuger.event, + org.opengauss.mppdbide.debuger.exception, + org.opengauss.mppdbide.debuger.service, + org.opengauss.mppdbide.debuger.service.chain, + org.opengauss.mppdbide.debuger.thread, + org.opengauss.mppdbide.debuger.vo +Bundle-ClassPath: . +Import-Package: org.postgresql.core, + org.postgresql.jdbc, + org.postgresql.util +Bundle-ActivationPolicy: lazy diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/build.properties b/code/datastudio/src/org.opengauss.mppdbide.debuger/build.properties new file mode 100644 index 0000000000000000000000000000000000000000..34d2e4d2dad529ceaeb953bfcdb63c51d69ffed2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/build.properties @@ -0,0 +1,4 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + . diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/pom.xml b/code/datastudio/src/org.opengauss.mppdbide.debuger/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..8fabd10f8e4102aefeadd83d3d53151f74d0a21b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/pom.xml @@ -0,0 +1,12 @@ + + + 4.0.0 + + org.opengauss.plide.build + GAUSS_MPP_DB_IDE + 1.0.0-SNAPSHOT + + org.opengauss.mppdbide.debuger + eclipse-plugin + diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/common/DBConnectionAdapter.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/common/DBConnectionAdapter.java new file mode 100644 index 0000000000000000000000000000000000000000..85750ffce74eb276841947526b548481f73c1f79 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/common/DBConnectionAdapter.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.common; + +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.List; + +import org.postgresql.core.NoticeListener; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.debuger.debug.DebugConstants; +import org.opengauss.mppdbide.debuger.debug.DebugConstants.DebugOpt; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * Title: DBConnectionAdapter for use + * Description: IConnection instance + * + * @since 3.0.0 + */ +public class DBConnectionAdapter implements IConnection { + /** + * the default of debug function operation timeout + */ + private static final int DEFAULT_DEBUG_QUERY_TIMEOUT = 5; + private DBConnection conn; + private IConnectionDisconnect disconnect; + private NoticeListener listener; + + public DBConnectionAdapter( + DBConnection conn, + IConnectionDisconnect disconnect) { + this.conn = conn; + this.disconnect = disconnect; + } + + /** + * get PreparedStatement from connection + * + * @param sql sql to execute + * @return PreparedStatement preparedstatement instance + * @throws SQLException sql exception + */ + @Override + public PreparedStatement getStatement(String sql) throws SQLException { + try { + PreparedStatement ps = conn.getPrepareStmt(sql); + if (this.listener != null) { + GaussManager.INSTANCE.addNoticeListener(ps, this.listener); + } + return ps; + } catch (DatabaseCriticalException | DatabaseOperationException dbException) { + throw new SQLException(dbException.getMessage(), "", dbException.getErrorCode()); + } + } + + /** + * get templated of DebugOpt PreparedStatement from connection + * + * @param debugOpt enum opt + * @param params the param to set to PreparedStatement + * @return PreparedStatement preparedstatement instance + * @throws SQLException sql exception + */ + @Override + public PreparedStatement getDebugOptPrepareStatement( + DebugOpt debugOpt, + List params) throws SQLException { + String sql = DebugConstants.getSql(debugOpt); + PreparedStatement ps = getStatement(sql); + ps.setQueryTimeout(DEFAULT_DEBUG_QUERY_TIMEOUT); + for (int i = 1 ; i < params.size() + 1 ; i ++) { + ps.setObject(i, params.get(i - 1)); + } + return ps; + } + + @Override + public void setNoticeListener(NoticeListener listener) { + this.listener = listener; + } + + @Override + public void close() throws SQLException { + if (this.conn != null) { + this.disconnect.releaseConnection(conn); + this.conn = null; + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/common/GaussManager.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/common/GaussManager.java new file mode 100644 index 0000000000000000000000000000000000000000..76d141b394f52c32ad0fb22dc6be3fa5933658c3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/common/GaussManager.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.common; + +import org.postgresql.core.BaseStatement; +import org.postgresql.core.NoticeListener; + +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.SQLWarning; + +/** + * Title: GaussManager for use + * Description: GaussManager to add default listener to PreparedStatement + * + * @since 3.0.0 + */ +public class GaussManager { + /** + * singleton instance + */ + public static final GaussManager INSTANCE = new GaussManager(); + + private GaussManager() { + } + + /** + * add noticeListener to PreparedStatement object + * + * @param ps listener to set + * @return boolean true if success + */ + public boolean addNoticeListener(PreparedStatement ps) { + return addNoticeListener(ps, getNoticeListener()); + } + + /** + * add noticeListener to PreparedStatement object + * + * @param ps listener to set + * @param listener the listener + * @return boolean true if success + */ + public boolean addNoticeListener(PreparedStatement ps, NoticeListener listener) { + if (ps instanceof BaseStatement) { + try { + ((BaseStatement) ps).addNoticeListener(listener); + return true; + } catch (SQLException e) { + e.printStackTrace(); + } + } + return false; + } + + /** + * get default noticeListener to PreparedStatement object + * + * @return NoticeListener instance of listener + */ + public NoticeListener getNoticeListener() { + return new GaussNoticeListener(); + } + + private static class GaussNoticeListener implements NoticeListener { + @Override + public void noticeReceived(SQLWarning notice) { + if (notice == null || notice.getMessage() == null) { + return; + } + String msgString = notice.getMessage(); + MPPDBIDELoggerUtility.info("default sql message:" + msgString); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/common/IConnection.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/common/IConnection.java new file mode 100644 index 0000000000000000000000000000000000000000..588ad6893afd925d9f8e6bd5770c05f9f38f2fcb --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/common/IConnection.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.common; + +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.List; + +import org.opengauss.mppdbide.debuger.debug.DebugConstants; +import org.postgresql.core.NoticeListener; + +/** + * Title: interface + * Description: IConnection + * + * @since 3.0.0 + */ +public interface IConnection { + /** + * description: get PreparedStatement instance + * + * @param sql the sql query string + * @return PreparedStatement the instance + * @throws SQLException then sql exception + */ + PreparedStatement getStatement(String sql) throws SQLException; + + /** + * description: get PreparedStatement instance + * + * @param debugOpt which debug operation + * @param params input params + * @return PreparedStatement the instance + * @throws SQLException then sql exception + */ + PreparedStatement getDebugOptPrepareStatement(DebugConstants.DebugOpt debugOpt, + List params) throws SQLException; + + /** + * description: set listener + * + * @param listener then listener + * @return void + */ + void setNoticeListener(NoticeListener listener); + + /** + * description: close connection + * + * @return void + * @throws SQLException + */ + void close() throws SQLException; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/common/IConnectionDisconnect.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/common/IConnectionDisconnect.java new file mode 100644 index 0000000000000000000000000000000000000000..75c7857870f18037d608d188973b8d12099ddf76 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/common/IConnectionDisconnect.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.common; + +/** + * Title: IConnectionDisconnect for use + * Description: use to release connection + * + * @since 3.0.0 + */ +public interface IConnectionDisconnect { + /** + * description: release generated connection + * + * @param connection contact of free connection + */ + void releaseConnection(T connection); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/common/IConnectionProvider.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/common/IConnectionProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..cfa79cb8cf5389790096583d3f100246d5f56a34 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/common/IConnectionProvider.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.common; + +import java.sql.SQLException; +import java.util.Optional; + +/** + * Title: IConnectionProvider + * Description: IConnectionProvider to provider connection of database + * + * @since 3.0.0 + */ +public interface IConnectionProvider { + /** + * desrciption: get free connection from database + * + * @return Optional the connection + */ + Optional getFreeConnection(); + + /** + * desrciption: get free valid connection from database + * + * @return IConnection the connection + * @throws SQLException the null connection exception + */ + default IConnection getValidFreeConnection() throws SQLException { + Optional conn = getFreeConnection(); + if (conn.isPresent()) { + return conn.get(); + } + throw new SQLException("get free connection failed!"); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/Activator.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/Activator.java new file mode 100644 index 0000000000000000000000000000000000000000..cef6fe5f54eda5b7d51ad617390377f6286db655 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/Activator.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; + +/** + * Title: class + * Description: The Class Activator. + * + * @since 3.0.0 + */ +public class Activator implements BundleActivator { + private static BundleContext context; + + /** + * Gets the context. + * + * @return the context + */ + public static BundleContext getContext() { + return context; + } + + /** + * Sets the context. + * + * @param bundleContext the new context + */ + public static void setContext(BundleContext bundleContext) { + Activator.context = bundleContext; + } + + /** + * Start. + * + * @param bundleContext the bundle context + */ + public void start(BundleContext bundleContext) { + setContext(bundleContext); + } + + /** + * Stop. + * + * @param bundleContext the bundle context + */ + public void stop(BundleContext bundleContext) { + setContext(null); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/annotation/DumpFiled.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/annotation/DumpFiled.java new file mode 100644 index 0000000000000000000000000000000000000000..12b765ecbc659f86b4f5325491ff8fdbc5731d82 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/annotation/DumpFiled.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.annotation; + +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; +import java.lang.annotation.ElementType; +import java.lang.annotation.RetentionPolicy; + +/** + * Title: annotation for DumpField + * Description: The dump vo's attr + * + * @since 3.0.0 + */ +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +@Inherited +public @interface DumpFiled { + String name() default ""; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/annotation/ParseVo.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/annotation/ParseVo.java new file mode 100644 index 0000000000000000000000000000000000000000..7f3583bb5b19192eb566dfcd941624144e224e58 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/annotation/ParseVo.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.annotation; + +import java.lang.reflect.Field; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; + +/** + * Title: class for LoadVO + * Description: The dump VO load class + * + * @since 3.0.0 + */ +public class ParseVo { + /** + * get inputs clz's all fields with annotation @DumpField. + * + * @param clz input clz + * @return Map return map field name and Field + */ + public static Map parseDumpFields(Class clz) { + Field[] fields = clz.getDeclaredFields(); + Map name2Field = new HashMap<>(); + for (Field f: fields) { + DumpFiled dumpFiled = f.getAnnotation(DumpFiled.class); + if (dumpFiled != null) { + String name = dumpFiled.name(); + if ("".equals(name)) { + name = f.getName(); + } + name2Field.put(name, f); + } + } + return name2Field; + } + + /** + * fill inputs clz's all fields with annotation @DumpField by ResultSet. + * + * @param rs database query one row + * @param clazz input clz + * @return T new instance by ResultSet + */ + public static T parse(ResultSet rs, Class clazz) { + Map name2Field = parseDumpFields(clazz); + return parse(rs, clazz, name2Field); + } + + /** + * get list of class from rs + * + * @param rs database query one row + * @param clazz input clz + * @return List new instance by ResultSet + * @throws SQLException execute with ResultSet error + */ + public static List parseList(ResultSet rs, Class clazz) throws SQLException { + Map name2Field = parseDumpFields(clazz); + List vos = new ArrayList<>(); + while (rs.next()) { + vos.add(ParseVo.parse(rs, clazz, name2Field)); + } + return vos; + } + + /** + * fill inputs clz's all fields with annotation @DumpField by ResultSet. + * + * @param rs database query one row + * @param clazz input clz + * @param name2Field returned by parseDumpFields + * @return T new instance by ResultSet + */ + public static T parse(ResultSet rs, Class clazz, Map name2Field) { + T obj; + try { + obj = clazz.newInstance(); + for (Entry entry: name2Field.entrySet()) { + Field field = entry.getValue(); + Optional tmpObj = getValueByKey(rs, entry.getKey(), field); + field.set(obj, tmpObj.orElse(null)); + } + } catch (InstantiationException | SQLException | IllegalAccessException ignored) { + obj = null; + } + return obj; + } + + /** + * get value from rs by special field + * + * @param rs database query one row + * @param key ResultSet's column + * @param field input clz + * @return Object new instance of ResultSet' column + * @throws SQLException throw get column error + */ + public static Optional getValueByKey(ResultSet rs, String key, Field field) throws SQLException { + return getValueByKey(rs, key, field.getType()); + } + + /** + * get ResultSet' column value and convert to type. + * + * @param rs database query one row + * @param key ResultSet's column + * @param type input clz + * @return Object new instance of ResultSet' column + * @throws SQLException throw get column error + */ + public static Optional getValueByKey( + ResultSet rs, + String key, + Class type) throws SQLException { + Object obj = rs.getObject(key); + if (rs.wasNull()) { + obj = null; + } + return Optional.ofNullable(obj); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/dao/FunctionDao.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/dao/FunctionDao.java new file mode 100644 index 0000000000000000000000000000000000000000..abeded7b15f9af53cb73e753c487fc0a8554be58 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/dao/FunctionDao.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.dao; + +import org.opengauss.mppdbide.debuger.annotation.ParseVo; +import org.opengauss.mppdbide.debuger.vo.FunctionVo; + +import java.sql.ResultSet; +import java.util.Locale; + +/** + * Title: the FunctionDao class + * + * @since 3.0.0 + */ +public class FunctionDao { + /** + * query function detail by proname + * + * @param proname name of function + * @return String query sql + */ + public String getSql(String proname) { + String sql = "select oid, proname, proretset, prorettype, " + + "pronargs, pronargdefaults, proargtypes, proallargtypes," + + "proargmodes, proargnames, proargdefaults, " + + "prodefaultargpos, prosrc from pg_proc where proname = "; + return String.format(Locale.ENGLISH, "%s \'%s\'", sql, proname); + } + + /** + * parse ResultSet to FunctionVo object + * + * @param rs the sql query result + * @return FunctionVo the result + */ + public FunctionVo parse(ResultSet rs) { + return ParseVo.parse(rs, FunctionVo.class); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/debug/DebugConstants.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/debug/DebugConstants.java new file mode 100644 index 0000000000000000000000000000000000000000..8e28d5218d2c168aee52829c67bb63d46389b188 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/debug/DebugConstants.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.debug; + +import java.util.Locale; +import java.util.stream.Stream; + +/** + * Title: the DebugConstants class + * + * @since 3.0.0 + */ +public class DebugConstants { + /** + * default string length + */ + public static final int DEFAULT_STRING_BUILD_LEN = 128; + + /** + * Title: the DebugOpt enum use to descript debuger interface + */ + public static enum DebugOpt { + DEBUG_ON("pldbg_on", 0), + DEBUG_OFF("pldbg_off", 0), + DEBUG_VERSION("pldbg_get_proxy_info", 0), + GET_SOURCE_CODE("pldbg_get_source", 1), + GET_TOTAL_SOURCE_CODE("pg_get_functiondef", 1), + START_SESSION("plpgsql_oid_debug", 1), + ATTACH_SESSION("pldbg_attach_to_port", 1), + STEP_INTO("pldbg_step_into", 1), + STEP_OVER("pldbg_step_over", 1), + STEP_OUT("pldbg_step_out", 1), + CONTINUE_EXEC("pldbg_continue", 1), + ABORT_TARGET("pldbg_abort_target", 1), + GET_VARIABLES("pldbg_get_variables", 1), + GET_STACKS("pldbg_get_stack", 1), + GET_BREAKPOINTS("pldbg_get_breakpoints", 1), + DROP_BREAKPOINT("pldbg_drop_breakpoint", 3), + SET_BREAKPOINT("pldbg_set_breakpoint", 3); + + /** + * opt of interface + */ + public final String opt; + /** + * interface param num + */ + public final int paramNum; + + DebugOpt(String opt, int paramNum) { + this.opt = opt; + this.paramNum = paramNum; + } + }; + + /** + * get opt sql query + * + * @param debugOpt the interface desc + * @return String query sql + */ + public static String getSql(DebugOpt debugOpt) { + return getSql(debugOpt.opt, debugOpt.paramNum); + } + + /** + * get opt sql query + * + * @param debugOpt the interface desc + * @param paramNum number of input params number + * @return String query sql + */ + public static String getSql(String opt, int paramNum) { + // generate number of ? + String paramReplace = Stream.iterate(0, number -> number) + .limit(paramNum) + .map(paramArg -> "?") + .reduce((paramArgsA, paramArgsB) -> paramArgsA + "," + paramArgsB) + .orElse(""); + return String.format(Locale.ENGLISH, "select * from %s(%s)", + opt, + paramReplace + ); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/debug/DebugState.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/debug/DebugState.java new file mode 100644 index 0000000000000000000000000000000000000000..58317fbd86f417a4ba1fd82582436635538ec060 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/debug/DebugState.java @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.debug; + +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: the DebugState class + * + * @since 3.0.0 + */ +public class DebugState { + /** + * Title: state of debuger + */ + public static enum State { + UNKNOWN(-1), + PREPARED(0), + RUNNING(1), + ATTACHED(2), + STOP(3), + TERMINALED(4); + + /** + * state to description + */ + public final int state; + + State(int state) { + this.state = state; + } + } + + private State state = State.UNKNOWN; + private boolean stateLocked = false; + + /** + * set prepared state + * + * @return void + */ + public void prepared() { + setState(State.PREPARED); + } + + /** + * set running state + * + * @return void + */ + public void running() { + setState(State.RUNNING); + } + + /** + * set stop state + * + * @return void + */ + public void stop() { + setState(State.STOP); + } + + /** + * set ternimaled state + * + * @return void + */ + public void terminaled() { + setState(State.TERMINALED); + } + + /** + * set attached state + * + * @return void + */ + public void attached() { + setState(State.ATTACHED); + } + + /** + * query is running + * + * @return boolean true if running + */ + public boolean isRunning() { + return this.state == State.RUNNING; + } + + /** + * query is stopped + * + * @return boolean true if stopped + */ + public boolean isStopped() { + return state == State.STOP || state == State.TERMINALED; + } + + /** + * query is normal stopped + * + * @return boolean true if normal stopped + */ + public boolean isNormalStopped() { + return state == State.STOP; + } + + /** + * lock state, and can't modify state after this + * + * @return void no ret + */ + public void stateLocked() { + this.stateLocked = true; + } + + /** + * query if state locked + * + * @return boolean true if locked + */ + public boolean getLockState() { + return this.stateLocked; + } + + /** + * query cur state + * + * @return State cur state + */ + public State getState() { + return this.state; + } + + /** + * set cur state + * + * @param state cur state to set + * @return void no ret + */ + public void setState(State state) { + if (state == getState()) { + return; + } + + if (!getLockState()) { + this.state = state; + return; + } else { + MPPDBIDELoggerUtility.warn("not allow modify state!"); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/event/DebugAddtionMsg.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/event/DebugAddtionMsg.java new file mode 100644 index 0000000000000000000000000000000000000000..f682526fd97a4af11ea2868fd834a6e420f39ad9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/event/DebugAddtionMsg.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.event; + +import java.util.Locale; +import java.util.Optional; + +import org.opengauss.mppdbide.debuger.vo.PositionVo; + +/** + * Title: DebugAddtionMsg for use + * + * @since 3.0.0 + */ +public class DebugAddtionMsg { + /** + * + * Title: State for use + */ + public static enum State { + START, + END; + } + + private State state; + private PositionVo positionVo; + + public DebugAddtionMsg(State state) { + this(state, null); + } + + public DebugAddtionMsg(State state, PositionVo positionVo) { + this.state = state; + this.positionVo = positionVo; + } + + /** + * description: get stateu + * + * @return State get state + */ + public State getState() { + return state; + } + + /** + * description: get position vo + * + * @return Optional the position vo + */ + public Optional getPositionVo() { + return Optional.ofNullable(positionVo); + } + + @Override + public String toString() { + return String.format(Locale.ENGLISH, "DebugAdditionMsg{state: %s, position: %s}", + this.state.toString(), + positionVo == null ? "" : positionVo.formatSelf()); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/event/Event.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/event/Event.java new file mode 100644 index 0000000000000000000000000000000000000000..087c6fd5a9f8d4442101884a0a7b846b877caa6f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/event/Event.java @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.event; + +import java.util.Locale; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Title: the Event class + * + * @since 3.0.0 + */ +public class Event { + /** + * Title: the EventMessage enum + */ + public static enum EventMessage { + ON_EXIT, + ON_SQL_MSG, + DEBUG_BEGIN, + DEBUG_RUN, + DEBUG_END, + BREAKPOINT_ADD, + BREAKPOINT_DELETE, + BREAKPOINT_CHANGE, + CANCEL_HIGHLIGHT; + } + + private static AtomicInteger autoId = new AtomicInteger(); + private EventMessage msg; + private Object addition; + private Exception exp; + private int id = -1; + + public Event(EventMessage msg, Object addtion) { + this(msg, addtion, null); + } + + public Event(EventMessage msg, Object addtion, Exception exp) { + this(msg, addtion, exp, autoId.getAndIncrement()); + } + + public Event(EventMessage msg, Object addition, Exception exp, int id) { + this.msg = msg; + this.addition = addition; + this.exp = exp; + this.id = id; + } + + /** + * get event id + * + * @return int unique id + */ + public int getId() { + return id; + } + + /** + * get event type + * + * @return EventMessage the eunm of message + */ + public EventMessage getMsg() { + return this.msg; + } + + /** + * get addition msg + * + * @return Optional return addition msg + */ + public Optional getAddition() { + return Optional.ofNullable(this.addition); + } + + /** + * get addition string msg + * + * @return String auto convert addtion object to String object + */ + public String getStringAddition() { + if (this.addition instanceof String) { + return (String) this.addition; + } + return addition.toString(); + } + + /** + * get addition integer msg + * + * @return int auto convert addtion object to Integer object + */ + public int getIntegerAddition() { + if (this.addition instanceof Integer) { + return (Integer) this.addition; + } + return -1; + } + + /** + * get if have exception + * + * @return boolean true if have exception + */ + public boolean hasException() { + return exp != null; + } + + /** + * get exception + * + * @return Exception if exp occur, this will not null + */ + public Exception getException() { + return this.exp; + } + + @Override + public String toString() { + return String.format( + Locale.ENGLISH, + "Event{id: %s,type: %s, addition:%s, exp: %s}", + id, + msg.toString(), + addition == null ? "" : addition.toString(), + exp == null ? "" : exp.getMessage()); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/event/EventHander.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/event/EventHander.java new file mode 100644 index 0000000000000000000000000000000000000000..2bb9507772608840aede21ee233b0ca6f85cee96 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/event/EventHander.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.event; + +/** + * Title: the EventHander interface + * + * @since 3.0.0 + */ +public interface EventHander { + void handleEvent(Event event); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/event/IHandlerManger.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/event/IHandlerManger.java new file mode 100644 index 0000000000000000000000000000000000000000..8155ef2653fa003aae293d5f63f11d239daa8a5e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/event/IHandlerManger.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.event; + +/** + * Title: IHandlerManger for use + * + * @since 3.0.0 + */ +public interface IHandlerManger { + /** + * description: add handler + * + * @param handler handler to add + * @return void + */ + void addHandler(EventHander handler); + + /** + * description: remove handler + * + * @param handler handler to remove + * @return void + */ + void removeHandler(EventHander handler); + + /** + * description: remove all handler + * + * @return remote all handler + */ + void removeAllHandler(); + + /** + * description: notify all handler + * + * @param event the event to notify + * @return void + */ + void notifyAllHandler(Event event); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/exception/DebugExitException.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/exception/DebugExitException.java new file mode 100644 index 0000000000000000000000000000000000000000..543195cd91fedb42f2a91ad232495be35ad39079 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/exception/DebugExitException.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.exception; + +/** + * Title: the DebugExitException class + * + * @since 3.0.0 + */ +public class DebugExitException extends Exception { + /** + * description of exit exception + */ + public static final String DEBUG_EXIT = "debug_exit"; + + /** + * serialVersionUID + */ + private static final long serialVersionUID = 6693123333489198245L; + + public DebugExitException() { + super(DEBUG_EXIT); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/exception/DebugPositionNotFoundException.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/exception/DebugPositionNotFoundException.java new file mode 100644 index 0000000000000000000000000000000000000000..7dad7df6e00e09417ded197a9afd0b8f43809e1a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/exception/DebugPositionNotFoundException.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.exception; + +/** + * Title: the DebugPositionNotFoundException class + * + * @since 3.0.0 + */ +public class DebugPositionNotFoundException extends Exception { + /** + * serialVersionUID + */ + private static final long serialVersionUID = 611011583720487538L; + private static final String DEBUG_POSITION_NOT_FOUND = "debug_position_not_found"; + + public DebugPositionNotFoundException() { + super(DEBUG_POSITION_NOT_FOUND); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/DebugService.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/DebugService.java new file mode 100644 index 0000000000000000000000000000000000000000..ea5d4e2dbb80fc7af994312a22d1188481887edf --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/DebugService.java @@ -0,0 +1,684 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.service; + +import org.opengauss.mppdbide.debuger.event.Event; +import org.opengauss.mppdbide.debuger.event.EventHander; +import org.opengauss.mppdbide.debuger.event.Event.EventMessage; +import org.opengauss.mppdbide.debuger.exception.DebugExitException; +import org.opengauss.mppdbide.debuger.service.chain.MsgChainHelper; +import org.opengauss.mppdbide.debuger.annotation.ParseVo; +import org.opengauss.mppdbide.debuger.debug.DebugConstants; +import org.opengauss.mppdbide.debuger.debug.DebugConstants.DebugOpt; +import org.opengauss.mppdbide.debuger.debug.DebugState; +import org.opengauss.mppdbide.debuger.thread.DebugServerRunable; +import org.opengauss.mppdbide.debuger.thread.DebugServerThreadProxy; +import org.opengauss.mppdbide.debuger.thread.EventQueueThread; +import org.opengauss.mppdbide.debuger.vo.FunctionVo; +import org.opengauss.mppdbide.debuger.vo.PositionVo; +import org.opengauss.mppdbide.debuger.vo.SessionVo; +import org.opengauss.mppdbide.debuger.vo.StackVo; +import org.opengauss.mppdbide.debuger.vo.VariableVo; +import org.opengauss.mppdbide.debuger.vo.VersionVo; +import org.opengauss.mppdbide.common.IConnection; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.postgresql.core.NoticeListener; + +import java.lang.Thread.State; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** + * Title: the DebugService class + * Description: this is module use to debug openGauss database's pl/sql function. + * you can use by this step: + * 1. create and DebugService by new DebugService() + * 2. set DebugService.functionVo which come from QueryService.queryFunction + * by functionName + * 3. set DebugService.clientConn and DebugService.serverConn, + * this is IConnection instance, your can create ConnectionAdapter objects + * 4. set DebugService.clinetConn and DebugService.serverConn's NoticeListener, + * which is DebugService instance self + * 5. call DebugService.prepareDebug + * 6. call DebugService.startDebug and receive return value for close back server + * thread in end + * 7. call DebugService.attachDebug + * 8. then you can use stepOver/StepInto/continueExec to control debug process + * 9. you can use getVariables and getStacks get variables and stacks info + * 10. you can use getBreakPoints/setBreakpoint/dropBreakpoint function to manager + * breakpoints + * 11. when debug over, call DebugService.abortDebug, if forget this operation, + * threadleak will occur + * 12. call DebugService.debugOff, if forget this operation, openGauss Database + * will exit!! + * 13. call DebugService.closeConn + * sample use you can see DebugTest.java + * + * @since 3.0.0 + */ +public class DebugService implements NoticeListener, EventHander, IDebugService { + private static final int DEFAULT_WAIT_LOCK_TIME = 2000; // ms + private IConnection serverConn; + private IConnection clientConn; + private FunctionVo functionVo; + private MsgChainHelper msgChainHelper; + private boolean isRollback = false; + private SessionVo sessionVo = new SessionVo(); + private final Object waitLock = new int[0]; + private DebugState serverState = new DebugState(); + private DebugState clientState = new DebugState(); + private EventQueueThread eventQueueThread = new EventQueueThread(); + private DebugServerThreadProxy serverThreadProxy = new DebugServerThreadProxy(); + + public DebugService() { + eventQueueThread.addHandler(this); + msgChainHelper = new MsgChainHelper(this); + } + + /** + * prepare to debug + * + * @return void + * @throws SQLException the exp + */ + public void prepareDebug() throws SQLException { + List inputsParams = Arrays.asList(functionVo.oid); + serverConn.getDebugOptPrepareStatement( + DebugConstants.DebugOpt.START_SESSION, + inputsParams).execute(); + } + + /** + * start to debug + * + * @param args input args to function + * @return DebugServerThreadProxy debug manager thread + */ + public DebugServerThreadProxy startDebug(List args) { + DebugServerRunable debugServerRunable = new DebugServerRunable( + this, + args, + eventQueueThread); + serverThreadProxy.setDebugServerRunable(debugServerRunable); + serverThreadProxy.start(); + return serverThreadProxy; + } + + /** + * get debug manager thread + * + * @return DebugServerThreadProxy debug manager thread + */ + public DebugServerThreadProxy getServerThreadProxy() { + return serverThreadProxy; + } + + /** + * when server backthread started, this will callback + * + * @param args input args to function + * @return Optional the function result + * @throws SQLException the exp + */ + public Optional serverDebugCallBack(List args) throws SQLException { + try { + serverCallBackBegin(); + String sql = DebugConstants.getSql(functionVo.proname, args.size()); + try (PreparedStatement ps = serverConn.getStatement(sql)) { + for (int i = 1 ; i < args.size() + 1; i ++) { + ps.setObject(i, args.get(i - 1)); + } + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + return Optional.ofNullable(rs.getObject(1)); + } + return Optional.empty(); + } + } + } finally { + serverCallBackEnd(); + } + } + + /** + * client attach debug + * + * @return void + * @throws SQLException the exp + */ + public void attachDebug() throws SQLException { + waitServerStart(); + List inputParams = Arrays.asList(sessionVo.serverPort); + try (PreparedStatement ps = clientConn.getDebugOptPrepareStatement( + DebugConstants.DebugOpt.ATTACH_SESSION, inputParams)) { + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + clientState.attached(); + sessionVo.clientPort = rs.getInt(1); + return; + } + } + } + throw new SQLException("client attach failed, please check"); + } + + private void waitServerStart() throws SQLException { + synchronized (waitLock) { + try { + waitLock.wait(DEFAULT_WAIT_LOCK_TIME); + } catch (InterruptedException intExp) { + MPPDBIDELoggerUtility.debug("wait has error!!!! err=" + intExp.toString()); + Thread.currentThread().interrupt(); + } + } + + if (!serverState.isRunning()) { + throw new SQLException("server not running, please check!"); + } + } + + /** + * server set debug session off + * + * @return void + * @throws SQLException the exp + */ + public void debugOff() throws SQLException { + serverConn.getDebugOptPrepareStatement( + DebugConstants.DebugOpt.DEBUG_OFF, + new ArrayList(1)).execute(); + } + + /** + * client abort debug + * + * @return Optional true if success + * @throws SQLException the exp + */ + public Optional abortDebug() throws SQLException { + if (clientState.isStopped()) { + return Optional.empty(); + } + List inputParams = Arrays.asList(sessionVo.clientPort); + try (PreparedStatement ps = clientConn.getDebugOptPrepareStatement( + DebugConstants.DebugOpt.ABORT_TARGET, inputParams)) { + clientState.stop(); + clientState.stateLocked(); + try (ResultSet rs = ps.executeQuery()) { + Boolean result = false; + if (rs.next()) { + result = rs.getBoolean(1); + } + return Optional.of(result); + } + } + } + + /** + * step over run + * + * @return Optional the breakpoint line position + * @throws SQLException the exp + * @throws DebugExitException the debug exit exp + */ + @Override + public Optional stepOver() throws SQLException, DebugExitException { + return getPositionVo(DebugConstants.DebugOpt.STEP_OVER); + } + + /** + * step into run + * + * @return Optional the breakpoint line position + * @throws SQLException the exp + * @throws DebugExitException the debug exit exp + */ + @Override + public Optional stepInto() throws SQLException, DebugExitException { + return getPositionVo(DebugConstants.DebugOpt.STEP_INTO); + } + + /** + * step out run + * + * @return Optional the breakpoint line position + * @throws SQLException the exp + * @throws DebugExitException the debug exit exp + */ + @Override + public Optional stepOut() throws SQLException, DebugExitException { + return getPositionVo(DebugOpt.STEP_OUT); + } + + /** + * continue exec run + * + * @return Optional the breakpoint line position + * @throws SQLException the exp + * @throws DebugExitException the debug exit exp + */ + @Override + public Optional continueExec() throws SQLException, DebugExitException { + return getPositionVo(DebugConstants.DebugOpt.CONTINUE_EXEC); + } + + /** + * step run common command + * + * @param debugOpt which opteration to exec + * @return Optional the breakpoint line position + * @throws SQLException the exp + * @throws DebugExitException the debug exit exp + */ + @Override + public Optional getPositionVo( + DebugConstants.DebugOpt debugOpt + ) throws SQLException, DebugExitException { + clientState.running(); + if (debugOpt == DebugOpt.STEP_OUT) { + throw new SQLException("not support method!"); + } + List inputParams = Arrays.asList(sessionVo.clientPort); + try (PreparedStatement ps = clientConn.getDebugOptPrepareStatement( + debugOpt, inputParams)) { + try (ResultSet rs = ps.executeQuery()) { + // this order is very important, because when debug opt is return, + // maybe server is already over, so must stop debug! + if (!serverState.isRunning()) { + throw new DebugExitException(); + } + PositionVo positionVo = null; + if (rs.next()) { + positionVo = ParseVo.parse(rs, PositionVo.class); + } + return Optional.ofNullable(positionVo); + } + } + } + + /** + * get cur variables + * + * @return List all variables + * @throws SQLException the exp + */ + @Override + public List getVariables() throws SQLException { + return getListVos(DebugConstants.DebugOpt.GET_VARIABLES, VariableVo.class); + } + + /** + * get cur stacks + * + * @return List all stacks + * @throws SQLException the exp + */ + @Override + public List getStacks() throws SQLException { + return getListVos(DebugConstants.DebugOpt.GET_STACKS, StackVo.class); + } + + /** + * get cur breakpoints + * + * @return List all breakpoints + * @throws SQLException the exp + */ + @Override + public List getBreakPoints() throws SQLException { + return getListVos(DebugConstants.DebugOpt.GET_BREAKPOINTS, PositionVo.class); + } + + private List getListVos(DebugConstants.DebugOpt debugOpt, Class clazz) throws SQLException { + List inputParams = Arrays.asList(sessionVo.clientPort); + try (PreparedStatement ps = clientConn.getDebugOptPrepareStatement( + debugOpt, inputParams)) { + try (ResultSet rs = ps.executeQuery()) { + List results = ParseVo.parseList(rs, clazz); + return results; + } + } + } + + /** + * set breakpoint + * + * @param positionVo which line will set breakpoint + * @return boolean true if success + * @throws SQLException the exp + */ + @Override + public boolean setBreakPoint(PositionVo positionVo) throws SQLException { + return disposeBreakpoint(DebugConstants.DebugOpt.SET_BREAKPOINT, positionVo); + } + + /** + * delete breakpoint + * + * @param positionVo which line will set breakpoint + * @return boolean true if success + * @throws SQLException the exp + */ + @Override + public boolean dropBreakPoint(PositionVo positionVo) throws SQLException { + return disposeBreakpoint(DebugConstants.DebugOpt.DROP_BREAKPOINT, positionVo); + } + + /** + * set/delete breakpoint + * + * @param debugOpt which opteration to exec + * @param positionVo which line will set breakpoint + * @return boolean true if success + * @throws SQLException the exp + */ + public boolean disposeBreakpoint(DebugConstants.DebugOpt debugOpt, + PositionVo positionVo) throws SQLException { + if (positionVo.func == null || positionVo.func.intValue() == 0) { + positionVo.func = functionVo.oid; + } + + List inputParams = Arrays.asList( + sessionVo.clientPort, + positionVo.func, + positionVo.linenumber + ); + try (PreparedStatement ps = clientConn.getDebugOptPrepareStatement( + debugOpt, inputParams)) { + try (ResultSet rs = ps.executeQuery()) { + boolean result = false; + if (rs.next()) { + result = rs.getBoolean(1); + } + return result; + } + } + } + + /** + * set server connection + * + * @param serverConn connection to set of server + * @return void + */ + public void setServerConn(IConnection serverConn) { + this.serverConn = serverConn; + this.serverConn.setNoticeListener(this); + } + + /** + * set client connection + * + * @param clientConn connection + * @return void + */ + public void setClientConn(IConnection clientConn) { + this.clientConn = clientConn; + this.clientConn.setNoticeListener(this); + } + + /** + * close all connection + * + * @return void + */ + @Override + public void closeService() { + eventQueueThread.stopThread(); + try { + if (clientConn != null) { + clientConn.close(); + clientConn = null; + } + } catch (SQLException sqlErr) { + MPPDBIDELoggerUtility.warn("clientConn close failed!err=" + sqlErr.toString()); + } + + try { + if (serverConn != null) { + serverConn.close(); + serverConn = null; + } + } catch (SQLException sqlErr) { + MPPDBIDELoggerUtility.warn("serverConn close failed, err=" + sqlErr.toString()); + } + } + + /** + * dispose sql warning of notice + * + * @param notice the notice + * @return void + */ + @Override + public void noticeReceived(SQLWarning notice) { + if (notice == null || notice.getMessage() == null) { + return; + } + String msgString = notice.getMessage(); + MPPDBIDELoggerUtility.debug("sql message:" + msgString); + msgChainHelper.handleSqlMsg(new Event(EventMessage.ON_SQL_MSG, msgString)); + } + + /** + * handle event + * + * @param event event to handle + * @return void + */ + @Override + public void handleEvent(Event event) { + msgChainHelper.handleEventMsg(event); + } + + /** + * update server port + * + * @param serverPort the port to set + * @return void + */ + public void updateServerPort(int serverPort) { + sessionVo.serverPort = serverPort; + serverState.running(); + synchronized (waitLock) { + waitLock.notifyAll(); + } + } + + /** + * update server state with exception + * + * @return void + */ + public void updateServerWithException() { + serverState.terminaled(); + } + + /** + * update server state with normal exit + * + * @param result the execute result + * @return void + */ + public void updateServerWithResult(Object result) { + serverState.stop(); + serverState.stateLocked(); + sessionVo.result = result; + serverThreadProxy.start(); + } + + @Override + public Optional version() throws SQLException { + try (PreparedStatement ps = serverConn.getDebugOptPrepareStatement( + DebugConstants.DebugOpt.DEBUG_VERSION, new ArrayList<>(1))) { + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + return Optional.ofNullable(ParseVo.parse(rs, VersionVo.class)); + } + return Optional.empty(); + } + } + } + + /** + * begin debug + * + * @param args function input args + * @return void + * @throws SQLException sql exception + */ + @Override + public void begin(List args) throws SQLException { + init(); + prepareDebug(); + startDebug(args); + attachDebug(); + } + + /** + * end debug + * + * @return void + */ + @Override + public void end() { + try { + abortDebug(); + } catch (SQLException e) { + MPPDBIDELoggerUtility.debug("abortDebug with error:" + e.toString()); + } + serverThreadProxy.join(); + try { + debugOff(); + } catch (SQLException e) { + MPPDBIDELoggerUtility.debug("debugOff with error:" + e.toString()); + } + closeService(); + } + + /** + * get normal end result + * + * @return Optional the result + */ + @Override + public Optional getResult() { + if (isNormalEnd()) { + return Optional.ofNullable(sessionVo.result); + } + return Optional.empty(); + } + + /** + * is normal end + * + * @return true if normal end + */ + @Override + public boolean isNormalEnd() { + return serverState.isNormalStopped(); + } + + /** + * is debug server still running + * + * @return true if running + */ + @Override + public boolean isRunning() { + return getServerDebugState().isRunning(); + } + + /** + * set function vo + * + * @param functionVo function vo + * @return void + */ + public void setFunctionVo(FunctionVo functionVo) { + this.functionVo = functionVo; + } + + /** + * get server state + * + * @return DebugState state of server + */ + public DebugState getServerDebugState() { + return serverState; + } + + /** + * get server state + * + * @return DebugState state of client + */ + public DebugState getClientDebugState() { + return clientState; + } + + /** + * add server debug exit listener + * + * @param handler event handler of exit + * @return void + */ + @Override + public void addServerExistListener(EventHander handler) { + eventQueueThread.addHandler(handler); + } + + @Override + public void init() { + if (eventQueueThread.getState() == State.NEW) { + eventQueueThread.start(); + } + } + + @Override + public boolean isRollback() { + return isRollback; + } + + @Override + public void setRollback(boolean isRollback) { + this.isRollback = isRollback; + } + + private void serverCallBackBegin() throws SQLException { + serverExecuteInner("begin;"); + } + + private void serverCallBackEnd() throws SQLException { + if (isRollback()) { + serverExecuteInner("rollback;"); + } else { + serverExecuteInner("commit;"); + } + } + + private void serverExecuteInner(String sql) throws SQLException { + try (PreparedStatement ps = serverConn.getStatement(sql)) { + ps.execute(); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/IDebugService.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/IDebugService.java new file mode 100644 index 0000000000000000000000000000000000000000..6ddb1c65120fa61d76d57e4bd75e943476a34c2b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/IDebugService.java @@ -0,0 +1,197 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.service; + +import java.sql.SQLException; +import java.util.List; +import java.util.Optional; + +import org.opengauss.mppdbide.debuger.debug.DebugConstants.DebugOpt; +import org.opengauss.mppdbide.debuger.event.EventHander; +import org.opengauss.mppdbide.debuger.exception.DebugExitException; +import org.opengauss.mppdbide.debuger.vo.PositionVo; +import org.opengauss.mppdbide.debuger.vo.StackVo; +import org.opengauss.mppdbide.debuger.vo.VariableVo; +import org.opengauss.mppdbide.debuger.vo.VersionVo; + +/** + * Title: IDebugService for use + * + * @since 3.0.0 + */ +public interface IDebugService extends IService { + /** + * get version of debug, if any error or null mains not support debug + * + * @return Optional the version vo + * @throws SQLException sql error + */ + Optional version() throws SQLException; + + /** + * begin debug + * + * @param args function input args + * @return void + * @throws SQLException sql exception + */ + void begin(List args) throws SQLException; + + /** + * end debug + * + * @return void + */ + void end(); + + /** + * init debug + * + * @return void + */ + void init(); + + /** + * description: is need roll back + * + * @return boolean true if need roll back + */ + boolean isRollback(); + + /** + * description: set roll back flag + * + * @param isRollback true if need roll back + */ + void setRollback(boolean isRollback); + + /** + * step into run + * + * @return Optional the breakpoint line position + * @throws SQLException the exp + * @throws DebugExitException the debug exit exp + */ + Optional stepInto() throws SQLException, DebugExitException; + + /** + * step over run + * + * @return Optional the breakpoint line position + * @throws SQLException the exp + * @throws DebugExitException the debug exit exp + */ + Optional stepOver() throws SQLException, DebugExitException; + + /** + * step out run + * + * @return Optional the breakpoint line position + * @throws SQLException the exp + * @throws DebugExitException the debug exit exp + */ + Optional stepOut() throws SQLException, DebugExitException; + + /** + * continue exec run + * + * @return Optional the breakpoint line position + * @throws SQLException the exp + * @throws DebugExitException the debug exit exp + */ + Optional continueExec() throws SQLException, DebugExitException; + + /** + * step run common command + * + * @param debugOpt which opteration to exec + * @return Optional the breakpoint line position + * @throws SQLException the exp + * @throws DebugExitException the debug exit exp + */ + Optional getPositionVo(DebugOpt debugOpt) throws SQLException, DebugExitException; + + /** + * get cur variables + * + * @return List all variables + * @throws SQLException the exp + */ + List getVariables() throws SQLException; + + /** + * get cur stacks + * + * @return List all stacks + * @throws SQLException the exp + */ + List getStacks() throws SQLException; + + /** + * get cur breakpoints + * + * @return List all breakpoints + * @throws SQLException the exp + */ + List getBreakPoints() throws SQLException; + + /** + * set breakpoint + * + * @param positionVo which line will set breakpoint + * @return boolean true if success + * @throws SQLException the exp + */ + boolean setBreakPoint(PositionVo positionVo) throws SQLException; + + /** + * delete breakpoint + * + * @param positionVo which line will set breakpoint + * @return boolean true if success + * @throws SQLException the exp + */ + boolean dropBreakPoint(PositionVo positionVo) throws SQLException; + + /** + * add server debug exit listener + * + * @param handler event handler of exit + * @return void + */ + void addServerExistListener(EventHander handler); + + /** + * get normal end result + * + * @return Optional the result + */ + Optional getResult(); + + /** + * is normal end + * + * @return true if normal end + */ + boolean isNormalEnd(); + + /** + * is debug server still running + * + * @return true if running + */ + boolean isRunning(); +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/IService.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/IService.java new file mode 100644 index 0000000000000000000000000000000000000000..aade20933a8bf8d3f96143af708a6747837d8e83 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/IService.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.service; + +/** + * Title: the IService interface + * + * @since 3.0.0 + */ +public interface IService { + void closeService(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/QueryService.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/QueryService.java new file mode 100644 index 0000000000000000000000000000000000000000..810bbf6cb0ff23720519ec040545df368afa1b63 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/QueryService.java @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.service; + +import org.opengauss.mppdbide.debuger.dao.FunctionDao; +import org.opengauss.mppdbide.debuger.annotation.ParseVo; +import org.opengauss.mppdbide.debuger.debug.DebugConstants; +import org.opengauss.mppdbide.debuger.vo.FunctionVo; +import org.opengauss.mppdbide.debuger.vo.SourceCodeVo; +import org.opengauss.mppdbide.debuger.vo.TotalSourceCodeVo; +import org.opengauss.mppdbide.common.IConnection; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** + * Title: the QueryService class + * + * @since 3.0.0 + */ +public class QueryService implements IService { + private IConnection conn = null; + private FunctionDao functionDao = null; + + /** + * query function vo + * + * @param proname the debug function name + * @return FunctionVo the function vo + * @throws SQLException sql exp + */ + public FunctionVo queryFunction(String proname) throws SQLException { + try (PreparedStatement ps = conn.getStatement(functionDao.getSql(proname))) { + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + return functionDao.parse(rs); + } + throw new SQLException("proname:" + proname + " not found!"); + } + } + } + + /** + * get base source code + * + * @param oid function oid + * @return Optional the source code + * @throws SQLException sql exp + */ + public Optional getSourceCode(Long oid) throws SQLException { + return getTempSourceCode(oid, + DebugConstants.DebugOpt.GET_SOURCE_CODE, + SourceCodeVo.class); + } + + /** + * get sourceCode source code + * + * @param oid function oid + * @return Optional the source code + * @throws SQLException sql exp + */ + public Optional getTotalSourceCode(Long oid) throws SQLException { + return getTempSourceCode(oid, + DebugConstants.DebugOpt.GET_TOTAL_SOURCE_CODE, + TotalSourceCodeVo.class); + } + + private Optional getTempSourceCode( + Long oid, + DebugConstants.DebugOpt debugOpt, + Class clazz) throws SQLException { + List inputParams = Arrays.asList(oid); + try (PreparedStatement ps = conn.getDebugOptPrepareStatement( + debugOpt, inputParams)) { + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + return Optional.of(ParseVo.parse(rs, clazz)); + } + return Optional.empty(); + } + } + } + + /** + * set conn + * + * @param conn connection + * @return void + */ + public void setConn(IConnection conn) { + this.conn = conn; + } + + /** + * get conn + * + * @return IConnection the connection + */ + public IConnection getConn() { + return this.conn; + } + + /** + * set function dao + * + * @param dao set function dao + * @return void + */ + public void setFunctionDao(FunctionDao dao) { + this.functionDao = dao; + } + + /** + * get function dao + * + * @return FunctionDao get function dao + */ + public FunctionDao getFunctionDao() { + return this.functionDao; + } + + /** + * close service + * + * @return void + */ + @Override + public void closeService() { + try { + if (this.conn != null) { + this.conn.close(); + this.conn = null; + } + } catch (SQLException e) { + MPPDBIDELoggerUtility.warn("close conn with err:" + e.toString()); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/ServiceFactory.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/ServiceFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..f6f19ba1d5b6319749e7185251d2b8603a785837 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/ServiceFactory.java @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.service; + +import org.opengauss.mppdbide.debuger.annotation.ParseVo; +import org.opengauss.mppdbide.debuger.dao.FunctionDao; +import org.opengauss.mppdbide.debuger.debug.DebugConstants; +import org.opengauss.mppdbide.debuger.vo.FunctionVo; +import org.opengauss.mppdbide.common.IConnection; +import org.opengauss.mppdbide.common.IConnectionProvider; +import org.opengauss.mppdbide.debuger.vo.VersionVo; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.NoSuchElementException; +import java.util.Optional; + +/** + * Title: the ServiceFactory class + * + * @since 3.0.0 + */ +public class ServiceFactory { + private IConnectionProvider provider; + + public ServiceFactory(IConnectionProvider provider) { + this.provider = provider; + } + + /** + * description: get query service + * + * @return QueryService the query service + * @throws SQLException the sql exception + */ + public QueryService getQueryService() throws SQLException { + return createQueryService(provider.getValidFreeConnection()); + } + + /** + * description: get debug service + * + * @param functionVo the functionVo + * @return DebugService debug service + * @throws SQLException the null connection sqlexception + */ + public DebugService getDebugService(FunctionVo functionVo) throws SQLException { + return createDebugService(functionVo, + provider.getValidFreeConnection(), + provider.getValidFreeConnection()); + } + + /** + * judge is support debug + * + * @return boolean true if support + */ + public boolean isSupportDebug() { + try { + return getVersion().isPresent(); + } catch (SQLException | NoSuchElementException notSupportExp) { + return false; + } + } + + /** + * get version of server + * + * @return Optional the version vo + * @throws SQLException sql error + */ + public Optional getVersion() throws SQLException { + IConnection conn = provider.getValidFreeConnection(); + try (PreparedStatement ps = conn.getDebugOptPrepareStatement( + DebugConstants.DebugOpt.DEBUG_VERSION, + new ArrayList<>(1))) { + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + return Optional.ofNullable(ParseVo.parse(rs, VersionVo.class)); + } + return Optional.empty(); + } + } finally { + try { + conn.close(); + } catch (SQLException sqlExp) { + MPPDBIDELoggerUtility.warn("get version with err=" + sqlExp.getMessage()); + } + } + } + + /** + * description: get code service + * + * @return SourceCodeService the code service + */ + public SourceCodeService getCodeService() { + return new SourceCodeService(); + } + + private static DebugService createDebugService( + FunctionVo functionVo, + IConnection serverConn, + IConnection clientConn) { + DebugService debugService = new DebugService(); + debugService.setFunctionVo(functionVo); + debugService.setServerConn(serverConn); + debugService.setClientConn(clientConn); + return debugService; + } + + private static QueryService createQueryService(IConnection conn) { + QueryService queryService = new QueryService(); + queryService.setFunctionDao(new FunctionDao()); + queryService.setConn(conn); + return queryService; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/SourceCodeService.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/SourceCodeService.java new file mode 100644 index 0000000000000000000000000000000000000000..717547e4bf1f928f963032c1c1982c93d4adecc0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/SourceCodeService.java @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.service; + +import org.opengauss.mppdbide.debuger.exception.DebugPositionNotFoundException; + +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; + +/** + * Title: the SourceCodeService class + * + * @since 3.0.0 + */ +public class SourceCodeService implements IService { + /** + * the offset of show code and base code + */ + public static final int CODE_BASE_OFFSET = 1; + private CodeDescription baseCodeDesc = null; + private CodeDescription totalCodeDesc = null; + + /** + * close service + * + * @return void + */ + @Override + public void closeService() { + } + + /** + * set base code + * + * @param the base code + * @return void + */ + public void setBaseCode(String code) { + this.baseCodeDesc = new CodeDescription(code); + } + + /** + * set total code + * + * @param the total code + * @return void + */ + public void setTotalCode(String code) { + this.totalCodeDesc = new CodeDescription(code); + } + + /** + * showline convert to codeline + * + * @param showLine the show line + * @return int return converted result line + * @throws DebugPositionNotFoundException debug position exp + */ + public int showLine2CodeLine(int showLine) throws DebugPositionNotFoundException { + return showLine - getBeginTotalAndBaseDiff() + CODE_BASE_OFFSET; + } + + /** + * codeline convert to showline + * + * @param codeLine the code line + * @return int return converted result line + * @throws DebugPositionNotFoundException debug position exp + */ + public int codeLine2ShowLine(int codeLine) throws DebugPositionNotFoundException { + return codeLine + getBeginTotalAndBaseDiff() - CODE_BASE_OFFSET; + } + + /** + * get begin debug line number + * + * @return int return begin debug line number in code line + * @throws DebugPositionNotFoundException debug position exp + */ + public int getBeginDebugCodeLine() throws DebugPositionNotFoundException { + return getFirstValidDebugPos() + getBeginTotalAndBaseDiff(); + } + + /** + * get base code begin line position + * + * @return int return begin debug line number in code line + * @throws DebugPositionNotFoundException debug position exp + */ + public int getFirstValidDebugPos() throws DebugPositionNotFoundException { + // BEGIN line is not a valid debug pos, so add 1 + // out code line base on 0, but breakpoint base on 1, so add 1 + // next BEGIN line is default attach breakpoint, so add 1, total pos need add 3! + return getBeignOfBaseCode() + CODE_BASE_OFFSET; + } + + /** + * get max code line pos + * + * @return int return max debug line number in code line + */ + public int getMaxValidDebugPos() { + return this.baseCodeDesc.getMaxPostion(); + } + + /** + * get base code desc + * + * @return CodeDescription code desc + */ + public CodeDescription getBaseCodeDesc() { + return this.baseCodeDesc; + } + + /** + * get total code desc + * + * @return CodeDescription code desc + */ + public CodeDescription getTotalCodeDesc() { + return this.totalCodeDesc; + } + + /** + * get total and base diff line + * + * @return int the diff line + * @throws DebugPositionNotFoundException not found exp + */ + public int getBeginTotalAndBaseDiff() throws DebugPositionNotFoundException { + return getBeignfTotalCode() - getBeignOfBaseCode(); + } + + /** + * get base code being pos + * + * @return int the begin line + * @throws DebugPositionNotFoundException not found exp + */ + public int getBeignOfBaseCode() throws DebugPositionNotFoundException { + return this.baseCodeDesc.getBeginPosition(); + } + + /** + * get total code being pos + * + * @return int the begin line + * @throws DebugPositionNotFoundException not found exp + */ + public int getBeignfTotalCode() throws DebugPositionNotFoundException { + return this.totalCodeDesc.getBeginPosition(); + } + + /** + * Title: CodeDescription class + */ + public static class CodeDescription { + /** + * invalid position + */ + public static final int INVALID_POSITION = -1; + private String code; + private List codeList; + private int beginPosition = INVALID_POSITION; + + public CodeDescription(String code) { + this.code = code; + this.codeList = getLines(this.code); + this.beginPosition = getBeginFromCode(this.codeList); + } + + /** + * get the begin line + * + * @return int the begin line + * @throws DebugPositionNotFoundException the not found exp + */ + public int getBeginPosition() throws DebugPositionNotFoundException { + if (beginPosition == INVALID_POSITION) { + throw new DebugPositionNotFoundException(); + } + return beginPosition; + } + + /** + * get max code line + * + * @return int the max line + */ + public int getMaxPostion() { + return this.codeList.size(); + } + + /** + * get special line code + * + * @param idx code line + * @return String the code + */ + public String getCodeByIndex(int idx) { + return this.codeList.get(idx); + } + + /** + * code to mutil line + * + * @param srcCode source code + * @return List the list of code + */ + public static List getLines(String srcCode) { + return Arrays.stream(srcCode.split("[\\n]")).collect(Collectors.toList()); + } + + private int getBeginFromCode(List lines) { + for (int i = 0; i < lines.size(); i ++) { + if (lines.get(i).toUpperCase(Locale.ENGLISH).startsWith("BEGIN")) { + return i; + } + } + return INVALID_POSITION; + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/WrappedDebugService.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/WrappedDebugService.java new file mode 100644 index 0000000000000000000000000000000000000000..0399a8f1357e240dc51f12d7b224ba9ee6eaf87f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/WrappedDebugService.java @@ -0,0 +1,317 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.service; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.opengauss.mppdbide.debuger.debug.DebugConstants.DebugOpt; +import org.opengauss.mppdbide.debuger.event.DebugAddtionMsg; +import org.opengauss.mppdbide.debuger.event.DebugAddtionMsg.State; +import org.opengauss.mppdbide.debuger.event.Event; +import org.opengauss.mppdbide.debuger.event.EventHander; +import org.opengauss.mppdbide.debuger.event.IHandlerManger; +import org.opengauss.mppdbide.debuger.exception.DebugExitException; +import org.opengauss.mppdbide.debuger.vo.PositionVo; +import org.opengauss.mppdbide.debuger.vo.StackVo; +import org.opengauss.mppdbide.debuger.vo.VariableVo; +import org.opengauss.mppdbide.debuger.vo.VersionVo; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +import org.opengauss.mppdbide.debuger.event.Event.EventMessage; + +/** + * Title: WrappedDebugService for use + * + * @since 3.0.0 + */ +public class WrappedDebugService implements IDebugService, IHandlerManger { + private static final int DEFALUT_HANDER_SIZE = 10; + private List eventHandlers = new ArrayList(DEFALUT_HANDER_SIZE); + private DebugService debugService; + + public WrappedDebugService(DebugService debugService) { + this.debugService = debugService; + } + + @Override + public Optional version() throws SQLException { + return debugService.version(); + } + + /** + * begin debug + * + * @param args function input args + * @return void + * @throws SQLException sql exception + */ + @Override + public void begin(List args) throws SQLException { + try { + new EventRunner(this, args, EventMessage.DEBUG_BEGIN) { + @Override + protected void innertRun() throws SQLException { + Object inputArgs = this.args; + if (inputArgs instanceof List) { + List beginParams = (List) inputArgs; + debugService.begin(beginParams); + } + } + }.run(); + } catch (DebugExitException e) { + MPPDBIDELoggerUtility.error("begin can\'t run here!!"); + } + } + + @Override + public Optional stepOver() throws SQLException, DebugExitException { + return runDebugRunStep(DebugOpt.STEP_OVER); + } + + @Override + public Optional stepInto() throws SQLException, DebugExitException { + return runDebugRunStep(DebugOpt.STEP_INTO); + } + + @Override + public Optional continueExec() throws SQLException, DebugExitException { + return runDebugRunStep(DebugOpt.CONTINUE_EXEC); + } + + @Override + public Optional stepOut() throws SQLException, DebugExitException { + return runDebugRunStep(DebugOpt.STEP_OUT); + } + + /** + * step run debug step + * + * @param debugOpt which debug opt to run + * @return Optional the breakpoint line position + * @throws SQLException the exp + * @throws DebugExitException the debug exit exp + */ + public Optional runDebugRunStep(DebugOpt debugOpt) throws SQLException, DebugExitException { + EventRunner runner = new EventRunner(this, debugOpt, EventMessage.DEBUG_RUN) { + @Override + protected void innertRun() throws SQLException, DebugExitException { + if (args instanceof DebugOpt) { + positionVo = debugService.getPositionVo((DebugOpt) args).orElse(null); + } + } + }; + runner.run(); + return Optional.ofNullable(runner.getPositionVo()); + } + + @Override + public void notifyAllHandler(Event event) { + for (EventHander hander: eventHandlers) { + hander.handleEvent(event); + } + } + + @Override + public void addHandler(EventHander handler) { + if (!eventHandlers.contains(handler)) { + eventHandlers.add(handler); + } + addServerExistListener(handler); + } + + @Override + public void removeHandler(EventHander handler) { + eventHandlers.remove(handler); + } + + + @Override + public void removeAllHandler() { + eventHandlers.clear(); + } + + @Override + public void closeService() { + debugService.closeService(); + } + + @Override + public void end() { + try { + new EventRunner(this, null, EventMessage.DEBUG_END) { + @Override + protected void innertRun() throws SQLException, DebugExitException { + debugService.end(); + } + }.run(); + } catch (SQLException | DebugExitException sqlExp) { + MPPDBIDELoggerUtility.error("can\'t run here!"); + } + } + + @Override + public Optional getPositionVo(DebugOpt debugOpt) + throws SQLException, DebugExitException { + return debugService.getPositionVo(debugOpt); + } + + @Override + public List getVariables() throws SQLException { + return debugService.getVariables(); + } + + + @Override + public List getStacks() throws SQLException { + return debugService.getStacks(); + } + + + @Override + public List getBreakPoints() throws SQLException { + return debugService.getBreakPoints(); + } + + + @Override + public boolean setBreakPoint(PositionVo positionVo) throws SQLException { + return debugService.setBreakPoint(positionVo); + } + + + @Override + public boolean dropBreakPoint(PositionVo positionVo) throws SQLException { + return debugService.dropBreakPoint(positionVo); + } + + + @Override + public Optional getResult() { + return debugService.getResult(); + } + + + @Override + public boolean isNormalEnd() { + return debugService.isNormalEnd(); + } + + @Override + public boolean isRunning() { + return debugService.isRunning(); + } + + @Override + public void addServerExistListener(EventHander handler) { + debugService.addServerExistListener(handler); + } + + /** + * + * Title: EventRunner for use + */ + public abstract static class EventRunner { + /** + * the wrapped debug service + */ + protected WrappedDebugService service; + + /** + * the start debug args + */ + protected Object args; + + /** + * the event msg to send + */ + protected EventMessage msg; + + /** + * result of debug breakpoint position + */ + protected PositionVo positionVo = null; + + public EventRunner(WrappedDebugService service, Object args, EventMessage msg) { + this.service = service; + this.args = args; + this.msg = msg; + } + + /** + * inner run of debug step + * + * @return void + * @throws SQLException the exp + * @throws DebugExitException the debug exit exp + */ + protected abstract void innertRun() throws SQLException, DebugExitException; + + /** + * get result of position + * + * @return PositionVo the debug position + */ + public PositionVo getPositionVo() { + return positionVo; + } + + /** + * run of debug step ,and send event + * + * @return void + * @throws SQLException the exp + * @throws DebugExitException the debug exit exp + */ + public void run() throws SQLException, DebugExitException { + Event beginEvent = new Event(msg, new DebugAddtionMsg(State.START)); + Exception runException = null; + try { + service.notifyAllHandler(beginEvent); + innertRun(); + } catch (SQLException | DebugExitException debugExp) { + runException = debugExp; + throw debugExp; + } finally { + service.notifyAllHandler( + new Event( + msg, + new DebugAddtionMsg(State.END, positionVo), + runException, + beginEvent.getId() + ) + ); + } + } + } + + @Override + public void init() { + debugService.init(); + } + + @Override + public boolean isRollback() { + return debugService.isRollback(); + } + + @Override + public void setRollback(boolean isRollback) { + debugService.setRollback(isRollback); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/chain/IMsgChain.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/chain/IMsgChain.java new file mode 100644 index 0000000000000000000000000000000000000000..48a997693445c2aa63a3f8ea40cf2dc1bd123d7c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/chain/IMsgChain.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.service.chain; + +import org.opengauss.mppdbide.debuger.event.Event; + +/** + * Title: IMsgChain for use + * Description: IMsgChain is base chain of Responsibility + * + * @since 3.0.0 + */ +public abstract class IMsgChain { + /** + * next chain + */ + protected IMsgChain msgChain = null; + + /** + * get next chain + * + * @return IMsgChain get next chain + */ + public IMsgChain getNext() { + return this.msgChain; + } + + /** + * set next chain + * + * @param msgChain next chain to set + * @return void no return value + */ + public void setNext(IMsgChain msgChain) { + this.msgChain = msgChain; + } + + /** + * if event matched, than this chain will dispose it + * + * @param event event to dispose + * @return boolean true if matched + */ + public abstract boolean matchMsg(Event event); + + /** + * dispose Event msg + * + * @param event event to dispose + * @return void + */ + protected abstract void disposeMsg(Event event); + + /** + * handleMsg by chain + * + * @param event event to dispose + * @return void + */ + public void handleMsg(Event event) { + if (matchMsg(event)) { + disposeMsg(event); + } else { + if (getNext() != null) { + getNext().handleMsg(event); + } + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/chain/MsgChainHelper.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/chain/MsgChainHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..11a789793df95a951af23538eacffd0acab9bf98 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/chain/MsgChainHelper.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.service.chain; + +import org.opengauss.mppdbide.debuger.event.Event; +import org.opengauss.mppdbide.debuger.service.DebugService; + +/** + * Title: MsgChainHelper for use + * Description: MsgChainHelper is a better way to use default chain + * + * @since 3.0.0 + */ +public class MsgChainHelper { + private IMsgChain sqlMsgChain = null; + private IMsgChain eventChain = null; + + public MsgChainHelper(DebugService debugService) { + sqlMsgChain = new PrepareMsgChian(debugService); + sqlMsgChain.setNext(new ServerPortMsgChain(debugService)); + + eventChain = new ServerExitEventChain(debugService); + } + + /** + * description: handle sql msg + * + * @param event event of reveive from sql + * @return void + */ + public void handleSqlMsg(Event event) { + sqlMsgChain.handleMsg(event); + } + + /** + * description: handle event msg + * + * @param event event of reveive from notify handler manager + * @return void + */ + public void handleEventMsg(Event event) { + eventChain.handleMsg(event); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/chain/PrepareMsgChian.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/chain/PrepareMsgChian.java new file mode 100644 index 0000000000000000000000000000000000000000..96797eacef9ea749eacfcf365b8e987e1da966a9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/chain/PrepareMsgChian.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.service.chain; + +import org.opengauss.mppdbide.debuger.event.Event; +import org.opengauss.mppdbide.debuger.event.Event.EventMessage; +import org.opengauss.mppdbide.debuger.service.DebugService; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: PrepareMsgChian + * Description: PrepareMsgChian to instance IMsgChain and deal with ON_SQL_MSG + * + * @since 3.0.0 + */ +public class PrepareMsgChian extends IMsgChain { + /** + * msg to match + */ + public static final String PREPARE_SUCCESS = "Pldebugger is started successfully, you are"; + private DebugService debugService; + + public PrepareMsgChian(DebugService debugService) { + super(); + this.debugService = debugService; + } + + @Override + public boolean matchMsg(Event event) { + if (event.getMsg() == EventMessage.ON_SQL_MSG + && event.getStringAddition().contains(PREPARE_SUCCESS)) { + return true; + } + return false; + } + + @Override + public void disposeMsg(Event event) { + String msg = event.getStringAddition(); + if (msg.contains("SERVER")) { + debugService.getServerDebugState().prepared(); + } else if (msg.contains("CLIENT")) { + debugService.getClientDebugState().prepared(); + } else { + MPPDBIDELoggerUtility.debug("can\'t run here!"); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/chain/ServerExitEventChain.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/chain/ServerExitEventChain.java new file mode 100644 index 0000000000000000000000000000000000000000..0c25aaaeda5576085eb1b92f8d11304f0e5a14cf --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/chain/ServerExitEventChain.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.service.chain; + +import org.opengauss.mppdbide.debuger.event.Event; +import org.opengauss.mppdbide.debuger.event.Event.EventMessage; +import org.opengauss.mppdbide.debuger.service.DebugService; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: ServerExitEventChain for use + * + * @since 3.0.0 + */ +public class ServerExitEventChain extends IMsgChain { + private DebugService debugService; + + public ServerExitEventChain(DebugService debugService) { + super(); + this.debugService = debugService; + } + + @Override + public boolean matchMsg(Event event) { + return event.getMsg() == EventMessage.ON_EXIT; + } + + @Override + protected void disposeMsg(Event event) { + if (event.hasException()) { + MPPDBIDELoggerUtility.debug("server exited with exception:" + event.getException().getMessage()); + debugService.updateServerWithException(); + } else { + MPPDBIDELoggerUtility.debug("server exited normal, result = " + event.getAddition().orElse("")); + debugService.updateServerWithResult(event.getAddition().orElse("")); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/chain/ServerPortMsgChain.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/chain/ServerPortMsgChain.java new file mode 100644 index 0000000000000000000000000000000000000000..5b6ad341adc50e922153a5caba4dbf47ee142348 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/service/chain/ServerPortMsgChain.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.service.chain; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.opengauss.mppdbide.debuger.event.Event; +import org.opengauss.mppdbide.debuger.event.Event.EventMessage; +import org.opengauss.mppdbide.debuger.service.DebugService; + +/** + * Title: ServerPortMsgChain for use + * + * @since 3.0.0 + */ +public class ServerPortMsgChain extends IMsgChain { + /** + * msg to matched + */ + public static final String SERVER_PORT_MATCH = "YOUR PROXY PORT ID IS:"; + private DebugService debugService; + + public ServerPortMsgChain(DebugService debugService) { + super(); + this.debugService = debugService; + } + + @Override + public boolean matchMsg(Event event) { + if (event.getMsg() == EventMessage.ON_SQL_MSG + && event.getStringAddition().contains(SERVER_PORT_MATCH)) { + return true; + } + return false; + } + + @Override + protected void disposeMsg(Event event) { + String msg = event.getStringAddition(); + Matcher matcher = Pattern.compile(SERVER_PORT_MATCH + "(\\d+)").matcher(msg); + if (matcher.find()) { + debugService.updateServerPort(Integer.parseInt(matcher.group(1).trim())); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/thread/DebugServerRunable.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/thread/DebugServerRunable.java new file mode 100644 index 0000000000000000000000000000000000000000..fb11e59663e520ad7c7633aaed40d8a9b5c30693 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/thread/DebugServerRunable.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.thread; + +import org.opengauss.mppdbide.debuger.event.Event; +import org.opengauss.mppdbide.debuger.service.DebugService; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +import java.sql.SQLException; +import java.util.List; +import java.util.Optional; + +/** + * Title: the DebugServerRunable class + * + * @since 3.0.0 + */ +public class DebugServerRunable implements Runnable { + private DebugService debugService; + private List debugParams; + private EventQueueThread eventQueueThread; + + public DebugServerRunable(DebugService debugService, List params, EventQueueThread eventQueueThread) { + this.debugService = debugService; + this.debugParams = params; + this.eventQueueThread = eventQueueThread; + } + + @Override + public void run() { + Event event; + Object retValue = null; + Exception exp = null; + try { + Optional optionalObj = debugService.serverDebugCallBack(debugParams); + retValue = optionalObj.orElse(null); + } catch (SQLException sqlExp) { + exp = sqlExp; + } + MPPDBIDELoggerUtility.debug("DebugServerRunable server exit!!!"); + event = new Event(Event.EventMessage.ON_EXIT, retValue, exp); + eventQueueThread.add(event); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/thread/DebugServerThreadProxy.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/thread/DebugServerThreadProxy.java new file mode 100644 index 0000000000000000000000000000000000000000..0b848ac47bf82442468d197e252cd87093d044b7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/thread/DebugServerThreadProxy.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.thread; + +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: the DebugServerThreadProxy class + * + * @since 3.0.0 + */ +public class DebugServerThreadProxy { + private static final int DEFAULT_WAIT_TIME = 2000; // ms + private static final int DEFAULT_WAIT_PER_COUNT = 10; // ms + private static final int DEFAULT_MAX_THREADS = 2; + private int runCount = 1; // the max run count + + private ThreadPoolExecutor executor = new ThreadPoolExecutor( + DEFAULT_MAX_THREADS, + DEFAULT_MAX_THREADS, + 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + private DebugServerRunable debugServerRunable; + + /** + * set which torrun + * + * @param runable the runable + * @return void + */ + public void setDebugServerRunable(DebugServerRunable runable) { + this.debugServerRunable = runable; + } + + /** + * start debug + * + * @return void + */ + public void start() { + if (runCount < 0) { + return; + } + if (isAlive()) { + MPPDBIDELoggerUtility.warn("old thread not exit, please check!"); + return; + } + MPPDBIDELoggerUtility.info("debug server run again!" + runCount); + runCount -= 1; + executor.execute(debugServerRunable); + } + + /** + * is back run alive + * + * @return true if alive + */ + public boolean isAlive() { + if (executor == null) { // this main executor already closed + return true; + } + return executor.getActiveCount() != 0; + } + + /** + * wait back thread exit + * + * @return void + */ + public void join() { + if (this.executor != null) { + this.executor.shutdown(); + boolean shutDownSuccess = waitExecutorShutDown(DEFAULT_WAIT_TIME); + if (!shutDownSuccess) { + MPPDBIDELoggerUtility.warn("executor shutdown failed!"); + } + this.executor = null; + } + } + + private boolean waitExecutorShutDown(int timeout) { + int curWaitTime = 0; + while (curWaitTime < timeout) { + if (this.executor.isShutdown()) { + return true; + } + curWaitTime += DEFAULT_WAIT_PER_COUNT; + try { + Thread.sleep(DEFAULT_WAIT_PER_COUNT); + } catch (InterruptedException e) { + MPPDBIDELoggerUtility.warn("wait executor shutdown have error:" + e.getMessage()); + Thread.currentThread().interrupt(); + } + } + return false; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/thread/EventQueueThread.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/thread/EventQueueThread.java new file mode 100644 index 0000000000000000000000000000000000000000..0c72aa84dd477dab6be1d1d1c89e8c1b2b22469a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/thread/EventQueueThread.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.thread; + +import org.opengauss.mppdbide.debuger.event.Event; +import org.opengauss.mppdbide.debuger.event.EventHander; +import org.opengauss.mppdbide.debuger.event.IHandlerManger; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.LinkedBlockingQueue; + +/** + * Title: the EventQueueThread class + * + * @since 3.0.0 + */ +public class EventQueueThread extends Thread implements IHandlerManger { + private static final int DEFAULT_EVENT_HANDLES = 3; + private static final int DEFAULT_EVENT_SLEEP = 10; + private static final int TIMEOUT_COUNT = 200; + private LinkedBlockingQueue queue = new LinkedBlockingQueue<>(); + private List eventHandlers = new ArrayList(DEFAULT_EVENT_HANDLES); + + @Override + public void run() { + while (true) { + try { + Event event = queue.take(); + if (event.getMsg() == null) { + break; + } + Thread.sleep(DEFAULT_EVENT_SLEEP); + notifyAllHandler(event); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + MPPDBIDELoggerUtility.debug("event queue exit!"); + } + + /** + * add event to queue + * + * @param event event to queue + * @return void + */ + public void add(Event event) { + boolean flag = queue.offer(event); + if (!flag) { + MPPDBIDELoggerUtility.debug("event add failed!"); + } + } + + /** + * exit this thread + * + * @return void + */ + public void stopThread() { + add(new Event(null, null)); + int count = TIMEOUT_COUNT; + while (count > 0) { + if (!isAlive()) { + break; + } + try { + sleep(DEFAULT_EVENT_SLEEP); + } catch (InterruptedException e) { + MPPDBIDELoggerUtility.warn("sleep have error!"); + Thread.currentThread().interrupt(); + } + count -= 1; + } + } + + @Override + public void addHandler(EventHander handler) { + if (!eventHandlers.contains(handler)) { + eventHandlers.add(handler); + } + } + + @Override + public void removeHandler(EventHander handler) { + eventHandlers.remove(handler); + } + + @Override + public void removeAllHandler() { + eventHandlers.clear(); + } + + @Override + public void notifyAllHandler(Event event) { + for (EventHander hander: eventHandlers) { + hander.handleEvent(event); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/BreakpointList.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/BreakpointList.java new file mode 100644 index 0000000000000000000000000000000000000000..294a36e36e938c3eb0b44b8941ff690d7d0d7500 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/BreakpointList.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.vo; + +import java.util.HashMap; +import java.util.Map; + +/** + * Title: class + * Description: The Class BreakpointList. + * + * @since 3.0.0 + */ +public class BreakpointList { + private static Map breakpointList; + + private BreakpointList() { + } + + /** + * Gets the instance of BreakpointList. + * + * @return Map the instance of BreakpointList + */ + public static Map getInstance() { + return breakpointList; + } + + /** + * Initials the instance of BreakpointList. + */ + public static void initialInstance() { + breakpointList = new HashMap(); + } + + /** + * Resets the instance of BreakpointList. + */ + public static void resetInstance() { + breakpointList = null; + } + + /** + * Sets the instance of BreakpointList. + * + * @param breakpoint the breakpoint + */ + public static void setBreakpointList(Map breakpoint) { + breakpointList = breakpoint; + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/BreakpointVo.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/BreakpointVo.java new file mode 100644 index 0000000000000000000000000000000000000000..fb69d65c65a7da436b4c651dbbe55bb2fb245ee4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/BreakpointVo.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.vo; + +/** + * Title: class + * Description: The Class BreakpointVo. + * + * @since 3.0.0 + */ +public class BreakpointVo { + private int lineNum; + private String statement; + private Boolean enable; + + /** + * Instantiates a new breakpoint. + * + * @param lineNum the lineNum + * @param statement the statement + * @param enable the enable + */ + public BreakpointVo(int lineNum, String statement, Boolean enable) { + this.lineNum = lineNum; + this.statement = statement; + this.enable = enable; + } + + /** + * Gets the lineNum. + * + * @return int the lineNum + */ + public int getLineNum() { + return lineNum; + } + + /** + * Sets the lineNum. + * + * @param lineNum the lineNum + */ + public void setLineNum(int lineNum) { + this.lineNum = lineNum; + } + + /** + * Gets the statement. + * + * @return String the statement + */ + public String getStatement() { + return statement; + } + + /** + * Sets the statement. + * + * @param statement the statement + */ + public void setStatement(String statement) { + this.statement = statement; + } + + /** + * Gets the enable. + * + * @return Boolean the enable + */ + public Boolean getEnable() { + return enable; + } + + /** + * Sets the enable. + * + * @param enable the enable + */ + public void setEnable(Boolean enable) { + this.enable = enable; + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/FunctionVo.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/FunctionVo.java new file mode 100644 index 0000000000000000000000000000000000000000..f7c6c953df0ac1f718f386fd7d987e71e2e3912d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/FunctionVo.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.vo; + +import org.opengauss.mppdbide.debuger.annotation.DumpFiled; +import org.postgresql.jdbc.PgArray; +import org.postgresql.util.PGobject; + +/** + * Title: the FunctionVo class + * + * @since 3.0.0 + */ +public class FunctionVo { + /** + * oid of function + */ + @DumpFiled + public Long oid; + + /** + * proname of function + */ + @DumpFiled + public String proname; + + /** + * prorettype of function + */ + @DumpFiled + public Long prorettype; + + /** + * proretset of function + */ + @DumpFiled + public Boolean proretset; + + /** + * pronargs of function + */ + @DumpFiled + public Integer pronargs; + + /** + * pronargdefaults of function + */ + @DumpFiled + public Integer pronargdefaults; + + /** + * proargtypes of function + */ + @DumpFiled + public PGobject proargtypes; + + /** + * proallargtypes of function + */ + @DumpFiled + public PgArray proallargtypes; + + /** + * proargmodes of function + */ + @DumpFiled + public PgArray proargmodes; + + /** + * proargnames of function + */ + @DumpFiled + public PgArray proargnames; + + /** + * proargdefaults of function + */ + @DumpFiled + public PGobject proargdefaults; + + /** + * prodefaultargpos of function + */ + @DumpFiled + public PGobject prodefaultargpos; + + /** + * prosrc of function + */ + @DumpFiled + public String prosrc; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/PositionVo.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/PositionVo.java new file mode 100644 index 0000000000000000000000000000000000000000..7c2250faa006746c8768537df70fe254243d4a4c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/PositionVo.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.vo; + +import org.opengauss.mppdbide.debuger.annotation.DumpFiled; + +import java.util.Locale; + +/** + * Title: the PositionVo class + * + * @since 3.0.0 + */ +public class PositionVo { + /** + * the format of this vo + */ + public static final String FORMAT = "%8s %20s"; + + /** + * func of positionvo + */ + @DumpFiled + public Long func; + + /** + * linenumber of positionvo + */ + @DumpFiled + public Integer linenumber; + + /** + * targetname of positionvo + */ + @DumpFiled + public String targetname; + + public PositionVo() { + this(null, null, null); + } + + public PositionVo(Long func, Integer linenumber, String targetname) { + this.func = func; + this.linenumber = linenumber; + this.targetname = targetname; + } + + /** + * format this vo title + * + * @return String the title + */ + public static String title() { + return String.format(Locale.ENGLISH, FORMAT, "linenum", "funcoid"); + } + + /** + * format self + * + * @return String the self + */ + public String formatSelf() { + return String.format(Locale.ENGLISH, FORMAT, linenumber, func); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/SessionVo.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/SessionVo.java new file mode 100644 index 0000000000000000000000000000000000000000..a8df9fc7d7bb23f23dbe4c5d4531cda466d3f6c9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/SessionVo.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.vo; + +/** + * Title: the SessionIdVo class + * + * @since 3.0.0 + */ +public class SessionVo { + /** + * serverPort for sessionVO + */ + public Integer serverPort; + + /** + * clientPort for sessionVO + */ + public Integer clientPort; + + /** + * result for sessionVO + */ + public Object result; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/SourceCodeVo.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/SourceCodeVo.java new file mode 100644 index 0000000000000000000000000000000000000000..967e572f621cf92a99d731739bb62fa115c59ced --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/SourceCodeVo.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.vo; + +import org.opengauss.mppdbide.debuger.annotation.DumpFiled; + +/** + * Title: the SourceCodeVo class + * + * @since 3.0.0 + */ +public class SourceCodeVo { + /** + * the source code + */ + @DumpFiled + public String pldbg_get_source; + + /** + * get source code + * + * @return String source code + */ + public String getSourceCode() { + return pldbg_get_source; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/StackVo.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/StackVo.java new file mode 100644 index 0000000000000000000000000000000000000000..ca59fe56b14d6af45aba1dedb99a8f544eddf6e5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/StackVo.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.vo; + +import org.opengauss.mppdbide.debuger.annotation.DumpFiled; + +import java.util.Locale; + +/** + * Title: the StackVo class + * + * @since 3.0.0 + */ +public class StackVo { + /** + * level of stack + */ + @DumpFiled + public Integer level; + + /** + * targetname of stack + */ + @DumpFiled + public String targetname; + + /** + * func of stack + */ + @DumpFiled + public Long func; + + /** + * linenumbe of stack + */ + @DumpFiled + public Integer linenumber; + + /** + * args of stack + */ + @DumpFiled + public Object args; + + @Override + public String toString() { + return String.format(Locale.ENGLISH, + "StackVo(level %s : targetname %s)", + level, + targetname); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/TotalSourceCodeVo.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/TotalSourceCodeVo.java new file mode 100644 index 0000000000000000000000000000000000000000..dfe6118103483e5b5fcf677935a532f32929eae4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/TotalSourceCodeVo.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.vo; + +import org.opengauss.mppdbide.debuger.annotation.DumpFiled; + +/** + * Title: the TotalSourceCodeVo class + * + * @since 3.0.0 + */ +public class TotalSourceCodeVo { + /** + * headerlines of total source code + */ + @DumpFiled + public Integer headerlines; + + /** + * definition of total source code + */ + @DumpFiled + public String definition; + + /** + * description: get source code + * + * @return String source code + */ + public String getSourceCode() { + return definition.replaceAll("\\$function\\$", "\\$\\$") + "/"; + } + + /** + * description: get head lines + * + * @return int head lines + */ + public int getHeadlines() { + return headerlines; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/VariableVo.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/VariableVo.java new file mode 100644 index 0000000000000000000000000000000000000000..1e479f92688f7f060d93c8be83bdfad76a6da55f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/VariableVo.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.vo; + +import org.opengauss.mppdbide.debuger.annotation.DumpFiled; + +import java.util.Locale; + +/** + * Title: the VariableVo class + * + * @since 3.0.0 + */ +public class VariableVo { + /** + * name linenumber value dtype isnotnull + */ + public static final String FORMAT = "%40s %6s %20s %6s %7s"; + + /** + * name of variable + */ + @DumpFiled + public String name; + + /** + * var class of variable + */ + @DumpFiled + public String varclass; + + /** + * linenumber of variable + */ + @DumpFiled + public Integer linenumber; + + /** + * is unique of variable + */ + @DumpFiled + public Boolean isunique; + + /** + * is const of variable + */ + @DumpFiled + public Boolean isconst; + + /** + * is not null of variable + */ + @DumpFiled + public Boolean isnotnull; + + /** + * dtype of variable + */ + @DumpFiled + public Long dtype; + + /** + * value of variable + */ + @DumpFiled + public Object value; + + @Override + public String toString() { + return String.format(Locale.ENGLISH, "VariableVo(name %s : value: %s)", name, value); + } + + /** + * description:title of variable + * + * @return String title of variable + */ + public static String title() { + return String.format(Locale.ENGLISH, FORMAT, "name", "line", "value", "type", "isNull"); + } + + /** + * description: format variable self + * + * @return String formated result + */ + public String formatSelf() { + String newName = name.length() > 40 ? name.substring(0, 40) : name; + return String.format(Locale.ENGLISH, FORMAT, newName, linenumber, value, dtype, isnotnull ? "f" : "t"); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/VersionVo.java b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/VersionVo.java new file mode 100644 index 0000000000000000000000000000000000000000..aebe21855b3ceb9a56e44e5fbd28c5bfe0ed3a52 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.debuger/src/org/opengauss/mppdbide/debuger/vo/VersionVo.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.debuger.vo; + +import org.opengauss.mppdbide.debuger.annotation.DumpFiled; + +/** + * Title: VersionVo for use + * + * @since 3.0.0 + */ +public class VersionVo { + /** + * this is version str + */ + @DumpFiled + public String serverversionstr; + + /** + * this is version number + */ + @DumpFiled + public Integer serverversionnum; + + /** + * this is proxy api version + */ + @DumpFiled + public Integer proxyapiver; + + /** + * this is server process id + */ + @DumpFiled + public Long serverprocessid; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.editor.extension/.classpath b/code/datastudio/src/org.opengauss.mppdbide.editor.extension/.classpath new file mode 100644 index 0000000000000000000000000000000000000000..065ac06e197692d54ca4890fd3674df11d41c8c0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.editor.extension/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.editor.extension/.project b/code/datastudio/src/org.opengauss.mppdbide.editor.extension/.project new file mode 100644 index 0000000000000000000000000000000000000000..e3585767f2d9a52d90c52de45f3e159f17bdd5fc --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.editor.extension/.project @@ -0,0 +1,34 @@ + + + org.opengauss.mppdbide.editor.extension + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.editor.extension/META-INF/MANIFEST.MF b/code/datastudio/src/org.opengauss.mppdbide.editor.extension/META-INF/MANIFEST.MF new file mode 100644 index 0000000000000000000000000000000000000000..2432239a6eb4135a3f221d55e4dc3a1ccc8a7147 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.editor.extension/META-INF/MANIFEST.MF @@ -0,0 +1,10 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: ExtensionTwo +Bundle-SymbolicName: org.opengauss.mppdbide.editor.extension +Bundle-Version: 1.0.0.qualifier +Bundle-Vendor: OPENGAUSS +Bundle-RequiredExecutionEnvironment: JavaSE-11 +Require-Bundle: org.opengauss.mppdbide.parser +Export-Package: org.opengauss.mppdbide.editor.extension.nameparser +Import-Package: org.opengauss.mppdbide.utils.logger diff --git a/code/datastudio/src/org.opengauss.mppdbide.editor.extension/build.properties b/code/datastudio/src/org.opengauss.mppdbide.editor.extension/build.properties new file mode 100644 index 0000000000000000000000000000000000000000..34d2e4d2dad529ceaeb953bfcdb63c51d69ffed2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.editor.extension/build.properties @@ -0,0 +1,4 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + . diff --git a/code/datastudio/src/org.opengauss.mppdbide.editor.extension/pom.xml b/code/datastudio/src/org.opengauss.mppdbide.editor.extension/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..2c466a4efe01e06fe825291316272b9aae8bdd2f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.editor.extension/pom.xml @@ -0,0 +1,10 @@ + + 4.0.0 + + org.opengauss.plide.build + GAUSS_MPP_DB_IDE + 1.0.0-SNAPSHOT + + org.opengauss.mppdbide.editor.extension + eclipse-plugin + \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.editor.extension/src/org/opengauss/mppdbide/editor/extension/nameparser/ObjectNameParseErrorListener.java b/code/datastudio/src/org.opengauss.mppdbide.editor.extension/src/org/opengauss/mppdbide/editor/extension/nameparser/ObjectNameParseErrorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..41ff329362022e29402340ddb937f79a6607ae15 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.editor.extension/src/org/opengauss/mppdbide/editor/extension/nameparser/ObjectNameParseErrorListener.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.editor.extension.nameparser; + +import java.util.ArrayList; + +import org.antlr.v4.runtime.BaseErrorListener; +import org.antlr.v4.runtime.NoViableAltException; +import org.antlr.v4.runtime.Parser; +import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.Recognizer; + +/** + * Title: ObjectNameParseErrorListener + * + * Description:The listener interface for receiving objectNameParseError events. + * The class that is interested in processing a objectNameParseError event + * implements this interface, and the object created with that class is + * registered with a component using the component's + * addObjectNameParseErrorListener method. When the + * objectNameParseError event occurs, that object's appropriate method is + * invoked. + * + * @since 3.0.0 + */ +public class ObjectNameParseErrorListener extends BaseErrorListener { + + /** + * The Constant INSTANCE. + */ + public static final ObjectNameParseErrorListener INSTANCE = new ObjectNameParseErrorListener(); + + @Override + public void syntaxError(Recognizer recognier, Object offendingSymbol, int line, int charPositionInLine, + String msg, RecognitionException e) { + if (recognier instanceof Parser) { + Parser parser = (Parser) recognier; + + ParserRuleContext ctx = ((Parser) recognier).getRuleContext(); + ArrayList affectedClauses = new ArrayList(5); + // keep this as the last item + affectedClauses.add("PostgresParser$Simple_selectContext"); + + while (ctx != null) { + String className = ctx.getClass().getName(); + int lastIndexOf = className.lastIndexOf("."); + className = className.substring(lastIndexOf + 1); + + if (affectedClauses.contains(className)) { + break; + } + ctx = ctx.getParent(); + } + + if ((ctx != null) && (ctx.exception == null)) { + NoViableAltException recognitionException = new NoViableAltException(parser, parser.getTokenStream(), + ((Parser) recognier).getCurrentToken(), ((Parser) recognier).getCurrentToken(), null, + parser.getRuleContext()); + ctx.exception = recognitionException; + } + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.editor.extension/src/org/opengauss/mppdbide/editor/extension/nameparser/ParseObjectNameMain.java b/code/datastudio/src/org.opengauss.mppdbide.editor.extension/src/org/opengauss/mppdbide/editor/extension/nameparser/ParseObjectNameMain.java new file mode 100644 index 0000000000000000000000000000000000000000..ddfc44500c01201cf4369f6aea45df02b2c51976 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.editor.extension/src/org/opengauss/mppdbide/editor/extension/nameparser/ParseObjectNameMain.java @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.editor.extension.nameparser; + +import java.util.List; + +import org.antlr.v4.runtime.ANTLRInputStream; +import org.antlr.v4.runtime.CommonTokenStream; +import org.antlr.v4.runtime.tree.ParseTree; +import org.antlr.v4.runtime.tree.ParseTreeWalker; + +import org.opengauss.mppdbide.parser.grammar.PostgresLexer; +import org.opengauss.mppdbide.parser.grammar.PostgresParser; +import org.opengauss.mppdbide.parser.runtimehandler.RuntimeErrorStrategyManager; + +/** + * + * Title: class + * + * Description: The Class ParseObjectNameMain. + * + * @since 3.0.0 + */ +public class ParseObjectNameMain { + ParserObjectNameListener parseListener = new ParserObjectNameListener(); + + /** + * Parsename. + * + * @param sqlquery the sqlquery + */ + public void parsename(String sqlquery) { + if (null != sqlquery) { + ANTLRInputStream input = new ANTLRInputStream(sqlquery); + PostgresLexer lexer = new PostgresLexer(input); + lexer.addErrorListener(ObjectNameParseErrorListener.INSTANCE); + CommonTokenStream tokens = new CommonTokenStream(lexer); + PostgresParser parser = new PostgresParser(tokens); + parser.setErrorHandler(RuntimeErrorStrategyManager.getRuntimeErrorhandler()); + parser.removeErrorListeners(); + parser.addErrorListener(ObjectNameParseErrorListener.INSTANCE); + ParseTree tree = parser.functionStmt(); + ParseTreeWalker walker = new ParseTreeWalker(); + walker.walk(parseListener, tree); + } + } + + /** + * Gets the object type. + * + * @return the object type + */ + public String getObjectType() { + return parseListener.getObjectName()[0]; + } + + /** + * Gets the object name. + * + * @return the object name + */ + public String getObjectName() { + return parseListener.getObjectName()[1]; + } + + /** + * Gets the schema name. + * + * @return the schema name + */ + public String getSchemaName() { + return parseListener.getSchemaName(); + } + + /** + * Gets the func name. + * + * @return the func name + */ + public String getFuncName() { + return parseListener.getFuncName(); + } + + /** + * Gets the args. + * + * @return the args + */ + public List getArgs() { + return parseListener.getArguements(); + } + + /** + * Gets the ret type. + * + * @return the ret type + */ + public String getRetType() { + return parseListener.getreturnType(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.editor.extension/src/org/opengauss/mppdbide/editor/extension/nameparser/ParserObjectNameListener.java b/code/datastudio/src/org.opengauss.mppdbide.editor.extension/src/org/opengauss/mppdbide/editor/extension/nameparser/ParserObjectNameListener.java new file mode 100644 index 0000000000000000000000000000000000000000..e2d9f2f965d7cf1621ee122413f47746d8b93113 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.editor.extension/src/org/opengauss/mppdbide/editor/extension/nameparser/ParserObjectNameListener.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.editor.extension.nameparser; + +import java.util.ArrayList; + +import org.antlr.v4.runtime.ParserRuleContext; + +import org.opengauss.mppdbide.parser.grammar.PostgresParser; +import org.opengauss.mppdbide.parser.grammar.PostgresParserBaseListener; + +/** + * Title: ParserObjectNameListener + * + * Description:The listener interface for receiving parserObjectName events. The + * class that is interested in processing a parserObjectName event implements + * this interface, and the object created with that class is registered with a + * component using the component's addParserObjectNameListener + * method. When the parserObjectName event occurs, that object's appropriate + * method is invoked. + * + * @since 3.0.0 + */ +public class ParserObjectNameListener extends PostgresParserBaseListener { + private String objectType; + private String objectName; + private String schemaName; + private String funcName; + private ArrayList args = new ArrayList(5); + private String objReturnType; + + @Override + public void enterFunction_type(PostgresParser.Function_typeContext ctx) { + objectType = ctx.getText(); + } + + @Override + public void enterFunction_name(PostgresParser.Function_nameContext ctx) { + objectName = ctx.getText(); + } + + @Override + public void enterFunction_aguments(PostgresParser.Function_agumentsContext ctx) { + + } + + @Override + public void enterSchema_name(PostgresParser.Schema_nameContext ctx) { + schemaName = ctx.getText(); + } + + @Override + public void enterFunct_name(PostgresParser.Funct_nameContext ctx) { + funcName = ctx.getText(); + } + + @Override + public void enterFunc_returns(PostgresParser.Func_returnsContext ctx) { + objReturnType = ctx.getChild(1).getText(); + } + + @Override + public void enterOne_funtion_argument(PostgresParser.One_funtion_argumentContext ctx) { + String[] argsInfo = new String[3]; + argsInfo[1] = "IN"; + for (int i = 0; i < ctx.getChildCount(); i++) { + ParserRuleContext child = (ParserRuleContext) ctx.getChild(i); + if (child.getClass().getName().contains("arg_nameContext")) { + argsInfo[0] = child.getText(); + } else if (child.getClass().getName().contains("arg_modeContext")) { + argsInfo[1] = child.getText(); + } else if (child.getClass().getName().contains("TypenameContext")) { + argsInfo[2] = child.getText(); + } + } + args.add(argsInfo); + } + + /** + * Gets the object name. + * + * @return the object name + */ + public String[] getObjectName() { + + return new String[] {objectType, objectName}; + } + + /** + * Gets the schema name. + * + * @return the schema name + */ + public String getSchemaName() { + + return schemaName; + } + + /** + * Gets the func name. + * + * @return the func name + */ + public String getFuncName() { + + return funcName; + } + + /** + * Gets the arguements. + * + * @return the arguements + */ + public ArrayList getArguements() { + + return args; + } + + /** + * Gets the return type. + * + * @return the return type + */ + public String getreturnType() { + + return objReturnType; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/.classpath b/code/datastudio/src/org.opengauss.mppdbide.explainplan/.classpath new file mode 100644 index 0000000000000000000000000000000000000000..936cda9e9fd714f6e0445428b3dfbdba65649eb6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/.classpath @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/.gitignore b/code/datastudio/src/org.opengauss.mppdbide.explainplan/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..09e3bc9b241c477ea341af9ee029becad0c2148c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/.gitignore @@ -0,0 +1,2 @@ +/bin/ +/target/ diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/.project b/code/datastudio/src/org.opengauss.mppdbide.explainplan/.project new file mode 100644 index 0000000000000000000000000000000000000000..2a869edf698178a7f20521a8fe2a44619856ce47 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/.project @@ -0,0 +1,34 @@ + + + org.opengauss.mppdbide.explainplan + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/META-INF/MANIFEST.MF b/code/datastudio/src/org.opengauss.mppdbide.explainplan/META-INF/MANIFEST.MF new file mode 100644 index 0000000000000000000000000000000000000000..29174715fb40f87ad27c5a56fd6753231164a9f6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/META-INF/MANIFEST.MF @@ -0,0 +1,37 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: MPPDBIDE_Explainplan +Bundle-SymbolicName: org.opengauss.mppdbide.explainplan +Bundle-Version: 1.0.0.qualifier +Bundle-Vendor: Huawei Technologies +Bundle-RequiredExecutionEnvironment: JavaSE-11 +Require-Bundle: org.apache.commons.lang;bundle-version="2.6.0", + org.opengauss.mppdbide.bl, + ca.odell.glazedlists;bundle-version="1.9.0", + org.opengauss.mppdbide.presentation;bundle-version="1.0.0", + org.eclipse.gef.graph, + org.eclipse.gef.common;bundle-version="5.0.0", + org.eclipse.gef.zest.fx +Export-Package: org.opengauss.mppdbide.explainplan.jsonparser, + org.opengauss.mppdbide.explainplan.nodetypes, + org.opengauss.mppdbide.explainplan.service, + org.opengauss.mppdbide.explainplan.ui.model, + org.opengauss.mppdbide.presentation.visualexplainplan +Import-Package: org.opengauss.mppdbide.adapter, + org.opengauss.mppdbide.adapter.gauss, + org.opengauss.mppdbide.bl.serverdatacache, + org.opengauss.mppdbide.explainplan.nodetypes, + org.opengauss.mppdbide.presentation, + org.opengauss.mppdbide.presentation.grid, + org.opengauss.mppdbide.presentation.objectproperties, + org.opengauss.mppdbide.utils, + org.opengauss.mppdbide.utils.exceptions, + org.opengauss.mppdbide.utils.loader, + org.opengauss.mppdbide.utils.logger, + org.opengauss.mppdbide.utils.messaging, + org.opengauss.mppdbide.utils.observer, + org.apache.commons.io.input;version="2.2.0", + org.eclipse.core.runtime, + org.eclipse.gef.layout.algorithms +Bundle-ClassPath: ., + gson-2.8.6.jar diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/build.properties b/code/datastudio/src/org.opengauss.mppdbide.explainplan/build.properties new file mode 100644 index 0000000000000000000000000000000000000000..03d62209b818ea95d07b111dfb444bb5602f470e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/build.properties @@ -0,0 +1,5 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + gson-2.8.6.jar diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/pom.xml b/code/datastudio/src/org.opengauss.mppdbide.explainplan/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..7f9b0c41a892dab72a72ad58f1bd2f192f33e28f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/pom.xml @@ -0,0 +1,13 @@ + + + 4.0.0 + + org.opengauss.plide.build + GAUSS_MPP_DB_IDE + 1.0.0-SNAPSHOT + + org.opengauss.mppdbide.explainplan + eclipse-plugin + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/jsonparser/ExplainPlanJsonContentParser.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/jsonparser/ExplainPlanJsonContentParser.java new file mode 100644 index 0000000000000000000000000000000000000000..a8412f4b205fa79697350a8cde334b496fc9901d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/jsonparser/ExplainPlanJsonContentParser.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.jsonparser; + +import java.util.ArrayList; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonSyntaxException; +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNodeDeserializer; +import org.opengauss.mppdbide.explainplan.nodetypes.RootPlanNode; +import org.opengauss.mppdbide.explainplan.nodetypes.RootPlanNodeDeserializer; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class ExplainPlanJsonContentParser. + * + * @since 3.0.0 + */ +public class ExplainPlanJsonContentParser { + private String jsonContent; + + /** + * Instantiates a new explain plan json content parser. + * + * @param jsonContent the json content + */ + public ExplainPlanJsonContentParser(String jsonContent) { + this.jsonContent = jsonContent; + } + + /** + * Parses the file contents. + * + * @return the root plan node + * @throws DatabaseOperationException the database operation exception + */ + public RootPlanNode parseFileContents() throws DatabaseOperationException { + RootPlanNode cRootNode = jsonParser(); + if (cRootNode != null && !cRootNode.getChildren().isEmpty()) { + cRootNode.getChildren().get(0).setParent(null); + fixParentChildRelationship(cRootNode.getChildren(), null); + return cRootNode; + } + + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_JSON_PARSING_FAILED)); + throw new DatabaseOperationException(IMessagesConstants.VIS_EXPLAIN_JSON_PARSING_FAILED); + + } + + private void fixParentChildRelationship(ArrayList arrayList, OperationalNode parent) { + for (OperationalNode c : arrayList) { + c.setParent(parent); + fixParentChildRelationship(c.getChildren(), c); + } + + } + + private RootPlanNode jsonParser() { + Gson gson = null; + GsonBuilder gsonBuilder = new GsonBuilder(); + + gsonBuilder.registerTypeAdapter(RootPlanNode.class, new RootPlanNodeDeserializer()); + gsonBuilder.registerTypeAdapter(OperationalNode.class, new OperationalNodeDeserializer()); + gson = gsonBuilder.create(); + + try { + return gson.fromJson(jsonContent, RootPlanNode.class); + } catch (JsonSyntaxException e) { + return null; + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/AbstractOperationalNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/AbstractOperationalNode.java new file mode 100644 index 0000000000000000000000000000000000000000..5a3cfe99022f1fbb6e28cfeafdf558242e656524 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/AbstractOperationalNode.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.nodetypes; + +/** + * + * Title: class + * + * Description: The Class AbstractOperationalNode. + * + * @since 3.0.0 + */ +public abstract class AbstractOperationalNode extends BasicNode { + + /** + * Instantiates a new abstract operational node. + * + * @param cat the cat + */ + public AbstractOperationalNode(NodeCategoryEnum cat) { + super(cat); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/ActualInDetail.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/ActualInDetail.java new file mode 100644 index 0000000000000000000000000000000000000000..88f762a15c3549271de721e9756801b09a0be3da --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/ActualInDetail.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.nodetypes; + +import com.google.gson.annotations.SerializedName; + +/** + * + * Title: class + * + * Description: The Class ActualInDetail. + * + * @since 3.0.0 + */ +public class ActualInDetail { + @SerializedName("DN Name") + private String dnName; + + @SerializedName("Actual Startup Time") + private double actualStartupTime; + + @SerializedName("Actual Total Time") + private double actualTotalTime; + + @SerializedName("Actual Rows") + private long actualRows; + + @SerializedName("Actual Loops") + private long actualLoops; + + /** + * Gets the actual rows. + * + * @return the actual rows + */ + public long getActualRows() { + return actualRows; + } + + /** + * Gets the actual startup time. + * + * @return the actual startup time + */ + public double getActualStartupTime() { + return actualStartupTime; + } + + /** + * Gets the actual total time. + * + * @return the actual total time + */ + public double getActualTotalTime() { + return actualTotalTime; + } + + /** + * Gets the dn name. + * + * @return the dn name + */ + public String getDnName() { + return dnName; + } + + /** + * Gets the actual loops. + * + * @return the actual loops + */ + public long getActualLoops() { + return actualLoops; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/ActualInDetailUtility.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/ActualInDetailUtility.java new file mode 100644 index 0000000000000000000000000000000000000000..82051135713610e2d1038a18da641ca6fe767d0d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/ActualInDetailUtility.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.nodetypes; + +import java.util.ArrayList; + +import org.opengauss.mppdbide.presentation.objectproperties.DNIntraNodeDetailsColumn; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class ActualInDetailUtility. + * + * @since 3.0.0 + */ +public class ActualInDetailUtility { + + /** + * Fill column property header. + * + * @return the DN intra node details column + */ + public static DNIntraNodeDetailsColumn fillColumnPropertyHeader() { + DNIntraNodeDetailsColumn dnActualsInDetail = new DNIntraNodeDetailsColumn(); + + dnActualsInDetail.setGroupColumnName( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_PERDN_ACTUALSINDETAIL_COLUMNGRP)); + + ArrayList colnames = new ArrayList(5); + colnames.add( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_PERDN_ACTUALS_COLUMN_STARTUPTIME)); + colnames.add( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_PERDN_ACTUALS_COLUMN_TOTALTIME)); + colnames.add(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_PERDN_ACTUALS_COLUMN_ROWS)); + colnames.add(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_PERDN_ACTUALS_COLUMN_LOOPS)); + + dnActualsInDetail.setColCount(4); + dnActualsInDetail.setColnames(colnames); + + return dnActualsInDetail; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/BaseNodeIf.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/BaseNodeIf.java new file mode 100644 index 0000000000000000000000000000000000000000..f9a07ab3dd636c7b95952eb8d66395a73935e922 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/BaseNodeIf.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.nodetypes; + +/** + * + * Title: interface + * + * Description: The Interface BaseNodeIf. + * + * @since 3.0.0 + */ +public interface BaseNodeIf { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/BasicNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/BasicNode.java new file mode 100644 index 0000000000000000000000000000000000000000..3c9ac34d9b1fa301a2e6841c1bdbbbf5b07db245 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/BasicNode.java @@ -0,0 +1,950 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.nodetypes; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.presentation.objectproperties.DNIntraNodeDetailsColumn; +import org.opengauss.mppdbide.utils.EnvirnmentVariableValidator; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class BasicNode. + * + * @since 3.0.0 + */ +public abstract class BasicNode implements IStatisticalData { + + /** + * The node category. + */ + protected NodeCategoryEnum nodeCategory; + + /** + * The sub plan + */ + @SerializedName("Subplan Name") + protected String subPlan = ""; + + /** + * The node type + */ + @SerializedName("Node Type") + protected String nodeType = ""; + + /** + * The parent relationship + */ + @SerializedName("Parent Relationship") + protected String parentRelationship = ""; + + /** + * The startup cost + */ + @SerializedName("Startup Cost") + protected double startupCost; + + /** + * The total cost + */ + @SerializedName("Total Cost") + protected double totalCost; + + /** + * The plan rows + */ + @SerializedName("Plan Rows") + protected long planRows; + + /** + * The plan width + */ + @SerializedName("Plan Width") + protected long planWidth; + + /** + * The actual in detail + */ + @SerializedName("Actual In Detail") + protected List actualsInDetail; + + /** + * The output + */ + @SerializedName("Output") + protected String[] output; + + /** + * The cpu in detail + */ + @SerializedName("Cpus In Detail") + protected List cpuInDetail; + + /** + * The exclusive cycles per rowno DN + */ + @SerializedName("Exclusive Cycles/Row") + private String exclusiveCyclesPerRowNoDN; + + /** + * The exclusive cycles per row. + */ + protected long exclusiveCyclesPerRow; + + /** + * The exclusive cycles + */ + @SerializedName("Exclusive Cycles") + protected long exclusiveCycles; + + /** + * The inclusive cycles + */ + @SerializedName("Inclusive Cycles") + protected long inclusiveCycles; + + /** + * The buffers in detail + */ + @SerializedName("Buffers In Detail") + protected List buffersInDetail; + + @SerializedName("Shared Hit Blocks") + private String sharedHitBlocksNoDN; + + private long sharedHitBlocks = 0; + + @SerializedName("Shared Read Blocks") + private long sharedReadBlocks = 0; + + @SerializedName("Shared Dirtied Blocks") + private long sharedDirtiedBlocks = 0; + + @SerializedName("Shared Written Blocks") + private long sharedWrittenBlocks = 0; + + @SerializedName("Local Hit Blocks") + private long localHitBlocks = 0; + + @SerializedName("Local Read Blocks") + private long localReadBlocks = 0; + + @SerializedName("Local Dirtied Blocks") + private long localDirtiedBlocks = 0; + + @SerializedName("Local Written Blocks") + private long localWrittenBlocks = 0; + + @SerializedName("Temp Read Blocks") + private long tempReadBlocks = 0; + + @SerializedName("Temp Written Blocks") + private long tempWrittenBlocks = 0; + + @SerializedName("I/O Read Time") + private double ioReadTime = 0d; + + @SerializedName("I/O Write Time") + private double ioWriteTime = 0d; + + /** + * The actal min startup time + */ + @SerializedName("Actual Min Startup Time") + protected double actualMinStartupTime; + + /** + * The actual max startup time + */ + @SerializedName("Actual Max Startup Time") + protected double actualMaxStartupTime; + + /** + * The actual min total time + */ + @SerializedName("Actual Min Total Time") + protected double actualMinTotalTime; + + /** + * The actual max total time + */ + @SerializedName("Actual Max Total Time") + protected double actualMaxTotalTime; + + /** + * The actual rows + */ + @SerializedName("Actual Rows") + protected long actualRows; + + /** + * The actual total rows + */ + @SerializedName("Actual Total Rows") + protected long actualTotalRows; + + /** + * The actual loops + */ + @SerializedName("Actual Loops") + protected long actualLoops; + + /** + * The actual startup time + */ + @SerializedName("Actual Startup Time") + protected double actualStartupTime = 0d; + + /** + * The actual total time + */ + @SerializedName("Actual Total Time") + protected double actualTotalTime = 0d; + + /** + * The Llvm detail + */ + @SerializedName("Llvm Detail") + protected List llvmDetail; + + /** + * The nodes + */ + @SerializedName("Node/s") + protected String nodes; + + /** + * The cost info for text display. + */ + protected String costInfoForTextDisplay = null; + + /** + * Instantiates a new basic node. + * + * @param cat the cat + */ + public BasicNode(NodeCategoryEnum cat) { + this.nodeCategory = cat; + actualsInDetail = new ArrayList(5); + cpuInDetail = new ArrayList(5); + } + + /** + * Creates the cost info for text display. + * + * @return the string + */ + private String createCostInfoForTextDisplay() { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("(cost="); + sb.append(startupCost); + sb.append(".."); + sb.append(totalCost); + sb.append(" rows="); + sb.append(planRows); + sb.append(" width="); + sb.append(planWidth); + sb.append(")"); + return sb.toString(); + } + + /** + * Creates the analyze info for text display. + * + * @return the string + */ + private String createAnalyzeInfoForTextDisplay() { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("(actual time="); + if (getActualStartupTime() != 0) { + sb.append(getActualStartupTime()); + } else { + sb.append("["); + sb.append(actualMinStartupTime); + sb.append(","); + sb.append(actualMaxStartupTime); + sb.append("]"); + } + sb.append(".."); + if (getActualTotalTime() != 0) { + sb.append(getActualTotalTime()); + } else { + sb.append("["); + sb.append(actualMinTotalTime); + sb.append(","); + sb.append(actualMaxTotalTime); + sb.append("]"); + } + sb.append(" rows="); + sb.append(getActualRows()); + if (getActualLoopCount() != 0) { + sb.append(" loops="); + sb.append(getActualLoopCount()); + } + sb.append(")"); + return sb.toString(); + } + + /** + * Gets the cost info for text display. + * + * @param isAnalyze the is analyze + * @return the cost info for text display + */ + protected String getCostInfoForTextDisplay(boolean isAnalyze) { + if (this.costInfoForTextDisplay == null) { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append(createCostInfoForTextDisplay()); + if (isAnalyze) { + sb.append(" "); + sb.append(createAnalyzeInfoForTextDisplay()); + } + this.costInfoForTextDisplay = sb.toString(); + } + return this.costInfoForTextDisplay; + } + + /** + * Gets the actual max total time. + * + * @return the actual max total time + */ + public double getActualMaxTotalTime() { + return Math.abs(actualStartupTime) > 0d ? Math.abs(actualStartupTime) : Math.abs(actualMaxTotalTime); + } + + /** + * Gets the actual max startup time. + * + * @return the actual max startup time + */ + public double getActualMaxStartupTime() { + return actualMaxStartupTime; + } + + /** + * Gets the node type. + * + * @return the node type + */ + public String getNodeType() { + return nodeType; + } + + /** + * Gets the plan rows. + * + * @return the plan rows + */ + public long getPlanRows() { + return planRows; + } + + /** + * Gets the plan width. + * + * @return the plan width + */ + public long getPlanWidth() { + return planWidth; + } + + /** + * To string. + * + * @return toString + */ + public String toString() { + return getNodeType() + EnvirnmentVariableValidator.validateAndGetLineSeperator(); + } + + /** + * Gets the total cost. + * + * @return the total cost + */ + @Override + public double getTotalCost() { + return totalCost; + } + + /** + * Gets the actual max time taken. + * + * @return getActualMaxTimeTaken + */ + public double getActualMaxTimeTaken() { + return this.getActualMaxTotalTime(); + } + + /** + * Gets the actual total time. + * + * @return the actual total time + */ + @Override + public double getActualTotalTime() { + if (0 == actualsInDetail.size()) { + return this.actualTotalTime; + } else { + double count = 0; + + for (ActualInDetail a : actualsInDetail) { + if (Math.abs(count) < Math.abs(a.getActualTotalTime())) { + count = a.getActualTotalTime(); + } + } + + return count; + } + } + + /** + * Gets the actual rows. + * + * @return the actual rows + */ + @Override + public long getActualRows() { + if (0 == actualsInDetail.size()) { + return (0 == actualRows) ? this.actualTotalRows : this.actualRows; + } else { + long count = 0; + + for (ActualInDetail a : actualsInDetail) { + count += a.getActualRows(); + } + + return count; + } + } + + /** + * Gets the actual loop count. + * + * @return the actual loop count + */ + public long getActualLoopCount() { + if (0 == actualsInDetail.size()) { + return this.actualLoops; + } else { + long count = 0; + + for (ActualInDetail a : actualsInDetail) { + count += a.getActualLoops(); + } + + return count; + } + } + + /** + * Gets the actual startup time. + * + * @return the actual startup time + */ + public double getActualStartupTime() { + if (0 == actualsInDetail.size()) { + return this.actualStartupTime; + } else { + double count = 0; + + for (ActualInDetail a : actualsInDetail) { + count += a.getActualStartupTime(); + } + + return count; + } + } + + /** + * Checks for DN data. + * + * @return true, if successful + */ + public boolean hasDNData() { + + return actualsInDetail.size() != 0; + + } + + /** + * Gets the parent relationship. + * + * @return the parent relationship + */ + public String getParentRelationship() { + return "Parent Relationship : " + parentRelationship; + } + + /** + * Gets the node specific properties. + * + * @return getNodeSpecificProperties + */ + public List getNodeSpecificProperties() { + ArrayList arList = new ArrayList(5); + + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_PLANWIDTH), planWidth) + .getProp()); + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_PLANROWS), getPlanRows()) + .getProp()); + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_ACTUALOUTROWS), + getActualRows()).getProp()); + + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_ACTUALSTARTUPTIME), + getActualStartupTime()).getProp()); + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_ACTUALTOTALTIME), + getActualTotalTime()).getProp()); + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_ACTUALLOOPS), + getActualLoopCount()).getProp()); + + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_STARTUPCOST), startupCost) + .getProp()); + + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_TOTALCOST), totalCost) + .getProp()); + + String nodeNameFirstPart = nodeType.split(" ")[0]; + if ("Vector".equalsIgnoreCase(nodeNameFirstPart)) { + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_ISVECTORIZED), "Yes") + .getProp()); + } else { + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_ISVECTORIZED), "No") + .getProp()); + } + + if (!this.hasDNData()) { + fillnoDNBufferDetail(arList); + fillnoDNCPUDetail(arList); + } + + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_NODETYPE), nodeType) + .getProp()); + if (!"".equals(parentRelationship)) { + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_PARENTRELATIONSHIP), + parentRelationship).getProp()); + } + + return arList; + } + + private void fillnoDNCPUDetail(ArrayList arList) { + if (null == exclusiveCyclesPerRowNoDN) { + return; + } + + try { + exclusiveCyclesPerRow = Long.parseLong(exclusiveCyclesPerRowNoDN); + + arList.add(new ServerProperty( + MessageConfigLoader + .getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_CPU_EXCLUSIVECYCLESROW), + exclusiveCyclesPerRow).getProp()); + + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_CPU_EXCLUSIVECYCLES), + exclusiveCycles).getProp()); + + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_CPU_INCLUSIVECYCLES), + inclusiveCycles).getProp()); + } catch (NumberFormatException numberFormatException) { + MPPDBIDELoggerUtility.error("Error while parsing the string argument as a signed decimal ", numberFormatException); + } + } + + private void fillnoDNBufferDetail(ArrayList arList) { + // shall fill this info only if Info is present. + if (null == sharedHitBlocksNoDN) { + return; + } + + this.sharedHitBlocks = Long.parseLong(sharedHitBlocksNoDN); + + fillnoDNBufferDetail1(arList); + + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_TEMPREADBLOCKS), + tempReadBlocks).getProp()); + + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_TEMPWRITTENBLOCKS), + tempWrittenBlocks).getProp()); + + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_IOREADTIME), + ioReadTime).getProp()); + + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_IOWRITETIME), + ioWriteTime).getProp()); + } + + private void fillnoDNBufferDetail1(ArrayList arList) { + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDHITBLOCKS), + sharedHitBlocks).getProp()); + + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDREADBLOCKS), + sharedReadBlocks).getProp()); + + arList.add( + new ServerProperty( + MessageConfigLoader + .getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDDIRTIEDBLOCKS), + sharedDirtiedBlocks).getProp()); + + arList.add( + new ServerProperty( + MessageConfigLoader + .getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDWRITTENBLOCKS), + sharedWrittenBlocks).getProp()); + + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALHITBLOCKS), + localHitBlocks).getProp()); + + arList.add( + new ServerProperty( + MessageConfigLoader + .getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALREADHITBLOCKS), + localReadBlocks).getProp()); + + arList.add( + new ServerProperty( + MessageConfigLoader + .getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALDIRTIEDBLOCKS), + localDirtiedBlocks).getProp()); + + arList.add( + new ServerProperty( + MessageConfigLoader + .getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALWRITTENBLOCKS), + localWrittenBlocks).getProp()); + } + + /** + * Gets the per DN specific details. + * + * @param inputMap the input map + * @return the per DN specific details + */ + public Map> getPerDNSpecificDetails(Map> inputMap) { + getActualsDetails(inputMap); + getCpuDetails(inputMap); + + if (null != llvmDetail) { + getLlvmDetails(inputMap); + } + + if (null != buffersInDetail) { + getBufferInDetails(inputMap); + } + + return inputMap; + } + + /** + * Gets the per DN specific column grouping info. + * + * @param colGroup the col group + * @return the per DN specific column grouping info + */ + public List getPerDNSpecificColumnGroupingInfo(List colGroup) { + colGroup.add(ActualInDetailUtility.fillColumnPropertyHeader()); + colGroup.add(CpuInDetail.fillColumnPropertyHeader()); + + if (null != llvmDetail) { + colGroup.add(LLVMDNDetails.fillColumnPropertyHeader()); + } + + if (null != buffersInDetail) { + colGroup.add(BuffersInDetail.fillColumnPropertyHeader()); + } + + return colGroup; + } + + /** + * Gets the per DN specific details. + * + * @param inputMap the input map + * @param detailsNeeded the details needed + * @return the per DN specific details + */ + public Map> getPerDNSpecificDetails(Map> inputMap, + ArrayList detailsNeeded) { + if (detailsNeeded.contains(INDETAILSCATEGORY.ACTUALS_IN_DETAIL)) { + getActualsDetails(inputMap); + } + + if (detailsNeeded.contains(INDETAILSCATEGORY.CPU_IN_DETAIL)) { + getCpuDetails(inputMap); + } + + if (detailsNeeded.contains(INDETAILSCATEGORY.LLVM_DETAIL) && null != llvmDetail) { + getLlvmDetails(inputMap); + } + + if (detailsNeeded.contains(INDETAILSCATEGORY.BUFFERS_IN_DETAIL) && null != buffersInDetail) { + getBufferInDetails(inputMap); + } + + return inputMap; + } + + private void getCpuDetails(Map> inputMap) { + for (CpuInDetail cnt : this.cpuInDetail) { + if (!inputMap.containsKey(cnt.getDnName())) { + List propsValues = cnt.propertyDetails(); + inputMap.put(cnt.getDnName(), propsValues); + } else { + inputMap.get(cnt.getDnName()).addAll(cnt.propertyDetails()); + } + } + + } + + private void getActualsDetails(Map> inputMap) { + for (ActualInDetail entry : actualsInDetail) { + if (!inputMap.containsKey(entry.getDnName())) { + List propsValues = propertyDetails(entry); + inputMap.put(entry.getDnName(), propsValues); + } else { + inputMap.get(entry.getDnName()).addAll(propertyDetails(entry)); + } + } + + } + + private List propertyDetails(ActualInDetail arList) { + ArrayList colInfo = new ArrayList(5); + + colInfo.add(arList.getActualStartupTime()); + colInfo.add(arList.getActualTotalTime()); + colInfo.add(arList.getActualRows()); + colInfo.add(arList.getActualLoops()); + + return colInfo; + } + + private void getBufferInDetails(Map> inputMap) { + for (BuffersInDetail entry : buffersInDetail) { + if (!inputMap.containsKey(entry.getDnName())) { + List propsValues = entry.propertyDetails(); + inputMap.put(entry.getDnName(), propsValues); + } else { + inputMap.get(entry.getDnName()).addAll(entry.propertyDetails()); + } + } + + } + + private void getLlvmDetails(Map> inputMap) { + for (LLVMDNDetails entry : llvmDetail) { + if (!inputMap.containsKey(entry.getDnName())) { + List propsValues = entry.propertyDetails(); + inputMap.put(entry.getDnName(), propsValues); + } else { + inputMap.get(entry.getDnName()).addAll(entry.propertyDetails()); + } + } + + } + + /** + * Gets the per DN specific column grouping info. + * + * @param colGroup the col group + * @param detailsNeeded the details needed + * @return the per DN specific column grouping info + */ + public List getPerDNSpecificColumnGroupingInfo(List colGroup, + ArrayList detailsNeeded) { + if (detailsNeeded.contains(INDETAILSCATEGORY.ACTUALS_IN_DETAIL)) { + colGroup.add(ActualInDetailUtility.fillColumnPropertyHeader()); + } + + if (detailsNeeded.contains(INDETAILSCATEGORY.CPU_IN_DETAIL)) { + colGroup.add(CpuInDetail.fillColumnPropertyHeader()); + } + + if (detailsNeeded.contains(INDETAILSCATEGORY.LLVM_DETAIL) && null != llvmDetail) { + colGroup.add(LLVMDNDetails.fillColumnPropertyHeader()); + } + + if (detailsNeeded.contains(INDETAILSCATEGORY.BUFFERS_IN_DETAIL) && null != buffersInDetail) { + colGroup.add(BuffersInDetail.fillColumnPropertyHeader()); + } + + return colGroup; + } + + /** + * Gets the DN involved. + * + * @param dnsInvolved the dns involved + * @return the DN involved + */ + public ArrayList getDNInvolved(ArrayList dnsInvolved) { + + for (ActualInDetail elmnt : actualsInDetail) { + dnsInvolved.add(elmnt.getDnName()); + } + + return dnsInvolved; + } + + /** + * Adds the node DN plan view. + * + * @param dnViewofExplainPlan the dn viewof explain plan + * @param idx the idx + */ + public void addNodeDNPlanView(Map dnViewofExplainPlan, int idx) { + String dnName = null; + Object[] nodesArr = null; + for (Entry entry : dnViewofExplainPlan.entrySet()) { + dnName = entry.getKey(); + nodesArr = entry.getValue(); + nodesArr[idx] = null; + + for (ActualInDetail elemt : actualsInDetail) { + if (dnName.equals(elemt.getDnName())) { + nodesArr[idx] = this; + break; + } + } + } + + } + + /** + * Gets the node name. + * + * @return the node name + */ + public String getNodeName() { + return getNodeType(); + } + + /** + * Gets the node category name. + * + * @return the node category name + */ + public String getNodeCategoryName() { + return this.nodeCategory.getCategoryName(); + } + + /** + * Gets the actuals by DN name. + * + * @param dnName the dn name + * @return the actuals by DN name + */ + public ActualInDetail getActualsByDNName(String dnName) { + for (ActualInDetail elmnt : actualsInDetail) { + if (dnName.equals(elmnt.getDnName())) { + return elmnt; + } + } + + return null; + } + + /** + * Gets the additional info. + * + * @param isAnalyze the is analyze + * @return the additional info + */ + public List getAdditionalInfo(boolean isAnalyze) { + List arList = new ArrayList(4); + if (nodes != null) { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Node/s: "); + sb.append(nodes); + arList.add(sb.toString()); + } + if (isAnalyze) { + if (buffersInDetail != null) { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Buffers: "); + if (sharedHitBlocks + sharedReadBlocks != 0) { + sb.append("shared hit="); + sb.append(sharedHitBlocks); + sb.append(" read="); + sb.append(sharedReadBlocks); + arList.add(sb.toString()); + } + if (tempReadBlocks + tempWrittenBlocks != 0) { + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("temp read="); + sb.append(tempReadBlocks); + sb.append(" written="); + sb.append(tempWrittenBlocks); + arList.add(sb.toString()); + } + } + } + return arList; + } + + /** + * Gets the startup cost. + * + * @return the startup cost + */ + public double getStartupCost() { + return startupCost; + } + + /** + * Gets the subplan name. + * + * @return the subplan name + */ + public String getSubplanName() { + return this.subPlan; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/BuffersInDetail.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/BuffersInDetail.java new file mode 100644 index 0000000000000000000000000000000000000000..cde4c277cb5f89369b954129e2a7e1cd5eac1503 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/BuffersInDetail.java @@ -0,0 +1,199 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.nodetypes; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.presentation.objectproperties.DNIntraNodeDetailsColumn; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class BuffersInDetail. + * + * @since 3.0.0 + */ +public class BuffersInDetail { + @SerializedName("DN Name") + private String dnName; + + @SerializedName("Shared Hit Blocks") + private long sharedHitBlocks; + + @SerializedName("Shared Read Blocks") + private long sharedReadBlocks; + + @SerializedName("Shared Dirtied Blocks") + private long sharedDirtiedBlocks; + + @SerializedName("Shared Written Blocks") + private long sharedWrittenBlocks; + + @SerializedName("Local Hit Blocks") + private long localHitBlocks; + + @SerializedName("Local Read Blocks") + private long localReadBlocks; + + @SerializedName("Local Dirtied Blocks") + private long localDirtiedBlocks; + + @SerializedName("Local Written Blocks") + private long localWrittenBlocks; + + @SerializedName("Temp Read Blocks") + private long tempReadBlocks; + + @SerializedName("Temp Written Blocks") + private long tempWrittenBlocks; + + @SerializedName("I/O Read Time") + private double ioReadTime; + + @SerializedName("I/O Write Time") + private double ioWriteTime; + + /** + * Property details. + * + * @return the list + */ + public List propertyDetails() { + ArrayList colInfo = new ArrayList(5); + + colInfo.add(getSharedHitBlocks()); + colInfo.add(getSharedReadBlocks()); + colInfo.add(getSharedDirtiedBlocks()); + colInfo.add(getSharedWrittenBlocks()); + + colInfo.add(getLocalHitBlocks()); + colInfo.add(getLocalReadBlocks()); + colInfo.add(getLocalDirtiedBlocks()); + colInfo.add(getLocalWrittenBlocks()); + + colInfo.add(getTempReadBlocks()); + colInfo.add(getTempWrittenBlocks()); + colInfo.add(getIoReadTime()); + colInfo.add(getIoWriteTime()); + + return colInfo; + } + + /** + * Fill column property header. + * + * @return the DN intra node details column + */ + public static DNIntraNodeDetailsColumn fillColumnPropertyHeader() { + DNIntraNodeDetailsColumn dnBufferInDetail = new DNIntraNodeDetailsColumn(); + + dnBufferInDetail.setGroupColumnName( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_PERDN_BUFFERSINDETAIL)); + + ArrayList colnames = new ArrayList(12); + colnames.add( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDHITBLOCKS)); + colnames.add( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDREADBLOCKS)); + colnames.add(MessageConfigLoader + .getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDDIRTIEDBLOCKS)); + colnames.add(MessageConfigLoader + .getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDWRITTENBLOCKS)); + + colnames.add( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALHITBLOCKS)); + colnames.add(MessageConfigLoader + .getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALREADHITBLOCKS)); + colnames.add(MessageConfigLoader + .getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALDIRTIEDBLOCKS)); + colnames.add(MessageConfigLoader + .getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALWRITTENBLOCKS)); + + colnames.add( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_TEMPREADBLOCKS)); + colnames.add(MessageConfigLoader + .getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_TEMPWRITTENBLOCKS)); + colnames.add(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_IOREADTIME)); + colnames.add(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_BUFFER_IOWRITETIME)); + + dnBufferInDetail.setColCount(12); + dnBufferInDetail.setColnames(colnames); + + return dnBufferInDetail; + } + + /** + * Gets the dn name. + * + * @return the dn name + */ + public String getDnName() { + return dnName; + } + + private double getLocalReadBlocks() { + return localReadBlocks; + } + + private double getSharedHitBlocks() { + return sharedHitBlocks; + } + + private long getSharedReadBlocks() { + return sharedReadBlocks; + } + + private long getSharedDirtiedBlocks() { + return sharedDirtiedBlocks; + } + + private long getSharedWrittenBlocks() { + return sharedWrittenBlocks; + } + + private long getLocalHitBlocks() { + return localHitBlocks; + } + + private long getLocalDirtiedBlocks() { + return localDirtiedBlocks; + } + + private long getLocalWrittenBlocks() { + return localWrittenBlocks; + } + + private long getTempReadBlocks() { + return tempReadBlocks; + } + + private long getTempWrittenBlocks() { + return tempWrittenBlocks; + } + + private double getIoReadTime() { + return ioReadTime; + } + + private double getIoWriteTime() { + return ioWriteTime; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/CpuInDetail.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/CpuInDetail.java new file mode 100644 index 0000000000000000000000000000000000000000..7e2cc5da78a68bc50bd49db3aa225f67ababb83a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/CpuInDetail.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.nodetypes; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.presentation.objectproperties.DNIntraNodeDetailsColumn; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class CpuInDetail. + * + * @since 3.0.0 + */ +public class CpuInDetail { + @SerializedName("DN Name") + private String dnName; + + /** + * The exclusive cycles per row. + */ + @SerializedName("Exclusive Cycles/Row") + protected long exclusiveCyclesPerRow; + + /** + * The exclusive cycles. + */ + @SerializedName("Exclusive Cycles") + protected long exclusiveCycles; + + /** + * The inclusive cycles. + */ + @SerializedName("Inclusive Cycles") + protected long inclusiveCycles; + + /** + * Property details. + * + * @return the list + */ + public List propertyDetails() { + ArrayList colInfo = new ArrayList(5); + + colInfo.add(exclusiveCyclesPerRow); + colInfo.add(exclusiveCycles); + colInfo.add(inclusiveCycles); + + return colInfo; + } + + /** + * Fill column property header. + * + * @return the DN intra node details column + */ + public static DNIntraNodeDetailsColumn fillColumnPropertyHeader() { + DNIntraNodeDetailsColumn dnActualsInDetail = new DNIntraNodeDetailsColumn(); + + dnActualsInDetail.setGroupColumnName( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_PERDN_CPUINDETAIL)); + + ArrayList colnames = new ArrayList(5); + colnames.add( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_CPU_EXCLUSIVECYCLESROW)); + colnames.add( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_CPU_EXCLUSIVECYCLES)); + colnames.add( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_CPU_INCLUSIVECYCLES)); + + dnActualsInDetail.setColCount(3); + dnActualsInDetail.setColnames(colnames); + + return dnActualsInDetail; + } + + /** + * Gets the dn name. + * + * @return the dn name + */ + public String getDnName() { + return dnName; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/HashDetail.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/HashDetail.java new file mode 100644 index 0000000000000000000000000000000000000000..68094860948fdbb25cb79b5c7a4c94aa7cf378c4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/HashDetail.java @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.nodetypes; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.presentation.objectproperties.DNIntraNodeDetailsColumn; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class HashDetail. + * + * @since 3.0.0 + */ +public class HashDetail { + @SerializedName("DN Name") + private String dnName; + + @SerializedName("Hash Buckets") + private long hashBuckets; + + @SerializedName("Hash Batches") + private long hashBatches; + + @SerializedName("Original Hash Batches") + private long originalHashBatches; + + @SerializedName("Peak Memory Usage") + private long peakMemoryUsage; + + /** + * Property details. + * + * @return the list + */ + public List propertyDetails() { + ArrayList colInfo = new ArrayList(5); + + colInfo.add(getHashBuckets()); + colInfo.add(getHashBatches()); + colInfo.add(getOriginalHashBatches()); + colInfo.add(getPeakMemoryUsage()); + + return colInfo; + } + + /** + * Fill column property header. + * + * @return the DN intra node details column + */ + public static DNIntraNodeDetailsColumn fillColumnPropertyHeader() { + DNIntraNodeDetailsColumn dnBufferInDetail = new DNIntraNodeDetailsColumn(); + + dnBufferInDetail.setGroupColumnName( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_PERDN_HASHDETAIL)); + + ArrayList colnames = new ArrayList(12); + colnames.add(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_HASH_HASHBUCKETS)); + colnames.add(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_HASH_HASHBATCHES)); + colnames.add(MessageConfigLoader + .getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_HASH_ORIGINALHASHBATCHES)); + colnames.add( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_BASICNODE_HASH_PEAKMEMORYUSAGE)); + + dnBufferInDetail.setColCount(4); + dnBufferInDetail.setColnames(colnames); + + return dnBufferInDetail; + } + + private long getHashBuckets() { + return hashBuckets; + } + + private long getHashBatches() { + return hashBatches; + } + + private long getOriginalHashBatches() { + return originalHashBatches; + } + + private long getPeakMemoryUsage() { + return peakMemoryUsage; + } + + /** + * Gets the dn name. + * + * @return the dn name + */ + public String getDnName() { + return dnName; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/HashJoinDNDetails.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/HashJoinDNDetails.java new file mode 100644 index 0000000000000000000000000000000000000000..6ab5dd05be96e1d0498916e6b065cadf15ce13fa --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/HashJoinDNDetails.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.nodetypes; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.presentation.objectproperties.DNIntraNodeDetailsColumn; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class HashJoinDNDetails. + * + * @since 3.0.0 + */ +public class HashJoinDNDetails { + @SerializedName("DN Name") + private String dnName; + + @SerializedName("Memory Used") + private double memoryUsed; + + /** + * Property details. + * + * @param childNodes the child nodes + * @return the list + */ + public List propertyDetails(ArrayList childNodes) { + ArrayList colInfo = new ArrayList(5); + colInfo.add(getMemoryUsed()); + ActualInDetail inner = (!childNodes.isEmpty()) ? childNodes.get(0).getActualsByDNName(getDnName()) : null; + ActualInDetail outer = (childNodes.size() > 1) ? childNodes.get(1).getActualsByDNName(getDnName()) : null; + + colInfo.add((inner == null) ? 0 : inner.getActualRows()); + colInfo.add(outer == null ? 0 : outer.getActualRows()); + colInfo.add((inner == null) ? 0 : inner.getActualStartupTime()); + colInfo.add(outer == null ? 0 : outer.getActualStartupTime()); + + colInfo.add((inner == null) ? 0 : inner.getActualTotalTime()); + colInfo.add(outer == null ? 0 : outer.getActualTotalTime()); + + return colInfo; + } + + /** + * Fill column property header. + * + * @return the DN intra node details column + */ + public static DNIntraNodeDetailsColumn fillColumnPropertyHeader() { + DNIntraNodeDetailsColumn dnActualsInDetail = new DNIntraNodeDetailsColumn(); + + dnActualsInDetail.setGroupColumnName( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_PERDN_JOININDETAIL)); + + ArrayList colnames = new ArrayList(5); + colnames.add("Memory Used"); + colnames.add("Inner node- Rows"); + colnames.add("Outer Node- Rows"); + colnames.add("Inner node- Startup Time"); + colnames.add("Outer Node- Startup Time"); + colnames.add("Inner node- Total Time"); + colnames.add("Outer Node- Total Time"); + + dnActualsInDetail.setColCount(7); + dnActualsInDetail.setColnames(colnames); + + return dnActualsInDetail; + } + + /** + * Gets the dn name. + * + * @return the dn name + */ + public String getDnName() { + return dnName; + } + + /** + * Sets the dn name. + * + * @param dnName the new dn name + */ + public void setDnName(String dnName) { + this.dnName = dnName; + } + + /** + * Gets the memory used. + * + * @return the memory used + */ + public double getMemoryUsed() { + return memoryUsed; + } + + /** + * Sets the memory used. + * + * @param memoryUsed the new memory used + */ + public void setMemoryUsed(double memoryUsed) { + this.memoryUsed = memoryUsed; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/INDETAILSCATEGORY.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/INDETAILSCATEGORY.java new file mode 100644 index 0000000000000000000000000000000000000000..c407ba198116036ec6e4a4287d8e644eeac881cb --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/INDETAILSCATEGORY.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.nodetypes; + +/** + * + * Title: enum + * + * Description: The Enum INDETAILSCATEGORY. + * + * @since 3.0.0 + */ +public enum INDETAILSCATEGORY { + ACTUALS_IN_DETAIL, CPU_IN_DETAIL, IO_IN_DETAIL, LLVM_DETAIL, BUFFERS_IN_DETAIL +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/IStatisticalData.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/IStatisticalData.java new file mode 100644 index 0000000000000000000000000000000000000000..a9b85a92c55dd9492209c54aaced534e4eaa858f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/IStatisticalData.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.nodetypes; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.opengauss.mppdbide.presentation.objectproperties.DNIntraNodeDetailsColumn; + +/** + * + * Title: interface + * + * Description: The Interface IStatisticalData. + * + * @since 3.0.0 + */ +public interface IStatisticalData { + + /** + * Gets the total cost. + * + * @return the total cost + */ + double getTotalCost(); + + /** + * Gets the actual max time taken. + * + * @return the actual max time taken + */ + double getActualMaxTimeTaken(); + + /** + * Gets the actual rows. + * + * @return the actual rows + */ + long getActualRows(); + + /** + * Gets the actual total time. + * + * @return the actual total time + */ + double getActualTotalTime(); + + /** + * Gets the node specific properties. + * + * @return the node specific properties + */ + List getNodeSpecificProperties(); + + /** + * Gets the per DN specific details. + * + * @param inputMap the input map + * @param detailsNeeded the details needed + * @return the per DN specific details + */ + Map> getPerDNSpecificDetails(Map> inputMap, + ArrayList detailsNeeded); + + /** + * Gets the per DN specific details. + * + * @param inputMap the input map + * @return the per DN specific details + */ + Map> getPerDNSpecificDetails(Map> inputMap); + + /** + * Gets the per DN specific column grouping info. + * + * @param colGroup the col group + * @param detailsNeeded the details needed + * @return the per DN specific column grouping info + */ + List getPerDNSpecificColumnGroupingInfo(List colGroup, + ArrayList detailsNeeded); + + /** + * Gets the per DN specific column grouping info. + * + * @param colGroup the col group + * @return the per DN specific column grouping info + */ + List getPerDNSpecificColumnGroupingInfo(List colGroup); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/LLVMDNDetails.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/LLVMDNDetails.java new file mode 100644 index 0000000000000000000000000000000000000000..499b9ce6160f0bbf7626a87ef1c81987552d103c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/LLVMDNDetails.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.nodetypes; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.presentation.objectproperties.DNIntraNodeDetailsColumn; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class LLVMDNDetails. + * + * @since 3.0.0 + */ +public class LLVMDNDetails { + @SerializedName("DN Name") + private String dnName; + + @SerializedName("LLVM") + private String llvm; + + /** + * Gets the dn name. + * + * @return the dn name + */ + public String getDnName() { + return dnName; + } + + /** + * Gets the llvm. + * + * @return the llvm + */ + public String getLlvm() { + return llvm; + } + + /** + * Property details. + * + * @return the list + */ + public List propertyDetails() { + ArrayList colInfo = new ArrayList(5); + + colInfo.add(getLlvm()); + return colInfo; + } + + /** + * Fill column property header. + * + * @return the DN intra node details column + */ + public static DNIntraNodeDetailsColumn fillColumnPropertyHeader() { + DNIntraNodeDetailsColumn dnLlvmDetails = new DNIntraNodeDetailsColumn(); + + dnLlvmDetails.setGroupColumnName( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_PERDN_LLVM_COLUMNGRP)); + + ArrayList colnames = new ArrayList(5); + colnames.add(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_PERDN_LLVM_COLUMN)); + + dnLlvmDetails.setColCount(1); + dnLlvmDetails.setColnames(colnames); + + return dnLlvmDetails; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/NodeCategoryEnum.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/NodeCategoryEnum.java new file mode 100644 index 0000000000000000000000000000000000000000..238ee3a982510505a6a92a8ca3a5dc89b56cb69c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/NodeCategoryEnum.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.nodetypes; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: enum + * + * Description: The Enum NodeCategoryEnum. + * + * @since 3.0.0 + */ +public enum NodeCategoryEnum { + AGGREGATE(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_AGGREGATE)), + + FUNCTION(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_FUNCTION)), + + GROUPAGGREGATE(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_GROUPAGGREGATE)), + + HASH(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_HASH)), + + HASHJOIN(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_HASHJOIN)), + + MODIFYTABLE(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_MODIFYTABLE)), + + NESTLOOPJOIN(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_NESTLOOPJOIN)), + + NESTEDLOOP(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_NESTEDLOOP)), + + PARTITIONITERATOR(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_PARTITIONITERATOR)), + + ROWADAPTER(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_ROWADAPTER)), + + SCAN(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_SCAN)), + + SETOP(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_SETOP)), + + SORT(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_SORT)), + + STREAM(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_STREAM)), + + UNKNOWN(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_UNKNOWN)), + + UNION(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_UNION)); + + private final String categoryName; + + private NodeCategoryEnum(String name) { + this.categoryName = name; + } + + /** + * Gets the category name. + * + * @return the category name + */ + public String getCategoryName() { + return this.categoryName; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/OperationalNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/OperationalNode.java new file mode 100644 index 0000000000000000000000000000000000000000..67521c85a54ffa2e69125be734c3a3630abc957d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/OperationalNode.java @@ -0,0 +1,330 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.nodetypes; + +import java.beans.PropertyChangeListener; +import java.beans.PropertyChangeSupport; +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class OperationalNode. + * + * @since 3.0.0 + */ +public abstract class OperationalNode extends BasicNode { + + private PropertyChangeSupport listeners; + + /** + * The Constant PROPERTY_LAYOUT. + */ + public static final String PROPERTY_LAYOUT = "Nodelayout"; + + /** + * The max file num. + */ + @SerializedName("Max File Num") + protected long maxFileNum; + + /** + * The min file num. + */ + @SerializedName("Min File Num") + protected long minFileNum; + + /** + * The max memory used. + */ + @SerializedName("Max Memory Used") + protected double maxMemoryUsed; + + /** + * The min memory used. + */ + @SerializedName("Min Memory Used") + protected long minMemoryUsed; + + /** + * The parent. + */ + protected OperationalNode parent; + + /** + * Sets the parent. + * + * @param parent the new parent + */ + public void setParent(OperationalNode parent) { + this.parent = parent; + } + + /** + * The children. + */ + protected ArrayList children; + + /** + * The indentation level. + */ + private int indentationLevel; + + /** + * Instantiates a new operational node. + * + * @param nodetype the nodetype + */ + public OperationalNode(NodeCategoryEnum nodetype) { + super(nodetype); + children = new ArrayList(0); + this.listeners = new PropertyChangeSupport(this); + } + + /** + * Adds the child node. + * + * @param childnode the childnode + */ + public void addChildNode(OperationalNode childnode) { + children.add(childnode); + } + + /** + * Adds the indentation level. + * + * @param indentationlevel the indentationlevel + */ + public void setIndentationLevel(int level) { + this.indentationLevel = level; + } + + /** + * Adds the property change listener. + * + * @param listener the listener + */ + public void addPropertyChangeListener(PropertyChangeListener listener) { + listeners.addPropertyChangeListener(listener); + } + + /** + * Gets the listeners. + * + * @return the listeners + */ + public PropertyChangeSupport getListeners() { + return listeners; + } + + /** + * Removes the property change listener. + * + * @param listener the listener + */ + public void removePropertyChangeListener(PropertyChangeListener listener) { + listeners.removePropertyChangeListener(listener); + } + + /** + * To string. + * + * @return the string + */ + public String toString() { + String chilNodeInfo = null; + if (this.children.size() == 0) { + return super.toString(); + } + + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + int index = 1; + + for (BasicNode child : this.children) { + sb.append(index + ". "); + sb.append(child.toString()); + sb.append(System.lineSeparator()); + index++; + } + + chilNodeInfo = sb.toString(); + + return super.toString() + System.lineSeparator() + chilNodeInfo; + } + + /** + * Gets the children. + * + * @return the children + */ + public ArrayList getChildren() { + return children; + } + + /** + * Gets the parent. + * + * @return the parent + */ + public OperationalNode getParent() { + return this.parent; + } + + /** + * Gets the indentation level. + * + * @return the indentation level + */ + public int getIndentationLevel() { + return this.indentationLevel; + } + + /** + * Gets the output. + * + * @return the output + */ + public String[] getOutput() { + if (this.output != null) { + return this.output.clone(); + } + return new String[0]; + + } + + /** + * Gets the node specific. + * + * @return the node specific + */ + public List getNodeSpecific() { + + return null; + } + + /** + * Gets the DN involved. + * + * @param dnsInvolved the dns involved + * @return the DN involved + */ + public ArrayList getDNInvolved(ArrayList dnsInvolved) { + return super.getDNInvolved(dnsInvolved); + } + + /** + * Gets the node specific properties. + * + * @return the node specific properties + */ + @Override + public List getNodeSpecificProperties() { + List output = super.getNodeSpecificProperties(); + + if (1 == this.getChildren().size()) { + output.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_OPERATIONALNODE_CHILD1NAME), + this.getChildren().get(0).getNodeType()).getProp()); + } else if (2 == this.getChildren().size()) { + output.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_OPERATIONALNODE_CHILD1NAME), + this.getChildren().get(0).getNodeType()).getProp()); + output.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_OPERATIONALNODE_CHILD2NAME), + this.getChildren().get(1).getNodeType()).getProp()); + } else if (2 < this.getChildren().size()) { + int index = 1; + + for (OperationalNode c : this.getChildren()) { + output.add(new ServerProperty( + MessageConfigLoader.getProperty( + IMessagesConstants.VIS_EXPLAIN_PROP_OPERATIONALNODE_CHILDRENNAME) + '-' + index, + c.getNodeType()).getProp()); + index++; + } + + } + + return output; + + } + + /** + * Gets the item name. + * + * @return the item name + */ + public String getItemName() { + + return null; + } + + /** + * Gets the item details. + * + * @return the item details + */ + public String getItemDetails() { + + return null; + } + + /** + * Gets the entity name. + * + * @return the entity name + */ + public String getEntityName() { + + return null; + } + + /** + * To text. + * + * @param isAnalyze the is analyze + * @return the string + */ + public String toText(boolean isAnalyze) { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append(getNodeType()); + sb.append(" "); + sb.append(getCostInfoForTextDisplay(isAnalyze)); + return sb.toString(); + } + + /** + * Inits the detail array. + * + * @param indetailscategories the indetailscategories + * @return the array list + */ + protected ArrayList initDetailArray(INDETAILSCATEGORY... indetailscategories) { + ArrayList detailsNeeded = new ArrayList(5); + for (INDETAILSCATEGORY field : indetailscategories) { + detailsNeeded.add(field); + } + return detailsNeeded; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/OperationalNodeDeserializer.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/OperationalNodeDeserializer.java new file mode 100644 index 0000000000000000000000000000000000000000..12cc5ccf9380cb8de1d5f3966203354242aa7d6e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/OperationalNodeDeserializer.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.nodetypes; + +import java.lang.reflect.Type; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import org.opengauss.mppdbide.explainplan.plannode.factory.GetNodeFromFactory; + +/** + * + * Title: class + * + * Description: The Class OperationalNodeDeserializer. + * + * @since 3.0.0 + */ +public class OperationalNodeDeserializer implements JsonDeserializer { + + @Override + public OperationalNode deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) + throws JsonParseException { + + final JsonObject jsonObject = json.getAsJsonObject(); + OperationalNode node = null; + + String nodeType = jsonObject.get("Node Type").getAsString(); + + Class concreteClass = GetNodeFromFactory.getClass(nodeType); + Object obj = new Gson().fromJson(json, concreteClass); + + if (obj != null && obj instanceof OperationalNode) { + node = (OperationalNode) obj; + + JsonElement json2 = jsonObject.getAsJsonObject().get("Plans"); + if (null != json2) { + JsonArray array = json2.getAsJsonArray(); + int size = array.size(); + OperationalNode childnode = null; + for (int i = 0; i < size; i++) { + childnode = context.deserialize(array.get(i), OperationalNode.class); + node.addChildNode(childnode); + } + } + } + + return node; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/RootPlanNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/RootPlanNode.java new file mode 100644 index 0000000000000000000000000000000000000000..9be735f5b8636272d7388d24c74f2afb31753686 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/RootPlanNode.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.nodetypes; + +import java.util.List; + +import com.google.gson.annotations.SerializedName; + +/** + * + * Title: class + * + * Description: The Class RootPlanNode. + * + * @since 3.0.0 + */ +public class RootPlanNode extends OperationalNode { + + /** + * The total run time. + */ + @SerializedName("Total Runtime") + protected double totalRunTime; + + /** + * The triggers. + */ + @SerializedName("Triggers") + protected List triggers; + + /** + * Instantiates a new root plan node. + */ + public RootPlanNode() { + super(NodeCategoryEnum.UNKNOWN); + } + + /** + * Gets the total runtime. + * + * @return the total runtime + */ + public double getTotalRuntime() { + return totalRunTime; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/RootPlanNodeDeserializer.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/RootPlanNodeDeserializer.java new file mode 100644 index 0000000000000000000000000000000000000000..aff1d6ebea6194643a25b00271d750b3e28a60e8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/RootPlanNodeDeserializer.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.nodetypes; + +import java.lang.reflect.Type; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +/** + * + * Title: class + * + * Description: The Class RootPlanNodeDeserializer. + * + * @since 3.0.0 + */ +public class RootPlanNodeDeserializer implements JsonDeserializer { + + @Override + public RootPlanNode deserialize(final JsonElement json, final Type typeOfT, + final JsonDeserializationContext context) throws JsonParseException { + JsonArray array = json.getAsJsonArray(); + if (array.size() <= 0) { + return null; + } + + JsonObject obj = array.get(0).getAsJsonObject(); + + JsonElement json1 = obj.get("Plan"); + + RootPlanNode root = new Gson().fromJson(obj, RootPlanNode.class); + + OperationalNode childnode = context.deserialize(json1, OperationalNode.class); + + root.addChildNode(childnode); + + return root; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/SetopDetail.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/SetopDetail.java new file mode 100644 index 0000000000000000000000000000000000000000..5796becb2763b6ee8167a657d5c570bc1611fb24 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/nodetypes/SetopDetail.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.nodetypes; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.presentation.objectproperties.DNIntraNodeDetailsColumn; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class SetopDetail. + * + * @since 3.0.0 + */ +public class SetopDetail { + @SerializedName("DN Name") + private String dnName; + + @SerializedName("Temp File Num") + private long tempFileNum; + + /** + * Property details. + * + * @return the list + */ + public List propertyDetails() { + ArrayList colInfo = new ArrayList(5); + + colInfo.add(getTempFileNum()); + + return colInfo; + } + + /** + * Fill column property header. + * + * @return the DN intra node details column + */ + public static DNIntraNodeDetailsColumn fillColumnPropertyHeader() { + DNIntraNodeDetailsColumn dnBufferInDetail = new DNIntraNodeDetailsColumn(); + + dnBufferInDetail.setGroupColumnName( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_PERDN_SETOPDETAIL)); + + ArrayList colnames = new ArrayList(1); + colnames.add(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_SETOPNODE_TEMPFILENUM)); + + dnBufferInDetail.setColCount(1); + dnBufferInDetail.setColnames(colnames); + + return dnBufferInDetail; + } + + /** + * Gets the dn name. + * + * @return the dn name + */ + public String getDnName() { + return dnName; + } + + private long getTempFileNum() { + return tempFileNum; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/AbstractStreamNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/AbstractStreamNode.java new file mode 100644 index 0000000000000000000000000000000000000000..76382fd93c88a2e89c02a12bedda9b476c963448 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/AbstractStreamNode.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.explainplan.nodetypes.NodeCategoryEnum; +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class AbstractStreamNode. + * + * @since 3.0.0 + */ +public abstract class AbstractStreamNode extends OperationalNode { + + /** + * The spawn on. + */ + @SerializedName("Spawn on") + protected String spawnOn = ""; + + /** + * Instantiates a new abstract stream node. + */ + public AbstractStreamNode() { + super(NodeCategoryEnum.STREAM); + } + + @Override + public String toText(boolean isAnalyze) { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append(getNodeType()); + sb.append(" "); + sb.append(getCostInfoForTextDisplay(isAnalyze)); + return sb.toString(); + } + + @Override + public List getAdditionalInfo(boolean isAnalyze) { + List list = new ArrayList(1); + List otherInfo = super.getAdditionalInfo(isAnalyze); + list.addAll(otherInfo); + + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + if (!"".equals(spawnOn)) { + sb.append("Spawn on: "); + sb.append(spawnOn); + list.add(sb.toString()); + } + return list; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/AggregateDetail.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/AggregateDetail.java new file mode 100644 index 0000000000000000000000000000000000000000..6b4c288857d9d09f42ccf875ac0f0519781e87f3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/AggregateDetail.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import com.google.gson.annotations.SerializedName; + +/** + * + * Title: class + * + * Description: The Class AggregateDetail. + * + * @since 3.0.0 + */ +public class AggregateDetail { + + /** + * The dn Name + */ + @SerializedName("DN Name") + protected String dnName; + + /** + * The tempFile Num + */ + @SerializedName("Temp File Num") + protected int tempFileNum; + + /** + * Gets the dn name. + * + * @return the dn name + */ + public String getDnName() { + return dnName; + } + + /** + * Gets the temp file num. + * + * @return the temp file num + */ + public int getTempFileNum() { + return tempFileNum; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/CStoreScanNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/CStoreScanNode.java new file mode 100644 index 0000000000000000000000000000000000000000..fdcbea1e5e5dc95d24a42613d559b78b359c12cd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/CStoreScanNode.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.opengauss.mppdbide.explainplan.nodetypes.INDETAILSCATEGORY; + +/** + * + * Title: class + * + * Description: The Class CStoreScanNode. + * + * @since 3.0.0 + */ +public class CStoreScanNode extends ScanNode { + + /** + * Instantiates a new c store scan node. + */ + public CStoreScanNode() { + super(); + } + + @Override + public List getAdditionalInfo(boolean isAnalyze) { + return getNodeSpecific(); + } + + @Override + public List getNodeSpecific() { + return super.getNodeSpecific(); + } + + @Override + public List getNodeSpecificProperties() { + List moreInfo = super.getNodeSpecificProperties(); + + ArrayList arList = new ArrayList(5); + + arList.addAll(moreInfo); + + addPropFilter(arList); + addPropRowsRemovedByFilter(arList); + + return arList; + } + + @Override + public Map> getPerDNSpecificDetails(Map> inputMap) { + ArrayList detailsNeeded = new ArrayList(5); + detailsNeeded.add(INDETAILSCATEGORY.ACTUALS_IN_DETAIL); + detailsNeeded.add(INDETAILSCATEGORY.CPU_IN_DETAIL); + detailsNeeded.add(INDETAILSCATEGORY.LLVM_DETAIL); + detailsNeeded.add(INDETAILSCATEGORY.BUFFERS_IN_DETAIL); + + Map> output = super.getPerDNSpecificDetails(inputMap, detailsNeeded); + + return output; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/CTEScanNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/CTEScanNode.java new file mode 100644 index 0000000000000000000000000000000000000000..d7d6a3201b363f19f21a66ba8c3aa0981c218199 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/CTEScanNode.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.explainplan.nodetypes.INDETAILSCATEGORY; +import org.opengauss.mppdbide.explainplan.nodetypes.NodeCategoryEnum; +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class CTEScanNode. + * + * @since 3.0.0 + */ +public class CTEScanNode extends OperationalNode { + + /** + * The cte name. + */ + @SerializedName("CTE Name") + protected String cteName = ""; + + /** + * The alias. + */ + @SerializedName("Alias") + protected String alias = ""; + + /** + * Instantiates a new CTE scan node. + */ + public CTEScanNode() { + super(NodeCategoryEnum.SCAN); + } + + @Override + public List getNodeSpecific() { + ArrayList list = new ArrayList(1); + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + if (!"".equals(cteName)) { + sb.append("CTE Name: ").append(cteName); + list.add(sb.toString()); + } + + if (!"".equals(alias)) { + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Alias: ").append(alias); + list.add(sb.toString()); + } + + return list; + } + + @Override + public List getNodeSpecificProperties() { + return super.getNodeSpecificProperties(); + } + + @Override + public Map> getPerDNSpecificDetails(Map> inputMap) { + ArrayList detailsNeeded = initDetailArray(INDETAILSCATEGORY.BUFFERS_IN_DETAIL, + INDETAILSCATEGORY.CPU_IN_DETAIL, INDETAILSCATEGORY.ACTUALS_IN_DETAIL); + Map> output = super.getPerDNSpecificDetails(inputMap, detailsNeeded); + + return output; + } + + @Override + public String getItemName() { + if (!"".equals(cteName)) { + return "CTE: " + this.cteName; + } + + return null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/DataNodeScan.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/DataNodeScan.java new file mode 100644 index 0000000000000000000000000000000000000000..912a8088227be57720be414df62cfbd8f0760dfe --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/DataNodeScan.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.StringEscapeUtils; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class DataNodeScan. + * + * @since 3.0.0 + */ +public class DataNodeScan extends ScanNode { + + /** + * The primary node count. + */ + @SerializedName("Primary node count") + protected long primaryNodeCount; + + /** + * The node count. + */ + @SerializedName("Node count") + protected long nodeCount; + + /** + * The remote query. + */ + @SerializedName("Remote Query") + protected String remoteQuery = ""; + + /** + * Instantiates a new data node scan. + */ + public DataNodeScan() { + super(); + } + + @Override + public List getNodeSpecific() { + ArrayList list = new ArrayList(1); + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_DATANODESCAN_PRIMARYNODECOUNT)) + .append(": ").append(primaryNodeCount); + list.add(sb.toString()); + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_DATANODESCAN_NODECOUNT)) + .append(": ").append(nodeCount); + list.add(sb.toString()); + + if (!"".equals(remoteQuery)) { + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_NODE_REMOTEQUERY)) + .append(": ").append(StringEscapeUtils.escapeHtml(remoteQuery)); + list.add(sb.toString()); + } + + return list; + } + + @Override + public List getNodeSpecificProperties() { + List moreInfo = super.getNodeSpecificProperties(); + + ArrayList arList = new ArrayList(5); + + arList.addAll(moreInfo); + + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_DATANODESCAN_PRIMARYNODECOUNT), + primaryNodeCount).getProp()); + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_DATANODESCAN_NODECOUNT), nodeCount) + .getProp()); + + if (!"".equals(remoteQuery)) { + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_NODE_REMOTEQUERY), + StringEscapeUtils.escapeHtml(remoteQuery)).getProp()); + } + return arList; + } + + @Override + public Map> getPerDNSpecificDetails(Map> inputMap) { + Map> output = super.getPerDNSpecificDetails(inputMap); + + return output; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/FunctionScanNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/FunctionScanNode.java new file mode 100644 index 0000000000000000000000000000000000000000..b86ddf1fd40fa4405329c64c768d1de8f96181ec --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/FunctionScanNode.java @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.explainplan.nodetypes.INDETAILSCATEGORY; +import org.opengauss.mppdbide.explainplan.nodetypes.NodeCategoryEnum; +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class FunctionScanNode. + * + * @since 3.0.0 + */ +public class FunctionScanNode extends OperationalNode { + + /** + * The function name. + */ + @SerializedName("Function Name") + protected String functionName = ""; + + /** + * The alias. + */ + @SerializedName("Alias") + protected String alias = ""; + + /** + * The function call. + */ + @SerializedName("Function Call") + protected String functionCall = ""; + + /** + * The schema. + */ + @SerializedName("Schema") + protected String schema = ""; + + /** + * Instantiates a new function scan node. + */ + public FunctionScanNode() { + super(NodeCategoryEnum.FUNCTION); + } + + /** + * Gets the node specific. + * + * @return the node specific + */ + @Override + public List getNodeSpecific() { + ArrayList list = new ArrayList(1); + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + sb.append("Function Name: ").append(functionName); + list.add(sb.toString()); + + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Alias: ").append(alias); + list.add(sb.toString()); + + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Schema: ").append(schema); + list.add(sb.toString()); + + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Function Call: ").append(functionCall); + list.add(sb.toString()); + return list; + } + + /** + * Gets the node specific properties. + * + * @return the node specific properties + */ + @Override + public List getNodeSpecificProperties() { + List moreInfo = super.getNodeSpecificProperties(); + + ArrayList arList = new ArrayList(5); + + arList.addAll(moreInfo); + + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_FUNCTIONSCANNODE_FUNCTIONNAME), + functionName).getProp()); + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_FUNCTIONSCANNODE_FUNCTIONALIASNAME), + alias).getProp()); + + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_FUNCTIONSCANNODE_SCHEMANAME), + schema).getProp()); + + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_FUNCTIONSCANNODE_FUNCTIONCALL), + functionCall).getProp()); + + return arList; + } + + /** + * Gets the per DN specific details. + * + * @param inputMap the input map + * @return the per DN specific details + */ + @Override + public Map> getPerDNSpecificDetails(Map> inputMap) { + ArrayList detailsNeeded = initDetailArray(INDETAILSCATEGORY.ACTUALS_IN_DETAIL, + INDETAILSCATEGORY.CPU_IN_DETAIL); + Map> output = super.getPerDNSpecificDetails(inputMap, detailsNeeded); + + return output; + } + + /** + * Gets the item name. + * + * @return the item name + */ + @Override + public String getItemName() { + return "Function: " + this.functionName; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/GroupBy.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/GroupBy.java new file mode 100644 index 0000000000000000000000000000000000000000..489d915a4e4c37d16e715c9dd80bc178dc49ef54 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/GroupBy.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.explainplan.nodetypes.NodeCategoryEnum; +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.utils.CustomStringUtility; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class GroupBy. + * + * @since 3.0.0 + */ +public class GroupBy extends OperationalNode { + + /** + * Instantiates a new group by. + */ + public GroupBy() { + super(NodeCategoryEnum.GROUPAGGREGATE); + } + + /** + * The group by key. + */ + @SerializedName("Group By Key") + protected List groupByKey; + + /** + * The details. + */ + @SerializedName("Aggregate Detail") + protected List details; + + /** + * Gets the node specific. + * + * @return the node specific + */ + @Override + public List getNodeSpecific() { + return groupByKey; + } + + /** + * Gets the node specific properties. + * + * @return the node specific properties + */ + @Override + public List getNodeSpecificProperties() { + List moreInfo = super.getNodeSpecificProperties(); + + ArrayList arList = new ArrayList(5); + + arList.addAll(moreInfo); + + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_GROUP_BY_GRPBYKEYS), + CustomStringUtility.getFormatedOutput(groupByKey, ",")).getProp()); + return arList; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/HashAggregate.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/HashAggregate.java new file mode 100644 index 0000000000000000000000000000000000000000..bee3ba1a0b77a1dd29fba2db5b0f99871947de0f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/HashAggregate.java @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.explainplan.nodetypes.ActualInDetail; +import org.opengauss.mppdbide.explainplan.nodetypes.INDETAILSCATEGORY; +import org.opengauss.mppdbide.explainplan.nodetypes.NodeCategoryEnum; +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.presentation.objectproperties.DNIntraNodeDetailsColumn; +import org.opengauss.mppdbide.utils.CustomStringUtility; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class HashAggregate. + * + * @since 3.0.0 + */ +public class HashAggregate extends OperationalNode { + + /** + * The group by key. + */ + @SerializedName("Group By Key") + protected List groupByKey; + + /** + * The aggregate details. + */ + @SerializedName("Aggregate Detail") + protected List aggregateDetails; + + /** + * The strategy. + */ + @SerializedName("Strategy") + protected String strategy = ""; + + /** + * The filter. + */ + @SerializedName("Filter") + protected String filter = ""; + + @SerializedName("Rows Removed by Filter") + private long rowsRemovedbyFilter; + + /** + * Instantiates a new hash aggregate. + */ + public HashAggregate() { + super(NodeCategoryEnum.AGGREGATE); + } + + /** + * Gets the additional info. + * + * @param isAnalyze the is analyze + * @return the additional info + */ + @Override + public List getAdditionalInfo(boolean isAnalyze) { + ArrayList list = new ArrayList(1); + + if (groupByKey != null && groupByKey.size() != 0) { + StringBuilder sb = new StringBuilder("Group By Key: "); + int index = 0; + for (String s : this.groupByKey) { + if (index != 0) { + sb.append(", "); + } + sb.append(s); + index++; + } + list.add(sb.toString()); + } + if (!"".equals(filter)) { + StringBuilder sb = new StringBuilder("Filter: "); + sb.append(filter); + list.add(sb.toString()); + } + if (rowsRemovedbyFilter != 0) { + StringBuilder sb = new StringBuilder("Rows Removed by Filter: "); + sb.append(rowsRemovedbyFilter); + list.add(sb.toString()); + } + if (maxFileNum != 0 || minFileNum != 0) { + StringBuilder sb = new StringBuilder("Max File Num: "); + sb.append(maxFileNum); + sb.append(" Min File Num: "); + sb.append(minFileNum); + list.add(sb.toString()); + } + return list; + } + + /** + * Gets the node specific properties. + * + * @return the node specific properties + */ + @Override + public List getNodeSpecificProperties() { + List moreInfo = super.getNodeSpecificProperties(); + + ArrayList arList = new ArrayList(5); + + arList.addAll(moreInfo); + if (null != this.groupByKey) { + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_GROUP_BY_GRPBYKEYS), + CustomStringUtility.getFormatedOutput(groupByKey, ",")).getProp()); + } + return arList; + } + + /** + * Gets the per DN specific details. + * + * @param inputMap the input map + * @return the per DN specific details + */ + @Override + public Map> getPerDNSpecificDetails(Map> inputMap) { + ArrayList detailsNeeded = initDetailArray(INDETAILSCATEGORY.ACTUALS_IN_DETAIL, + INDETAILSCATEGORY.CPU_IN_DETAIL); + + Map> output = super.getPerDNSpecificDetails(inputMap, detailsNeeded); + + if (this.aggregateDetails != null) { + List propsValues = null; + for (AggregateDetail entry : aggregateDetails) { + propsValues = buildHashAggreagateNodePropertyDetails(entry); + if (!output.containsKey(entry.getDnName())) { + output.put(entry.getDnName(), propsValues); + } else { + output.get(entry.getDnName()).addAll(propsValues); + } + } + + } + + return output; + } + + private List buildHashAggreagateNodePropertyDetails(AggregateDetail element) { + ArrayList colInfo = new ArrayList(5); + ActualInDetail outer = !this.getChildren().isEmpty() + ? this.getChildren().get(0).getActualsByDNName(element.getDnName()) + : null; + if (outer != null) { + colInfo.add(outer.getActualRows()); + } + colInfo.add(element.getTempFileNum()); + + return colInfo; + } + + private static List + buildHashAggregateNodePropertyColumnGroupingInfo(List colGroup) { + DNIntraNodeDetailsColumn dnActualsInDetail = new DNIntraNodeDetailsColumn(); + + dnActualsInDetail.setGroupColumnName( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_PERDN_AGGREGATEINDETAIL)); + + ArrayList colnames = new ArrayList(5); + colnames.add("Outer node- Rows"); + colnames.add("Temp File Num"); + dnActualsInDetail.setColCount(2); + dnActualsInDetail.setColnames(colnames); + + colGroup.add(dnActualsInDetail); + + return colGroup; + + } + + /** + * Gets the per DN specific column grouping info. + * + * @param colGroupParam the col group param + * @return the per DN specific column grouping info + */ + @Override + public List + getPerDNSpecificColumnGroupingInfo(List colGroupParam) { + List colGroup = colGroupParam; + ArrayList detailsNeeded = new ArrayList(5); + detailsNeeded.add(INDETAILSCATEGORY.CPU_IN_DETAIL); + detailsNeeded.add(INDETAILSCATEGORY.ACTUALS_IN_DETAIL); + + colGroup = super.getPerDNSpecificColumnGroupingInfo(colGroup, detailsNeeded); + if (this.aggregateDetails != null) { + colGroup = buildHashAggregateNodePropertyColumnGroupingInfo(colGroup); + } + return colGroup; + } + + /** + * Gets the node type. + * + * @return the node type + */ + @Override + public String getNodeType() { + if ("Hashed".equals(strategy)) { + return "HashAggregate"; + } else if ("Sorted".equals(strategy)) { + return "GroupAggregate"; + } else if ("Mixed".equals(strategy)) { + return "MixedAggregate"; + } + return super.getNodeType(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/HashJoin.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/HashJoin.java new file mode 100644 index 0000000000000000000000000000000000000000..78e952ae49d90a2b77064f02015476760e2680d6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/HashJoin.java @@ -0,0 +1,288 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.explainplan.nodetypes.ActualInDetail; +import org.opengauss.mppdbide.explainplan.nodetypes.HashJoinDNDetails; +import org.opengauss.mppdbide.explainplan.nodetypes.INDETAILSCATEGORY; +import org.opengauss.mppdbide.explainplan.nodetypes.NodeCategoryEnum; +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.presentation.objectproperties.DNIntraNodeDetailsColumn; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class HashJoin. + * + * @since 3.0.0 + */ +public class HashJoin extends OperationalNode { + + /** + * The hash condition. + */ + @SerializedName("Hash Cond") + protected String hashCondition = ""; + + /** + * The join type. + */ + @SerializedName("Join Type") + protected String joinType = ""; + + /** + * The join D ndetails. + */ + @SerializedName("VecJoin Detail") + protected List joinDNdetails; + + /** + * The join filter. + */ + @SerializedName("Join Filter") + protected String joinFilter = ""; + + /** + * The rows removed by join filter. + */ + @SerializedName("Rows Removed by Join Filter") + protected String rowsRemovedByJoinFilter = ""; + + /** + * Instantiates a new hash join. + */ + public HashJoin() { + super(NodeCategoryEnum.HASHJOIN); + } + + /** + * Gets the additional info. + * + * @param isAnalyze the is analyze + * @return the additional info + */ + @Override + public List getAdditionalInfo(boolean isAnalyze) { + List addi = new ArrayList(1); + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Hash Cond: "); + sb.append(hashCondition); + addi.add(sb.toString()); + + if (!"".equals(joinFilter)) { + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Join Filter: "); + sb.append(joinFilter); + addi.add(sb.toString()); + } + + if (!"".equals(rowsRemovedByJoinFilter)) { + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Rows Removed by Join Filter: "); + sb.append(rowsRemovedByJoinFilter); + addi.add(sb.toString()); + } + return addi; + } + + /** + * To text. + * + * @param isAnalyze the is analyze + * @return the string + */ + @Override + public String toText(boolean isAnalyze) { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append(getNodeName()); + sb.append(" "); + sb.append(getCostInfoForTextDisplay(isAnalyze)); + return sb.toString(); + } + + /** + * Gets the node specific. + * + * @return the node specific + */ + @Override + public List getNodeSpecific() { + ArrayList list = new ArrayList(1); + list.add(this.hashCondition); + return list; + } + + /** + * Gets the node specific properties. + * + * @return the node specific properties + */ + @Override + public List getNodeSpecificProperties() { + List moreInfo = super.getNodeSpecificProperties(); + + ArrayList arList = new ArrayList(5); + + arList.addAll(moreInfo); + + arList.add( + new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_JOIN_JOINTYPE), + joinType).getProp()); + + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_HASH_JOIN_JOINCOND), hashCondition) + .getProp()); + return arList; + } + + /** + * Gets the per DN specific details. + * + * @param inputMap the input map + * @return the per DN specific details + */ + @Override + public Map> getPerDNSpecificDetails(Map> inputMap) { + ArrayList detailsNeeded = initDetailArray(INDETAILSCATEGORY.ACTUALS_IN_DETAIL, + INDETAILSCATEGORY.CPU_IN_DETAIL, INDETAILSCATEGORY.BUFFERS_IN_DETAIL, INDETAILSCATEGORY.LLVM_DETAIL); + + Map> output = super.getPerDNSpecificDetails(inputMap, detailsNeeded); + + if (this.joinDNdetails != null && this.joinDNdetails.size() > 0) { + List propsValues = null; + for (HashJoinDNDetails entry : joinDNdetails) { + propsValues = buildhashNodePropertyDetails(entry); + if (!output.containsKey(entry.getDnName())) { + output.put(entry.getDnName(), propsValues); + } else { + output.get(entry.getDnName()).addAll(propsValues); + } + } + + } + + return output; + } + + private List buildhashNodePropertyDetails(HashJoinDNDetails hash) { + ArrayList colInfo = new ArrayList(5); + String dnName = hash.getDnName(); + ActualInDetail innerActInDetail = this.getChildren().size() >= 2 + ? this.getChildren().get(1).getActualsByDNName(dnName) + : null; + ActualInDetail outerActInDetail = this.getChildren().size() >= 1 + ? this.getChildren().get(0).getActualsByDNName(dnName) + : null; + ActualInDetail hashNodeInDetail = this.getActualsByDNName(dnName); + + colInfo.add((innerActInDetail == null) ? 0 : innerActInDetail.getActualRows()); + colInfo.add((outerActInDetail == null) ? 0 : outerActInDetail.getActualRows()); + colInfo.add((hashNodeInDetail == null) ? 0 : hashNodeInDetail.getActualRows()); + colInfo.add((innerActInDetail == null) ? 0 : innerActInDetail.getActualStartupTime()); + colInfo.add((outerActInDetail == null) ? 0 : outerActInDetail.getActualStartupTime()); + colInfo.add((hashNodeInDetail == null) ? 0 : hashNodeInDetail.getActualStartupTime()); + + colInfo.add((innerActInDetail == null) ? 0 : innerActInDetail.getActualTotalTime()); + colInfo.add((outerActInDetail == null) ? 0 : outerActInDetail.getActualTotalTime()); + colInfo.add((hashNodeInDetail == null) ? 0 : hashNodeInDetail.getActualTotalTime()); + + colInfo.add(hash.getMemoryUsed()); + return colInfo; + } + + private static List + buildHashNodePropertyColumnGroupingInfo(List colGroup) { + DNIntraNodeDetailsColumn dnActualsInDetail = new DNIntraNodeDetailsColumn(); + + dnActualsInDetail.setGroupColumnName( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_PERDN_JOININDETAIL)); + + ArrayList colnameList = new ArrayList(5); + colnameList.add("Inner node- Rows"); + colnameList.add("Outer Node- Rows"); + colnameList.add("Join Output Rows"); + + colnameList.add("Inner node- Startup Time"); + colnameList.add("Outer Node- Startup Time"); + colnameList.add("Join Node Startup Time"); + + colnameList.add("Inner node- Total Time"); + colnameList.add("Outer Node- Total Time"); + colnameList.add("Join Node Total Time"); + + colnameList.add("Join Node Memory Used"); + dnActualsInDetail.setColCount(10); + dnActualsInDetail.setColnames(colnameList); + + colGroup.add(dnActualsInDetail); + + return colGroup; + + } + + /** + * Gets the per DN specific column grouping info. + * + * @param colGroupParam the col group param + * @return the per DN specific column grouping info + */ + @Override + public List + getPerDNSpecificColumnGroupingInfo(List colGroupParam) { + List colGroup = colGroupParam; + ArrayList detailsNeeded = new ArrayList(5); + detailsNeeded.add(INDETAILSCATEGORY.ACTUALS_IN_DETAIL); + detailsNeeded.add(INDETAILSCATEGORY.CPU_IN_DETAIL); + detailsNeeded.add(INDETAILSCATEGORY.LLVM_DETAIL); + detailsNeeded.add(INDETAILSCATEGORY.BUFFERS_IN_DETAIL); + + colGroup = super.getPerDNSpecificColumnGroupingInfo(colGroup, detailsNeeded); + + if (this.joinDNdetails != null && this.joinDNdetails.size() != 0) { + return buildHashNodePropertyColumnGroupingInfo(colGroup); + } else { + return colGroup; + } + + } + + /** + * Gets the node name. + * + * @return the node name + */ + @Override + public String getNodeName() { + StringBuilder sb = new StringBuilder("Hash "); + // do not include if "Inner" + if ("Right".equals(joinType) || "Semi".equals(joinType) || "Anti".equals(joinType)) { + sb.append(joinType); + } + sb.append(" Join"); + return sb.toString(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/HashNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/HashNode.java new file mode 100644 index 0000000000000000000000000000000000000000..bbbdfb5cd881d771e5a4b3ba0e5b6b0a97a6ec69 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/HashNode.java @@ -0,0 +1,281 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.explainplan.nodetypes.HashDetail; +import org.opengauss.mppdbide.explainplan.nodetypes.INDETAILSCATEGORY; +import org.opengauss.mppdbide.explainplan.nodetypes.NodeCategoryEnum; +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.presentation.objectproperties.DNIntraNodeDetailsColumn; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class HashNode. + * + * @since 3.0.0 + */ +public class HashNode extends OperationalNode { + + /** + * The hash buckets. + */ + @SerializedName("Hash Buckets") + protected long hashBuckets; + + /** + * The hash batches. + */ + @SerializedName("Hash Batches") + protected long hashBatches; + + /** + * The original hash batches. + */ + @SerializedName("Original Hash Batches") + protected long originalHashBatches; + + /** + * The peak memory usage. + */ + @SerializedName("Peak Memory Usage") + protected long peakMemoryUsage; + + /** + * The hash detail. + */ + @SerializedName("Hash Detail") + protected List hashDetail; + + @SerializedName("Max Hash Buckets") + private long maxHashBuckets; + @SerializedName("Min Hash Buckets") + private long minHashBuckets; + @SerializedName("Max Hash Batches") + private long maxHashBatches; + @SerializedName("Min Hash Batches") + private long minHashBatches; + @SerializedName("Max Peak Memory Usage") + private long maxMemoryUsage; + @SerializedName("min Peak Memory Usage") + private long minMemoryUsage; + @SerializedName("Max Original Hash Batches") + private long maxOriginalBatches; + @SerializedName("Min Original Hash Batches") + private long minOriginalBatches; + + /** + * Instantiates a new hash node. + */ + public HashNode() { + super(NodeCategoryEnum.HASH); + } + + /** + * Gets the additional info. + * + * @param isAnalyze the is analyze + * @return the additional info + */ + @Override + public List getAdditionalInfo(boolean isAnalyze) { + List list = new ArrayList(1); + List otherInfo = super.getAdditionalInfo(isAnalyze); + list.addAll(otherInfo); + + if (hashBatches > 0) { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Buckets: "); + sb.append(hashBuckets); + sb.append(" Batches: "); + sb.append(hashBatches); + sb.append(" Memory Usage: "); + sb.append(peakMemoryUsage); + list.add(sb.toString()); + } + if (isAnalyze) { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Max Buckets: "); + sb.append(maxHashBuckets); + sb.append(" Max Batches: "); + sb.append(maxHashBatches); + if (maxHashBatches != maxOriginalBatches || minHashBatches != minOriginalBatches) { + sb.append(" (max originally "); + sb.append(maxOriginalBatches); + sb.append(") "); + } + sb.append(" Max Memory Usage: "); + sb.append(maxMemoryUsage); + sb.append("kB"); + + list.add(sb.toString()); + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Min Buckets: "); + sb.append(minHashBuckets); + sb.append(" Min Batches: "); + sb.append(minHashBatches); + if (maxHashBatches != maxOriginalBatches || minHashBatches != minOriginalBatches) { + sb.append(" (min originally "); + sb.append(minOriginalBatches); + sb.append(") "); + } + sb.append(" Min Memory Usage: "); + sb.append(minMemoryUsage); + sb.append("kB"); + list.add(sb.toString()); + } + return list; + } + + /** + * To text. + * + * @param isAnalyze the is analyze + * @return the string + */ + @Override + public String toText(boolean isAnalyze) { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append(getNodeType()); + sb.append(" "); + sb.append(getCostInfoForTextDisplay(isAnalyze)); + return sb.toString(); + } + + /** + * Gets the node specific. + * + * @return the node specific + */ + @Override + public List getNodeSpecific() { + if (null == hashDetail) { + ArrayList arList = new ArrayList(1); + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Hash Buckets: ").append(hashBuckets); + arList.add(sb.toString()); + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Hash Batches: ").append(hashBatches); + arList.add(sb.toString()); + + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Original Hash Batches: ").append(originalHashBatches); + arList.add(sb.toString()); + + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Peak Memory Usage: ").append(peakMemoryUsage); + arList.add(sb.toString()); + + return arList; + } + + return null; + } + + private void fillnoDNHashDetail(ArrayList arList) { + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_HASHNODE_HASHBUCKETS), hashBuckets) + .getProp()); + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_HASHNODE_HASHBATCHES), hashBatches) + .getProp()); + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_HASHNODE_ORIGINALHASHBATCHES), + originalHashBatches).getProp()); + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_HASHNODE_PEAKMEMORYUSAGE), + peakMemoryUsage).getProp()); + } + + /** + * Gets the node specific properties. + * + * @return the node specific properties + */ + @Override + public List getNodeSpecificProperties() { + List moreInfo = super.getNodeSpecificProperties(); + + ArrayList arList = new ArrayList(5); + + arList.addAll(moreInfo); + + /* If DN does not have hash node specific information */ + if (null == hashDetail) { + fillnoDNHashDetail(arList); + } + + return arList; + } + + /** + * Gets the per DN specific details. + * + * @param inputMap the input map + * @return the per DN specific details + */ + @Override + public Map> getPerDNSpecificDetails(Map> inputMap) { + ArrayList detailsNeeded = initDetailArray(INDETAILSCATEGORY.ACTUALS_IN_DETAIL, + INDETAILSCATEGORY.CPU_IN_DETAIL, INDETAILSCATEGORY.BUFFERS_IN_DETAIL); + Map> output = super.getPerDNSpecificDetails(inputMap, detailsNeeded); + + /* Add HASH DN Information */ + if (null != hashDetail) { + getHashDetail(output); + } + return output; + } + + /** + * Gets the per DN specific column grouping info. + * + * @param colGroup the col group + * @return the per DN specific column grouping info + */ + @Override + public List getPerDNSpecificColumnGroupingInfo(List colGroup) { + List outputColGroup = super.getPerDNSpecificColumnGroupingInfo(colGroup); + + if (null != hashDetail) { + outputColGroup.add(HashDetail.fillColumnPropertyHeader()); + } + + return outputColGroup; + } + + private void getHashDetail(Map> inputMap) { + for (HashDetail entry : hashDetail) { + if (!inputMap.containsKey(entry.getDnName())) { + List propsValues = entry.propertyDetails(); + inputMap.put(entry.getDnName(), propsValues); + } else { + inputMap.get(entry.getDnName()).addAll(entry.propertyDetails()); + } + } + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/INodeFunctions.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/INodeFunctions.java new file mode 100644 index 0000000000000000000000000000000000000000..c5d70a2349e2d35e1a4befc7549d4433f2ae1c32 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/INodeFunctions.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +/** + * + * Title: interface + * + * Description: The Interface INodeFunctions. + * + * @since 3.0.0 + */ +public interface INodeFunctions { + + /** + * Gets the specific info. + * + * @return the specific info + */ + String getSpecificInfo(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/IndexScan.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/IndexScan.java new file mode 100644 index 0000000000000000000000000000000000000000..3c941d295c6c920068a3a135da671fc0b9a6e8d6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/IndexScan.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class IndexScan. + * + * @since 3.0.0 + */ +public class IndexScan extends ScanNode { + + /** + * The scan direction. + */ + @SerializedName("Scan Direction") + protected String scanDirection = ""; + + /** + * The index name. + */ + @SerializedName("Index Name") + protected String indexName = ""; + + /** + * The index cond. + */ + @SerializedName("Index Cond") + protected String indexCond = ""; + + /** + * The rows removed index recheck. + */ + @SerializedName("Rows Removed by Index Recheck") + protected String rowsRemovedIndexRecheck = ""; + + /** + * Instantiates a new index scan. + */ + public IndexScan() { + super(); + } + + /** + * To text. + * + * @param isAnalyze the is analyze + * @return the string + */ + @Override + public String toText(boolean isAnalyze) { + StringBuilder sb = new StringBuilder(getNodeName()); + sb.append(" "); + sb.append(getCostInfoForTextDisplay(isAnalyze)); + return sb.toString(); + } + + /** + * Gets the node name. + * + * @return the node name + */ + @Override + public String getNodeName() { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append(getNodeType()); + sb.append(" using "); + sb.append(indexName); + if (!"".equals(relationName)) { + sb.append(" on "); + sb.append(relationName); + sb.append(" "); + } + + if (!"".equals(alias) && !alias.equals(relationName)) { + sb.append(alias); + } + return sb.toString(); + } + + /** + * Gets the additional info. + * + * @param isAnalyze the is analyze + * @return the additional info + */ + public List getAdditionalInfo(boolean isAnalyze) { + List list = new ArrayList(1); + if (!"".equals(indexCond)) { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Index Cond: "); + sb.append(indexCond); + list.add(sb.toString()); + } + if (!"".equals(filter)) { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Filter: "); + sb.append(filter); + list.add(sb.toString()); + } + return list; + } + + /** + * Gets the node specific. + * + * @return the node specific + */ + @Override + public List getNodeSpecific() { + List moreInfo = super.getNodeSpecific(); + ArrayList arList = new ArrayList(1); + + arList.add(moreInfo.toString()); + + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Scan Direction: ").append(scanDirection); + arList.add(sb.toString()); + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Index Name: ").append(indexName); + arList.add(sb.toString()); + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Index Cond: ").append(indexCond); + arList.add(sb.toString()); + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Rows Removed by Index Recheck: ").append(rowsRemovedIndexRecheck); + arList.add(sb.toString()); + + if (!"".equals(filter)) { + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Filter: ").append(filter); + arList.add(sb.toString()); + } + + if (!"".equals(rowsRemovedByFilter)) { + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Rows Removed by Filter: ").append(rowsRemovedByFilter); + arList.add(sb.toString()); + } + + return arList; + } + + /** + * Gets the node specific properties. + * + * @return the node specific properties + */ + @Override + public List getNodeSpecificProperties() { + List moreInfo = super.getNodeSpecificProperties(); + + ArrayList arList = new ArrayList(5); + + arList.addAll(moreInfo); + + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_INDEXSCANNODE_SCANDIRECTION), + scanDirection).getProp()); + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_INDEXSCANNODE_INDEXNAME), indexName) + .getProp()); + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_INDEXSCANNODE_INDEXCOND), indexCond) + .getProp()); + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_INDEXSCANNODE_ROWSREMOVEDRECHECK), + rowsRemovedIndexRecheck).getProp()); + + addPropFilter(arList); + addPropRowsRemovedByFilter(arList); + + return arList; + } + + /** + * Gets the per DN specific details. + * + * @param inputMap the input map + * @return the per DN specific details + */ + @Override + public Map> getPerDNSpecificDetails(Map> inputMap) { + return inputMap; + } + + /** + * Gets the item name. + * + * @return the item name + */ + @Override + public String getItemName() { + return "Index: " + this.indexName; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/ModifyTableNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/ModifyTableNode.java new file mode 100644 index 0000000000000000000000000000000000000000..4fde81bcc72af1e65729cbee66e36d33a7975cb3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/ModifyTableNode.java @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.StringEscapeUtils; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.explainplan.nodetypes.INDETAILSCATEGORY; +import org.opengauss.mppdbide.explainplan.nodetypes.NodeCategoryEnum; +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class ModifyTableNode. + * + * @since 3.0.0 + */ +public class ModifyTableNode extends OperationalNode { + + /** + * The relation name. + */ + @SerializedName("Relation Name") + protected String relationName = ""; + + /** + * The alias. + */ + @SerializedName("Alias") + protected String alias = ""; + + /** + * The operation. + */ + @SerializedName("Operation") + protected String operation = ""; + + /** + * The schema. + */ + @SerializedName("Schema") + protected String schema = ""; + + /** + * The remote query. + */ + @SerializedName("Remote query") + protected String remoteQuery = ""; + + /** + * Instantiates a new modify table node. + */ + public ModifyTableNode() { + super(NodeCategoryEnum.MODIFYTABLE); + } + + /** + * Gets the node specific. + * + * @return the node specific + */ + @Override + public List getNodeSpecific() { + ArrayList list = new ArrayList(1); + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + sb.append("Operation: ").append(operation); + list.add(sb.toString()); + + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Relation Name: ").append(relationName); + list.add(sb.toString()); + + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Alias: ").append(alias); + list.add(sb.toString()); + + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Schema: ").append(schema); + list.add(sb.toString()); + + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Remote Query: ").append(StringEscapeUtils.escapeHtml(remoteQuery)); + list.add(sb.toString()); + + return list; + } + + /** + * Gets the node specific properties. + * + * @return the node specific properties + */ + @Override + public List getNodeSpecificProperties() { + List moreInfo = super.getNodeSpecificProperties(); + + ArrayList index = new ArrayList(5); + + index.addAll(moreInfo); + + index.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_MODIFYTABLE_OPERATION), operation) + .getProp()); + index.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_SCANNODE_SCANTABLENAME), + relationName).getProp()); + + index.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_SCANNODE_SCANTABLEALIASNAME), alias) + .getProp()); + + index.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_SCANNODE_SCHEMANAME), schema) + .getProp()); + + index.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_NODE_REMOTEQUERY), + StringEscapeUtils.escapeHtml(remoteQuery)).getProp()); + + return index; + } + + /** + * Gets the per DN specific details. + * + * @param inputMap the input map + * @return the per DN specific details + */ + @Override + public Map> getPerDNSpecificDetails(Map> inputMap) { + ArrayList detailsNeeded = initDetailArray(INDETAILSCATEGORY.CPU_IN_DETAIL, + INDETAILSCATEGORY.ACTUALS_IN_DETAIL, INDETAILSCATEGORY.BUFFERS_IN_DETAIL); + Map> output = super.getPerDNSpecificDetails(inputMap, detailsNeeded); + + return output; + } + + /** + * Gets the item name. + * + * @return the item name + */ + @Override + public String getItemName() { + return "Table: " + this.relationName; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/NestLoopJoin.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/NestLoopJoin.java new file mode 100644 index 0000000000000000000000000000000000000000..6496d1cb6a850284f251ff4da73686a38d8f4805 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/NestLoopJoin.java @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.explainplan.nodetypes.ActualInDetail; +import org.opengauss.mppdbide.explainplan.nodetypes.INDETAILSCATEGORY; +import org.opengauss.mppdbide.explainplan.nodetypes.NodeCategoryEnum; +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.presentation.objectproperties.DNIntraNodeDetailsColumn; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class NestLoopJoin. + * + * @since 3.0.0 + */ +public class NestLoopJoin extends OperationalNode { + + /** + * The join type. + */ + @SerializedName("Join Type") + protected String joinType = ""; + + /** + * The join filter. + */ + @SerializedName("Join Filter") + protected String joinFilter = ""; + + /** + * The rows removed by join filter. + */ + @SerializedName("Rows Removed by Join Filter") + protected int rowsRemovedByJoinFilter; + + /** + * Instantiates a new nest loop join. + */ + public NestLoopJoin() { + super(NodeCategoryEnum.NESTLOOPJOIN); + } + + /** + * Gets the additional info. + * + * @param isAnalyze the is analyze + * @return the additional info + */ + @Override + public List getAdditionalInfo(boolean isAnalyze) { + ArrayList list = new ArrayList(1); + + if (!"".equals(joinFilter)) { + StringBuilder sb = new StringBuilder("Join Filter : "); + sb.append(joinFilter); + list.add(sb.toString()); + } + + return list; + } + + /** + * Gets the node specific properties. + * + * @return the node specific properties + */ + @Override + public List getNodeSpecificProperties() { + List moreInfo = super.getNodeSpecificProperties(); + + ArrayList elements = new ArrayList(5); + + elements.addAll(moreInfo); + + elements.add( + new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_JOIN_JOINTYPE), + joinType).getProp()); + elements.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_NESTLOOP_JOIN_JOINFILTER), + joinFilter).getProp()); + + elements.add(new ServerProperty( + MessageConfigLoader + .getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_NESTLOOP_JOIN_ROWSREMOVEDBYJOINFILTER), + rowsRemovedByJoinFilter).getProp()); + return elements; + } + + /** + * Gets the per DN specific details. + * + * @param inputMap the input map + * @return the per DN specific details + */ + @Override + public Map> getPerDNSpecificDetails(Map> inputMap) { + ArrayList detailsNeeded = initDetailArray(INDETAILSCATEGORY.CPU_IN_DETAIL, + INDETAILSCATEGORY.LLVM_DETAIL); + + Map> op = super.getPerDNSpecificDetails(inputMap, detailsNeeded); + List propsValues = null; + + for (ActualInDetail entry : actualsInDetail) { + propsValues = buildJoinNodePropertyDetails(entry.getDnName()); + if (!op.containsKey(entry.getDnName())) { + op.put(entry.getDnName(), propsValues); + } else { + op.get(entry.getDnName()).addAll(propsValues); + } + } + + return op; + } + + private List buildJoinNodePropertyDetails(String dnName) { + ArrayList colInfo = new ArrayList(5); + ActualInDetail innerDetail = (!this.getChildren().isEmpty()) + ? this.getChildren().get(0).getActualsByDNName(dnName) + : null; + ActualInDetail outerDetail = (this.getChildren().size() > 1) + ? this.getChildren().get(1).getActualsByDNName(dnName) + : null; + ActualInDetail hashNode = this.getActualsByDNName(dnName); + + colInfo.add((innerDetail == null) ? 0 : innerDetail.getActualRows()); + colInfo.add((outerDetail == null) ? 0 : outerDetail.getActualRows()); + colInfo.add((hashNode == null) ? 0 : hashNode.getActualRows()); + + colInfo.add((innerDetail == null) ? 0 : innerDetail.getActualStartupTime()); + colInfo.add((outerDetail == null) ? 0 : outerDetail.getActualStartupTime()); + colInfo.add((hashNode == null) ? 0 : hashNode.getActualStartupTime()); + + colInfo.add((innerDetail == null) ? 0 : innerDetail.getActualTotalTime()); + colInfo.add((outerDetail == null) ? 0 : outerDetail.getActualTotalTime()); + colInfo.add((hashNode == null) ? 0 : hashNode.getActualTotalTime()); + + return colInfo; + } + + private static List + buildHashNodePropertyColumnGroupingInfo(List colGroup) { + DNIntraNodeDetailsColumn dnActualsInDetail = new DNIntraNodeDetailsColumn(); + + dnActualsInDetail.setGroupColumnName( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_PERDN_JOININDETAIL)); + + ArrayList clmnames = new ArrayList(5); + clmnames.add("Inner node- Rows"); + clmnames.add("Outer Node- Rows"); + clmnames.add("Join Output Rows"); + + clmnames.add("Inner node- Startup Time"); + clmnames.add("Outer Node- Startup Time"); + clmnames.add("Join Node Startup Time"); + + clmnames.add("Inner node- Total Time"); + clmnames.add("Outer Node- Total Time"); + clmnames.add("Join Node Total Time"); + + dnActualsInDetail.setColCount(9); + dnActualsInDetail.setColnames(clmnames); + + colGroup.add(dnActualsInDetail); + + return colGroup; + + } + + /** + * Gets the per DN specific column grouping info. + * + * @param colGroupParam the col group param + * @return the per DN specific column grouping info + */ + @Override + public List + getPerDNSpecificColumnGroupingInfo(List colGroupParam) { + List colGrp = colGroupParam; + ArrayList detailsNeeded = new ArrayList(5); + detailsNeeded.add(INDETAILSCATEGORY.CPU_IN_DETAIL); + detailsNeeded.add(INDETAILSCATEGORY.LLVM_DETAIL); + colGrp = super.getPerDNSpecificColumnGroupingInfo(colGrp, detailsNeeded); + + return buildHashNodePropertyColumnGroupingInfo(colGrp); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/NestedLoopNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/NestedLoopNode.java new file mode 100644 index 0000000000000000000000000000000000000000..6867d80fc762d2b522b29c40d0bc87a07b4c08bd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/NestedLoopNode.java @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.explainplan.nodetypes.ActualInDetail; +import org.opengauss.mppdbide.explainplan.nodetypes.INDETAILSCATEGORY; +import org.opengauss.mppdbide.explainplan.nodetypes.NodeCategoryEnum; +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.presentation.objectproperties.DNIntraNodeDetailsColumn; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class NestedLoopNode. + * + * @since 3.0.0 + */ +public class NestedLoopNode extends OperationalNode { + + /** + * The join type. + */ + @SerializedName("Join Type") + protected String joinType = ""; + + /** + * Instantiates a new nested loop node. + */ + public NestedLoopNode() { + super(NodeCategoryEnum.NESTEDLOOP); + } + + /** + * Gets the node specific properties. + * + * @return the node specific properties + */ + @Override + public List getNodeSpecificProperties() { + List moreInfo = super.getNodeSpecificProperties(); + + ArrayList arList = new ArrayList(5); + + arList.addAll(moreInfo); + + arList.add( + new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_JOIN_JOINTYPE), + joinType).getProp()); + + if (!"".equals(subPlan)) { + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_NODE_SUBPLANNAME), subPlan) + .getProp()); + } + + return arList; + } + + /** + * Gets the per DN specific details. + * + * @param inputMap the input map + * @return the per DN specific details + */ + @Override + public Map> getPerDNSpecificDetails(Map> inputMap) { + ArrayList detailsNeeded = initDetailArray(INDETAILSCATEGORY.CPU_IN_DETAIL, + INDETAILSCATEGORY.LLVM_DETAIL); + + Map> output = super.getPerDNSpecificDetails(inputMap, detailsNeeded); + List propsValues = null; + + for (ActualInDetail index : actualsInDetail) { + propsValues = buildJoinNodePropertyDetails(index.getDnName()); + if (!output.containsKey(index.getDnName())) { + output.put(index.getDnName(), propsValues); + } else { + output.get(index.getDnName()).addAll(propsValues); + } + } + + return output; + } + + private List buildJoinNodePropertyDetails(String dnName) { + ArrayList colInfo = new ArrayList(5); + ActualInDetail inner = (!this.getChildren().isEmpty()) ? this.getChildren().get(0).getActualsByDNName(dnName) + : null; + ActualInDetail outer = (this.getChildren().size() > 1) ? this.getChildren().get(1).getActualsByDNName(dnName) + : null; + ActualInDetail hashNode = this.getActualsByDNName(dnName); + + colInfo.add((inner == null) ? 0 : inner.getActualRows()); + colInfo.add((outer == null) ? 0 : outer.getActualRows()); + colInfo.add((hashNode == null) ? 0 : hashNode.getActualRows()); + + colInfo.add((inner == null) ? 0 : inner.getActualStartupTime()); + colInfo.add((outer == null) ? 0 : outer.getActualStartupTime()); + colInfo.add((hashNode == null) ? 0 : hashNode.getActualStartupTime()); + + colInfo.add((inner == null) ? 0 : inner.getActualTotalTime()); + colInfo.add((outer == null) ? 0 : outer.getActualTotalTime()); + colInfo.add((hashNode == null) ? 0 : hashNode.getActualTotalTime()); + return colInfo; + } + + private static List + buildHashNodePropertyColumnGroupingInfo(List colGroup) { + DNIntraNodeDetailsColumn dnActualsInDetail = new DNIntraNodeDetailsColumn(); + + dnActualsInDetail.setGroupColumnName( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_PERDN_JOININDETAIL)); + + ArrayList colnames = new ArrayList(5); + colnames.add("Inner node- Rows"); + colnames.add("Outer Node- Rows"); + colnames.add("Join Output Rows"); + + colnames.add("Inner node- Startup Time"); + colnames.add("Outer Node- Startup Time"); + colnames.add("Join Node Startup Time"); + + colnames.add("Inner node- Total Time"); + colnames.add("Outer Node- Total Time"); + colnames.add("Join Node Total Time"); + + dnActualsInDetail.setColCount(9); + dnActualsInDetail.setColnames(colnames); + + colGroup.add(dnActualsInDetail); + + return colGroup; + + } + + /** + * Gets the per DN specific column grouping info. + * + * @param colGroupParam the col group param + * @return the per DN specific column grouping info + */ + @Override + public List + getPerDNSpecificColumnGroupingInfo(List colGroupParam) { + + List colGroup = colGroupParam; + ArrayList detailsNeeded = new ArrayList(5); + detailsNeeded.add(INDETAILSCATEGORY.CPU_IN_DETAIL); + detailsNeeded.add(INDETAILSCATEGORY.LLVM_DETAIL); + colGroup = super.getPerDNSpecificColumnGroupingInfo(colGroup, detailsNeeded); + + return buildHashNodePropertyColumnGroupingInfo(colGroup); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/PartitionItetrator.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/PartitionItetrator.java new file mode 100644 index 0000000000000000000000000000000000000000..a9e950003b5c14021ac72d42916f13bc79d0bc8f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/PartitionItetrator.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import org.opengauss.mppdbide.explainplan.nodetypes.NodeCategoryEnum; +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; + +/** + * + * Title: class + * + * Description: The Class PartitionItetrator. + * + * @since 3.0.0 + */ +public class PartitionItetrator extends OperationalNode { + + /** + * Instantiates a new partition itetrator. + */ + public PartitionItetrator() { + super(NodeCategoryEnum.PARTITIONITERATOR); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/RecursiveUnionNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/RecursiveUnionNode.java new file mode 100644 index 0000000000000000000000000000000000000000..763e741f63905d573c95a8d65eb4efd7e2c623a0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/RecursiveUnionNode.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.explainplan.nodetypes.INDETAILSCATEGORY; +import org.opengauss.mppdbide.explainplan.nodetypes.NodeCategoryEnum; +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class RecursiveUnionNode. + * + * @since 3.0.0 + */ +public class RecursiveUnionNode extends OperationalNode { + + /** + * Instantiates a new recursive union node. + */ + public RecursiveUnionNode() { + super(NodeCategoryEnum.UNION); + } + + @Override + public List getAdditionalInfo(boolean isAnalyze) { + return getNodeSpecific(); + } + + @Override + public List getNodeSpecific() { + ArrayList list = new ArrayList(1); + StringBuilder sb = null; + + if (!"".equals(subPlan)) { + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Subplan Name: ").append(subPlan); + list.add(sb.toString()); + } + + return list; + } + + @Override + public List getNodeSpecificProperties() { + List moreInfo = super.getNodeSpecificProperties(); + + ArrayList arList = new ArrayList(5); + + arList.addAll(moreInfo); + + if (!"".equals(subPlan)) { + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_NODE_SUBPLANNAME), subPlan) + .getProp()); + } + + return arList; + } + + @Override + public String getItemName() { + return null; + } + + @Override + public Map> getPerDNSpecificDetails(Map> inputMap) { + ArrayList detailsNeeded = initDetailArray(INDETAILSCATEGORY.BUFFERS_IN_DETAIL, + INDETAILSCATEGORY.CPU_IN_DETAIL, INDETAILSCATEGORY.ACTUALS_IN_DETAIL); + Map> output = super.getPerDNSpecificDetails(inputMap, detailsNeeded); + + return output; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/RowAdapter.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/RowAdapter.java new file mode 100644 index 0000000000000000000000000000000000000000..2fc36d951440d391d36bc5e2bf1a7b5783feba20 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/RowAdapter.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.explainplan.nodetypes.NodeCategoryEnum; +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; + +/** + * + * Title: class + * + * Description: The Class RowAdapter. + * + * @since 3.0.0 + */ +public class RowAdapter extends OperationalNode { + + /** + * Instantiates a new row adapter. + */ + public RowAdapter() { + super(NodeCategoryEnum.ROWADAPTER); + } + + @Override + public ArrayList getDNInvolved(ArrayList dnsInvolved) { + return new ArrayList(5); + } + + @Override + public List getNodeSpecificProperties() { + List moreInfo = super.getNodeSpecificProperties(); + + ArrayList arList = new ArrayList(5); + + arList.addAll(moreInfo); + + return arList; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/ScanNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/ScanNode.java new file mode 100644 index 0000000000000000000000000000000000000000..96783c1a18e491f3fde5eb8dfc123b7eb20dda36 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/ScanNode.java @@ -0,0 +1,316 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.StringEscapeUtils; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.explainplan.nodetypes.INDETAILSCATEGORY; +import org.opengauss.mppdbide.explainplan.nodetypes.NodeCategoryEnum; +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class ScanNode. + * + * @since 3.0.0 + */ +public class ScanNode extends OperationalNode { + + /** + * The filter. + */ + @SerializedName("Filter") + protected String filter = ""; + + /** + * The rows removed by filter. + */ + @SerializedName("Rows Removed by Filter") + protected String rowsRemovedByFilter = ""; + + /** + * The relation name. + */ + @SerializedName("Relation Name") + protected String relationName = ""; + + /** + * The alias. + */ + @SerializedName("Alias") + protected String alias = ""; + + /** + * The selected partitions. + */ + @SerializedName("Selected Partitions") + protected String selectedPartitions = ""; + + /** + * The schema. + */ + @SerializedName("Schema") + protected String schema = ""; + + /** + * Instantiates a new scan node. + */ + public ScanNode() { + super(NodeCategoryEnum.SCAN); + } + + /** + * To text. + * + * @param isAnalyze the is analyze + * @return the string + */ + @Override + public String toText(boolean isAnalyze) { + StringBuilder sb = new StringBuilder(getNodeName()); + sb.append(" "); + sb.append(getCostInfoForTextDisplay(isAnalyze)); + return sb.toString(); + } + + /** + * Gets the node name. + * + * @return the node name + */ + @Override + public String getNodeName() { + boolean onUsed = false; + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append(getNodeType()); + if (!"".equals(relationName)) { + sb.append(" on "); + onUsed = true; + sb.append(relationName); + } + + if (!"".equals(alias) && !alias.equals(relationName)) { + if (onUsed) { + sb.append(" "); + } else { + sb.append(" on "); + } + sb.append(alias); + } + return sb.toString(); + } + + /** + * Gets the node specific. + * + * @return the node specific + */ + public List getNodeSpecific() { + ArrayList list = new ArrayList(1); + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + if (!"".equals(relationName)) { + sb.append("Relation Name: ").append(relationName); + list.add(sb.toString()); + } + + if (!"".equals(alias)) { + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Alias: ").append(alias); + list.add(sb.toString()); + } + + if (!"".equals(selectedPartitions)) { + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Selected Partitions: ").append(selectedPartitions); + list.add(sb.toString()); + } + + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Schema: ").append(schema); + list.add(sb.toString()); + + if (!"".equals(filter)) { + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_CSTORESCANNODE_FILTER)) + .append(": ").append(filter); + list.add(sb.toString()); + } + + if (!"".equals(rowsRemovedByFilter) && !"0".equals(rowsRemovedByFilter)) { + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append(MessageConfigLoader + .getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_CSTORESCANNODE_ROWREMOVEDFILTER)).append(": ") + .append(rowsRemovedByFilter); + list.add(sb.toString()); + } + + return list; + } + + /** + * Gets the node specific properties. + * + * @return the node specific properties + */ + @Override + public List getNodeSpecificProperties() { + List moreInfo = super.getNodeSpecificProperties(); + + ArrayList arList = new ArrayList(5); + + arList.addAll(moreInfo); + + if (!"".equals(relationName)) { + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_SCANNODE_SCANTABLENAME), + relationName).getProp()); + } + + if (!"".equals(alias)) { + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_SCANNODE_SCANTABLEALIASNAME), + alias).getProp()); + } + + if (!"".equals(schema)) { + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_SCANNODE_SCHEMANAME), schema) + .getProp()); + } + + if (!"".equals(selectedPartitions)) { + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_SCANNODE_SELECTEDPARTITIONS), + selectedPartitions).getProp()); + } + + addPropFilter(arList); + addPropRowsRemovedByFilter(arList); + + return arList; + } + + /** + * Adds the prop filter. + * + * @param arList the ar list + */ + protected void addPropFilter(ArrayList arList) { + // if condition moved to function to remove duplicacy in derived classes + if (!"".equals(filter)) { + arList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_CSTORESCANNODE_FILTER), + StringEscapeUtils.escapeHtml(filter)).getProp()); + } + } + + /** + * Adds the prop rows removed by filter. + * + * @param arList the ar list + */ + protected void addPropRowsRemovedByFilter(ArrayList arList) { + // if condition moved to function to remove duplicacy in derived classes + if (!"".equals(rowsRemovedByFilter)) { + arList.add( + new ServerProperty( + MessageConfigLoader + .getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_CSTORESCANNODE_ROWREMOVEDFILTER), + rowsRemovedByFilter).getProp()); + } + } + + /** + * Gets the per DN specific details. + * + * @param inputMap the input map + * @return the per DN specific details + */ + @Override + public Map> getPerDNSpecificDetails(Map> inputMap) { + ArrayList detailsNeeded = initDetailArray(INDETAILSCATEGORY.ACTUALS_IN_DETAIL, + INDETAILSCATEGORY.CPU_IN_DETAIL, INDETAILSCATEGORY.BUFFERS_IN_DETAIL); + Map> output = super.getPerDNSpecificDetails(inputMap, detailsNeeded); + + return output; + } + + /** + * Gets the item name. + * + * @return the item name + */ + @Override + public String getItemName() { + if (!"".equals(relationName)) { + return "Table: " + this.relationName; + } + + return null; + } + + /** + * Gets the entity name. + * + * @return the entity name + */ + @Override + public String getEntityName() { + if (!"".equals(relationName) && !"".equals(alias)) { + return this.relationName + " as " + this.alias; + } + return null; + } + + /** + * Gets the additional info. + * + * @param isAnalyze the is analyze + * @return the additional info + */ + @Override + public List getAdditionalInfo(boolean isAnalyze) { + ArrayList list = new ArrayList(1); + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + if (!"".equals(filter)) { + sb.append(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_CSTORESCANNODE_FILTER)) + .append(": ").append(filter); + list.add(sb.toString()); + } + + if (!"".equals(rowsRemovedByFilter)) { + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append(MessageConfigLoader + .getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_CSTORESCANNODE_ROWREMOVEDFILTER)).append(": ") + .append(rowsRemovedByFilter); + list.add(sb.toString()); + } + + return list; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/SortDetails.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/SortDetails.java new file mode 100644 index 0000000000000000000000000000000000000000..ad675a2094c2377b925e87f2bf285bbc4208c64b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/SortDetails.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class SortDetails. + * + * @since 3.0.0 + */ +public class SortDetails { + + /** + * The sort method. + */ + @SerializedName("Sort Method") + protected String sortMethod; + + /** + * The dn name. + */ + @SerializedName("DN Name") + protected String dnName; + + /** + * The sort key. + */ + @SerializedName("Sort Key") + protected List sortKey; + + /** + * The sort space used. + */ + @SerializedName("Sort Space Used") + protected String sortSpaceUsed; + + /** + * Gets the sort details. + * + * @return the sort details + */ + public List getSortDetails() { + ArrayList list = new ArrayList(1); + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append(" Sort Method: ").append(sortMethod); + list.add(sb.toString()); + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append(" Sort Key: "); + + int size = sortKey.size(); + if (size > 0) { + for (int index = 0; index < size - 1; index++) { + sb.append(sortKey.get(index)); + sb.append(","); + } + + sb.append(sortKey.get(sortKey.size() - 1)); + } + list.add(sb.toString()); + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append(" Sort Space Used: ").append(sortSpaceUsed); + list.add(sb.toString()); + + return list; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/SortNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/SortNode.java new file mode 100644 index 0000000000000000000000000000000000000000..44bb199bbd66a4f3cc85dcc4191f31ed92fef2e0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/SortNode.java @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.explainplan.nodetypes.NodeCategoryEnum; +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.utils.CustomStringUtility; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class SortNode. + * + * @since 3.0.0 + */ +public class SortNode extends OperationalNode { + + /** + * The sort key. + */ + @SerializedName("Sort Key") + protected List sortKey; + + /** + * The sort method. + */ + @SerializedName("Sort Method") + protected String sortMethod = ""; + + /** + * The sort space used. + */ + @SerializedName("Sort Space Used") + protected int sortSpaceUsed; + + /** + * The sort space type. + */ + @SerializedName("Sort Space Type") + protected String sortSpaceType = ""; + + /** + * The dn details. + */ + @SerializedName("Sort Detail") + protected List dnDetails; + + /** + * Instantiates a new sort node. + */ + public SortNode() { + super(NodeCategoryEnum.SORT); + } + + /** + * Gets the additional info. + * + * @param isAnalyze the is analyze + * @return the additional info + */ + @Override + public List getAdditionalInfo(boolean isAnalyze) { + ArrayList list = new ArrayList(1); + List otherInfo = super.getAdditionalInfo(isAnalyze); + list.addAll(otherInfo); + + StringBuilder sb = new StringBuilder("Sort Key: "); + int index = 0; + if (!this.sortKey.isEmpty()) { + for (String str : this.sortKey) { + if (index != 0) { + sb.append(", "); + } + sb.append(str); + index++; + } + } + list.add(sb.toString()); + + if (isAnalyze) { + if (!"".equals(sortMethod)) { + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Sort Method: "); + sb.append(sortMethod); + sb.append(" Memory: "); + sb.append(sortSpaceUsed); + sb.append("kB"); + list.add(sb.toString()); + } + } + return list; + } + + /** + * Gets the node specific. + * + * @return the node specific + */ + @Override + public List getNodeSpecific() { + ArrayList nodes = new ArrayList(3); + nodes.add("Sort Method : " + this.sortMethod); + nodes.add("Sort Space Used : " + this.sortSpaceUsed); + nodes.add("Sort Space Type : " + this.sortSpaceType); + + return nodes; + } + + /** + * Gets the node specific properties. + * + * @return the node specific properties + */ + @Override + public List getNodeSpecificProperties() { + List moreInfo = super.getNodeSpecificProperties(); + + ArrayList arList = new ArrayList(5); + + arList.addAll(moreInfo); + + arList.add( + new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_SORT_SORTKEYS), + CustomStringUtility.getFormatedOutput(sortKey, ",")).getProp()); + return arList; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/SortNodeDNDetails.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/SortNodeDNDetails.java new file mode 100644 index 0000000000000000000000000000000000000000..770a557096acbe00fc5561d2a6e45fe026e7edc2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/SortNodeDNDetails.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import com.google.gson.annotations.SerializedName; + +/** + * + * Title: class + * + * Description: The Class SortNodeDNDetails. + * + * @since 3.0.0 + */ +public class SortNodeDNDetails { + + /** + * The dn name. + */ + @SerializedName("DN Name") + protected String dnName; + + /** + * The sort method. + */ + @SerializedName("Sort Method") + protected String sortMethod; + + /** + * The sort space used. + */ + @SerializedName("Sort Space Used") + protected int sortSpaceUsed; + + /** + * The sort space type. + */ + @SerializedName("Sort Space Type") + protected String sortSpaceType; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/StreamBroadcast.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/StreamBroadcast.java new file mode 100644 index 0000000000000000000000000000000000000000..b91afaca97a95b428063ef27c79243acc3383a83 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/StreamBroadcast.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +/** + * + * Title: class + * + * Description: The Class StreamBroadcast. + * + * @since 3.0.0 + */ +public class StreamBroadcast extends AbstractStreamNode { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/StreamGather.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/StreamGather.java new file mode 100644 index 0000000000000000000000000000000000000000..5e20c3ee88044cf7c72b65aa0804aedf17e40e79 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/StreamGather.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class StreamGather. + * + * @since 3.0.0 + */ +public class StreamGather extends AbstractStreamNode { + + @Override + public List getNodeSpecificProperties() { + List moreInfo = super.getNodeSpecificProperties(); + + ArrayList elements = new ArrayList(5); + + elements.addAll(moreInfo); + + elements.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_STREAM_GATHER_NODES), nodes) + .getProp()); + return elements; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/StreamRedistribute.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/StreamRedistribute.java new file mode 100644 index 0000000000000000000000000000000000000000..8cf7df4450534a6fc34f13c44b234ecd46bf4e18 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/StreamRedistribute.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.utils.CustomStringUtility; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class StreamRedistribute. + * + * @since 3.0.0 + */ +public class StreamRedistribute extends AbstractStreamNode { + + /** + * The distribute key. + */ + @SerializedName("Distribute Key") + protected List distributeKey; + + /** + * Gets the node specific properties. + * + * @return the node specific properties + */ + @Override + public List getNodeSpecificProperties() { + List moreInfo = super.getNodeSpecificProperties(); + + ArrayList elements = new ArrayList(5); + + elements.addAll(moreInfo); + + elements.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_STREAM_REDISTRIBUTE_DISTRKEY), + CustomStringUtility.getFormatedOutput(distributeKey, ",")).getProp()); + + elements.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_STREAM_REDISTRIBUTE_SPAWNON), + spawnOn).getProp()); + return elements; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/UnknownOperator.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/UnknownOperator.java new file mode 100644 index 0000000000000000000000000000000000000000..9f3778da24a6664e0ae21ef18b9d18317d5871fa --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/UnknownOperator.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import org.opengauss.mppdbide.explainplan.nodetypes.NodeCategoryEnum; +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; + +/** + * + * Title: class + * + * Description: The Class UnknownOperator. + * + * @since 3.0.0 + */ +public class UnknownOperator extends OperationalNode { + + /** + * Instantiates a new unknown operator. + */ + public UnknownOperator() { + super(NodeCategoryEnum.UNKNOWN); + } + + @Override + public String getNodeCategoryName() { + String retName = this.getNodeType(); + if (null != retName) { + String nodeNameFirstPart = retName.split(" ")[0]; + if ("Vector".equalsIgnoreCase(nodeNameFirstPart)) { + retName = nodeType.substring(nodeNameFirstPart.length() + 1); + } + } + + return retName; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/ValuesScanNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/ValuesScanNode.java new file mode 100644 index 0000000000000000000000000000000000000000..00c50a95910878e881e7d5e019d540bcca9c2dab --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/ValuesScanNode.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.explainplan.nodetypes.INDETAILSCATEGORY; +import org.opengauss.mppdbide.explainplan.nodetypes.NodeCategoryEnum; +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class ValuesScanNode. + * + * @since 3.0.0 + */ +public class ValuesScanNode extends OperationalNode { + + /** + * The alias. + */ + @SerializedName("Alias") + protected String alias = ""; + + /** + * Instantiates a new values scan node. + */ + public ValuesScanNode() { + super(NodeCategoryEnum.SCAN); + } + + /** + * Gets the node specific. + * + * @return the node specific + */ + @Override + public List getNodeSpecific() { + ArrayList list = new ArrayList(1); + StringBuilder sb = null; + + if (!"".equals(alias)) { + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Alias: ").append(alias); + list.add(sb.toString()); + } + + return list; + } + + /** + * Gets the node specific properties. + * + * @return the node specific properties + */ + @Override + public List getNodeSpecificProperties() { + List moreInfo = super.getNodeSpecificProperties(); + + ArrayList nodesList = new ArrayList(5); + + nodesList.addAll(moreInfo); + + if (!"".equals(alias)) { + nodesList.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_SCANNODE_ALIASNAME), alias) + .getProp()); + } + + return nodesList; + } + + /** + * Gets the per DN specific details. + * + * @param inputMap the input map + * @return the per DN specific details + */ + @Override + public Map> getPerDNSpecificDetails(Map> inputMap) { + ArrayList detailsNeeded = initDetailArray(INDETAILSCATEGORY.ACTUALS_IN_DETAIL, + INDETAILSCATEGORY.CPU_IN_DETAIL, INDETAILSCATEGORY.BUFFERS_IN_DETAIL); + Map> output = super.getPerDNSpecificDetails(inputMap, detailsNeeded); + + return output; + } + + /** + * Gets the item name. + * + * @return the item name + */ + @Override + public String getItemName() { + return null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/VectorSetOpNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/VectorSetOpNode.java new file mode 100644 index 0000000000000000000000000000000000000000..3f6fd9c47b7db776d644dac7690150919f5ce365 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/VectorSetOpNode.java @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.explainplan.nodetypes.INDETAILSCATEGORY; +import org.opengauss.mppdbide.explainplan.nodetypes.NodeCategoryEnum; +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.explainplan.nodetypes.SetopDetail; +import org.opengauss.mppdbide.presentation.objectproperties.DNIntraNodeDetailsColumn; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class VectorSetOpNode. + * + * @since 3.0.0 + */ +public class VectorSetOpNode extends OperationalNode { + + /** + * The strategy. + */ + @SerializedName("Strategy") + protected String strategy = ""; + + /** + * The command. + */ + @SerializedName("Command") + protected String command = ""; + + /** + * The setop details. + */ + @SerializedName("Setop Detail") + protected List setopDetails; + + /** + * Instantiates a new vector set op node. + */ + public VectorSetOpNode() { + super(NodeCategoryEnum.SETOP); + } + + /** + * Gets the node specific. + * + * @return the node specific + */ + @Override + public List getNodeSpecific() { + ArrayList list = new ArrayList(1); + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + sb.append("Strategy: ").append(strategy); + list.add(sb.toString()); + + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("Command: ").append(command); + list.add(sb.toString()); + + return list; + } + + /** + * Gets the node specific properties. + * + * @return the node specific properties + */ + @Override + public List getNodeSpecificProperties() { + List moreInfo = super.getNodeSpecificProperties(); + + ArrayList nodes = new ArrayList(5); + + nodes.addAll(moreInfo); + + nodes.add( + new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_SETOP_STRATEGY), + strategy).getProp()); + nodes.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_SETOP_COMMAND), + command).getProp()); + + return nodes; + } + + /** + * Gets the per DN specific column grouping info. + * + * @param colGroup the col group + * @return the per DN specific column grouping info + */ + @Override + public List getPerDNSpecificColumnGroupingInfo(List colGroup) { + List outputColGroup = super.getPerDNSpecificColumnGroupingInfo(colGroup); + + outputColGroup.add(SetopDetail.fillColumnPropertyHeader()); + + return outputColGroup; + } + + /** + * Gets the per DN specific details. + * + * @param inputMap the input map + * @return the per DN specific details + */ + @Override + public Map> getPerDNSpecificDetails(Map> inputMap) { + ArrayList detailsNeeded = initDetailArray(INDETAILSCATEGORY.ACTUALS_IN_DETAIL, + INDETAILSCATEGORY.CPU_IN_DETAIL, INDETAILSCATEGORY.BUFFERS_IN_DETAIL); + Map> output = super.getPerDNSpecificDetails(inputMap, detailsNeeded); + + getSetOpDetail(output); + return output; + } + + private void getSetOpDetail(Map> inputMap) { + if (null != setopDetails) { + for (SetopDetail element : setopDetails) { + if (!inputMap.containsKey(element.getDnName())) { + List propsValues = element.propertyDetails(); + inputMap.put(element.getDnName(), propsValues); + } else { + inputMap.get(element.getDnName()).addAll(element.propertyDetails()); + } + } + } + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/WorkTableScanNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/WorkTableScanNode.java new file mode 100644 index 0000000000000000000000000000000000000000..91ebc0e22b26b7305daa51c6ec62020ea1921edf --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/WorkTableScanNode.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.StringEscapeUtils; + +import com.google.gson.annotations.SerializedName; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.explainplan.nodetypes.INDETAILSCATEGORY; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class WorkTableScanNode. + * + * @since 3.0.0 + */ +public class WorkTableScanNode extends CTEScanNode { + + /** + * The filter. + */ + @SerializedName("Filter") + protected String filter = ""; + + /** + * The rows removed by filter. + */ + @SerializedName("Rows Removed by Filter") + protected String rowsRemovedByFilter = ""; + + /** + * Instantiates a new work table scan node. + */ + public WorkTableScanNode() { + super(); + } + + /** + * Gets the additional info. + * + * @param isAnalyze the is analyze + * @return the additional info + */ + @Override + public List getAdditionalInfo(boolean isAnalyze) { + return getNodeSpecific(); + } + + /** + * Gets the node specific. + * + * @return the node specific + */ + @Override + public List getNodeSpecific() { + ArrayList list = new ArrayList(1); + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + if (!"".equals(filter)) { + sb.append(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_WORKTABLESCANNODE_FILTER)) + .append(": ").append(StringEscapeUtils.escapeHtml(filter)); + list.add(sb.toString()); + } + + if (!"".equals(rowsRemovedByFilter)) { + sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append(MessageConfigLoader + .getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_WORKTABLESCANNODE_ROWREMOVEDFILTER)).append(": ") + .append(rowsRemovedByFilter); + list.add(sb.toString()); + } + + return list; + } + + /** + * Gets the node specific properties. + * + * @return the node specific properties + */ + @Override + public List getNodeSpecificProperties() { + List moreInfo = super.getNodeSpecificProperties(); + + ArrayList elements = new ArrayList(5); + + elements.addAll(moreInfo); + + if (!"".equals(filter)) { + elements.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_WORKTABLESCANNODE_FILTER), + StringEscapeUtils.escapeHtml(filter)).getProp()); + } + if (!"".equals(rowsRemovedByFilter)) { + elements.add(new ServerProperty( + MessageConfigLoader + .getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_WORKTABLESCANNODE_ROWREMOVEDFILTER), + rowsRemovedByFilter).getProp()); + } + + return elements; + } + + /** + * Gets the per DN specific details. + * + * @param inputMap the input map + * @return the per DN specific details + */ + @Override + public Map> getPerDNSpecificDetails(Map> inputMap) { + ArrayList detailsNeeded = initDetailArray(INDETAILSCATEGORY.ACTUALS_IN_DETAIL, + INDETAILSCATEGORY.CPU_IN_DETAIL, INDETAILSCATEGORY.BUFFERS_IN_DETAIL); + + Map> output = super.getPerDNSpecificDetails(inputMap, detailsNeeded); + + return output; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/factory/GetNodeFromFactory.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/factory/GetNodeFromFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..f550c33c520973cd1f6d8913d9958a994c7939a7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/plannode/factory/GetNodeFromFactory.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.plannode.factory; + +import java.util.HashMap; +import java.util.Map; + +import org.opengauss.mppdbide.explainplan.plannode.CStoreScanNode; +import org.opengauss.mppdbide.explainplan.plannode.CTEScanNode; +import org.opengauss.mppdbide.explainplan.plannode.DataNodeScan; +import org.opengauss.mppdbide.explainplan.plannode.FunctionScanNode; +import org.opengauss.mppdbide.explainplan.plannode.HashAggregate; +import org.opengauss.mppdbide.explainplan.plannode.HashJoin; +import org.opengauss.mppdbide.explainplan.plannode.HashNode; +import org.opengauss.mppdbide.explainplan.plannode.IndexScan; +import org.opengauss.mppdbide.explainplan.plannode.ModifyTableNode; +import org.opengauss.mppdbide.explainplan.plannode.NestLoopJoin; +import org.opengauss.mppdbide.explainplan.plannode.NestedLoopNode; +import org.opengauss.mppdbide.explainplan.plannode.PartitionItetrator; +import org.opengauss.mppdbide.explainplan.plannode.RecursiveUnionNode; +import org.opengauss.mppdbide.explainplan.plannode.RowAdapter; +import org.opengauss.mppdbide.explainplan.plannode.ScanNode; +import org.opengauss.mppdbide.explainplan.plannode.SortNode; +import org.opengauss.mppdbide.explainplan.plannode.StreamBroadcast; +import org.opengauss.mppdbide.explainplan.plannode.StreamGather; +import org.opengauss.mppdbide.explainplan.plannode.StreamRedistribute; +import org.opengauss.mppdbide.explainplan.plannode.UnknownOperator; +import org.opengauss.mppdbide.explainplan.plannode.ValuesScanNode; +import org.opengauss.mppdbide.explainplan.plannode.VectorSetOpNode; +import org.opengauss.mppdbide.explainplan.plannode.WorkTableScanNode; + +/** + * Title: GetNodeFromFactory + * + * Description:A factory for creating GetNodeFrom objects. + * + * @since 3.0.0 + */ +public abstract class GetNodeFromFactory { + private static final Map OPERATOR_CLASS_MAP = new HashMap(10); + static { + OPERATOR_CLASS_MAP.put("Aggregate", HashAggregate.class); + + OPERATOR_CLASS_MAP.put("CStore Scan", ScanNode.class); + OPERATOR_CLASS_MAP.put("CTE Scan", CTEScanNode.class); + OPERATOR_CLASS_MAP.put("Data Node Scan", DataNodeScan.class); + + OPERATOR_CLASS_MAP.put("Function Scan", FunctionScanNode.class); + + OPERATOR_CLASS_MAP.put("Hash", HashNode.class); + OPERATOR_CLASS_MAP.put("Hash Aggregate", HashAggregate.class); + OPERATOR_CLASS_MAP.put("Hash Join", HashJoin.class); + + OPERATOR_CLASS_MAP.put("Index Scan", IndexScan.class); + + OPERATOR_CLASS_MAP.put("ModifyTable", ModifyTableNode.class); + + OPERATOR_CLASS_MAP.put("Nest Loop Join", NestLoopJoin.class); + OPERATOR_CLASS_MAP.put("Nested Loop", NestedLoopNode.class); + + OPERATOR_CLASS_MAP.put("Partitioned CStore Scan", CStoreScanNode.class); + OPERATOR_CLASS_MAP.put("Partition Iterator", PartitionItetrator.class); + OPERATOR_CLASS_MAP.put("Partitioned Seq Scan", ScanNode.class); + + OPERATOR_CLASS_MAP.put("Recursive Union", RecursiveUnionNode.class); + OPERATOR_CLASS_MAP.put("Row Adapter", RowAdapter.class); + + OPERATOR_CLASS_MAP.put("Seq Scan", ScanNode.class); + OPERATOR_CLASS_MAP.put("Sort", SortNode.class); + OPERATOR_CLASS_MAP.put("Streaming(type: BROADCAST)", StreamBroadcast.class); + OPERATOR_CLASS_MAP.put("Streaming (type: GATHER)", StreamGather.class); + OPERATOR_CLASS_MAP.put("Streaming(type: REDISTRIBUTE)", StreamRedistribute.class); + OPERATOR_CLASS_MAP.put("Subquery Scan", ScanNode.class); + OPERATOR_CLASS_MAP.put("SetOp", VectorSetOpNode.class); + + OPERATOR_CLASS_MAP.put("Values Scan", ValuesScanNode.class); + OPERATOR_CLASS_MAP.put("WorkTable Scan", WorkTableScanNode.class); + } + + /** + * Gets the class. + * + * @param nodeType the node type + * @return the class + */ + public static Class getClass(String nodeType) { + Class retClass = null; + if (null != nodeType) { + String lookupNodeType = nodeType; + String nodeNameFirstPart = nodeType.split(" ")[0]; + if ("Vector".equalsIgnoreCase(nodeNameFirstPart)) { + lookupNodeType = nodeType.substring(nodeNameFirstPart.length() + 1); + } + retClass = OPERATOR_CLASS_MAP.get(lookupNodeType); + } + if (null == retClass) { + return UnknownOperator.class; + } + return retClass; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/service/AbstractAnalysedPlanNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/service/AbstractAnalysedPlanNode.java new file mode 100644 index 0000000000000000000000000000000000000000..3888c5d3373f6c533276380f04f4ff4cdc928880 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/service/AbstractAnalysedPlanNode.java @@ -0,0 +1,478 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.service; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class AbstractAnalysedPlanNode. + * + * @since 3.0.0 + */ +public abstract class AbstractAnalysedPlanNode { + + /** + * The parent. + */ + protected AnalysedPlanNode parent; + + /** + * The core stats. + */ + protected OperationalNode coreStats; + + /** + * The child node stats. + */ + protected ArrayList childNodeStats; + + /** + * The node sequence number. + */ + protected int nodeSequenceNumber; + + /** + * The self time. + */ + protected double selfTime; + + /** + * The self time contribution in over all plan. + */ + protected double selfTimeContributionInOverAllPlan; + + /** + * The self cost. + */ + protected double selfCost; + + /** + * The source relationship. + */ + protected ArrayList sourceRelationship = new ArrayList(1); + + /** + * The target relationship. + */ + protected ArrayList targetRelationship = new ArrayList(1); + + /** + * The is slowest. + */ + protected boolean isSlowest; + + /** + * The is costliest. + */ + protected boolean isCostliest; + + /** + * The is heaviest. + */ + protected boolean isHeaviest; + + /** + * The total time contribution percentage. + */ + + protected double totalTimeContributionPercentage; + + /** + * Checks if is heaviest. + * + * @return true, if is heaviest + */ + public boolean isHeaviest() { + return isHeaviest; + } + + /** + * Sets the heaviest. + * + * @param isHeavist the new heaviest + */ + public void setHeaviest(boolean isHeavist) { + this.isHeaviest = isHeavist; + } + + /** + * Checks if is slowest. + * + * @return true, if is slowest + */ + public boolean isSlowest() { + return isSlowest; + } + + /** + * Checks if is costliest. + * + * @return true, if is costliest + */ + public boolean isCostliest() { + return isCostliest; + } + + /** + * Gets the child node stats. + * + * @return the child node stats + */ + public ArrayList getChildNodeStats() { + return childNodeStats; + } + + /** + * Gets the total time contribution percentage. + * + * @return the total time contribution percentage + */ + public double getTotalTimeContributionPercentage() { + return totalTimeContributionPercentage; + } + + /** + * Sets the total time contribution percentage. + * + * @param totalTimeContributionPercentage the new total time contribution + * percentage + */ + public void setTotalTimeContributionPercentage(double totalTimeContributionPercentage) { + this.totalTimeContributionPercentage = totalTimeContributionPercentage; + } + + /** + * Instantiates a new abstract analysed plan node. + * + * @param inputStat the input stat + */ + public AbstractAnalysedPlanNode(OperationalNode inputStat) { + this.coreStats = inputStat; + this.childNodeStats = new ArrayList(0); + + } + + /** + * Adds the child. + * + * @param childAnalysedNode the child analysed node + */ + public void addChild(AnalysedPlanNode childAnalysedNode) { + this.childNodeStats.add(childAnalysedNode); + + } + + /** + * Gets the child. + * + * @return the child + */ + public OperationalNode getChild() { + return coreStats; + } + + /** + * Sets the costliest node. + * + * @param value the new costliest node + */ + public void setCostliestNode(boolean value) { + isCostliest = value; + } + + /** + * Sets the heaviest node. + * + * @param value the new heaviest node + */ + public void setHeaviestNode(boolean value) { + isHeaviest = value; + } + + /** + * Sets the slowest node. + * + * @param value the new slowest node + */ + public void setSlowestNode(boolean value) { + isSlowest = value; + + } + + /** + * To string. + * + * @return the string + */ + public String toString() { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append(coreStats.getNodeType()); + sb.append(" {"); + + if (isHeaviest) { + sb.append(" heaviest = true"); + sb.append("; "); + } + + if (isSlowest) { + sb.append(" slowest = true"); + sb.append("; "); + } + + if (isCostliest) { + sb.append(" costliest = true"); + sb.append("; "); + } + + sb.append(" cost_contribution: "); + sb.append(new DecimalFormat("##.##").format(this.totalTimeContributionPercentage)); + sb.append("%"); + sb.append("}"); + + sb.append(System.lineSeparator()); + + for (AnalysedPlanNode child : childNodeStats) { + sb.append(child.toString()); + } + + return sb.toString(); + } + + /** + * Gets the node type. + * + * @return the node type + */ + public String getNodeType() { + return coreStats.getNodeType(); + } + + /** + * Sets the parent. + * + * @param parent2 the new parent + */ + public void setParent(AnalysedPlanNode parent2) { + this.parent = parent2; + } + + /** + * Gets the parent. + * + * @return the parent + */ + public AnalysedPlanNode getParent() { + return this.parent; + } + + /** + * Gets the self cost. + * + * @return the self cost + */ + public double getSelfCost() { + return selfCost; + } + + /** + * Sets the self cost. + * + * @param selfCost the new self cost + */ + public void setSelfCost(double selfCost) { + this.selfCost = selfCost; + } + + /** + * Do auto analysis. + * + * @param dvalue the dvalue + */ + public void doAutoAnalysis(double dvalue) { + if (Math.abs(dvalue) != 0) { + this.totalTimeContributionPercentage = this.coreStats.getActualMaxTimeTaken() * 100 / dvalue; + } + this.selfTime = 0d; + double childTotalCost = 0d; + double childTotalTime = 0d; + + for (AnalysedPlanNode child : childNodeStats) { + childTotalCost += child.getChild().getTotalCost(); + childTotalTime += child.getChild().getActualTotalTime(); + } + + this.selfCost = this.getChild().getTotalCost() - childTotalCost; + if (this.selfCost < 0) { + this.selfCost = 0; + } + + this.selfTime = this.getChild().getActualTotalTime() - childTotalTime; + if (this.selfTime < 0) { + this.selfTime = 0; + } + + if (Math.abs(dvalue) != 0) { + this.selfTimeContributionInOverAllPlan = (this.selfTime * 100) / dvalue; + } + } + + /** + * Gets the self time contribution in over all plan. + * + * @return the self time contribution in over all plan + */ + public double getSelfTimeContributionInOverAllPlan() { + return selfTimeContributionInOverAllPlan; + } + + /** + * Gets the source relationship. + * + * @return the source relationship + */ + public List getSourceRelationship() { + return this.sourceRelationship; + } + + /** + * Gets the target relationship. + * + * @return the target relationship + */ + public List getTargetRelationship() { + return this.targetRelationship; + } + + /** + * Adds the source relationship. + * + * @param rs the rs + */ + public void addSourceRelationship(Relationship rs) { + sourceRelationship.add(rs); + } + + /** + * Adds the target relationship. + * + * @param rs the rs + */ + public void addTargetRelationship(Relationship rs) { + targetRelationship.add(rs); + } + + /** + * Gets the record count. + * + * @return the record count + */ + public long getRecordCount() { + return getChild().getActualRows(); + + } + + /** + * Gets the node specific. + * + * @return the node specific + */ + public List getNodeSpecific() { + return this.getChild().getNodeSpecific(); + } + + /** + * Gets the output. + * + * @return the output + */ + public String[] getOutput() { + return this.getChild().getOutput(); + } + + /** + * Gets the actual max time taken. + * + * @return the actual max time taken + */ + public double getActualMaxTimeTaken() { + return this.getChild().getActualMaxTimeTaken(); + } + + /** + * Gets the parent relationship. + * + * @return the parent relationship + */ + public String getParentRelationship() { + return this.getChild().getParentRelationship(); + } + + /** + * Gets the plan record count. + * + * @return the plan record count + */ + public long getPlanRecordCount() { + return getChild().getPlanRows(); + } + + /** + * Sets the node sequence num. + * + * @param seqNumber the new node sequence num + */ + public void setNodeSequenceNum(int seqNumber) { + this.nodeSequenceNumber = seqNumber; + } + + /** + * Gets the node sequence num. + * + * @return the node sequence num + */ + public int getNodeSequenceNum() { + return this.nodeSequenceNumber; + } + + /** + * Gets the formated output. + * + * @param seperator the seperator + * @return the formated output + */ + public String getFormatedOutput(String seperator) { + String[] str = getOutput(); + if (1 == str.length) { + return str[0]; + } + StringBuilder sb = new StringBuilder(str[0]); + for (int index = 1; index < str.length; index++) { + sb.append(seperator); + sb.append(str[index]); + } + + return sb.toString(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/service/AnalysePlanService.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/service/AnalysePlanService.java new file mode 100644 index 0000000000000000000000000000000000000000..b60f1cbfc40812117e17ee823558ee13f9302866 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/service/AnalysePlanService.java @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.service; + +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.explainplan.nodetypes.RootPlanNode; + +/** + * + * Title: class + * + * Description: The Class AnalysePlanService. + * + * @since 3.0.0 + */ +public class AnalysePlanService { + private boolean isAnalysisDone; + + /** + * The root. + */ + protected RootPlanNode root; + private AnalysedPlanNode analysedplan; + + private double tempMaxCost; + private double tempMaxTime; + private long tempMaxRows; + + private AnalysedPlanNode tempCostliestNode; + private AnalysedPlanNode tempHeaviestNode; + private AnalysedPlanNode tempSlowestNode; + + private int nodeSequence = 0; + + private int getSeqNumber() { + return ++nodeSequence; + } + + /** + * Instantiates a new analyse plan service. + * + * @param planroot the planroot + */ + public AnalysePlanService(RootPlanNode planroot) { + + this.root = planroot; + this.isAnalysisDone = false; + this.tempMaxCost = 0; + this.tempMaxTime = 0; + this.tempMaxRows = 0; + this.nodeSequence = 0; + /* + * get the child(0) as the root has no data in it. All data is stored in + * its 0th child node. + */ + tempCostliestNode = new AnalysedPlanNode(this.root.getChildren().get(0)); + tempHeaviestNode = new AnalysedPlanNode(this.root.getChildren().get(0)); + tempSlowestNode = new AnalysedPlanNode(this.root.getChildren().get(0)); + } + + /** + * Do analysis. + * + * @return the analysed plan node + */ + public AnalysedPlanNode doAnalysis() { + if (this.isAnalysisDone()) { + return this.analysedplan; + } + + this.setAnalysisDone(false); + this.analysedplan = doDetailedAnalysis(this.root.getChildren().get(0), null); + this.tempCostliestNode.setCostliestNode(true); + this.tempHeaviestNode.setHeaviestNode(true); + this.tempSlowestNode.setSlowestNode(true); + createParentChildRelationship(this.analysedplan); + this.setAnalysisDone(true); + + return this.analysedplan; + } + + private void createParentChildRelationship(AnalysedPlanNode curNode) { + for (AnalysedPlanNode child : curNode.getChildNodeStats()) { + Relationship rs = new Relationship(curNode, child); + curNode.addSourceRelationship(rs); + child.addTargetRelationship(rs); + createParentChildRelationship(child); + } + + } + + private AnalysedPlanNode doDetailedAnalysis(OperationalNode curNode, AnalysedPlanNode parent) { + AnalysedPlanNode curAnalysedNode = new AnalysedPlanNode(curNode); + curAnalysedNode.setNodeSequenceNum(this.getSeqNumber()); + curAnalysedNode.setParent(parent); + AnalysedPlanNode childAnalysedNode = null; + + for (OperationalNode child : curNode.getChildren()) { + childAnalysedNode = doDetailedAnalysis(child, curAnalysedNode); + curAnalysedNode.addChild(childAnalysedNode); + } + + curAnalysedNode.doAutoAnalysis(this.root.getTotalRuntime()); + + // checking for costliest node + if (Math.abs(curAnalysedNode.getSelfCost()) > Math.abs(tempMaxCost)) { + tempMaxCost = curNode.getTotalCost(); + this.tempCostliestNode = curAnalysedNode; + } + + // checking for heaviest node + if (curNode.getActualRows() > tempMaxRows) { + tempMaxRows = curNode.getActualRows(); + this.tempHeaviestNode = curAnalysedNode; + } + + // checking for slowest node + if (Math.abs(curAnalysedNode.getSelfTotalTime()) > Math.abs(tempMaxTime)) { + tempMaxTime = curAnalysedNode.getSelfTotalTime(); + this.tempSlowestNode = curAnalysedNode; + } + + return curAnalysedNode; + } + + /** + * Checks if is analysis done. + * + * @return true, if is analysis done + */ + public boolean isAnalysisDone() { + return isAnalysisDone; + } + + /** + * Sets the analysis done. + * + * @param isAnalysDone the new analysis done + */ + public void setAnalysisDone(boolean isAnalysDone) { + this.isAnalysisDone = isAnalysDone; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/service/AnalysedPlanNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/service/AnalysedPlanNode.java new file mode 100644 index 0000000000000000000000000000000000000000..a2da6c942b31838121e3d6e3ec39f820cd2ca410 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/service/AnalysedPlanNode.java @@ -0,0 +1,297 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.presentation.objectproperties.DNIntraNodeDetailsColumn; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class AnalysedPlanNode. + * + * @since 3.0.0 + */ +public class AnalysedPlanNode extends AbstractAnalysedPlanNode { + + /** + * Instantiates a new analysed plan node. + * + * @param inputStat the input stat + */ + public AnalysedPlanNode(OperationalNode inputStat) { + super(inputStat); + + } + + /** + * Gets the self total time. + * + * @return the self total time + */ + public double getSelfTotalTime() { + return this.selfTime; + } + + /** + * Gets the node name. + * + * @return the node name + */ + public String getNodeName() { + return this.coreStats.getNodeType(); + } + + /** + * Gets the node unique name with type. + * + * @return the node unique name with type + */ + public String getNodeUniqueNameWithType() { + return this.getNodeSequenceNum() + ". " + this.getNodeName(); + } + + /** + * Gets the node unique name. + * + * @return the node unique name + */ + public String getNodeUniqueName() { + return this.getNodeSequenceNum() + ". " + this.getNodeCategoryName(); + } + + private String getNodeCategoryName() { + return this.coreStats.getNodeCategoryName(); + } + + /** + * Gets the node specific properties. + * + * @param props the props + * @return the node specific properties + */ + public List getNodeSpecificProperties(List props) { + props.addAll(this.coreStats.getNodeSpecificProperties()); + return props; + } + + /** + * Gets the node specific DN properties. + * + * @return the node specific DN properties + */ + public Map> getNodeSpecificDNProperties() { + if (this.coreStats.hasDNData()) { + Map> inputMap = new HashMap>(1); + return this.coreStats.getPerDNSpecificDetails(inputMap); + } + + return null; + } + + /** + * Gets the per DN specific column grouping info. + * + * @return the per DN specific column grouping info + */ + public List getPerDNSpecificColumnGroupingInfo() { + List colGroup = new ArrayList(5); + return this.coreStats.getPerDNSpecificColumnGroupingInfo(colGroup); + } + + /** + * Gets the DN involved. + * + * @param dnsInvolved the dns involved + * @return the DN involved + */ + public ArrayList getDNInvolved(ArrayList dnsInvolved) { + return this.coreStats.getDNInvolved(dnsInvolved); + } + + /** + * Adds the node DN plan view. + * + * @param dnViewofExplainPlan the dn viewof explain plan + * @param idx the idx + */ + public void addNodeDNPlanView(Map dnViewofExplainPlan, int idx) { + this.coreStats.addNodeDNPlanView(dnViewofExplainPlan, idx); + + } + + /** + * Gets the analysis. + * + * @return the analysis + */ + public String getAnalysis() { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + boolean needLineSeperator = false; + + if (this.isHeaviest()) { + sb.append(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_ANALYSIS_HEAVIEST)); + needLineSeperator = true; + } + if (this.isCostliest()) { + if (needLineSeperator) { + sb.append(", "); + } + + sb.append(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_ANALYSIS_COSTLIEST)); + needLineSeperator = true; + } + if (this.isSlowest()) { + if (needLineSeperator) { + sb.append(", "); + } + + sb.append(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_ANALYSIS_SLOWEST)); + needLineSeperator = true; + } + if (needLineSeperator) { + return sb.toString(); + } else { + return "---NA---"; + } + } + + /** + * Gets the total cost. + * + * @return the total cost + */ + public double getTotalCost() { + return this.coreStats.getTotalCost(); + } + + /** + * Gets the plan deviation by record count. + * + * @param plannedRecCount the planned rec count + * @param actualRecordCount the actual record count + * @return the plan deviation by record count + */ + public double getPlanDeviationByRecordCount(long plannedRecCount, long actualRecordCount) { + return calculateDeviation(plannedRecCount, actualRecordCount) * 100; + } + + private double calculateDeviation(long point, long cnt) { + if (point == 0) { + return cnt; + } + + return (double) (cnt - point) / point; + + } + + /** + * Gets the item name. + * + * @return the item name + */ + public String getItemName() { + return this.coreStats.getItemName(); + } + + /** + * Gets the item details. + * + * @return the item details + */ + public String getItemDetails() { + return this.coreStats.getItemDetails(); + } + + /** + * To text. + * + * @param isAnalyze the is analyze + * @return the string + */ + public String toText(boolean isAnalyze) { + return coreStats.toText(isAnalyze); + } + + /** + * Gets the additional info. + * + * @param isAnalyze the is analyze + * @return the additional info + */ + public List getAdditionalInfo(boolean isAnalyze) { + return coreStats.getAdditionalInfo(isAnalyze); + } + + /** + * Hash code. + * + * @return the int + */ + public int hashCode() { + // just an extra line so that this does not fall over when the tool is + // used incorrectly + if (coreStats.getNodeType() == null) { + return super.hashCode(); + } + + if (null == this.getParent()) { + return coreStats.getNodeType().hashCode(); + } + String schemaName = this.getParent().getNodeType(); + return schemaName.hashCode() + coreStats.getNodeType().hashCode(); + } + + /** + * Equals. + * + * @param obj the obj + * @return true, if successful + */ + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + + if (obj instanceof AnalysedPlanNode) { + AnalysedPlanNode node = (AnalysedPlanNode) obj; + AnalysedPlanNode objectParent = node.getParent(); + AnalysedPlanNode currentParent = this.getParent(); + if (node.getNodeType().equals(this.getNodeType())) { + if (objectParent == null && currentParent == null) { + return true; + } else { + if (null != objectParent && null != currentParent + && objectParent.getNodeType().equals(currentParent.getNodeType())) { + return true; + } + } + } + } + + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/service/ExplainPlanAnlysisService.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/service/ExplainPlanAnlysisService.java new file mode 100644 index 0000000000000000000000000000000000000000..23f27c6c1d782b592fe4743c7511a84095cf58c1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/service/ExplainPlanAnlysisService.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.service; + +import org.opengauss.mppdbide.explainplan.jsonparser.ExplainPlanJsonContentParser; +import org.opengauss.mppdbide.explainplan.nodetypes.RootPlanNode; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: class + * + * Description: The Class ExplainPlanAnlysisService. + * + * @since 3.0.0 + */ +public class ExplainPlanAnlysisService { + private ExplainPlanJsonContentParser parser; + private AnalysedPlanNode apn; + private RootPlanNode planRoot; + + /** + * Instantiates a new explain plan anlysis service. + * + * @param jsonContent the json content + */ + public ExplainPlanAnlysisService(String jsonContent) { + this.parser = new ExplainPlanJsonContentParser(jsonContent); + } + + /** + * Do analysis. + * + * @return the analysed plan node + * @throws DatabaseOperationException the database operation exception + */ + public AnalysedPlanNode doAnalysis() throws DatabaseOperationException { + planRoot = parser.parseFileContents(); + AnalysePlanService analysisService = new AnalysePlanService(planRoot); + apn = analysisService.doAnalysis(); + + return apn; + } + + /** + * Gets the root plan. + * + * @return the root plan + */ + public RootPlanNode getRootPlan() { + return planRoot; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/service/Relationship.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/service/Relationship.java new file mode 100644 index 0000000000000000000000000000000000000000..e0cd5d1fc51433ffb5d41588b49b171a59d4502e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/service/Relationship.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.service; + +/** + * + * Title: class + * + * Description: The Class Relationship. + * + * @since 3.0.0 + */ +public class Relationship { + private AnalysedPlanNode parentNode; + private AnalysedPlanNode childNode; + + /** + * Instantiates a new relationship. + * + * @param parent the parent + * @param child the child + */ + public Relationship(AnalysedPlanNode parent, AnalysedPlanNode child) { + this.parentNode = parent; + this.childNode = child; + } + + /** + * Gets the parent node. + * + * @return the parent node + */ + public AnalysedPlanNode getParentNode() { + return parentNode; + } + + /** + * Sets the parent node. + * + * @param parentNode the new parent node + */ + public void setParentNode(AnalysedPlanNode parentNode) { + this.parentNode = parentNode; + } + + /** + * Gets the child node. + * + * @return the child node + */ + public AnalysedPlanNode getChildNode() { + return childNode; + } + + /** + * Sets the child node. + * + * @param childNode the new child node + */ + public void setChildNode(AnalysedPlanNode childNode) { + this.childNode = childNode; + } + + /** + * Gets the record count. + * + * @return the record count + */ + public long getRecordCount() { + return getChildNode().getRecordCount(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/ui/model/CompartmentUnitNames.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/ui/model/CompartmentUnitNames.java new file mode 100644 index 0000000000000000000000000000000000000000..ac6a25e32deec24c69f5717721be486a88670e50 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/ui/model/CompartmentUnitNames.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.ui.model; + +/** + * + * Title: interface + * + * Description: The Interface CompartmentUnitNames. + * + * @since 3.0.0 + */ +public interface CompartmentUnitNames { + + /** + * The node header. + */ + int NODE_HEADER = 0; + + /** + * The output details. + */ + int OUTPUT_DETAILS = 1; + + /** + * The node specific details. + */ + int NODE_SPECIFIC_DETAILS = 2; + + /** + * The heavy node analysis. + */ + int HEAVY_NODE_ANALYSIS = 3; + + /** + * The costly node analysis. + */ + int COSTLY_NODE_ANALYSIS = 4; + + /** + * The slow node analysis. + */ + int SLOW_NODE_ANALYSIS = 5; + + /** + * The max compartment unit.keep changing this number evevry time a new is + * added. + */ + int MAX_COMPARTMENT_UNIT = 6; + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/ui/model/ExplainAnalyzePlanNodeTreeDisplayData.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/ui/model/ExplainAnalyzePlanNodeTreeDisplayData.java new file mode 100644 index 0000000000000000000000000000000000000000..6f6a104ce2a37cc98ad1cb966f6f74f6b707141f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/ui/model/ExplainAnalyzePlanNodeTreeDisplayData.java @@ -0,0 +1,404 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.ui.model; + +import java.util.List; + +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.explainplan.service.AnalysedPlanNode; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class ExplainAnalyzePlanNodeTreeDisplayData. + * + * @since 3.0.0 + */ +public class ExplainAnalyzePlanNodeTreeDisplayData implements IDSGridDataRow { + private int id; + private ExplainAnalyzePlanNodeTreeDisplayData parent; + + /** + * Gets the parent. + * + * @return the parent + */ + public ExplainAnalyzePlanNodeTreeDisplayData getParent() { + return parent; + } + + /** + * Sets the parent. + * + * @param parent the new parent + */ + public void setParent(ExplainAnalyzePlanNodeTreeDisplayData parent) { + this.parent = parent; + } + + private String nodeType; + private double startupCost; + private double totalCost; + private long planRows; + private long planWidth; + private String additionalInfo; + + private double actualStartupTime; + private double actualTotalTime; + private long actualRows; + private long actualLoops; + + private boolean heaviest; + private boolean costliest; + private boolean slowest; + + private boolean isAnalyze; + + /** + * Gets the additional info. + * + * @return the additional info + */ + public String getAdditionalInfo() { + return additionalInfo; + } + + /** + * Sets the additional info. + * + * @param additionalInfo the new additional info + */ + public void setAdditionalInfo(String additionalInfo) { + this.additionalInfo = additionalInfo; + } + + /** + * Gets the actual startup time. + * + * @return the actual startup time + */ + public double getActualStartupTime() { + return actualStartupTime; + } + + /** + * Sets the actual startup time. + * + * @param actualStartupTime the new actual startup time + */ + public void setActualStartupTime(double actualStartupTime) { + this.actualStartupTime = actualStartupTime; + } + + /** + * Gets the actual total time. + * + * @return the actual total time + */ + public double getActualTotalTime() { + return actualTotalTime; + } + + /** + * Sets the actual total time. + * + * @param actualTotalTime the new actual total time + */ + public void setActualTotalTime(double actualTotalTime) { + this.actualTotalTime = actualTotalTime; + } + + /** + * Gets the actual rows. + * + * @return the actual rows + */ + public long getActualRows() { + return actualRows; + } + + /** + * Sets the actual rows. + * + * @param actualRows the new actual rows + */ + public void setActualRows(int actualRows) { + this.actualRows = actualRows; + } + + /** + * Gets the actual loops. + * + * @return the actual loops + */ + public long getActualLoops() { + return actualLoops; + } + + /** + * Sets the actual loops. + * + * @param actualLoops the new actual loops + */ + public void setActualLoops(int actualLoops) { + this.actualLoops = actualLoops; + } + + /** + * Checks if is heaviest. + * + * @return true, if is heaviest + */ + public boolean isHeaviest() { + return heaviest; + } + + /** + * Sets the heaviest. + * + * @param heaviest the new heaviest + */ + public void setHeaviest(boolean heaviest) { + this.heaviest = heaviest; + } + + /** + * Checks if is costliest. + * + * @return true, if is costliest + */ + public boolean isCostliest() { + return costliest; + } + + /** + * Sets the costliest. + * + * @param costliest the new costliest + */ + public void setCostliest(boolean costliest) { + this.costliest = costliest; + } + + /** + * Checks if is slowest. + * + * @return true, if is slowest + */ + public boolean isSlowest() { + return slowest; + } + + /** + * Sets the slowest. + * + * @param slowest the new slowest + */ + public void setSlowest(boolean slowest) { + this.slowest = slowest; + } + + /** + * Instantiates a new explain analyze plan node tree display data. + * + * @param id the id + * @param analysedNode the analysed node + * @param isAnalyze the is analyze + */ + public ExplainAnalyzePlanNodeTreeDisplayData(int id, AnalysedPlanNode analysedNode, boolean isAnalyze) { + this.id = id; + OperationalNode node = analysedNode.getChild(); + this.nodeType = node.getNodeName(); + this.startupCost = node.getStartupCost(); + this.totalCost = node.getTotalCost(); + this.planRows = node.getPlanRows(); + this.planWidth = node.getPlanWidth(); + this.isAnalyze = isAnalyze; + this.additionalInfo = buildAdditionalInfo(analysedNode); + + if (this.isAnalyze) { + this.actualLoops = node.getActualLoopCount(); + this.actualRows = node.getActualRows(); + this.actualStartupTime = node.getActualStartupTime(); + if (this.actualStartupTime == 0) { + this.actualStartupTime = node.getActualMaxStartupTime(); + } + this.actualTotalTime = node.getActualTotalTime(); + if (this.actualTotalTime == 0) { + this.actualTotalTime = node.getActualMaxTotalTime(); + } + } + this.heaviest = analysedNode.isHeaviest(); + this.costliest = analysedNode.isCostliest(); + this.slowest = analysedNode.isSlowest(); + } + + private String buildAdditionalInfo(AnalysedPlanNode node) { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + List info = node.getAdditionalInfo(isAnalyze); + if (info != null && info.size() != 0) { + for (int i = 0; i < info.size(); i++) { + String n1 = info.get(i).replaceAll(">", ">"); + String n2 = n1.replaceAll("<", "<"); + sb.append(n2); + if (i < info.size() - 1) { + sb.append(System.lineSeparator()); + } + } + return sb.toString(); + } + return ""; + } + + /** + * Gets the node type. + * + * @return the node type + */ + public String getNodeType() { + return nodeType; + } + + /** + * Sets the node type. + * + * @param nodeType the new node type + */ + public void setNodeType(String nodeType) { + this.nodeType = nodeType; + } + + /** + * Gets the startup cost. + * + * @return the startup cost + */ + public double getStartupCost() { + return startupCost; + } + + /** + * Sets the startup cost. + * + * @param startupCost the new startup cost + */ + public void setStartupCost(double startupCost) { + this.startupCost = startupCost; + } + + /** + * Gets the total cost. + * + * @return the total cost + */ + public double getTotalCost() { + return totalCost; + } + + /** + * Sets the total cost. + * + * @param totalCost the new total cost + */ + public void setTotalCost(double totalCost) { + this.totalCost = totalCost; + } + + /** + * Gets the plan rows. + * + * @return the plan rows + */ + public long getPlanRows() { + return planRows; + } + + /** + * Sets the plan rows. + * + * @param planRows the new plan rows + */ + public void setPlanRows(long planRows) { + this.planRows = planRows; + } + + /** + * Gets the plan width. + * + * @return the plan width + */ + public long getPlanWidth() { + return planWidth; + } + + /** + * Sets the plan width. + * + * @param planWidth the new plan width + */ + public void setPlanWidth(long planWidth) { + this.planWidth = planWidth; + } + + /** + * Compare to. + * + * @param explainAnalysePlanNodeTreeData the explainAnalysePlanNodeTreeData + * @return the int + */ + public int compareTo(ExplainAnalyzePlanNodeTreeDisplayData explainAnalysePlanNodeTreeData) { + return id - explainAnalysePlanNodeTreeData.getId(); + } + + @Override + public int hashCode() { + return 42; // any arbitrary constant will do + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof ExplainAnalyzePlanNodeTreeDisplayData)) { + return false; + } + return id == ((ExplainAnalyzePlanNodeTreeDisplayData) obj).getId(); + } + + private int getId() { + return this.id; + } + + @Override + public Object[] getValues() { + if (this.isAnalyze) { + return new Object[] {nodeType, startupCost, totalCost, planRows, planWidth, actualStartupTime, + actualTotalTime, actualRows, actualLoops, additionalInfo}; + } + return new Object[] {nodeType, startupCost, totalCost, planRows, planWidth, additionalInfo}; + } + + @Override + public Object getValue(int columnIndex) { + return getValues()[columnIndex]; + } + + @Override + public Object[] getClonedValues() { + return getValues().clone(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/ui/model/ExplainAnalyzePlanNodeTreeDisplayDataFactory.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/ui/model/ExplainAnalyzePlanNodeTreeDisplayDataFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..53345f9be2ef586b46be14fa7c61c3912ed8c96c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/ui/model/ExplainAnalyzePlanNodeTreeDisplayDataFactory.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.ui.model; + +import org.opengauss.mppdbide.explainplan.service.AnalysedPlanNode; + +/** + * Title: ExplainAnalyzePlanNodeTreeDisplayDataFactory + * + * Description:A factory for creating ExplainAnalyzePlanNodeTreeDisplayData + * objects. + * + * @since 3.0.0 + */ +public class ExplainAnalyzePlanNodeTreeDisplayDataFactory { + private static volatile ExplainAnalyzePlanNodeTreeDisplayDataFactory instance = null; + private static final Object lock = new Object(); + private int newChildId; + + /** + * Gets the single instance of ExplainAnalyzePlanNodeTreeDisplayDataFactory. + * + * @return single instance of ExplainAnalyzePlanNodeTreeDisplayDataFactory + */ + public static ExplainAnalyzePlanNodeTreeDisplayDataFactory getInstance() { + if (instance == null) { + synchronized (lock) { + if (null == instance) { + instance = new ExplainAnalyzePlanNodeTreeDisplayDataFactory(); + } + } + } + return instance; + } + + private ExplainAnalyzePlanNodeTreeDisplayDataFactory() { + newChildId = 0; + } + + /** + * Creates a new ExplainAnalyzePlanNodeTreeDisplayData object. + * + * @param analysedNode the analysed node + * @param isAnalyze the is analyze + * @return the explain analyze plan node tree display data + */ + public ExplainAnalyzePlanNodeTreeDisplayData createData(AnalysedPlanNode analysedNode, boolean isAnalyze) { + newChildId++; + return new ExplainAnalyzePlanNodeTreeDisplayData(newChildId, analysedNode, isAnalyze); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/ui/model/ExplainAnalyzePlanNodeTreeDisplayDataTreeFormat.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/ui/model/ExplainAnalyzePlanNodeTreeDisplayDataTreeFormat.java new file mode 100644 index 0000000000000000000000000000000000000000..4dce1ce6c910e0ff2ee63337d7bd992d458f18b9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/ui/model/ExplainAnalyzePlanNodeTreeDisplayDataTreeFormat.java @@ -0,0 +1,567 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.ui.model; + +import java.sql.Time; +import java.sql.Types; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Stack; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DefaultParameter; +import org.opengauss.mppdbide.bl.serverdatacache.IQueryResult; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.sqlhistory.IQueryExecutionSummary; +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnGroupProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.presentation.visualexplainplan.UIModelAnalysedPlanNode; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import ca.odell.glazedlists.TreeList.Format; +/* + * tree structure that will work as data-provider to tree-table in execution tab + */ + +/** + * + * Title: class + * + * Description: The Class ExplainAnalyzePlanNodeTreeDisplayDataTreeFormat. + * + * @since 3.0.0 + */ +public class ExplainAnalyzePlanNodeTreeDisplayDataTreeFormat + implements Format, IDSGridDataProvider { + private IQueryExecutionSummary summary; + private boolean isFirstBatchOver; + private UIModelAnalysedPlanNode node; + private List nodeInfos; + private List nodes; + private IDSGridColumnProvider columnDataProvider; + private boolean analyzeOperationalNode; + private List listExec; + private String spaces; + + /** + * preDestroy + */ + public void preDestroy() { + this.summary = null; + this.node = null; + if (this.nodeInfos != null) { + this.nodeInfos.clear(); + } + this.nodeInfos = null; + if (this.nodes != null) { + this.nodes.clear(); + } + this.nodes = null; + } + + /** + * Checks if is heaviest. + * + * @param row the row + * @return true, if is heaviest + */ + public boolean isHeaviest(int row) { + return (nodes != null && nodes.size() > row) ? nodes.get(row).isHeaviest() : false; + } + + /** + * Checks if is costliest. + * + * @param row the row + * @return true, if is costliest + */ + public boolean isCostliest(int row) { + return (nodes != null && nodes.size() > row) ? nodes.get(row).isCostliest() : false; + } + + /** + * Checks if is slowest. + * + * @param row the row + * @return true, if is slowest + */ + public boolean isSlowest(int row) { + return (nodes != null && nodes.size() > row) ? nodes.get(row).isSlowest() : false; + } + + /** + * Gets the column label map. + * + * @return the column label map + */ + public HashMap getColumnLabelMap() { + return ((Column) columnDataProvider).getColumnLabelMap(); + } + + /** + * + * Title: class + * + * Description: The Class Column. + */ + public static class Column implements IDSGridColumnProvider { + private String[] columns; + private String[] columnLabels; + + /** + * Instantiates a new column. + * + * @param analyze the analyze + */ + public Column(boolean analyze) { + if (!analyze) { + String[] props = {TreeGridColumnHeader.PROP_NODE_TYPE, TreeGridColumnHeader.PROP_STARTUP_COST, + TreeGridColumnHeader.PROP_TOTAL_COST, TreeGridColumnHeader.PROP_ROWS, + TreeGridColumnHeader.PROP_WIDTH, TreeGridColumnHeader.PROP_ADDITIONAL_INFO}; + String[] popLabels = {TreeGridColumnHeader.LABEL_NODE_TYPE, TreeGridColumnHeader.LABEL_STARTUP_COST, + TreeGridColumnHeader.LABEL_TOTAL_COST, TreeGridColumnHeader.LABEL_ROWS, + TreeGridColumnHeader.LABEL_WIDTH, TreeGridColumnHeader.LABEL_ADDITIONAL_INFO}; + columns = props; + columnLabels = popLabels; + } else { + String[] props = {TreeGridColumnHeader.PROP_NODE_TYPE, TreeGridColumnHeader.PROP_STARTUP_COST, + TreeGridColumnHeader.PROP_TOTAL_COST, TreeGridColumnHeader.PROP_ROWS, + TreeGridColumnHeader.PROP_WIDTH, TreeGridColumnHeader.PROP_ACTUAL_STARTUP_TIME, + TreeGridColumnHeader.PROP_ACTUAL_TOTAL_TIME, TreeGridColumnHeader.PROP_ACTUAL_ROWS, + TreeGridColumnHeader.PROP_ACTUAL_LOOPS, TreeGridColumnHeader.PROP_ADDITIONAL_INFO}; + String[] popLabels = {TreeGridColumnHeader.LABEL_NODE_TYPE, TreeGridColumnHeader.LABEL_STARTUP_COST, + TreeGridColumnHeader.LABEL_TOTAL_COST, TreeGridColumnHeader.LABEL_ROWS, + TreeGridColumnHeader.LABEL_WIDTH, TreeGridColumnHeader.LABEL_ACTUAL_STARTUP_TIME, + TreeGridColumnHeader.LABEL_ACTUAL_TOTAL_TIME, TreeGridColumnHeader.LABEL_ACTUAL_ROWS, + TreeGridColumnHeader.LABEL_ACTUAL_LOOPS, TreeGridColumnHeader.LABEL_ADDITIONAL_INFO}; + columns = props; + columnLabels = popLabels; + } + } + + /** + * Gets the column label map. + * + * @return the column label map + */ + public HashMap getColumnLabelMap() { + HashMap columnLabelMap = new HashMap<>(); + for (int index = 0; index < columns.length; index++) { + columnLabelMap.put(columns[index], columnLabels[index]); + } + return columnLabelMap; + } + + @Override + public int getColumnCount() { + return columns.length; + } + + @Override + public String[] getColumnNames() { + return columns.clone(); + } + + @Override + public String getColumnName(int columnIndex) { + return columnLabels[columnIndex]; + } + + @Override + public String getColumnDesc(int columnIndex) { + return columnLabels[columnIndex]; + } + + @Override + public int getColumnIndex(String columnLabel) { + for (int index = 0; index < columnLabels.length; index++) { + if (columnLabels[index].equals(columnLabel)) { + return index; + } + } + return -1; + } + + @Override + public Comparator getComparator(int columnIndex) { + return null; + } + + @Override + public int getColumnDatatype(int columnIndex) { + return Types.VARCHAR; + } + + @Override + public String getColumnDataTypeName(int columnIndex) { + return "String"; + } + + @Override + public int getPrecision(int columnIndex) { + return 0; + } + + @Override + public int getScale(int columnIndex) { + + return 0; + } + + @Override + public int getMaxLength(int columnIndex) { + + return 0; + } + + @Override + public String getDefaultValue(int i) { + return null; + } + + } + + /** + * Gets the node infos. + * + * @return the node infos + */ + public List getNodes() { + return nodes; + } + + /** + * Gets the listExec. + * + * @return the list exec + */ + + public List getListExec() { + return listExec; + } + + /** + * Instantiates a new explain analyze plan node tree display data tree + * format. + * + * @param node the node + */ + public ExplainAnalyzePlanNodeTreeDisplayDataTreeFormat(UIModelAnalysedPlanNode node) { + this.isFirstBatchOver = false; + this.node = node; + nodeInfos = new ArrayList(5); + nodes = new ArrayList(5); + columnDataProvider = new Column(node.isAnalyze()); + doDFS(); + analyzeOperationalNode = this.node.isAnalyze(); + OperationalNode parent = this.node.getOperationalNode(); + parent.setIndentationLevel(0); + } + + /** + * Traverse through Tree data for exporting explain analyze plan node tree + * display data tree format. + */ + + public void treeExport() { + listExec = new ArrayList(); + doDFS(); + exportTreeFormatData(this.node, this.node.isAnalyze()); + } + + /** + * Populate path with a list describing the path from a root node to this + * element. Upon returning, the list must have size is equal to or greater + * than 1, where the provided element identical to the list's last element. + */ + public void getPath(List path, + ExplainAnalyzePlanNodeTreeDisplayData element) { + path.add(element); + ExplainAnalyzePlanNodeTreeDisplayData parent = element.getParent(); + while (parent != null) { + path.add(parent); + parent = parent.getParent(); + } + Collections.reverse(path); + } + + /** + * Simply always return true. + * + * @return true if this element can have child elements, or + * false if it is always a leaf node. + */ + + public boolean allowsChildren(ExplainAnalyzePlanNodeTreeDisplayData element) { + return true; + } + + /** + * Returns the comparator used to order path elements of the specified + * depth. If enforcing order at this level is not intended, this method + * should return null. + */ + public Comparator getComparator(int depth) { + return new Comparator() { + @Override + public int compare(ExplainAnalyzePlanNodeTreeDisplayData o1, ExplainAnalyzePlanNodeTreeDisplayData o2) { + return o1.compareTo(o2); + } + + }; + } + + private void doDFS() { + /* + * depth-first-traversal to create parent-child relation + */ + Stack modelStack = new Stack(); + Stack dataStack = new Stack(); + boolean analyze = this.node.isAnalyze(); + modelStack.push(this.node); // node actual has the tree, which we will + // traverse to create the map + ExplainAnalyzePlanNodeTreeDisplayData nodeData = ExplainAnalyzePlanNodeTreeDisplayDataFactory.getInstance() + // its structure for display + .createData(this.node.getAnalysedPlanNode(), analyze); + nodeData.setParent(null); + dataStack.push(nodeData); + this.node.setVisited(false); + while (!modelStack.isEmpty()) { + UIModelAnalysedPlanNode parentNode = modelStack.pop(); + ExplainAnalyzePlanNodeTreeDisplayData parentData = dataStack.pop(); + nodeInfos.add((IDSGridDataRow) parentData); + nodes.add(parentData); + List children = parentNode.getChildren(); + for (UIModelAnalysedPlanNode childNode : children) { + ExplainAnalyzePlanNodeTreeDisplayData childData = ExplainAnalyzePlanNodeTreeDisplayDataFactory + .getInstance().createData(childNode.getAnalysedPlanNode(), analyze); + childData.setParent(parentData); + modelStack.push(childNode); + dataStack.push(childData); + childNode.setVisited(false); + } + } + } + + private void exportTreeFormatData(UIModelAnalysedPlanNode parentNode, boolean isAnalyze) { + OperationalNode operationalNode = parentNode.getOperationalNode(); + int sizeStr; + if (isAnalyze) { + sizeStr = MPPDBIDEConstants.STR_EXPLAIN_PLAN_ANALYZE_SIZE; + } else { + sizeStr = MPPDBIDEConstants.STR_EXPLAIN_PLAN_SIZE; + } + String[] strInfo = new String[sizeStr]; + spaces = levelIndentation(operationalNode); + String nodeType = operationalNode.getNodeName(); + strInfo[0] = spaces + nodeType; + double startupCost = operationalNode.getStartupCost(); + strInfo[1] = getObjecttoString(startupCost); + double totalCost = operationalNode.getTotalCost(); + strInfo[2] = getObjecttoString(totalCost); + long planRows = operationalNode.getPlanRows(); + strInfo[3] = getObjecttoString(planRows); + long planWidth = operationalNode.getPlanWidth(); + strInfo[4] = getObjecttoString(planWidth); + if (isAnalyze) { + handleIsAnalyze(operationalNode, strInfo); + } else { + String additionalInfo = buildAdditionalInfo(operationalNode); + strInfo[5] = additionalInfo; + } + listExec.add(strInfo); + ArrayList children = parentNode.getChildren(); + parentNode.setVisited(true); + for (UIModelAnalysedPlanNode child : children) { + if (!child.getVisited()) { + OperationalNode nodeChild = child.getOperationalNode(); + nodeChild.setIndentationLevel(operationalNode.getIndentationLevel() + 1); + exportTreeFormatData(child, isAnalyze); + } + } + } + + private void handleIsAnalyze(OperationalNode operationalNode, String[] strInfo) { + double actualMaxStartUpTime = operationalNode.getActualStartupTime(); + if (actualMaxStartUpTime == 0) { + actualMaxStartUpTime = operationalNode.getActualMaxStartupTime(); + } + strInfo[5] = getObjecttoString(actualMaxStartUpTime); + double actualTotalTime = operationalNode.getActualTotalTime(); + if (actualTotalTime == 0) { + actualTotalTime = operationalNode.getActualMaxTotalTime(); + } + strInfo[6] = getObjecttoString(actualTotalTime); + long actualRows = operationalNode.getActualRows(); + strInfo[7] = getObjecttoString(actualRows); + long actualLoopCount = operationalNode.getActualLoopCount(); + strInfo[8] = getObjecttoString(actualLoopCount); + String additionalInfo = buildAdditionalInfo(operationalNode); + strInfo[9] = additionalInfo; + } + + private String levelIndentation(OperationalNode opNode) { + int integerValue = opNode.getIndentationLevel(); + StringBuilder strBuilder = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + for (int i = 0; i < integerValue; i++) { + strBuilder = strBuilder.append(" "); + } + + String levelSpace = strBuilder.toString(); + return levelSpace; + } + + private String buildAdditionalInfo(OperationalNode op) { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + List info = op.getAdditionalInfo(analyzeOperationalNode); + if (info != null && info.size() != 0) { + for (int i = 0; i < info.size(); i++) { + String n1 = info.get(i).replaceAll(">", ">"); + String n2 = n1.replaceAll("<", "<"); + sb.append(n2); + if (i < info.size() - 1) { + sb.append(System.lineSeparator()); + } + } + return sb.toString(); + } + return ""; + } + + private String getObjecttoString(Object dataObject) { + if (dataObject instanceof Long) { + return Long.toString((Long) dataObject); + } else if (dataObject instanceof Double) { + return Double.toString((Double) dataObject); + } else { + return null == dataObject ? "" : dataObject.toString(); + } + } + + @Override + public void close() throws DatabaseOperationException, DatabaseCriticalException { + + } + + @Override + public void init() { + + } + + @Override + public List getNextBatch() throws DatabaseOperationException, DatabaseCriticalException { + this.isFirstBatchOver = true; + return nodeInfos; + } + + @Override + public List getAllFetchedRows() { + return this.nodeInfos; + } + + @Override + public boolean isEndOfRecords() { + return this.isFirstBatchOver; + } + + @Override + public int getRecordCount() { + return nodeInfos.size(); + } + + @Override + public IDSGridColumnProvider getColumnDataProvider() { + return this.columnDataProvider; + } + + @Override + public IDSGridColumnGroupProvider getColumnGroupProvider() { + return null; + } + + @Override + public TableMetaData getTable() { + return null; + } + + @Override + public Database getDatabse() { + return null; + } + + @Override + public boolean getResultTabDirtyFlag() { + return false; + } + + @Override + public void setResultTabDirtyFlag(boolean flag) { + + } + + /** + * Gets the summary. + * + * @return the summary + */ + public IQueryExecutionSummary getSummary() { + return summary; + } + + /** + * Sets the summary. + * + * @param summary the new summary + */ + public void setSummary(IQueryExecutionSummary summary) { + this.summary = summary; + } + + /** + * init + */ + @Override + public void init(IQueryResult irq, ArrayList debugInputValuesList, boolean isCallableStmt) + throws DatabaseOperationException, DatabaseCriticalException { + } + + /** + * gets the next batch + */ + @Override + public List getNextBatch(ArrayList debugInputValuesList) + throws DatabaseOperationException, DatabaseCriticalException { + return null; + } + + @Override + public void setFuncProcExport(boolean isFuncProcedureExport) { + } + + @Override + public boolean isFuncProcExport() { + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/ui/model/TreeGridColumnHeader.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/ui/model/TreeGridColumnHeader.java new file mode 100644 index 0000000000000000000000000000000000000000..e2e43d9c33ed6b6590122751bca39ace7409acb4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/explainplan/ui/model/TreeGridColumnHeader.java @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.explainplan.ui.model; + +/** + * + * Title: interface + * + * Description: The Interface TreeGridColumnHeader. + * + * @since 3.0.0 + */ +public interface TreeGridColumnHeader { + + /** + * The Constant LABEL_NODE_TYPE. + */ + public static final String LABEL_NODE_TYPE = "Node Type"; + + /** + * The Constant LABEL_STARTUP_COST. + */ + public static final String LABEL_STARTUP_COST = "Startup Cost"; + + /** + * The Constant LABEL_TOTAL_COST. + */ + public static final String LABEL_TOTAL_COST = "Total Cost"; + + /** + * The Constant LABEL_ROWS. + */ + public static final String LABEL_ROWS = "Rows"; + + /** + * The Constant LABEL_WIDTH. + */ + public static final String LABEL_WIDTH = "Width"; + + /** + * The Constant LABEL_ACTUAL_STARTUP_TIME. + */ + public static final String LABEL_ACTUAL_STARTUP_TIME = "Actual Startup Time"; + + /** + * The Constant LABEL_ACTUAL_TOTAL_TIME. + */ + public static final String LABEL_ACTUAL_TOTAL_TIME = "Actual Total Time"; + + /** + * The Constant LABEL_ACTUAL_ROWS. + */ + public static final String LABEL_ACTUAL_ROWS = "Actual Rows"; + + /** + * The Constant LABEL_ACTUAL_LOOPS. + */ + public static final String LABEL_ACTUAL_LOOPS = "Actual Loops"; + + /** + * The Constant LABEL_ADDITIONAL_INFO. + */ + public static final String LABEL_ADDITIONAL_INFO = "Additional Info"; + + /** + * The Constant PROP_NODE_TYPE. + */ + + public static final String PROP_NODE_TYPE = "nodeType"; + + /** + * The Constant PROP_STARTUP_COST. + */ + public static final String PROP_STARTUP_COST = "startupCost"; + + /** + * The Constant PROP_TOTAL_COST. + */ + public static final String PROP_TOTAL_COST = "totalCost"; + + /** + * The Constant PROP_ROWS. + */ + public static final String PROP_ROWS = "planRows"; + + /** + * The Constant PROP_WIDTH. + */ + public static final String PROP_WIDTH = "planWidth"; + + /** + * The Constant PROP_ACTUAL_STARTUP_TIME. + */ + public static final String PROP_ACTUAL_STARTUP_TIME = "actualStartupTime"; + + /** + * The Constant PROP_ACTUAL_TOTAL_TIME. + */ + public static final String PROP_ACTUAL_TOTAL_TIME = "actualTotalTime"; + + /** + * The Constant PROP_ACTUAL_ROWS. + */ + public static final String PROP_ACTUAL_ROWS = "actualRows"; + + /** + * The Constant PROP_ACTUAL_LOOPS. + */ + public static final String PROP_ACTUAL_LOOPS = "actualLoops"; + + /** + * The Constant PROP_ADDITIONAL_INFO. + */ + public static final String PROP_ADDITIONAL_INFO = "additionalInfo"; + + /** + * The Constant COLUMN_LABEL_HEAVIEST. + */ + public static final String COLUMN_LABEL_HEAVIEST = "HEAVY"; + + /** + * The Constant COLUMN_LABEL_COSTLIEST. + */ + public static final String COLUMN_LABEL_COSTLIEST = "COSTLY"; + + /** + * The Constant COLUMN_LABEL_SLOWEST. + */ + public static final String COLUMN_LABEL_SLOWEST = "SLOW"; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/AbstractExplainPlanPropertyCore.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/AbstractExplainPlanPropertyCore.java new file mode 100644 index 0000000000000000000000000000000000000000..690e3c48ea61d7e82a110161c9a444b452f72eea --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/AbstractExplainPlanPropertyCore.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.visualexplainplan; + +import org.opengauss.mppdbide.presentation.DummyTerminalExecutionConnectionInfra; +import org.opengauss.mppdbide.presentation.TerminalExecutionConnectionInfra; +import org.opengauss.mppdbide.presentation.objectproperties.handler.PropertyHandlerCore; + +/** + * + * Title: class + * + * Description: The Class AbstractExplainPlanPropertyCore. + * + * @since 3.0.0 + */ +public abstract class AbstractExplainPlanPropertyCore extends PropertyHandlerCore + implements IAbstractExplainPlanPropertyCoreLabelFactory { + private int explainPlanType; + + /** + * Instantiates a new abstract explain plan property core. + * + * @param explainPlanType the explain plan type + */ + public AbstractExplainPlanPropertyCore(int explainPlanType) { + this.explainPlanType = explainPlanType; + } + + /** + * Gets the explain plan type. + * + * @return the explain plan type + */ + public int getExplainPlanType() { + return explainPlanType; + } + + /** + * Sets the explain plan type. + * + * @param explainPlanType the new explain plan type + */ + public void setExplainPlanType(int explainPlanType) { + this.explainPlanType = explainPlanType; + } + + /** + * Checks if is executable. + * + * @return true, if is executable + */ + @Override + public boolean isExecutable() { + return true; + } + + /** + * Gets the term connection. + * + * @return the term connection + */ + @Override + public TerminalExecutionConnectionInfra getTermConnection() { + if (null == connInfra) { + this.connInfra = new DummyTerminalExecutionConnectionInfra(); + } + + return connInfra; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/AnalysedPlanNodeProperties.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/AnalysedPlanNodeProperties.java new file mode 100644 index 0000000000000000000000000000000000000000..93654600302836baa483c299bfcdd174003c4911 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/AnalysedPlanNodeProperties.java @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.visualexplainplan; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.explainplan.service.AnalysedPlanNode; +import org.opengauss.mppdbide.presentation.objectproperties.ConvertToObjectPropertyData; +import org.opengauss.mppdbide.presentation.objectproperties.DNIntraNodeDetailsColumn; +import org.opengauss.mppdbide.presentation.objectproperties.IObjectPropertyData; +import org.opengauss.mppdbide.presentation.objectproperties.IServerObjectProperties; +import org.opengauss.mppdbide.presentation.objectproperties.handler.IPropertyDetail; +import org.opengauss.mppdbide.presentation.objectproperties.handler.PropertyHandlerCore; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MathUtils; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class AnalysedPlanNodeProperties. + * + * @since 3.0.0 + */ +public class AnalysedPlanNodeProperties implements IServerObjectProperties, IPropertyDetail { + + private AnalysedPlanNode planNode; + private PropertyHandlerCore core; + + /** + * The tab name list. + */ + protected List tabNameList; + + /** + * The node properties. + */ + protected List> nodeProperties; + + /** + * Instantiates a new analysed plan node properties. + * + * @param planNode the plan node + * @param explainPlanNodePropertiesCore the explain plan node properties core + */ + public AnalysedPlanNodeProperties(AnalysedPlanNode planNode, PropertyHandlerCore explainPlanNodePropertiesCore) { + this.planNode = planNode; + this.core = explainPlanNodePropertiesCore; + } + + /** + * Gets the object name. + * + * @return the object name + */ + @Override + public String getObjectName() { + return this.planNode.getNodeType(); + } + + /** + * Gets the header. + * + * @return the header + */ + @Override + public String getHeader() { + return getUniqueID() + ". " + this.planNode.getNodeType(); + } + + /** + * Gets the unique ID. + * + * @return the unique ID + */ + @Override + public String getUniqueID() { + return "" + planNode.getNodeSequenceNum(); + } + + /** + * Gets the all properties. + * + * @param conn the conn + * @return the all properties + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws MPPDBIDEException the MPPDBIDE exception + */ + @Override + public List getAllProperties(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException, MPPDBIDEException { + tabNameList = new ArrayList(5); + nodeProperties = new ArrayList>(1); + tabNameList.add(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PER_NODE_DETAILS_GENERAL_TAB)); + + nodeProperties.add(getGeneralProperty()); + + List l1 = ConvertToObjectPropertyData.getObjectPropertyDataGeneric(tabNameList, + nodeProperties); + List l2 = getDNSpecificDetails(); + if (null != l2) { + l1.addAll(l2); + } + + return l1; + } + + private List getDNSpecificDetails() + throws DatabaseOperationException, DatabaseCriticalException { + Map> data = planNode.getNodeSpecificDNProperties(); + if (null != data) { + List colgrp = planNode.getPerDNSpecificColumnGroupingInfo(); + ArrayList title = new ArrayList(1); + title.add(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PER_NODE_DETAILS_PERDN_TAB)); + + DNIntraNodeDetailsColumn firstColDetails = new DNIntraNodeDetailsColumn(); + firstColDetails.setColCount(1); + firstColDetails.setGroupColumnName( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_PERDN_DN_COLUMNGRP)); + firstColDetails.setColnames(new ArrayList(1)); + firstColDetails.getColnames() + .add(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_PERDN_DN_COLUMN)); + colgrp.add(0, firstColDetails); + + List l1 = ConvertToObjectPropertyData.getObjectPropertyDataGenericGroupedColumn(title, + data, colgrp); + + return l1; + } + + return null; + } + + private List getGeneralProperty() { + List props = new ArrayList(5); + String[] genPropHeader = {MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PER_NODE_COLUMN_PROP), + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PER_NODE_COLUMN_VALUE)}; + props.add(genPropHeader); + + props.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_ANALYSISNODE_OUTPUT), + planNode.getFormatedOutput(",")).getProp()); + + props.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_ANALYSISNODE_ANALYSIS), + planNode.getAnalysis()).getProp()); + + double deviation = planNode.getPlanDeviationByRecordCount(planNode.getPlanRecordCount(), + planNode.getRecordCount()); + + props.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROP_ANALYSISNODE_ROWSOUTPUTDEVIATION), + MathUtils.roundDoubleValues(deviation, 2)).getProp()); + + props = addNodeSpecificDetails(planNode, props); + return props; + } + + private List addNodeSpecificDetails(AnalysedPlanNode planNode2, List props) { + return planNode2.getNodeSpecificProperties(props); + + } + + /** + * Gets the database. + * + * @return the database + */ + @Override + public Database getDatabase() { + + return null; + } + + /** + * Gets the property core. + * + * @return the property core + */ + @Override + public PropertyHandlerCore getPropertyCore() { + return this.core; + } + + /** + * Objectproperties. + * + * @return the list + */ + @Override + public List objectproperties() { + + return new ArrayList(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/BasicUIModelPlanNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/BasicUIModelPlanNode.java new file mode 100644 index 0000000000000000000000000000000000000000..246287c771fd3775ab1563eaadadfa4bcf4e243b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/BasicUIModelPlanNode.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.visualexplainplan; + +/** + * Title: BasicUIModelPlanNode + * + * @since 3.0.0 + */ +public abstract class BasicUIModelPlanNode { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/DSSpaceTreeLayoutAlgorithm.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/DSSpaceTreeLayoutAlgorithm.java new file mode 100644 index 0000000000000000000000000000000000000000..177af39162ff45b1eb4b29f07ee15e661ab79853 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/DSSpaceTreeLayoutAlgorithm.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.visualexplainplan; + +import org.eclipse.gef.layout.algorithms.SpaceTreeLayoutAlgorithm; + +/** + * Title: DSSpaceTreeLayoutAlgorithm + * + * @since 3.0.0 + */ +public class DSSpaceTreeLayoutAlgorithm extends SpaceTreeLayoutAlgorithm { + + /** + * Instantiates a new DS space tree layout algorithm. + * + * @param orientation the orientation + */ + public DSSpaceTreeLayoutAlgorithm(int orientation) { + super(orientation); + customize(); + } + + private void customize() { + setLeafGap(50); + setBranchGap(65); + setLayerGap(50); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/ExecutionPlanTextDisplayGrid.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/ExecutionPlanTextDisplayGrid.java new file mode 100644 index 0000000000000000000000000000000000000000..bba435fce755960c949e98d80c352b4c822ad0ac --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/ExecutionPlanTextDisplayGrid.java @@ -0,0 +1,399 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.visualexplainplan; + +import java.sql.Types; +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DefaultParameter; +import org.opengauss.mppdbide.bl.serverdatacache.IQueryResult; +import org.opengauss.mppdbide.bl.serverdatacache.ResultSetColumn; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.sqlhistory.IQueryExecutionSummary; +import org.opengauss.mppdbide.presentation.edittabledata.DSResultSetGridColumnDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnGroupProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class ExecutionPlanTextDisplayGrid. + * + * @since 3.0.0 + */ +public class ExecutionPlanTextDisplayGrid implements IDSGridDataProvider { + private List rows; + private IDSGridColumnProvider columnProvider; + private UIModelAnalysedPlanNode planRootNode; + private IQueryExecutionSummary summary; + private boolean analyze; + private double totalRuntime; + + /** + * The first batch over. + */ + boolean firstBatchOver; + + /** + * Instantiates a new execution plan text display grid. + * + * @param uiModelAnalysedPlanNode the ui model analysed plan node + * @param totalRuntime the total runtime + */ + public ExecutionPlanTextDisplayGrid(UIModelAnalysedPlanNode uiModelAnalysedPlanNode, double totalRuntime) { + this.planRootNode = uiModelAnalysedPlanNode; + this.analyze = uiModelAnalysedPlanNode.isAnalyze(); + this.totalRuntime = totalRuntime; + } + + /** + * Inits the. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void init() throws DatabaseOperationException, DatabaseCriticalException { + ResultSetColumn[] col = new ResultSetColumn[1]; + col[0] = new ResultSetColumn(0); + col[0].setColumnName(MessageConfigLoader.getProperty(IMessagesConstants.COLUMN_HEADER_QUERY_PLAN)); + col[0].setDatatypeName("STRING"); + col[0].setDataType(Types.VARCHAR); + DSResultSetGridColumnDataProvider colProvider = new DSResultSetGridColumnDataProvider(); + colProvider.init(1, col); + this.columnProvider = colProvider; + + this.rows = addToDataRows(this.planRootNode, 0, this.analyze); + + if (this.analyze) { + StringBuilder sb = new StringBuilder("Total runtime: "); + sb.append(this.totalRuntime); + sb.append("ms"); // unit check with Kalyan + DataRow runtime = new DataRow(1); + runtime.setValue(0, sb.toString()); + this.rows.add(runtime); + } + this.firstBatchOver = false; + } + + private List addToDataRows(UIModelAnalysedPlanNode node, int spacesParam, boolean isAnalyze) { + int spaces = spacesParam; + List allRows = new ArrayList(2); + DataRow subplanName = new DataRow(1); + + if (!("".equals(node.getSubplanName()))) { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + for (int i = 0; i < spaces; i++) { + sb.append(" "); + } + sb.append(node.getSubplanName()); + subplanName.setValue(0, sb.toString()); + allRows.add(subplanName); + spaces = spaces + 1; + } + + DataRow nodeHead = new DataRow(1); + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + for (int i = 0; i < spaces; i++) { + sb.append(" "); + } + if (spaces != 0) { + sb.append("-> "); + } + sb.append(node.toText(isAnalyze)); + + nodeHead.setValue(0, sb.toString()); + + List additional = new ArrayList(2); + List additionalInfo = new ArrayList(2); + if (node.getAdditionalInfo(isAnalyze) != null && node.getAdditionalInfo(isAnalyze).size() != 0) { + additional.addAll(node.getAdditionalInfo(isAnalyze)); + } + + for (String oneInfo : additional) { + StringBuilder sb1 = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + for (int i = 0; i < spaces; i++) { + sb1.append(" "); + } + sb1.append(" "); + sb1.append(oneInfo); + DataRow addi = new DataRow(1); + addi.setValue(0, sb1.toString()); + additionalInfo.add(addi); + } + allRows.add(nodeHead); + allRows.addAll(additionalInfo); + + List children = node.getChildren(); + for (UIModelAnalysedPlanNode child : children) { + List rowForChild = addToDataRows(child, spaces + 1, isAnalyze); + allRows.addAll(rowForChild); + } + return allRows; + } + + /** + * Close. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + @Override + public void close() throws DatabaseOperationException, DatabaseCriticalException { + + } + + /** + * Gets the next batch. + * + * @return the next batch + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + @Override + public List getNextBatch() throws DatabaseOperationException, DatabaseCriticalException { + if (!this.firstBatchOver) { + this.firstBatchOver = true; + return rows; + } + return null; + } + + /** + * Gets the all fetched rows. + * + * @return the all fetched rows + */ + @Override + public List getAllFetchedRows() { + return rows; + } + + /** + * Checks if is end of records. + * + * @return true, if is end of records + */ + @Override + public boolean isEndOfRecords() { + return this.firstBatchOver; + } + + /** + * Gets the record count. + * + * @return the record count + */ + @Override + public int getRecordCount() { + return rows.size(); + } + + /** + * Gets the column data provider. + * + * @return the column data provider + */ + @Override + public IDSGridColumnProvider getColumnDataProvider() { + return this.columnProvider; + } + + /** + * Pre destroy. + */ + @Override + public void preDestroy() { + this.planRootNode = null; + this.summary = null; + if (this.rows != null) { + this.rows.clear(); + } + } + + /** + * Gets the summary. + * + * @return the summary + */ + public IQueryExecutionSummary getSummary() { + return summary; + } + + /** + * Gets the result tab dirty flag. + * + * @return the result tab dirty flag + */ + @Override + public boolean getResultTabDirtyFlag() { + + return false; + } + + /** + * Gets the column group provider. + * + * @return the column group provider + */ + @Override + public IDSGridColumnGroupProvider getColumnGroupProvider() { + + return null; + } + + /** + * Sets the result tab dirty flag. + * + * @param flag the new result tab dirty flag + */ + @Override + public void setResultTabDirtyFlag(boolean flag) { + + } + + /** + * Sets the summary. + * + * @param summary the new summary + */ + public void setSummary(IQueryExecutionSummary summary) { + this.summary = summary; + } + + /** + * + * Title: class + * + * Description: The Class DataRow. + */ + static class DataRow implements IDSGridDataRow { + + /** + * The values. + */ + String[] values; + + /** + * Instantiates a new data row. + * + * @param cols the cols + */ + DataRow(int cols) { + values = new String[cols]; + } + + /** + * Gets the values. + * + * @return the values + */ + @Override + public Object[] getValues() { + return values; + } + + /** + * Gets the value. + * + * @param columnIndex the column index + * @return the value + */ + @Override + public Object getValue(int columnIndex) { + return values[columnIndex]; + } + + /** + * Gets the cloned values. + * + * @return the cloned values + */ + @Override + public Object[] getClonedValues() { + return values.clone(); + } + + /** + * Sets the value. + * + * @param columnIndex the column index + * @param value the value + */ + public void setValue(int columnIndex, String value) { + values[columnIndex] = value; + } + + } + + /** + * Gets the table. + * + * @return the table + */ + @Override + public TableMetaData getTable() { + + return null; + } + + /** + * Gets the databse. + * + * @return the databse + */ + @Override + public Database getDatabse() { + + return null; + } + + /** + * init + */ + @Override + public void init(IQueryResult irq, ArrayList debugInputValueList, boolean isCallableStmt) + throws DatabaseOperationException, DatabaseCriticalException { + } + + /** + * gets the next batch + */ + @Override + public List getNextBatch(ArrayList debugInputValueList) + throws DatabaseOperationException, DatabaseCriticalException { + return null; + } + + @Override + public void setFuncProcExport(boolean isFuncProcExport) { + } + + @Override + public boolean isFuncProcExport() { + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/ExplainPlanNodeDetails.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/ExplainPlanNodeDetails.java new file mode 100644 index 0000000000000000000000000000000000000000..a6c974c0fddacbd8683c8bd91dd46239687ee77a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/ExplainPlanNodeDetails.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.visualexplainplan; + +import org.opengauss.mppdbide.explainplan.service.AnalysedPlanNode; + +/** + * + * Title: class + * + * Description: The Class ExplainPlanNodeDetails. + * + * @since 3.0.0 + */ +public class ExplainPlanNodeDetails implements IExplainPlanNodeDetails { + private AnalysedPlanNode coreNode; + + /** + * Instantiates a new explain plan node details. + * + * @param node the node + */ + public ExplainPlanNodeDetails(AnalysedPlanNode node) { + this.coreNode = node; + } + + /** + * Gets the node sequence num. + * + * @return the node sequence num + */ + @Override + public int getNodeSequenceNum() { + return this.coreNode.getNodeSequenceNum(); + } + + /** + * Gets the node title. + * + * @return the node title + */ + @Override + public String getNodeTitle() { + return this.coreNode.getNodeUniqueName(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/ExplainPlanNodePropertiesCore.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/ExplainPlanNodePropertiesCore.java new file mode 100644 index 0000000000000000000000000000000000000000..8532d15751a57002186fd54598b4fe0fe39d0c9f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/ExplainPlanNodePropertiesCore.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.visualexplainplan; + +import org.opengauss.mppdbide.explainplan.service.AnalysedPlanNode; +import org.opengauss.mppdbide.presentation.IWindowDetail; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class ExplainPlanNodePropertiesCore. + * + * @since 3.0.0 + */ +public class ExplainPlanNodePropertiesCore extends AbstractExplainPlanPropertyCore { + private AnalysedPlanNode planNode; + private AnalysedPlanNodeProperties nodeProperties; + + /** + * Instantiates a new explain plan node properties core. + * + * @param obj the obj + */ + public ExplainPlanNodePropertiesCore(AnalysedPlanNode obj) { + super(IAbstractExplainPlanPropertyCoreLabelFactory.VISUAL_EXPLAIN_PERNODEPROPERTIES_STACK); + this.planNode = obj; + this.nodeProperties = new AnalysedPlanNodeProperties(planNode, this); + setPropertiesObject(this.nodeProperties); + } + + /** + * Gets the window details. + * + * @return the window details + */ + @Override + public IWindowDetail getWindowDetails() { + if (null == details) { + this.details = new ExplainPlanNodeWindowDetails(nodeProperties.getUniqueID(), nodeProperties.getHeader()); + } + return details; + } + + /** + * + * Title: class + * + * Description: The Class ExplainPlanNodeWindowDetails. + */ + private static final class ExplainPlanNodeWindowDetails implements IWindowDetail { + private String nodeSequenceNum; + private String nodeTitle; + + private ExplainPlanNodeWindowDetails(String nodeSequenceNum, String nodeTitle) { + super(); + this.nodeSequenceNum = nodeSequenceNum; + this.nodeTitle = nodeTitle; + } + + @Override + public String getTitle() { + return this.nodeTitle; + } + + @Override + public String getUniqueID() { + return this.nodeSequenceNum; + } + + @Override + public String getIcon() { + return null; + } + + @Override + public String getShortTitle() { + return nodeTitle + " - " + + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PER_NODE_DETAILS_PART_LBL); + } + + @Override + public boolean isCloseable() { + return true; + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/ExplainPlanOverAllPlanPropertiesCore.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/ExplainPlanOverAllPlanPropertiesCore.java new file mode 100644 index 0000000000000000000000000000000000000000..1c450fbfc9e7a4b44f904a3ef730f667b403487f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/ExplainPlanOverAllPlanPropertiesCore.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.visualexplainplan; + +import org.opengauss.mppdbide.presentation.IWindowDetail; + +/** + * + * Title: class + * + * Description: The Class ExplainPlanOverAllPlanPropertiesCore. + * + * @since 3.0.0 + */ +public class ExplainPlanOverAllPlanPropertiesCore extends AbstractExplainPlanPropertyCore { + private ExplainPlanPresentation presentation; + private ExplainPlanOverAllProperties nodeProperties; + + /** + * Instantiates a new explain plan over all plan properties core. + * + * @param obj the obj + */ + public ExplainPlanOverAllPlanPropertiesCore(ExplainPlanPresentation obj) { + super(IAbstractExplainPlanPropertyCoreLabelFactory.VISUAL_EXPLAIN_OVERLLPROPERTIES_STACK); + this.presentation = obj; + this.nodeProperties = new ExplainPlanOverAllProperties(presentation, this); + setPropertiesObject(this.nodeProperties); + } + + /** + * Gets the window details. + * + * @return the window details + */ + @Override + public IWindowDetail getWindowDetails() { + return null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/ExplainPlanOverAllProperties.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/ExplainPlanOverAllProperties.java new file mode 100644 index 0000000000000000000000000000000000000000..329111b2ce0341eb81b7020f485a6210ae7a7742 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/ExplainPlanOverAllProperties.java @@ -0,0 +1,275 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.visualexplainplan; + +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.explainplan.service.AnalysedPlanNode; +import org.opengauss.mppdbide.presentation.objectproperties.ConvertToObjectPropertyData; +import org.opengauss.mppdbide.presentation.objectproperties.IObjectPropertyData; +import org.opengauss.mppdbide.presentation.objectproperties.IServerObjectProperties; +import org.opengauss.mppdbide.presentation.objectproperties.handler.IPropertyDetail; +import org.opengauss.mppdbide.presentation.objectproperties.handler.PropertyHandlerCore; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MathUtils; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class ExplainPlanOverAllProperties. + * + * @since 3.0.0 + */ +public class ExplainPlanOverAllProperties implements IServerObjectProperties, IPropertyDetail { + + private ExplainPlanPresentation presentation; + private PropertyHandlerCore core; + + /** + * The tab name list. + */ + protected List tabNameList; + + /** + * The node properties. + */ + protected List> nodeProperties; + + /** + * Instantiates a new explain plan over all properties. + * + * @param presentation the presentation + * @param explainPlanOverAllPlanPropertiesCore the explain plan over all plan properties core + */ + public ExplainPlanOverAllProperties(ExplainPlanPresentation presentation, + PropertyHandlerCore explainPlanOverAllPlanPropertiesCore) { + this.presentation = presentation; + this.core = explainPlanOverAllPlanPropertiesCore; + } + + /** + * Gets the property core. + * + * @return the property core + */ + @Override + public PropertyHandlerCore getPropertyCore() { + return this.core; + } + + /** + * Objectproperties. + * + * @return the list + */ + @Override + public List objectproperties() { + return new ArrayList(); + } + + /** + * Gets the object name. + * + * @return the object name + */ + @Override + public String getObjectName() { + return "ExplainPlanOverAllProperties.getObjectName"; + } + + /** + * Gets the header. + * + * @return the header + */ + @Override + public String getHeader() { + return "ExplainPlanOverAllProperties.getHeader"; + } + + /** + * Gets the unique ID. + * + * @return the unique ID + */ + @Override + public String getUniqueID() { + return "This is unique for Now"; + } + + /** + * Gets the all properties. + * + * @param conn the conn + * @return the all properties + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws MPPDBIDEException the MPPDBIDE exception + */ + @Override + public List getAllProperties(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException, MPPDBIDEException { + tabNameList = new ArrayList(5); + nodeProperties = new ArrayList>(1); + tabNameList.add(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_OVERALL_DETAILS_GENERAL_TAB)); + + nodeProperties.add(getGeneralProperty()); + + tabNameList.add(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_OVERALL_DETAILS_ALLNODES_TAB)); + + nodeProperties.add(getAllNodeDetails()); + tabNameList.add(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_PROPERTIES_EXEC_PLAN_TITLE)); + nodeProperties.add(getExecPlanDetails()); + return ConvertToObjectPropertyData.getObjectPropertyDataGeneric(tabNameList, nodeProperties); + } + + private List getAllNodeDetails() { + List props = new ArrayList(5); + String[] genPropHeader = { + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_NODENAME), + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_ANALYSIS), + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_ROWSOUTPUT), + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_ROWSOUTPUTDEVIATION), + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_EXECUTIONTIME), + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_CONTRIBUTION), + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_SELFCOST), + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_TOTALCOST)}; + props.add(genPropHeader); + + AnalysedPlanNode rootNode = this.presentation.getAnalysedPlanOutput().getAnalysedPlanNode(); + + getAllNodesInfo(props, rootNode, 1); + + return props; + } + + private List getExecPlanDetails() { + List props = new ArrayList(5); + String[] genPropHeader = { + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_NODENAME), + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_EXEC_PLAN_COLUMN_ENTITYNAME), + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_EXEC_PLAN_COLUMN_COST), + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_EXEC_PLAN_COLUMN_ROWS), + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_EXEC_PLAN_COLUMN_LOOPS), + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_EXEC_PLAN_COLUMN_WIDTH), + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_EXEC_PLAN_COLUMN_ACTUAL_ROWS), + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_EXEC_PLAN_COLUMN_ACTUAL_TIME)}; + props.add(genPropHeader); + + AnalysedPlanNode rootNode = this.presentation.getAnalysedPlanOutput().getAnalysedPlanNode(); + + getExecPlanInfo(props, rootNode, 1); + + return props; + } + + private int getAllNodesInfo(List props, AnalysedPlanNode rootNode, int sNoParam) { + int sno = sNoParam; + props.add(detailsInfo(rootNode, sno++)); + + for (AnalysedPlanNode node : rootNode.getChildNodeStats()) { + sno = getAllNodesInfo(props, node, sno); + } + + return sno; + } + + private int getExecPlanInfo(List props, AnalysedPlanNode rootNode, int sNoParam) { + int sno = sNoParam; + props.add(execPlanDetailsInfo(rootNode, sno++, props)); + + for (AnalysedPlanNode node : rootNode.getChildNodeStats()) { + sno = getExecPlanInfo(props, node, sno); + } + + return sno; + } + + private Object[] execPlanDetailsInfo(AnalysedPlanNode rootNode, int sno, List props) { + + Object[] colInfo = new Object[8]; + int jindex = 0; + colInfo[jindex++] = rootNode.getNodeUniqueNameWithType(); // node name + colInfo[jindex++] = rootNode.getChild().getEntityName(); + colInfo[jindex++] = rootNode.getTotalCost(); + colInfo[jindex++] = rootNode.getChild().getPlanRows(); + colInfo[jindex++] = rootNode.getChild().getActualLoopCount(); + colInfo[jindex++] = rootNode.getChild().getPlanWidth(); + colInfo[jindex++] = rootNode.getChild().getActualRows(); + colInfo[jindex++] = rootNode.getChild().getActualTotalTime(); + return colInfo; + + } + + private Object[] detailsInfo(AnalysedPlanNode rootNode, int sno) { + double deviation = rootNode.getPlanDeviationByRecordCount(rootNode.getPlanRecordCount(), + rootNode.getRecordCount()); + + Object[] colInfo = new Object[8]; + int index = 0; + // node name + colInfo[index++] = rootNode.getNodeUniqueNameWithType(); + // Analysis + colInfo[index++] = rootNode.getAnalysis(); + // RowsOutput + colInfo[index++] = rootNode.getRecordCount(); + // RowsOutput Deviation + colInfo[index++] = MathUtils.roundDoubleValues(deviation, 2); + // timeTaken + colInfo[index++] = MathUtils.roundDoubleValues(rootNode.getSelfTotalTime(), 2); + // Contribution + colInfo[index++] = MathUtils.roundDoubleValues(rootNode.getSelfTimeContributionInOverAllPlan(), 2); + // Self Cost + colInfo[index++] = MathUtils.roundDoubleValues(rootNode.getSelfCost(), 2); + // Total Cost + colInfo[index++] = MathUtils.roundDoubleValues(rootNode.getTotalCost(), 2); + + return colInfo; + + } + + private List getGeneralProperty() { + List props = new ArrayList(5); + String[] genPropHeader = { + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_OVERALL_DETAILS_GENERAL_COLUMN_PROP), + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_OVERALL_DETAILS_GENERAL_COLUMN_VALUE)}; + props.add(genPropHeader); + props.add(new ServerProperty( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_OVERALL_DETAILS_ROOTNODE_TOTALRUNTIME), + this.presentation.getRootNode().getTotalRuntime()).getProp()); + return props; + } + + /** + * Gets the database. + * + * @return the database + */ + @Override + public Database getDatabase() { + + return null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/ExplainPlanPresentation.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/ExplainPlanPresentation.java new file mode 100644 index 0000000000000000000000000000000000000000..34b4557476c5cd1e01b5cf35a4155d7ff1aed828 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/ExplainPlanPresentation.java @@ -0,0 +1,418 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.visualexplainplan; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.eclipse.gef.graph.Graph; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DatabaseUtils; +import org.opengauss.mppdbide.bl.serverdatacache.IQueryResult; +import org.opengauss.mppdbide.explainplan.nodetypes.RootPlanNode; +import org.opengauss.mppdbide.explainplan.service.AnalysedPlanNode; +import org.opengauss.mppdbide.explainplan.service.ExplainPlanAnlysisService; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.MaxLineBufferedReader; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.Message; +import org.opengauss.mppdbide.utils.messaging.MessageQueue; +import org.opengauss.mppdbide.utils.messaging.MessageType; + +/** + * + * Title: class + * + * Description: The Class ExplainPlanPresentation. + * + * @since 3.0.0 + */ +public class ExplainPlanPresentation { + private static final double EXPALIN_PLAN_DUMMY_MAX_SIZE_IN_MB = 1; + + private DBConnection conn = null; + private String allQuery; + private String query; + private String queryWithExplainPretext; + private MessageQueue msgQ; + private static final String PRE_TEXT_DETAILED = "explain (analyze, verbose, format json, costs true, cpu true, " + + "buffers true, timing true) "; + private UIModelAnalysedPlanNode analysedPlanOutput; + private List flattenedExplainPlan; + private List flattenedExplainPlanEdges; + private Map dnViewofExplainPlan; + private RootPlanNode planRootNode; + private Database database; + + + /** + * Instantiates a new explain plan presentation. + * + * @param query2 the query 2 + * @param queryArray the query array + * @param messageQueue the message queue + * @param conn2 the conn 2 + * @param db the db + */ + public ExplainPlanPresentation(String allQuery, String query, MessageQueue messageQueue, DBConnection conn2, + Database db) { + this.allQuery = allQuery; + this.database = db; + this.conn = conn2; + this.msgQ = messageQueue; + this.query = query; + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + return this.database; + } + + /** + * Do explain plan analysis. + * + * @param executionPlanFeatureCrossCheck the execution plan feature cross check + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public void doExplainPlanAnalysis(boolean executionPlanFeatureCrossCheck) throws MPPDBIDEException { + dnLevelExplainPlanQueryArray(executionPlanFeatureCrossCheck); + + doFlattenPlan(); + } + + private void consoleLogExecutionFailure(MPPDBIDEException exception) { + String message = MessageConfigLoader.getProperty(IMessagesConstants.EXECUTION_FAILED_ITEM, + MPPDBIDEConstants.LINE_SEPARATOR + " Plan Query:" + this.queryWithExplainPretext + + MPPDBIDEConstants.LINE_SEPARATOR, + exception.getErrorCode(), + exception.getServerMessage() == null ? exception.getDBErrorMessage() : exception.getServerMessage()); + msgQ.push(new Message(MessageType.ERROR, message)); + MPPDBIDELoggerUtility.error("ExplainPlan: Failed to execute query", exception); + } + + private void resetAutoCommit(boolean isAutoCommitChanged) { + if (isAutoCommitChanged) { + conn.rollback(); + try { + conn.getConnection().setAutoCommit(true); + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Unable to reset Autocommit state", exception); + } + } + } + + private void dnLevelExplainPlanQueryArray(boolean executionPlanFeatureCrossCheck) throws MPPDBIDEException { + String jsonOutput = ""; + // testing flow + if (executionPlanFeatureCrossCheck) { + jsonOutput = getDummyJsonFromFile(); + if (null == jsonOutput) { + MPPDBIDELoggerUtility.error("plan read error"); + return; + } + } + // normal flow + else { + IQueryResult result = null; + boolean isAutoCommitChanged = false; + + /* + * 1. Get a connection from the database. DO NOT FREE CONNECTION IN + * THIS METHOD. CALLER WILL HANDLE IT! + */ + + try { + if (conn.getConnection().getAutoCommit()) { + conn.getConnection().setAutoCommit(false); + isAutoCommitChanged = true; + } + } catch (SQLException exception) { + msgQ.push(new Message(MessageType.ERROR, exception.getMessage())); + MPPDBIDELoggerUtility.error("ExplainPlanPresentation: Explain query failed.", exception); + return; + } + result = executeExplainQuery(isAutoCommitChanged, query); + + jsonOutput = getJsonPlan(result, isAutoCommitChanged); + } + + ExplainPlanAnlysisService planAnalysis = new ExplainPlanAnlysisService(jsonOutput); + this.setAnalysedPlanOutput(UIModelConverter.covertToUIModel(planAnalysis.doAnalysis())); + this.planRootNode = planAnalysis.getRootPlan(); + } + + private String getDummyJsonFromFile() { + MaxLineBufferedReader reader = null; + InputStreamReader inputStream = null; + FileInputStream file = null; + StringBuilder stringBuilder = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + try { + File jsonFile = new File(MPPDBIDEConstants.JSON_PLAN_DUMP_FILE); + long fileSize = Files.size(jsonFile.toPath()) / 1024 * 1024; + if (fileSize > EXPALIN_PLAN_DUMMY_MAX_SIZE_IN_MB) { + MPPDBIDELoggerUtility.error("file read error"); + return null; + } + file = new FileInputStream(MPPDBIDEConstants.JSON_PLAN_DUMP_FILE); + inputStream = new InputStreamReader(file, StandardCharsets.UTF_8); // test-flow + reader = new MaxLineBufferedReader(inputStream); + String line = null; + while ((line = reader.readMaxLenLine()) != null) { + stringBuilder.append(line); + stringBuilder.append(MPPDBIDEConstants.LINE_SEPARATOR); + } + stringBuilder.deleteCharAt(stringBuilder.length() - 1); + } catch (FileNotFoundException exception) { + MPPDBIDELoggerUtility.error("Json File not found", exception); + return null; + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("file read error", exception); + return null; + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("file read error", exception); + return null; + } finally { + closeResources(reader, inputStream, file); + } + + return stringBuilder.toString(); + } + + private void closeResources(MaxLineBufferedReader reader, InputStreamReader inputStream, FileInputStream file) { + File jsonFile = new File(MPPDBIDEConstants.JSON_PLAN_DUMP_FILE); + try { + Files.delete(jsonFile.toPath()); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("error while deleting old file", exception); + } + try { + if (null != reader) { + reader.close(); + } + if (null != inputStream) { + inputStream.close(); + } + if (null != file) { + file.close(); + } + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("exception while closing resources", exception); + } + } + + private String getJsonPlan(IQueryResult result, boolean isAutoCommitChanged) throws DatabaseOperationException { + ResultSet rs = null; + String jsonOutput = ""; + + if (result != null) { + rs = result.getResultsSet(); + } + try { + if (rs != null && rs.next()) { + jsonOutput = rs.getString(1); + } + } catch (SQLException exception) { + msgQ.push(new Message(MessageType.ERROR, exception.getMessage())); + MPPDBIDELoggerUtility.error("ExplainPlanPresentation: explain plan query failed.", exception); + throw new DatabaseOperationException(IMessagesConstants.VIS_EXPLAIN_JSON_PARSING_FAILED); + } catch (Exception exception) { + msgQ.push(new Message(MessageType.ERROR, exception.getMessage())); + MPPDBIDELoggerUtility.error("ExplainPlanPresentation: explain plan query failed.", exception); + throw new DatabaseOperationException(IMessagesConstants.VIS_EXPLAIN_JSON_PARSING_FAILED); + } finally { + closeResultSet(rs); + resetAutoCommit(isAutoCommitChanged); + } + return jsonOutput; + } + + private IQueryResult executeExplainQuery(boolean isAutoCommitChanged, String query) + throws DatabaseOperationException, DatabaseCriticalException { + /* 3. Execute the explain query after prepending with explain text */ + IQueryResult result = null; + String qry = query; + StringBuilder sb = new StringBuilder(ExplainPlanPresentation.PRE_TEXT_DETAILED); + sb.append(qry); + + this.queryWithExplainPretext = sb.toString(); + + try { + result = DatabaseUtils.executeOnSqlTerminal(this.queryWithExplainPretext, 10, conn, msgQ); + } catch (DatabaseOperationException e) { + consoleLogExecutionFailure(e); + resetAutoCommit(isAutoCommitChanged); + throw e; + } catch (DatabaseCriticalException e) { + consoleLogExecutionFailure(e); + resetAutoCommit(isAutoCommitChanged); + throw e; + } + return result; + } + + private void closeResultSet(ResultSet rs) { + try { + if (null != rs) { + rs.close(); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("ADAPTER: resultset close returned exception", exception); + } + } + + private void doFlattenPlan() { + flattenedExplainPlan = new ArrayList(5); + flattenedExplainPlanEdges = new ArrayList(5); + analysedPlanOutput.flatten(flattenedExplainPlan, flattenedExplainPlanEdges); + } + + /** + * Gets the query. + * + * @return the query + */ + public String getAllQuery() { + return this.allQuery; + } + + /** + * Gets the analysed plan output. + * + * @return the analysed plan output + */ + public UIModelAnalysedPlanNode getAnalysedPlanOutput() { + return analysedPlanOutput; + } + + /** + * Sets the analysed plan output. + * + * @param analysedPlanOutput the new analysed plan output + */ + public void setAnalysedPlanOutput(UIModelAnalysedPlanNode analysedPlanOutput) { + this.analysedPlanOutput = analysedPlanOutput; + } + + /** + * Gets the plan node names. + * + * @return the plan node names + */ + public List getPlanNodeNames() { + ArrayList names = new ArrayList(flattenedExplainPlan.size()); + AnalysedPlanNode model = null; + for (UIModelAnalysedPlanNode n : this.flattenedExplainPlan) { + model = n.getAnalysedPlanNode(); + names.add(model.getNodeUniqueName()); + } + + return names; + } + + /** + * Gets the all DN viewof plan. + * + * @return the all DN viewof plan + */ + public Map getAllDNViewofPlan() { + if (null == this.dnViewofExplainPlan) { + this.dnViewofExplainPlan = new HashMap(1); + + this.getAllDNNamesInvolved(); + + this.buildPlanViewPerDN(); + + } + + return this.dnViewofExplainPlan; + } + + private void buildPlanViewPerDN() { + int idx = 0; + for (UIModelAnalysedPlanNode n : this.flattenedExplainPlan) { + AnalysedPlanNode model = n.getAnalysedPlanNode(); + addNodeDNPlanView(model, idx); + idx++; + } + + } + + private void addNodeDNPlanView(AnalysedPlanNode model, int idx) { + model.addNodeDNPlanView(this.dnViewofExplainPlan, idx); + + } + + private void getAllDNNamesInvolved() { + AnalysedPlanNode model = null; + for (UIModelAnalysedPlanNode n : this.flattenedExplainPlan) { + model = n.getAnalysedPlanNode(); + addDNDataToMap(model); + } + + } + + private void addDNDataToMap(AnalysedPlanNode model) { + ArrayList dnsInvolved = new ArrayList(5); + dnsInvolved = model.getDNInvolved(dnsInvolved); + + for (String dnName : dnsInvolved) { + this.dnViewofExplainPlan.put(dnName, new Object[flattenedExplainPlan.size()]); + } + + } + + /** + * Gets the root node. + * + * @return the root node + */ + public RootPlanNode getRootNode() { + return this.planRootNode; + } + + /** + * Gets the graph model. + * + * @return the graph model + */ + public Graph getGraphModel() { + return IUIModelAnalysedPlanNodeToGraphModelConvertor.getGraphModel(this.flattenedExplainPlan, + this.flattenedExplainPlanEdges); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/IAbstractExplainPlanPropertyCoreLabelFactory.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/IAbstractExplainPlanPropertyCoreLabelFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..33106c2ee430782f3399f4f4b6cc36c741ec0809 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/IAbstractExplainPlanPropertyCoreLabelFactory.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.visualexplainplan; + +/** + * Title: IAbstractExplainPlanPropertyCoreLabelFactory + * + * Description:A factory for creating IAbstractExplainPlanPropertyCoreLabel + * objects. + * + * @since 3.0.0 + */ +public interface IAbstractExplainPlanPropertyCoreLabelFactory { + + /** + * The visual explain diagram stack. + */ + int VISUAL_EXPLAIN_DIAGRAM_STACK = 1; + + /** + * The visual explain overllproperties stack. + */ + int VISUAL_EXPLAIN_OVERLLPROPERTIES_STACK = 2; + + /** + * The visual explain pernodeproperties stack. + */ + int VISUAL_EXPLAIN_PERNODEPROPERTIES_STACK = 3; + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/IExplainPlanNodeDetails.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/IExplainPlanNodeDetails.java new file mode 100644 index 0000000000000000000000000000000000000000..a29f84ece2307094512758c5315834c58319fae3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/IExplainPlanNodeDetails.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.visualexplainplan; + +/** + * + * Title: interface + * + * Description: The Interface IExplainPlanNodeDetails. + * + * @since 3.0.0 + */ +public interface IExplainPlanNodeDetails { + + /** + * Gets the node sequence num. + * + * @return the node sequence num + */ + int getNodeSequenceNum(); + + /** + * Gets the node title. + * + * @return the node title + */ + String getNodeTitle(); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/IUIModelAnalysedPlanNodeToGraphModelConvertor.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/IUIModelAnalysedPlanNodeToGraphModelConvertor.java new file mode 100644 index 0000000000000000000000000000000000000000..c1a3ee2d623d0da7bd194968490b163608a02c7d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/IUIModelAnalysedPlanNodeToGraphModelConvertor.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.visualexplainplan; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.eclipse.gef.graph.Edge; +import org.eclipse.gef.graph.Edge.Builder; +import org.eclipse.gef.graph.Graph; +import org.eclipse.gef.graph.Node; +import org.eclipse.gef.layout.algorithms.SpaceTreeLayoutAlgorithm; +import org.eclipse.gef.zest.fx.ZestProperties; + +import org.opengauss.mppdbide.explainplan.service.AnalysedPlanNode; + +/** + * Title: IUIModelAnalysedPlanNodeToGraphModelConvertor + * + * @since 3.0.0 + */ +public class IUIModelAnalysedPlanNodeToGraphModelConvertor { + + /** + * Gets the graph model. + * + * @param flattenedExplainPlanNodes the flattened explain plan nodes + * @param flattenedExplainPlanEdges the flattened explain plan edges + * @return the graph model + */ + public static Graph getGraphModel(List flattenedExplainPlanNodes, + List flattenedExplainPlanEdges) { + List nodes = new ArrayList<>(1); + List edges = new ArrayList<>(1); + Map nodeMap = new HashMap(1); + + for (UIModelAnalysedPlanNode node : flattenedExplainPlanNodes) { + org.eclipse.gef.graph.Node.Builder nodeBuilder = new org.eclipse.gef.graph.Node.Builder(); + AnalysedPlanNode analysedPlanNode = node.getAnalysedPlanNode(); + nodeBuilder.attr(VEPNodeAttributeId.ELE_ID, analysedPlanNode.getNodeSequenceNum()) + .attr(VEPNodeAttributeId.LABEL, analysedPlanNode.getNodeUniqueNameWithType()) + .attr(VEPNodeAttributeId.NODE_PROPERTY, node); + Node builtNode = nodeBuilder.attr(ZestProperties.TOOLTIP__N, node.getToopTipText()).buildNode(); + nodeMap.put(analysedPlanNode.getNodeUniqueNameWithType(), builtNode); + nodes.add(builtNode); + } + + for (Relationship edge : flattenedExplainPlanEdges) { + Node sourceNode = nodeMap.get(edge.getParentNode().getAnalysedPlanNode().getNodeUniqueNameWithType()); + Node targetNode = nodeMap.get(edge.getChildNode().getAnalysedPlanNode().getNodeUniqueNameWithType()); + + Builder edgeBuilder = new Builder(sourceNode, targetNode).attr(VEPNodeAttributeId.LABEL, + Long.toString(edge.getRecordCount())); + edges.add(edgeBuilder.buildEdge()); + } + + return new Graph.Builder().nodes(nodes.toArray(new Node[] {})).edges(edges.toArray(new Edge[] {})) + .attr(ZestProperties.LAYOUT_ALGORITHM__G, + new DSSpaceTreeLayoutAlgorithm(SpaceTreeLayoutAlgorithm.TOP_DOWN)) + .build(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/Relationship.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/Relationship.java new file mode 100644 index 0000000000000000000000000000000000000000..b06d5cf646a1f5832d771e0c2b83ed088a08ea3b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/Relationship.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.visualexplainplan; + +/** + * + * Title: class + * + * Description: The Class Relationship. + * + * @since 3.0.0 + */ +public class Relationship { + private UIModelAnalysedPlanNode parentNode; + private UIModelAnalysedPlanNode childNode; + + /** + * Instantiates a new relationship. + * + * @param parent the parent + * @param child the child + */ + public Relationship(UIModelAnalysedPlanNode parent, UIModelAnalysedPlanNode child) { + this.parentNode = parent; + this.childNode = child; + } + + /** + * Gets the parent node. + * + * @return the parent node + */ + public UIModelAnalysedPlanNode getParentNode() { + return parentNode; + } + + /** + * Sets the parent node. + * + * @param parentNode the new parent node + */ + public void setParentNode(UIModelAnalysedPlanNode parentNode) { + this.parentNode = parentNode; + } + + /** + * Gets the child node. + * + * @return the child node + */ + public UIModelAnalysedPlanNode getChildNode() { + return childNode; + } + + /** + * Sets the child node. + * + * @param childNode the new child node + */ + public void setChildNode(UIModelAnalysedPlanNode childNode) { + this.childNode = childNode; + } + + /** + * Gets the record count. + * + * @return the record count + */ + public long getRecordCount() { + return getChildNode().getActualRecordCount(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/UIModelAnalysedPlanNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/UIModelAnalysedPlanNode.java new file mode 100644 index 0000000000000000000000000000000000000000..bd65534cbcd87622cd8dd60bcb168cc0b66807bc --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/UIModelAnalysedPlanNode.java @@ -0,0 +1,440 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.visualexplainplan; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.runtime.IAdaptable; + +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.explainplan.service.AnalysedPlanNode; +import org.opengauss.mppdbide.presentation.objectproperties.handler.PropertyHandlerCore; +import org.opengauss.mppdbide.utils.EnvirnmentVariableValidator; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class UIModelAnalysedPlanNode. + * + * @since 3.0.0 + */ +public class UIModelAnalysedPlanNode extends BasicUIModelPlanNode implements IAdaptable { + + private AnalysedPlanNode model; + private UIModelOperationalPlanNode modelchild; + private ArrayList children; + private ArrayList sourceRelationship = new ArrayList(1); + private ArrayList targetRelationship = new ArrayList(1); + private Object explainPlanNodeDetails; + private ExecutionPlanTextDisplayGrid textView = null; + + private boolean isAnalyze; + private boolean visited; + + /** + * Instantiates a new UI model analysed plan node. + * + * @param node the node + */ + public UIModelAnalysedPlanNode(AnalysedPlanNode node) { + this.model = node; + } + + /** + * To text. + * + * @param analyze the analyze + * @return the string + */ + public String toText(boolean analyze) { + return model.toText(analyze); + } + + /** + * Gets the analysed plan node. + * + * @return the analysed plan node + */ + public AnalysedPlanNode getAnalysedPlanNode() { + return model; + } + + /** + * Sets the visited plan node + * + * @param visitedValue the visited value + */ + public void setVisited(boolean visitedValue) { + this.visited = visitedValue; + } + + /** + * Gets the children. + * + * @return the children + */ + public ArrayList getChildren() { + if (this.children == null) { + children = new ArrayList(0); + Relationship rs = null; + UIModelAnalysedPlanNode newChild = null; + + for (AnalysedPlanNode c : this.getAnalysedPlanNode().getChildNodeStats()) { + newChild = new UIModelAnalysedPlanNode(c); + rs = new Relationship(this, newChild); + children.add(newChild); + this.addSourceRelationship(rs); + newChild.addTargetRelationship(rs); + } + } + + return this.children; + } + + /** + * Checks if is slowest. + * + * @return true, if is slowest + */ + public boolean isSlowest() { + return model.isSlowest(); + } + + /** + * Checks if is costliest. + * + * @return true, if is costliest + */ + public boolean isCostliest() { + return model.isCostliest(); + } + + /** + * Gets the self cost. + * + * @return the self cost + */ + public double getSelfCost() { + return model.getSelfCost(); + } + + /** + * Gets the self time. + * + * @return the self time + */ + public double getSelfTime() { + return model.getSelfTotalTime(); + } + + /** + * Checks if is heaviest. + * + * @return true, if is heaviest + */ + public boolean isHeaviest() { + return model.isHeaviest(); + } + + /** + * Gets the actual record count. + * + * @return the actual record count + */ + public long getActualRecordCount() { + return model.getRecordCount(); + } + + /** + * Gets the node specific. + * + * @return the node specific + */ + public List getNodeSpecific() { + return this.getAnalysedPlanNode().getNodeSpecific(); + } + + /** + * Gets the output. + * + * @return the output + */ + public String[] getOutput() { + return this.getAnalysedPlanNode().getOutput(); + } + + /** + * Gets the node title. + * + * @return the node title + */ + public String getNodeTitle() { + return this.getAnalysedPlanNode().getNodeUniqueNameWithType(); + } + + /** + * Gets the node type. + * + * @return the node type + */ + public String getNodeType() { + return this.getAnalysedPlanNode().getNodeType(); + } + + /** + * Gets the actual max time taken. + * + * @return the actual max time taken + */ + public double getActualMaxTimeTaken() { + return this.getAnalysedPlanNode().getActualMaxTimeTaken(); + } + + /** + * Gets the total time contribution percentage. + * + * @return the total time contribution percentage + */ + public double getTotalTimeContributionPercentage() { + return this.getAnalysedPlanNode().getSelfTimeContributionInOverAllPlan(); + } + + /** + * Gets the model children. + * + * @return the model children + */ + public List getModelChildren() { + if (null == this.modelchild) { + this.modelchild = new UIModelOperationalPlanNode(model.getChild()); + } + ArrayList modelChildren = new ArrayList(1); + modelChildren.add(this.modelchild); + + return modelChildren; + } + + /** + * Gets the visited + * + * @return the visited + */ + public boolean getVisited() { + return this.visited; + } + + /** + * Gets the operational node. + * + * @return the model operational node + */ + public OperationalNode getOperationalNode() { + return this.model.getChild(); + } + + /** + * Adds the source relationship. + * + * @param rs the rs + */ + public void addSourceRelationship(Relationship rs) { + sourceRelationship.add(rs); + } + + /** + * Adds the target relationship. + * + * @param rs the rs + */ + public void addTargetRelationship(Relationship rs) { + targetRelationship.add(rs); + + } + + /** + * Gets the source relationship. + * + * @return the source relationship + */ + public List getSourceRelationship() { + return this.sourceRelationship; + } + + /** + * Gets the target relationship. + * + * @return the target relationship + */ + public List getTargetRelationship() { + return this.targetRelationship; + } + + /** + * Gets the parent relationship. + * + * @return the parent relationship + */ + public String getParentRelationship() { + return this.model.getParentRelationship(); + } + + /** + * Gets the plan record count. + * + * @return the plan record count + */ + public long getPlanRecordCount() { + return model.getPlanRecordCount(); + } + + /** + * Gets the adapter. + * + * @param the generic type + * @param adapter the adapter + * @return the adapter + */ + @SuppressWarnings("unchecked") + @Override + public T getAdapter(Class adapter) { + if (adapter == IExplainPlanNodeDetails.class) { + if (null == this.explainPlanNodeDetails) { + this.explainPlanNodeDetails = new ExplainPlanNodeDetails(this.getAnalysedPlanNode()); + } + + return (T) this.explainPlanNodeDetails; + } + if (PropertyHandlerCore.class == adapter) { + return (T) new ExplainPlanNodePropertiesCore(this.getAnalysedPlanNode()); + } + return null; + } + + /** + * Flatten. + * + * @param flattenedExplainPlan the flattened explain plan + * @param flattenedExplainPlanEdges the flattened explain plan edges + */ + public void flatten(List flattenedExplainPlan, + List flattenedExplainPlanEdges) { + flattenedExplainPlan.add(this); + flattenedExplainPlanEdges.addAll(this.getTargetRelationship()); + + for (UIModelAnalysedPlanNode c : this.getChildren()) { + c.flatten(flattenedExplainPlan, flattenedExplainPlanEdges); + } + } + + /** + * Gets the toop tip text. + * + * @return the toop tip text + */ + public String getToopTipText() { + StringBuffer sb = new StringBuffer(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + sb.append("Node: "); + sb.append(this.getAnalysedPlanNode().getNodeName()); + + String itemText = this.getAnalysedPlanNode().getItemName(); + if (null != itemText) { + sb.append(EnvirnmentVariableValidator.validateAndGetLineSeperator()); + sb.append(itemText); + } + + itemText = this.getAnalysedPlanNode().getItemDetails(); + if (null != itemText) { + sb.append(EnvirnmentVariableValidator.validateAndGetLineSeperator()); + sb.append(itemText); + } + + return sb.toString(); + } + + /** + * Gets the model in text format. + * + * @param totalRuntime the total runtime + * @return the model in text format + */ + public ExecutionPlanTextDisplayGrid getModelInTextFormat(double totalRuntime) { + if (this.textView == null) { + try { + this.textView = new ExecutionPlanTextDisplayGrid(this, totalRuntime); + this.textView.init(); + } catch (DatabaseOperationException | DatabaseCriticalException exception) { + MPPDBIDELoggerUtility.error("error in generating plan view", exception); + return null; + } + } + return this.textView; + } + + /** + * Checks if is analyze. + * + * @return true, if is analyze + */ + public boolean isAnalyze() { + return isAnalyze; + } + + /** + * Sets the analyze. + * + * @param analyze the new analyze + */ + public void setAnalyze(boolean analyze) { + this.isAnalyze = analyze; + } + + + /** + * Gets the node specific properties. + * + * @return the node specific properties + */ + public List getNodeSpecificProperties() { + + return null; + } + + /** + * Gets the additional info. + * + * @param analyze the analyze + * @return the additional info + */ + public List getAdditionalInfo(boolean analyze) { + return model.getAdditionalInfo(analyze); + } + + /** + * Gets the subplan name. + * + * @return the subplan name + */ + public String getSubplanName() { + return model.getChild().getSubplanName(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/UIModelContentNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/UIModelContentNode.java new file mode 100644 index 0000000000000000000000000000000000000000..ccae3999853d6b10763f1a0dae40bf312be8d48f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/UIModelContentNode.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.visualexplainplan; + +import java.util.ArrayList; +import java.util.List; + +/** + * + * Title: class + * + * Description: The Class UIModelContentNode. + * + * @since 3.0.0 + */ +public class UIModelContentNode extends BasicUIModelPlanNode { + + private String outputText; + + /** + * Instantiates a new UI model content node. + * + * @param str the str + */ + public UIModelContentNode(String str) { + this.outputText = str; + } + + /** + * Gets the label text. + * + * @return the label text + */ + public String getLabelText() { + return outputText; + } + + /** + * Gets the node contents. + * + * @param model the model + * @return the node contents + */ + public static List getNodeContents(UIModelOperationalPlanNode model) { + ArrayList nodeList = new ArrayList(1); + + String str = model.getOutput(); + String parentModel = model.getParentRelationship(); + + nodeList.add(new UIModelContentNode(str)); + nodeList.add(new UIModelContentNode(parentModel)); + + return nodeList; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/UIModelConverter.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/UIModelConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..030d512e3df84070238ecfd52746c10413a4c5b2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/UIModelConverter.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.visualexplainplan; + +import org.opengauss.mppdbide.explainplan.service.AnalysedPlanNode; + +/** + * + * Title: class + * + * Description: The Class UIModelConverter. + * + * @since 3.0.0 + */ +public class UIModelConverter { + + /** + * Covert to UI model. + * + * @param analysedPlanNode the analysed plan node + * @return the UI model analysed plan node + */ + public static UIModelAnalysedPlanNode covertToUIModel(AnalysedPlanNode analysedPlanNode) { + return new UIModelAnalysedPlanNode(analysedPlanNode); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/UIModelOperationalPlanNode.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/UIModelOperationalPlanNode.java new file mode 100644 index 0000000000000000000000000000000000000000..d7372599e0562fd49a5ea20ad301bbd09d6298f9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/UIModelOperationalPlanNode.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.visualexplainplan; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.opengauss.mppdbide.explainplan.nodetypes.OperationalNode; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class UIModelOperationalPlanNode. + * + * @since 3.0.0 + */ +public class UIModelOperationalPlanNode extends BasicUIModelPlanNode { + + /** + * The parent. + */ + protected UIModelOperationalPlanNode parent; + + /** + * The children. + */ + protected ArrayList children; + + /** + * The model. + */ + protected OperationalNode model; + + /** + * Sets the parent. + * + * @param parent the new parent + */ + public void setParent(UIModelOperationalPlanNode parent) { + this.parent = parent; + } + + /** + * Instantiates a new UI model operational plan node. + * + * @param operationalNode the operational node + */ + public UIModelOperationalPlanNode(OperationalNode operationalNode) { + super(); + this.model = operationalNode; + children = new ArrayList(0); + } + + /** + * Adds the child node. + * + * @param childnode the childnode + */ + public void addChildNode(UIModelOperationalPlanNode childnode) { + children.add(childnode); + } + + /** + * To string. + * + * @return the string + */ + public String toString() { + String chilNodeInfo = null; + if (this.children.size() == 0) { + return super.toString(); + } + + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + int index = 1; + for (BasicUIModelPlanNode child : this.children) { + sb.append(index + ". "); + sb.append(child.toString()); + sb.append(System.lineSeparator()); + index++; + } + + chilNodeInfo = sb.toString(); + + return super.toString() + System.lineSeparator() + chilNodeInfo; + } + + /** + * Gets the parent. + * + * @return the parent + */ + public UIModelOperationalPlanNode getParent() { + return this.parent; + } + + /** + * Gets the output. + * + * @return the output + */ + public String getOutput() { + return "Output : " + Arrays.toString(this.model.getOutput()); + } + + /** + * Gets the node specific. + * + * @return the node specific + */ + public List getNodeSpecific() { + + return null; + } + + /** + * Gets the parent relationship. + * + * @return the parent relationship + */ + public String getParentRelationship() { + return model.getParentRelationship(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/VEPNodeAttributeId.java b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/VEPNodeAttributeId.java new file mode 100644 index 0000000000000000000000000000000000000000..e3ca7f14bd7b9ee473b9352a95ecbbf807cb18b4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.explainplan/src/org/opengauss/mppdbide/presentation/visualexplainplan/VEPNodeAttributeId.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.visualexplainplan; + +/** + * Title: VEPNodeAttributeId + * + * @since 3.0.0 + */ +public interface VEPNodeAttributeId { + + /** + * The Constant ID. + */ + public static final String ELE_ID = "element_id"; + + /** + * The Constant LABEL. + */ + public static final String LABEL = "element-label"; + + /** + * The Constant NODE_PROPERTY. + */ + public static final String NODE_PROPERTY = "node_property"; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.feature/.project b/code/datastudio/src/org.opengauss.mppdbide.feature/.project new file mode 100644 index 0000000000000000000000000000000000000000..13c8b477badaf0a9dc37cf3e4aae8e72d0716d97 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.feature/.project @@ -0,0 +1,29 @@ + + + org.opengauss.mppdbide.feature + + + + + + org.eclipse.pde.FeatureBuilder + + + + + net.sf.eclipsecs.core.CheckstyleBuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.pde.FeatureNature + net.sf.eclipsecs.core.CheckstyleNature + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.feature/build.properties b/code/datastudio/src/org.opengauss.mppdbide.feature/build.properties new file mode 100644 index 0000000000000000000000000000000000000000..64f93a9f0b7328eb563aa5ad6cec7f828020e124 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.feature/build.properties @@ -0,0 +1 @@ +bin.includes = feature.xml diff --git a/code/datastudio/src/org.opengauss.mppdbide.feature/feature.xml b/code/datastudio/src/org.opengauss.mppdbide.feature/feature.xml new file mode 100644 index 0000000000000000000000000000000000000000..3dce89b54cd7922529f43d10efa679b651b1bc4e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.feature/feature.xml @@ -0,0 +1,134 @@ + + + + + [Enter Feature Description here.] + + + + [Enter Copyright Description here.] + + + + [Enter License Description here.] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.feature/pom.xml b/code/datastudio/src/org.opengauss.mppdbide.feature/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..c556d0109a08959dba589a1b4664d3fe47aedc9d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.feature/pom.xml @@ -0,0 +1,13 @@ + + + 4.0.0 + + org.opengauss.plide.build + GAUSS_MPP_DB_IDE + 1.0.0-SNAPSHOT + + org.opengauss.mppdbide.feature + eclipse-feature + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.parser/.classpath b/code/datastudio/src/org.opengauss.mppdbide.parser/.classpath new file mode 100644 index 0000000000000000000000000000000000000000..1722178cdfc5f1a0e96de49f82ee116d38dd6e7e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.parser/.classpath @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.parser/.gitignore b/code/datastudio/src/org.opengauss.mppdbide.parser/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..50b300d29c0d31394edd710de4cd3192db7db578 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.parser/.gitignore @@ -0,0 +1,4 @@ +/bin/ +/src/org/opengauss/mppdbide/parser/grammar/*.java +/src/org/opengauss/mppdbide/parser/grammar/*.tokens +/target/ diff --git a/code/datastudio/src/org.opengauss.mppdbide.parser/.project b/code/datastudio/src/org.opengauss.mppdbide.parser/.project new file mode 100644 index 0000000000000000000000000000000000000000..7ab09c8c1c804b7a14b089916fbc2f3be5ebadf7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.parser/.project @@ -0,0 +1,34 @@ + + + org.opengauss.mppdbide.parser + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.parser/META-INF/MANIFEST.MF b/code/datastudio/src/org.opengauss.mppdbide.parser/META-INF/MANIFEST.MF new file mode 100644 index 0000000000000000000000000000000000000000..6cc63314250d7e0b8b45436a885a11bcafe6aa80 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.parser/META-INF/MANIFEST.MF @@ -0,0 +1,17 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: gauss parser +Bundle-SymbolicName: org.opengauss.mppdbide.parser +Bundle-Version: 1.0.0.qualifier +Bundle-Vendor: OPENGAUSS +Bundle-RequiredExecutionEnvironment: JavaSE-11 +Bundle-ClassPath: ., + antlr4-runtime-4.9.2.jar +Import-Package: org.opengauss.mppdbide.bl.queryparser, + org.opengauss.mppdbide.utils.logger +Export-Package: org.opengauss.mppdbide.parser.alias, + org.opengauss.mppdbide.parser.grammar, + org.opengauss.mppdbide.parser.runtimehandler, + org.antlr.v4.runtime, + org.antlr.v4.runtime.misc, + org.antlr.v4.runtime.tree diff --git a/code/datastudio/src/org.opengauss.mppdbide.parser/build.properties b/code/datastudio/src/org.opengauss.mppdbide.parser/build.properties new file mode 100644 index 0000000000000000000000000000000000000000..c0e9080b46ac46df1fd8104c1909d8d2335a5b94 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.parser/build.properties @@ -0,0 +1,5 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + antlr4-runtime-4.9.2.jar diff --git a/code/datastudio/src/org.opengauss.mppdbide.parser/pom.xml b/code/datastudio/src/org.opengauss.mppdbide.parser/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..fee7b9534b4f6bfa591ceae73b7c98d89dd95417 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.parser/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + + org.opengauss.plide.build + GAUSS_MPP_DB_IDE + 1.0.0-SNAPSHOT + + org.opengauss.plide.build + org.opengauss.mppdbide.parser + eclipse-plugin + gauss parser + + UTF-8 + + + + org.antlr + antlr4-runtime + 4.7.1 + + + + + + org.antlr + antlr4-maven-plugin + 4.7.1 + + ${project.basedir}/src/org/opengauss/mppdbide/parser/grammar + ${project.basedir}/src/org/opengauss/mppdbide/parser/grammar + PostgresLexer.g4 + PostgresParser.g4 + true + true + + + + + antlr4 + + + + + + + \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/alias/AbstractAliasParseListener.java b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/alias/AbstractAliasParseListener.java new file mode 100644 index 0000000000000000000000000000000000000000..30a3d4e7c6158e97123e4d52740544ce290d9136 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/alias/AbstractAliasParseListener.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.parser.alias; + +import org.opengauss.mppdbide.parser.grammar.PostgresParser; +import org.opengauss.mppdbide.parser.grammar.PostgresParserBaseListener; + +/** + * Title: AbstractAliasParseListener Description:The listener interface for + * receiving abstractAliasParse events. The class that is interested in + * processing a abstractAliasParse event implements this interface, and the + * object created with that class is registered with a component using the + * component's addAbstractAliasParseListener method. When the + * abstractAliasParse event occurs, that object's appropriate method is invoked. + * + * @since 3.0.0 + */ + +public abstract class AbstractAliasParseListener extends PostgresParserBaseListener { + boolean isException = false; + + @Override + public void enterSelectStmt(PostgresParser.SelectStmtContext ctx) { + if (ctx.exception != null) { + isException = true; + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/alias/AliasParseListener.java b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/alias/AliasParseListener.java new file mode 100644 index 0000000000000000000000000000000000000000..0c9fc027a79e973b0fc2596078de261835785fd3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/alias/AliasParseListener.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.parser.alias; + +import java.util.LinkedList; + +import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.misc.Interval; +import org.antlr.v4.runtime.tree.ParseTree; + +import org.opengauss.mppdbide.bl.queryparser.ParseContext; +import org.opengauss.mppdbide.parser.grammar.PostgresParser; +import org.opengauss.mppdbide.parser.grammar.PostgresParser.Relation_exprContext; +import org.opengauss.mppdbide.parser.grammar.PostgresParser.Table_refContext; + +/** + * Title: AliasParseListener Description:The listener interface for receiving + * aliasParse events. The class that is interested in processing a aliasParse + * event implements this interface, and the object created with that class is + * registered with a component using the component's + * addAliasParseListener method. When the aliasParse event occurs, + * that object's appropriate method is invoked. + * + * @since 3.0.0 + */ +public class AliasParseListener extends AbstractAliasParseListener { + private ParseContext aliasParseContext; + + /** + * Instantiates a new alias parse listener. + */ + AliasParseListener() { + aliasParseContext = new ParseContext(); + } + + /** + * check the alias clause to get the alias. + * + * @param ctx the ctx + */ + @Override + public void enterAlias_clause(PostgresParser.Alias_clauseContext ctx) { + if (isException) { + return; + } + + ParserRuleContext tempCtx = (ParserRuleContext) ctx; + ParserRuleContext parent = tempCtx.getParent(); + + String aliasName; + + if (tempCtx.getChildCount() == 2) { + aliasName = tempCtx.getChild(1).getText(); + } else { + aliasName = tempCtx.getText(); + } + + if (parent instanceof Table_refContext) { + ParseTree firstChild = parent.getChild(0); + if (firstChild instanceof Relation_exprContext) { + String tableName = firstChild.getText(); + addToAliasParseContext(aliasName, tableName); + } + } + } + + @Override + public void enterRelation_expr_opt_alias(PostgresParser.Relation_expr_opt_aliasContext ctx) { + if (isException) { + return; + } + + ParserRuleContext tempCtx = (ParserRuleContext) ctx; + + int childCount = tempCtx.getChildCount(); + if (childCount > 1) { + addToAliasParseContext(tempCtx.getChild(childCount - 1).getText(), tempCtx.getChild(0).getText()); + } + } + + private void addToAliasParseContext(String aliasName, String tableName) { + if (aliasParseContext.getAliasToTableNameMap().containsKey(aliasName) == false) { + aliasParseContext.getAliasToTableNameMap().put(aliasName, new LinkedList()); + } + aliasParseContext.getAliasToTableNameMap().get(aliasName).add(tableName); + } + + /** + * Gets the alias parse context. + * + * @return the alias parse context + */ + public ParseContext getAliasParseContext() { + return aliasParseContext; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/alias/AliasParser.java b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/alias/AliasParser.java new file mode 100644 index 0000000000000000000000000000000000000000..bbecd1b3b7a427a36fc31e6c86cc5ed633769927 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/alias/AliasParser.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.parser.alias; + +import org.antlr.v4.runtime.Lexer; +import org.antlr.v4.runtime.Parser; +import org.antlr.v4.runtime.tree.ParseTree; +import org.antlr.v4.runtime.tree.ParseTreeWalker; + +import org.opengauss.mppdbide.bl.queryparser.IParseContextGetter; +import org.opengauss.mppdbide.bl.queryparser.ParseContext; +import org.opengauss.mppdbide.parser.factory.PostgresParserFactory; +import org.opengauss.mppdbide.parser.runtimehandler.RunTimeParserException; +import org.opengauss.mppdbide.parser.runtimehandler.RuntimeErrorStrategyManager; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: class Description: The Class AliasParser. + * + * @since 3.0.0 + */ +public class AliasParser implements IParseContextGetter { + private ParseContext aliases; + + private LexerErrorListener lexerErrlorListener; + + private AliasParserErrorListener parserErrlorListener; + + private ParseTreeWalker walker; + + /** + * Instantiates a new alias parser. + */ + public AliasParser() { + aliases = null; + lexerErrlorListener = new LexerErrorListener(); + parserErrlorListener = new AliasParserErrorListener(); + walker = new ParseTreeWalker(); + } + + /** + * parse a query using antlr4 + * + * @param query - query to be parsed + */ + public void parseQuery(String query) { + + Lexer lexer = PostgresParserFactory.getPostgresLexer(query); + lexer.removeErrorListeners(); + lexer.addErrorListener(lexerErrlorListener); + Parser parser = PostgresParserFactory.getPostgresParser(lexer); + parser.setErrorHandler(RuntimeErrorStrategyManager.getRuntimeErrorhandler()); + parser.removeErrorListeners(); + parser.addErrorListener(parserErrlorListener); + AliasParseListener parseListener = new AliasParseListener(); + + try { + ParseTree tree = PostgresParserFactory.getPostgresParserAllStmt(parser); + walker.walk(parseListener, tree); + aliases = parseListener.getAliasParseContext(); + } catch (Exception exception) { + if (exception instanceof RunTimeParserException) { + MPPDBIDELoggerUtility.error("Alias parser worker interrupted", exception); + throw exception; + } else { + MPPDBIDELoggerUtility.error("Error while parsing", exception); + } + } + } + + /** + * getter method for the parsed information + * + * @return - parse context for the query parsed + */ + public ParseContext getParseContext() { + return aliases; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/alias/AliasParserErrorListener.java b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/alias/AliasParserErrorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..7483c1ad8625027c9a38653c5529670ab882973a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/alias/AliasParserErrorListener.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.parser.alias; + +import org.antlr.v4.runtime.BaseErrorListener; +import org.antlr.v4.runtime.NoViableAltException; +import org.antlr.v4.runtime.Parser; +import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.Recognizer; + +import org.opengauss.mppdbide.parser.grammar.PostgresParser; + +/** + * Title: AliasParserErrorListener Description:The listener interface for + * receiving aliasParserError events. The class that is interested in processing + * a aliasParserError event implements this interface, and the object created + * with that class is registered with a component using the component's + * addAliasParserErrorListener method. When the aliasParserError + * event occurs, that object's appropriate method is invoked. + * + * @since 3.0.0 + */ +public class AliasParserErrorListener extends BaseErrorListener { + + @Override + public void syntaxError(Recognizer recognizer, Object offendingSymbol, int line, int charPositionInLine, + String msg, RecognitionException exception) throws NoViableAltException { + if (false == recognizer instanceof Parser) { + return; + } + Parser parser = (Parser) recognizer; + + ParserRuleContext parent = parser.getRuleContext().getParent(); + + if (parser.getRuleContext() instanceof PostgresParser.Alias_clauseContext) { + while ((parent != null) && (parent.getRuleContext() instanceof PostgresParser.SelectStmtContext == false)) { + parent = parent.getParent(); + } + + if (parent != null) { + parent.exception = exception; + } + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/alias/LexerErrorListener.java b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/alias/LexerErrorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..2ba00d8f93c2714550855073a0813db959c266e6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/alias/LexerErrorListener.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.parser.alias; + +import org.antlr.v4.runtime.BaseErrorListener; +import org.antlr.v4.runtime.NoViableAltException; +import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.Recognizer; + +/** + * Title: LexerErrorListener Description:The listener interface for receiving + * lexerError events. The class that is interested in processing a lexerError + * event implements this interface, and the object created with that class is + * registered with a component using the component's + * addLexerErrorListener method. When the lexerError event occurs, + * that object's appropriate method is invoked. + * + * @since 3.0.0 + */ +public class LexerErrorListener extends BaseErrorListener { + + @Override + public void syntaxError(Recognizer recognizer, Object offendingSymbol, int line, int charPositionInLine, + String msg, RecognitionException e) throws NoViableAltException { + /* + * Ignoring syntax error because, query is incomplete (and hence can + * have invalid tokens) while parsing to extract alias to table name map + */ + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/factory/PostgresParserFactory.java b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/factory/PostgresParserFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..42f0103e97a0a201a5921a899cb61f975f111403 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/factory/PostgresParserFactory.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.parser.factory; + +import org.antlr.v4.runtime.ANTLRInputStream; +import org.antlr.v4.runtime.CommonTokenStream; +import org.antlr.v4.runtime.Lexer; +import org.antlr.v4.runtime.Parser; +import org.antlr.v4.runtime.tree.ParseTree; + +import org.opengauss.mppdbide.parser.grammar.PostgresLexer; +import org.opengauss.mppdbide.parser.grammar.PostgresParser; + +/** + * Title: PostgresParserFactory Description:A factory for creating + * PostgresParser objects. + * + * @since 3.0.0 + */ +public abstract class PostgresParserFactory { + + /** + * Gets the postgres parser. + * + * @param lexer the lexer + * @return the postgres parser + */ + public static Parser getPostgresParser(Lexer lexer) { + CommonTokenStream tokens = new CommonTokenStream(lexer); + Parser parser = new PostgresParser(tokens); + return parser; + } + + /** + * Gets the postgres lexer. + * + * @param query the query + * @return the postgres lexer + */ + public static Lexer getPostgresLexer(String query) { + ANTLRInputStream input = new ANTLRInputStream(query); + Lexer lexer = new PostgresLexer(input); + return lexer; + } + + /** + * Gets the postgres parser all stmt. + * + * @param parser the parser + * @return the postgres parser all stmt + */ + public static ParseTree getPostgresParserAllStmt(Parser parser) { + + if (parser instanceof PostgresParser) { + return ((PostgresParser) parser).allStmt(); + } + + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/grammar/PostgresLexer.g4 b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/grammar/PostgresLexer.g4 new file mode 100644 index 0000000000000000000000000000000000000000..c9a719d077f9ac7cf752d55ab4da763286a64b09 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/grammar/PostgresLexer.g4 @@ -0,0 +1,761 @@ +lexer grammar PostgresLexer; + +@header { + package org.opengauss.mppdbide.parser.grammar; +} +/* ordinary key words in alphabetical order */ + +ABORT_P : A B O R T; +ABSOLUTE_P : A B S O L U T E; +ACCESS : A C C E S S; +ACCOUNT : A C C O U N T; +ACTION : A C T I O N; +ADD_P : A D D; +ADMIN : A D M I N; +AFTER : A F T E R; +AGGREGATE : A G G R E G A T E; +ALL : A L L; +ALSO : A L S O; +ALTER : A L T E R; +ALWAYS : A L W A Y S; +ANALYSE : A N A L Y S E; +ANALYZE : A N A L Y Z E; +AND : A N D; +ANOYBLOCK : A N O Y B L O C K; +ANY : A N Y; +APP : A P P; +ARRAY : A R R A Y; +AS : A S; +ASC : A S C; +ASSERTION : A S S E R T I O N; +ASSIGNMENT : A S S I G N M E N T; +ASYMMETRIC : A S Y M M E T R I C; +AT : A T; +ATTRIBUTE : A T T R I B U T E; +AUTHID : A U T H I D; +AUTHORIZATION : A U T H O R I Z A T I O N; +AUTOEXTEND : A U T O E X T E N D; +AUTOMAPPED : A U T O M A P P E D; +BACKWARD : B A C K W A R D; +BARRIER : B A R R I E R; +BEFORE : B E F O R E; +BEGIN_P : B E G I N; +BETWEEN : B E T W E E N; +BIGINT : B I G I N T; +BINARY : B I N A R Y; +BINARY_DOUBLE : B I N A R Y UNDERSCORE D O U B L E; +BINARY_INTEGER : B I N A R Y UNDERSCORE I N T E G E R; +BIT : B I T; +BLOB_P : B L O B; +BODY : B O D Y; +BOGUS : B O G U S; +BOOLEAN_P : B O O L E A N; +BOTH : B O T H; +BUCKETS : B U C K E T S; +BY : B Y; +CACHE : C A C H E; +CALL : C A L L; +CALLED : C A L L E D; +CASCADE : C A S C A D E; +CASCADED : C A S C A D E D; +CASE : C A S E; +CAST : C A S T; +CATALOG_P : C A T A L O G; +CHAIN : C H A I N; +CHAR_P : C H A R; +CHARACTER : C H A R A C T E R; +CHARACTERISTICS : C H A R A C T E R I S T I C S; +CHECK : C H E C K; +CHECKPOINT : C H E C K P O I N T; +CLASS : C L A S S; +CLEAN : C L E A N; +CLOB : C L O B; +CLOSE : C L O S E; +CLUSTER : C L U S T E R; +COALESCE : C O A L E S C E; +COLLATE : C O L L A T E; +COLLATION : C O L L A T I O N; +COLUMN : C O L U M N; +COMMENT : C O M M E N T; +COMMENTS : C O M M E N T S; +COMMIT : C O M M I T; +COMMITTED : C O M M I T T E D; +COMPACT : C O M P A C T; +COMPATIBLE_ILLEGAL_CHARS : C O M P A T I B L E UNDERSCORE I L L E G A L UNDERSCORE C H A R S; +COMPRESS : C O M P R E S S; +CONCURRENTLY : C O N C U R R E N T L Y; +CONFIGURATION : C O N F I G U R A T I O N; +CONNECTION : C O N N E C T I O N; +CONSTRAINT : C O N S T R A I N T; +CONSTRAINTS : C O N S T R A I N T S; +CONTENT_P : C O N T E N T; +CONTINUE_P : C O N T I N U E; +CONVERSION_P : C O N V E R S I O N; +COORDINATOR : C O O R D I N A T O R; +COPY : C O P Y; +COST : C O S T; +CREATE : C R E A T E; +CROSS : C R O S S; +CSV : C S V; +CUBE : C U B E; +CURRENT_P : C U R R E N T; +CURRENT_CATALOG : C U R R E N T UNDERSCORE C A T A L O G; +CURRENT_DATE : C U R R E N T UNDERSCORE D A T E; +CURRENT_ROLE : C U R R E N T UNDERSCORE R O L E; +CURRENT_SCHEMA : C U R R E N T UNDERSCORE S C H E M A; +CURRENT_TIME : C U R R E N T UNDERSCORE T I M E; +CURRENT_TIMESTAMP : C U R R E N T UNDERSCORE T I M E S T A M P; +CURRENT_USER : C U R R E N T UNDERSCORE U S E R; +CURSOR : C U R S O R; +CYCLE : C Y C L E; +DATA_P : D A T A; +DATABASE : D A T A B A S E; +DATAFILE : D A T A F I L E; +DATE_P : D A T E; +DATE_FORMAT_P : D A T E UNDERSCORE F O R M A T; +DAY_P : D A Y; +DBCOMPATIBILITY_P : D B C O M P A T I B I L I T Y; +DEALLOCATE : D E A L L O C A T E; +DEC : D E C; +DECIMAL_P : D E C I M A L; +DECLARE : D E C L A R E; +DECODE : D E C O D E; +DEFAULT : D E F A U L T; +DEFAULTS : D E F A U L T S; +DEFERRABLE : D E F E R R A B L E; +DEFERRED : D E F E R R E D; +DEFINER : D E F I N E R; +DELETE_P : D E L E T E; +DELIMITER : D E L I M I T E R; +DELIMITERS : D E L I M I T E R S; +DELTA : D E L T A; +DELTAMERGE : D E L T A M E R G E; +DESC : D E S C; +DETERMINISTIC : D E T E R M I N I S T I C; +DICTIONARY : D I C T I O N A R Y; +DIRECT : D I R E C T; +DISABLE_P : D I S A B L E; +DISCARD : D I S C A R D; +DISTINCT : D I S T I N C T; +DISTRIBUTE : D I S T R I B U T E; +DISTRIBUTION : D I S T R I B U T I O N; +DO : D O; +DOCUMENT_P : D O C U M E N T; +DOMAIN_P : D O M A I N; +DOUBLE_P : D O U B L E; +DROP : D R O P; +EACH : E A C H; +ELSE : E L S E; +ENABLE_P : E N A B L E; +ENCODING : E N C O D I N G; +ENCRYPTED : E N C R Y P T E D; +END_P : E N D; +ENFORCED : E N F O R C E D; +ENUM_P : E N U M; +ESCAPE : E S C A P E; +EOL : E O L; +ESCAPING : E S C A P I N G; +EXCEPT : E X C E P T; +EXCHANGE : E X C H A N G E; +EXCLUDE : E X C L U D E; +EXCLUDING : E X C L U D I N G; +EXCLUSIVE : E X C L U S I V E; +EXECUTE : E X E C U T E; +EXISTS : E X I S T S; +EXPLAIN : E X P L A I N; +EXTENSION : E X T E N S I O N; +EXTERNAL : E X T E R N A L; +EXTRACT : E X T R A C T; +FALSE_P : F A L S E; +FAMILY : F A M I L Y; +FETCH : F E T C H; +FILEHEADER_P : F I L E H E A D E R; +FIRST_P : F I R S T; +FIXED_P : F I X E D; +FLOAT_P : F L O A T; +FOLLOWING : F O L L O W I N G; +FOR : F O R; +FORCE : F O R C E; +FOREIGN : F O R E I G N; +FORMATTER : F O R M A T T E R; +FORWARD : F O R W A R D; +FREEZE : F R E E Z E; +FROM : F R O M; +FULL : F U L L; +FUNCTION : F U N C T I O N; +FUNCTIONS : F U N C T I O N S; +GLOBAL : G L O B A L; +GRANT : G R A N T; +GRANTED : G R A N T E D; +GREATEST : G R E A T E S T; +GROUP_P : G R O U P; +GROUPING_P : G R O U P I N G; +HANDLER : H A N D L E R; +HAVING : H A V I N G; +HDFSDIRECTORY : H D F S D I R E C T O R Y; +HEADER_P : H E A D E R; +HOLD : H O L D; +HOUR_P : H O U R; +IDENTIFIED : I D E N T I F I E D; +IDENTITY_P : I D E N T I T Y; +IF_P : I F; +IGNORE_EXTRA_DATA : I G N O R E UNDERSCORE E X T R A UNDERSCORE D A T A; +ILIKE : I L I K E; +IMMEDIATE : I M M E D I A T E; +IMMUTABLE : I M M U T A B L E; +IMPLICIT_P : I M P L I C I T; +IN_P : I N; +INCLUDING : I N C L U D I N G; +INCREMENT : I N C R E M E N T; +INDEX : I N D E X; +INDEXES : I N D E X E S; +INHERIT : I N H E R I T; +INHERITS : I N H E R I T S; +INITIAL_P : I N I T I A L; +INITIALLY : I N I T I A L L Y; +INITRANS : I N I T R A N S; +INLINE_P : I N L I N E; +INNER_P : I N N E R; +INOUT : I N O U T; +INPUT_P : I N P U T; +INSENSITIVE : I N S E N S I T I V E; +INSERT : I N S E R T; +INSTEAD : I N S T E A D; +INT_P : I N T; +INTEGER : I N T E G E R; +INTERSECT : I N T E R S E C T; +INTERVAL : I N T E R V A L; +INTO : I N T O; +INVOKER : I N V O K E R; +IS : I S; +ISNULL : I S N U L L; +ISOLATION : I S O L A T I O N; +JOIN : J O I N; +KEY : K E Y; +LABEL : L A B E L; +LANGUAGE : L A N G U A G E; +LARGE_P : L A R G E; +LAST_P : L A S T; +LC_COLLATE_P : L C UNDERSCORE C O L L A T E; +LC_CTYPE_P : L C UNDERSCORE C T Y P E; +LEADING : L E A D I N G; +LEAKPROOF : L E A K P R O O F; +LEAST : L E A S T; +LESS : L E S S; +LEFT : L E F T; +LEVEL : L E V E L; +LIKE : L I K E; +LIMIT : L I M I T; +LISTEN : L I S T E N; +LOAD : L O A D; +LOCAL : L O C A L; +LOCALTIME : L O C A L T I M E; +LOCALTIMESTAMP : L O C A L T I M E S T A M P; +LOCATION : L O C A T I O N; +LOCK_P : L O C K; +LOG_P : L O G; +LOGGING : L O G G I N G; +LOOP : L O O P; +MAPPING : M A P P I N G; +MATCH : M A T C H; +MAXEXTENTS : M A X E X T E N T S; +MAXSIZE : M A X S I Z E; +MAXTRANS : M A X T R A N S; +MAXVALUE : M A X V A L U E; +MERGE : M E R G E; +MINUS_P : M I N U S; +MINUTE_P : M I N U T E; +MINVALUE : M I N V A L U E; +MINEXTENTS : M I N E X T E N T S; +MODE : M O D E; +MODIFY_P : M O D I F Y; +MONTH_P : M O N T H; +MOVE : M O V E; +MOVEMENT : M O V E M E N T; +NAME_P : N A M E; +NAMES : N A M E S; +NATIONAL : N A T I O N A L; +NATURAL : N A T U R A L; +NCHAR : N C H A R; +NEXT : N E X T; +NLSSORT : N L S S O R T; +NO : N O; +NOCOMPRESS : N O C O M P R E S S; +NOCYCLE : N O C Y C L E; +NODE : N O D E; +NOLOGGING : N O L O G G I N G; +NOMAXVALUE : N O M A X V A L U E; +NOMINVALUE : N O M I N V A L U E; +NON : N O N; +NONE : N O N E; +NOT : N O T; +NOTHING : N O T H I N G; +NOTIFY : N O T I F Y; +NOTNULL : N O T N U L L; +NOWAIT : N O W A I T; +NULL_P : N U L L; +NULLIF : N U L L I F; +NULLS_P : N U L L S; +NUMBER_P : N U M B E R; +NUMERIC : N U M E R I C; +NUMSTR : N U M S T R; +NVARCHAR2 : N V A R C H A R '2'; +NVL : N V L; +OBJECT_P : O B J E C T; +OF : O F; +OFF : O F F; +OFFSET : O F F S E T; +OIDS : O I D S; +ON : O N; +ONLY : O N L Y; +OPERATOR : O P E R A T O R; +OPTIMIZATION : O P T I M I Z A T I O N; +OPTION : O P T I O N; +OPTIONS : O P T I O N S; +OR : O R; +ORDER : O R D E R; +OUT_P : O U T; +OUTER_P : O U T E R; +OVER : O V E R; +OVERLAPS : O V E R L A P S; +OVERLAY : O V E R L A Y; +OWNED : O W N E D; +OWNER : O W N E R; +PARSER : P A R S E R; +PARTIAL : P A R T I A L; +PARTITION : P A R T I T I O N; +PARTITIONS : P A R T I T I O N S; +PASSING : P A S S I N G; +PASSWORD : P A S S W O R D; +PCTFREE : P C T F R E E; +PER_P : P E R; +PERCENT : P E R C E N T; +PERFORMANCE : P E R F O R M A N C E; +PERM : P E R M; +PLACING : P L A C I N G; +PLANS : P L A N S; +POSITION : P O S I T I O N; +POOL : P O O L; +PRECEDING : P R E C E D I N G; +PRECISION : P R E C I S I O N; +PREFERRED : P R E F E R R E D; +PREFIX : P R E F I X; +PRESERVE : P R E S E R V E; +PREPARE : P R E P A R E; +PREPARED : P R E P A R E D; +PRIMARY : P R I M A R Y; +PRIOR : P R I O R; +PRIVILEGES : P R I V I L E G E S; +PRIVILEGE : P R I V I L E G E; +PROCEDURAL : P R O C E D U R A L; +PROCEDURE : P R O C E D U R E; +PACKAGE : P A C K A G E; +PROFILE : P R O F I L E; +QUERY : Q U E R Y; +QUOTE : Q U O T E; +RANGE : R A N G E; +RAW : R A W; +READ : R E A D; +REAL : R E A L; +REASSIGN : R E A S S I G N; +REBUILD : R E B U I L D; +RECHECK : R E C H E C K; +RECURSIVE : R E C U R S I V E; +REF : R E F; +REFERENCES : R E F E R E N C E S; +REINDEX : R E I N D E X; +REJECT_P : R E J E C T; +RELATIVE_P : R E L A T I V E; +RELEASE : R E L E A S E; +RELOPTIONS : R E L O P T I O N S; +REMOTE_P : R E M O T E; +RENAME : R E N A M E; +REPEATABLE : R E P E A T A B L E; +REPLACE : R E P L A C E; +REPLICA : R E P L I C A; +RESET : R E S E T; +RESIZE : R E S I Z E; +RESOURCE : R E S O U R C E; +RESTART : R E S T A R T; +RESTRICT : R E S T R I C T; +RETURN : R E T U R N; +RETURNING : R E T U R N I N G; +RETURNS : R E T U R N S; +REUSE : R E U S E; +REVOKE : R E V O K E; +RIGHT : R I G H T; +ROLE : R O L E; +ROLLBACK : R O L L B A C K; +ROLLUP : R O L L U P; +ROW : R O W; +ROWS : R O W S; +RULE : R U L E; +SAVEPOINT : S A V E P O I N T; +SCHEMA : S C H E M A; +SCROLL : S C R O L L; +SEARCH : S E A R C H; +SECOND_P : S E C O N D; +SECURITY : S E C U R I T Y; +SELECT : S E L E C T; +SEQUENCE : S E Q U E N C E; +SEQUENCES : S E Q U E N C E S; +SERIALIZABLE : S E R I A L I Z A B L E; +SERVER : S E R V E R; +SESSION : S E S S I O N; +SESSION_USER : S E S S I O N UNDERSCORE U S E R; +SET : S E T; +SETS : S E T S; +SETOF : S E T O F; +SHARE : S H A R E; +SHOW : S H O W; +SIMILAR : S I M I L A R; +SIMPLE : S I M P L E; +SIZE : S I Z E; +SMALLDATETIME : S M A L L D A T E T I M E; +SMALLDATETIME_FORMAT_P : S M A L L D A T E T I M E UNDERSCORE F O R M A T; +SMALLINT : S M A L L I N T; +SNAPSHOT : S N A P S H O T; +SOME : S O M E; +SPACE : S P A C E; +SPLIT : S P L I T; +STABLE : S T A B L E; +STANDALONE_P : S T A N D A L O N E; +START : S T A R T; +STATEMENT : S T A T E M E N T; +STATISTICS : S T A T I S T I C S; +STDIN : S T D I N; +STDOUT : S T D O U T; +STORAGE : S T O R A G E; +STORE_P : S T O R E; +STRICT_P : S T R I C T; +STRIP_P : S T R I P; +SUBSTRING : S U B S T R I N G; +SYMMETRIC : S Y M M E T R I C; +SYSDATE : S Y S D A T E; +SYSID : S Y S I D; +SYSTEM_P : S Y S T E M; +SYS_REFCURSOR : S Y S UNDERSCORE R E F C U R S O R; +TABLE : T A B L E; +TABLES : T A B L E S; +TABLESPACE : T A B L E S P A C E; +TEMP : T E M P; +TEMPLATE : T E M P L A T E; +TEMPORARY : T E M P O R A R Y; +TEXT_P : T E X T; +THAN : T H A N; +THEN : T H E N; +TIME : T I M E; +TIME_FORMAT_P : T I M E UNDERSCORE F O R M A T; +TIMESTAMP : T I M E S T A M P; +TIMESTAMP_FORMAT_P : T I M E S T A M P UNDERSCORE F O R M A T; +TINYINT : T I N Y I N T; +TO : T O; +TRAILING : T R A I L I N G; +TRANSACTION : T R A N S A C T I O N; +TREAT : T R E A T; +TRIGGER : T R I G G E R; +TRIM : T R I M; +TRUE_P : T R U E; +TRUNCATE : T R U N C A T E; +TRUSTED : T R U S T E D; +TYPE_P : T Y P E; +TYPES_P : T Y P E S; +UNBOUNDED : U N B O U N D E D; +UNCOMMITTED : U N C O M M I T T E D; +UNENCRYPTED : U N E N C R Y P T E D; +UNION : U N I O N; +UNIQUE : U N I Q U E; +UNKNOWN : U N K N O W N; +UNLIMITED : U N L I M I T E D; +UNLISTEN : U N L I S T E N; +UNLOCK : U N L O C K; +UNLOGGED : U N L O G G E D; +UNTIL : U N T I L; +UNUSABLE : U N U S A B L E; +UPDATE : U P D A T E; +USER : U S E R; +USING : U S I N G; +VACUUM : V A C U U M; +VALID : V A L I D; +VALIDATE : V A L I D A T E; +VALIDATION : V A L I D A T I O N; +VALIDATOR : V A L I D A T O R; +VALUE_P : V A L U E; +VALUES : V A L U E S; +VARCHAR : V A R C H A R; +VARCHAR2 : V A R C H A R '2'; +VARIADIC : V A R I A D I C; +VARRAY : V A R R A Y; +VARYING : V A R Y I N G; +VERBOSE : V E R B O S E; +VERSION_P : V E R S I O N; +VIEW : V I E W; +VOLATILE : V O L A T I L E; +WHEN : W H E N; +WHERE : W H E R E; +WHITESPACE_P : W H I T E S P A C E; +WINDOW : W I N D O W; +WITH : W I T H; +WITHOUT : W I T H O U T; +WORK : W O R K; +WORKLOAD : W O R K L O A D; +WRAPPER : W R A P P E R; +WRITE : W R I T E; +XML_P : X M L; +XMLATTRIBUTES : X M L A T T R I B U T E S; +XMLCONCAT : X M L C O N C A T; +XMLELEMENT : X M L E L E M E N T; +XMLEXISTS : X M L E X I S T S; +XMLFOREST : X M L F O R E S T; +XMLPARSE : X M L P A R S E; +XMLPI : X M L P I; +XMLROOT : X M L R O O T; +XMLSERIALIZE : X M L S E R I A L I Z E; +YEAR_P : Y E A R; +YES_P : Y E S; +ZONE : Z O N E; + +/* + * The grammar thinks these are keywords, but they are not in the kwlist.h + * list and so can never be entered directly. The filter in parser.c + * creates these tokens when required. + */ +NULLS_FIRST : NULLS_P T_whitespace+ FIRST_P; +NULLS_LAST : NULLS_P T_whitespace+ LAST_P; +WITH_TIME : WITH T_whitespace+ TIME; +PARTITION_FOR : PARTITION T_whitespace+ FOR; +BEGIN_NON_ANOYBLOCK : BEGIN_P T_whitespace+ NON T_whitespace+ ANOYBLOCK; + +T_TYPECAST : '::'; +T_PARAM : '$' T_integer; +T_COLON_EQUALS : ':='; +T_PARA_EQUALS : '=>'; + +/* making lexer case insensitive */ +fragment A:('a'|'A'); +fragment B:('b'|'B'); +fragment C:('c'|'C'); +fragment D:('d'|'D'); +fragment E:('e'|'E'); +fragment F:('f'|'F'); +fragment G:('g'|'G'); +fragment H:('h'|'H'); +fragment I:('i'|'I'); +fragment J:('j'|'J'); +fragment K:('k'|'K'); +fragment L:('l'|'L'); +fragment M:('m'|'M'); +fragment N:('n'|'N'); +fragment O:('o'|'O'); +fragment P:('p'|'P'); +fragment Q:('q'|'Q'); +fragment R:('r'|'R'); +fragment S:('s'|'S'); +fragment T:('t'|'T'); +fragment U:('u'|'U'); +fragment V:('v'|'V'); +fragment W:('w'|'W'); +fragment X:('x'|'X'); +fragment Y:('y'|'Y'); +fragment Z:('z'|'Z'); +fragment UNDERSCORE: '_'; + +/* common symbols used in parser grammar */ +T_LEFTBRACKET : '('; +T_RIGHTBRACKET : ')'; +T_LEFT_SQBRACKET : '['; +T_RIGHT_SQBRACKET : ']'; +T_COMMA : ','; +T_EQUALS : '='; +T_COLON : ':'; +T_PLUS : '+'; +T_MINUS : '-'; +T_PRODUCT : '*'; +T_DIVIDE : '/'; +T_MODULO : '%'; +T_EXPONENT : '^'; +T_LESSTHAN : '<'; +T_GREATERTHAN : '>'; +T_DOT : '.'; +T_SEMICOLON : ';'; + +LESS_LESS : '<<'; +GREATER_GREATER : '>>'; + +DOT_DOT : '..' ; +SCONST : XQString + | XNString + | XEString + | XDOLQString + ; +BCONST : XBString; +XCONST : XHString; +IDENT : '`'? XDQString '`'? + | XUIString + | IDENT_START IDENT_CONT* + | OLTP_IDENT + | IDENT_START_SPC T_space* + | IDENT_START_SPC IDENT_CONT* + ; +PARAM : '$' T_integer ; +FCONST : T_real | T_decimal; +ICONST : T_integer; + +fragment OP_SIMPLE : + ( '<' + | '>' + | '=' + | '/' { _input.LA(1) != '*' }? + | '*' + )+ + ; + +fragment OP_MINUS : '-' { _input.LA(1) != '-' }? ; +fragment OP_PLUS : '+' ; + +fragment OP_PLUSMINUS : ( OP_PLUS | OP_MINUS ) ; + +fragment OP_COMPLEX : [~!@#%&|`?^]+ ; + +fragment OP_WITH_COMPLEX + : + ( OP_PLUSMINUS + | OP_SIMPLE + )* + OP_COMPLEX + ( OP_PLUSMINUS + | OP_SIMPLE + | OP_COMPLEX + )* + ; + +fragment OP_WITHOUT_COMPLEX + : ( OP_SIMPLE | OP_PLUSMINUS )* OP_SIMPLE + ; + +Op : + ( OP_WITHOUT_COMPLEX + | OP_WITH_COMPLEX + | OP_PLUSMINUS + ) + ; + +/** Line comment */ +T_comment : '--' ( ~[\n\r] )* -> channel(HIDDEN); +/** C-style comments */ + +T_ccomment : '/*' ( T_ccomment | . )*? '*/' -> channel(HIDDEN); + +T_space : [ \t\n\r\f] -> channel(HIDDEN); +T_newline : [\n\r] -> channel(HIDDEN); +T_whitespace : ( T_space+ | T_comment ) -> channel(HIDDEN); + +/** Numbers */ +fragment T_real : ( T_integer | T_decimal ) [Ee] [-+]? DIGIT+ ; +fragment T_decimal : ( ( DIGIT* '.' DIGIT+ ) | ( DIGIT+ '.' DIGIT* ) ) ; +fragment T_integer : DIGIT+ ; + +/* + * SQL requires at least one newline in the whitespace separating + * string literals that are to be concatenated. Silly, but who are we + * to argue? Note that {whitespace_with_newline} should not have * after + * it, whereas {whitespace} should generally have a * after it... + */ + +T_special_whitespace : ( T_space+ | T_comment T_newline) -> channel(HIDDEN); +T_horiz_whitespace : (T_horiz_space | T_comment) -> channel(HIDDEN); +T_whitespace_with_newline : T_horiz_whitespace* T_newline T_special_whitespace* -> channel(HIDDEN); + +T_horiz_space : [ \t\f] -> channel(HIDDEN); + +/* + * To ensure that {quotecontinue} can be scanned without having to back up + * if the full pattern isn't matched, we include trailing whitespace in + * {quotestop}. This matches all cases where {quotecontinue} fails to match, + * except for {quote} followed by whitespace and just one "-" (not two, + * which would start a {comment}). To cover that we have {quotefail}. + * The actions for {quotestop} and {quotefail} must throw back characters + * beyond the quote proper. + */ +fragment T_quote : '\'' ; +fragment T_nonquote : ~'\''+ ; +fragment T_xeinside : ~[\\']+ ; +fragment T_quotecontinue : T_quote T_whitespace_with_newline T_quote ; +fragment T_xqdouble : T_quote T_quote ; +fragment OLTP_IDENT : '`' (T_dquote | T_nondquote)+ '`'; + +/** Quoted string */ +fragment XQString : T_quote ( T_xqdouble | T_quotecontinue | T_nonquote )* T_quote ; +/** Binary string number */ +fragment XBString : B T_quote ( T_quotecontinue | [01]+ )* T_quote ; +/** Hexadecimal number */ +fragment XHString : X T_quote ( T_quotecontinue | HDIGIT+ )* T_quote ; +/** National character */ +fragment XNString : N XQString ; +/* Quoted string that allows backslash escapes */ +fragment XEString : E T_quote ( T_xqdouble + | T_quotecontinue + | '\\' ( 'x' ( HDIGIT HDIGIT? ) // hex + | ( 'u' HDIGIT HDIGIT HDIGIT HDIGIT + | 'U' HDIGIT HDIGIT HDIGIT HDIGIT HDIGIT HDIGIT HDIGIT HDIGIT + ) // unicode + | NOT_ODIGIT // escape + | ( ODIGIT ODIGIT ODIGIT | ODIGIT ODIGIT | ODIGIT ) // octets + ) // escapes + | T_xeinside )* T_quote ; + +fragment DIGIT : [0-9] ; +fragment ODIGIT : [0-7] ; +fragment NOT_ODIGIT : ~[0-7] ; +fragment HDIGIT : [0-9A-Fa-f] ; + +/* $foo$ style quotes ("dollar quoting") + * The quoted string starts with $foo$ where "foo" is an optional string + * in the form of an identifier, except that it may not contain "$", + * and extends to the first occurrence of an identical string. + * There is *no* processing of the quoted text. + * + * {dolqfailed} is an error rule to avoid scanner backup when {dolqdelim} + * fails to match its trailing "$". + */ + +fragment XDOLQString : '$$' .*? '$$' + | '$BODY$' .*? '$BODY$' // this is a hack until the $$ string is implemented + | '$function$' .*? '$function$' + ; + +//support unicode characters +fragment IDENT_START_SPC : [`~{}@#$%/\\^&|:-] ; +fragment IDENT_START : [A-Za-z] | ~[\u0000-\u007F\uD800-\uDBFF] | [\uD800-\uDBFF] [\uDC00-\uDFFF]; +fragment IDENT_CONT : [A-Za-z0-9$_] | ~[\u0000-\u007F\uD800-\uDBFF] | [\uD800-\uDBFF] [\uDC00-\uDFFF] ; + +/* Double quote + * Allows embedded spaces and other special characters into identifiers. + */ + /* + * Gauss when has two double quotes inside a double quoted string, it takes it as one double quote. + * i.e "Hello""World" = "Hello"World" + * so the simple XDQString has been replaced with a new rule. + */ +/*fragment XDQString : T_dquote ( T_xddouble | T_nondquote )*? T_dquote ;*/ +fragment XDQString : T_dquote ( '""' | T_nondquote )* T_dquote + { + String s = getText(); + s = s.substring(1, s.length() - 1); // strip the leading and trailing quotes + s = s.replace("\"\"", "\""); // replace all double quotes with single quotes + setText(s); + } + ; + +fragment T_dquote : '"' ; +fragment T_nondquote : ~'"'+ ; +fragment T_xddouble : T_dquote T_dquote ; + +/* Unicode escapes */ +fragment T_uescape : U E S C A P E T_whitespace* T_quote T_nondquote*? T_quote ; + +fragment XUIString : U '&' XDQString ( T_whitespace* T_uescape )? ; + +PSQL_COMMAND : '\\' ( ~[\n\r] )*; + +ErrorChar : . ; \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/grammar/PostgresParser.g4 b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/grammar/PostgresParser.g4 new file mode 100644 index 0000000000000000000000000000000000000000..ae3b84cb33607ec2c6f2b63ce963fd293d9b2053 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/grammar/PostgresParser.g4 @@ -0,0 +1,1588 @@ +parser grammar PostgresParser; + +options { tokenVocab=PostgresLexer; } + +@header { + package org.opengauss.mppdbide.parser.grammar; +} + +allStmt : (unit_statement)+ | explainable_statement+; + +functionStmt : createFunction+; + +explainable_statement : EXPLAIN explain_type? unit_statement ; + +explain_type : VERBOSE + | PERFORMANCE + | ANALYSE VERBOSE? + | ANALYZE VERBOSE? + | T_LEFTBRACKET target_list T_RIGHTBRACKET //target_list is temporarily used for 18.1 version + ; + +unit_statement : (selectStmt + | insertStmt + | updateStmt + | deleteStmt + | any_stmt) T_SEMICOLON + ; + +selectStmt : select_no_parens + | select_with_parens + ; + +select_with_parens : T_LEFTBRACKET (select_no_parens | select_with_parens) T_RIGHTBRACKET ; + +select_no_parens : with_clause? select_clause sort_clause? ( select_limit opt_for_locking_clause + | for_locking_clause opt_select_limit + )? ; + +with_clause : WITH RECURSIVE? cte_list; + +cte_list : common_table_expr (T_COMMA common_table_expr)* ; + +common_table_expr : name opt_name_list AS T_LEFTBRACKET preparableStmt T_RIGHTBRACKET ; + +opt_name_list : T_LEFTBRACKET name_list T_RIGHTBRACKET | ; + +name_list : (name T_COMMA)* name ; + +preparableStmt : selectStmt + | insertStmt + | updateStmt + | deleteStmt + ; + +insertStmt : opt_with_clause insertInto insert_rest returning_clause?; + +insertInto : INSERT INTO insertTable; + +insertTable : qualified_name; + +returning_clause : RETURNING returningTargetList + | + ; + +returningTargetList : target_list; + +target_list : target_el (T_COMMA target_el)* ; //rule simplified for select alias + +target_el : T_PRODUCT + | a_expr ( AS colLabel + | IDENT + )? + ; + +insert_rest : insertColumnFull? (selectStmt + | insertDefaultValues) + ; + +insertDefaultValues : DEFAULT VALUES; + + +insertColumnFull : (T_LEFTBRACKET insert_column_list T_RIGHTBRACKET); + + +insert_column_list : (insert_column_item T_COMMA)* insert_column_item ; + +insert_column_item : colId opt_indirection ; + +updateStmt : opt_with_clause updateTableName updateSetCluase updateFrom_cluase? where_or_current_clause returning_clause ; + +updateTableName : UPDATE onlycluase? relation_expr_opt_alias; + +updateSetCluase : SET set_clause_list; + +updateFrom_cluase : from_clause; + +relation_expr_opt_alias : relation_expr AS? colId? ; + +relation_expr : qualified_name T_PRODUCT? + | ONLY ( qualified_name + | T_LEFTBRACKET qualified_name T_RIGHTBRACKET + ) + ; + +opt_with_clause : with_clause + | + ; + +set_clause_list : (set_clause T_COMMA)* set_clause ; + +set_clause : single_set_clause + | multiple_set_clause + ; + +single_set_clause : set_target T_EQUALS ctext_expr; + +multiple_set_clause : multiple_set_clause_columns T_EQUALS ( multiple_set_clause_ctext_row + | selectStmt) + ; + +multiple_set_clause_columns : T_LEFTBRACKET set_target_list T_RIGHTBRACKET; + +multiple_set_clause_ctext_row : ctext_row; + +where_clause : WHERE a_expr? + | + ; + +group_clause : GROUP_P BY group_by_list + | + ; + + +group_by_list : group_by_item (T_COMMA group_by_item)* //rule simplified for select alias + ; + +group_by_item : a_expr + | empty_grouping_set + | cube_clause + | rollup_clause + | grouping_sets_clause + ; + +empty_grouping_set : T_LEFTBRACKET T_RIGHTBRACKET; + +cube_clause : CUBE T_LEFTBRACKET expr_list T_RIGHTBRACKET; + +rollup_clause : ROLLUP T_LEFTBRACKET expr_list T_RIGHTBRACKET; + +grouping_sets_clause : GROUPING_P SETS T_LEFTBRACKET group_by_list T_RIGHTBRACKET; + +having_clause : HAVING a_expr + | + ; + +ctext_expr : a_expr + | DEFAULT + ; + +ctext_row : T_LEFTBRACKET ctext_expr_list T_RIGHTBRACKET; + +opt_distinct : DISTINCT (ON T_LEFTBRACKET expr_list T_RIGHTBRACKET)? + | ALL + | + ; + +ctext_expr_list : (ctext_expr T_COMMA)* ctext_expr + ; + +from_clause : FROM from_list + | + ; + +from_list : table_ref (T_COMMA table_ref)* //rule simplified for select alias + ; + +table_ref : relation_expr ( alias_clause + | PARTITION T_LEFTBRACKET name T_RIGHTBRACKET alias_clause? + | PARTITION_FOR T_LEFTBRACKET maxValueList T_RIGHTBRACKET alias_clause? + )? + | func_table ( alias_clause + | AS T_LEFTBRACKET tableFuncElementList T_RIGHTBRACKET + | AS? colId T_LEFTBRACKET tableFuncElementList T_RIGHTBRACKET + )? + | select_with_parens alias_clause? + | table_ref join_type table_ref join_qual? + | T_LEFTBRACKET table_ref join_type table_ref join_qual? T_RIGHTBRACKET? alias_clause? + ; + +join_qual : USING T_LEFTBRACKET name_list T_RIGHTBRACKET + | ON a_expr + ; + +join_type : FULL JOIN + | LEFT JOIN + | FULL JOIN + | RIGHT JOIN + | JOIN + | LEFT OUTER_P + | FULL OUTER_P + | RIGHT OUTER_P + | INNER_P JOIN + | NATURAL JOIN + | CROSS JOIN + | LEFT OUTER_P JOIN + | FULL OUTER_P JOIN + | RIGHT OUTER_P JOIN + ; + +join_outer : OUTER_P + | + ; + +tableFuncElementList : (tableFuncElement T_COMMA)* tableFuncElement + ; + +tableFuncElement : colId typename opt_collate_clause; + +opt_collate_clause : COLLATE any_name + | + ; + +alias_clause : AS? colId (T_LEFTBRACKET name_list T_RIGHTBRACKET)? + ; + +maxValueList : (maxValueItem T_COMMA)* maxValueItem + ; + +maxValueItem : a_expr + | MAXVALUE + ; + +func_table : func_expr; + +set_target : colId opt_indirection; + +set_target_list : (set_target T_COMMA)* set_target + ; + +deleteStmt : opt_with_clause deleteTableName using_clause? where_or_current_clause returning_clause + ; + +deleteTableName : DELETE_P FROM onlycluase? relation_expr_opt_alias; + +onlycluase : ONLY; + +where_or_current_clause : WHERE ( a_expr + | CURRENT_P OF cursor_name + ) + | + ; + +cursor_name : name; + +using_clause : USING from_list + | + ; + +name : colId; + +colId : unreserved_keyword + | col_name_keyword + | IDENT + ; + +select_clause : simple_select + | select_with_parens + | select_clause ( UNION //added from simple_select to remove left recursion + | INTERSECT + | EXCEPT + | MINUS_P + ) opt_all select_clause + ; + +simple_select : SELECT opt_distinct target_list? into_clause from_clause where_clause group_clause having_clause window_clause //rule simplified for select alias + | values_clause + | TABLE relation_expr + ; + +opt_sort_clause : sort_clause | ; + +select_limit : limit_clause offset_clause? + | offset_clause limit_clause? + ; + +limit_clause : LIMIT select_limit_value (T_COMMA select_offset_value)? + | FETCH first_or_next opt_select_fetch_first_value row_or_rows ONLY + ; + +first_or_next : FIRST_P + | NEXT + ; + +opt_select_fetch_first_value : signedIconst + | T_LEFTBRACKET a_expr T_RIGHTBRACKET + | + ; + +signedIconst : ICONST + | T_MINUS ICONST + | T_PLUS ICONST + ; + +row_or_rows : ROW + | ROWS + ; + +select_offset_value : a_expr; + +select_limit_value : a_expr + | ALL + ; + +offset_clause : OFFSET ( select_offset_value + | select_offset_value2 row_or_rows + ) + ; + +select_offset_value2 : c_expr; + +opt_for_locking_clause : for_locking_clause + | + ; + +for_locking_clause : for_locking_items + | FOR READ ONLY + ; + +for_locking_items : for_locking_item+ + ; + +for_locking_item : FOR UPDATE locked_rels_list opt_nowait + | FOR SHARE locked_rels_list opt_nowait + ; + +locked_rels_list : OF qualified_name_list + | + ; + +qualified_name_list : (qualified_name T_COMMA)* qualified_name + ; + +schema_name : colId ; + +qualified_name : colId indirection? ; + +funct_name : indirection? ; + +opt_nowait : NOWAIT + | + ; + +opt_select_limit : select_limit + | + ; + +a_expr : c_expr + | a_expr ( T_TYPECAST typename + | COLLATE any_name + | AT TIME ZONE a_expr + | T_PLUS a_expr + | T_MINUS a_expr + | T_PRODUCT a_expr + | T_DIVIDE a_expr + | T_MODULO a_expr + | T_EXPONENT a_expr + | T_LESSTHAN a_expr + | T_GREATERTHAN a_expr + | T_EQUALS a_expr + | cmpOp a_expr + | qual_Op a_expr + | AND a_expr + | OR a_expr + | NOT? ( LIKE + | ILIKE + | SIMILAR TO ) a_expr (ESCAPE a_expr)? + | ISNULL + | NOTNULL + | IS ( NOT? ( NULL_P + | TRUE_P + | FALSE_P + | UNKNOWN + | DISTINCT FROM a_expr + | OF T_LEFTBRACKET type_list T_RIGHTBRACKET + | DOCUMENT_P + ) + ) + | NOT? BETWEEN SYMMETRIC b_expr AND b_expr + | NOT? BETWEEN opt_asymmetric b_expr AND b_expr + | NOT? IN_P in_expr + | subquery_Op sub_type ( select_with_parens | T_LEFTBRACKET a_expr T_RIGHTBRACKET) + ) + | ( T_PLUS + | T_MINUS + | qual_Op + | NOT ) + a_expr + | row OVERLAPS row + | UNIQUE select_with_parens + ; + +subquery_Op : all_Op + | OPERATOR T_LEFTBRACKET any_operator T_RIGHTBRACKET + | NOT? LIKE + | NOT? ILIKE + ; + +any_operator : all_Op + | colId T_DOT any_operator + ; + +all_Op : Op + | cmpOp + | mathOp + ; + +cmpOp : + ; + +mathOp : T_PLUS + | T_MINUS + | T_PRODUCT + | T_DIVIDE + | T_MODULO + | T_EXPONENT + | T_LESSTHAN + | T_GREATERTHAN + | T_EQUALS + ; + +sub_type : ANY + | SOME + | ALL + ; + +in_expr : select_with_parens + | T_LEFTBRACKET expr_list T_RIGHTBRACKET + ; + + + +expr_list : (a_expr T_COMMA)* a_expr; + +opt_asymmetric : ASYMMETRIC + | + ; + +b_expr : c_expr + | b_expr ( T_TYPECAST typename + | T_PLUS b_expr + | T_MINUS b_expr + | T_PRODUCT b_expr + | T_DIVIDE b_expr + | T_MODULO b_expr + | T_EXPONENT b_expr + | T_LESSTHAN b_expr + | T_GREATERTHAN b_expr + | T_EQUALS b_expr + | cmpOp b_expr + | qual_Op b_expr + | qual_Op + | IS ( NOT? DISTINCT FROM b_expr + | NOT? OF T_LEFTBRACKET type_list T_RIGHTBRACKET + | NOT? DOCUMENT_P + ) + ) + | T_PLUS b_expr + | T_MINUS b_expr + | qual_Op b_expr + ; + +type_list : (typename T_COMMA)* typename + ; + +row : ROW T_LEFTBRACKET expr_list? T_RIGHTBRACKET + | T_LEFTBRACKET expr_list T_COMMA a_expr T_RIGHTBRACKET + ; + +qual_Op : Op + | OPERATOR T_LEFTBRACKET any_operator T_RIGHTBRACKET + ; + +c_expr : columnref + | aexprConst + | T_PARAM opt_indirection + | c_exprWithParams //rule simplified for select alias + | case_expr + | func_expr + | select_with_parens indirection? + | EXISTS select_with_parens + | ARRAY (select_with_parens|array_expr) + | explicit_row + | implicit_row + | GROUPING_P T_LEFTBRACKET expr_list T_RIGHTBRACKET + ; + +c_exprWithParams : T_LEFTBRACKET a_expr T_RIGHTBRACKET? opt_indirection; + +implicit_row : T_LEFTBRACKET expr_list T_COMMA a_expr T_RIGHTBRACKET; + +array_expr : T_LEFT_SQBRACKET (expr_list | array_expr_list)? T_RIGHT_SQBRACKET + ; + +array_expr_list : (array_expr T_COMMA)* array_expr + ; + +explicit_row : ROW T_LEFTBRACKET expr_list? T_RIGHTBRACKET + ; + +indirection : indirection_el+; + +indirection_el : T_DOT ( attr_name + | T_PRODUCT + )? + | T_LEFT_SQBRACKET a_expr? ( T_RIGHT_SQBRACKET? //rule simplified for select alias + | T_COLON? a_expr? T_RIGHT_SQBRACKET? //rule simplified for select alias + | T_COMMA? a_expr? T_RIGHT_SQBRACKET? //rule simplified for select alias + ) + ; + +attr_name : colLabel; + +colLabel : IDENT + | unreserved_keyword + | col_name_keyword + | type_func_name_keyword + | reserved_keyword + ; + +type_func_name_keyword : AUTHORIZATION + | BINARY + | COLLATION + | COMPACT + | CONCURRENTLY + | CROSS + | CURRENT_SCHEMA + | DELTAMERGE + | FREEZE + | FULL + | HDFSDIRECTORY + | ILIKE + | INNER_P + | ISNULL + | JOIN + | LEFT + | LIKE + | NATURAL + | NOTNULL + | OUTER_P + | OVER + | OVERLAPS + | RIGHT + | SIMILAR + | VERBOSE + ; + +reserved_keyword: ALL + | ANALYSE + | ANALYZE + | AND + | ANY + | ARRAY + | AS + | ASC + | ASYMMETRIC + | AUTHID + | BOTH + | BUCKETS + | CASE + | CAST + | CHECK + | COLLATE + | COLUMN + | CONSTRAINT + | CREATE + | CURRENT_CATALOG + | CURRENT_DATE + | CURRENT_ROLE + | CURRENT_TIME + | CURRENT_TIMESTAMP + | CURRENT_USER + | DEFAULT + | DEFERRABLE + | DESC + | DISTINCT + | DO + | ELSE + | END_P + | EXCEPT + | FALSE_P + | FETCH + | FOR + | FOREIGN + | FROM + | FUNCTION + | GRANT + | GROUP_P + | HAVING + | IN_P + | INITIALLY + | INTERSECT + | INTO + | IS + | LEADING + | LESS + | LIMIT + | LOCALTIME + | LOCALTIMESTAMP + | MAXVALUE + | MINUS_P + | MODIFY_P + | NLSSORT + | NOT + | NULL_P + | OFFSET + | ON + | ONLY + | OR + | ORDER + | PERFORMANCE + | PLACING + | PRIMARY + | PROCEDURE + | PACKAGE + | REFERENCES + | REJECT_P + | RETURN + | RETURNING + | SELECT + | SESSION_USER + | SOME + | SPLIT + | SYMMETRIC + | SYSDATE + | TABLE + | THEN + | TO + | TRAILING + | TRUE_P + | UNION + | UNIQUE + | USER + | USING + | VARIADIC + | WHEN + | WHERE + | WINDOW + | WITH + ; + +case_expr : CASE case_arg when_clause_list case_default END_P + | DECODE T_LEFTBRACKET a_expr T_COMMA expr_list T_RIGHTBRACKET + ; + +case_arg : a_expr | ; + +when_clause_list : when_clause+; + +when_clause : WHEN a_expr THEN a_expr; + +case_default : ELSE a_expr | ; + +func_expr : func_name T_LEFTBRACKET ( VARIADIC func_arg_expr + | func_arg_list + | func_arg_list (T_COMMA VARIADIC func_arg_expr|sort_clause) + )? T_RIGHTBRACKET over_clause + | ALL func_arg_list opt_sort_clause T_RIGHTBRACKET over_clause + | DISTINCT func_arg_list opt_sort_clause T_RIGHTBRACKET over_clause + | T_PRODUCT T_RIGHTBRACKET over_clause + | COLLATION FOR T_LEFTBRACKET a_expr T_RIGHTBRACKET + | CURRENT_DATE + | CURRENT_TIME (T_LEFTBRACKET ICONST T_RIGHTBRACKET)? + | CURRENT_TIMESTAMP (T_LEFTBRACKET ICONST T_RIGHTBRACKET)? + | LOCALTIME (T_LEFTBRACKET ICONST T_RIGHTBRACKET)? + | LOCALTIMESTAMP (T_LEFTBRACKET ICONST T_RIGHTBRACKET)? + | SYSDATE + | CURRENT_ROLE + | CURRENT_USER + | SESSION_USER + | USER + | CURRENT_CATALOG + | CURRENT_SCHEMA + | CAST T_LEFTBRACKET a_expr AS typename T_RIGHTBRACKET + | EXTRACT T_LEFTBRACKET extract_list T_RIGHTBRACKET + | OVERLAY T_LEFTBRACKET overlay_list T_RIGHTBRACKET + | POSITION T_LEFTBRACKET position_list T_RIGHTBRACKET + | SUBSTRING T_LEFTBRACKET substr_list T_RIGHTBRACKET + | TREAT T_LEFTBRACKET a_expr AS typename T_RIGHTBRACKET + | TRIM T_LEFTBRACKET ( BOTH + | LEADING + | TRAILING)? trim_list T_RIGHTBRACKET + | NULLIF T_LEFTBRACKET a_expr T_COMMA a_expr T_RIGHTBRACKET + | NVL T_LEFTBRACKET a_expr T_COMMA a_expr T_RIGHTBRACKET + | COALESCE T_LEFTBRACKET expr_list T_RIGHTBRACKET + | GREATEST T_LEFTBRACKET expr_list T_RIGHTBRACKET + | LEAST T_LEFTBRACKET expr_list T_RIGHTBRACKET + | XMLCONCAT T_LEFTBRACKET expr_list T_RIGHTBRACKET + | XMLELEMENT T_LEFTBRACKET NAME_P colLabel ( T_COMMA ( xml_attributes + | expr_list + | xml_attributes T_COMMA expr_list ) )? T_RIGHTBRACKET + | XMLEXISTS T_LEFTBRACKET c_expr xmlexists_argument T_RIGHTBRACKET + | XMLFOREST T_LEFTBRACKET xml_attribute_list T_RIGHTBRACKET + | XMLPARSE T_LEFTBRACKET document_or_content a_expr xml_whitespace_option T_RIGHTBRACKET + | XMLPI T_LEFTBRACKET NAME_P colLabel (T_COMMA a_expr)? T_RIGHTBRACKET + | XMLROOT T_LEFTBRACKET a_expr T_COMMA xml_root_version opt_xml_root_standalone T_RIGHTBRACKET + | XMLSERIALIZE T_LEFTBRACKET document_or_content a_expr AS simpleTypename T_RIGHTBRACKET + ; + +simpleTypename : genericType + | numeric + | bit + | character + | constDatetime + | constInterval (T_LEFTBRACKET ICONST T_RIGHTBRACKET)? opt_interval + ; + +opt_interval : YEAR_P + | MONTH_P + | DAY_P + | HOUR_P + | MINUTE_P + | interval_second + | YEAR_P TO MONTH_P + | DAY_P TO HOUR_P + | DAY_P TO MINUTE_P + | DAY_P TO interval_second + | HOUR_P TO MINUTE_P + | HOUR_P TO interval_second + | MINUTE_P TO interval_second + | YEAR_P T_LEFTBRACKET ICONST T_RIGHTBRACKET + | MONTH_P T_LEFTBRACKET ICONST T_RIGHTBRACKET + | DAY_P T_LEFTBRACKET ICONST T_RIGHTBRACKET + | HOUR_P T_LEFTBRACKET ICONST T_RIGHTBRACKET + | MINUTE_P T_LEFTBRACKET ICONST T_RIGHTBRACKET + | YEAR_P T_LEFTBRACKET ICONST T_RIGHTBRACKET TO MONTH_P + | DAY_P T_LEFTBRACKET ICONST T_RIGHTBRACKET TO HOUR_P + | DAY_P T_LEFTBRACKET ICONST T_RIGHTBRACKET TO MINUTE_P + | DAY_P T_LEFTBRACKET ICONST T_RIGHTBRACKET TO interval_second + | HOUR_P T_LEFTBRACKET ICONST T_RIGHTBRACKET TO MINUTE_P + | HOUR_P T_LEFTBRACKET ICONST T_RIGHTBRACKET TO interval_second + | MINUTE_P T_LEFTBRACKET ICONST T_RIGHTBRACKET TO interval_second + | + ; + +interval_second : SECOND_P (T_LEFTBRACKET ICONST T_RIGHTBRACKET)? + ; + +constInterval : INTERVAL; + +character : CHARACTER opt_varying + | CHAR_P opt_varying + | NVARCHAR2 + | VARCHAR + | VARCHAR2 + | NATIONAL CHARACTER opt_varying + | NATIONAL CHAR_P opt_varying + | NCHAR opt_varying + ; + +opt_varying : VARYING + | + ; + +bit : bitWithLength + | bitWithoutLength + ; + +numeric : INT_P + | INTEGER opt_type_modifiers + | SMALLINT + | TINYINT + | BIGINT + | REAL + | FLOAT_P opt_float + | BINARY_DOUBLE + | BINARY_INTEGER + | DOUBLE_P PRECISION + | DECIMAL_P opt_type_modifiers + | NUMBER_P opt_type_modifiers + | DEC opt_type_modifiers + | NUMERIC opt_type_modifiers + | BOOLEAN_P + ; + +opt_float : T_LEFTBRACKET ICONST T_RIGHTBRACKET + | + ; + +opt_type_modifiers : T_LEFTBRACKET expr_list T_RIGHTBRACKET + | + ; + +genericType : type_function_name attrs? opt_type_modifiers + ; + +attrs : T_DOT attr_name + | attrs T_DOT attr_name + ; + +type_function_name : IDENT + | unreserved_keyword + | type_func_name_keyword + ; + +xml_root_version : VERSION_P a_expr + | VERSION_P NO VALUE_P + ; + +opt_xml_root_standalone : T_COMMA STANDALONE_P YES_P + | T_COMMA STANDALONE_P NO + | T_COMMA STANDALONE_P NO VALUE_P + | + ; + +document_or_content : DOCUMENT_P + | CONTENT_P + ; + +xml_whitespace_option : WHITESPACE_P + | STRIP_P WHITESPACE_P + | + ; + +xml_attribute_list : xml_attribute_el + | xml_attribute_list T_COMMA xml_attribute_el + ; + +xml_attribute_el : a_expr AS colLabel + | a_expr + ; + +xmlexists_argument : PASSING c_expr + | PASSING c_expr BY REF + | PASSING BY REF c_expr + | PASSING BY REF c_expr BY REF + ; + +xml_attributes : XMLATTRIBUTES T_LEFTBRACKET xml_attribute_list T_RIGHTBRACKET; + +trim_list : a_expr FROM expr_list + | FROM expr_list + | expr_list + ; + +substr_list : a_expr ( substr_from substr_for? + | substr_for substr_from?) + | expr_list + | + ; + +substr_from : FROM a_expr; + +substr_for : FOR a_expr; + +position_list : b_expr IN_P b_expr + | + ; + +overlay_list : a_expr overlay_placing substr_from substr_for? + ; + +overlay_placing : PLACING a_expr; + +extract_list : extract_arg FROM a_expr + | + ; + +extract_arg : IDENT + | YEAR_P + | MONTH_P + | DAY_P + | HOUR_P + | MINUTE_P + | SECOND_P + | sconst + ; + +sort_clause : ORDER BY sortby_list; + +sortby_list : sortby + | sortby (T_COMMA sortby)* //rule simplified for select alias + ; + +sortby : a_expr ( USING qual_all_Op opt_nulls_order + | opt_asc_desc opt_nulls_order + ) + | NLSSORT T_LEFTBRACKET IDENT T_COMMA sconst T_RIGHTBRACKET opt_nulls_order + ; + +func_arg_expr : a_expr + | param_name (T_COLON_EQUALS | T_PARA_EQUALS) a_expr + ; + +param_name : type_function_name; + +func_arg_list : (func_arg_expr T_COMMA)* func_arg_expr + ; + +func_name : type_function_name + | colId indirection + ; + +over_clause : OVER (window_specification | colId) + | + ; + +opt_existing_window_name : colId + | + ; + +opt_partition_clause : PARTITION BY expr_list + | + ; + +opt_frame_clause : RANGE frame_extent + | ROWS frame_extent + | + ; + +frame_extent :(BETWEEN frame_bound AND)? frame_bound + ; + +frame_bound : UNBOUNDED (PRECEDING | FOLLOWING) + | CURRENT_P ROW + | a_expr (PRECEDING | FOLLOWING) + ; + +opt_indirection : indirection_el+ + | + ; + +aexprConst : ICONST + | FCONST + | sconst + | BCONST + | XCONST + | func_name (T_LEFTBRACKET func_arg_list T_RIGHTBRACKET)? sconst + | constInterval (T_LEFTBRACKET ICONST T_RIGHTBRACKET)? sconst opt_interval? + | TRUE_P + | FALSE_P + | NULL_P + ; + +constTypename : numeric + | constBit + | constCharacter + | constDatetime + ; + +constBit : bitWithLength + | bitWithoutLength + ; + +bitWithLength : BIT opt_varying T_LEFTBRACKET expr_list T_RIGHTBRACKET; + +bitWithoutLength : BIT opt_varying; + +constCharacter : characterWithLength + | characterWithoutLength + ; + +characterWithLength : character T_LEFTBRACKET ICONST T_RIGHTBRACKET opt_charset; + +characterWithoutLength : character opt_charset; + +opt_charset : CHARACTER SET colId + | + ; + +constDatetime : TIMESTAMP (T_LEFTBRACKET ICONST T_RIGHTBRACKET)? opt_timezone + | TIME (T_LEFTBRACKET ICONST T_RIGHTBRACKET)? opt_timezone + | DATE_P + | SMALLDATETIME + ; + +opt_timezone : WITH_TIME ZONE + | WITHOUT TIME ZONE + | + ; + +columnref : colId indirection? + ; + +typename : SETOF? simpleTypename ( opt_array_bounds + | ARRAY (T_LEFT_SQBRACKET ICONST T_RIGHT_SQBRACKET)?) + ; + +opt_array_bounds : opt_array_bounds ( T_LEFT_SQBRACKET ICONST? T_RIGHT_SQBRACKET + | T_LEFTBRACKET ICONST T_RIGHTBRACKET + ) + | + ; + +any_name : colId attrs? + ; + +qual_all_Op : all_Op + | OPERATOR T_LEFTBRACKET any_operator T_RIGHTBRACKET + ; + +opt_nulls_order : NULLS_FIRST + | NULLS_LAST + | + ; + +opt_asc_desc : ASC + | DESC + | + ; + +values_clause : valuesClauseSingle + | valuesClauseMul; + +valuesClauseSingle : VALUES ctext_row; + +valuesClauseMul : VALUES (ctext_row T_COMMA)* ctext_row; + + + +opt_all : ALL + | DISTINCT + | + ; + +into_clause : INTO optTempTableName + | + ; + +optTempTableName : ( TEMPORARY + | TEMP + | LOCAL TEMPORARY + | LOCAL TEMP + | GLOBAL TEMPORARY + | GLOBAL TEMP + | UNLOGGED ) opt_table qualified_name + | TABLE? qualified_name + ; + +opt_table : TABLE + | + ; + +window_clause : WINDOW window_definition_list + | + ; + +window_definition_list : (window_definition T_COMMA)* window_definition + ; + +window_definition : colId AS window_specification; + +window_specification : T_LEFTBRACKET opt_existing_window_name opt_partition_clause opt_sort_clause opt_frame_clause T_RIGHTBRACKET; + +sconst : SCONST; + +unreserved_keyword : ABORT_P + | ABSOLUTE_P + | ACCESS + | ACCOUNT + | ACTION + | ADD_P + | ADMIN + | AFTER + | AGGREGATE + | ALSO + | ALTER + | ALWAYS + | APP + | ASSERTION + | ASSIGNMENT + | AT + | ATTRIBUTE + | AUTOEXTEND + | AUTOMAPPED + | BACKWARD + | BARRIER + | BEFORE + | BEGIN_NON_ANOYBLOCK + | BEGIN_P + | BLOB_P + | BY + | CACHE + | CALL + | CALLED + | CASCADE + | CASCADED + | CATALOG_P + | CHAIN + | CHARACTERISTICS + | CHECKPOINT + | CLASS + | CLEAN + | CLOB + | CLOSE + | CLUSTER + | COMMENT + | COMMENTS + | COMMIT + | COMMITTED + | COMPATIBLE_ILLEGAL_CHARS + | COMPRESS + | CONFIGURATION + | CONNECTION + | CONSTRAINTS + | CONTENT_P + | CONTINUE_P + | CONVERSION_P + | COORDINATOR + | COPY + | COST + | CSV + | CUBE + | CURRENT_P + | CURSOR + | CYCLE + | DATA_P + | DATABASE + | DATAFILE + | DAY_P + | DATE_FORMAT_P + | DBCOMPATIBILITY_P + | DEALLOCATE + | DECLARE + | DEFAULTS + | DEFERRED + | DEFINER + | DELETE_P + | DELIMITER + | DELIMITERS + | DELTA + | DETERMINISTIC + | DICTIONARY + | DIRECT + | DISABLE_P + | DISCARD + | DISTRIBUTE + | DISTRIBUTION + | DOCUMENT_P + | DOMAIN_P + | DOUBLE_P + | DROP + | EACH + | ENABLE_P + | ENCODING + | ENCRYPTED + | ENFORCED + | ENUM_P + | EOL + | ESCAPE + | ESCAPING + | EXCHANGE + | EXCLUDE + | EXCLUDING + | EXCLUSIVE + | EXECUTE + | EXPLAIN + | EXTENSION + | EXTERNAL + | FAMILY + | FILEHEADER_P + | FIRST_P + | FIXED_P + | FOLLOWING + | FORCE + | FORMATTER + | FORWARD + | FUNCTIONS + | GLOBAL + | GRANTED + | HANDLER + | HEADER_P + | HOLD + | HOUR_P + | IDENTIFIED + | IDENTITY_P + | IF_P + | IGNORE_EXTRA_DATA + | IMMEDIATE + | IMMUTABLE + | IMPLICIT_P + | INCLUDING + | INCREMENT + | INDEX + | INDEXES + | INHERIT + | INHERITS + | INITIAL_P + | INITRANS + | INLINE_P + | INPUT_P + | INSENSITIVE + | INSERT + | INSTEAD + | INVOKER + | ISOLATION + | KEY + | LABEL + | LANGUAGE + | LARGE_P + | LAST_P + | LC_COLLATE_P + | LC_CTYPE_P + | LEAKPROOF + | LEVEL + | LISTEN + | LOAD + | LOCAL + | LOCATION + | LOCK_P + | LOG_P + | LOGGING + | LOOP + | MAPPING + | MATCH + | MAXEXTENTS + | MAXSIZE + | MAXTRANS + | MERGE + | MINEXTENTS + | MINUTE_P + | MINVALUE + | MODE + | MONTH_P + | MOVE + | MOVEMENT + | NAME_P + | NAMES + | NEXT + | NO + | NOCOMPRESS + | NOCYCLE + | NODE + | NOLOGGING + | NOMAXVALUE + | NOMINVALUE + | NOTHING + | NOTIFY + | NOWAIT + | NULLS_P + | NUMSTR + | OBJECT_P + | OF + | OFF + | OIDS + | OPERATOR + | OPTIMIZATION + | OPTION + | OPTIONS + | OWNED + | OWNER + | PARSER + | PARTIAL + | PARTITION + | PARTITIONS + | PASSING + | PASSWORD + | PCTFREE + | PER_P + | PERCENT + | PERM + | PLANS + | POOL + | PRECEDING + | PREFERRED + | PREFIX + | PREPARE + | PREPARED + | PRESERVE + | PRIOR + | PRIVILEGE + | PRIVILEGES + | PROCEDURAL + | PROFILE + | QUERY + | QUOTE + | RANGE + | RAW T_LEFTBRACKET ICONST T_RIGHTBRACKET + | RAW + | READ + | REASSIGN + | REBUILD + | RECHECK + | RECURSIVE + | REF + | REINDEX + | RELATIVE_P + | RELEASE + | RELOPTIONS + | REMOTE_P + | RENAME + | REPEATABLE + | REPLACE + | REPLICA + | RESET + | RESIZE + | RESOURCE + | RESTART + | RESTRICT + | RETURNS + | REUSE + | REVOKE + | ROLE + | ROLLBACK + | ROLLUP + | ROWS + | RULE + | SAVEPOINT + | SCHEMA + | SCROLL + | SEARCH + | SECOND_P + | SECURITY + | SEQUENCE + | SEQUENCES + | SERIALIZABLE + | SERVER + | SESSION + | SET + | SETS + | SHARE + | SHOW + | SIMPLE + | SIZE + | SMALLDATETIME_FORMAT_P + | SNAPSHOT + | SPACE + | STABLE + | STANDALONE_P + | START + | STATEMENT + | STATISTICS + | STDIN + | STDOUT + | STORAGE + | STORE_P + | STRICT_P + | STRIP_P + | SYS_REFCURSOR + | SYSID + | SYSTEM_P + | TABLES + | TABLESPACE + | TEMP + | TEMPLATE + | TEMPORARY + | TEXT_P + | THAN + | TIME_FORMAT_P + | TIMESTAMP_FORMAT_P + | TRANSACTION + | TRIGGER + | TRUNCATE + | TRUSTED + | TYPE_P + | TYPES_P + | UNBOUNDED + | UNCOMMITTED + | UNENCRYPTED + | UNKNOWN + | UNLIMITED + | UNLISTEN + | UNLOCK + | UNLOGGED + | UNTIL + | UNUSABLE + | UPDATE + | VACUUM + | VALID + | VALIDATE + | VALIDATION + | VALIDATOR + | VALUE_P + | VARYING + | VERSION_P + | VIEW + | VOLATILE + | WHITESPACE_P + | WITHOUT + | WORK + | WORKLOAD + | WRAPPER + | WRITE + | XML_P + | YEAR_P + | YES_P + | ZONE + ; + +col_name_keyword: BETWEEN + | BIGINT + | BINARY_DOUBLE + | BINARY_INTEGER + | BIT + | BOOLEAN_P + | CHAR_P + | CHARACTER + | COALESCE + | DATE_P + | DEC + | DECIMAL_P + | DECODE + | EXISTS + | EXTRACT + | FLOAT_P + | GREATEST + | GROUPING_P + | INOUT + | INT_P + | INTEGER + | INTERVAL + | LEAST + | NATIONAL + | NCHAR + | NONE + | NULLIF + | NUMBER_P + | NUMERIC + | NVARCHAR2 + | NVL + | OUT_P + | OVERLAY + | POSITION + | PRECISION + | REAL + | ROW + | SETOF + | SMALLDATETIME + | SMALLINT + | SUBSTRING + | TIME + | TIMESTAMP + | TINYINT + | TREAT + | TRIM + | VALUES + | VARCHAR + | VARCHAR2 + | XMLATTRIBUTES + | XMLCONCAT + | XMLELEMENT + | XMLEXISTS + | XMLFOREST + | XMLPARSE + | XMLPI + | XMLROOT + | XMLSERIALIZE + ; + +any_stmt : colLabel+ ; +createFunction : CREATE (OR REPLACE)+ function_type function_name function_aguments? func_returns? function_language? function_properties_list? func_as_is? function_body? function_properties_list? function_end?; +func_as_is : (AS|IS); +function_type : (FUNCTION|PROCEDURE|package_type); +package_type : PACKAGE BODY?; +function_name : (schema_name) (funct_name); +function_aguments : T_LEFTBRACKET (function_agrs_list)* T_RIGHTBRACKET; +function_agrs_list :one_funtion_argument (T_COMMA one_funtion_argument)* ; +one_funtion_argument : (func_arg_name)? (func_arg_mode)? typename (func_default_expr)?; +func_arg_name : colId; +func_arg_mode : (IN_P|OUT_P|INOUT_P); +func_default_expr : (DEFAULT | T_COLON_EQUALS | T_EQUALS) a_expr; +func_returns : RETURNS ( TABLE returns_table_expr_list | typename (DETERMINISTIC)?); +returns_table_expr_list : returns_table_expr_item (T_COMMA returns_table_expr_item)*; +returns_table_expr_item : colId typename; +function_language : LANGUAGE IDENT (WINDOW)?; +function_body : LESS_LESS (colId|':='|'+'|';')* GREATER_GREATER ; +function_properties_list : function_properties_item (T_COMMA function_properties_item)*; +function_end : END_P SEMICOLON T_DIVIDE; + +function_properties_item : (IMMUTABLE | STABLE | VOLATILE)? + |((NOT)? LEAKPROOF)? + |(CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT_P)? + |((EXTERNAL)? SECURITY (INVOKER|DEFINER))? + |(COST IDENT)? + |(ROWS IDENT)? + |(SET colId (TO | T_EQUALS)? ctext_expr | FROM CURRENT_P)? + |(AUTHID (DEFINER|CURRENT_USER))? + | (FENCED); +/* pl_block : decl_sect BEGIN proc_sect exception_sect END opt_label; + decl_sect : opt_block_label| opt_block_label decl_start | opt_block_label decl_start decl_stmts; + opt_block_label : + | LESS_LESS any_identifier GREATER_GREATER; + any_identifier : pl_unreserved_keyword; + + decl_start : K_DECLARE; + + decl_stmts : decl_stmts decl_stmt | decl_stmt; + decl_stmt :decl_statement + |K_DECLARE + |LESS_LESS any_identifier GREATER_GREATER + ; +decl_statement : decl_varname decl_const decl_datatype decl_collate decl_notnull decl_defval + |decl_varname K_ALIAS K_FOR decl_aliasitem T_SEMICOLON + |decl_varname opt_scrollable K_CURSOR decl_cursor_args decl_is_for decl_cursor_query + ; +decl_varname :colId + ; +decl_const : K_CONSTANT + | + ; +decl_datatype : typename + ; + + pl_unreserved_keyword : K_ABSOLUTE + | K_ALIAS + | K_ARRAY + | K_ASSERT + | K_BACKWARD + | K_CLOSE + | K_COLLATE + | K_COLUMN + | K_COLUMN_NAME + | K_CONSTANT + | K_CONSTRAINT + | K_CONSTRAINT_NAME + | K_CONTINUE + | K_CURRENT + | K_CURSOR + | K_DATATYPE + | K_DEBUG + | K_DEFAULT + | K_DETAIL + | K_DIAGNOSTICS + | K_DUMP + | K_ELSIF + | K_ERRCODE + | K_ERROR + | K_EXCEPTION + | K_EXIT + | K_FETCH + | K_FIRST + | K_FORWARD + | K_GET + | K_HINT + | K_IMPORT + | K_INFO + | K_INSERT + | K_IS + | K_LAST + | K_LOG + | K_MESSAGE + | K_MESSAGE_TEXT + | K_MOVE + | K_NEXT + | K_NO + | K_NOTICE + | K_OPEN + | K_OPTION + | K_PERFORM + | K_PG_CONTEXT + | K_PG_DATATYPE_NAME + | K_PG_EXCEPTION_CONTEXT + | K_PG_EXCEPTION_DETAIL + | K_PG_EXCEPTION_HINT + | K_PRINT_STRICT_PARAMS + | K_PRIOR + | K_QUERY + | K_RAISE + | K_RELATIVE + | K_RESULT_OID + | K_RETURN + | K_RETURNED_SQLSTATE + | K_REVERSE + | K_ROW_COUNT + | K_ROWTYPE + | K_SCHEMA + | K_SCHEMA_NAME + | K_SCROLL + | K_SLICE + | K_SQLSTATE + | K_STACKED + | K_TABLE + | K_TABLE_NAME + | K_TYPE + | K_USE_COLUMN + | K_USE_VARIABLE + | K_VARIABLE_CONFLICT + | K_WARNING + ;*/ + +/* AS function_body function_properties_list + ; +function_aguments : T_LEFTBRACKET (function_agrs_list)* T_RIGHTBRACKET; +function_agrs_list :one_funtion_argument (T_COMMA one_funtion_argument)* ; +one_funtion_argument : func_arg_name (func_arg_mode)? typename (func_default_expr)?; + + + +*/ \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/runtimehandler/RunTimeExceptionCheckErrorStrategy.java b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/runtimehandler/RunTimeExceptionCheckErrorStrategy.java new file mode 100644 index 0000000000000000000000000000000000000000..ee557ea574f9cc911fd8877cb24c7dffaddb65ce --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/runtimehandler/RunTimeExceptionCheckErrorStrategy.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.parser.runtimehandler; + +import org.antlr.v4.runtime.DefaultErrorStrategy; +import org.antlr.v4.runtime.Parser; +import org.antlr.v4.runtime.RecognitionException; + +/** + * Title: class Description: The Class RunTimeExceptionCheckErrorStrategy. + * + * @since 3.0.0 + */ +public class RunTimeExceptionCheckErrorStrategy extends DefaultErrorStrategy { + @Override + public void sync(Parser recognizer) throws RecognitionException { + if (Thread.interrupted()) { + throw new RunTimeParserException("formatting interrupted"); + } + super.sync(recognizer); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/runtimehandler/RunTimeParserException.java b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/runtimehandler/RunTimeParserException.java new file mode 100644 index 0000000000000000000000000000000000000000..3e4fac2006e1fd28385e2ddfdc913556e3b33788 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/runtimehandler/RunTimeParserException.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.parser.runtimehandler; + +/** + * Title: class Description: The Class RunTimeParserException. + * + * @since 3.0.0 + */ +public class RunTimeParserException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + /** + * Instantiates a new run time parser exception. + * + * @param string the string + */ + public RunTimeParserException(String string) { + super(string); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/runtimehandler/RuntimeErrorStrategyIf.java b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/runtimehandler/RuntimeErrorStrategyIf.java new file mode 100644 index 0000000000000000000000000000000000000000..fbe83e7084a8bcf40a397869496bb9be7bf4c8fd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/runtimehandler/RuntimeErrorStrategyIf.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.parser.runtimehandler; + +import org.antlr.v4.runtime.ANTLRErrorStrategy; + +/** + * Title: interface Description: The Interface RuntimeErrorStrategyIf. + * + * @since 3.0.0 + */ +public interface RuntimeErrorStrategyIf { + + /** + * Gets the runtime errorhandler. + * + * @return the runtime errorhandler + */ + ANTLRErrorStrategy getRuntimeErrorhandler(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/runtimehandler/RuntimeErrorStrategyImpl.java b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/runtimehandler/RuntimeErrorStrategyImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..06e0ff9d9e358cbf59d8efb973766a91fe86ed2d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/runtimehandler/RuntimeErrorStrategyImpl.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.parser.runtimehandler; + +import org.antlr.v4.runtime.ANTLRErrorStrategy; + +/** + * Title: class Description: The Class RuntimeErrorStrategyImpl. + * + * @since 3.0.0 + */ +public class RuntimeErrorStrategyImpl implements RuntimeErrorStrategyIf { + + /** + * Gets the runtime errorhandler. + * + * @return the runtime errorhandler + */ + public ANTLRErrorStrategy getRuntimeErrorhandler() { + return new RunTimeExceptionCheckErrorStrategy(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/runtimehandler/RuntimeErrorStrategyManager.java b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/runtimehandler/RuntimeErrorStrategyManager.java new file mode 100644 index 0000000000000000000000000000000000000000..84615627a35ce5300f2727f249e5fa2ee0c7805d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.parser/src/org/opengauss/mppdbide/parser/runtimehandler/RuntimeErrorStrategyManager.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.parser.runtimehandler; + +import org.antlr.v4.runtime.ANTLRErrorStrategy; + +/** + * Title: class Description: The Class RuntimeErrorStrategyManager. + * + * @since 3.0.0 + */ +public abstract class RuntimeErrorStrategyManager { + + /** + * Gets the runtime errorhandler. + * + * @return the runtime errorhandler + */ + public static ANTLRErrorStrategy getRuntimeErrorhandler() { + return new RuntimeErrorStrategyImpl().getRuntimeErrorhandler(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/.classpath b/code/datastudio/src/org.opengauss.mppdbide.presentation/.classpath new file mode 100644 index 0000000000000000000000000000000000000000..e31912d3b25059455c950ac11dd9c8897d859a70 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/.classpath @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/.gitignore b/code/datastudio/src/org.opengauss.mppdbide.presentation/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ddc25c7fcd00a3a38f67eabde7efb88c26a8c3a8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/.gitignore @@ -0,0 +1,3 @@ +/bin/ +/.settings/ +/target/ diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/.project b/code/datastudio/src/org.opengauss.mppdbide.presentation/.project new file mode 100644 index 0000000000000000000000000000000000000000..bf55dd17c00f5e73afcbfea7c8baa54b4a08511a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/.project @@ -0,0 +1,34 @@ + + + org.opengauss.mppdbide.presentation + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/META-INF/MANIFEST.MF b/code/datastudio/src/org.opengauss.mppdbide.presentation/META-INF/MANIFEST.MF new file mode 100644 index 0000000000000000000000000000000000000000..54a764861fc0c86e73c0b8606e67e21f9a1c3c1a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/META-INF/MANIFEST.MF @@ -0,0 +1,42 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Presentation +Bundle-SymbolicName: org.opengauss.mppdbide.presentation +Bundle-Version: 1.0.0.qualifier +Bundle-Vendor: HUAWEI +Bundle-RequiredExecutionEnvironment: JavaSE-11 +Import-Package: ca.odell.glazedlists, + ca.odell.glazedlists.matchers, + org.opengauss.mppdbide.adapter.gauss, + org.opengauss.mppdbide.bl.serverdatacache, + org.opengauss.mppdbide.utils, + org.opengauss.mppdbide.utils.exceptions, + org.eclipse.e4.core.services.events, + org.eclipse.swt.graphics, + org.postgresql.core +Export-Package: org.opengauss.mppdbide.presentation, + org.opengauss.mppdbide.presentation.autorefresh, + org.opengauss.mppdbide.presentation.contentassistprocesser, + org.opengauss.mppdbide.presentation.edittabledata, + org.opengauss.mppdbide.presentation.erd, + org.opengauss.mppdbide.presentation.exportdata, + org.opengauss.mppdbide.presentation.exportimportdsconnectionprofiles, + org.opengauss.mppdbide.presentation.grid, + org.opengauss.mppdbide.presentation.grid.batchdrop, + org.opengauss.mppdbide.presentation.grid.resultset, + org.opengauss.mppdbide.presentation.objectbrowser, + org.opengauss.mppdbide.presentation.objectproperties, + org.opengauss.mppdbide.presentation.objectproperties.handler, + org.opengauss.mppdbide.presentation.resultset, + org.opengauss.mppdbide.presentation.resultsetif, + org.opengauss.mppdbide.presentation.search, + org.opengauss.mppdbide.presentation.synonym.olap, + org.opengauss.mppdbide.presentation.userrole, + org.opengauss.mppdbide.presentation.util, + org.opengauss.mppdbide.presentation.view +Require-Bundle: org.opengauss.mppdbide.bl, + org.opengauss.mppdbide.util, + org.apache.commons.lang3;bundle-version="3.1.0", + Common-collection;bundle-version="1.0.0", + org.opengauss.mppdbide.debuger;bundle-version="1.0.0" +Bundle-ClassPath: . diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/build.properties b/code/datastudio/src/org.opengauss.mppdbide.presentation/build.properties new file mode 100644 index 0000000000000000000000000000000000000000..34d2e4d2dad529ceaeb953bfcdb63c51d69ffed2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/build.properties @@ -0,0 +1,4 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + . diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/compile_plsqlide.utils.xml b/code/datastudio/src/org.opengauss.mppdbide.presentation/compile_plsqlide.utils.xml new file mode 100644 index 0000000000000000000000000000000000000000..2e6f6eed564467e7523d1bec4060d852723e7832 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/compile_plsqlide.utils.xml @@ -0,0 +1,84 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/pom.xml b/code/datastudio/src/org.opengauss.mppdbide.presentation/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..7995bf340a4b1934af2ccbb29a683e7c91ce3b83 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/pom.xml @@ -0,0 +1,76 @@ + + + 4.0.0 + + org.opengauss.plide.build + GAUSS_MPP_DB_IDE + 1.0.0-SNAPSHOT + + + org.opengauss.mppdbide.presentation + eclipse-plugin + + + + junit + junit + 4.11 + test + + + com.mockrunner + mockrunner-jdbc + 1.1.2 + test + + + xerces + xercesImpl + + + + + +${project.basedir}/src-test + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12.4 + + + test + test + + ${presentation.skip} + + ${runSuite} + + + + test + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.5.1 + + + compiletests + test-compile + + testCompile + + + + + + + + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/BaseConnectionHelper.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/BaseConnectionHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..56ccecca18d046d6091f8e6025887ebc7d36c1be --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/BaseConnectionHelper.java @@ -0,0 +1,409 @@ +package org.opengauss.mppdbide.mock.presentation; + +import java.sql.Array; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Map; +import java.util.Properties; +import java.util.TimerTask; +import java.util.concurrent.Executor; + +import org.postgresql.PGNotification; +import org.postgresql.copy.CopyManager; +import org.postgresql.core.BaseConnection; +import org.postgresql.core.CachedQuery; +import org.postgresql.core.Encoding; +import org.postgresql.core.QueryExecutor; +import org.postgresql.core.ReplicationProtocol; +import org.postgresql.core.TransactionState; +import org.postgresql.core.TypeInfo; +import org.postgresql.core.Version; +import org.postgresql.log.Log; +import org.postgresql.fastpath.Fastpath; +import org.postgresql.jdbc.AutoSave; +import org.postgresql.jdbc.FieldMetadata; +import org.postgresql.jdbc.FieldMetadata.Key; +import org.postgresql.jdbc.PreferQueryMode; +import org.postgresql.largeobject.LargeObjectManager; +import org.postgresql.replication.PGReplicationConnection; +import org.postgresql.util.HostSpec; +import org.postgresql.util.LruCache; +import org.postgresql.xml.PGXmlFactoryFactory; + +import com.mockrunner.mock.jdbc.MockConnection; + +public class BaseConnectionHelper extends MockConnection implements BaseConnection +{ + + QueryExecutor queryExecutor; + boolean returnBaseStmt = false; + String encoding = "UTF8"; + + public void setReturnBaseStmt(boolean returnBaseStmt) + { + this.returnBaseStmt = returnBaseStmt; + } + + public void setEncoding(String encoding) + { + this.encoding = encoding; + } + + public BaseConnectionHelper(String url, Properties info, HostSpec[] hostSpec, String database, String user, boolean isSQLExceptionReq) throws SQLException + { + queryExecutor = new Connfactory(isSQLExceptionReq); + } + + @Override + public void addDataType(String arg0, String arg1) + { + + + } + + @Override + public void addDataType(String arg0, Class arg1) throws SQLException + { + + + } + + @Override + public CopyManager getCopyAPI() throws SQLException + { + + return null; + } + + @Override + public Fastpath getFastpathAPI() throws SQLException + { + + return null; + } + + @Override + public LargeObjectManager getLargeObjectAPI() throws SQLException + { + + return null; + } + + @Override + public PGNotification[] getNotifications() throws SQLException + { + + return null; + } + + @Override + public int getPrepareThreshold() + { + + return 0; + } + + @Override + public void setPrepareThreshold(int arg0) + { + + + } + + + @Override + public void abort(Executor executor) throws SQLException + { + + + } + + @Override + public void setNetworkTimeout(Executor executor, int milliseconds) + throws SQLException + { + + + } + + @Override + public int getNetworkTimeout() throws SQLException + { + + return 0; + } + + @Override + public boolean binaryTransferSend(int arg0) + { + + return false; + } + + @Override + public void cancelQuery() throws SQLException + { + + + } + + @Override + public byte[] encodeString(String arg0) throws SQLException + { + + return null; + } + + @Override + public String escapeString(String arg0) throws SQLException + { + + return null; + } + + @Override + public ResultSet execSQLQuery(String arg0) throws SQLException + { + + return null; + } + + @Override + public ResultSet execSQLQuery(String arg0, int arg1, int arg2) + throws SQLException + { + + return null; + } + + @Override + public void execSQLUpdate(String arg0) throws SQLException + { + + + } + + @Override + public Encoding getEncoding() throws SQLException + { + + return new EncodingHelper(encoding); + } + + + @Override + public Object getObject(String arg0, String arg1, byte[] arg2) + throws SQLException + { + + return null; + } + + @Override + public QueryExecutor getQueryExecutor() + { + + return queryExecutor; + } + + @Override + public boolean getStandardConformingStrings() + { + + return false; + } + + @Override + public boolean getStringVarcharFlag() + { + + return false; + } + + + @Override + public TransactionState getTransactionState() + { + + return TransactionState.IDLE; + } + + @Override + public TypeInfo getTypeInfo() + { + + return null; + } + + + +private boolean throwSQLException; + + public void setThrowSQLException(boolean throwSQLException) + { + this.throwSQLException = throwSQLException; + } + + @Override + public Statement createStatement() throws SQLException + { + + if(returnBaseStmt) + { + returnBaseStmt = false; + + BaseStatementHelper bs = new BaseStatementHelper(); + bs.setThrowSQLException(throwSQLException); + + throwSQLException = false; + + return bs; + } + else + { + return super.createStatement(); + } + + } + + + @Override + public boolean isColumnSanitiserDisabled() + { + + return false; + } + + @Override + public void addTimerTask(TimerTask arg0, long arg1) { + // TODO Auto-generated method stub + + } + + @Override + public CachedQuery createQuery(String arg0, boolean arg1, boolean arg2, String... arg3) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public LruCache getFieldMetadataCache() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Log getLogger() { + // TODO Auto-generated method stub + return null; + } + + @Override + public ReplicationProtocol getReplicationProtocol() { + // TODO Auto-generated method stub + return null; + } + + @Override + public org.postgresql.jdbc.TimestampUtils getTimestampUtils() { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean haveMinimumServerVersion(int arg0) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean haveMinimumServerVersion(Version arg0) { + // TODO Auto-generated method stub + return false; + } + + @Override + public void purgeTimerTasks() { + // TODO Auto-generated method stub + + } + + @Override + public void setFlushCacheOnDeallocate(boolean arg0) { + // TODO Auto-generated method stub + + } + + @Override + public Array createArrayOf(String arg0, Object arg1) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public String escapeIdentifier(String arg0) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public String escapeLiteral(String arg0) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public AutoSave getAutosave() { + // TODO Auto-generated method stub + return null; + } + + @Override + public int getDefaultFetchSize() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public PGNotification[] getNotifications(int arg0) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public PreferQueryMode getPreferQueryMode() { + // TODO Auto-generated method stub + return null; + } + + @Override + public PGReplicationConnection getReplicationAPI() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setAutosave(AutoSave arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void setDefaultFetchSize(int arg0) throws SQLException { + // TODO Auto-generated method stub + + } + + @Override + public PGXmlFactoryFactory getXmlFactoryFactory() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getSocketAddress() { + return ""; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/BaseStatementHelper.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/BaseStatementHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..15a0e28400e31f0307639b4697eb9ffea1efbb43 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/BaseStatementHelper.java @@ -0,0 +1,422 @@ +package org.opengauss.mppdbide.mock.presentation; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.util.List; + +import org.postgresql.core.BaseStatement; +import org.postgresql.core.CachedQuery; +import org.postgresql.core.Field; +import org.postgresql.core.NoticeListener; +import org.postgresql.core.Query; +import org.postgresql.core.ResultCursor; + +public class BaseStatementHelper implements BaseStatement +{ + + @Override + public long getLastOID() throws SQLException + { + + return 0; + } + + @Override + public void setUseServerPrepare(boolean flag) throws SQLException + { + + + } + + @Override + public boolean isUseServerPrepare() + { + + return false; + } + + @Override + public void setPrepareThreshold(int threshold) throws SQLException + { + + + } + + @Override + public int getPrepareThreshold() + { + + return 0; + } + + @Override + public ResultSet executeQuery(String sql) throws SQLException + { + + return null; + } + + @Override + public int executeUpdate(String sql) throws SQLException + { + + return 0; + } + + @Override + public void close() throws SQLException + { + + + } + + @Override + public int getMaxFieldSize() throws SQLException + { + + return 0; + } + + @Override + public void setMaxFieldSize(int max) throws SQLException + { + + + } + + @Override + public int getMaxRows() throws SQLException + { + + return 0; + } + + @Override + public void setMaxRows(int max) throws SQLException + { + + + } + + @Override + public void setEscapeProcessing(boolean enable) throws SQLException + { + + + } + + @Override + public int getQueryTimeout() throws SQLException + { + + return 0; + } + + @Override + public void setQueryTimeout(int seconds) throws SQLException + { + + + } + + @Override + public void cancel() throws SQLException + { + + + } + + @Override + public SQLWarning getWarnings() throws SQLException + { + + return null; + } + + @Override + public void clearWarnings() throws SQLException + { + + + } + + @Override + public void setCursorName(String name) throws SQLException + { + + + } + + @Override + public boolean execute(String sql) throws SQLException + { + + return false; + } + + @Override + public ResultSet getResultSet() throws SQLException + { + + return null; + } + + @Override + public int getUpdateCount() throws SQLException + { + + return 0; + } + + @Override + public boolean getMoreResults() throws SQLException + { + + return false; + } + + @Override + public void setFetchDirection(int direction) throws SQLException + { + + + } + + @Override + public int getFetchDirection() throws SQLException + { + + return 0; + } + + @Override + public void setFetchSize(int rows) throws SQLException + { + + + } + + @Override + public int getFetchSize() throws SQLException + { + + return 0; + } + + @Override + public int getResultSetConcurrency() throws SQLException + { + + return 0; + } + + @Override + public int getResultSetType() throws SQLException + { + + return 0; + } + + @Override + public void addBatch(String sql) throws SQLException + { + + + } + + @Override + public void clearBatch() throws SQLException + { + + + } + + @Override + public int[] executeBatch() throws SQLException + { + + return null; + } + + @Override + public Connection getConnection() throws SQLException + { + + return null; + } + + @Override + public boolean getMoreResults(int current) throws SQLException + { + + return false; + } + + @Override + public ResultSet getGeneratedKeys() throws SQLException + { + + return null; + } + + @Override + public int executeUpdate(String sql, int autoGeneratedKeys) + throws SQLException + { + + return 0; + } + + @Override + public int executeUpdate(String sql, int[] columnIndexes) + throws SQLException + { + + return 0; + } + + @Override + public int executeUpdate(String sql, String[] columnNames) + throws SQLException + { + + return 0; + } + + @Override + public boolean execute(String sql, int autoGeneratedKeys) + throws SQLException + { + + return false; + } + + @Override + public boolean execute(String sql, int[] columnIndexes) throws SQLException + { + + return false; + } + + @Override + public boolean execute(String sql, String[] columnNames) + throws SQLException + { + + return false; + } + + @Override + public int getResultSetHoldability() throws SQLException + { + + return 0; + } + + @Override + public boolean isClosed() throws SQLException + { + + return false; + } + + @Override + public void setPoolable(boolean poolable) throws SQLException + { + + + } + + @Override + public boolean isPoolable() throws SQLException + { + + return false; + } + + @Override + public void closeOnCompletion() throws SQLException + { + + + } + + @Override + public boolean isCloseOnCompletion() throws SQLException + { + + return false; + } + + @Override + public T unwrap(Class iface) throws SQLException + { + + return null; + } + + @Override + public boolean isWrapperFor(Class iface) throws SQLException + { + + return false; + } + + @Override + public ResultSet createDriverResultSet(Field[] fields, List tuples) + throws SQLException + { + + return null; + } + + @Override + public ResultSet createResultSet(Query originalQuery, Field[] fields, + List tuples, ResultCursor cursor) throws SQLException + { + + return null; + } + + @Override + public boolean executeWithFlags(String p_sql, int flags) + throws SQLException + { + + return false; + } + + @Override + public boolean executeWithFlags(int flags) throws SQLException + { + + return false; + } + + private boolean throwSQLException; + + public void setThrowSQLException(boolean throwSQLException) + { + this.throwSQLException = throwSQLException; + } + + @Override + public void addNoticeListener(NoticeListener listener) throws SQLException + { + if(throwSQLException) + { + this.throwSQLException = false; + throw new SQLException(); + } + + } + + @Override + public boolean executeWithFlags(CachedQuery arg0, int arg1) throws SQLException { + // TODO Auto-generated method stub + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/CommonLLTUtils.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/CommonLLTUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..ab5abce2c1710755dd4ccc7a858847e69548804c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/CommonLLTUtils.java @@ -0,0 +1,4445 @@ +package org.opengauss.mppdbide.mock.presentation; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.AclEntry; +import java.nio.file.attribute.AclEntryPermission; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.PosixFilePermission; +import java.sql.Connection; +import java.sql.Driver; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Properties; +import java.util.Set; + +import org.opengauss.mppdbide.adapter.AbstractConnectionDriver; +import org.opengauss.mppdbide.adapter.IConnectionDriver; +import org.opengauss.mppdbide.adapter.driver.DBMSDriverManager; +import org.opengauss.mppdbide.adapter.driver.Gauss200V1R7Driver; +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.keywordssyntax.Keywords; +import org.opengauss.mppdbide.adapter.keywordssyntax.OLAPKeywords; +import org.opengauss.mppdbide.adapter.keywordssyntax.SQLSyntax; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionManager; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ObjectParameter; +import org.opengauss.mppdbide.bl.serverdatacache.ObjectParameter.PARAMETERTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.SynonymMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.SynonymUtil; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.files.DSFileAttributes; +import org.opengauss.mppdbide.utils.files.FilePermissionFactory; +import org.opengauss.mppdbide.utils.files.ISetFilePermission; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; +import com.mockrunner.mock.jdbc.MockResultSet; + +public class CommonLLTUtils +{ + private static final String OS_NAME = "os.name"; + private static final String WINDOWS = "Windows"; + private static final String LINUX = "Linux"; + private static ResultSet rs; + + public static final Timestamp TIMESTAMP = new Timestamp( + System.currentTimeMillis()); + + public enum EXCEPTIONENUM + { + YES, NO, EXCEPTION + } + public static final String FETCH_ALL_NAMESPACE_LOAD_PRIV = "SELECT oid, nspname from pg_namespace where has_schema_privilege(nspname, 'USAGE') ORDER BY nspname;"; + public static final String FETCH_ALL_NAMESPACE_LOAD_ALL = "SELECT oid, nspname from pg_namespace ORDER BY nspname;"; + public static final String GET_ALL_NAMESPACE = "SELECT oid, nspname from pg_namespace where ((oid >= 16384 or nspname LIKE 'public') and nspname NOT LIKE 'pg_%') and has_schema_privilege(nspname, 'USAGE') ORDER BY nspname;"; + public static final String GET_ALL_SYSTEM_NAMESPACE = "SELECT oid, nspname from pg_namespace where ((oid < 16384 and nspname NOT LIKE 'public') or nspname LIKE 'pg_%') and has_schema_privilege(nspname, 'USAGE') ORDER BY nspname;"; + public static final String GET_ALL_SHALLOWLOADTABLES = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, " + + " tbl.relpersistence relpersistence from pg_class tbl where tbl.relkind = 'r' " + + "and tbl.relnamespace not in (select oid from pg_namespace where nspname in ('cstore', 'pg_toast')) " + + "order by relname"; + public static final String Shallowload1 = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, tbl.relpersistence relpersistence,ts.spcname as reltablespace " + + "from pg_class tbl left join pg_tablespace ts on ts.oid = tbl.reltablespace " + + "where tbl.relkind = 'r' and tbl.relnamespace not in " + + "(select oid from pg_namespace where nspname in ('cstore', 'pg_toast'))" + + " order by relname"; + public static final String FUNCTIONONLY = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs,pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, pr.proisstrict isstrict, pr.proretset retset, pr.procost procost, pr.prorows setrows FROM pg_proc pr JOIN pg_type typ ON typ.oid=prorettype JOIN pg_namespace typns ON typns.oid=typ.typnamespace JOIN pg_language lng ON lng.oid=prolang WHERE lng.lanname='plpgsql' and UPPER(typ.typname) != 'TRIGGER' and pr.pronamespace= 1 ORDER BY objname"; + public static final String SHALLOWLOADQUERYDEFAULT = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs,pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, pr.proisstrict isstrict, pr.proretset retset, pr.procost procost, pr.prorows setrows FROM pg_proc pr JOIN pg_type typ ON typ.oid=prorettype JOIN pg_namespace typns ON typns.oid=typ.typnamespace JOIN pg_language lng ON lng.oid=prolang WHERE lng.lanname='plpgsql' and pr.pronamespace= 1 ORDER BY objname"; + public static final String TRIGGERONLY = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs,pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, pr.proisstrict isstrict, pr.proretset retset, pr.procost procost, pr.prorows setrows FROM pg_proc pr JOIN pg_type typ ON typ.oid=prorettype JOIN pg_namespace typns ON typns.oid=typ.typnamespace JOIN pg_language lng ON lng.oid=prolang WHERE lng.lanname='plpgsql' and UPPER(typ.typname) = 'TRIGGER' ORDER BY objname"; + public static final String TRIGGERONLY1 = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs,pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, pr.proisstrict isstrict, pr.proretset retset, pr.procost procost, pr.prorows setrows FROM pg_proc pr JOIN pg_type typ ON typ.oid=prorettype JOIN pg_namespace typns ON typns.oid=typ.typnamespace JOIN pg_language lng ON lng.oid=prolang WHERE lng.lanname='plpgsql' and UPPER(typ.typname) != 'TRIGGER' "; + public static final String TRIGGERONLY2 = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs,pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, pr.proisstrict isstrict, pr.proretset retset, pr.procost procost, pr.prorows setrows FROM pg_proc pr JOIN pg_type typ ON typ.oid=prorettype JOIN pg_namespace typns ON typns.oid=typ.typnamespace JOIN pg_language lng ON lng.oid=prolang WHERE lng.lanname='plpgsql' and UPPER(typ.typname) = 'TRIGGER' and pr.pronamespace= 1 ORDER BY objname"; + public static final String ALLCONSTRAIN = "SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, ci.relnamespace as namespaceid, ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, i.indisexclusion as isexclusion, i.indimmediate as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, i.indisready as isready, i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions, def.indexdef FROM pg_index i LEFT JOIN pg_class t on (t.oid = i.indrelid) LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) LEFT JOIN pg_namespace ns on (ci.relnamespace = ns.oid) LEFT JOIN pg_indexes def on (ci.relname = def.indexname and ns.nspname = def.schemaname) WHERE t.relkind = 'r' and t.oid = 1;"; + public static final String ALLCONSTRAIN_1 = "SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, ci.relnamespace as namespaceid, ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, i.indisexclusion as isexclusion, i.indimmediate as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, i.indisready as isready, i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions FROM pg_index i LEFT JOIN pg_class t on (t.oid = i.indrelid) LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) WHERE t.relkind = 'r' and t.oid = 1"; + public static final String ALLCONSTRAIN_2 = "SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, ci.relnamespace as namespaceid, ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, i.indisexclusion as isexclusion, i.indimmediate as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, i.indisready as isready, i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions FROM pg_index i LEFT JOIN pg_class t on (t.oid = i.indrelid) LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) WHERE t.relkind = 'r' and t.oid = 1"; + public static final String LAVEL2COLUNM = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, c.atttypid as datatypeoid, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr, typ.typnamespace as dtns from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.relkind = 'r') left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and t.relnamespace = 1 order by t.oid, c.attnum"; + public static final String SHALLOWLOADQUERY = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, " + + "pr.pronargs nargs,pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, " + + "pr.proisstrict isstrict, pr.proretset retset, pr.procost procost, pr.prorows setrows, lng.lanname lang FROM pg_proc pr " + + "JOIN pg_type typ ON typ.oid=prorettype JOIN pg_namespace typns ON typns.oid=typ.typnamespace JOIN pg_language lng ON lng.oid=prolang " + + "WHERE lng.lanname in ('plpgsql','sql','c') and has_function_privilege(pr.oid, 'EXECUTE') and pr.pronamespace= 1 ORDER BY objname"; + + public static final String CHECK_DEBUG = "SELECT count(1) from pg_proc where proname='pldbg_attach_session';"; + public static final String CHECK_EXPLAIN_PLAN = "EXPLAIN SELECT 1"; + /* + * public static final String GET_ALL_DATATYPE = + * "select typ.oid as oid, typ.typname as typname, typ.typnamespace as typnamespace, " + * + + * "typ.typlen as typlen, typ.typbyval as typbyval, typ.typtype as typtype, typ.typcategory as typcategory, " + * + + * "typ.typtypmod as typtypmod, typ.typnotnull as typnotnull, typ.typarray as typarray, des.description as desc " + * + + * "from pg_type typ left join pg_description des on (typ.oid = des.objoid) " + * ; public static final String GET_ALL_DATATYPE_DB = + * "select typ.oid as oid, typ.typname as typname, typ.typnamespace as typnamespace, " + * + + * "typ.typlen as typlen, typ.typbyval as typbyval, typ.typtype as typtype, typ.typcategory as typcategory, " + * + + * "typ.typtypmod as typtypmod, typ.typnotnull as typnotnull, typ.typarray as typarray, des.description as desc " + * + + * "from pg_type typ left join pg_description des on (typ.oid = des.objoid) " + * ; public static final String GET_ALL_DATATYPE_database = + * "select typ.oid as oid, typ.typname as typname, typ.typnamespace as typnamespace, " + * + + * "typ.typlen as typlen, typ.typbyval as typbyval, typ.typtype as typtype, typ.typcategory as typcategory, " + * + + * "typ.typtypmod as typtypmod, typ.typnotnull as typnotnull, typ.typarray as typarray, des.description as desc " + * + + * "from pg_type typ left join pg_description des on (typ.oid = des.objoid) " + * ; + */ + + public static final String GET_ALL_DATATYPE = "select typ.oid as oid, typ.typname as typname, typ.typnamespace as typnamespace, typ.typlen as typlen, pg_catalog.format_type(oid,typ.typtypmod) as displaycolumns , typ.typbyval as typbyval, typ.typtype as typtype, typ.typcategory as typcategory, typ.typtypmod as typtypmod, typ.typnotnull as typnotnull, typ.typarray as typarray, des.description as desc from pg_type typ left join pg_description des on (typ.oid = des.objoid) where typ.typnamespace in (select oid from pg_namespace where nspname in ('information_schema', 'pg_catalog')) order by typ.typname"; + public static final String GET_ALL_DATATYPE_DB = "select typ.oid as oid, typ.typname as typname, typ.typnamespace as typnamespace, typ.typlen as typlen, pg_catalog.format_type(oid,typ.typtypmod) as displaycolumns , typ.typbyval as typbyval, typ.typtype as typtype, typ.typcategory as typcategory, typ.typtypmod as typtypmod, typ.typnotnull as typnotnull, typ.typarray as typarray, des.description as desc from pg_type typ left join pg_description des on (typ.oid = des.objoid) where typ.typnamespace in (select oid from pg_namespace where nspname in ('information_schema', 'pg_catalog')) order by typ.typname"; + public static final String GET_ALL_DATATYPE_database = "select typ.oid as oid, typ.typname as typname, typ.typnamespace as typnamespace, typ.typlen as typlen, pg_catalog.format_type(oid,typ.typtypmod) as displaycolumns , typ.typbyval as typbyval, typ.typtype as typtype, typ.typcategory as typcategory, typ.typtypmod as typtypmod, typ.typnotnull as typnotnull, typ.typarray as typarray, des.description as desc from pg_type typ left join pg_description des on (typ.oid = des.objoid) where typ.typnamespace in (select oid from pg_namespace where nspname in ('information_schema', 'pg_catalog')) order by typ.typname"; + + public static final String FETCH_ALL_TABLEMETADATA = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace,tbl.reloptions as reloptions, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r'"; + // overloaded method of refreshTableMetada + + public static final String REFRESH_TABLE_METADATA = "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, " + + "ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, " + + "xctbl.nodeoids as nodes ,tbl.reloptions as reloptions " + + "from pg_class tbl left join (select d.description, d.objoid from pg_description d " + + "where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl " + + "on (tbl.oid = xctbl.pcrelid) " + + "left join pg_tablespace ts on ts.oid = tbl.reltablespace " + + "where tbl.relkind = 'r' and " + + "tbl.parttype in ('n','p') and tbl.oid = 1" + + " and oid in (" + + "select pcrelid from pgxc_class " + + "where has_nodegroup_privilege(pgroup, 'USAGE'))" + + ") select * from x " + + "where has_table_privilege(x.oid,'SELECT');"; + + // Partition table info for a particular table + public static final String REFRESH_TABLE_METADATA_PARTITION_TABLE = "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes, tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.parttype in ('p', 'v') and tbl.oid = 1 and tbl.relkind <> 'i'" + + " and oid in (" + + "select pcrelid from pgxc_class " + + "where has_nodegroup_privilege(pgroup, 'USAGE'))" + + ") select * from x " + + "where has_table_privilege(x.oid,'SELECT');"; + + public static final String GET_ALL_COLUMN_METADATA = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.relkind = 'r' and t.parttype ='n') left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and t.relnamespace = 1 order by t.oid, c.attnum;"; + + public static final String GET_ALL_COLUMN_METADATA_OVERLOADED_METHOD = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.relkind = 'r') left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and t.oid = 1 order by t.oid, c.attnum;"; + + public static final String GET_ALL_INDEXES = "SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, ci.relnamespace as namespaceid, " + + "ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, i.indisexclusion as isexclusion, " + + "i.indimmediate as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, i.indisready as isready, " + + "i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions FROM pg_index i LEFT JOIN pg_class t on (t.oid = i.indrelid) " + + "LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) WHERE t.relkind = 'r';"; + + public static final String GET_ALL_INDEXES_BYNAMESPACE = "SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, ci.relnamespace as namespaceid, ci.relam as accessmethodid, " + + "i.indisunique as isunique, i.indisprimary as isprimary, i.indisexclusion as isexclusion, i.indimmediate " + + "as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, i.indisready as isready, " + + "i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions, def.indexdef , def.tablespace " + + "FROM pg_index i LEFT JOIN pg_class t on (t.oid = i.indrelid) LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) LEFT JOIN pg_namespace ns on (ci.relnamespace = ns.oid)" + + " LEFT JOIN pg_indexes def on (ci.relname = def.indexname and ns.nspname = def.schemaname) WHERE t.relkind = 'r' and ci.relnamespace = 1" + + " and ci.parttype not in ('p','v') and ci.relkind not in ('I')" + ';'; + + public static final String GET_ALL_CONSTRAINTS = "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, c.conname as constraintname ,c.contype as constrainttype, c.condeferrable as deferrable, c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, pg_get_constraintdef(c.oid) as const_def , ts.spcname as tablespace FROM pg_constraint c LEFT JOIN pg_class t on (t.oid = c.conrelid) LEFT JOIN pg_index ind ON c.conindid = ind.indexrelid LEFT JOIN pg_class ci on (ind.indexrelid = ci.oid) LEFT JOIN pg_tablespace ts ON (ts.oid = ci.reltablespace) WHERE t.relkind = 'r' and t.oid = 1"; + + public static final String GET_ALL_CONSTRAINTS_BYNAMESPACE = "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, " + + + "c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, " + + "c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, " + + "c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, " + + "c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist " + + "pg_get_constraintdef(c.oid) as const_def " + + "FROM pg_constraint c LEFT JOIN pg_class t on (t.oid = c.conrelid) WHERE t.relkind = 'r' and c.connamespace=1" + + " and cl.parttype not in ('p','v')" + " and c.conrelid <> 0" + + ';'; + + public static final String GET_ALL_FUNCTION_QUERY = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype,pr.pronargs nargs,pr.proargtypes argtype, " + + "pr.proargnames argname,pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, pr.proisstrict isstrict, pr.proretset retset, pr.procost procost, pr.prorows setrows" + + " FROM pg_proc pr " + + " JOIN pg_type typ ON typ.oid=prorettype JOIN pg_namespace typns ON typns.oid=typ.typnamespace" + + " JOIN pg_language lng ON lng.oid=prolang LEFT OUTER JOIN pg_description des ON des.objoid=pr.oid " + + " WHERE lng.lanname in ('plpgsql','sql') and UPPER(typ.typname) != 'TRIGGER' AND pr.pronamespace=" + + 1 + " ORDER BY objname;"; + + public static final String GET_ALL_TRIGGER_QUERY = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype,pr.pronargs nargs,pr.proargtypes argtype, " + + "pr.proargnames argname,pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, pr.proisstrict isstrict, pr.proretset retset, pr.procost procost, pr.prorows setrows" + + " FROM pg_proc pr " + + " JOIN pg_type typ ON typ.oid=prorettype JOIN pg_namespace typns ON typns.oid=typ.typnamespace" + + " JOIN pg_language lng ON lng.oid=prolang LEFT OUTER JOIN pg_description des ON des.objoid=pr.oid " + + " WHERE lng.lanname='plpgsql' and UPPER(typ.typname) = 'TRIGGER' and pr.pronamespace=" + + 1 + " ORDER BY objname;"; + + public static final String TBL_SPC_META = "select oid, pg_tablespace_location(oid) as location, spcname,spcacl,spcoptions, spcmaxsize, relative from pg_tablespace where oid =" + + 10 + ";"; + + public static final String TBL_SPC_NAME = "SELECT tbs.spcname from pg_tablespace tbs, pg_database db where tbs.oid = db.dattablespace and db.datname = 'Gauss'"; + + public static final String GET_ALL_VIEWS = "select v.oid as viewid, v.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, " + + "c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, " + + "c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value " + + "from pg_class v " + + "left join pg_attribute c on (v.oid = c.attrelid and v.relkind = 'v') " + + "left join pg_attrdef d on (v.oid = d.adrelid and c.attnum = d.adnum) " + + "left join pg_type typ on (c.atttypid = typ.oid) " + + "where c.attisdropped = 'f' and c.attnum > 0 " + "and v.oid = " + + 1 + " order by v.oid, c.attnum"; + + public static final String Refresh_TABLEMETADATA = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype = 'n' and tbl.oid = 1;"; + + public static final String GET_ALL_FTABLES_IN_SCHEMA = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes,tbl.reloptions as reloptions, frgn.ftoptions, tbl.parttype as parttype, array_to_string(part.partkey,',') as partkey from pg_class tbl left join pg_partition part on(tbl.oid=part.parentid and part.parttype='r') left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'f' and has_table_privilege(frgn.ftrelid, 'SELECT') and tbl.relnamespace = 1;"; + + public static final String GET_COLUMN_INFO_FOREIGN_TABLES = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.relkind = 'f' and t.parttype ='n') left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and t.relnamespace = 1 order by t.oid, c.attnum;"; + + public static final String NOTIFICATION_QUERY_SUCCESSFULL = "SELECT logintime, client_conninfo from login_audit_messages_pid(true)"; + + public static final String NOTIFICATION_QUERY_FAILURE = "SELECT logintime, client_conninfo from login_audit_messages_pid(false)"; + + public static final String GET_ALL_PARTITION_TABLES = "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes, tbl.reloptions as reloptions , array_to_string(part.partkey,',') as partkey from pg_class tbl left join pg_partition part on(tbl.oid=part.parentid and part.parttype='r') left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on(tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.parttype in ('p', 'v') and tbl.relnamespace = 1 and tbl.relkind <> 'i'" + + " and oid in (" + + "select pcrelid from pgxc_class " + + "where has_nodegroup_privilege(pgroup, 'USAGE'))" + + ") select * from x " + + "where has_table_privilege(x.oid,'SELECT');"; + + public static final String GET_COLUMN_INFO_PARTITION_TABLES = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.parttype in ('p', 'v')) left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and t.relnamespace = 1 and t.relkind <> 'i' order by t.oid, c.attnum;"; + // column info for a single partition table + public static final String GET_COLUMN_INFO_PARTITION_TABLE = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.parttype in ('p', 'v')) left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and t.oid = 1 and t.relkind <> 'i' order by c.attnum;"; + + public static final String GET_PARTITIONS = "select p.oid AS partition_id , p.relname AS partition_name , p.parentid AS table_id from pg_class c, pg_partition p where c.relnamespace = 1 and c.parttype = 'p' and p.parentid = c.oid and p.parttype = 'p' order by p.boundaries;"; + + // partition info for a single table + public static final String GET_PARTITION = "select p.oid AS partition_id , p.relname AS partition_name , p.parentid AS table_id from pg_class c, pg_partition p where c.oid = 1 and c.parttype = 'p' and p.parentid = c.oid and p.parttype = 'p' order by p.boundaries;"; + + public static final String GET_PARTITION_CONSTRAINTS = "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c join pg_class cl on c.conrelid = cl.oid where c.connamespace=1 and cl.parttype in ('p','v') and c.conrelid <> 0;"; + // constraint info for a single partition table + public static final String GET_PARTITION_CONSTRAINT = "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c join pg_class cl on c.conrelid = cl.oid where c.conrelid=1 and cl.parttype in ('p','v') and c.conrelid <> 0;"; + + public static final String GET_PARTITION_INDEXES = "SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, ci.relnamespace as namespaceid, ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, i.indisexclusion as isexclusion, i.indimmediate as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, i.indisready as isready, i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions, def.indexdef, def.tablespace FROM pg_index i LEFT JOIN pg_class t on (t.oid = i.indrelid) LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) LEFT JOIN pg_namespace ns on (ci.relnamespace = ns.oid) LEFT JOIN pg_indexes def on (ci.relname = def.indexname and ns.nspname = def.schemaname) WHERE t.relkind in ('r', 'f') and ci.parttype in ('p','v') and ci.relnamespace = 1;"; + + // index info for a single partition table + public static final String GET_PARTITION_INDEX = "SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, ci.relnamespace as namespaceid, ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, i.indisexclusion as isexclusion, i.indimmediate as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, i.indisready as isready, i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions, def.indexdef, def.tablespace FROM pg_index i LEFT JOIN pg_class t on (t.oid = i.indrelid) LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) LEFT JOIN pg_namespace ns on (ci.relnamespace = ns.oid) LEFT JOIN pg_indexes def on (ci.relname = def.indexname and ns.nspname = def.schemaname) WHERE t.relkind = 'r' and ci.parttype in ('p','v') and ci.oid = 1;"; + + public static final String GET_REFRESH_DATATYPE = "select typ.oid as oid, typ.typname as typname, typ.typnamespace as typnamespace, typ.typlen as typlen, pg_catalog.format_type(oid,typ.typtypmod) as displaycolumns , typ.typbyval as typbyval, typ.typtype as typtype, typ.typcategory as typcategory, typ.typtypmod as typtypmod, typ.typnotnull as typnotnull, typ.typarray as typarray, des.description as desc from pg_type typ left join pg_description des on (typ.oid = des.objoid) where typnamespace = 1 order by typ.typname"; + + public static final String REFRESH_SEQUENCE_METADATA = "select oid,relnamespace,relowner,relname from pg_class where relkind='S' and relnamespace= 1"; + public static final String COLUMN_COMMENTS = "select a.attrelid,a.attname ,d.objsubid, d.description from pg_description d left join pg_attribute a on (d.objoid = a.attrelid and a.attnum = d.objsubid) where d.objoid = 1"; + + public static final String EDIT_TABLE_DATA_SELECT_QUERY = + "select * from " + "pg_catalog.\"EditTable\""; + + public static final String FETCH_DISTRIBUTION_COLUMNLIST_QUERY = + "select CASE pclocatortype WHEN 'R' THEN 'REPLICATION' WHEN 'H' THEN 'HASH' END as distriute_type, getdistributekey(1) as distributekey from pgxc_class, (SELECT count(*) AS dn_cn FROM pg_catalog.pgxc_node WHERE node_type = 'D') as nc where pcrelid = 1"; + + public static final String FETCH_SERVER_IP = "select inet_server_addr();"; + + public static final String CURSOR_QUERY_EXECUTION = + "CURSOR __DS_QRY_CRSR_155867822__ NO SCROLL FOR select * from pg_amop;"; + + public static final String CURSOR_QUERY_FETCH = + "FETCH FORWARD 1000 FROM __DS_QRY_CRSR_155867822__"; + public static final String FETCH_ALL_TABLE_IN_NAMESPACE = "with x as (" + + "select tbl.oid as oid, tbl.relname relname, tbl.relpersistence relpersistence,tbl.reloptions as reloptions, tbl.parttype as parttype, array_to_string(part.partkey,',') as partkey from pg_class tbl left join pg_partition part on(tbl.oid=part.parentid and part.parttype='r') where tbl.relkind = 'r' and tbl.relnamespace = 1" + + " and oid in (" + + "select pcrelid from pgxc_class " + + "where has_nodegroup_privilege(pgroup, 'USAGE'))" + + ") select * from x " + + "where has_table_privilege(x.oid,'SELECT');"; + + public static DBConnection getDBConnection() + { + DBConnection connection1 = new DBConnection(); + + String url = null; + Properties props = new Properties(); + + try + { + initDriver("org.postgresql.Driver"); + } + catch (DatabaseOperationException e) + { + + e.printStackTrace(); + } + + props.setProperty("user", "test"); + props.setProperty("password", "test"); + props.setProperty("allowEncodingChanges", "true"); + String encoding = System.getProperty("file.encoding"); + props.setProperty("characterEncoding", encoding); + props.setProperty("ApplicationName", "MPP IDE"); + + url = "jdbc:postgresql://127.0.0.1:1234/testDB"; + connection1.setDriver(new IConnectionDriver() + { + + @Override + public String getToolPath(String toolName) + { + + return null; + } + + @Override + public Driver getJDBCDriver() + { + + return null; + } + + @Override + public Properties getDriverSpecificProperties() + { + + return null; + } + + @Override + public String getDriverName() + { + + return null; + } + + @Override + public String extractErrCodeAdErrMsgFrmServErr(SQLException e) + { + + return null; + } + + @Override + public Keywords getKeywordList() { + + return new OLAPKeywords(); + } + + @Override + public SQLSyntax loadSQLSyntax() + { + + return null; + } + + }); + try + { + connection1.dbConnect(props, url); + } + catch (DatabaseOperationException e) + { + + e.printStackTrace(); + } + catch (DatabaseCriticalException e) + { + + e.printStackTrace(); + } + + return connection1; + } + + public static void initDriver(String strDriver) throws DatabaseOperationException { + try { + Class.forName(strDriver); + MPPDBIDELoggerUtility.info("ADAPTER: Driver Init Successful."); + } catch (ClassNotFoundException e) { + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_DRIVER_INIT_FAILED, e); + } + } + + public static void prepareProxyInfo( + PreparedStatementResultSetHandler preparedstatementHandler) + { + mockCheckDebugSupport(preparedstatementHandler); + mockCheckExplainPlanSupport(preparedstatementHandler); + MockResultSet sequenceset = preparedstatementHandler.createResultSet(); + sequenceset.addColumn("oid"); + sequenceset.addColumn("relnamespace"); + sequenceset.addColumn("relowner"); + sequenceset.addColumn("relname"); + sequenceset.addRow(new Object[] {1, 1, 10, "sequence1"}); + sequenceset.addRow(new Object[] {2, 1, 10, "sequence2"}); + preparedstatementHandler.prepareResultSet( + "select oid,relnamespace,relowner,relname from pg_class where relkind='S' and relnamespace=1", + sequenceset); + MockResultSet sequenceset2 = preparedstatementHandler.createResultSet(); + sequenceset2.addColumn("oid"); + sequenceset2.addColumn("relnamespace"); + sequenceset2.addColumn("relowner"); + sequenceset2.addColumn("relname"); + sequenceset2.addRow(new Object[] {1, 1, 10, "sequence1"}); + preparedstatementHandler.prepareResultSet( + "select oid,relnamespace,relowner,relname from pg_class where relkind='S' and oid=1", + sequenceset2); + // getSchemaNameOne(preparedstatementHandler); + MockResultSet getDeadlineInfo = preparedstatementHandler + .createResultSet(); + getDeadlineInfo.addColumn("DEADLINE"); + + getDeadlineInfo.addRow(new Object[] {"3.124632"}); + preparedstatementHandler.prepareResultSet( + "select intervaltonum(gs_password_deadline()) as DEADLINE;", + getDeadlineInfo); + + MockResultSet indexRS1 = preparedstatementHandler.createResultSet(); + indexRS1.addColumn("oid"); + indexRS1.addColumn("tableId"); + indexRS1.addColumn("indexname"); + indexRS1.addColumn("namespaceid"); + indexRS1.addColumn("accessmethodid"); + indexRS1.addColumn("isunique"); + indexRS1.addColumn("isprimary"); + indexRS1.addColumn("isexclusion"); + indexRS1.addColumn("isimmediate"); + indexRS1.addColumn("isclustered"); + indexRS1.addColumn("checkmin"); + indexRS1.addColumn("isready"); + indexRS1.addColumn("cols"); + indexRS1.addColumn("reloptions"); + indexRS1.addColumn("indexdef"); + + indexRS1.addRow(new Object[] {1, 1, "IndexName", 1, 1, true, false, + false, false, false, false, false, "1", "", ""}); + String query = "SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, ci.relnamespace as namespaceid, " + + "ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, i.indisexclusion as isexclusion," + + " i.indimmediate as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, i.indisready as isready, " + + "i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions, def.indexdef " + + "FROM pg_index i" + + " LEFT JOIN pg_class t on (t.oid = i.indrelid) " + + "LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) " + + "LEFT JOIN pg_namespace ns on (ci.relnamespace = ns.oid) " + + "LEFT JOIN pg_indexes def on (ci.relname = def.indexname and ns.nspname = def.schemaname)" + + " WHERE t.relkind = 'r' and t.oid = " + 0 + ';'; + preparedstatementHandler.prepareResultSet(query, indexRS1); + + MockResultSet getVersionResult = preparedstatementHandler + .createResultSet(); + getVersionResult.addColumn("proxyAPIVer"); + getVersionResult.addColumn("serverVersionStr"); + + getVersionResult.addRow(new Object[] { + "PostgreSQL 9.2beta2 on i686-pc-linux-gnu, compiled by gcc (SUSE Linux) 4.3.4 [gcc-4_3-branch revision 152973], 32-bit", + "GMDB Tools V2R5C00B201"}); + preparedstatementHandler.prepareResultSet( + "SELECT * from pldbg_get_proxy_info();", getVersionResult); + + MockResultSet gettblsprs1 = preparedstatementHandler.createResultSet(); + gettblsprs1.addColumn("oid"); + gettblsprs1.addColumn("nspname"); + gettblsprs1.addRow(new Object[] {1}); + preparedstatementHandler.prepareResultSet( + "SELECT oid from pg_namespace WHERE nspname=?", gettblsprs1); + + MockResultSet getdbsrs1 = preparedstatementHandler.createResultSet(); + getdbsrs1.addColumn("oid"); + getdbsrs1.addColumn("nspoid"); + getdbsrs1.addColumn("schemaname"); + getdbsrs1.addColumn("viewname"); + getdbsrs1.addColumn("viewowner"); + getdbsrs1.addRow(new Object[] {2, 1, "public", "mytestview", "owner1"}); + getdbsrs1.addRow( + new Object[] {25, 1, "public", "mytestview2", "owner1"}); + preparedstatementHandler.prepareResultSet( + "SELECT c.oid, n.oid as nspoid, n.nspname AS schemaname, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner " + + "FROM (pg_class c LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace))) WHERE (c.relkind = 'v'::\"char\" or c.relkind = 'm'::\"char\") and has_table_privilege(c.oid,'SELECT') ", + getdbsrs1); + + MockResultSet getdbsrs1_1 = preparedstatementHandler.createResultSet(); + getdbsrs1_1.addColumn("oid"); + getdbsrs1_1.addColumn("nspoid"); + getdbsrs1_1.addColumn("schemaname"); + getdbsrs1_1.addColumn("viewname"); + getdbsrs1_1.addColumn("viewowner"); + getdbsrs1_1.addRow(new Object[] {2, 1, "public", "mytestview", "owner1"}); + getdbsrs1_1.addRow( + new Object[] {25, 1, "public", "mytestview2", "owner1"}); + preparedstatementHandler.prepareResultSet( + "SELECT c.oid, n.oid as nspoid, n.nspname AS schemaname, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner " + + "FROM (pg_class c LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace))) WHERE (c.relkind = 'v'::\"char\" or c.relkind = 'm'::\"char\") ", + getdbsrs1_1); + + MockResultSet gettblsprs2 = preparedstatementHandler.createResultSet(); + gettblsprs2.addColumn("nodeid"); + gettblsprs2.addColumn("namespaceid"); + gettblsprs2.addColumn("relname"); + gettblsprs2.addRow(new Object[] {1, 1, "veera"}); + preparedstatementHandler.prepareResultSet( + "select cls.relfilenode as nodeid ,cls.relnamespace as namespaceid from pg_class as cls where cls.relname=?", + gettblsprs2); + + MockResultSet gettblsprs4 = preparedstatementHandler.createResultSet(); + gettblsprs4.addColumn("distype"); + gettblsprs4.addColumn("attnum"); + gettblsprs4.addColumn("pcrelid"); + + gettblsprs4.addRow(new Object[] {1, 1, "veera"}); + preparedstatementHandler.prepareResultSet( + "select xcls.pclocatortype as distype,xcls.pcattnum as attnum from pgxc_class as xcls where xcls.pcrelid=?", + gettblsprs4); + + MockResultSet tablespaceMetaData = preparedstatementHandler + .createResultSet(); + tablespaceMetaData.addColumn("oid"); + tablespaceMetaData.addColumn("spcname"); + tablespaceMetaData.addColumn("spcoptions"); + tablespaceMetaData.addColumn("location"); + tablespaceMetaData.addColumn("spcmaxsize"); + tablespaceMetaData.addColumn("relative"); + tablespaceMetaData.addRow(new Object[] {1, "tblspc", + new String[] {"filesystem=HDFS", "address = address"}, + "location", "spcmaxsize", false}); + tablespaceMetaData.addRow( + new Object[] {1, "tblspc", null, "location", "spcmaxsize", false}); + preparedstatementHandler.prepareResultSet( + "select oid, pg_tablespace_location(oid) as location, spcname,spcacl,spcoptions, spcmaxsize, relative from pg_tablespace where oid =" + + 1, + tablespaceMetaData); + + + + MockResultSet getServerVersionResult = preparedstatementHandler + .createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] { + "PostgreSQL 9.2.4 (openGauss 1.0 build e2c0f862) compiled at 2020-04-29 10:27:47 commit 2144 last mr 131 debug on aarch64-unknown-linux-gnu, compiled by g++ (GCC) 8.2.0, 64-bit"}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", + getServerVersionResult); + + MockResultSet getServerVersionResultSet = preparedstatementHandler + .createResultSet(); + getServerVersionResultSet.addColumn("VERSION"); + + getServerVersionResultSet.addRow(new Object[] { + "Gauss200 OLAP V100R005C10 build 7123 compiled at 2016-11-11 16:18:35 on x86_64-unknown-linux-gnu, compiled by g++ (SUSE Linux) 4.3.4 [gcc-4_3-branch revision 152973], 64-bit"}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", + getServerVersionResultSet); + + MockResultSet getdboidrs = preparedstatementHandler.createResultSet(); + getdboidrs.addColumn("oid"); + + getdboidrs.addRow(new Object[] {1}); + preparedstatementHandler.prepareResultSet( + "SELECT oid from pg_database where datname = 'Gauss'", + getdboidrs); + + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("oid"); + getdbsrs.addColumn("datname"); + + getdbsrs.addRow(new Object[] {1, "Gauss"}); + preparedstatementHandler.prepareResultSet( + "select oid, datname from pg_database where datistemplate='f'", + getdbsrs); + + MockResultSet server_encoding = preparedstatementHandler + .createResultSet(); + server_encoding.addRow(new Object[] {"UTF-8"}); + preparedstatementHandler.prepareResultSet("show server_encoding", + server_encoding); + + MockResultSet getnoders = preparedstatementHandler.createResultSet(); + getnoders.addColumn("oid"); + getnoders.addColumn("node_name"); + getnoders.addColumn("node_type"); + getnoders.addColumn("node_port"); + getnoders.addColumn("node_host"); + getnoders.addColumn("nodeis_primary"); + getnoders.addColumn("nodeis_preferred"); + getnoders.addColumn("node_id"); + + getnoders.addRow(new Object[] {1, "Node_1", "node_type", 23456, + "1.0.0.0", true, true, 12}); + preparedstatementHandler.prepareResultSet( + "select oid, node_name, node_type, node_port, node_host, nodeis_primary, nodeis_preferred, node_id from pgxc_node;", + getnoders); + + MockResultSet getnodegrprs = preparedstatementHandler.createResultSet(); + getnodegrprs.addColumn("oid"); + getnodegrprs.addColumn("group_name"); + getnodegrprs.addColumn("group_members"); + + getnodegrprs.addRow(new Object[] {1, "group_1", "23 25"}); + preparedstatementHandler.prepareResultSet( + "select oid, group_name, group_members from pgxc_group order by group_name;", + getnodegrprs); + + MockResultSet gettblsprs = preparedstatementHandler.createResultSet(); + gettblsprs.addColumn("oid"); + gettblsprs.addColumn("location"); + gettblsprs.addColumn("spcname"); + gettblsprs.addColumn("spcacl"); + gettblsprs.addColumn("spcoptions"); + gettblsprs.addColumn("spcmaxsize"); + gettblsprs.addColumn("relative"); + gettblsprs.addRow( + new Object[] {1, "/home/dsdev/shalini", "tablespace1", null, + new String[] {"filesystem=general", + "random_page_cost=2", "seq_page_cost=2", + "address =address"}, + "10K", false}); + preparedstatementHandler.prepareResultSet( + "select oid, pg_tablespace_location(oid) as location ,spcname,spcacl,spcoptions, spcmaxsize, relative from pg_tablespace where has_tablespace_privilege(spcname, 'CREATE') order by spcname;", + gettblsprs); + + MockResultSet gettblsprs_new = preparedstatementHandler.createResultSet(); + gettblsprs.addColumn("oid"); + gettblsprs.addColumn("spcname"); + gettblsprs.addColumn("spcacl"); + gettblsprs.addColumn("spcoptions"); + gettblsprs.addColumn("spcmaxsize"); + gettblsprs.addColumn("relative"); + gettblsprs.addRow( + new Object[] {1, "tablespace1", null, + new String[] {"filesystem=general", + "random_page_cost=2", "seq_page_cost=2", + "address =address"}, + "10K", false}); + preparedstatementHandler.prepareResultSet( + "select oid,spcname,spcacl,spcoptions, spcmaxsize, relative from pg_tablespace order by spcname;", + gettblsprs); + + MockResultSet getaccessmethodrs = preparedstatementHandler + .createResultSet(); + getaccessmethodrs.addColumn("oid"); + getaccessmethodrs.addColumn("amname"); + + getaccessmethodrs.addRow(new Object[] {1, "accemethod1"}); + preparedstatementHandler.prepareResultSet( + "SELECT oid, amname from pg_am order by oid;", + getaccessmethodrs); + + MockResultSet namespaceRS = preparedstatementHandler.createResultSet(); + namespaceRS.addColumn("oid"); + namespaceRS.addColumn("nspname"); + namespaceRS.addRow(new Object[] {3, "PUBLIC"}); + //namespaceRS.addRow(new Object[] {1, "pg_catalog"}); + //namespaceRS.addRow(new Object[] {2, "information_schema"}); + // namespaceRS.addRow(new Object[] {2, "schema1"}); + // namespaceRS.addRow(new Object[] {3, "schema2"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_ALL_NAMESPACE, namespaceRS); + + MockResultSet systemNamespaceRS = preparedstatementHandler.createResultSet(); + systemNamespaceRS.addColumn("oid"); + systemNamespaceRS.addColumn("nspname"); + //namespaceRS.addRow(new Object[] {1, "PUBLIC"}); + systemNamespaceRS.addRow(new Object[] {1, "pg_catalog"}); + systemNamespaceRS.addRow(new Object[] {2, "information_schema"}); + // namespaceRS.addRow(new Object[] {2, "schema1"}); + // namespaceRS.addRow(new Object[] {3, "schema2"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_ALL_SYSTEM_NAMESPACE, systemNamespaceRS); + + MockResultSet namespaceRS1 = preparedstatementHandler.createResultSet(); + namespaceRS1.addColumn("oid"); + namespaceRS1.addColumn("nspname"); + namespaceRS1.addColumn("nspowner"); + namespaceRS1.addColumn("nspacl"); + namespaceRS1.addRow(new Object[] {1, "pg_catalog"}); + namespaceRS1.addRow(new Object[] {2, "information_schema"}); + namespaceRS1.addRow(new Object[] {3, "PUBLIC"}); + namespaceRS1.addRow(new Object[] {10, "newSchema"}); + preparedstatementHandler.prepareResultSet(CommonLLTUtils.FETCH_ALL_NAMESPACE_LOAD_PRIV, namespaceRS1); + + + + MockResultSet namespaceRS11 = preparedstatementHandler.createResultSet(); + namespaceRS11.addColumn("oid"); + namespaceRS11.addColumn("nspname"); + namespaceRS11.addColumn("nspowner"); + namespaceRS11.addColumn("nspacl"); + namespaceRS11.addRow(new Object[] {1, "pg_catalog"}); + namespaceRS11.addRow(new Object[] {2, "information_schema"}); + namespaceRS11.addRow(new Object[] {3, "PUBLIC"}); + namespaceRS11.addRow(new Object[] {10, "newSchema"}); + preparedstatementHandler.prepareResultSet(CommonLLTUtils.FETCH_ALL_NAMESPACE_LOAD_ALL, namespaceRS11); + + MockResultSet viewRS = preparedstatementHandler.createResultSet(); + viewRS.addColumn("viewid"); + viewRS.addColumn("namespaceid"); + viewRS.addColumn("columnidx"); + viewRS.addColumn("name"); + viewRS.addColumn("datatypeoid"); + viewRS.addColumn("dtns"); + viewRS.addColumn("length"); + viewRS.addColumn("precision"); + viewRS.addColumn("dimentions"); + viewRS.addColumn("notnull"); + viewRS.addColumn("isdefaultvalueavailable"); + viewRS.addColumn("default_value"); + viewRS.addRow( + new Object[] {2, 1, 1, "col1", 3, 1, 0, 0, 0, 'f', 'f', ""}); + viewRS.addRow( + new Object[] {2, 1, 1, "col1", 8, 1, 0, 0, 0, 'f', 'f', ""}); + viewRS.addRow( + new Object[] {2, 1, 1, "col1", 5, 1, 0, 0, 0, 'f', 'f', ""}); + preparedstatementHandler.prepareResultSet(CommonLLTUtils.GET_ALL_VIEWS, + viewRS); + + MockResultSet shallowLoadTablesRS = preparedstatementHandler + .createResultSet(); + shallowLoadTablesRS.addColumn("oid"); + shallowLoadTablesRS.addColumn("relname"); + shallowLoadTablesRS.addColumn("relnamespace"); + shallowLoadTablesRS.addColumn("relpersistence"); + shallowLoadTablesRS.addRow(new Object[] {1, "order_7", 1, "p"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_ALL_SHALLOWLOADTABLES, shallowLoadTablesRS); + MockResultSet functionRS = preparedstatementHandler.createResultSet(); + functionRS.addColumn("oid"); + functionRS.addColumn("objname"); + functionRS.addColumn("namespace"); + functionRS.addColumn("ret"); + functionRS.addColumn("alltype"); + functionRS.addColumn("nargs"); + functionRS.addColumn("argtype"); + functionRS.addColumn("argname"); + functionRS.addColumn("argmod"); + functionRS.addColumn("secdef"); + functionRS.addColumn("vola"); + functionRS.addColumn("isstrict"); + functionRS.addColumn("retset"); + functionRS.addColumn("procost"); + functionRS.addColumn("setrows"); + + // 11389,pgxc_prepared_xact,11,25,,0,,,,f,v,f,t,100,1000 + functionRS.addRow(new Object[] {1, "pgxc_prepared_xact", 1, 1, null, 0, + " ", null, null, "f", "v", "f", "t", 1, 1}); + preparedstatementHandler.prepareResultSet(CommonLLTUtils.FUNCTIONONLY, + functionRS); + MockResultSet Shallowload1RS = preparedstatementHandler + .createResultSet(); + Shallowload1RS.addColumn("oid"); + Shallowload1RS.addColumn("relname"); + Shallowload1RS.addColumn("relnamespace"); + Shallowload1RS.addColumn("relpersistence"); + Shallowload1RS.addColumn("reltablespace"); + // 736937,AAA,2200,p + // 11389,pgxc_prepared_xact,11,25,,0,,,,f,v,f,t,100,1000 + Shallowload1RS + .addRow(new Object[] {1, "Table1", 1, "p", "tablespace1"}); + Shallowload1RS + .addRow(new Object[] {1, "Table2", 1, "t", "tablespace2"}); + Shallowload1RS + .addRow(new Object[] {1, "Table3", 1, "u", "tablespace3"}); + preparedstatementHandler.prepareResultSet(CommonLLTUtils.Shallowload1, + Shallowload1RS); + /* + * MockResultSet shallowLoadQueryDefaultRS = + * preparedstatementHandler.createResultSet(); + * shallowLoadQueryDefaultRS.addColumn("oid"); + * shallowLoadQueryDefaultRS.addColumn("objname"); + * shallowLoadQueryDefaultRS.addColumn("namespace"); + * shallowLoadQueryDefaultRS.addColumn("ret"); + * shallowLoadQueryDefaultRS.addColumn("alltype"); + * shallowLoadQueryDefaultRS.addColumn("nargs"); + * shallowLoadQueryDefaultRS.addColumn("argtype"); + * shallowLoadQueryDefaultRS.addColumn("argname"); + * shallowLoadQueryDefaultRS.addColumn("argmod"); + * shallowLoadQueryDefaultRS.addColumn("secdef"); + * shallowLoadQueryDefaultRS.addColumn("vola"); + * shallowLoadQueryDefaultRS.addColumn("isstrict"); + * shallowLoadQueryDefaultRS.addColumn("retset"); + * shallowLoadQueryDefaultRS.addColumn("procost"); + * shallowLoadQueryDefaultRS.addColumn("setrows"); + * shallowLoadQueryDefaultRS.addRow(new Object[] + * {1,"auto1",1,23,null,0,null,null,null,"f","v","f","f",100,0}); // + * shallowLoadQueryRS.addRow(new Object[] + * {17830,"calculateoutput",1,2278 + * ,"{23,23}",1,23,"{id,value}","{i,o}","f","v","f","f",100,0}); + * preparedstatementHandler + * .prepareResultSet(CommonLLTUtils.SHALLOWLOADQUERYDEFAULT, + * shallowLoadQueryDefaultRS); + */ + + MockResultSet refreshtablemetadatainnamspace = preparedstatementHandler + .createResultSet(); + refreshtablemetadatainnamspace.addColumn("oid"); + refreshtablemetadatainnamspace.addColumn("relname"); + refreshtablemetadatainnamspace.addColumn("relpersistence"); + refreshtablemetadatainnamspace.addColumn("reloptions"); + refreshtablemetadatainnamspace.addColumn("parttype"); + refreshtablemetadatainnamspace.addColumn("partkey"); + refreshtablemetadatainnamspace + .addRow(new Object[] {1, "MyTable", 'p', "", 'n', "abc"}); + preparedstatementHandler.prepareResultSet(CommonLLTUtils.FETCH_ALL_TABLE_IN_NAMESPACE, + refreshtablemetadatainnamspace); + + + + MockResultSet loadFuncTriggerRS = preparedstatementHandler + .createResultSet(); + loadFuncTriggerRS.addColumn("oid"); + loadFuncTriggerRS.addColumn("objname"); + loadFuncTriggerRS.addColumn("namespace"); + loadFuncTriggerRS.addColumn("ret"); + loadFuncTriggerRS.addColumn("alltype"); + loadFuncTriggerRS.addColumn("nargs"); + loadFuncTriggerRS.addColumn("argtype"); + loadFuncTriggerRS.addColumn("argname"); + loadFuncTriggerRS.addColumn("argmod"); + loadFuncTriggerRS.addColumn("secdef"); + loadFuncTriggerRS.addColumn("vola"); + loadFuncTriggerRS.addColumn("isstrict"); + loadFuncTriggerRS.addColumn("retset"); + loadFuncTriggerRS.addColumn("procost"); + loadFuncTriggerRS.addColumn("setrows"); + loadFuncTriggerRS.addColumn("lang"); + loadFuncTriggerRS.addRow(new Object[] {1, "auto1", 1, 23, null, 0, null, + null, null, "f", "v", "f", "f", 100, 0, "plpgsql"}); + // loadFuncTriggerRS.addRow(new Object[] + // {17830,"calculateoutput",1,2278,"{23,23}",1,23,"{id,value}","{i,o}","f","v","f","f",100,0}); + loadFuncTriggerRS.addRow(new Object[] {2, "function2", 1, 2278, + "{23,23,23}", 2, 23, "{id1,id2,value}", "{i,o,b}", "f", "v", + "f", "f", 100, 0, "plpgsql"}); + preparedstatementHandler.prepareResultSet(CommonLLTUtils.TRIGGERONLY, + loadFuncTriggerRS); + MockResultSet loadTriggerRS = preparedstatementHandler + .createResultSet(); + loadTriggerRS.addColumn("oid"); + loadTriggerRS.addColumn("objname"); + loadTriggerRS.addColumn("namespace"); + loadTriggerRS.addColumn("ret"); + loadTriggerRS.addColumn("alltype"); + loadTriggerRS.addColumn("nargs"); + loadTriggerRS.addColumn("argtype"); + loadTriggerRS.addColumn("argname"); + loadTriggerRS.addColumn("argmod"); + loadTriggerRS.addColumn("secdef"); + loadTriggerRS.addColumn("vola"); + loadTriggerRS.addColumn("isstrict"); + loadTriggerRS.addColumn("retset"); + loadTriggerRS.addColumn("procost"); + loadTriggerRS.addColumn("setrows"); + loadTriggerRS.addRow(new Object[] {1, "auto1", 1, 23, null, 0, null, + null, null, "f", "v", "f", "f", 100, 0}); + // loadTriggerRS.addRow(new Object[] + // {17830,"calculateoutput",1,2278,"{23,23}",1,23,"{id,value}","{i,o}","f","v","f","f",100,0}); + preparedstatementHandler.prepareResultSet(CommonLLTUtils.TRIGGERONLY1, + loadTriggerRS); + MockResultSet loadTriggerRS2 = preparedstatementHandler + .createResultSet(); + loadTriggerRS2.addColumn("oid"); + loadTriggerRS2.addColumn("objname"); + loadTriggerRS2.addColumn("namespace"); + loadTriggerRS2.addColumn("ret"); + loadTriggerRS2.addColumn("alltype"); + loadTriggerRS2.addColumn("nargs"); + loadTriggerRS2.addColumn("argtype"); + loadTriggerRS2.addColumn("argname"); + loadTriggerRS2.addColumn("argmod"); + loadTriggerRS2.addColumn("secdef"); + loadTriggerRS2.addColumn("vola"); + loadTriggerRS2.addColumn("isstrict"); + loadTriggerRS2.addColumn("retset"); + loadTriggerRS2.addColumn("procost"); + loadTriggerRS2.addColumn("setrows"); + loadTriggerRS2.addRow(new Object[] {1, "auto1", 1, 23, null, 0, null, + null, null, "f", "v", "f", "f", 100, 0}); + // loadTriggerRS.addRow(new Object[] + // {17830,"calculateoutput",1,2278,"{23,23}",1,23,"{id,value}","{i,o}","f","v","f","f",100,0}); + preparedstatementHandler.prepareResultSet(CommonLLTUtils.TRIGGERONLY2, + loadTriggerRS); + + MockResultSet shallowLoadQueryRS = preparedstatementHandler + .createResultSet(); + shallowLoadQueryRS.addColumn("oid"); + shallowLoadQueryRS.addColumn("objname"); + shallowLoadQueryRS.addColumn("namespace"); + shallowLoadQueryRS.addColumn("ret"); + shallowLoadQueryRS.addColumn("alltype"); + shallowLoadQueryRS.addColumn("nargs"); + shallowLoadQueryRS.addColumn("argtype"); + shallowLoadQueryRS.addColumn("argname"); + shallowLoadQueryRS.addColumn("argmod"); + shallowLoadQueryRS.addColumn("secdef"); + shallowLoadQueryRS.addColumn("vola"); + shallowLoadQueryRS.addColumn("isstrict"); + shallowLoadQueryRS.addColumn("retset"); + shallowLoadQueryRS.addColumn("procost"); + shallowLoadQueryRS.addColumn("setrows"); + shallowLoadQueryRS.addColumn("lang"); + shallowLoadQueryRS.addRow(new Object[] {1, "auto1", 1, 23, null, 0, + null, null, null, "f", "v", "f", "f", 100, 0, "plpgsql"}); + // shallowLoadQueryRS.addRow(new Object[] + // {17830,"calculateoutput",1,2278,"{23,23}",1,23,"{id,value}","{i,o}","f","v","f","f",100,0}); + shallowLoadQueryRS.addRow(new Object[] {2, "function2", 1, 2278, + "{23,23,23}", 2, 23, "{id1,id2,value}", "{i,o,b}", "f", "v", + "f", "f", 100, 0, "plpgsql"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.SHALLOWLOADQUERY, shallowLoadQueryRS); + + MockResultSet shallowLoadQueryDefaultRS = preparedstatementHandler + .createResultSet(); + shallowLoadQueryDefaultRS.addColumn("oid"); + shallowLoadQueryDefaultRS.addColumn("objname"); + shallowLoadQueryDefaultRS.addColumn("namespace"); + shallowLoadQueryDefaultRS.addColumn("ret"); + shallowLoadQueryDefaultRS.addColumn("alltype"); + shallowLoadQueryDefaultRS.addColumn("nargs"); + shallowLoadQueryDefaultRS.addColumn("argtype"); + shallowLoadQueryDefaultRS.addColumn("argname"); + shallowLoadQueryDefaultRS.addColumn("argmod"); + shallowLoadQueryDefaultRS.addColumn("secdef"); + shallowLoadQueryDefaultRS.addColumn("vola"); + shallowLoadQueryDefaultRS.addColumn("isstrict"); + shallowLoadQueryDefaultRS.addColumn("retset"); + shallowLoadQueryDefaultRS.addColumn("procost"); + shallowLoadQueryDefaultRS.addColumn("setrows"); + shallowLoadQueryDefaultRS.addColumn("lang"); + shallowLoadQueryDefaultRS.addRow(new Object[] {1, "auto1", 1, 23, null, + 1, null, null, null, "f", "v", "f", "f", 100, 0, "plpgsql"}); + // shallowLoadQueryRS.addRow(new Object[] + // {17830,"calculateoutput",1,2278,"{23,23}",1,23,"{id,value}","{i,o}","f","v","f","f",100,0}); + shallowLoadQueryRS.addRow(new Object[] {2, "function2", 1, 2278, + "{23,23,23}", 2, 23, "{id1,id2,value}", "{i,o,b}", "f", "v", + "f", "f", 100, 0, "plpgsql"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.SHALLOWLOADQUERYDEFAULT, + shallowLoadQueryDefaultRS); + + /* + * MockResultSet datatypeRS = + * preparedstatementHandler.createResultSet(); + * datatypeRS.addColumn("oid"); datatypeRS.addColumn("typname"); + * datatypeRS.addColumn("typnamespace"); datatypeRS.addColumn("typlen"); + * datatypeRS.addColumn("typbyval"); datatypeRS.addColumn("typtype"); + * datatypeRS.addColumn("typcategory"); + * datatypeRS.addColumn("typtypmod"); + * datatypeRS.addColumn("typnotnull"); datatypeRS.addColumn("typarray"); + * datatypeRS.addColumn("desc"); datatypeRS.addColumn("displaycolumns"); + * + * datatypeRS.addRow(new Object[] {1, "bigint", 1, 1, true, "type", + * "category", 1, true, 12, "description","bigint"}); + * datatypeRS.addRow(new Object[] {2, "int8", 1, 1, true, "type", + * "category", 1, true, 12, "description2","character"}); + * + * datatypeRS.addRow(new Object[] {3, "bit", 1, 1, true, "type", + * "category", 1, true, 12, "description","bit"}); datatypeRS.addRow(new + * Object[] {4, "varbit", 1, 1, true, "type", "category", 1, true, 12, + * "description","varbit"}); datatypeRS.addRow(new Object[] {5, "bool", + * 1, 1, true, "type", "category", 1, true, 12, "description","bool"}); + * datatypeRS.addRow(new Object[] {6, "box", 1, 1, true, "type", + * "category", 1, true, 12, "description","box"}); datatypeRS.addRow(new + * Object[] {7, "bytea", 1, 1, true, "type", "category", 1, true, 12, + * "description","bytea"}); datatypeRS.addRow(new Object[] {8, + * "varchar", 1, 1, true, "type", "category", 1, true, 12, + * "description","varchar"}); datatypeRS.addRow(new Object[] {9, "char", + * 1, 1, true, "type", "category", 1, true, 12, "description","char"}); + * datatypeRS.addRow(new Object[] {10, "cidr", 1, 1, true, "type", + * "category", 1, true, 12, "description","cidr"}); + * datatypeRS.addRow(new Object[] {11, "circle", 1, 1, true, "type", + * "category", 1, true, 12, "description","circle"}); + * datatypeRS.addRow(new Object[] {12, "date", 1, 1, true, "type", + * "category", 1, true, 12, "description","date"}); + * + * datatypeRS.addRow(new Object[] {13, "float8", 1, 1, true, "type", + * "category", 1, true, 12, "description","float"}); + * datatypeRS.addRow(new Object[] {14, "inet", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {15, "int4", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); datatypeRS.addRow(new Object[] {16, "interval", + * 1, 1, true, "type", "category", 1, true, 12, "description",""}); + * datatypeRS.addRow(new Object[] {17, "line", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {18, "lseg", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); datatypeRS.addRow(new Object[] {19, "macaddr", 1, + * 1, true, "type", "category", 1, true, 12, "description",""}); + * datatypeRS.addRow(new Object[] {20, "money", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {21, "numeric", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); datatypeRS.addRow(new Object[] {22, "numeric", 1, + * 1, true, "type", "category", 1, true, 12, "description",""}); + * datatypeRS.addRow(new Object[] {23, "path", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {24, "point", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); datatypeRS.addRow(new Object[] {25, "polygon", 1, + * 1, true, "type", "category", 1, true, 12, "description",""}); + * datatypeRS.addRow(new Object[] {26, "float4", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {27, "int2", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); + * + * datatypeRS.addRow(new Object[] {28, "text", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {29, "time", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); datatypeRS.addRow(new Object[] {30, "timetz", 1, + * 1, true, "type", "category", 1, true, 12, "description",""}); + * datatypeRS.addRow(new Object[] {31, "timestamp", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {32, "timestamptz", 1, 1, true, "type", "category", 1, true, + * 12, "description",""}); datatypeRS.addRow(new Object[] {33, + * "tsquery", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); datatypeRS.addRow(new Object[] {34, "tsvector", + * 1, 1, true, "type", "category", 1, true, 12, "description",""}); + * datatypeRS.addRow(new Object[] {35, "txid_snapshot", 1, 1, true, + * "type", "category", 1, true, 12, "description",""}); + * datatypeRS.addRow(new Object[] {36, "uuid", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {37, "xml", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); + * + * preparedstatementHandler + * .prepareResultSet(CommonLLTUtils.GET_ALL_DATATYPE, datatypeRS); + */ + + String qry = "select typ.oid as oid, typ.typname as typname, typ.typnamespace as typnamespace, typ.typlen as typlen, pg_catalog.format_type(oid,typ.typtypmod) as displaycolumns , typ.typbyval as typbyval, typ.typtype as typtype, typ.typcategory as typcategory, typ.typtypmod as typtypmod, typ.typnotnull as typnotnull, typ.typarray as typarray, des.description as desc from pg_type typ left join pg_description des on (typ.oid = des.objoid) where typ.typnamespace in (select oid from pg_namespace where nspname in ('information_schema', 'pg_catalog')) order by typ.typname"; + MockResultSet dbrs = preparedstatementHandler.createResultSet(); + dbrs.addColumn("oid"); + dbrs.addColumn("typname"); + dbrs.addColumn("typnamespace"); + dbrs.addColumn("typlen"); + dbrs.addColumn("displaycolumns"); + dbrs.addColumn("typbyval"); + dbrs.addColumn("typtype"); + dbrs.addColumn("typcategory"); + dbrs.addColumn("typtypmod"); + dbrs.addColumn("typnotnull"); + dbrs.addColumn("typarray"); + dbrs.addColumn("desc"); + + dbrs.addRow(new Object[] {1, "bigint", 1, 1, "character", true, "type", + "category", 1, true, 12, "description", "bigint"}); + preparedstatementHandler.prepareResultSet(qry, dbrs); + + MockResultSet tablemetadataRS = preparedstatementHandler + .createResultSet(); + tablemetadataRS.addColumn("oid"); + tablemetadataRS.addColumn("relname"); + tablemetadataRS.addColumn("relnamespace"); + tablemetadataRS.addColumn("reltablespace"); + tablemetadataRS.addColumn("relpersistence"); + tablemetadataRS.addColumn("desc"); + tablemetadataRS.addColumn("nodes"); + tablemetadataRS.addColumn("reloptions"); + + tablemetadataRS.addRow(new Object[] {1, "MyTable", 1, 1, true, + "description", "1 2", ""}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.REFRESH_TABLE_METADATA, tablemetadataRS); + + MockResultSet colmetadataRS5 = preparedstatementHandler + .createResultSet(); + colmetadataRS5.addColumn("tableid"); + colmetadataRS5.addColumn("namespaceid"); + colmetadataRS5.addColumn("columnidx"); + colmetadataRS5.addColumn("name"); + colmetadataRS5.addColumn("displayColumns"); + colmetadataRS5.addColumn("datatypeoid"); + colmetadataRS5.addColumn("dtns"); + colmetadataRS5.addColumn("length"); + colmetadataRS5.addColumn("precision"); + colmetadataRS5.addColumn("dimentions"); + colmetadataRS5.addColumn("notnull"); + colmetadataRS5.addColumn("isdefaultvalueavailable"); + colmetadataRS5.addColumn("default_value"); + colmetadataRS5.addColumn("attDefStr"); + + colmetadataRS5.addRow(new Object[] {1, 1, 1, "ColName", "bigint", 1, 1, 200, 0, 0, + false, true, "Default value", "attrString"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_ALL_COLUMN_METADATA, colmetadataRS5); + + MockResultSet level2colunmRS = preparedstatementHandler + .createResultSet(); + level2colunmRS.addColumn("tableid"); + level2colunmRS.addColumn("namespaceid"); + level2colunmRS.addColumn("columnidx"); + level2colunmRS.addColumn("name"); + level2colunmRS.addColumn("datatypeoid"); + level2colunmRS.addColumn("dtns"); + level2colunmRS.addColumn("length"); + level2colunmRS.addColumn("precision"); + level2colunmRS.addColumn("dimentions"); + level2colunmRS.addColumn("notnull"); + level2colunmRS.addColumn("isdefaultvalueavailable"); + level2colunmRS.addColumn("default_value"); + level2colunmRS.addColumn("attDefStr"); + + level2colunmRS.addRow(new Object[] {1, 1, 1, "ColName", 1, 1, 0, 0, 0, + false, true, "Default value", "attrString"}); + preparedstatementHandler.prepareResultSet(CommonLLTUtils.LAVEL2COLUNM, + level2colunmRS); + + MockResultSet allIndexesRS = preparedstatementHandler.createResultSet(); + allIndexesRS.addColumn("oid"); + allIndexesRS.addColumn("tableId"); + allIndexesRS.addColumn("indexname"); + allIndexesRS.addColumn("namespaceid"); + allIndexesRS.addColumn("accessmethodid"); + allIndexesRS.addColumn("isunique"); + allIndexesRS.addColumn("isprimary"); + allIndexesRS.addColumn("isexclusion"); + allIndexesRS.addColumn("isimmediate"); + allIndexesRS.addColumn("isclustered"); + allIndexesRS.addColumn("checkmin"); + allIndexesRS.addColumn("isready"); + allIndexesRS.addColumn("cols"); + allIndexesRS.addColumn("reloptions"); + allIndexesRS.addColumn("indexdef"); + + allIndexesRS.addRow(new Object[] {1, 1, "IndexName", 1, 1, true, false, + false, false, false, false, false, "1", "", ""}); + preparedstatementHandler.prepareResultSet(CommonLLTUtils.ALLCONSTRAIN, + allIndexesRS); + + MockResultSet allIndexes_rs = preparedstatementHandler + .createResultSet(); + allIndexes_rs.addColumn("oid"); + allIndexes_rs.addColumn("tableId"); + allIndexes_rs.addColumn("indexname"); + allIndexes_rs.addColumn("namespaceid"); + allIndexes_rs.addColumn("accessmethodid"); + allIndexes_rs.addColumn("isunique"); + allIndexes_rs.addColumn("isprimary"); + allIndexes_rs.addColumn("isexclusion"); + allIndexes_rs.addColumn("isimmediate"); + allIndexes_rs.addColumn("isclustered"); + allIndexes_rs.addColumn("checkmin"); + allIndexes_rs.addColumn("isready"); + allIndexes_rs.addColumn("cols"); + allIndexes_rs.addColumn("reloptions"); + allIndexes_rs.addColumn("indexdef"); + + allIndexes_rs.addRow(new Object[] {1, 1, "IndexName", 1, 1, true, false, + false, false, false, false, false, "-1", "", "fillfactor=1"}); + preparedstatementHandler.prepareResultSet(CommonLLTUtils.ALLCONSTRAIN_1, + allIndexes_rs); + + MockResultSet indexRS = preparedstatementHandler.createResultSet(); + indexRS.addColumn("oid"); + indexRS.addColumn("tableId"); + indexRS.addColumn("indexname"); + indexRS.addColumn("namespaceid"); + indexRS.addColumn("accessmethodid"); + indexRS.addColumn("isunique"); + indexRS.addColumn("isprimary"); + indexRS.addColumn("isexclusion"); + indexRS.addColumn("isimmediate"); + indexRS.addColumn("isclustered"); + indexRS.addColumn("checkmin"); + indexRS.addColumn("isready"); + indexRS.addColumn("cols"); + indexRS.addColumn("reloptions"); + indexRS.addColumn("indexdef"); + indexRS.addColumn("tablespace"); + + indexRS.addRow(new Object[] {1, 1, "IndexName", 1, 1, true, false, + false, false, false, false, false, "1", "", "", ""}); + preparedstatementHandler + .prepareResultSet(CommonLLTUtils.GET_ALL_INDEXES, indexRS); + + MockResultSet constraintRS = preparedstatementHandler.createResultSet(); + constraintRS.addColumn("constraintid"); + constraintRS.addColumn("tableid"); + constraintRS.addColumn("namespaceid"); + constraintRS.addColumn("constraintname"); + constraintRS.addColumn("constrainttype"); + constraintRS.addColumn("deferrable"); + constraintRS.addColumn("deferred"); + constraintRS.addColumn("validate"); + constraintRS.addColumn("indexid"); + constraintRS.addColumn("fkeytableId"); + constraintRS.addColumn("updatetype"); + constraintRS.addColumn("deletetype"); + constraintRS.addColumn("matchtype"); + constraintRS.addColumn("expr"); + constraintRS.addColumn("columnlist"); + constraintRS.addColumn("fkeycolumnlist"); + constraintRS.addColumn("const_def"); + constraintRS.addColumn("tablespace"); + constraintRS.addRow(new Object[] {1, 1, 1, "ConstraintName", + "ConstraintType", false, false, false, 1, 1, "", "", "", "", + "{1}", "1", "", "constraint_tablespace"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_ALL_CONSTRAINTS, constraintRS); + + MockResultSet listnerResultSet = preparedstatementHandler + .createResultSet(); + + listnerResultSet.addColumn("oid"); + listnerResultSet.addColumn("objname"); + listnerResultSet.addColumn("namespace"); + listnerResultSet.addColumn("ret"); + listnerResultSet.addColumn("alltype"); + listnerResultSet.addColumn("nargs"); + listnerResultSet.addColumn("argtype"); + listnerResultSet.addColumn("argname"); + listnerResultSet.addColumn("argmod"); + listnerResultSet.addColumn("secdef"); + listnerResultSet.addColumn("vola"); + listnerResultSet.addColumn("isstrict"); + listnerResultSet.addColumn("retset"); + listnerResultSet.addColumn("procost"); + listnerResultSet.addColumn("setrows"); + listnerResultSet.addColumn("lang"); + + ObjectParameter retParam = new ObjectParameter(); + retParam.setDataType("int"); + retParam.setName("a"); + retParam.setType(PARAMETERTYPE.IN); + + listnerResultSet.addRow(new Object[] {new Integer(2), "function2", 1, + new Integer(16), null, "1", "20 21 21", "{arg1, arg2, arg3}", + "{i,o,b}", false, "volatile", false, false, 10, 10, "plpgsql"}); + + /* + * listnerResultSet.addRow(new Object[] {2, "function2", 1, new + * Integer(16), null, "1", "20 21 21", "{arg1, arg2, arg3}", "{i,o,b}", + * false, "volatile", false, false, 10, 10, "plpgsql"}); + * listnerResultSet.addRow(new Object[] {3, "function2", 1, new + * Integer(16), null, "1", "20 21 21", "{arg1, arg2, arg3}", "{i,o,b}", + * false, "volatile", false, false, 10, 10, "sql"}); + */ + setResultSet(listnerResultSet); + + preparedstatementHandler.prepareResultSet(GET_ALL_FUNCTION_QUERY, + listnerResultSet); + + MockResultSet triggerResultSet = preparedstatementHandler + .createResultSet(); + + triggerResultSet.addColumn("oid"); + triggerResultSet.addColumn("objname"); + triggerResultSet.addColumn("namespace"); + triggerResultSet.addColumn("ret"); + triggerResultSet.addColumn("alltype"); + triggerResultSet.addColumn("nargs"); + triggerResultSet.addColumn("argtype"); + triggerResultSet.addColumn("argname"); + triggerResultSet.addColumn("argmod"); + triggerResultSet.addColumn("secdef"); + triggerResultSet.addColumn("vola"); + triggerResultSet.addColumn("isstrict"); + triggerResultSet.addColumn("retset"); + triggerResultSet.addColumn("procost"); + triggerResultSet.addColumn("setrows"); + + ObjectParameter tretParam = new ObjectParameter(); + tretParam.setDataType("int"); + tretParam.setName("a"); + tretParam.setType(PARAMETERTYPE.IN); + + triggerResultSet.addRow(new Object[] {new Integer(1), "trigger1", 1, + new Integer(2279), null, null, null, null, "mode", false, + "volatile", false, false, 10, 10}); + + preparedstatementHandler.prepareResultSet(GET_ALL_TRIGGER_QUERY, + triggerResultSet); + + getViewMockRS(preparedstatementHandler); + + MockResultSet searchpath = preparedstatementHandler.createResultSet(); + searchpath.addColumn("search_path"); + + searchpath.addRow(new Object[] {"PUBLIC,abc,pg_catalog"}); + preparedstatementHandler.prepareResultSet("SHOW search_path", + searchpath); + MockResultSet refreshtablemetada = preparedstatementHandler + .createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "MyTable", 1, 1, true, + "description", "1 2", ""}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.Refresh_TABLEMETADATA, refreshtablemetada); + + MockResultSet colmetadataRS1 = preparedstatementHandler + .createResultSet(); + colmetadataRS1.addColumn("tableid"); + colmetadataRS1.addColumn("namespaceid"); + colmetadataRS1.addColumn("columnidx"); + colmetadataRS1.addColumn("name"); + colmetadataRS1.addColumn("datatypeoid"); + colmetadataRS1.addColumn("dtns"); + colmetadataRS1.addColumn("length"); + colmetadataRS1.addColumn("precision"); + colmetadataRS1.addColumn("dimentions"); + colmetadataRS1.addColumn("notnull"); + colmetadataRS1.addColumn("isdefaultvalueavailable"); + colmetadataRS1.addColumn("default_value"); + colmetadataRS1.addColumn("attDefStr"); + colmetadataRS1.addColumn("displayColumns"); + + colmetadataRS1.addRow(new Object[] {1, 1, 1, "ColName", 1, 1, 200, 0, 0, + false, true, "Default value", "attrString", ""}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_ALL_COLUMN_METADATA_OVERLOADED_METHOD, + colmetadataRS1); + + MockResultSet fetchalltablemetada = preparedstatementHandler + .createResultSet(); + fetchalltablemetada.addColumn("oid"); + fetchalltablemetada.addColumn("relname"); + fetchalltablemetada.addColumn("relnamespace"); + fetchalltablemetada.addColumn("reloptions"); + fetchalltablemetada.addColumn("reltablespace"); + fetchalltablemetada.addColumn("relpersistence"); + fetchalltablemetada.addColumn("desc"); + fetchalltablemetada.addColumn("nodes"); + + fetchalltablemetada + .addRow(new Object[] {1, "pg_db_role_setting_mytable", 1, "", 1, + true, "description", "1 2"}); + + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.FETCH_ALL_TABLEMETADATA, fetchalltablemetada); + + MockResultSet getallftablesinschema = preparedstatementHandler + .createResultSet(); + getallftablesinschema.addColumn("oid"); + getallftablesinschema.addColumn("relname"); + getallftablesinschema.addColumn("relnamespace"); + getallftablesinschema.addColumn("reltablespace"); + getallftablesinschema.addColumn("relpersistence"); + getallftablesinschema.addColumn("desc"); + getallftablesinschema.addColumn("nodes"); + getallftablesinschema.addColumn("reloptions"); + getallftablesinschema.addColumn("ftoptions"); + getallftablesinschema.addColumn("parttype"); + getallftablesinschema.addColumn("partkey"); + + getallftablesinschema.addRow(new Object[] {1, "MyTable", 1, 1, true, + "description", "1 2", "", "gsfs", "n", "abc"}); + + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_ALL_FTABLES_IN_SCHEMA, + getallftablesinschema); + + MockResultSet getcolumninfoRSftble = preparedstatementHandler + .createResultSet(); + getcolumninfoRSftble.addColumn("tableid"); + getcolumninfoRSftble.addColumn("namespaceid"); + getcolumninfoRSftble.addColumn("columnidx"); + getcolumninfoRSftble.addColumn("name"); + getcolumninfoRSftble.addColumn("datatypeoid"); + getcolumninfoRSftble.addColumn("dtns"); + getcolumninfoRSftble.addColumn("length"); + getcolumninfoRSftble.addColumn("precision"); + getcolumninfoRSftble.addColumn("dimentions"); + getcolumninfoRSftble.addColumn("notnull"); + getcolumninfoRSftble.addColumn("isdefaultvalueavailable"); + getcolumninfoRSftble.addColumn("default_value"); + getcolumninfoRSftble.addColumn("attDefStr"); + getcolumninfoRSftble.addColumn("displayColumns"); + getcolumninfoRSftble.addRow(new Object[] {1, 1, 1, "ColName", 1, 1, 200, + 0, 0, false, true, "Default value", "attrString", "bigint"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_COLUMN_INFO_FOREIGN_TABLES, + getcolumninfoRSftble); + + MockResultSet getAllPartitionatable = preparedstatementHandler + .createResultSet(); + getAllPartitionatable.addColumn("oid"); + getAllPartitionatable.addColumn("relname"); + getAllPartitionatable.addColumn("relnamespace"); + getAllPartitionatable.addColumn("reltablespace"); + getAllPartitionatable.addColumn("relpersistence"); + getAllPartitionatable.addColumn("desc"); + getAllPartitionatable.addColumn("nodes"); + getAllPartitionatable.addColumn("reloptions"); + getAllPartitionatable.addColumn("partkey"); + + getAllPartitionatable.addRow(new Object[] {1, "MyPartTable", 1, 1, true, + "description", "1 2", "", "1"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_ALL_PARTITION_TABLES, getAllPartitionatable); + + MockResultSet getcolumninfoRSptble = preparedstatementHandler + .createResultSet(); + getcolumninfoRSptble.addColumn("tableid"); + getcolumninfoRSptble.addColumn("namespaceid"); + getcolumninfoRSptble.addColumn("columnidx"); + getcolumninfoRSptble.addColumn("name"); + getcolumninfoRSptble.addColumn("datatypeoid"); + getcolumninfoRSptble.addColumn("dtns"); + getcolumninfoRSptble.addColumn("length"); + getcolumninfoRSptble.addColumn("precision"); + getcolumninfoRSptble.addColumn("dimentions"); + getcolumninfoRSptble.addColumn("notnull"); + getcolumninfoRSptble.addColumn("isdefaultvalueavailable"); + getcolumninfoRSptble.addColumn("default_value"); + getcolumninfoRSptble.addColumn("attDefStr"); + getcolumninfoRSptble.addColumn("displayColumns"); + getcolumninfoRSptble.addRow(new Object[] {1, 1, 1, "ColName", 1, 1, 200, + 0, 0, false, true, "Default value", "attrString", "bigint"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_COLUMN_INFO_PARTITION_TABLES, + getcolumninfoRSptble); + + MockResultSet getPartitionsRS = preparedstatementHandler + .createResultSet(); + getPartitionsRS.addColumn("partition_id"); + getPartitionsRS.addColumn("partition_name"); + getPartitionsRS.addColumn("table_id"); + + getPartitionsRS.addRow(new Object[] {1, "part_1", 1}); + preparedstatementHandler.prepareResultSet(CommonLLTUtils.GET_PARTITIONS, + getPartitionsRS); + + /* + * MockResultSet getPartitionsRS1 = preparedstatementHandler + * .createResultSet(); getPartitionsRS.addColumn("partition_id"); + * getPartitionsRS.addColumn("partition_name"); + * getPartitionsRS.addColumn("table_id"); + * + * getPartitionsRS.addRow(new Object[] {1, "part_1", 1}); + * preparedstatementHandler.prepareResultSet( + * CommonLLTUtils.GET_PARTITIONS_OVERLOADED, getPartitionsRS); + */ + + MockResultSet indexpartitionRS = preparedstatementHandler + .createResultSet(); + indexRS.addColumn("oid"); + indexRS.addColumn("tableId"); + indexRS.addColumn("indexname"); + indexRS.addColumn("namespaceid"); + indexRS.addColumn("accessmethodid"); + indexRS.addColumn("isunique"); + indexRS.addColumn("isprimary"); + indexRS.addColumn("isexclusion"); + indexRS.addColumn("isimmediate"); + indexRS.addColumn("isclustered"); + indexRS.addColumn("checkmin"); + indexRS.addColumn("isready"); + indexRS.addColumn("cols"); + indexRS.addColumn("reloptions"); + indexRS.addColumn("indexdef"); + indexRS.addColumn("tablespace"); + indexRS.addRow(new Object[] {1, 1, "IndexName", 1, 1, true, false, + false, false, false, false, false, "1", "", "", ""}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_PARTITION_INDEXES, indexpartitionRS); + + MockResultSet partitionConstraintRS = preparedstatementHandler + .createResultSet(); + partitionConstraintRS.addColumn("constraintid"); + partitionConstraintRS.addColumn("tableid"); + partitionConstraintRS.addColumn("namespaceid"); + partitionConstraintRS.addColumn("constraintname"); + partitionConstraintRS.addColumn("constrainttype"); + partitionConstraintRS.addColumn("deferrable"); + partitionConstraintRS.addColumn("deferred"); + partitionConstraintRS.addColumn("validate"); + partitionConstraintRS.addColumn("indexid"); + partitionConstraintRS.addColumn("fkeytableId"); + partitionConstraintRS.addColumn("updatetype"); + partitionConstraintRS.addColumn("deletetype"); + partitionConstraintRS.addColumn("matchtype"); + partitionConstraintRS.addColumn("expr"); + partitionConstraintRS.addColumn("columnlist"); + partitionConstraintRS.addColumn("fkeycolumnlist"); + partitionConstraintRS.addColumn("const_def"); + partitionConstraintRS.addRow(new Object[] {1, 1, 1, "ConstraintName", + "ConstraintType", false, false, false, 1, 1, "", "", "", "", + "{1}", "1", ""}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_PARTITION_CONSTRAINTS, + partitionConstraintRS); + + MockResultSet refreshDatatypeRS = preparedstatementHandler + .createResultSet(); + /* + * refreshDatatypeRS.addColumn("oid"); + * refreshDatatypeRS.addColumn("typname"); + * refreshDatatypeRS.addColumn("typnamespace"); + * refreshDatatypeRS.addColumn("typbyval"); + * refreshDatatypeRS.addColumn("displaycolumns"); + * refreshDatatypeRS.addColumn("typarray"); + * refreshDatatypeRS.addColumn("typcategory"); + * refreshDatatypeRS.addColumn("typtype"); + * refreshDatatypeRS.addColumn("typlen"); + * refreshDatatypeRS.addColumn("typnotnull"); + * refreshDatatypeRS.addColumn("typtypmod"); + * refreshDatatypeRS.addColumn("desc"); + */ + + refreshDatatypeRS.addColumn("oid"); + refreshDatatypeRS.addColumn("typname"); + refreshDatatypeRS.addColumn("typnamespace"); + refreshDatatypeRS.addColumn("typlen"); + refreshDatatypeRS.addColumn("displaycolumns"); + refreshDatatypeRS.addColumn("typbyval"); + refreshDatatypeRS.addColumn("typtype"); + refreshDatatypeRS.addColumn("typcategory"); + refreshDatatypeRS.addColumn("typtypmod"); + refreshDatatypeRS.addColumn("typnotnull"); + refreshDatatypeRS.addColumn("typarray"); + refreshDatatypeRS.addColumn("desc"); + refreshDatatypeRS.addRow( + new Object[] {1, "bigint", 1, 1, "character", true, "type", + "category", 1, true, 12, "description", "bigint"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_REFRESH_DATATYPE, refreshDatatypeRS); + + //For serverIp + MockResultSet serverResultset= preparedstatementHandler.createResultSet(); + serverResultset.addColumn("inet_server_addr"); + serverResultset.addRow( new Object[]{"127.0.0.1"}); + preparedstatementHandler.prepareResultSet(FETCH_SERVER_IP, + serverResultset); + + MockResultSet getUserRoleRs = preparedstatementHandler.createResultSet(); + getUserRoleRs.addColumn("rolname"); + getUserRoleRs.addColumn("rolcanlogin"); + getUserRoleRs.addColumn("oid"); + getUserRoleRs.addRow(new Object[] {"chris", true, 16408}); + getUserRoleRs.addRow(new Object[] {"tom", false, 16410}); + preparedstatementHandler.prepareResultSet( + "SELECT rolname,rolcanlogin,oid FROM pg_catalog.pg_roles WHERE rolsuper = false;", getUserRoleRs); + + mockServerEncoding(preparedstatementHandler); + } + + public static void mockCheckDebugSupport(PreparedStatementResultSetHandler preparedstatementHandler) { + MockResultSet debugCheckTest = preparedstatementHandler.createResultSet(); + debugCheckTest.addColumn("count"); + debugCheckTest.addRow(new Object[] {0}); + preparedstatementHandler.prepareResultSet( + CHECK_DEBUG, debugCheckTest); + } + + public static void mockCheckExplainPlanSupport(PreparedStatementResultSetHandler preparedstatementHandler) { + MockResultSet debugCheckTest = preparedstatementHandler.createResultSet(); + debugCheckTest.addColumn("QUERY PLAN"); + debugCheckTest.addRow(new Object[] {"Result (cost=0.00..0.01 rows=1 width=0)"}); + preparedstatementHandler.prepareResultSet( + CHECK_EXPLAIN_PLAN, debugCheckTest); + } + + public static void mockServerEncoding(PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet serverEncodingRs = preparedstatementHandler.createResultSet(); + serverEncodingRs.addColumn("server_encoding"); + serverEncodingRs.addRow(new Object[] {"UTF-8"}); + preparedstatementHandler.prepareResultSet("show server_encoding", serverEncodingRs); + } + + public static void prepareProxyInfoForRs( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet allIndexes_rs_1 = preparedstatementHandler + .createResultSet(); + allIndexes_rs_1.addColumn("oid"); + allIndexes_rs_1.addColumn("tableId"); + allIndexes_rs_1.addColumn("indexname"); + allIndexes_rs_1.addColumn("namespaceid"); + allIndexes_rs_1.addColumn("accessmethodid"); + allIndexes_rs_1.addColumn("isunique"); + allIndexes_rs_1.addColumn("isprimary"); + allIndexes_rs_1.addColumn("isexclusion"); + allIndexes_rs_1.addColumn("isimmediate"); + allIndexes_rs_1.addColumn("isclustered"); + allIndexes_rs_1.addColumn("checkmin"); + allIndexes_rs_1.addColumn("isready"); + allIndexes_rs_1.addColumn("cols"); + allIndexes_rs_1.addColumn("reloptions"); + allIndexes_rs_1.addColumn("indexdef"); + + allIndexes_rs_1.addRow(new Object[] {1, 1, "IndexName", 1, 1, true, + false, false, false, false, false, false, "0", "", ""}); + preparedstatementHandler.prepareResultSet(CommonLLTUtils.ALLCONSTRAIN_2, + allIndexes_rs_1); + } + + public static void prepareProxyInfoForDB( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet datatypeRS_1 = preparedstatementHandler.createResultSet(); + datatypeRS_1.addColumn("oid"); + datatypeRS_1.addColumn("typname"); + datatypeRS_1.addColumn("typnamespace"); + datatypeRS_1.addColumn("typlen"); + datatypeRS_1.addColumn("typbyval"); + datatypeRS_1.addColumn("typtype"); + datatypeRS_1.addColumn("typcategory"); + datatypeRS_1.addColumn("typtypmod"); + datatypeRS_1.addColumn("typnotnull"); + datatypeRS_1.addColumn("typarray"); + datatypeRS_1.addColumn("desc"); + datatypeRS_1.addColumn("displaycolumns"); + + datatypeRS_1.addRow(new Object[] {1, "bpchar", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {2, "int8", 1, 1, true, "type", + "category", 1, true, 12, "description2", ""}); + + datatypeRS_1.addRow(new Object[] {3, "bit", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {4, "varbit", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {5, "bool", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {6, "box", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {7, "bytea", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {8, "varchar", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {9, "char", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {10, "cidr", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {11, "circle", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {12, "date", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + + datatypeRS_1.addRow(new Object[] {13, "float8", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {14, "inet", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {15, "int4", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {16, "interval", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {17, "line", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {18, "lseg", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {19, "macaddr", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {20, "money", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {21, "numeric", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {22, "numeric", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {23, "path", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {24, "point", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {25, "polygon", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {26, "float4", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {27, "int2", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + + datatypeRS_1.addRow(new Object[] {28, "text", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {29, "time", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {30, "timetz", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {31, "timestamp", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {32, "timestamptz", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {33, "tsquery", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {34, "tsvector", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {35, "txid_snapshot", 1, 1, true, + "type", "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {36, "uuid", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {37, "xml", 1, 1, true, "type", + "category", 1, true, 12, "description", ""}); + datatypeRS_1.addRow(new Object[] {38, "char", 1, 1, true, "char", + "category", 1, true, 12, "description", ""}); + + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_ALL_DATATYPE_DB, datatypeRS_1); + } + + public static void getAllNodes( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet getnoders = preparedstatementHandler.createResultSet(); + getnoders.addColumn("oid"); + getnoders.addColumn("node_name"); + getnoders.addColumn("node_type"); + getnoders.addColumn("node_port"); + getnoders.addColumn("node_host"); + getnoders.addColumn("nodeis_primary"); + getnoders.addColumn("nodeis_preferred"); + getnoders.addColumn("node_id"); + + getnoders.addRow(new Object[] {1, "Node_1", "C", 23456, "1.0.0.0", true, + true, 12}); + preparedstatementHandler.prepareResultSet( + "select oid, node_name, node_type, node_port, node_host, nodeis_primary, nodeis_preferred, node_id from pgxc_node;", + getnoders); + } + + /* + * public static void getAllDatatypeExpection( + * PreparedStatementResultSetHandler preparedstatementHandler) { + * MockResultSet datatypeRS = preparedstatementHandler.createResultSet(); + * datatypeRS.addColumn("oid"); datatypeRS.addColumn("typname"); + * datatypeRS.addColumn("typnamespace"); datatypeRS.addColumn("typlen"); + * datatypeRS.addColumn("typbyval"); datatypeRS.addColumn("typtype"); + * datatypeRS.addColumn("typcategory"); datatypeRS.addColumn("typtypmod"); + * datatypeRS.addColumn("typnotnull"); datatypeRS.addColumn("typarray"); + * datatypeRS.addColumn("desc"); datatypeRS.addColumn("displaycolumns"); // + * datatypeRS.addRow(new Object[]{1, "bigint", 1, 1, true, // + * "type","category", 1, true, 12, "description"}); datatypeRS.addRow(new + * Object[] {2, "int8", 1, 1, true, "type", "category", 1, true, 12, + * "description2"}); + * + * datatypeRS.addRow(new Object[] {3, "bit", 1, 1, true, "type", "category", + * 1, true, 12, "description"}); datatypeRS.addRow(new Object[] {4, + * "varbit", 1, 1, true, "type", "category", 1, true, 12, "description"}); + * datatypeRS.addRow(new Object[] {5, "bool", 1, 1, true, "type", + * "category", 1, true, 12, "description"}); datatypeRS.addRow(new Object[] + * {6, "box", 1, 1, true, "type", "category", 1, true, 12, "description"}); + * datatypeRS.addRow(new Object[] {7, "bytea", 1, 1, true, "type", + * "category", 1, true, 12, "description"}); datatypeRS.addRow(new Object[] + * {8, "varchar", 1, 1, true, "type", "category", 1, true, 12, + * "description"}); datatypeRS.addRow(new Object[] {9, "char", 1, 1, true, + * "type", "category", 1, true, 12, "description"}); datatypeRS.addRow(new + * Object[] {10, "cidr", 1, 1, true, "type", "category", 1, true, 12, + * "description"}); datatypeRS.addRow(new Object[] {11, "circle", 1, 1, + * true, "type", "category", 1, true, 12, "description"}); + * datatypeRS.addRow(new Object[] {12, "date", 1, 1, true, "type", + * "category", 1, true, 12, "description"}); + * + * datatypeRS.addRow(new Object[] {13, "float8", 1, 1, true, "type", + * "category", 1, true, 12, "description"}); datatypeRS.addRow(new Object[] + * {14, "inet", 1, 1, true, "type", "category", 1, true, 12, + * "description"}); datatypeRS.addRow(new Object[] {15, "int4", 1, 1, true, + * "type", "category", 1, true, 12, "description"}); datatypeRS.addRow(new + * Object[] {16, "interval", 1, 1, true, "type", "category", 1, true, 12, + * "description"}); datatypeRS.addRow(new Object[] {17, "line", 1, 1, true, + * "type", "category", 1, true, 12, "description"}); datatypeRS.addRow(new + * Object[] {18, "lseg", 1, 1, true, "type", "category", 1, true, 12, + * "description"}); datatypeRS.addRow(new Object[] {19, "macaddr", 1, 1, + * true, "type", "category", 1, true, 12, "description"}); + * datatypeRS.addRow(new Object[] {20, "money", 1, 1, true, "type", + * "category", 1, true, 12, "description"}); datatypeRS.addRow(new Object[] + * {21, "numeric", 1, 1, true, "type", "category", 1, true, 12, + * "description"}); datatypeRS.addRow(new Object[] {22, "numeric", 1, 1, + * true, "type", "category", 1, true, 12, "description"}); + * datatypeRS.addRow(new Object[] {23, "path", 1, 1, true, "type", + * "category", 1, true, 12, "description"}); datatypeRS.addRow(new Object[] + * {24, "point", 1, 1, true, "type", "category", 1, true, 12, + * "description"}); datatypeRS.addRow(new Object[] {25, "polygon", 1, 1, + * true, "type", "category", 1, true, 12, "description"}); + * datatypeRS.addRow(new Object[] {26, "float4", 1, 1, true, "type", + * "category", 1, true, 12, "description"}); datatypeRS.addRow(new Object[] + * {27, "int2", 1, 1, true, "type", "category", 1, true, 12, + * "description"}); + * + * datatypeRS.addRow(new Object[] {28, "text", 1, 1, true, "type", + * "category", 1, true, 12, "description"}); datatypeRS.addRow(new Object[] + * {29, "time", 1, 1, true, "type", "category", 1, true, 12, + * "description"}); datatypeRS.addRow(new Object[] {30, "timetz", 1, 1, + * true, "type", "category", 1, true, 12, "description"}); + * datatypeRS.addRow(new Object[] {31, "timestamp", 1, 1, true, "type", + * "category", 1, true, 12, "description"}); datatypeRS.addRow(new Object[] + * {32, "timestamptz", 1, 1, true, "type", "category", 1, true, 12, + * "description"}); datatypeRS.addRow(new Object[] {33, "tsquery", 1, 1, + * true, "type", "category", 1, true, 12, "description"}); + * datatypeRS.addRow(new Object[] {34, "tsvector", 1, 1, true, "type", + * "category", 1, true, 12, "description"}); datatypeRS.addRow(new Object[] + * {35, "txid_snapshot", 1, 1, true, "type", "category", 1, true, 12, + * "description"}); datatypeRS.addRow(new Object[] {36, "uuid", 1, 1, true, + * "type", "category", 1, true, 12, "description"}); datatypeRS.addRow(new + * Object[] {37, "xml", 1, 1, true, "type", "category", 1, true, 12, + * "description"}); + * + * preparedstatementHandler + * .prepareResultSet(CommonLLTUtils.GET_ALL_DATATYPE, datatypeRS); } + */ + + public static void createDataBaseRS( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("oid"); + getdbsrs.addColumn("datname"); + + getdbsrs.addRow(new Object[] {1, "Gauss"}); + getdbsrs.addRow(new Object[] {2, "tempdb"}); + + preparedstatementHandler.prepareResultSet( + "select oid, datname from pg_database where datistemplate='f'", + getdbsrs); + } + + public static void updateDataBaseRS( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("datname"); + getdbsrs.addRow(new Object[] {"tempdb2"}); + preparedstatementHandler.prepareResultSet( + "SELECT datname FROM PG_DATABASE WHERE OID=2", getdbsrs); + + } + + public static void dropDataBaseRS( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("oid"); + getdbsrs.addColumn("datname"); + + getdbsrs.addRow(new Object[] {1, "Gauss"}); + + preparedstatementHandler.prepareResultSet( + "select oid, datname from pg_database where datistemplate='f'", + getdbsrs); + } + + public static void getDataBasePtropertiesRS( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("oid"); + getdbsrs.addColumn("name"); + getdbsrs.addColumn("encoding"); + getdbsrs.addColumn("allow_conn"); + getdbsrs.addColumn("max_conn_limit"); + getdbsrs.addColumn("default_tablespace"); + getdbsrs.addColumn("collation"); + getdbsrs.addColumn("char_type"); + + getdbsrs.addRow(new Object[] {1, "Gauss", "UTF-8", "Yes", "100", + "Defauly Tablespace", "Collation", "Charset..."}); + + preparedstatementHandler.prepareResultSet( + "SELECT oid as oid, datname AS name, pg_encoding_to_char(encoding) as encoding, datallowconn as allow_conn, " + + "datconnlimit as max_conn_limit, (select spcname from pg_tablespace where oid=dattablespace) as default_tablespace, datcollate as collation, datctype as char_type from pg_database where oid = 1;", + getdbsrs); + } + + public static void getDataBasePtropertiesemptyRS( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("oid"); + getdbsrs.addColumn("name"); + getdbsrs.addColumn("encoding"); + getdbsrs.addColumn("allow_conn"); + getdbsrs.addColumn("max_conn_limit"); + getdbsrs.addColumn("default_tablespace"); + getdbsrs.addColumn("collation"); + getdbsrs.addColumn("char_type"); + + getdbsrs.addRow(new Object[] {}); + + preparedstatementHandler.prepareResultSet( + "SELECT oid as oid, datname AS name, pg_encoding_to_char(encoding) as encoding, datallowconn as allow_conn, " + + "datconnlimit as max_conn_limit, (select spcname from pg_tablespace where oid=dattablespace) as default_tablespace, datcollate as collation, datctype as char_type from pg_database where oid = 23;", + getdbsrs); + } + + public static void refreshDebugObjectRS( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String REFRESH_DBG_OBJ_QRY = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, " + + "pr.prorettype ret, pr.proallargtypes alltype,pr.pronargs nargs,pr.proargtypes argtype, " + + "pr.proargnames argname,pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, " + + "pr.proisstrict isstrict, pr.proretset retset, pr.procost procost, pr.prorows setrows" + + " FROM pg_proc pr WHERE oid = 2"; + + MockResultSet listnerResultSet = preparedstatementHandler + .createResultSet(); + + listnerResultSet.addColumn("oid"); + listnerResultSet.addColumn("objname"); + listnerResultSet.addColumn("namespace"); + listnerResultSet.addColumn("ret"); + listnerResultSet.addColumn("alltype"); + listnerResultSet.addColumn("nargs"); + listnerResultSet.addColumn("argtype"); + listnerResultSet.addColumn("argname"); + listnerResultSet.addColumn("argmod"); + listnerResultSet.addColumn("secdef"); + listnerResultSet.addColumn("vola"); + listnerResultSet.addColumn("isstrict"); + listnerResultSet.addColumn("retset"); + listnerResultSet.addColumn("procost"); + listnerResultSet.addColumn("setrows"); + listnerResultSet.addColumn("lang"); + + ObjectParameter retParam = new ObjectParameter(); + retParam.setDataType("int"); + retParam.setName("a"); + retParam.setType(PARAMETERTYPE.IN); + + listnerResultSet.addRow(new Object[] {new Integer(2), "function2", 1, + new Integer(16), null, null, null, null, "mode", false, + "volatile", false, false, 10, 10, "plpgsql"}); + + preparedstatementHandler.prepareResultSet(REFRESH_DBG_OBJ_QRY, + listnerResultSet); + + } + + public static void refreshDebugObjectRS2( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String REFRESH_DBG_OBJ_QRY = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, " + + "pr.prorettype ret, pr.proallargtypes alltype,pr.pronargs nargs,pr.proargtypes argtype, " + + "pr.proargnames argname,pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, " + + "pr.proisstrict isstrict, pr.proretset retset, pr.procost procost, pr.prorows setrows, " + + "lng.lanname lang " + + "FROM pg_proc pr JOIN pg_language lng ON lng.oid=pr.prolang WHERE lng.lanname in ('plpgsql','sql') and oid = 1"; + + MockResultSet listnerResultSet = preparedstatementHandler + .createResultSet(); + + listnerResultSet.addColumn("oid"); + listnerResultSet.addColumn("objname"); + listnerResultSet.addColumn("namespace"); + listnerResultSet.addColumn("ret"); + listnerResultSet.addColumn("alltype"); + listnerResultSet.addColumn("nargs"); + listnerResultSet.addColumn("argtype"); + listnerResultSet.addColumn("argname"); + listnerResultSet.addColumn("argmod"); + listnerResultSet.addColumn("secdef"); + listnerResultSet.addColumn("vola"); + listnerResultSet.addColumn("isstrict"); + listnerResultSet.addColumn("retset"); + listnerResultSet.addColumn("procost"); + listnerResultSet.addColumn("setrows"); + listnerResultSet.addColumn("lang"); + + ObjectParameter retParam = new ObjectParameter(); + retParam.setDataType("int"); + retParam.setName("a"); + retParam.setType(PARAMETERTYPE.IN); + + listnerResultSet.addRow(new Object[] {new Integer(2), "function2", 1, + new Integer(2279), null, null, null, null, "mode", false, + "volatile", false, false, 10, 10, "plpgsql"}); + + preparedstatementHandler.prepareResultSet(REFRESH_DBG_OBJ_QRY, + listnerResultSet); + + } + + public static void refreshDebugObjectRS3( + PreparedStatementResultSetHandler preparedstatementHandler) + { + + String REFRESH_DBG_OBJ_QRY = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype,pr.pronargs nargs,pr.proargtypes argtype, pr.proargnames argname,pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, pr.proisstrict isstrict, pr.proretset retset, pr.procost procost, pr.prorows setrows, lng.lanname lang FROM pg_proc pr JOIN pg_language lng ON lng.oid=pr.prolang WHERE lng.lanname in ('plpgsql','sql') and oid = 1"; + MockResultSet listnerResultSet = preparedstatementHandler + .createResultSet(); + + listnerResultSet.addColumn("oid"); + listnerResultSet.addColumn("objname"); + listnerResultSet.addColumn("namespace"); + listnerResultSet.addColumn("ret"); + listnerResultSet.addColumn("alltype"); + listnerResultSet.addColumn("nargs"); + listnerResultSet.addColumn("argtype"); + listnerResultSet.addColumn("argname"); + listnerResultSet.addColumn("argmod"); + listnerResultSet.addColumn("secdef"); + listnerResultSet.addColumn("vola"); + listnerResultSet.addColumn("isstrict"); + listnerResultSet.addColumn("retset"); + listnerResultSet.addColumn("procost"); + listnerResultSet.addColumn("setrows"); + listnerResultSet.addColumn("lang"); + + ObjectParameter retParam = new ObjectParameter(); + retParam.setDataType("int"); + retParam.setName("a"); + retParam.setType(PARAMETERTYPE.IN); + + listnerResultSet.addRow(new Object[] {new Integer(2), null, 1, + new Integer(2279), null, null, null, null, "mode", false, + "volatile", false, false, 10, 10, "plpgsql"}); + + preparedstatementHandler.prepareResultSet(REFRESH_DBG_OBJ_QRY, + listnerResultSet); + + } + + public static void fetchNamespaceRS( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String REFRESH_DBG_OBJ_QRY = "SELECT oid, nspname from pg_namespace WHERE oid=1"; + + MockResultSet listnerResultSet = preparedstatementHandler + .createResultSet(); + + listnerResultSet.addColumn("oid"); + listnerResultSet.addColumn("nspname"); + + listnerResultSet.addRow(new Object[] {new Integer(3), "PUBLIC"}); + + preparedstatementHandler.prepareResultSet(REFRESH_DBG_OBJ_QRY, + listnerResultSet); + + MockResultSet colmetadataRS = preparedstatementHandler + .createResultSet(); + colmetadataRS.addColumn("tableid"); + colmetadataRS.addColumn("namespaceid"); + colmetadataRS.addColumn("columnidx"); + colmetadataRS.addColumn("name"); + colmetadataRS.addColumn("datatypeoid"); + colmetadataRS.addColumn("dtns"); + colmetadataRS.addColumn("length"); + colmetadataRS.addColumn("precision"); + colmetadataRS.addColumn("dimentions"); + colmetadataRS.addColumn("notnull"); + colmetadataRS.addColumn("isdefaultvalueavailable"); + colmetadataRS.addColumn("default_value"); + + String colmetadata = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, " + + "c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, " + + "c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value " + + "from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.relkind = 'r') " + + "left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) " + + "where c.attisdropped = 'f' and c.attnum > 0 and t.relnamespace = " + + 1 + " order by t.oid, c.attnum;"; + + colmetadataRS.addRow(new Object[] {1, 1, 1, "ColName", 1, 1, 200, 0, 0, + false, true, "Default value"}); + preparedstatementHandler.prepareResultSet(colmetadata, colmetadataRS); + + MockResultSet tablemetadataRS = preparedstatementHandler + .createResultSet(); + tablemetadataRS.addColumn("oid"); + tablemetadataRS.addColumn("relname"); + tablemetadataRS.addColumn("relnamespace"); + tablemetadataRS.addColumn("reltablespace"); + tablemetadataRS.addColumn("relpersistence"); + tablemetadataRS.addColumn("desc"); + tablemetadataRS.addColumn("nodes"); + + tablemetadataRS.addRow( + new Object[] {1, "MyTable", 1, 1, true, "description", "1 2"}); + preparedstatementHandler.prepareResultSet( + "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes " + + "from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) " + + "left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.relnamespace = " + + 1 + ';', + tablemetadataRS); + + } + + public static void runOnSQLTerminalRS( + PreparedStatementResultSetHandler statementHandler) + { + String REFRESH_DBG_OBJ_QRY = "select * from tbl1"; + + MockResultSet listnerResultSet = statementHandler.createResultSet(); + + listnerResultSet.addColumn("id"); + listnerResultSet.addColumn("name"); + + listnerResultSet.addRow(new Object[] {new Integer(1), "PUBLIC"}); + listnerResultSet.addRow(new Object[] {new Integer(2), null}); + + statementHandler.prepareResultSet(REFRESH_DBG_OBJ_QRY, + listnerResultSet); + + } + + public static void runOnSQLTerminalBytesRS(PreparedStatementResultSetHandler statementHandler) { + String REFRESH_DBG_OBJ_QRY = "select * from bytes_table"; + + MockResultSet listnerResultSet = statementHandler.createResultSet(); + + listnerResultSet.addColumn("byte1"); + listnerResultSet.addColumn("byte2"); + listnerResultSet.addColumn("byte3"); + listnerResultSet.addColumn("byte4"); + listnerResultSet.addColumn("byte5"); + + listnerResultSet.addRow(new Object[] {new byte[] {10, 11, 12}, new byte[] {10, 11, 12}, new byte[] {10, 11, 12}, + new byte[] {10, 11, 12}, new byte[] {10, 11, 12}}); + + statementHandler.prepareResultSet(REFRESH_DBG_OBJ_QRY, listnerResultSet); + + } + + public static void renameRS( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String REFRESH_DBG_OBJ_QRY = ""; + + MockResultSet colmetadataRS = preparedstatementHandler + .createResultSet(); + colmetadataRS.addColumn("tableid"); + colmetadataRS.addColumn("namespaceid"); + colmetadataRS.addColumn("columnidx"); + colmetadataRS.addColumn("name"); + colmetadataRS.addColumn("datatypeoid"); + colmetadataRS.addColumn("dtns"); + colmetadataRS.addColumn("length"); + colmetadataRS.addColumn("precision"); + colmetadataRS.addColumn("dimentions"); + colmetadataRS.addColumn("notnull"); + colmetadataRS.addColumn("isdefaultvalueavailable"); + colmetadataRS.addColumn("default_value"); + + colmetadataRS.addRow(new Object[] {1, 1, 1, "ColName", 1, 1, 200, 0, 0, + false, true, "Default value"}); + preparedstatementHandler.prepareResultSet(REFRESH_DBG_OBJ_QRY, + colmetadataRS); + + } + + public static void dropRS( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String REFRESH_DBG_OBJ_QRY = ""; + + MockResultSet colmetadataRS = preparedstatementHandler + .createResultSet(); + colmetadataRS.addColumn("tableid"); + colmetadataRS.addColumn("namespaceid"); + colmetadataRS.addColumn("columnidx"); + colmetadataRS.addColumn("name"); + colmetadataRS.addColumn("datatypeoid"); + colmetadataRS.addColumn("dtns"); + colmetadataRS.addColumn("length"); + colmetadataRS.addColumn("precision"); + colmetadataRS.addColumn("dimentions"); + colmetadataRS.addColumn("notnull"); + colmetadataRS.addColumn("isdefaultvalueavailable"); + colmetadataRS.addColumn("default_value"); + + colmetadataRS.addRow(new Object[] {1, 1, 1, "ColName", 1, 1, 200, 0, 0, + false, true, "Default value"}); + preparedstatementHandler.prepareResultSet(REFRESH_DBG_OBJ_QRY, + colmetadataRS); + + } + + public static void createTableRS( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String REFRESH_DBG_OBJ_QRY = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, " + + "c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, " + + "c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value " + + "from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.relkind = 'r') " + + "left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) " + + "where c.attisdropped = 'f' and c.attnum > 0 and t.relnamespace = " + + 1 + " order by t.oid, c.attnum;"; + + MockResultSet colmetadataRS = preparedstatementHandler + .createResultSet(); + colmetadataRS.addColumn("tableid"); + colmetadataRS.addColumn("namespaceid"); + colmetadataRS.addColumn("columnidx"); + colmetadataRS.addColumn("name"); + colmetadataRS.addColumn("datatypeoid"); + colmetadataRS.addColumn("dtns"); + colmetadataRS.addColumn("length"); + colmetadataRS.addColumn("precision"); + colmetadataRS.addColumn("dimentions"); + colmetadataRS.addColumn("notnull"); + colmetadataRS.addColumn("isdefaultvalueavailable"); + colmetadataRS.addColumn("default_value"); + + colmetadataRS.addRow(new Object[] {1, 1, 1, "ColName", 1, 1, 200, 0, 0, + false, true, "Default value"}); + preparedstatementHandler.prepareResultSet(REFRESH_DBG_OBJ_QRY, + colmetadataRS); + + } + + public static void createTableSpaceRS( + PreparedStatementResultSetHandler preparedstatementHandler) + { + + MockResultSet colmetadataRS = preparedstatementHandler + .createResultSet(); + colmetadataRS.addColumn("oid"); + colmetadataRS.addColumn("spcname"); + colmetadataRS.addColumn("spcoptions"); + colmetadataRS.addColumn("location"); + colmetadataRS.addColumn("spcmaxsize"); + colmetadataRS.addColumn("relative"); + colmetadataRS.addRow(new Object[] {1, "tblspc", + new String[] {"spcoptions=options"}, "location", "spcmaxsize", false}); + preparedstatementHandler.prepareResultSet(TBL_SPC_META, colmetadataRS); + + // Stub for Database.fetchTablespaceName() + MockResultSet colNamesRS = preparedstatementHandler.createResultSet(); + colNamesRS.addColumn("spcname"); + + colNamesRS.addRow(new Object[] {"pg_default"}); + preparedstatementHandler.prepareResultSet(TBL_SPC_NAME, colNamesRS); + } + + + public static void createSequence( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet tablemetadataRS = preparedstatementHandler + .createResultSet(); + tablemetadataRS.addColumn("SEQUENCE"); + tablemetadataRS.addColumn("INCREMENT BY"); + tablemetadataRS.addColumn("MINVALUE"); + tablemetadataRS.addColumn("MAXVALUE"); + tablemetadataRS.addColumn("START WITH"); + tablemetadataRS.addColumn("CACHE"); + tablemetadataRS.addColumn("CYCLE"); + // tablemetadataRS.addColumn("OWNED BY"); + + tablemetadataRS.addRow(new Object[] {"pg_catalog.Seq_01", 2, 10, 10000, + 10, 1, "CYCLE"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.REFRESH_SEQUENCE_METADATA, tablemetadataRS); + + } + + public static void createSequenceWithOwner( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet tablemetadataRS = preparedstatementHandler + .createResultSet(); + tablemetadataRS.addColumn("SEQUENCE"); + tablemetadataRS.addColumn("INCREMENT BY"); + tablemetadataRS.addColumn("MINVALUE"); + tablemetadataRS.addColumn("MAXVALUE"); + tablemetadataRS.addColumn("START WITH"); + tablemetadataRS.addColumn("CACHE"); + tablemetadataRS.addColumn("CYCLE"); + tablemetadataRS.addColumn("OWNED BY"); + + tablemetadataRS.addRow(new Object[] {"pg_catalog.Seq_01", 2, 10, 10000, + 10, 1, "CYCLE", "pg_catalog.table1.col1"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.REFRESH_SEQUENCE_METADATA, tablemetadataRS); + + } + + public static void fetchColMetadataForTableRS( + PreparedStatementResultSetHandler preparedstatementHandler) + { + /* + * String REFRESH_DBG_OBJ_QRY = + * "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, " + * + + * "c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, " + * + + * "c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value " + * + + * "from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.relkind = 'r') " + * + + * "left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) " + * + "where c.attisdropped = 'f' and c.attnum > 0 and t.oid = " + 1 + + * " order by t.oid, c.attnum;"; + */ + //String REFRESH_DBG_OBJ_QRY = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.relkind = 'r') left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and t.oid = 1 order by t.oid, c.attnum;"; +//String REFRESH_DBG_OBJ_QRY = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.relkind = 'r' and t.parttype ='n') left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and t.relnamespace = 1 order by t.oid, c.attnum;"; + +String REFRESH_DBG_OBJ_QRY = "WITH tbl AS ( select oid as tableid,relnamespace as namespaceid from pg_class where relnamespace = 1and relkind = 'r' and parttype ='n'), attr AS ( select c.attnum as columnidx,c.attname as name , pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns,c.atttypid as datatypeoid ,c.attlen as length,c.atttypmod as precision,c.attndims as dimentions,c.attnotnull as notnull,c.atthasdef as isdefaultvalueavailable,c.attrelid as tableoid from pg_attribute c where c.attrelid in (select tableid from tbl) and c.attisdropped = 'f' and c.attnum > 0), dtype AS (select typ.typnamespace as dtns,oid from pg_type typ where typ.oid in (select datatypeoid from attr) ), attrdef AS ( select d.adsrc as default_value ,d.adbin as attDefStr ,adrelid,adnum from pg_attrdef d where d.adrelid in ( select oid from tbl) and d.adnum in( select columnidx from attr))select t.tableid as tableid ,t.namespaceid as namespaceid,c.columnidx,c.name,c.displaycolumns,c.datatypeoid,typ.dtns,c.length,c.precision,c.dimentions,c.notnull,c.isdefaultvalueavailable,default_value, d.attDefStr FROM tbl t LEFT JOIN attr c ON(t.tableid = c.tableoid) LEFT JOIN attrdef d ON(t.tableid = d.adrelid AND c.columnidx = d.adnum) LEFT JOIN dtype typ ON (c.datatypeoid = typ.oid) ORDER BY t.tableid ,c.columnidx;"; +MockResultSet colmetadataRS = preparedstatementHandler + .createResultSet(); + colmetadataRS.addColumn("tableid"); + colmetadataRS.addColumn("namespaceid"); + colmetadataRS.addColumn("columnidx"); + colmetadataRS.addColumn("name"); + colmetadataRS.addColumn("displayColumns"); + colmetadataRS.addColumn("datatypeoid"); + colmetadataRS.addColumn("dtns"); + colmetadataRS.addColumn("length"); + colmetadataRS.addColumn("precision"); + colmetadataRS.addColumn("dimentions"); + colmetadataRS.addColumn("notnull"); + colmetadataRS.addColumn("isdefaultvalueavailable"); + colmetadataRS.addColumn("default_value"); + colmetadataRS.addColumn("attDefStr"); + + colmetadataRS.addRow(new Object[] {1, 1, 1, "ColName", "", 1, 1, 200, 0, 0, + false, true, "Default value", ""}); + preparedstatementHandler.prepareResultSet(REFRESH_DBG_OBJ_QRY, + colmetadataRS); + + + String fetchTableClmQuery = "select oid as tableid from pg_class where relnamespace=1 and relkind = 'r' and parttype ='n'"; + MockResultSet fetchViewRS = preparedstatementHandler.createResultSet(); + fetchViewRS.addColumn("tableid"); + fetchViewRS.addRow(new Object[] {1}); + preparedstatementHandler.prepareResultSet(fetchTableClmQuery, fetchViewRS); + + String fecthForeignTableColumns="WITH tbl AS ( select oid as tableid,relnamespace as namespaceid from pg_class where relnamespace = 1and relkind = 'f' and parttype ='n'), attr AS ( select c.attnum as columnidx,c.attname as name , pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns,c.atttypid as datatypeoid ,c.attlen as length,c.atttypmod as precision,c.attndims as dimentions,c.attnotnull as notnull,c.atthasdef as isdefaultvalueavailable,c.attrelid as tableoid from pg_attribute c where c.attrelid in (select tableid from tbl) and c.attisdropped = 'f' and c.attnum > 0), dtype AS (select typ.typnamespace as dtns,oid from pg_type typ where typ.oid in (select datatypeoid from attr) ), attrdef AS ( select d.adsrc as default_value ,d.adbin as attDefStr ,adrelid,adnum from pg_attrdef d where d.adrelid in ( select oid from tbl) and d.adnum in( select columnidx from attr))select t.tableid as tableid ,t.namespaceid as namespaceid,c.columnidx,c.name,c.displaycolumns,c.datatypeoid,typ.dtns,c.length,c.precision,c.dimentions,c.notnull,c.isdefaultvalueavailable,default_value, d.attDefStr FROM tbl t LEFT JOIN attr c ON(t.tableid = c.tableoid) LEFT JOIN attrdef d ON(t.tableid = d.adrelid AND c.columnidx = d.adnum) LEFT JOIN dtype typ ON (c.datatypeoid = typ.oid) ORDER BY t.tableid ,c.columnidx;"; + MockResultSet fecthForeignTableColumnsRS = preparedstatementHandler.createResultSet(); + fecthForeignTableColumnsRS.addColumn("tableid"); + fecthForeignTableColumnsRS.addColumn("namespaceid"); + fecthForeignTableColumnsRS.addColumn("datatypeoid"); + fecthForeignTableColumnsRS.addColumn("dtns"); + fecthForeignTableColumnsRS.addColumn("columnidx"); + fecthForeignTableColumnsRS.addColumn("name"); + fecthForeignTableColumnsRS.addColumn("dimentions"); + fecthForeignTableColumnsRS.addColumn("notnull"); + fecthForeignTableColumnsRS.addColumn("isdefaultvalueavailable"); + fecthForeignTableColumnsRS.addColumn("attDefStr"); + fecthForeignTableColumnsRS.addColumn("default_value"); + fecthForeignTableColumnsRS.addColumn("displayColumns"); + fecthForeignTableColumnsRS.addColumn("precision"); + fecthForeignTableColumnsRS.addColumn("length"); + + fecthForeignTableColumnsRS.addRow(new Object[] {1,1,1,1,1,"col1",1,false,false,null,"default","col1",1,0}); + preparedstatementHandler.prepareResultSet(fecthForeignTableColumns, fecthForeignTableColumnsRS); + + String partTableColumns="WITH tbl AS ( select oid as tableid,relnamespace as namespaceid from pg_class where relnamespace = 1and relkind <> 'i' and parttype in ('p', 'v')), attr AS ( select c.attnum as columnidx,c.attname as name , pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns,c.atttypid as datatypeoid ,c.attlen as length,c.atttypmod as precision,c.attndims as dimentions,c.attnotnull as notnull,c.atthasdef as isdefaultvalueavailable,c.attrelid as tableoid from pg_attribute c where c.attrelid in (select tableid from tbl) and c.attisdropped = 'f' and c.attnum > 0), dtype AS (select typ.typnamespace as dtns,oid from pg_type typ where typ.oid in (select datatypeoid from attr) ), attrdef AS ( select d.adsrc as default_value ,d.adbin as attDefStr ,adrelid,adnum from pg_attrdef d where d.adrelid in ( select tableid from tbl) and d.adnum in( select columnidx from attr))select t.tableid as tableid ,t.namespaceid as namespaceid,c.columnidx,c.name,c.displaycolumns,c.datatypeoid,typ.dtns,c.length,c.precision,c.dimentions,c.notnull,c.isdefaultvalueavailable,default_value, d.attDefStr FROM tbl t LEFT JOIN attr c ON(t.tableid = c.tableoid) LEFT JOIN attrdef d ON(t.tableid = d.adrelid AND c.columnidx = d.adnum) LEFT JOIN dtype typ ON (c.datatypeoid = typ.oid) ORDER BY t.tableid ,c.columnidx;"; + preparedstatementHandler.prepareResultSet(partTableColumns, fecthForeignTableColumnsRS); + + String str="select c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable from pg_attribute c where c.attrelid=1 and c.attisdropped = 'f' and c.attnum > 0;"; + + MockResultSet fetchViewRS1 = preparedstatementHandler.createResultSet(); + fetchViewRS1.addColumn("columnidx"); + fetchViewRS1.addColumn("name"); + fetchViewRS1.addColumn("displayColumns"); + fetchViewRS1.addColumn("datatypeoid"); + fetchViewRS1.addColumn("length"); + fetchViewRS1.addColumn("precision"); + fetchViewRS1.addColumn("dimentions"); + fetchViewRS1.addColumn("notnull"); + fetchViewRS1.addColumn("isdefaultvalueavailable"); + + + + fetchViewRS1.addRow(new Object[] {1, "ColName", "",1, 200, 0, 0, false,true}); + preparedstatementHandler.prepareResultSet(str, fetchViewRS1); + + String str5="select c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable from pg_attribute c where c.attrelid=2 and c.attisdropped = 'f' and c.attnum > 0;"; + preparedstatementHandler.prepareResultSet(str5, fetchViewRS1); + + String str1="select typ.typnamespace as dtns from pg_type typ where typ.oid=2"; + MockResultSet fetchViewRS2 = preparedstatementHandler.createResultSet(); + fetchViewRS2.addColumn("dtns"); + fetchViewRS2.addRow(new Object[] {1}); + preparedstatementHandler.prepareResultSet(str1, fetchViewRS2); + + String str2="select typ.typnamespace as dtns from pg_type typ where typ.oid=1"; + preparedstatementHandler.prepareResultSet(str2, fetchViewRS2); + + + String str3="select d.adsrc as default_value, d.adbin as attDefStr from pg_attrdef d where d.adrelid=1 and d.adnum=1"; + MockResultSet fetchViewRS3 = preparedstatementHandler.createResultSet(); + fetchViewRS3.addColumn("default_value"); + fetchViewRS3.addColumn("attDefStr"); + fetchViewRS3.addRow(new Object[] {"Default value",""}); + preparedstatementHandler.prepareResultSet(str3, fetchViewRS3); + + /* + * getdbsrs.addRow(new Object[] {2, nsid, 1, "col3", 2, 1, 64, -1, 0, + * 'f', 'f', ""}); getdbsrs.addRow(new Object[] {2, nsid, 2, "col4", 1, + * 1, 64, -1, 0, 'f', 'f', ""}); getdbsrs.addRow(new Object[] {3, nsid, + * 1, "col5", 2, 1, 64, -1, 0, 'f', 'f', ""}); getdbsrs.addRow(new + * Object[] {3, nsid, 2, "col6", 1, 1, 64, -1, 0, 'f', 'f', ""}); + * getdbsrs.addRow(new Object[] {3, nsid, 2, "col6", 1, 1, -1, -1, 0, + * 'f', 'f', ""}); getdbsrs.addRow(new Object[] {3, nsid, 2, "col6", 11, + * 1, -1, -1, 0, 'f', 'f', ""}); + */ + } + + public static void fetchAllSynonyms(PreparedStatementResultSetHandler preparedstatementHandler) { + String fetchAllsynonys = SynonymUtil.FETCH_SYNONYM_STATEMENT; + + MockResultSet fetchAllsynonysRS = preparedstatementHandler.createResultSet(); + fetchAllsynonysRS.addColumn("synonym_name"); + fetchAllsynonysRS.addColumn("owner"); + fetchAllsynonysRS.addColumn("schema_name"); + fetchAllsynonysRS.addColumn("table_name"); + fetchAllsynonysRS.addRow(new Object[] {1, "syn1", "user", "user", "tbl1"}); + preparedstatementHandler.prepareResultSet(fetchAllsynonys, fetchAllsynonysRS); + } + + public static void getCountRS( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String REFRESH_DBG_OBJ_QRY = "SELECT count(*) as cnt FROM \"pg_catalog\".\"MyTable\";"; + + MockResultSet colmetadataRS = preparedstatementHandler + .createResultSet(); + colmetadataRS.addColumn("cnt"); + + colmetadataRS.addRow(new Object[] {10}); + preparedstatementHandler.prepareResultSet(REFRESH_DBG_OBJ_QRY, + colmetadataRS); + + } + + public static void getTablePtropertiesRS( + PreparedStatementResultSetHandler preparedstatementHandler, + String tableType) + { + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("relpersistence"); + getdbsrs.addColumn("owner"); + getdbsrs.addColumn("pages"); + getdbsrs.addColumn("rows_count"); + getdbsrs.addColumn("has_index"); + getdbsrs.addColumn("is_shared"); + getdbsrs.addColumn("check_count"); + getdbsrs.addColumn("has_pkey"); + getdbsrs.addColumn("has_rules"); + getdbsrs.addColumn("has_triggers"); + getdbsrs.addColumn("options"); + getdbsrs.addColumn("hashoid"); + getdbsrs.addColumn("tbl_desc"); + getdbsrs.addColumn("spcname"); + getdbsrs.addRow(new Object[] {tableType, "GaussMPPDB", "12", "1200", + false, false, false, true, true, false, "orientation= row,fillfactor= 90,compression= no,MAX_Batchrow= 10,Partial_cluster_rows= 2,version= v6.5.1", true, + "Tbl Description", "tblspc_prop"}); + getdbsrs.addRow(new Object[] {tableType, "GaussMppDB", "12", "1200", + false, false, false, true, true, false, + "orientation= row,compression= no", true, "Tbl Description", + "tblspc_prop_1"}); + + preparedstatementHandler.prepareResultSet( + "SELECT tbl.relpersistence as relpersistence, case when tbl.reltablespace = 0 then 'DEFAULT' else tblsp.spcname end, auth.rolname as owner, tbl.relpages pages, tbl.reltuples as rows_count, tbl.relhasindex as has_index, tbl.relisshared as is_shared, tbl.relchecks as check_count, tbl.relhaspkey as has_pkey, tbl.relhasrules as has_rules, tbl.relhastriggers as has_triggers, array_to_string(tbl.reloptions, ',') as options,tbl.relhasoids as hashoid, d.description as tbl_desc FROM pg_class tbl LEFT JOIN pg_roles auth on (tbl.relowner = auth.oid) left join pg_description d on (tbl.oid = d.objoid) LEFT JOIN pg_tablespace tblsp ON (tbl.reltablespace = tblsp.oid) WHERE tbl.oid = 1;", + getdbsrs); + MockResultSet getdbsrs1 = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("pg_get_expr"); + getdbsrs1.addRow(new Object[] {"C>1"}); + + preparedstatementHandler.prepareResultSet( + "select pg_get_expr(indpred,1) from pg_index where indrelid = 1", + getdbsrs); + + String str3="select d.adsrc as default_value, d.adbin as attDefStr from pg_attrdef d where d.adrelid=1 and d.adnum=1"; + MockResultSet fetchViewRS3 = preparedstatementHandler.createResultSet(); + fetchViewRS3.addColumn("default_value"); + fetchViewRS3.addColumn("attDefStr"); + fetchViewRS3.addRow(new Object[] {"Default value",""}); + preparedstatementHandler.prepareResultSet(str3, fetchViewRS3); + + } + + public static void getTablePtropertiesRS_forOptions( + PreparedStatementResultSetHandler preparedstatementHandler, + String tableType) + { + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("relpersistence"); + getdbsrs.addColumn("owner"); + getdbsrs.addColumn("pages"); + getdbsrs.addColumn("rows_count"); + getdbsrs.addColumn("has_index"); + getdbsrs.addColumn("is_shared"); + getdbsrs.addColumn("check_count"); + getdbsrs.addColumn("has_pkey"); + getdbsrs.addColumn("has_rules"); + getdbsrs.addColumn("has_triggers"); + getdbsrs.addColumn("options"); + getdbsrs.addColumn("hashoid"); + getdbsrs.addColumn("tbl_desc"); + getdbsrs.addColumn("spcname"); + getdbsrs.addRow(new Object[] {tableType, "GaussMppDB", "12", "1200", + false, false, false, true, true, false, + "orientation= row,compression= no,fillfactor=12,MAX_Batchrow=10,Partial_cluster_rows=1,version=1.2", + false, "Tbl Description", "tblspc_prop_1"}); + + preparedstatementHandler.prepareResultSet( + "SELECT tbl.relpersistence as relpersistence, case when tbl.reltablespace = 0 then 'DEFAULT' else tblsp.spcname end, auth.rolname as owner, tbl.relpages pages, tbl.reltuples as rows_count, tbl.relhasindex as has_index, tbl.relisshared as is_shared, tbl.relchecks as check_count, tbl.relhaspkey as has_pkey, tbl.relhasrules as has_rules, tbl.relhastriggers as has_triggers, array_to_string(tbl.reloptions, ',') as options,tbl.relhasoids as hashoid, d.description as tbl_desc FROM pg_class tbl LEFT JOIN pg_roles auth on (tbl.relowner = auth.oid) left join pg_description d on (tbl.oid = d.objoid) LEFT JOIN pg_tablespace tblsp ON (tbl.reltablespace = tblsp.oid) WHERE tbl.oid = 1;", + getdbsrs); + } + + public static void getTablePtropertiesRS_TableDoesNotExist( + PreparedStatementResultSetHandler preparedstatementHandler, + String tableType) + { + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("relpersistence"); + getdbsrs.addColumn("owner"); + getdbsrs.addColumn("pages"); + getdbsrs.addColumn("rows_count"); + getdbsrs.addColumn("has_index"); + getdbsrs.addColumn("is_shared"); + getdbsrs.addColumn("check_count"); + getdbsrs.addColumn("has_pkey"); + getdbsrs.addColumn("has_rules"); + getdbsrs.addColumn("has_triggers"); + getdbsrs.addColumn("options"); + getdbsrs.addColumn("hashoid"); + getdbsrs.addColumn("tbl_desc"); + getdbsrs.addColumn("spcname"); + + preparedstatementHandler.prepareResultSet( + "SELECT tbl.relpersistence as relpersistence, case when tbl.reltablespace = 0 then 'DEFAULT' else tblsp.spcname end, auth.rolname as owner, tbl.relpages pages, tbl.reltuples as rows_count, tbl.relhasindex as has_index, tbl.relisshared as is_shared, tbl.relchecks as check_count, tbl.relhaspkey as has_pkey, tbl.relhasrules as has_rules, tbl.relhastriggers as has_triggers, array_to_string(tbl.reloptions, ',') as options,tbl.relhasoids as hashoid, d.description as tbl_desc FROM pg_class tbl LEFT JOIN pg_roles auth on (tbl.relowner = auth.oid) left join pg_description d on (tbl.oid = d.objoid) LEFT JOIN pg_tablespace tblsp ON (tbl.reltablespace = tblsp.oid) WHERE tbl.oid = 1;", + getdbsrs); + } + + public static void getTablePtropertiesemptyRS( + PreparedStatementResultSetHandler preparedstatementHandler, + String tableType) + { + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("relpersistence"); + getdbsrs.addColumn("owner"); + getdbsrs.addColumn("pages"); + getdbsrs.addColumn("rows_count"); + getdbsrs.addColumn("has_index"); + getdbsrs.addColumn("is_shared"); + getdbsrs.addColumn("check_count"); + getdbsrs.addColumn("has_pkey"); + getdbsrs.addColumn("has_rules"); + getdbsrs.addColumn("has_triggers"); + getdbsrs.addColumn("options"); + getdbsrs.addColumn("hashoid"); + getdbsrs.addColumn("tbl_desc"); + + getdbsrs.addRow(new Object[] {}); + + preparedstatementHandler.prepareResultSet( + "SELECT tbl.relpersistence as relpersistence, auth.rolname as owner, tbl.relpages pages, " + + "tbl.reltuples as rows_count, tbl.relhasindex as has_index, tbl.relisshared as is_shared, " + + "tbl.relchecks as check_count, tbl.relhaspkey as has_pkey, tbl.relhasrules as has_rules, " + + "tbl.relhastriggers as has_triggers, array_to_string(tbl.reloptions, ',') as options,tbl.relhasoids as hashoid, d.description as tbl_desc " + + "FROM pg_class tbl LEFT JOIN pg_roles auth on " + + "(tbl.relowner = auth.oid) left join " + + "pg_description d on (tbl.oid = d.objoid) WHERE tbl.oid = " + + 2 + " ;", + getdbsrs); + } + + public static void getTablePtropertiesRS_01( + PreparedStatementResultSetHandler preparedstatementHandler, + String tableType) + { + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("relpersistence"); + getdbsrs.addColumn("owner"); + getdbsrs.addColumn("pages"); + getdbsrs.addColumn("rows_count"); + getdbsrs.addColumn("has_index"); + getdbsrs.addColumn("is_shared"); + getdbsrs.addColumn("check_count"); + getdbsrs.addColumn("has_pkey"); + getdbsrs.addColumn("has_rules"); + getdbsrs.addColumn("has_triggers"); + getdbsrs.addColumn("options"); + getdbsrs.addColumn("hashoid"); + getdbsrs.addColumn("tbl_desc"); + + getdbsrs.addRow(new Object[] {tableType, "GaussMPPDB", "12", "1200", + false, false, false, true, true, false, "1=2 3", false, + "Tbl Description"}); + + preparedstatementHandler.prepareResultSet( + + "SELECT tbl.relpersistence as relpersistence, auth.rolname as owner, tbl.relpages pages, tbl.reltuples as rows_count, tbl.relhasindex as has_index, tbl.relisshared as is_shared, tbl.relchecks as check_count, tbl.relhaspkey as has_pkey, tbl.relhasrules as has_rules, tbl.relhastriggers as has_triggers, array_to_string(tbl.reloptions, ',') as options,tbl.relhasoids as hashoid, d.description as tbl_desc FROM pg_class tbl LEFT JOIN pg_roles auth on (tbl.relowner = auth.oid) left join pg_description d on (tbl.oid = d.objoid) WHERE tbl.oid = 1;", + getdbsrs); + } + + public static void selectFromTableRS( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String REFRESH_DBG_OBJ_QRY = "SELECT * FROM \"pg_catalog\".\"MyTable\" LIMIT 1000 OFFSET 0;"; + + MockResultSet colmetadataRS = preparedstatementHandler + .createResultSet(); + colmetadataRS.addColumn("cnt"); + + colmetadataRS.addRow(new Object[] {10}); + preparedstatementHandler.prepareResultSet(REFRESH_DBG_OBJ_QRY, + colmetadataRS); + + } + + public static void getPropertiesConstraint( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet propconstraintRS = preparedstatementHandler + .createResultSet(); + propconstraintRS.addColumn("constraintid"); + propconstraintRS.addColumn("tableid"); + propconstraintRS.addColumn("namespaceid"); + propconstraintRS.addColumn("constraintname"); + propconstraintRS.addColumn("constrainttype"); + propconstraintRS.addColumn("deferrable"); + propconstraintRS.addColumn("deferred"); + propconstraintRS.addColumn("validate"); + propconstraintRS.addColumn("indexid"); + propconstraintRS.addColumn("fkeytableId"); + propconstraintRS.addColumn("updatetype"); + propconstraintRS.addColumn("deletetype"); + propconstraintRS.addColumn("matchtype"); + propconstraintRS.addColumn("expr"); + propconstraintRS.addColumn("columnlist"); + propconstraintRS.addColumn("fkeycolumnlist"); + propconstraintRS.addColumn("const_def"); + propconstraintRS.addColumn("tablespace"); + propconstraintRS.addRow(new Object[] {1, 1, 1, "ConstraintName", + "ConstraintType", false, false, false, 1, 1, "", "", "", "", + "{1}", "1", "", "constraint_tablespace"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_ALL_CONSTRAINTS, propconstraintRS); + } + + public static void getConstaraintForTableRS( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet constraintRS = preparedstatementHandler.createResultSet(); + constraintRS.addColumn("constraintid"); + constraintRS.addColumn("tableid"); + constraintRS.addColumn("namespaceid"); + constraintRS.addColumn("constraintname"); + constraintRS.addColumn("constrainttype"); + constraintRS.addColumn("deferrable"); + constraintRS.addColumn("deferred"); + constraintRS.addColumn("validate"); + constraintRS.addColumn("indexid"); + constraintRS.addColumn("fkeytableId"); + constraintRS.addColumn("updatetype"); + constraintRS.addColumn("deletetype"); + constraintRS.addColumn("matchtype"); + constraintRS.addColumn("expr"); + constraintRS.addColumn("columnlist"); + constraintRS.addColumn("fkeycolumnlist"); + constraintRS.addColumn("const_def"); + + constraintRS.addRow(new Object[] {1, 1, 1, "ConstraintName", + "ConstraintType", false, false, false, 1, 1, "", "", "", "", + "1", "1", ""}); + preparedstatementHandler.prepareResultSet( + "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c where c.conrelid = 1;", + constraintRS); + /* + * preparedstatementHandler.prepareResultSet( + * "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, " + * + + * "c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, " + * + + * "c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, " + * + + * "c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, " + * + + * "c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, " + * + "pg_get_constraintdef(c.oid) as const_def " + + * "FROM pg_constraint c where c.connamespace= " + 1 + ';', + * constraintRS); + */ + } + + public static void getConstaraintForTableRSEx( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet constraintRS = preparedstatementHandler.createResultSet(); + constraintRS.addColumn("constraintid"); + constraintRS.addColumn("tableid"); + constraintRS.addColumn("namespaceid"); + constraintRS.addColumn("constraintname"); + constraintRS.addColumn("constrainttype"); + constraintRS.addColumn("deferrable"); + constraintRS.addColumn("deferred"); + constraintRS.addColumn("validate"); + constraintRS.addColumn("indexid"); + constraintRS.addColumn("fkeytableId"); + constraintRS.addColumn("updatetype"); + constraintRS.addColumn("deletetype"); + constraintRS.addColumn("matchtype"); + constraintRS.addColumn("expr"); + constraintRS.addColumn("columnlist"); + constraintRS.addColumn("fkeycolumnlist"); + constraintRS.addColumn("const_def"); + + constraintRS.addRow(new Object[] {1, 1, 1, "ConstraintName", + "ConstraintType", false, false, false, 1, 1, "", "", "", "", + "1", "1", ""}); + // preparedstatementHandler.prepareResultSet("SELECT c.oid as + // constraintid, c.conrelid as tableid, c.connamespace as namespaceid, + // c.conname as constraintname, c.contype as constrainttype, + // c.condeferrable as deferrable, c.condeferred as deferred, + // c.convalidated as validate, c.conindid as indexid, c.confrelid as + // fkeytableId, c.confupdtype as updatetype, c.confdeltype as + // deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey + // as columnlist, c.confkey as fkeycolumnlist, + // pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c where + // c.conrelid = 1;",constraintRS); + // SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace + // as namespaceid, c.conname as constraintname, c.contype as + // constrainttype, c.condeferrable as deferrable, c.condeferred as + // deferred, c.convalidated as validate, c.conindid as indexid, + // c.confrelid as fkeytableId, c.confupdtype as updatetype, + // c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc + // as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, + // pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c where + // c.conrelid = 24900; + preparedstatementHandler.prepareResultSet( + "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c join pg_class cl on c.conrelid = cl.oid where c.connamespace=1 and cl.parttype not in ('p','v') and c.conrelid <> 0;", + constraintRS); + + } + + public static void getConstaraintForTableRSExAutoSuggest( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet constraintRS = preparedstatementHandler.createResultSet(); + constraintRS.addColumn("constraintid"); + constraintRS.addColumn("tableid"); + constraintRS.addColumn("namespaceid"); + constraintRS.addColumn("constraintname"); + constraintRS.addColumn("constrainttype"); + constraintRS.addColumn("deferrable"); + constraintRS.addColumn("deferred"); + constraintRS.addColumn("validate"); + constraintRS.addColumn("indexid"); + constraintRS.addColumn("fkeytableId"); + constraintRS.addColumn("updatetype"); + constraintRS.addColumn("deletetype"); + constraintRS.addColumn("matchtype"); + constraintRS.addColumn("expr"); + constraintRS.addColumn("columnlist"); + constraintRS.addColumn("fkeycolumnlist"); + constraintRS.addColumn("const_def"); + + constraintRS.addRow(new Object[] {1, 1, 1, "ConstraintName", + "ConstraintType", false, false, false, 1, 1, "", "", "", "", + "1", "1", ""}); + // preparedstatementHandler.prepareResultSet("SELECT c.oid as + // constraintid, c.conrelid as tableid, c.connamespace as namespaceid, + // c.conname as constraintname, c.contype as constrainttype, + // c.condeferrable as deferrable, c.condeferred as deferred, + // c.convalidated as validate, c.conindid as indexid, c.confrelid as + // fkeytableId, c.confupdtype as updatetype, c.confdeltype as + // deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey + // as columnlist, c.confkey as fkeycolumnlist, + // pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c where + // c.conrelid = 1;",constraintRS); + // SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace + // as namespaceid, c.conname as constraintname, c.contype as + // constrainttype, c.condeferrable as deferrable, c.condeferred as + // deferred, c.convalidated as validate, c.conindid as indexid, + // c.confrelid as fkeytableId, c.confupdtype as updatetype, + // c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc + // as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, + // pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c where + // c.conrelid = 24900; + preparedstatementHandler.prepareResultSet( + "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c join pg_class cl on c.conrelid = cl.oid where c.connamespace=1 and cl.parttype not in ('p','v') and c.conrelid <> 0;", + constraintRS); + preparedstatementHandler.prepareResultSet( + "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c join pg_class cl on c.conrelid = cl.oid where c.connamespace=2 and cl.parttype not in ('p','v') and c.conrelid <> 0;", + constraintRS); + preparedstatementHandler.prepareResultSet( + "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c join pg_class cl on c.conrelid = cl.oid where c.connamespace=3 and cl.parttype not in ('p','v') and c.conrelid <> 0;", + constraintRS); + preparedstatementHandler.prepareResultSet( + "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c join pg_class cl on c.conrelid = cl.oid where c.connamespace=4 and cl.parttype not in ('p','v') and c.conrelid <> 0;", + constraintRS); + preparedstatementHandler.prepareResultSet( + "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c join pg_class cl on c.conrelid = cl.oid where c.connamespace=5 and cl.parttype not in ('p','v') and c.conrelid <> 0;", + constraintRS); + preparedstatementHandler.prepareResultSet( + "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c join pg_class cl on c.conrelid = cl.oid where c.connamespace=6 and cl.parttype not in ('p','v') and c.conrelid <> 0;", + constraintRS); + + } + + public static void getConstaraintForTableRSEx2( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet constraintRS = preparedstatementHandler.createResultSet(); + constraintRS.addColumn("constraintid"); + constraintRS.addColumn("tableid"); + constraintRS.addColumn("namespaceid"); + constraintRS.addColumn("constraintname"); + constraintRS.addColumn("constrainttype"); + constraintRS.addColumn("deferrable"); + constraintRS.addColumn("deferred"); + constraintRS.addColumn("validate"); + constraintRS.addColumn("indexid"); + constraintRS.addColumn("fkeytableId"); + constraintRS.addColumn("updatetype"); + constraintRS.addColumn("deletetype"); + constraintRS.addColumn("matchtype"); + constraintRS.addColumn("expr"); + constraintRS.addColumn("columnlist"); + constraintRS.addColumn("fkeycolumnlist"); + constraintRS.addColumn("const_def"); + + constraintRS.addRow(new Object[] {1, 1, 1, "ConstraintName", + "ConstraintType", false, false, false, 1, 1, "", "", "", "", + "1", "1", ""}); + // preparedstatementHandler.prepareResultSet("SELECT c.oid as + // constraintid, c.conrelid as tableid, c.connamespace as namespaceid, + // c.conname as constraintname, c.contype as constrainttype, + // c.condeferrable as deferrable, c.condeferred as deferred, + // c.convalidated as validate, c.conindid as indexid, c.confrelid as + // fkeytableId, c.confupdtype as updatetype, c.confdeltype as + // deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey + // as columnlist, c.confkey as fkeycolumnlist, + // pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c where + // c.conrelid = 1;",constraintRS); + // SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace + // as namespaceid, c.conname as constraintname, c.contype as + // constrainttype, c.condeferrable as deferrable, c.condeferred as + // deferred, c.convalidated as validate, c.conindid as indexid, + // c.confrelid as fkeytableId, c.confupdtype as updatetype, + // c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc + // as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, + // pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c where + // c.conrelid = 24900; + preparedstatementHandler.prepareResultSet( + "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c join pg_class cl on c.conrelid = cl.oid where c.connamespace=1 and cl.parttype not in ('p','v') and c.conrelid <> 0;", + constraintRS); + + } + + public static void getIndexForTableRS1( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet indexRS = preparedstatementHandler.createResultSet(); + indexRS.addColumn("oid"); + indexRS.addColumn("tableId"); + indexRS.addColumn("indexname"); + indexRS.addColumn("namespaceid"); + indexRS.addColumn("accessmethodid"); + indexRS.addColumn("isunique"); + indexRS.addColumn("isprimary"); + indexRS.addColumn("isexclusion"); + indexRS.addColumn("isimmediate"); + indexRS.addColumn("isclustered"); + indexRS.addColumn("checkmin"); + indexRS.addColumn("isready"); + indexRS.addColumn("cols"); + indexRS.addColumn("reloptions"); + indexRS.addColumn("indexdef"); + + indexRS.addRow(new Object[] {1, 1, "IndexName", 1, 1, true, false, + false, false, false, false, false, "1", "", ""}); + preparedstatementHandler.prepareResultSet( + "SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, ci.relnamespace as namespaceid, ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, i.indisexclusion as isexclusion, i.indimmediate as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, i.indisready as isready, i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions ,def.indexdef FROM pg_index i LEFT JOIN pg_class t on (t.oid = i.indrelid) LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) LEFT JOIN pg_namespace ns on (ci.relnamespace = ns.oid) LEFT JOIN pg_indexes def on (ci.relname = def.indexname and ns.nspname = def.schemaname) WHERE t.relkind = 'r' and t.oid = 1", + indexRS); + + } + + public static void getIndexForTableRS( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String qry = "SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, ci.relnamespace as namespaceid, ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, i.indisexclusion as isexclusion, i.indimmediate as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, i.indisready as isready, i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions, def.indexdef , def.tablespace FROM pg_index i LEFT JOIN pg_class t on (t.oid = i.indrelid) LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) LEFT JOIN pg_namespace ns on (ci.relnamespace = ns.oid) LEFT JOIN pg_indexes def on (ci.relname = def.indexname and ns.nspname = def.schemaname) WHERE t.relkind = 'r' and t.oid = 1;"; + MockResultSet indexRS = preparedstatementHandler.createResultSet(); + indexRS.addColumn("oid"); + indexRS.addColumn("tableId"); + indexRS.addColumn("indexname"); + indexRS.addColumn("namespaceid"); + indexRS.addColumn("accessmethodid"); + indexRS.addColumn("isunique"); + indexRS.addColumn("isprimary"); + indexRS.addColumn("isexclusion"); + indexRS.addColumn("isimmediate"); + indexRS.addColumn("isclustered"); + indexRS.addColumn("checkmin"); + indexRS.addColumn("isready"); + indexRS.addColumn("cols"); + indexRS.addColumn("reloptions"); + indexRS.addColumn("indexdef"); + indexRS.addColumn("tablespace"); + + indexRS.addRow(new Object[] {1, 1, "IndexName", 1, 1, true, false, + false, false, false, false, false, "1", "", "", ""}); + preparedstatementHandler.prepareResultSet(qry, indexRS); + + } + + public static void getIndexWhereExpr(PreparedStatementResultSetHandler preparedstatementHandler) + { + + String query = "select pg_get_expr(indpred,1) from pg_index where indrelid = 1 and indexrelid = 1"; + MockResultSet whereExprRs = preparedstatementHandler.createResultSet(); + whereExprRs.addColumn("pg_get_expr"); + whereExprRs.addRow(new Object[] {"a>1"}); + preparedstatementHandler.prepareResultSet(query, whereExprRs); + } + + public static void refreshDbgObj( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String query = "select a.headerlines, a.definition, b.xmin, b.cmin from pg_proc b left join " + + "(select * from PG_GET_FUNCTIONDEF(" + 1 + + ")) a on (1) where b.oid=" + 1 + ';'; + + StringBuilder strSourcecode = new StringBuilder(); + + strSourcecode.append("\"Declare").append("\nc INT = 6;") + .append("\nd INT;BEGIN"); + strSourcecode.append("\nc := c+1;") + .append("\nc := perform nestedfunc()"); + strSourcecode.append("\nc := c+1;").append("\nc := c+1;"); + strSourcecode.append("\nc := c+1;").append("\nc := c+1;") + .append("\nc := 100;"); + strSourcecode.append("\nd := c + 200;").append("\nreturn d;") + .append("\nend;\")"); + + MockResultSet indexRS = preparedstatementHandler.createResultSet(); + indexRS.addRow(new Object[] {4, strSourcecode.toString(), 1, 1}); + + preparedstatementHandler.prepareResultSet(query, indexRS); + } + + public static void refreshDbgObj1( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String query = "select a.headerlines, a.definition, b.xmin, b.cmin from pg_proc b left join " + + "(select * from PG_GET_FUNCTIONDEF(" + 1 + + ")) a on (1) where b.oid=" + 1; + + StringBuilder strSourcecode = new StringBuilder(); + + strSourcecode.append("(\"Declare").append("\nc INT = 6;") + .append("\nd INT;BEGIN"); + strSourcecode.append("\nc := c+1;") + .append("\nc := perform nestedfunc()"); + strSourcecode.append("\nc := c+1;").append("\nc := c+1;"); + strSourcecode.append("\nc := c+1;").append("\nc := c+1;") + .append("\nc := 100;"); + strSourcecode.append("\nd := c + 200;").append("\nreturn d;") + .append("\nend;\")"); + + MockResultSet indexRS = preparedstatementHandler.createResultSet(); + indexRS.addRow(new Object[] {4, strSourcecode.toString(), 1, 1}); + + preparedstatementHandler.prepareResultSet(query, indexRS); + } + + public static void executeExecutor( + PreparedStatementResultSetHandler statementHandler) + { + String query = "SELECT pg_catalog.function2(1, 1)"; + + MockResultSet indexRS = statementHandler.createResultSet(); + indexRS.addColumn("col1"); + indexRS.addRow(new Object[] {1}); + + statementHandler.prepareResultSet(query, indexRS); + } + + public static void getColMetaDataPreScale( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet colmetadataRS = preparedstatementHandler + .createResultSet(); + colmetadataRS.addColumn("tableid"); + colmetadataRS.addColumn("namespaceid"); + colmetadataRS.addColumn("columnidx"); + colmetadataRS.addColumn("name"); + colmetadataRS.addColumn("datatypeoid"); + colmetadataRS.addColumn("dtns"); + colmetadataRS.addColumn("length"); + colmetadataRS.addColumn("precision"); + colmetadataRS.addColumn("dimentions"); + colmetadataRS.addColumn("notnull"); + colmetadataRS.addColumn("isdefaultvalueavailable"); + colmetadataRS.addColumn("default_value"); + + String colmetadata = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, " + + "c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, " + + "c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value " + + "from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.relkind = 'r') " + + "left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) " + + "where c.attisdropped = 'f' and c.attnum > 0 and t.relnamespace = " + + 1 + " order by t.oid, c.attnum;"; + + colmetadataRS.addRow(new Object[] {1, 1, 1, "ColName", 1, 1, 0, 1, 0, + false, true, "Default value"}); + preparedstatementHandler.prepareResultSet(colmetadata, colmetadataRS); + } + + public static void getColMetaDataPreScale2( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet colmetadataRS = preparedstatementHandler + .createResultSet(); + colmetadataRS.addColumn("tableid"); + colmetadataRS.addColumn("namespaceid"); + colmetadataRS.addColumn("columnidx"); + colmetadataRS.addColumn("name"); + colmetadataRS.addColumn("datatypeoid"); + colmetadataRS.addColumn("dtns"); + colmetadataRS.addColumn("length"); + colmetadataRS.addColumn("precision"); + colmetadataRS.addColumn("dimentions"); + colmetadataRS.addColumn("notnull"); + colmetadataRS.addColumn("isdefaultvalueavailable"); + colmetadataRS.addColumn("default_value"); + + String colmetadata = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, " + + "c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, " + + "c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value " + + "from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.relkind = 'r') " + + "left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) " + + "where c.attisdropped = 'f' and c.attnum > 0 and t.relnamespace = " + + 1 + " order by t.oid, c.attnum;"; + + colmetadataRS.addRow(new Object[] {1, 1, 1, "ColName", 1, 1, 0, -1, 0, + false, true, "Default value"}); + preparedstatementHandler.prepareResultSet(colmetadata, colmetadataRS); + } + + public static void getIndexcCOnstaByNamespace( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet indexRS = preparedstatementHandler.createResultSet(); + indexRS.addColumn("oid"); + indexRS.addColumn("tableId"); + indexRS.addColumn("indexname"); + indexRS.addColumn("namespaceid"); + indexRS.addColumn("accessmethodid"); + indexRS.addColumn("isunique"); + indexRS.addColumn("isprimary"); + indexRS.addColumn("isexclusion"); + indexRS.addColumn("isimmediate"); + indexRS.addColumn("isclustered"); + indexRS.addColumn("checkmin"); + indexRS.addColumn("isready"); + indexRS.addColumn("cols"); + indexRS.addColumn("reloptions"); + indexRS.addColumn("indexdef"); + indexRS.addColumn("tablespace"); + indexRS.addRow(new Object[] {1, 1, "IndexName", 1, 1, true, false, + false, false, false, false, false, "1", "", "", ""}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_ALL_INDEXES_BYNAMESPACE, indexRS); + + MockResultSet constraintRS = preparedstatementHandler.createResultSet(); + constraintRS.addColumn("constraintid"); + constraintRS.addColumn("tableid"); + constraintRS.addColumn("namespaceid"); + constraintRS.addColumn("constraintname"); + constraintRS.addColumn("constrainttype"); + constraintRS.addColumn("deferrable"); + constraintRS.addColumn("deferred"); + constraintRS.addColumn("validate"); + constraintRS.addColumn("indexid"); + constraintRS.addColumn("fkeytableId"); + constraintRS.addColumn("updatetype"); + constraintRS.addColumn("deletetype"); + constraintRS.addColumn("matchtype"); + constraintRS.addColumn("expr"); + constraintRS.addColumn("columnlist"); + constraintRS.addColumn("fkeycolumnlist"); + constraintRS.addColumn("const_def"); + constraintRS.addRow(new Object[] {1, 1, 1, "ConstraintName", + "ConstraintType", false, false, false, 1, 1, "", "", "", "", + "1", "1", ""}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_ALL_CONSTRAINTS_BYNAMESPACE, constraintRS); + } + + public static void getDeadLineInfoRs( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("DEADLINE"); + getdbsrs.addRow(new Object[] {"2Days"}); + preparedstatementHandler.prepareResultSet( + "select intervaltonum(gs_password_deadline()) as DEADLINE;", + getdbsrs); + + } + + public static void getDeadLineInfoRsPasswordExpired( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("DEADLINE"); + getdbsrs.addRow(new Object[] {"-1.00"}); + preparedstatementHandler.prepareResultSet( + "select intervaltonum(gs_password_deadline()) as DEADLINE;", + getdbsrs); + + } + + public static void getNotifyInfoRs( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("NOTIFYTIME"); + getdbsrs.addRow(new Object[] {2}); + preparedstatementHandler.prepareResultSet( + "select * from gs_password_notifytime() as NOTIFYTIME;", + getdbsrs); + + } + + public static void getViewMockRS( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("oid"); + getdbsrs.addColumn("nspoid"); + getdbsrs.addColumn("schemaname"); + getdbsrs.addColumn("viewname"); + getdbsrs.addColumn("viewowner"); + getdbsrs.addRow(new Object[] {2, 1, "public", "mytestview", "owner1"}); + getdbsrs.addRow( + new Object[] {25, 1, "public", "mytestview2", "owner1"}); + preparedstatementHandler.prepareResultSet( + "SELECT c.oid, n.oid as nspoid, n.nspname AS schemaname, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner " + + "FROM (pg_class c LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace))) WHERE (c.relkind = 'v'::\"char\" or c.relkind = 'm'::\"char\") and has_table_privilege(c.oid,'SELECT') ", + getdbsrs); + + MockResultSet getdbsrs_1 = preparedstatementHandler.createResultSet(); + getdbsrs_1.addColumn("oid"); + getdbsrs_1.addColumn("nspoid"); + getdbsrs_1.addColumn("schemaname"); + getdbsrs_1.addColumn("viewname"); + getdbsrs_1.addColumn("viewowner"); + getdbsrs_1.addRow(new Object[] {2, 1, "public", "mytestview", "owner1"}); + getdbsrs_1.addRow( + new Object[] {25, 1, "public", "mytestview2", "owner1"}); + preparedstatementHandler.prepareResultSet( + "SELECT c.oid, n.oid as nspoid, n.nspname AS schemaname, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner " + + "FROM (pg_class c LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace))) WHERE (c.relkind = 'v'::\"char\" or c.relkind = 'm'::\"char\") ", + getdbsrs_1); + + addViewColumn(preparedstatementHandler, 2, 1); + addViewColumn(preparedstatementHandler, 11, 1); + addViewColumn(preparedstatementHandler, 22, 1); + addViewColumn1(preparedstatementHandler); + + MockResultSet viewDdlRs = preparedstatementHandler.createResultSet(); + viewDdlRs.addColumn("definition"); + viewDdlRs.addRow(new Object[] {"select * from something"}); + preparedstatementHandler + .prepareResultSet("SELECT * FROM pg_get_viewdef(2)", viewDdlRs); + + MockResultSet viewDdlRs2 = preparedstatementHandler.createResultSet(); + viewDdlRs2.addColumn("definition"); + viewDdlRs2.addRow( + new Object[] {"SELECT * FROM t1 WHERE kind = 'Comedy';"}); + preparedstatementHandler.prepareResultSet( + "SELECT * FROM pg_get_viewdef(25)", viewDdlRs2); + + } + + public static void getViewMockView1( + PreparedStatementResultSetHandler preparedstatementHandler, + String schemaname) + { + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("oid"); + getdbsrs.addColumn("nspoid"); + getdbsrs.addColumn("schemaname"); + getdbsrs.addColumn("viewname"); + getdbsrs.addColumn("viewowner"); + getdbsrs.addRow(new Object[] {11, 10, "public", schemaname, "owner1"}); + preparedstatementHandler.prepareResultSet( + "SELECT c.oid, n.oid as nspoid, n.nspname AS schemaname, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner " + + "FROM (pg_class c LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace))) WHERE (c.relkind = 'v'::\"char\" or c.relkind = 'm'::\"char\") and has_table_privilege(c.oid,'SELECT') ", + getdbsrs); + + MockResultSet getdbsrs_1 = preparedstatementHandler.createResultSet(); + getdbsrs_1.addColumn("oid"); + getdbsrs_1.addColumn("nspoid"); + getdbsrs_1.addColumn("schemaname"); + getdbsrs_1.addColumn("viewname"); + getdbsrs_1.addColumn("viewowner"); + getdbsrs_1.addRow(new Object[] {11, 10, "public", schemaname, "owner1"}); + preparedstatementHandler.prepareResultSet( + "SELECT c.oid, n.oid as nspoid, n.nspname AS schemaname, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner " + + "FROM (pg_class c LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace))) WHERE (c.relkind = 'v'::\"char\" or c.relkind = 'm'::\"char\") ", + getdbsrs_1); + + addViewColumn(preparedstatementHandler, 2, 10); + addViewColumn(preparedstatementHandler, 11, 10); + addViewColumn(preparedstatementHandler, 22, 10); + } + + public static void getSchemaNameOne( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet namespaceRS = preparedstatementHandler.createResultSet(); + namespaceRS.addColumn("oid"); + namespaceRS.addColumn("nspname"); + namespaceRS.addRow(new Object[] {1, "pg_catalog"}); + namespaceRS.addRow(new Object[] {2, "information_schema"}); + namespaceRS.addRow(new Object[] {10, "Schema_One"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_ALL_NAMESPACE, namespaceRS); + } + + public static void getSchemaTwo( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet namespaceRS = preparedstatementHandler.createResultSet(); + namespaceRS.addColumn("oid"); + namespaceRS.addColumn("nspname"); + namespaceRS.addRow(new Object[] {1, "pg_catalog"}); + /* namespaceRS.addRow(new Object[]{10, "Schema_One"}); */ + namespaceRS.addRow(new Object[] {11, "Schema_Two"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_ALL_NAMESPACE, namespaceRS); + } + + public static void addViewColumn( + PreparedStatementResultSetHandler preparedstatementHandler, int id, + int nsid) + { + String query = "select v.oid as viewid, v.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, c.atttypid as datatypeoid, typ.typnamespace as dtns, " + + "c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, " + + "d.adsrc as default_value from pg_class v left join pg_attribute c on (v.oid = c.attrelid and v.relkind = 'v') " + + "left join pg_attrdef d on (v.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) " + + "where c.attisdropped = 'f' and c.attnum > 0 and v.relnamespace = " + + nsid + " order by v.oid, c.attnum"; + + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("viewid"); + getdbsrs.addColumn("namespaceid"); + getdbsrs.addColumn("columnidx"); + getdbsrs.addColumn("name"); + getdbsrs.addColumn("datatypeoid"); + getdbsrs.addColumn("dtns"); + getdbsrs.addColumn("length"); + getdbsrs.addColumn("precision"); + getdbsrs.addColumn("dimentions"); + getdbsrs.addColumn("notnull"); + getdbsrs.addColumn("isdefaultvalueavailable"); + getdbsrs.addColumn("default_value"); + + getdbsrs.addRow(new Object[] {id, nsid, 1, "col1", 2, 1, 64, -1, 0, 'f', + 'f', ""}); + getdbsrs.addRow(new Object[] {id, nsid, 2, "col2", 1, 1, 64, -1, 0, 'f', + 'f', ""}); + + preparedstatementHandler.prepareResultSet(query, getdbsrs); + } + + public static void addViewColumn1( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String query = "select v.oid as viewid, v.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value from pg_class v left join pg_attribute c on (v.oid = c.attrelid and v.relkind = 'v') left join pg_attrdef d on (v.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and v.oid = 2 order by v.oid, c.attnum"; + + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("viewid"); + getdbsrs.addColumn("namespaceid"); + getdbsrs.addColumn("columnidx"); + getdbsrs.addColumn("name"); + getdbsrs.addColumn("datatypeoid"); + getdbsrs.addColumn("dtns"); + getdbsrs.addColumn("length"); + getdbsrs.addColumn("precision"); + getdbsrs.addColumn("dimentions"); + getdbsrs.addColumn("notnull"); + getdbsrs.addColumn("isdefaultvalueavailable"); + getdbsrs.addColumn("default_value"); + + getdbsrs.addRow( + new Object[] {2, 1, 1, "col1", 2, 1, 64, -1, 0, 'f', 'f', ""}); + getdbsrs.addRow( + new Object[] {2, 2, 2, "col2", 1, 1, 64, -1, 0, 'f', 'f', ""}); + + preparedstatementHandler.prepareResultSet(query, getdbsrs); + } + + public static void fetchColumnMetaDataRS( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String REFRESH_DBG_OBJ_QRY = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, " + + "c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, " + + "c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, " + + "d.adsrc as default_value from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.relkind = 'r') " + + "left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) " + + "where c.attisdropped = 'f' and c.attnum > 0 and t.relnamespace = 1 order by t.oid, c.attnum;"; + + MockResultSet listnerResultSet = preparedstatementHandler + .createResultSet(); + + listnerResultSet.addColumn("tableid"); + listnerResultSet.addColumn("namespaceid"); + listnerResultSet.addColumn("columnidx"); + listnerResultSet.addColumn("name"); + listnerResultSet.addColumn("datatypeoid"); + listnerResultSet.addColumn("dtns"); + listnerResultSet.addColumn("length"); + listnerResultSet.addColumn("precision"); + listnerResultSet.addColumn("dimentions"); + listnerResultSet.addColumn("notnull"); + listnerResultSet.addColumn("isdefaultvalueavailable"); + listnerResultSet.addColumn("default_value"); + + listnerResultSet.addRow(new Object[] {new Integer(1), new Integer(1), + null, null, null, null, null, null, null, "t", null, null}); + + preparedstatementHandler.prepareResultSet(REFRESH_DBG_OBJ_QRY, + listnerResultSet); + + } + + public static void prepareproxryfordebug( + PreparedStatementResultSetHandler preparedstatementHandler) + { + + MockResultSet loadFuncTriggerRS = preparedstatementHandler + .createResultSet(); + loadFuncTriggerRS.addColumn("oid"); + loadFuncTriggerRS.addColumn("objname"); + loadFuncTriggerRS.addColumn("namespace"); + loadFuncTriggerRS.addColumn("ret"); + loadFuncTriggerRS.addColumn("alltype"); + loadFuncTriggerRS.addColumn("nargs"); + loadFuncTriggerRS.addColumn("argtype"); + loadFuncTriggerRS.addColumn("argname"); + loadFuncTriggerRS.addColumn("argmod"); + loadFuncTriggerRS.addColumn("secdef"); + loadFuncTriggerRS.addColumn("vola"); + loadFuncTriggerRS.addColumn("isstrict"); + loadFuncTriggerRS.addColumn("retset"); + loadFuncTriggerRS.addColumn("procost"); + loadFuncTriggerRS.addColumn("setrows"); + loadFuncTriggerRS.addColumn("lang"); + loadFuncTriggerRS.addRow(new Object[] {1, "auto1", 1, 23, null, 0, null, + null, null, "f", "v", "f", "f", 100, 0}); + loadFuncTriggerRS.addRow(new Object[] {2, "function2", 1, 2278, + "{23,23,23}", 2, 23, "{id1,id2,value}", "{i,o,b}", "f", "v", + "f", "f", 100, 0, "plpgsql"}); + preparedstatementHandler.prepareResultSet( + "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs,pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, pr.proisstrict isstrict, pr.proretset retset, pr.procost procost, pr.prorows setrows FROM pg_proc pr JOIN pg_type typ ON typ.oid=prorettype JOIN pg_namespace typns ON typns.oid=typ.typnamespace JOIN pg_language lng ON lng.oid=prolang WHERE lng.lanname='plpgsql' and pr.pronamespace= 1 ORDER BY objname", + loadFuncTriggerRS); + } + + public static void refreshSourceCodeRS( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String REFRESH_DBG_OBJ_QRY = "select a.headerlines, a.definition, b.xmin, b.cmin from pg_proc b left join (select * from PG_GET_FUNCTIONDEF(1)) a on (1) where b.oid=1;"; + + MockResultSet listnerResultSet = preparedstatementHandler + .createResultSet(); + + listnerResultSet.addColumn("headerlines"); + listnerResultSet.addColumn("definition"); + listnerResultSet.addColumn("xmin"); + listnerResultSet.addColumn("cmin"); + + listnerResultSet.addRow( + new Object[] {new Integer(1), new Integer(1), null, null}); + + preparedstatementHandler.prepareResultSet(REFRESH_DBG_OBJ_QRY, + listnerResultSet); + + } + + public static void prepareProxyInfoForSearchPath( + PreparedStatementResultSetHandler preparedstatementHandler) + { + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + MockResultSet searchpath = preparedstatementHandler.createResultSet(); + searchpath.addColumn("search_path"); + + searchpath.addRow( + new Object[] {"PUBLIC,,pg_catalog,schema1,schema2,schema3"}); + preparedstatementHandler.prepareResultSet("SHOW search_path", + searchpath); + } + + /* + * public static void prepareProxyInfoForGetAllNamespaces( + * PreparedStatementResultSetHandler preparedstatementHandler){ + * + * MockResultSet namespaceRS = preparedstatementHandler.createResultSet(); + * namespaceRS.addColumn("oid"); namespaceRS.addColumn("nspname"); + * namespaceRS.addRow(new Object[] {1, "PUBLIC"}); namespaceRS.addRow(new + * Object[] {1, "pg_catalog"}); namespaceRS.addRow(new Object[] {2, + * "information_schema"}); preparedstatementHandler.prepareResultSet( + * CommonLLTUtils.GET_ALL_NAMESPACE, namespaceRS); } + */ + + public static void addViewTableData( + PreparedStatementResultSetHandler preparedstatementHandler) + { + + String query = "select row_number() over () as \"*\", * from pg_catalog.\"Mytable\""; + + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("col1"); + getdbsrs.addColumn("col2"); + getdbsrs.addColumn("col3"); + getdbsrs.addColumn("col4"); + getdbsrs.addColumn("col5"); + + getdbsrs.addRow(new Object[] {1, "abc", 2, 3, 4}); + getdbsrs.addRow(new Object[] {100, "cde", 101, 102, 103}); + getdbsrs.addRow(new Object[] {200, "egh", 201, 202, 203}); + getdbsrs.addRow(new Object[] {300, "def", 301, 302, 303}); + + preparedstatementHandler.prepareResultSet(query, getdbsrs); + + } + + public static void setResultSet(ResultSet resultSet) + { + rs = resultSet; + } + + public static ResultSet getResultSet() + { + return rs; + } + + public static void getAllFunctionQuery( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet listnerResultSet1 = preparedstatementHandler + .createResultSet(); + + listnerResultSet1.addColumn("oid"); + listnerResultSet1.addColumn("objname"); + listnerResultSet1.addColumn("namespace"); + listnerResultSet1.addColumn("ret"); + listnerResultSet1.addColumn("alltype"); + listnerResultSet1.addColumn("nargs"); + listnerResultSet1.addColumn("argtype"); + listnerResultSet1.addColumn("argname"); + listnerResultSet1.addColumn("argmod"); + listnerResultSet1.addColumn("secdef"); + listnerResultSet1.addColumn("vola"); + listnerResultSet1.addColumn("isstrict"); + listnerResultSet1.addColumn("retset"); + listnerResultSet1.addColumn("procost"); + listnerResultSet1.addColumn("setrows"); + listnerResultSet1.addColumn("lang"); + + ObjectParameter retParam = new ObjectParameter(); + retParam.setDataType("int"); + retParam.setName("a"); + retParam.setType(PARAMETERTYPE.IN); + + listnerResultSet1.addRow(new Object[] {2, "function2", 1, + new Integer(16), null, "1", "20 21 21", "{arg1, arg2, arg3}", + "{i,o,b}", false, "volatile", false, false, 10, 10, "sql"}); + listnerResultSet1.addRow(new Object[] {3, "function2", 1, + new Integer(16), null, "1", "20 21 21", "{arg1, arg2, arg3}", + "{i,o,b}", false, "volatile", false, false, 10, 10, "sql"}); + preparedstatementHandler.prepareResultSet(GET_ALL_FUNCTION_QUERY, + listnerResultSet1); + setResultSet(listnerResultSet1); + + } + + public static void notificationResultSet( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet notifyResultset = preparedstatementHandler + .createResultSet(); + + notifyResultset.addColumn("Timestamp"); + notifyResultset.addColumn("client_conninfo"); + notifyResultset + .addRow(new Object[] {TIMESTAMP, "[unknown]@10.18.214.64"}); + notifyResultset + .addRow(new Object[] {TIMESTAMP, "[unknown]@10.18.213.65"}); + + preparedstatementHandler.prepareResultSet( + NOTIFICATION_QUERY_SUCCESSFULL, notifyResultset); + } + + public static void notificationResultSetFailure( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet notifyResultset1 = preparedstatementHandler + .createResultSet(); + + notifyResultset1.addColumn("Timestamp"); + notifyResultset1.addColumn("client_conninfo"); + notifyResultset1 + .addRow(new Object[] {TIMESTAMP, "[unknown]@10.18.214.64"}); + notifyResultset1 + .addRow(new Object[] {TIMESTAMP, "[unknown]@10.18.213.65"}); + + preparedstatementHandler.prepareResultSet(NOTIFICATION_QUERY_FAILURE, + notifyResultset1); + } + + public static void mockGetPartitionOverloaded( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String GET_PARTITIONS_OVERLOADED = "select p.oid AS partition_id , p.relname AS partition_name , p.parentid AS table_id" + + " from pg_class c, pg_partition p where c.oid = 0 and c.parttype = 'p' " + + " and p.parentid = c.oid and p.parttype = 'p' order by p.boundaries;"; + + MockResultSet getPartitionsOverloadedRS = preparedstatementHandler + .createResultSet(); + getPartitionsOverloadedRS.addColumn("partition_id"); + getPartitionsOverloadedRS.addColumn("partition_name"); + getPartitionsOverloadedRS.addColumn("table_id"); + getPartitionsOverloadedRS.addRow(new Object[] {1, "part_1", 1}); + preparedstatementHandler.prepareResultSet(GET_PARTITIONS_OVERLOADED, + getPartitionsOverloadedRS); + + } + + public static void Dropsequence( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String dropView = "DROP SEQUENCE IF EXISTS pg_catalog.sequence1"; + + MockResultSet colmetadataRS = preparedstatementHandler + .createResultSet(); + colmetadataRS.addColumn("messaage"); + + colmetadataRS.addRow(new Object[] {"View droped"}); + preparedstatementHandler.prepareResultSet(dropView, colmetadataRS); + } + + public static void columnComments( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet columnComnt = preparedstatementHandler.createResultSet(); + columnComnt.addColumn("description"); + columnComnt.addColumn("attname"); + columnComnt.addRow(new Object[] {"my comment","col1"}); + preparedstatementHandler.prepareResultSet(COLUMN_COMMENTS, columnComnt); + } + + public static void getPartitionData( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String qry = "select pr.relname ,array_to_string(pr.boundaries, ','::text, 'MAXVALUE'::text) as boundaries ,t.spcname from pg_partition pr left join pg_tablespace t on (pr.reltablespace=t.oid) where parttype in('p,v') and pr.parentid =1"; + MockResultSet partinfo = preparedstatementHandler.createResultSet(); + partinfo.addColumn("relname"); + partinfo.addColumn("boundaries"); + partinfo.addColumn("spcname"); + partinfo.addRow(new Object[] {"part_1", "10", "tablespace"}); + preparedstatementHandler.prepareResultSet(qry, partinfo); + + } + + public static void datatypes( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String qry = "select typ.oid as oid, typ.typname as typname, typ.typnamespace as typnamespace, typ.typlen as typlen, pg_catalog.format_type(oid,typ.typtypmod) as displaycolumns , typ.typbyval as typbyval, typ.typtype as typtype, typ.typcategory as typcategory, typ.typtypmod as typtypmod, typ.typnotnull as typnotnull, typ.typarray as typarray from pg_type typ where typnamespace = 1 order by typ.typname"; + MockResultSet dbrs = preparedstatementHandler.createResultSet(); + dbrs.addColumn("oid"); + dbrs.addColumn("typname"); + dbrs.addColumn("typnamespace"); + dbrs.addColumn("typlen"); + dbrs.addColumn("displaycolumns"); + dbrs.addColumn("typbyval"); + dbrs.addColumn("typtype"); + dbrs.addColumn("typcategory"); + dbrs.addColumn("typtypmod"); + dbrs.addColumn("typnotnull"); + dbrs.addColumn("typarray"); + + dbrs.addRow(new Object[] {1, "bigint", 1, 1, "character", true, "type", + "category", 1, true, 12, "bigint"}); + /* + * dbrs.addRow(new Object[] {2, "int8", 1, 1, true, "type", "category", + * 1, true, 12, "description2"}); + */ + + /* + * datatypeRS.addRow(new Object[] {3, "bit", 1, 1, true, "type", + * "category", 1, true, 12, "description","bit"}); datatypeRS.addRow(new + * Object[] {4, "varbit", 1, 1, true, "type", "category", 1, true, 12, + * "description","varbit"}); datatypeRS.addRow(new Object[] {5, "bool", + * 1, 1, true, "type", "category", 1, true, 12, "description","bool"}); + * datatypeRS.addRow(new Object[] {6, "box", 1, 1, true, "type", + * "category", 1, true, 12, "description","box"}); datatypeRS.addRow(new + * Object[] {7, "bytea", 1, 1, true, "type", "category", 1, true, 12, + * "description","bytea"}); datatypeRS.addRow(new Object[] {8, + * "varchar", 1, 1, true, "type", "category", 1, true, 12, + * "description","varchar"}); datatypeRS.addRow(new Object[] {9, "char", + * 1, 1, true, "type", "category", 1, true, 12, "description","char"}); + * datatypeRS.addRow(new Object[] {10, "cidr", 1, 1, true, "type", + * "category", 1, true, 12, "description","cidr"}); + * datatypeRS.addRow(new Object[] {11, "circle", 1, 1, true, "type", + * "category", 1, true, 12, "description","circle"}); + * datatypeRS.addRow(new Object[] {12, "date", 1, 1, true, "type", + * "category", 1, true, 12, "description","date"}); + * + * datatypeRS.addRow(new Object[] {13, "float8", 1, 1, true, "type", + * "category", 1, true, 12, "description","float"}); + * datatypeRS.addRow(new Object[] {14, "inet", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {15, "int4", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); datatypeRS.addRow(new Object[] {16, "interval", + * 1, 1, true, "type", "category", 1, true, 12, "description",""}); + * datatypeRS.addRow(new Object[] {17, "line", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {18, "lseg", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); datatypeRS.addRow(new Object[] {19, "macaddr", 1, + * 1, true, "type", "category", 1, true, 12, "description",""}); + * datatypeRS.addRow(new Object[] {20, "money", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {21, "numeric", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); datatypeRS.addRow(new Object[] {22, "numeric", 1, + * 1, true, "type", "category", 1, true, 12, "description",""}); + * datatypeRS.addRow(new Object[] {23, "path", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {24, "point", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); datatypeRS.addRow(new Object[] {25, "polygon", 1, + * 1, true, "type", "category", 1, true, 12, "description",""}); + * datatypeRS.addRow(new Object[] {26, "float4", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {27, "int2", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); + * + * datatypeRS.addRow(new Object[] {28, "text", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {29, "time", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); datatypeRS.addRow(new Object[] {30, "timetz", 1, + * 1, true, "type", "category", 1, true, 12, "description",""}); + * datatypeRS.addRow(new Object[] {31, "timestamp", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {32, "timestamptz", 1, 1, true, "type", "category", 1, true, + * 12, "description",""}); datatypeRS.addRow(new Object[] {33, + * "tsquery", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); datatypeRS.addRow(new Object[] {34, "tsvector", + * 1, 1, true, "type", "category", 1, true, 12, "description",""}); + * datatypeRS.addRow(new Object[] {35, "txid_snapshot", 1, 1, true, + * "type", "category", 1, true, 12, "description",""}); + * datatypeRS.addRow(new Object[] {36, "uuid", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {37, "xml", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); + */ + preparedstatementHandler.prepareResultSet(qry, dbrs); + } + + /// new queries mocked + + public static void refreshTableinnamespace( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String qry = "with x as (" + + "select tbl.oid as oid, tbl.relname relname, tbl.relpersistence relpersistence,tbl.reloptions as reloptions, tbl.parttype as parttype, array_to_string(part.partkey,',') as partkey from pg_class tbl left join pg_partition part on(tbl.oid=part.parentid and part.parttype='r') where tbl.relkind = 'r' and tbl.relnamespace = 1" + + " and oid in (" + + "select pcrelid from pgxc_class " + + "where has_nodegroup_privilege(pgroup, 'USAGE'))" + + ") select * from x " + + "where has_table_privilege(x.oid,'SELECT');"; + MockResultSet refreshtablemetadatainnamspace = preparedstatementHandler + .createResultSet(); + refreshtablemetadatainnamspace.addColumn("oid"); + refreshtablemetadatainnamspace.addColumn("relname"); + refreshtablemetadatainnamspace.addColumn("relpersistence"); + refreshtablemetadatainnamspace.addColumn("reloptions"); + refreshtablemetadatainnamspace.addColumn("parttype"); + refreshtablemetadatainnamspace.addColumn("partkey"); + refreshtablemetadatainnamspace + .addRow(new Object[] {1, "MyTable", 'p', "", 'n', "abc"}); + preparedstatementHandler.prepareResultSet(qry, + refreshtablemetadatainnamspace); + + } + + public static void refreshTableinnamespaceAutoSuggest( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String qry1 = "select tbl.oid as oid, tbl.relname relname, tbl.relpersistence relpersistence,tbl.reloptions as reloptions, tbl.parttype as parttype, array_to_string(part.partkey,',') as partkey from pg_class tbl left join pg_partition part on(tbl.oid=part.parentid and part.parttype='r') where tbl.relkind = 'r' and tbl.relnamespace = 1 and has_table_privilege(tbl.oid, 'SELECT');"; + String qry2 = "select tbl.oid as oid, tbl.relname relname, tbl.relpersistence relpersistence,tbl.reloptions as reloptions, tbl.parttype as parttype, array_to_string(part.partkey,',') as partkey from pg_class tbl left join pg_partition part on(tbl.oid=part.parentid and part.parttype='r') where tbl.relkind = 'r' and tbl.relnamespace = 2 and has_table_privilege(tbl.oid, 'SELECT');"; + String qry3 = "select tbl.oid as oid, tbl.relname relname, tbl.relpersistence relpersistence,tbl.reloptions as reloptions, tbl.parttype as parttype, array_to_string(part.partkey,',') as partkey from pg_class tbl left join pg_partition part on(tbl.oid=part.parentid and part.parttype='r') where tbl.relkind = 'r' and tbl.relnamespace = 3 and has_table_privilege(tbl.oid, 'SELECT');"; + String qry4 = "select tbl.oid as oid, tbl.relname relname, tbl.relpersistence relpersistence,tbl.reloptions as reloptions, tbl.parttype as parttype, array_to_string(part.partkey,',') as partkey from pg_class tbl left join pg_partition part on(tbl.oid=part.parentid and part.parttype='r') where tbl.relkind = 'r' and tbl.relnamespace = 4 and has_table_privilege(tbl.oid, 'SELECT');"; + String qry5 = "select tbl.oid as oid, tbl.relname relname, tbl.relpersistence relpersistence,tbl.reloptions as reloptions, tbl.parttype as parttype, array_to_string(part.partkey,',') as partkey from pg_class tbl left join pg_partition part on(tbl.oid=part.parentid and part.parttype='r') where tbl.relkind = 'r' and tbl.relnamespace = 5 and has_table_privilege(tbl.oid, 'SELECT');"; + String qry6 = "select tbl.oid as oid, tbl.relname relname, tbl.relpersistence relpersistence,tbl.reloptions as reloptions, tbl.parttype as parttype, array_to_string(part.partkey,',') as partkey from pg_class tbl left join pg_partition part on(tbl.oid=part.parentid and part.parttype='r') where tbl.relkind = 'r' and tbl.relnamespace = 6 and has_table_privilege(tbl.oid, 'SELECT');"; + + MockResultSet refreshtablemetadatainnamspace = preparedstatementHandler + .createResultSet(); + refreshtablemetadatainnamspace.addColumn("oid"); + refreshtablemetadatainnamspace.addColumn("relname"); + refreshtablemetadatainnamspace.addColumn("relpersistence"); + refreshtablemetadatainnamspace.addColumn("reloptions"); + refreshtablemetadatainnamspace.addColumn("parttype"); + refreshtablemetadatainnamspace.addColumn("partkey"); + refreshtablemetadatainnamspace + .addRow(new Object[] {1, "MyTable", 'p', "", 'n', "abc"}); + preparedstatementHandler.prepareResultSet(qry1, + refreshtablemetadatainnamspace); + refreshtablemetadatainnamspace + .addRow(new Object[] {1, "MyTable", 'p', "", 'n', "abc"}); + preparedstatementHandler.prepareResultSet(qry2, + refreshtablemetadatainnamspace); + refreshtablemetadatainnamspace + .addRow(new Object[] {1, "MyTable", 'p', "", 'n', "abc"}); + preparedstatementHandler.prepareResultSet(qry3, + refreshtablemetadatainnamspace); + refreshtablemetadatainnamspace + .addRow(new Object[] {1, "MyTable", 'p', "", 'n', "abc"}); + preparedstatementHandler.prepareResultSet(qry4, + refreshtablemetadatainnamspace); + refreshtablemetadatainnamspace + .addRow(new Object[] {1, "MyTable", 'p', "", 'n', "abc"}); + preparedstatementHandler.prepareResultSet(qry5, + refreshtablemetadatainnamspace); + refreshtablemetadatainnamspace + .addRow(new Object[] {1, "MyTable", 'p', "", 'n', "abc"}); + preparedstatementHandler.prepareResultSet(qry6, + refreshtablemetadatainnamspace); + + } + + public static void fetchTriggerQuery(PreparedStatementResultSetHandler preparedstatementHandler) { + String fetchTriggerQuery = "select t.oid as oid, t.tgrelid as tableoid, t.tgname as name, t.tgfoid as functionoid, t.tgtype as tgtype, t.tgenabled as tgenable, pg_get_triggerdef(t.oid) as ddlmsg from pg_trigger t, pg_class c where t.tgrelid = c.oid and c.relnamespace=?"; + MockResultSet fetchTriggerRS = preparedstatementHandler.createResultSet(); + fetchTriggerRS.addColumn("oid"); + fetchTriggerRS.addColumn("tableoid"); + fetchTriggerRS.addColumn("name"); + fetchTriggerRS.addColumn("functionoid"); + fetchTriggerRS.addColumn("tgtype"); + fetchTriggerRS.addColumn("tgenable"); + fetchTriggerRS.addColumn("ddlmsg"); + fetchTriggerRS.addRow(new Object[] {1, 1, "trigger1", 1, 1, true, ""}); + preparedstatementHandler.prepareResultSet(fetchTriggerQuery, fetchTriggerRS); + } + + public static void fetchViewQuery( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String fetchViewQuery = "with x as (SELECT c.oid, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner , c.relkind as relkind FROM pg_class c WHERE (c.relkind = 'v'::char or c.relkind = 'm'::char) and c.relnamespace = 1) select * from x where has_table_privilege(x.oid,'SELECT');"; + MockResultSet fetchViewRS = preparedstatementHandler.createResultSet(); + fetchViewRS.addColumn("oid"); + fetchViewRS.addColumn("viewname"); + fetchViewRS.addColumn("viewowner"); + fetchViewRS.addColumn("relkind"); + fetchViewRS.addRow(new Object[] {1, "myview", "Gauss123", "v"}); + fetchViewRS.addRow(new Object[] {2, "mytestview2", "Gauss1234", "v"}); + preparedstatementHandler.prepareResultSet(fetchViewQuery, fetchViewRS); + } + + public static void fetchViewQuery_1( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String fetchViewQuery = "SELECT c.oid, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner , c.relkind as relkind FROM pg_class c WHERE (c.relkind = 'v'::char or c.relkind = 'm'::char) and has_table_privilege(c.oid,'SELECT') and c.relnamespace = 1"; + MockResultSet fetchViewRS = preparedstatementHandler.createResultSet(); + fetchViewRS.addColumn("oid"); + fetchViewRS.addColumn("viewname"); + fetchViewRS.addColumn("viewowner"); + fetchViewRS.addColumn("relkind"); + + fetchViewRS.addRow(new Object[] {1, "myview", "Gauss123", "v"}); + fetchViewRS.addRow(new Object[] {2, "mytestview2", "Gauss1234", "v"}); + preparedstatementHandler.prepareResultSet(fetchViewQuery, fetchViewRS); + } + + public static void createViewColunmMetadata( + PreparedStatementResultSetHandler preparedstatementHandler) + { + //String query = "select v.oid as viewid, v.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class v left join pg_attribute c on (v.oid = c.attrelid and v.relkind = 'v') left join pg_attrdef d on (v.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and v.relnamespace = 1 order by v.oid, c.attnum"; + + + String query = " WITH tbl AS ( select oid as viewid,relnamespace as namespaceid from pg_class where relnamespace =1 and relkind = 'v'), attr AS ( select c.attnum as columnidx,c.attname as name , pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns,c.atttypid as datatypeoid ,c.attlen as length,c.atttypmod as precision,c.attndims as dimentions,c.attnotnull as notnull,c.atthasdef as isdefaultvalueavailable,c.attrelid as tableoid from pg_attribute c where c.attrelid in (select viewid from tbl) and c.attisdropped = 'f' and c.attnum > 0), dtype AS (select typ.typnamespace as dtns,oid from pg_type typ where typ.oid in (select datatypeoid from attr) ), attrdef AS ( select d.adsrc as default_value ,d.adbin as attDefStr ,adrelid,adnum from pg_attrdef d where d.adrelid in ( select oid from tbl) and d.adnum in( select columnidx from attr)) select t.viewid as viewid ,t.namespaceid as namespaceid,c.columnidx,c.name,c.displaycolumns,c.datatypeoid,typ.dtns,c.length,c.precision,c.dimentions,c.notnull,c.isdefaultvalueavailable,default_value, d.attDefStr FROM tbl t LEFT JOIN attr c ON(t.viewid = c.tableoid) LEFT JOIN attrdef d ON(t.viewid = d.adrelid AND c.columnidx = d.adnum) LEFT JOIN dtype typ ON (c.datatypeoid = typ.oid) ORDER BY t.viewid ,c.columnidx;"; + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("viewid"); + getdbsrs.addColumn("namespaceid"); + getdbsrs.addColumn("columnidx"); + getdbsrs.addColumn("name"); + getdbsrs.addColumn("datatypeoid"); + getdbsrs.addColumn("dtns"); + getdbsrs.addColumn("length"); + getdbsrs.addColumn("precision"); + getdbsrs.addColumn("dimentions"); + getdbsrs.addColumn("notnull"); + getdbsrs.addColumn("isdefaultvalueavailable"); + getdbsrs.addColumn("default_value"); + getdbsrs.addColumn("attDefStr"); + getdbsrs.addColumn("displayColumns"); + + getdbsrs.addRow(new Object[] {1, 1, 1, "col1", 2, 1, 64, -1, 0, 'f', + 'f', "", "", ""}); + getdbsrs.addRow(new Object[] {1, 1, 2, "col2", 1, 1, 64, -1, 0, 'f', + 'f', "", "", ""}); + + String fetchViewQuery = "select oid as viewid, relnamespace as namespaceid from pg_class where relnamespace=1 and relkind = 'v'"; + MockResultSet fetchViewRS = preparedstatementHandler.createResultSet(); + fetchViewRS.addColumn("viewid"); + fetchViewRS.addColumn("namespaceid"); + //fetchViewRS.addColumn("viewowner"); + fetchViewRS.addRow(new Object[] {1, 1}); + fetchViewRS.addRow(new Object[] {2,1}); + preparedstatementHandler.prepareResultSet(fetchViewQuery, fetchViewRS); + + String str="select c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable from pg_attribute c where c.attrelid=1 and c.attisdropped = 'f' and c.attnum > 0;"; + + MockResultSet fetchViewRS1 = preparedstatementHandler.createResultSet(); + fetchViewRS1.addColumn("columnidx"); + fetchViewRS1.addColumn("name"); + fetchViewRS1.addColumn("displayColumns"); + fetchViewRS1.addColumn("datatypeoid"); + fetchViewRS1.addColumn("length"); + fetchViewRS1.addColumn("precision"); + fetchViewRS1.addColumn("dimentions"); + fetchViewRS1.addColumn("notnull"); + fetchViewRS1.addColumn("isdefaultvalueavailable"); + + + + fetchViewRS1.addRow(new Object[] {1, "col1", "",2, 64, -1, 0, 'f', + 'f'}); + fetchViewRS1.addRow(new Object[] {2, "col2","", 1, 64, -1, 0, 'f', + 'f'}); + preparedstatementHandler.prepareResultSet(str, fetchViewRS1); + + String str5="select c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable from pg_attribute c where c.attrelid=2 and c.attisdropped = 'f' and c.attnum > 0;"; + preparedstatementHandler.prepareResultSet(str5, fetchViewRS1); + + String str1="select typ.typnamespace as dtns from pg_type typ where typ.oid=2"; + MockResultSet fetchViewRS2 = preparedstatementHandler.createResultSet(); + fetchViewRS2.addColumn("dtns"); + fetchViewRS2.addRow(new Object[] {1}); + preparedstatementHandler.prepareResultSet(str1, fetchViewRS2); + + String str2="select typ.typnamespace as dtns from pg_type typ where typ.oid=1"; + preparedstatementHandler.prepareResultSet(str2, fetchViewRS2); + + + String str3="select d.adsrc as default_value, d.adbin as attDefStr from pg_attrdef d where d.adrelid=1 and d.adnum=1"; + MockResultSet fetchViewRS3 = preparedstatementHandler.createResultSet(); + fetchViewRS3.addColumn("default_value"); + fetchViewRS3.addColumn("attDefStr"); + fetchViewRS3.addRow(new Object[] {"",""}); + preparedstatementHandler.prepareResultSet(str3, fetchViewRS3); + + String str4="select d.adsrc as default_value, d.adbin as attDefStr from pg_attrdef d where d.adrelid=1 and d.adnum=2"; + preparedstatementHandler.prepareResultSet(str4, fetchViewRS3); + + String str6="select d.adsrc as default_value, d.adbin as attDefStr from pg_attrdef d where d.adrelid=2 and d.adnum=1"; + preparedstatementHandler.prepareResultSet(str6, fetchViewRS3); + + String str7="select d.adsrc as default_value, d.adbin as attDefStr from pg_attrdef d where d.adrelid=2 and d.adnum=2"; + preparedstatementHandler.prepareResultSet(str7, fetchViewRS3); + /* + * getdbsrs.addRow(new Object[] {2, nsid, 1, "col3", 2, 1, 64, -1, 0, + * 'f', 'f', ""}); getdbsrs.addRow(new Object[] {2, nsid, 2, "col4", 1, + * 1, 64, -1, 0, 'f', 'f', ""}); getdbsrs.addRow(new Object[] {3, nsid, + * 1, "col5", 2, 1, 64, -1, 0, 'f', 'f', ""}); getdbsrs.addRow(new + * Object[] {3, nsid, 2, "col6", 1, 1, 64, -1, 0, 'f', 'f', ""}); + * getdbsrs.addRow(new Object[] {3, nsid, 2, "col6", 1, 1, -1, -1, 0, + * 'f', 'f', ""}); getdbsrs.addRow(new Object[] {3, nsid, 2, "col6", 11, + * 1, -1, -1, 0, 'f', 'f', ""}); + */ + preparedstatementHandler.prepareResultSet(query, getdbsrs); + } + + public static void fetchViewColumnInfo( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String query = "select v.oid as viewid, v.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class v left join pg_attribute c on (v.oid = c.attrelid and v.relkind = 'v') left join pg_attrdef d on (v.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and v.oid = 2 order by v.oid, c.attnum"; + + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("viewid"); + getdbsrs.addColumn("namespaceid"); + getdbsrs.addColumn("columnidx"); + getdbsrs.addColumn("name"); + getdbsrs.addColumn("displaycolumns"); + getdbsrs.addColumn("datatypeoid"); + getdbsrs.addColumn("dtns"); + getdbsrs.addColumn("length"); + getdbsrs.addColumn("precision"); + getdbsrs.addColumn("dimentions"); + getdbsrs.addColumn("notnull"); + getdbsrs.addColumn("isdefaultvalueavailable"); + getdbsrs.addColumn("default_value"); + getdbsrs.addColumn("attDefStr"); + + getdbsrs.addRow(new Object[] {1, 1, 1, "col1", "", 2, 1, 64, -1, 0, 'f', + 'f', "", ""}); + getdbsrs.addRow(new Object[] {1, 1, 2, "col2", "", 1, 1, 64, -1, 0, 'f', + 'f', "", ""}); + /* + * getdbsrs.addRow(new Object[] {2, nsid, 1, "col3", 2, 1, 64, -1, 0, + * 'f', 'f', ""}); getdbsrs.addRow(new Object[] {2, nsid, 2, "col4", 1, + * 1, 64, -1, 0, 'f', 'f', ""}); getdbsrs.addRow(new Object[] {3, nsid, + * 1, "col5", 2, 1, 64, -1, 0, 'f', 'f', ""}); getdbsrs.addRow(new + * Object[] {3, nsid, 2, "col6", 1, 1, 64, -1, 0, 'f', 'f', ""}); + * getdbsrs.addRow(new Object[] {3, nsid, 2, "col6", 1, 1, -1, -1, 0, + * 'f', 'f', ""}); getdbsrs.addRow(new Object[] {3, nsid, 2, "col6", 11, + * 1, -1, -1, 0, 'f', 'f', ""}); + */ + preparedstatementHandler.prepareResultSet(query, getdbsrs); + } + + public static void refreshTableForPartitionTable( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet partitionTablemetadataRS = preparedstatementHandler + .createResultSet(); + partitionTablemetadataRS.addColumn("oid"); + partitionTablemetadataRS.addColumn("relname"); + partitionTablemetadataRS.addColumn("relnamespace"); + partitionTablemetadataRS.addColumn("reltablespace"); + partitionTablemetadataRS.addColumn("relpersistence"); + partitionTablemetadataRS.addColumn("desc"); + partitionTablemetadataRS.addColumn("nodes"); + partitionTablemetadataRS.addColumn("reloptions"); + + partitionTablemetadataRS.addRow(new Object[] {1, "MyTable", 1, 1, true, + "description", "1 2", ""}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.REFRESH_TABLE_METADATA_PARTITION_TABLE, + partitionTablemetadataRS); + MockResultSet getcolumninfoRSptble_1 = preparedstatementHandler + .createResultSet(); + getcolumninfoRSptble_1.addColumn("tableid"); + getcolumninfoRSptble_1.addColumn("namespaceid"); + getcolumninfoRSptble_1.addColumn("columnidx"); + getcolumninfoRSptble_1.addColumn("name"); + getcolumninfoRSptble_1.addColumn("datatypeoid"); + getcolumninfoRSptble_1.addColumn("dtns"); + getcolumninfoRSptble_1.addColumn("length"); + getcolumninfoRSptble_1.addColumn("precision"); + getcolumninfoRSptble_1.addColumn("dimentions"); + getcolumninfoRSptble_1.addColumn("notnull"); + getcolumninfoRSptble_1.addColumn("isdefaultvalueavailable"); + getcolumninfoRSptble_1.addColumn("default_value"); + getcolumninfoRSptble_1.addColumn("attDefStr"); + getcolumninfoRSptble_1.addColumn("displayColumns"); + getcolumninfoRSptble_1 + .addRow(new Object[] {1, 1, 1, "ColName", 1, 1, 200, 0, 0, + false, true, "Default value", "attrString", "bigint"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_COLUMN_INFO_PARTITION_TABLE, + getcolumninfoRSptble_1); + + MockResultSet partitionConstraintRS_1 = preparedstatementHandler + .createResultSet(); + partitionConstraintRS_1.addColumn("constraintid"); + partitionConstraintRS_1.addColumn("tableid"); + partitionConstraintRS_1.addColumn("namespaceid"); + partitionConstraintRS_1.addColumn("constraintname"); + partitionConstraintRS_1.addColumn("constrainttype"); + partitionConstraintRS_1.addColumn("deferrable"); + partitionConstraintRS_1.addColumn("deferred"); + partitionConstraintRS_1.addColumn("validate"); + partitionConstraintRS_1.addColumn("indexid"); + partitionConstraintRS_1.addColumn("fkeytableId"); + partitionConstraintRS_1.addColumn("updatetype"); + partitionConstraintRS_1.addColumn("deletetype"); + partitionConstraintRS_1.addColumn("matchtype"); + partitionConstraintRS_1.addColumn("expr"); + partitionConstraintRS_1.addColumn("columnlist"); + partitionConstraintRS_1.addColumn("fkeycolumnlist"); + partitionConstraintRS_1.addColumn("const_def"); + partitionConstraintRS_1.addRow(new Object[] {1, 1, 1, "ConstraintName", + "ConstraintType", false, false, false, 1, 1, "", "", "", "", + "1", "1", ""}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_PARTITION_CONSTRAINT, + partitionConstraintRS_1); + + MockResultSet indexpartitionRS_1 = preparedstatementHandler + .createResultSet(); + indexpartitionRS_1.addColumn("oid"); + indexpartitionRS_1.addColumn("tableId"); + indexpartitionRS_1.addColumn("indexname"); + indexpartitionRS_1.addColumn("namespaceid"); + indexpartitionRS_1.addColumn("accessmethodid"); + indexpartitionRS_1.addColumn("isunique"); + indexpartitionRS_1.addColumn("isprimary"); + indexpartitionRS_1.addColumn("isexclusion"); + indexpartitionRS_1.addColumn("isimmediate"); + indexpartitionRS_1.addColumn("isclustered"); + indexpartitionRS_1.addColumn("checkmin"); + indexpartitionRS_1.addColumn("isready"); + indexpartitionRS_1.addColumn("cols"); + indexpartitionRS_1.addColumn("reloptions"); + indexpartitionRS_1.addColumn("indexdef"); + indexpartitionRS_1.addColumn("tablespace"); + indexpartitionRS_1.addRow(new Object[] {1, 1, "IndexName", 1, 1, true, + false, false, false, false, false, false, "1", "", "", ""}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_PARTITION_INDEX, indexpartitionRS_1); + + MockResultSet getPartitionsRS_1 = preparedstatementHandler + .createResultSet(); + getPartitionsRS_1.addColumn("partition_id"); + getPartitionsRS_1.addColumn("partition_name"); + getPartitionsRS_1.addColumn("table_id"); + + getPartitionsRS_1.addRow(new Object[] {1, "part_1", 1}); + preparedstatementHandler.prepareResultSet(CommonLLTUtils.GET_PARTITION, + getPartitionsRS_1); + + } + + public static void getRsForAutoSuggest( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet namespaceRS = preparedstatementHandler.createResultSet(); + namespaceRS.addColumn("oid"); + namespaceRS.addColumn("nspname"); + namespaceRS.addRow(new Object[] {1, "ns1"}); + namespaceRS.addRow(new Object[] {2, "NS1"}); + namespaceRS.addRow(new Object[] {3, "Ns1"}); + namespaceRS.addRow(new Object[] {4, "ns2"}); + namespaceRS.addRow(new Object[] {5, "NS3"}); + namespaceRS.addRow(new Object[] {6, "\"NS1\""}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtils.GET_ALL_NAMESPACE, namespaceRS); + + String REFRESH_TABLE = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, " + + "c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, " + + "c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value " + + "from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.relkind = 'r') " + + "left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) " + + "where c.attisdropped = 'f' and c.attnum > 0 and t.relnamespace = " + + 1 + " order by t.oid, c.attnum;"; + + MockResultSet colmetadataRS = preparedstatementHandler + .createResultSet(); + colmetadataRS.addColumn("tableid"); + colmetadataRS.addColumn("namespaceid"); + colmetadataRS.addColumn("columnidx"); + colmetadataRS.addColumn("name"); + colmetadataRS.addColumn("datatypeoid"); + colmetadataRS.addColumn("dtns"); + colmetadataRS.addColumn("length"); + colmetadataRS.addColumn("precision"); + colmetadataRS.addColumn("dimentions"); + colmetadataRS.addColumn("notnull"); + colmetadataRS.addColumn("isdefaultvalueavailable"); + colmetadataRS.addColumn("default_value"); + + colmetadataRS.addRow(new Object[] {1, 1, 1, "tbl1", 1, 1, 200, 0, 0, + false, true, "Default value"}); + colmetadataRS.addRow(new Object[] {2, 1, 1, "tbl2", 1, 1, 200, 0, 0, + false, true, "Default value"}); + colmetadataRS.addRow(new Object[] {3, 1, 1, "TBL1", 1, 1, 200, 0, 0, + false, true, "Default value"}); + preparedstatementHandler.prepareResultSet(REFRESH_TABLE, colmetadataRS); + + String REFRESH_TABLE1 = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, " + + "c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, " + + "c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value " + + "from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.relkind = 'r') " + + "left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) " + + "where c.attisdropped = 'f' and c.attnum > 0 and t.relnamespace = " + + 2 + " order by t.oid, c.attnum;"; + + MockResultSet colmetadataRS1 = preparedstatementHandler + .createResultSet(); + colmetadataRS1.addColumn("tableid"); + colmetadataRS1.addColumn("namespaceid"); + colmetadataRS1.addColumn("columnidx"); + colmetadataRS1.addColumn("name"); + colmetadataRS1.addColumn("datatypeoid"); + colmetadataRS1.addColumn("dtns"); + colmetadataRS1.addColumn("length"); + colmetadataRS1.addColumn("precision"); + colmetadataRS1.addColumn("dimentions"); + colmetadataRS1.addColumn("notnull"); + colmetadataRS1.addColumn("isdefaultvalueavailable"); + colmetadataRS1.addColumn("default_value"); + + colmetadataRS1.addRow(new Object[] {1, 2, 1, "tbl1", 1, 1, 200, 0, 0, + false, true, "Default value"}); + colmetadataRS1.addRow(new Object[] {2, 2, 1, "tbl2", 1, 1, 200, 0, 0, + false, true, "Default value"}); + colmetadataRS1.addRow(new Object[] {3, 2, 1, "TBL1", 1, 1, 200, 0, 0, + false, true, "Default value"}); + colmetadataRS1.addRow(new Object[] {3, 2, 1, "Tbl1", 1, 1, 200, 0, 0, + false, true, "Default value"}); + preparedstatementHandler.prepareResultSet(REFRESH_TABLE1, + colmetadataRS1); + + String REFRESH_TABLE2 = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, " + + "c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, " + + "c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value " + + "from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.relkind = 'r') " + + "left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) " + + "where c.attisdropped = 'f' and c.attnum > 0 and t.relnamespace = " + + 3 + " order by t.oid, c.attnum;"; + + MockResultSet colmetadataRS2 = preparedstatementHandler + .createResultSet(); + colmetadataRS2.addColumn("tableid"); + colmetadataRS2.addColumn("namespaceid"); + colmetadataRS2.addColumn("columnidx"); + colmetadataRS2.addColumn("name"); + colmetadataRS2.addColumn("datatypeoid"); + colmetadataRS2.addColumn("dtns"); + colmetadataRS2.addColumn("length"); + colmetadataRS2.addColumn("precision"); + colmetadataRS2.addColumn("dimentions"); + colmetadataRS2.addColumn("notnull"); + colmetadataRS2.addColumn("isdefaultvalueavailable"); + colmetadataRS2.addColumn("default_value"); + + colmetadataRS2.addRow(new Object[] {1, 4, 1, "Tbl1", 1, 1, 200, 0, 0, + false, true, "Default value"}); + colmetadataRS2.addRow(new Object[] {2, 4, 1, "xtbl2", 1, 1, 200, 0, 0, + false, true, "Default value"}); + colmetadataRS2.addRow(new Object[] {3, 4, 1, "xtbl1", 1, 1, 200, 0, 0, + false, true, "Default value"}); + + preparedstatementHandler.prepareResultSet(REFRESH_TABLE2, + colmetadataRS2); + + String REFRESH_TABLE3 = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, " + + "c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, " + + "c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value " + + "from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.relkind = 'r') " + + "left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) " + + "where c.attisdropped = 'f' and c.attnum > 0 and t.relnamespace = " + + 4 + " order by t.oid, c.attnum;"; + + MockResultSet colmetadataRS3 = preparedstatementHandler + .createResultSet(); + colmetadataRS3.addColumn("tableid"); + colmetadataRS3.addColumn("namespaceid"); + colmetadataRS3.addColumn("columnidx"); + colmetadataRS3.addColumn("name"); + colmetadataRS3.addColumn("datatypeoid"); + colmetadataRS3.addColumn("dtns"); + colmetadataRS3.addColumn("length"); + colmetadataRS3.addColumn("precision"); + colmetadataRS3.addColumn("dimentions"); + colmetadataRS3.addColumn("notnull"); + colmetadataRS3.addColumn("isdefaultvalueavailable"); + colmetadataRS3.addColumn("default_value"); + + colmetadataRS3.addRow(new Object[] {1, 4, 1, "Tbl1", 1, 1, 200, 0, 0, + false, true, "Default value"}); + colmetadataRS3.addRow(new Object[] {2, 4, 1, "xtbl2", 1, 1, 200, 0, 0, + false, true, "Default value"}); + colmetadataRS3.addRow(new Object[] {3, 4, 1, "xtbl1", 1, 1, 200, 0, 0, + false, true, "Default value"}); + preparedstatementHandler.prepareResultSet(REFRESH_TABLE3, + colmetadataRS3); + + String REFRESH_TABLE4 = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, " + + "c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, " + + "c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value " + + "from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.relkind = 'r') " + + "left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) " + + "where c.attisdropped = 'f' and c.attnum > 0 and t.relnamespace = " + + 5 + " order by t.oid, c.attnum;"; + + MockResultSet colmetadataRS4 = preparedstatementHandler + .createResultSet(); + colmetadataRS4.addColumn("tableid"); + colmetadataRS4.addColumn("namespaceid"); + colmetadataRS4.addColumn("columnidx"); + colmetadataRS4.addColumn("name"); + colmetadataRS4.addColumn("datatypeoid"); + colmetadataRS4.addColumn("dtns"); + colmetadataRS4.addColumn("length"); + colmetadataRS4.addColumn("precision"); + colmetadataRS4.addColumn("dimentions"); + colmetadataRS4.addColumn("notnull"); + colmetadataRS4.addColumn("isdefaultvalueavailable"); + colmetadataRS4.addColumn("default_value"); + + colmetadataRS4.addRow(new Object[] {1, 5, 1, "NS1", 1, 1, 200, 0, 0, + false, true, "Default value"}); + + preparedstatementHandler.prepareResultSet(REFRESH_TABLE4, + colmetadataRS4); + + String REFRESH_TABLE5 = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, " + + "c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, " + + "c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value " + + "from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.relkind = 'r') " + + "left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) " + + "where c.attisdropped = 'f' and c.attnum > 0 and t.relnamespace = " + + 6 + " order by t.oid, c.attnum;"; + + MockResultSet colmetadataRS5 = preparedstatementHandler + .createResultSet(); + colmetadataRS5.addColumn("tableid"); + colmetadataRS5.addColumn("namespaceid"); + colmetadataRS5.addColumn("columnidx"); + colmetadataRS5.addColumn("name"); + colmetadataRS5.addColumn("datatypeoid"); + colmetadataRS5.addColumn("dtns"); + colmetadataRS5.addColumn("length"); + colmetadataRS5.addColumn("precision"); + colmetadataRS5.addColumn("dimentions"); + colmetadataRS5.addColumn("notnull"); + colmetadataRS5.addColumn("isdefaultvalueavailable"); + colmetadataRS5.addColumn("default_value"); + + colmetadataRS5.addRow(new Object[] {1, 6, 1, "TBL2", 1, 1, 200, 0, 0, + false, true, "Default value"}); + + preparedstatementHandler.prepareResultSet(REFRESH_TABLE5, + colmetadataRS5); + + } + + public static void prepareEditTableDataResultSet( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet editTableResultSet = preparedstatementHandler + .createResultSet(); + editTableResultSet.addColumn("Emp_ID"); + editTableResultSet.addColumn("Emp_NAME"); + editTableResultSet.addColumn("EMP_AGE"); + editTableResultSet.addRow(new Object[] {1, "Item1", "31"}); + editTableResultSet.addRow(new Object[] {2, "Item2", "45"}); + editTableResultSet.addRow(new Object[] {3, "Item3", "21"}); + editTableResultSet.addRow(new Object[] {4, "Item4", "25"}); + editTableResultSet.addRow(new Object[] {5, "Item5", "30"}); + editTableResultSet.addRow(new Object[] {6, "Item6", "20"}); + editTableResultSet.addRow(new Object[] {7, null, null}); + preparedstatementHandler.prepareResultSet(EDIT_TABLE_DATA_SELECT_QUERY, + editTableResultSet); + + } + + public static void prepareDistibutionColumnListResultSetWithHashDistribution( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet hashDistributionColRS = preparedstatementHandler + .createResultSet(); + + hashDistributionColRS.addColumn("distriute_type"); + hashDistributionColRS.addColumn("distributekey"); + hashDistributionColRS.addRow(new Object[] {"Hash", "Emp_ID,Emp_NAME"}); + preparedstatementHandler.prepareResultSet( + FETCH_DISTRIBUTION_COLUMNLIST_QUERY, hashDistributionColRS); + + } + + public static void prepareDistibutionColumnListResultSetWithReplicationDistribution( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet hashDistributionColRS = preparedstatementHandler + .createResultSet(); + + hashDistributionColRS.addColumn("distriute_type"); + hashDistributionColRS.addColumn("distributekey"); + hashDistributionColRS + .addRow(new Object[] {"REPLICATION", "Emp_ID,Emp_NAME"}); + + preparedstatementHandler.prepareResultSet( + FETCH_DISTRIBUTION_COLUMNLIST_QUERY, hashDistributionColRS); + } + + public static void prepareInsertQueryForEditTableData( + PreparedStatementResultSetHandler preparedstatementHandler, + MockConnection connection) + { + String query = "INSERT into \"pg_catalog\".\"EditTable\" (\"Emp_ID\", \"Emp_NAME\", \"EMP_AGE\") values (?, ?, ?) RETURNING *"; + // preparedstatementHandler.prepareUpdateCount(query, 1); + MockResultSet resultset = preparedstatementHandler.createResultSet(); + resultset.addColumn("Emp_ID"); + resultset.addColumn("Emp_NAME"); + resultset.addColumn("EMP_AGE"); + // resultset.addRow( new Object[]{"101","newItem1","25"}); + preparedstatementHandler.prepareResultSet(query, resultset); + + } + + public static void prepareUpdateQueryForEditTableData(PreparedStatementResultSetHandler preparedstatementHandler, MockConnection connection) + { + String query ="UPDATE \"pg_catalog\".\"EditTable\" SET \"Emp_ID\"= 101, \"Emp_NAME\"= newItem1, \"EMP_AGE\"= 25 WHERE \"Emp_ID\" = 1 AND \"Emp_NAME\" = Item1"; + MockResultSet resultset= preparedstatementHandler.createResultSet(); + resultset.addColumn("Emp_ID"); + resultset.addColumn("Emp_NAME"); + resultset.addColumn("EMP_AGE"); + resultset.addRow( new Object[]{"101","newitem1","25"}); + preparedstatementHandler.prepareResultSet(query, + resultset); + + } + + + public static void updateSelectQryCursorExecRS(StatementResultSetHandler preparedstatementHandler) + { + MockResultSet getselectrs = preparedstatementHandler.createResultSet(); + getselectrs.addColumn("amopfamily"); + getselectrs.addColumn("amoplefttype"); + getselectrs.addColumn("amoprighttype"); + getselectrs.addColumn("amopstrategy"); + getselectrs.addColumn("amoppurpose"); + getselectrs.addColumn("amopopr"); + getselectrs.addColumn("amopmethod"); + getselectrs.addColumn("amopsortfamily"); + + getselectrs.addRow(new Object[] {1, 21, 23, 5, 's', 77, 403, 0 }); + + preparedstatementHandler.prepareResultSet(CURSOR_QUERY_EXECUTION, getselectrs); + } + + + + public static Gauss200V1R7Driver mockConnection(Driver driver) { + ArrayList olapDriverInstance = DBMSDriverManager.getOLAPDriverInstance(""); + + Gauss200V1R7Driver lGauss200V1R7Driver = getGaussDriver(driver); + + olapDriverInstance.add(0,lGauss200V1R7Driver); + olapDriverInstance.add(1,lGauss200V1R7Driver); + return lGauss200V1R7Driver; + } + + public static Gauss200V1R7Driver getGaussDriver(Driver driver) { + Gauss200V1R7Driver lGauss200V1R7Driver=new Gauss200V1R7Driver("") { + @Override + protected void configureDriverDetails(String dsInstallPath) { + super.configureDriverDetails(dsInstallPath); + setDriver(MPPDBIDEConstants.GAUSS200V1R7DRIVER); + setJDBCDriver(driver); + }}; + return lGauss200V1R7Driver; + } + + public static void runLinuxFilePermissionInstance() throws Exception { + Object filePermissionFactory = FilePermissionFactory.class.newInstance(); + Field f1 = filePermissionFactory.getClass().getDeclaredField("INSTANCE"); + f1.setAccessible(true); + if (isLinux()) { + f1.set(filePermissionFactory, new SetFilePermissionLinux()); + } else { + f1.set(filePermissionFactory, new SetFilePermissionWindows()); + } + } + + private static class SetFilePermissionLinux implements ISetFilePermission { + + @Override + public Path createFileWithPermission(String path, boolean isDir, Set userChosenPermissions, + boolean setDefaultOnNull) throws DatabaseOperationException { + // To Auto-generated method stub + Path newPath = Paths.get(path); + + // Check if file already exists + boolean fileExists = Files.exists(newPath); + + try { + if (isDir) { + // If create log directory and logs folder does not exist, + // create it with security permissions. + + /* default Directory permission 700 */ + Set permsDir = new HashSet(); + permsDir.add(PosixFilePermission.OWNER_READ); + permsDir.add(PosixFilePermission.OWNER_WRITE); + permsDir.add(PosixFilePermission.OWNER_EXECUTE); + if (!fileExists) { + + newPath = Files.createDirectory(newPath); + Files.setPosixFilePermissions(newPath, permsDir); + + } + } else { + // Create file with security permissions. + + /* default File permission 644 */ + + Set permsFile = new HashSet(); + permsFile.add(PosixFilePermission.OWNER_READ); + permsFile.add(PosixFilePermission.OWNER_WRITE); + permsFile.add(PosixFilePermission.OWNER_EXECUTE); + if (!fileExists) { + newPath = Files.createFile(newPath); + } + Files.setPosixFilePermissions(newPath, permsFile); + } + + } catch (IOException exception) { + try { + Files.deleteIfExists(newPath); + } catch (IOException e1) { + MPPDBIDELoggerUtility.trace("Error while deleting file in exception."); + } + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.FILE_PERMISSION_ERROR), + exception); + throw new DatabaseOperationException(IMessagesConstants.FILE_PERMISSION_ERROR, exception); + } + return newPath; + + } + } + + public static void setConnectionManagerConnectionDriver(IConnectionDriver connectionDriver,Database db) throws Exception { + Object connectionManagerInstance = db.getConnectionManager(); + Field f1 = connectionManagerInstance.getClass().getDeclaredField("connectionDriver"); + f1.setAccessible(true); + f1.set(connectionManagerInstance, connectionDriver); + } + + public static boolean isWindows() { + if ((System.getProperty(OS_NAME)).contains(WINDOWS)) { + return true; + } + return false; + } + + public static boolean isLinux() { + if ((System.getProperty(OS_NAME)).contains(LINUX)) { + return true; + } + return false; + } + + private static class SetFilePermissionWindows implements ISetFilePermission { + @Override + public Path createFileWithPermission(String path, boolean isDir, Set userChosenPermissions, + boolean setDefaultOnNull) throws DatabaseOperationException { + Path newPath = Paths.get(path); + boolean fileExists = Files.exists(newPath); + FileAttribute> fileAttributes = new DSFileAttributes(userChosenPermissions); + try { + if (isDir) { + if (!fileExists) { + if (setDefaultOnNull) { + try { + newPath = Files.createDirectory(newPath); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FOLDER_FAIL_ERR), + exception); + } + } else { + newPath = Files.createDirectory(newPath); + } + } + } else { + if (!fileExists) { + if (setDefaultOnNull) { + try { + Files.createFile(newPath); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FILE_FAIL_ERR), + exception); + } + } else { + newPath = Files.createFile(newPath); + } + } + } + + } catch (IOException exception) { + try { + Files.deleteIfExists(newPath); + } catch (IOException e1) { + MPPDBIDELoggerUtility.error("Error while deleting file in exception.", e1); + throw new DatabaseOperationException("Error while deleting file in exception."); + } + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.FILE_PERMISSION_ERROR), + exception); + throw new DatabaseOperationException(IMessagesConstants.FILE_PERMISSION_ERROR, exception); + } + return newPath; + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/CommonLLTUtilsHelper.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/CommonLLTUtilsHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..67dc0ab3940630d4eaffba62a86066475974d4ec --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/CommonLLTUtilsHelper.java @@ -0,0 +1,1589 @@ +package org.opengauss.mppdbide.mock.presentation; + +import org.opengauss.mppdbide.bl.serverdatacache.ObjectParameter; +import org.opengauss.mppdbide.bl.serverdatacache.ObjectParameter.PARAMETERTYPE; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.JDBCMockObjectFactory; +import com.mockrunner.mock.jdbc.MockConnection; +import com.mockrunner.mock.jdbc.MockResultSet; + +public class CommonLLTUtilsHelper +{ + + public enum EXCEPTIONENUM + { + YES, NO, EXCEPTION + } + + public static final String GET_ALL_SHALLOWLOADTABLES = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, " + + " tbl.relpersistence relpersistence from pg_class tbl where tbl.relkind = 'r' " + + "and tbl.relnamespace not in (select oid from pg_namespace where nspname in ('cstore', 'pg_toast')) " + + "order by relname"; + public static final String Shallowload1 = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, tbl.relpersistence relpersistence,ts.spcname as reltablespace " + + "from pg_class tbl left join pg_tablespace ts on ts.oid = tbl.reltablespace " + + "where tbl.relkind = 'r' and tbl.relnamespace not in " + + "(select oid from pg_namespace where nspname in ('cstore', 'pg_toast'))" + + " order by relname"; + public static final String SHALLOWLOADQUERY = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, " + + "pr.pronargs nargs,pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, " + + "pr.proisstrict isstrict, pr.proretset retset, pr.procost procost, pr.prorows setrows FROM pg_proc pr " + + "JOIN pg_type typ ON typ.oid=prorettype JOIN pg_namespace typns ON typns.oid=typ.typnamespace JOIN pg_language lng ON lng.oid=prolang " + + "WHERE lng.lanname='plpgsql' ORDER BY objname"; + public static final String TRIGGERONLY = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs,pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, pr.proisstrict isstrict, pr.proretset retset, pr.procost procost, pr.prorows setrows FROM pg_proc pr JOIN pg_type typ ON typ.oid=prorettype JOIN pg_namespace typns ON typns.oid=typ.typnamespace JOIN pg_language lng ON lng.oid=prolang WHERE lng.lanname='plpgsql' and UPPER(typ.typname) = 'TRIGGER' ORDER BY objname"; + public static final String TRIGGERONLY1 = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs,pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, pr.proisstrict isstrict, pr.proretset retset, pr.procost procost, pr.prorows setrows FROM pg_proc pr JOIN pg_type typ ON typ.oid=prorettype JOIN pg_namespace typns ON typns.oid=typ.typnamespace JOIN pg_language lng ON lng.oid=prolang WHERE lng.lanname='plpgsql' and UPPER(typ.typname) != 'TRIGGER' "; + public static final String FUNCTIONONLY = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs,pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, pr.proisstrict isstrict, pr.proretset retset, pr.procost procost, pr.prorows setrows FROM pg_proc pr JOIN pg_type typ ON typ.oid=prorettype JOIN pg_namespace typns ON typns.oid=typ.typnamespace JOIN pg_language lng ON lng.oid=prolang WHERE lng.lanname='plpgsql' and UPPER(typ.typname) != 'TRIGGER' and pr.pronamespace= 1 ORDER BY objname"; + public static final String SHALLOWLOADQUERYDEFAULT = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs,pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, pr.proisstrict isstrict, pr.proretset retset, pr.procost procost, pr.prorows setrows FROM pg_proc pr JOIN pg_type typ ON typ.oid=prorettype JOIN pg_namespace typns ON typns.oid=typ.typnamespace JOIN pg_language lng ON lng.oid=prolang WHERE lng.lanname='plpgsql' and pr.pronamespace= 1 ORDER BY objname"; + + public static final String GET_ALL_FUNCTION_QUERY = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype,pr.pronargs nargs,pr.proargtypes argtype, " + + "pr.proargnames argname,pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, pr.proisstrict isstrict, pr.proretset retset, pr.procost procost, pr.prorows setrows" + + " FROM pg_proc pr " + + " JOIN pg_type typ ON typ.oid=prorettype JOIN pg_namespace typns ON typns.oid=typ.typnamespace" + + " JOIN pg_language lng ON lng.oid=prolang LEFT OUTER JOIN pg_description des ON des.objoid=pr.oid " + + " WHERE lng.lanname='plpgsql' and UPPER(typ.typname) != 'TRIGGER' AND pr.pronamespace=" + + 1 + " ORDER BY objname;"; + + public static final String GET_ALL_TABLE_METADATA = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes " + + "from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) " + + "left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r'"; + + public static final String GET_ALL_DATATYPE = "select typ.oid as oid, typ.typname as typname, typ.typnamespace as typnamespace, " + + "typ.typlen as typlen, typ.typbyval as typbyval, typ.typtype as typtype, typ.typcategory as typcategory, " + + "typ.typtypmod as typtypmod, typ.typnotnull as typnotnull, typ.typarray as typarray, des.description as desc " + + "from pg_type typ left join pg_description des on (typ.oid = des.objoid) "; + + public static final String GET_ALL_COLUMN_METADATA = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, " + + "c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, " + + "c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value " + + "from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.relkind = 'r') " + + "left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) " + + "where c.attisdropped = 'f' and c.attnum > 0 order by t.oid, c.attnum;"; + + public static final String GET_ALL_INDEXES = "SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, ci.relnamespace as namespaceid, " + + "ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, i.indisexclusion as isexclusion, " + + "i.indimmediate as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, i.indisready as isready, " + + "i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions FROM pg_index i LEFT JOIN pg_class t on (t.oid = i.indrelid) " + + "LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) WHERE t.relkind = 'r';"; + + public static final String GET_ALL_CONSTRAINTS = "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, " + + "c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, " + + "c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, " + + "c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, " + + "c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist " + + "FROM pg_constraint c LEFT JOIN pg_class t on (t.oid = c.conrelid) WHERE t.relkind = 'r'"; + + public static final String GET_ALL_TRIGGER_QUERY = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype,pr.pronargs nargs,pr.proargtypes argtype, " + + "pr.proargnames argname,pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, pr.proisstrict isstrict, pr.proretset retset, pr.procost procost, pr.prorows setrows" + + " FROM pg_proc pr " + + " JOIN pg_type typ ON typ.oid=prorettype JOIN pg_namespace typns ON typns.oid=typ.typnamespace" + + " JOIN pg_language lng ON lng.oid=prolang LEFT OUTER JOIN pg_description des ON des.objoid=pr.oid " + + " WHERE lng.lanname='plpgsql' and UPPER(typ.typname) = 'TRIGGER' and pr.pronamespace=" + + 1 + " ORDER BY objname;"; + + public static final String GET_FUNCTION_WITH_HEADER = "select a.headerlines, a.definition, b.xmin, b.cmin from pg_proc b left join " + + "(select * from PG_GET_FUNCTIONDEF("; + + public static final String GET_NAMESPACE_QUERY = "SELECT nspname from pg_namespace where oid = ?"; + public static final String SYNC_QUERY = "SELECT FUNC, LINENUMBER," + + " TARGETNAME from pldbg_sync_target(?);"; + public static final String GET_SOURCE_VERSION = "SELECT * from pldbg_get_funcVer(?);"; + public static final String REFRESH_OBJECT_QUERY = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype,pr.pronargs nargs,pr.proargtypes argtype, " + + "pr.proargnames argname,pr.proargmodes argmod,pr.prosecdef secdef, pr.provolatile vola, pr.proisstrict isstrict, pr.proretset retset, pr.procost procost, pr.prorows setrows" + + " FROM pg_proc pr WHERE oid = ?"; + + public static final String GET_VARIABLES = "SELECT NAME, LINENUMBER," + + " VARCLASS, ISCONST, DTYPE, ISVALUENULL, VALUE " + + "FROM pldbg_get_variables(?);"; + + public static final String GET_VARIABLE = "SELECT NAME, LINENUMBER," + + " VARCLASS, ISCONST, DTYPE, ISVALUENULL, VALUE " + + "from pldbg_get_varinfo(?,?,?);"; + + public static final String GET_ALL_NAMESPACE = "SELECT oid, nspname from pg_namespace where nspname NOT LIKE 'pg_toast%' and nspname NOT LIKE 'pg_temp%' and has_schema_privilege(nspname, 'USAGE') ORDER BY nspname;"; + + public static final String GET_NAMESPACE_BY_ID = "SELECT oid, nspname from pg_namespace WHERE oid=?"; + + public static final String CREATE_EXTENSION = "CREATE EXTENSION IF NOT EXISTS pldbgapi"; + + public static final String DETACH_SESSION = "SELECT pldbg_detach_session(?);"; + + public static final String ATTACH_SESSION = "SELECT pldbg_attach_session(?,?);"; + + public static final String GET_STACK = "SELECT pldbg_get_stack(?);"; + + public static final String STEP_INTO = "SELECT FUNC, LINENUMBER," + + " TARGETNAME from pldbg_step_into(?);"; + + public static final String STEP_OUT = "SELECT FUNC, LINENUMBER," + + " TARGETNAME from pldbg_step_out(?);"; + + public static final String STEP_OVER = "SELECT FUNC, LINENUMBER," + + " TARGETNAME from pldbg_step_over(?);"; + + public static final String CONTINUE = "SELECT FUNC, LINENUMBER," + + " TARGETNAME from pldbg_continue(?);"; + + public static final String DEPOSIT_VALUE = "SELECT pldbg_deposit_value(?,?,?,?);"; + + public static final String DEBUG_ID = "SELECT pg_backend_pid();"; + + public static final String FUNCTION_VERSION = "SELECT * from pldbg_get_funcVer(?);"; + + public static final String SERVER_SYNC = "SELECT pldbg_server_in_sync(?);"; + + private static final String BREAKPOINT_DELETE = "SELECT pldbg_drop_breakpoint(?,?,?,?);"; + + public static final String GET_ALL_VIEWS = "select v.oid as viewid, v.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, " + + "c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, " + + "c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value " + + "from pg_class v " + + "left join pg_attribute c on (v.oid = c.attrelid and v.relkind = 'v') " + + "left join pg_attrdef d on (v.oid = d.adrelid and c.attnum = d.adnum) " + + "left join pg_type typ on (c.atttypid = typ.oid) " + + "where c.attisdropped = 'f' and c.attnum > 0 " + + " and v.relnamespace = " + 1 + " order by v.oid, c.attnum"; + + public static void prepareConnectionResultSets( + JDBCMockObjectFactory objectFactory) + { + MockConnection connection = objectFactory.getMockConnection(); + + PreparedStatementResultSetHandler preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + MockResultSet listnerResultSet = preparedstatementHandler + .createResultSet(); + listnerResultSet.addRow(new Integer[] {12}); + preparedstatementHandler.prepareResultSet( + "SELECT pldbg_create_listener();", listnerResultSet); + + MockResultSet initializeDebugResult = preparedstatementHandler + .createResultSet(); + initializeDebugResult.addRow(new String[] {"1231"}); + preparedstatementHandler.prepareResultSet( + "SELECT pldbg_initialize_debug();", initializeDebugResult); + + MockResultSet attachResult = preparedstatementHandler.createResultSet(); + attachResult.addRow(new Boolean[] {true}); + + preparedstatementHandler.prepareResultSet( + "SELECT pldbg_attach_session(?,?);", attachResult); + + MockResultSet detachResult = preparedstatementHandler.createResultSet(); + detachResult.addRow(new Boolean[] {true}); + preparedstatementHandler.prepareResultSet( + "SELECT pldbg_detach_session(?);", detachResult); + + MockResultSet isDebugResult = preparedstatementHandler + .createResultSet(); + isDebugResult.addRow(new Boolean[] {true}); + + preparedstatementHandler.prepareResultSet("SELECT pldbg_is_debug_on();", + isDebugResult); + + MockResultSet debugOn = preparedstatementHandler.createResultSet(); + debugOn.addRow(new Boolean[] {true}); + preparedstatementHandler.prepareResultSet("SELECT pldbg_debug_on();", + debugOn); + + MockResultSet debugOff = preparedstatementHandler.createResultSet(); + debugOff.addRow(new Boolean[] {true}); + preparedstatementHandler.prepareResultSet("SELECT pldbg_debug_off();", + debugOff); + + MockResultSet tablespaceMetaData = preparedstatementHandler + .createResultSet(); + tablespaceMetaData.addColumn("oid"); + tablespaceMetaData.addColumn("spcname"); + tablespaceMetaData.addColumn("spcoptions"); + tablespaceMetaData.addColumn("location"); + tablespaceMetaData.addColumn("spcmaxsize"); + tablespaceMetaData.addColumn("relative"); + tablespaceMetaData.addRow(new Object[] {1, "tblspc", + new String[] {"spcoptions=options"}, "location", "spcmaxsize", false}); + preparedstatementHandler.prepareResultSet( + "select oid, pg_tablespace_location(oid) as location, spcname,spcacl,spcoptions, spcmaxsize, relative from pg_tablespace where oid =" + + 1, + tablespaceMetaData); + + MockResultSet setDebugPositionRS = preparedstatementHandler + .createResultSet(); + setDebugPositionRS.addRow(new String[] {"(6,5)"}); + preparedstatementHandler.prepareResultSet( + "SELECT FUNC, LINENUMBER," + + " TARGETNAME from pldbg_sync_target(?);", + setDebugPositionRS); + + prepareProxyInfo(preparedstatementHandler); + prepareValidateVersion(preparedstatementHandler); + + MockResultSet namespaceRS = preparedstatementHandler.createResultSet(); + namespaceRS.addColumn("oid"); + namespaceRS.addColumn("nspname"); + namespaceRS.addRow(new Object[] {1, "PUBLIC"}); + namespaceRS.addRow(new Object[] {1, "pg_catalog"}); + namespaceRS.addRow(new Object[] {2, "information_schema"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtilsHelper.GET_ALL_NAMESPACE, namespaceRS); + + MockResultSet refreshnamespaceRS = preparedstatementHandler + .createResultSet(); + refreshnamespaceRS.addColumn("oid"); + refreshnamespaceRS.addColumn("nspname"); + refreshnamespaceRS.addRow(new Object[] {1, "PUBLIC"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtilsHelper.GET_NAMESPACE_BY_ID, refreshnamespaceRS); + + } + + public static void prepareConnectionResultSetsNoNSP( + JDBCMockObjectFactory objectFactory) + { + MockConnection connection = objectFactory.getMockConnection(); + + PreparedStatementResultSetHandler preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + MockResultSet listnerResultSet = preparedstatementHandler + .createResultSet(); + listnerResultSet.addRow(new Integer[] {12}); + preparedstatementHandler.prepareResultSet( + "SELECT pldbg_create_listener();", listnerResultSet); + + MockResultSet initializeDebugResult = preparedstatementHandler + .createResultSet(); + initializeDebugResult.addRow(new String[] {"1231"}); + preparedstatementHandler.prepareResultSet( + "SELECT pldbg_initialize_debug();", initializeDebugResult); + + MockResultSet attachResult = preparedstatementHandler.createResultSet(); + attachResult.addRow(new Boolean[] {true}); + + preparedstatementHandler.prepareResultSet( + "SELECT pldbg_attach_session(?,?);", attachResult); + + MockResultSet detachResult = preparedstatementHandler.createResultSet(); + detachResult.addRow(new Boolean[] {true}); + preparedstatementHandler.prepareResultSet( + "SELECT pldbg_detach_session(?);", detachResult); + + MockResultSet isDebugResult = preparedstatementHandler + .createResultSet(); + isDebugResult.addRow(new Boolean[] {true}); + + preparedstatementHandler.prepareResultSet("SELECT pldbg_is_debug_on();", + isDebugResult); + + MockResultSet debugOn = preparedstatementHandler.createResultSet(); + debugOn.addRow(new Boolean[] {true}); + preparedstatementHandler.prepareResultSet("SELECT pldbg_debug_on();", + debugOn); + + MockResultSet debugOff = preparedstatementHandler.createResultSet(); + debugOff.addRow(new Boolean[] {true}); + preparedstatementHandler.prepareResultSet("SELECT pldbg_debug_off();", + debugOff); + + MockResultSet setDebugPositionRS = preparedstatementHandler + .createResultSet(); + setDebugPositionRS.addRow(new String[] {"(6,5)"}); + preparedstatementHandler.prepareResultSet( + "SELECT FUNC, LINENUMBER," + + " TARGETNAME from pldbg_sync_target(?);", + setDebugPositionRS); + + prepareProxyInfo(preparedstatementHandler); + prepareValidateVersion(preparedstatementHandler); + + MockResultSet namespaceRS = preparedstatementHandler.createResultSet(); + namespaceRS.addColumn("oid"); + namespaceRS.addColumn("nspname"); + // namespaceRS.addRow(new Object[]{1, "PUBLIC"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtilsHelper.GET_ALL_NAMESPACE, namespaceRS); + + MockResultSet refreshnamespaceRS = preparedstatementHandler + .createResultSet(); + refreshnamespaceRS.addColumn("oid"); + refreshnamespaceRS.addColumn("nspname"); + // refreshnamespaceRS.addRow(new Object[]{1, "PUBLIC"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtilsHelper.GET_NAMESPACE_BY_ID, refreshnamespaceRS); + + } + + public static void prepareFunctionResultSet(MockConnection connection) + { + PreparedStatementResultSetHandler preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + MockResultSet listnerResultSet = connection + .getPreparedStatementResultSetHandler().createResultSet(); + + listnerResultSet.addColumn("oid"); + listnerResultSet.addColumn("objname"); + listnerResultSet.addColumn("namespace"); + listnerResultSet.addColumn("ret"); + listnerResultSet.addColumn("alltype"); + listnerResultSet.addColumn("nargs"); + listnerResultSet.addColumn("argtype"); + listnerResultSet.addColumn("argname"); + listnerResultSet.addColumn("argmod"); + listnerResultSet.addColumn("secdef"); + listnerResultSet.addColumn("vola"); + listnerResultSet.addColumn("isstrict"); + listnerResultSet.addColumn("retset"); + listnerResultSet.addColumn("procost"); + listnerResultSet.addColumn("setrows"); + + ObjectParameter retParam = new ObjectParameter(); + retParam.setDataType("int"); + retParam.setName("a"); + retParam.setType(PARAMETERTYPE.IN); + + listnerResultSet.addRow(new Object[] {new Integer(2), "function2", 1, + new Integer(16), null, null, null, null, "mode", false, + "volatile", false, false, 10, 10}); + + preparedstatementHandler.prepareResultSet(GET_ALL_FUNCTION_QUERY, + listnerResultSet); + + MockResultSet nameSpaceResultSet = preparedstatementHandler + .createResultSet(); + nameSpaceResultSet.addColumn("nspname"); + nameSpaceResultSet.addRow(new Object[] {"PUBLIC"}); + preparedstatementHandler.prepareResultSet(GET_NAMESPACE_QUERY, + nameSpaceResultSet); + } + + public static void prepareFunctionResultSetNoNSP(MockConnection connection) + { + PreparedStatementResultSetHandler preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + MockResultSet listnerResultSet = connection + .getPreparedStatementResultSetHandler().createResultSet(); + + listnerResultSet.addColumn("oid"); + listnerResultSet.addColumn("objname"); + listnerResultSet.addColumn("namespace"); + listnerResultSet.addColumn("ret"); + listnerResultSet.addColumn("alltype"); + listnerResultSet.addColumn("nargs"); + listnerResultSet.addColumn("argtype"); + listnerResultSet.addColumn("argname"); + listnerResultSet.addColumn("argmod"); + listnerResultSet.addColumn("secdef"); + listnerResultSet.addColumn("vola"); + listnerResultSet.addColumn("isstrict"); + listnerResultSet.addColumn("retset"); + listnerResultSet.addColumn("procost"); + listnerResultSet.addColumn("setrows"); + + ObjectParameter retParam = new ObjectParameter(); + retParam.setDataType("int"); + retParam.setName("a"); + retParam.setType(PARAMETERTYPE.IN); + + listnerResultSet.addRow(new Object[] {new Integer(2), "function2", 1, + new Integer(16), null, null, null, null, "mode", false, + "volatile", false, false, 10, 10}); + + preparedstatementHandler.prepareResultSet(GET_ALL_FUNCTION_QUERY, + listnerResultSet); + + MockResultSet nameSpaceResultSet = preparedstatementHandler + .createResultSet(); + nameSpaceResultSet.addColumn("nspname"); + // nameSpaceResultSet.addRow(new Object[] {"PUBLIC"}); + preparedstatementHandler.prepareResultSet(GET_NAMESPACE_QUERY, + nameSpaceResultSet); + } + + public static void prepareFunctionWithParamResultSet( + MockConnection connection) + { + PreparedStatementResultSetHandler preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + MockResultSet listnerResultSet = connection + .getPreparedStatementResultSetHandler().createResultSet(); + + listnerResultSet.addColumn("oid"); + listnerResultSet.addColumn("objname"); + listnerResultSet.addColumn("namespace"); + listnerResultSet.addColumn("ret"); + listnerResultSet.addColumn("alltype"); + listnerResultSet.addColumn("nargs"); + listnerResultSet.addColumn("argtype"); + listnerResultSet.addColumn("argname"); + listnerResultSet.addColumn("argmod"); + listnerResultSet.addColumn("secdef"); + listnerResultSet.addColumn("vola"); + listnerResultSet.addColumn("isstrict"); + listnerResultSet.addColumn("retset"); + listnerResultSet.addColumn("procost"); + listnerResultSet.addColumn("setrows"); + + listnerResultSet.addRow(new Object[] {new Integer(2), "function2", 1, + new Integer(1), "{23,23,23}", null, "23", "{arg1,arg2, arg3}", + "{i,o,b}", false, "volatile", false, false, 0, 0}); + + preparedstatementHandler.prepareResultSet(GET_ALL_FUNCTION_QUERY, + listnerResultSet); + + MockResultSet nameSpaceResultSet = preparedstatementHandler + .createResultSet(); + nameSpaceResultSet.addColumn("nspname"); + nameSpaceResultSet.addRow(new Object[] {"PUBLIC"}); + preparedstatementHandler.prepareResultSet(GET_NAMESPACE_QUERY, + nameSpaceResultSet); + } + + public static void prepareFailureFunctionResultSet( + MockConnection connection) + { + PreparedStatementResultSetHandler preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + MockResultSet listnerResultSet = connection + .getPreparedStatementResultSetHandler().createResultSet(); + + listnerResultSet.addColumn("oid"); + listnerResultSet.addColumn("objname"); + listnerResultSet.addColumn("namespace"); + listnerResultSet.addColumn("ret"); + listnerResultSet.addColumn("alltype"); + listnerResultSet.addColumn("nargs"); + listnerResultSet.addColumn("argtype"); + listnerResultSet.addColumn("argname"); + listnerResultSet.addColumn("argmod"); + listnerResultSet.addColumn("secdef"); + listnerResultSet.addColumn("vola"); + listnerResultSet.addColumn("isstrict"); + listnerResultSet.addColumn("retset"); + listnerResultSet.addColumn("procost1"); + listnerResultSet.addColumn("setrows"); + + ObjectParameter retParam = new ObjectParameter(); + retParam.setDataType("int"); + retParam.setName("a"); + retParam.setType(PARAMETERTYPE.IN); + + listnerResultSet.addRow(new Object[] {new Integer(2), "function2", 1, + new Integer(16), null, null, null, null, "mode", false, + "volatile", false, false, 10}); + + preparedstatementHandler.prepareResultSet(GET_ALL_FUNCTION_QUERY, + listnerResultSet); + + MockResultSet nameSpaceResultSet = preparedstatementHandler + .createResultSet(); + nameSpaceResultSet.addColumn("nspname"); + nameSpaceResultSet.addRow(new Object[] {"public"}); + preparedstatementHandler.prepareResultSet(GET_NAMESPACE_QUERY, + nameSpaceResultSet); + } + + public static void prepareVersionCheckInitial( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet sourceVersionResultSet = preparedstatementHandler + .createResultSet(); + sourceVersionResultSet.addColumn("xmin"); + sourceVersionResultSet.addColumn("cmin"); + sourceVersionResultSet.addRow(new Object[] {1, 1}); + preparedstatementHandler.prepareResultSet(GET_SOURCE_VERSION, + sourceVersionResultSet); + } + + public static void prepareVersionCheckModified( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet sourceVersionResultSet = preparedstatementHandler + .createResultSet(); + sourceVersionResultSet.addColumn("xmin"); + sourceVersionResultSet.addColumn("cmin"); + sourceVersionResultSet.addRow(new Object[] {1, 1}); + preparedstatementHandler.prepareResultSet(GET_SOURCE_VERSION, + sourceVersionResultSet); + } + + public static void prepareTriggerResultSet(MockConnection connection) + { + PreparedStatementResultSetHandler preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + MockResultSet listnerResultSet = connection + .getPreparedStatementResultSetHandler().createResultSet(); + + listnerResultSet.addColumn("oid"); + listnerResultSet.addColumn("objname"); + listnerResultSet.addColumn("namespace"); + listnerResultSet.addColumn("ret"); + listnerResultSet.addColumn("alltype"); + listnerResultSet.addColumn("nargs"); + listnerResultSet.addColumn("argtype"); + listnerResultSet.addColumn("argname"); + listnerResultSet.addColumn("argmod"); + listnerResultSet.addColumn("secdef"); + listnerResultSet.addColumn("vola"); + listnerResultSet.addColumn("isstrict"); + listnerResultSet.addColumn("retset"); + listnerResultSet.addColumn("procost"); + listnerResultSet.addColumn("setrows"); + + ObjectParameter retParam = new ObjectParameter(); + retParam.setDataType("int"); + retParam.setName("a"); + retParam.setType(PARAMETERTYPE.IN); + + listnerResultSet.addRow(new Object[] {new Integer(1), "trigger1", 1, + new Integer(2279), null, null, null, null, "mode", false, + "volatile", false, false, 10, 10}); + + preparedstatementHandler.prepareResultSet(GET_ALL_TRIGGER_QUERY, + listnerResultSet); + MockResultSet nameSpaceResultSet = preparedstatementHandler + .createResultSet(); + nameSpaceResultSet.addColumn("nspname"); + nameSpaceResultSet.addRow(new Object[] {"PUBLIC"}); + preparedstatementHandler.prepareResultSet(GET_NAMESPACE_QUERY, + nameSpaceResultSet); + + } + + public static void prepareTriggerResultSetNoNSP(MockConnection connection) + { + PreparedStatementResultSetHandler preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + MockResultSet listnerResultSet = connection + .getPreparedStatementResultSetHandler().createResultSet(); + + listnerResultSet.addColumn("oid"); + listnerResultSet.addColumn("objname"); + listnerResultSet.addColumn("namespace"); + listnerResultSet.addColumn("ret"); + listnerResultSet.addColumn("alltype"); + listnerResultSet.addColumn("nargs"); + listnerResultSet.addColumn("argtype"); + listnerResultSet.addColumn("argname"); + listnerResultSet.addColumn("argmod"); + listnerResultSet.addColumn("secdef"); + listnerResultSet.addColumn("vola"); + listnerResultSet.addColumn("isstrict"); + listnerResultSet.addColumn("retset"); + listnerResultSet.addColumn("procost"); + listnerResultSet.addColumn("setrows"); + + ObjectParameter retParam = new ObjectParameter(); + retParam.setDataType("int"); + retParam.setName("a"); + retParam.setType(PARAMETERTYPE.IN); + + listnerResultSet.addRow(new Object[] {new Integer(1), "trigger1", 1, + new Integer(2279), null, null, null, null, "mode", false, + "volatile", false, false, 10, 10}); + + preparedstatementHandler.prepareResultSet(GET_ALL_TRIGGER_QUERY, + listnerResultSet); + MockResultSet nameSpaceResultSet = preparedstatementHandler + .createResultSet(); + nameSpaceResultSet.addColumn("nspname"); + // nameSpaceResultSet.addRow(new Object[] {"PUBLIC"}); + preparedstatementHandler.prepareResultSet(GET_NAMESPACE_QUERY, + nameSpaceResultSet); + + } + + public static void prepareSourceCodeResultSet(MockConnection connection) + { + PreparedStatementResultSetHandler preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + MockResultSet sourceCodeResult = preparedstatementHandler + .createResultSet(); + sourceCodeResult.addRow( + new String[] {"Declare\na int:=0;\nbegin\na:=a+1;\nend;"}); + preparedstatementHandler.prepareResultSet( + "SELECT prosrc FROM pg_proc WHERE oid = ?;", sourceCodeResult); + + } + + public static void prepareRefreshObjectResult(MockConnection connection) + { + PreparedStatementResultSetHandler preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + MockResultSet refreshObjectResult = preparedstatementHandler + .createResultSet(); + + refreshObjectResult.addColumn("oid"); + refreshObjectResult.addColumn("objname"); + refreshObjectResult.addColumn("namespace"); + refreshObjectResult.addColumn("ret"); + refreshObjectResult.addColumn("alltype"); + refreshObjectResult.addColumn("nargs"); + refreshObjectResult.addColumn("argtype"); + refreshObjectResult.addColumn("argname"); + refreshObjectResult.addColumn("argmod"); + refreshObjectResult.addColumn("secdef"); + refreshObjectResult.addColumn("vola"); + refreshObjectResult.addColumn("isstrict"); + refreshObjectResult.addColumn("retset"); + refreshObjectResult.addColumn("procost"); + refreshObjectResult.addColumn("setrows"); + + ObjectParameter retParam = new ObjectParameter(); + retParam.setDataType("int"); + retParam.setName("a"); + retParam.setType(PARAMETERTYPE.IN); + + refreshObjectResult.addRow(new Object[] {new Integer(1), "trigger1", 1, + new Integer(2279), null, null, null, null, "mode", false, + "volatile", false, false, 10, 10}); + + preparedstatementHandler.prepareResultSet(REFRESH_OBJECT_QUERY, + refreshObjectResult); + } + + public static void createBreakpoint(String isDisabledStr, + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet addBPResult = preparedstatementHandler.createResultSet(); + addBPResult.addRow(new String[] {"(2,5," + isDisabledStr + ":2:o)"}); + preparedstatementHandler.prepareResultSet( + "SELECT FUNC, LINENUMBER, TARGETNAME from pldbg_set_breakpoint(?,?,?,?,?);", + addBPResult); + } + + public static void getServerBreakPoints( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet breakPointsFromServer = preparedstatementHandler + .createResultSet(); + breakPointsFromServer.addRow(new String[] {"(6,5,f)"}); + // breakPointsFromServer.addRow(new String[] { "(7,6,f)" }); + preparedstatementHandler.prepareResultSet( + "SELECT FUNC, LINENUMBER," + + " TARGETNAME from pldbg_get_breakpoints(?,?);", + breakPointsFromServer); + } + + public static void debugPositionRelated( + PreparedStatementResultSetHandler preparedstatementHandler, + StatementResultSetHandler statementHandler) + { + MockResultSet debugOnRS = preparedstatementHandler.createResultSet(); + debugOnRS.addRow(new Boolean[] {true}); + preparedstatementHandler.prepareResultSet("SELECT pldbg_debug_on();", + debugOnRS); + + MockResultSet setDebugPositionRS = preparedstatementHandler + .createResultSet(); + setDebugPositionRS.addRow(new String[] {"(2,5)"}); + preparedstatementHandler.prepareResultSet( + "SELECT FUNC, LINENUMBER," + + " TARGETNAME from pldbg_sync_target(?);", + setDebugPositionRS); + + MockResultSet continueExecutionRS = preparedstatementHandler + .createResultSet(); + continueExecutionRS.addRow(new String[] {"(0,-1)"}); + preparedstatementHandler.prepareResultSet( + "SELECT FUNC, LINENUMBER," + + " TARGETNAME from pldbg_continue(?);", + continueExecutionRS); + + /* + * MockResultSet stepInExecutionRS = preparedstatementHandler + * .createResultSet(); stepInExecutionRS.addRow(new String[] { "(6,7)" + * }); stepInExecutionRS.addRow(new String[] { "(6,8)" }); + * preparedstatementHandler .prepareResultSet("SELECT FUNC, LINENUMBER," + * + " TARGETNAME from pldbg_step_into(?);", stepInExecutionRS); + */ + + MockResultSet getSourceResult = preparedstatementHandler + .createResultSet(); + getSourceResult.addRow(new String[] {"\nDeclare\nc INT = 6;\nd INT;" + + "BEGIN\nc := c+1;\nc := perform nestedfunc()\nc := c+1;" + + "\nc := c+1;\nc := c+1;\nc := c+1;\nc := 100;\nd := c + 200;" + + "\nreturn d;\nend;"}); + + preparedstatementHandler.prepareResultSet( + "SELECT prosrc FROM pg_proc " + "WHERE oid = ?;", + getSourceResult); + + MockResultSet getFrameResult = preparedstatementHandler + .createResultSet(); + getFrameResult.addRow(new String[] {"(0,func,2,5)"}); + + preparedstatementHandler.prepareResultSet("SELECT pldbg_get_stack(?);", + getFrameResult); + + MockResultSet getFrameVarResult = preparedstatementHandler + .createResultSet(); + + getFrameVarResult.addColumn("name"); + getFrameVarResult.addColumn("varClass"); + getFrameVarResult.addColumn("lineNumber"); + getFrameVarResult.addColumn("isUnique"); + getFrameVarResult.addColumn("isConst"); + getFrameVarResult.addColumn("isNotNull"); + getFrameVarResult.addColumn("isValueNull"); + getFrameVarResult.addColumn("dtype"); + getFrameVarResult.addColumn("value"); + + /* + * getFrameVarResult.addRow(new String[] { "(c,L,3,t,f,f,f,23,6)" }); + * getFrameVarResult.addRow(new String[] { "(d,L,4,t,f,f,t,23,NULL)" }); + */ + getFrameVarResult.addRow( + new String[] {"c", "L", "3", "t", "f", "f", "f", "23", "6"}); + getFrameVarResult.addRow( + new String[] {"d", "L", "4", "t", "f", "f", "t", "23", "NULL"}); + preparedstatementHandler.prepareResultSet(CommonLLTUtilsHelper.GET_VARIABLES, + getFrameVarResult); + + MockResultSet getSelectFrameResult = preparedstatementHandler + .createResultSet(); + getSelectFrameResult.addRow(new String[] {"(2,5,func)"}); + + preparedstatementHandler.prepareResultSet( + "SELECT pldbg_select_frame(?,?);", getSelectFrameResult); + } + + public static void prepareValidateVersion( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet validateVersionResult = preparedstatementHandler + .createResultSet(); + validateVersionResult.addRow(new Boolean[] {true}); + + preparedstatementHandler.prepareResultSet( + "SELECT pldbg_validate_version(?);", validateVersionResult); + } + + public static void prepareProxyInfo( + PreparedStatementResultSetHandler preparedstatementHandler) + { + + MockResultSet getDeadlineInfo = preparedstatementHandler + .createResultSet(); + getDeadlineInfo.addColumn("DEADLINE"); + + getDeadlineInfo.addRow(new Object[] {"3.124632"}); + preparedstatementHandler.prepareResultSet( + "select intervaltonum(gs_password_deadline()) as DEADLINE;", + getDeadlineInfo); + + MockResultSet getNamespaceInfo = preparedstatementHandler + .createResultSet(); + getNamespaceInfo.addColumn("oid"); + getNamespaceInfo.addColumn("nspname"); + + getNamespaceInfo.addRow(new Object[] {new Integer(1), "PUBLIC"}); + preparedstatementHandler.prepareResultSet( + "SELECT oid, nspname from pg_namespace WHERE oid=1", + getNamespaceInfo); + + MockResultSet viewRS = preparedstatementHandler.createResultSet(); + viewRS.addColumn("viewid"); + viewRS.addColumn("namespaceid"); + viewRS.addColumn("columnidx"); + viewRS.addColumn("name"); + viewRS.addColumn("datatypeoid"); + viewRS.addColumn("dtns"); + viewRS.addColumn("length"); + viewRS.addColumn("precision"); + viewRS.addColumn("dimentions"); + viewRS.addColumn("notnull"); + viewRS.addColumn("isdefaultvalueavailable"); + viewRS.addColumn("default_value"); + viewRS.addRow( + new Object[] {2, 1, 1, "col1", 3, 1, 0, 0, 0, 'f', 'f', ""}); + viewRS.addRow( + new Object[] {2, 1, 1, "col1", 8, 1, 0, 0, 0, 'f', 'f', ""}); + viewRS.addRow( + new Object[] {2, 1, 1, "col1", 5, 1, 0, 0, 0, 'f', 'f', ""}); + preparedstatementHandler.prepareResultSet(CommonLLTUtilsHelper.GET_ALL_VIEWS, + viewRS); + MockResultSet colmetadataRS = preparedstatementHandler + .createResultSet(); + colmetadataRS.addColumn("tableid"); + colmetadataRS.addColumn("namespaceid"); + colmetadataRS.addColumn("columnidx"); + colmetadataRS.addColumn("name"); + colmetadataRS.addColumn("datatypeoid"); + colmetadataRS.addColumn("dtns"); + colmetadataRS.addColumn("length"); + colmetadataRS.addColumn("precision"); + colmetadataRS.addColumn("dimentions"); + colmetadataRS.addColumn("notnull"); + colmetadataRS.addColumn("isdefaultvalueavailable"); + colmetadataRS.addColumn("default_value"); + + String colmetadata = "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, " + + "c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, " + + "c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value " + + "from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.relkind = 'r') " + + "left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) " + + "where c.attisdropped = 'f' and c.attnum > 0 and t.relnamespace = " + + 1 + " order by t.oid, c.attnum;"; + + colmetadataRS.addRow(new Object[] {1, 1, 1, "ColName", 1, 1, 0, -1, 0, + false, true, "Default value"}); + preparedstatementHandler.prepareResultSet(colmetadata, colmetadataRS); + + MockResultSet constraintRS = preparedstatementHandler.createResultSet(); + constraintRS.addColumn("constraintid"); + constraintRS.addColumn("tableid"); + constraintRS.addColumn("namespaceid"); + constraintRS.addColumn("constraintname"); + constraintRS.addColumn("constrainttype"); + constraintRS.addColumn("deferrable"); + constraintRS.addColumn("deferred"); + constraintRS.addColumn("validate"); + constraintRS.addColumn("indexid"); + constraintRS.addColumn("fkeytableId"); + constraintRS.addColumn("updatetype"); + constraintRS.addColumn("deletetype"); + constraintRS.addColumn("matchtype"); + constraintRS.addColumn("expr"); + constraintRS.addColumn("columnlist"); + constraintRS.addColumn("fkeycolumnlist"); + constraintRS.addColumn("const_def"); + + constraintRS.addRow(new Object[] {1, 1, 1, "ConstraintName", + "ConstraintType", false, false, false, 1, 1, "", "", "", "", + "1", "1", ""}); + // preparedstatementHandler.prepareResultSet("SELECT c.oid as + // constraintid, c.conrelid as tableid, c.connamespace as namespaceid, + // c.conname as constraintname, c.contype as constrainttype, + // c.condeferrable as deferrable, c.condeferred as deferred, + // c.convalidated as validate, c.conindid as indexid, c.confrelid as + // fkeytableId, c.confupdtype as updatetype, c.confdeltype as + // deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey + // as columnlist, c.confkey as fkeycolumnlist, + // pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c where + // c.conrelid = 1;",constraintRS); + // SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace + // as namespaceid, c.conname as constraintname, c.contype as + // constrainttype, c.condeferrable as deferrable, c.condeferred as + // deferred, c.convalidated as validate, c.conindid as indexid, + // c.confrelid as fkeytableId, c.confupdtype as updatetype, + // c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc + // as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, + // pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c where + // c.conrelid = 24900; + preparedstatementHandler + .prepareResultSet( + "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, " + + "c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, " + + "c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, " + + "c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, " + + "c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, " + + "pg_get_constraintdef(c.oid) as const_def " + + "FROM pg_constraint c where c.connamespace=" + + 1 + " and c.conrelid <> 0" + ';', + constraintRS); + + MockResultSet getVersionResult = preparedstatementHandler + .createResultSet(); + getVersionResult.addColumn("proxyAPIVer"); + getVersionResult.addColumn("serverVersionStr"); + + getVersionResult.addRow(new Object[] { + "PostgreSQL 9.2beta2 on i686-pc-linux-gnu, compiled by gcc (SUSE Linux) 4.3.4 [gcc-4_3-branch revision 152973], 32-bit", + "GMDB Tools V2R5C00B201"}); + preparedstatementHandler.prepareResultSet( + "SELECT * from pldbg_get_proxy_info();", getVersionResult); + + MockResultSet getServerVersionResult = preparedstatementHandler + .createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] { + "GaussDBV100R003C00B530 (2013-01-28 16:14:03) on x86_64-unknown-linux-gnu, compiled by gcc (SUSE Linux) 4.3.4 [gcc-4_3-branch revision 152973], 64-bit"}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", + getServerVersionResult); + + MockResultSet getServerVersionResultSet = preparedstatementHandler + .createResultSet(); + getServerVersionResultSet.addColumn("VERSION"); + + getServerVersionResultSet.addRow(new Object[] { + "Gauss200 OLAP V100R005C10 build 7123 compiled at 2016-11-11 16:18:35 on x86_64-unknown-linux-gnu, compiled by g++ (SUSE Linux) 4.3.4 [gcc-4_3-branch revision 152973], 64-bit"}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", + getServerVersionResultSet); + MockResultSet getdboidrs = preparedstatementHandler.createResultSet(); + getdboidrs.addColumn("oid"); + + getdboidrs.addRow(new Object[] {1}); + preparedstatementHandler.prepareResultSet( + "SELECT oid from pg_database where datname = 'Gauss'", + getdboidrs); + // newly added + + MockResultSet getSourceCode = preparedstatementHandler + .createResultSet(); + String query = "select a.headerlines, a.definition, b.xmin, b.cmin from pg_proc b left join " + + "(select * from PG_GET_FUNCTIONDEF(" + 1 + + ")) a on (1) where b.oid=" + 1; + + getSourceCode.addColumn("Code"); + getSourceCode.addColumn("VersionNumber1"); + getSourceCode.addColumn("VersionNumber2"); + getSourceCode.addRow(new Object[] {4, + "\"Declare\na int:=0;\nbegin\na:=a+1;\nend;\")", 1, 1}); + + preparedstatementHandler.prepareResultSet(query, getSourceCode); + + MockResultSet getListner = preparedstatementHandler.createResultSet(); + getListner.addColumn("pldbg_create_listener"); + + getListner.addRow(new Object[] {1}); + preparedstatementHandler.prepareResultSet( + "SELECT pldbg_create_listener();", getListner); + + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("oid"); + getdbsrs.addColumn("datname"); + + getdbsrs.addRow(new Object[] {1, "Gauss"}); + preparedstatementHandler.prepareResultSet( + "select oid, datname from pg_database where datistemplate='f'", + getdbsrs); + + MockResultSet getnoders = preparedstatementHandler.createResultSet(); + getnoders.addColumn("oid"); + getnoders.addColumn("node_name"); + getnoders.addColumn("node_type"); + getnoders.addColumn("node_port"); + getnoders.addColumn("node_host"); + getnoders.addColumn("nodeis_primary"); + getnoders.addColumn("nodeis_preferred"); + getnoders.addColumn("node_id"); + + getnoders.addRow(new Object[] {1, "Node_1", "node_type", 23456, + "1.0.0.0", true, true, 12}); + preparedstatementHandler.prepareResultSet( + "select oid, node_name, node_type, node_port, node_host, nodeis_primary, nodeis_preferred, node_id from pgxc_node;", + getnoders); + + MockResultSet getnodegrprs = preparedstatementHandler.createResultSet(); + getnodegrprs.addColumn("oid"); + getnodegrprs.addColumn("group_name"); + getnodegrprs.addColumn("group_members"); + + getnodegrprs.addRow(new Object[] {1, "group_1", "23 25"}); + preparedstatementHandler.prepareResultSet( + "select oid, group_name, group_members from pgxc_group order by group_name;", + getnodegrprs); + + MockResultSet gettblsprs = preparedstatementHandler.createResultSet(); + gettblsprs.addColumn("oid"); + gettblsprs.addColumn("location"); + gettblsprs.addColumn("spcname"); + gettblsprs.addColumn("spcacl"); + gettblsprs.addColumn("spcoptions"); + gettblsprs.addColumn("spcmaxsize"); + gettblsprs.addColumn("relative"); + gettblsprs.addRow( + new Object[] {1, "/home/dsdev/shalini", "tablespace1", null, + new String[] {"filesystem=general", + "random_page_cost=2", "seq_page_cost=2", + "address =address"}, + "10K", false}); + preparedstatementHandler.prepareResultSet( + "select oid, pg_tablespace_location(oid) as location ,spcname,spcacl,spcoptions, spcmaxsize, relative from pg_tablespace order by spcname;", + gettblsprs); + + MockResultSet getaccessmethodrs = preparedstatementHandler + .createResultSet(); + getaccessmethodrs.addColumn("oid"); + getaccessmethodrs.addColumn("amname"); + + getaccessmethodrs.addRow(new Object[] {1, "accemethod1"}); + preparedstatementHandler.prepareResultSet( + "SELECT oid, amname from pg_am order by oid;", + getaccessmethodrs); + + MockResultSet server_encoding = preparedstatementHandler + .createResultSet(); + server_encoding.addRow(new Object[] {"UTF-8"}); + preparedstatementHandler.prepareResultSet("show server_encoding", + server_encoding); + + MockResultSet namespaceRS = preparedstatementHandler.createResultSet(); + namespaceRS.addColumn("oid"); + namespaceRS.addColumn("nspname"); + namespaceRS.addRow(new Object[] {1, "PUBLIC"}); + namespaceRS.addRow(new Object[] {1, "pg_catalog"}); + namespaceRS.addRow(new Object[] {2, "information_schema"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtilsHelper.GET_ALL_NAMESPACE, namespaceRS); + + MockResultSet datatypeRS = preparedstatementHandler.createResultSet(); + datatypeRS.addColumn("oid"); + datatypeRS.addColumn("typname"); + datatypeRS.addColumn("typnamespace"); + datatypeRS.addColumn("typlen"); + datatypeRS.addColumn("typbyval"); + datatypeRS.addColumn("typtype"); + datatypeRS.addColumn("typcategory"); + datatypeRS.addColumn("typtypmod"); + datatypeRS.addColumn("typnotnull"); + datatypeRS.addColumn("typarray"); + datatypeRS.addColumn("desc"); + + datatypeRS.addRow(new Object[] {1, "bigint", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {2, "int8", 1, 1, true, "type", + "category", 1, true, 12, "description2"}); + + datatypeRS.addRow(new Object[] {3, "bit", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {4, "varbit", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {5, "bool", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {6, "box", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {7, "bytea", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {8, "varchar", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {9, "char", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {10, "cidr", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {11, "circle", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {12, "date", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + + datatypeRS.addRow(new Object[] {13, "float8", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {14, "inet", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {15, "int4", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {16, "interval", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {17, "line", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {18, "lseg", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {19, "macaddr", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {20, "money", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {21, "numeric", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {22, "numeric", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {23, "path", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {24, "point", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {25, "polygon", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {26, "float4", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {27, "int2", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + + datatypeRS.addRow(new Object[] {28, "text", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {29, "time", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {30, "timetz", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {31, "timestamp", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {32, "timestamptz", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {33, "tsquery", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {34, "tsvector", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {35, "txid_snapshot", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {36, "uuid", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + datatypeRS.addRow(new Object[] {37, "xml", 1, 1, true, "type", + "category", 1, true, 12, "description"}); + + preparedstatementHandler + .prepareResultSet(CommonLLTUtilsHelper.GET_ALL_DATATYPE, datatypeRS); + + MockResultSet tablemetadataRS = preparedstatementHandler + .createResultSet(); + tablemetadataRS.addColumn("oid"); + tablemetadataRS.addColumn("relname"); + tablemetadataRS.addColumn("relnamespace"); + tablemetadataRS.addColumn("reltablespace"); + tablemetadataRS.addColumn("relpersistence"); + tablemetadataRS.addColumn("desc"); + tablemetadataRS.addColumn("nodes"); + + tablemetadataRS.addRow( + new Object[] {1, "MyTable", 1, 1, true, "description", "1 2"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtilsHelper.GET_ALL_TABLE_METADATA, tablemetadataRS); + + MockResultSet colmetadataRS1 = preparedstatementHandler + .createResultSet(); + colmetadataRS1.addColumn("tableid"); + colmetadataRS1.addColumn("namespaceid"); + colmetadataRS1.addColumn("columnidx"); + colmetadataRS1.addColumn("name"); + colmetadataRS1.addColumn("datatypeoid"); + colmetadataRS1.addColumn("dtns"); + colmetadataRS1.addColumn("length"); + colmetadataRS1.addColumn("precision"); + colmetadataRS1.addColumn("dimentions"); + colmetadataRS1.addColumn("notnull"); + colmetadataRS1.addColumn("isdefaultvalueavailable"); + colmetadataRS1.addColumn("default_value"); + + colmetadataRS1.addRow(new Object[] {1, 1, 1, "ColName", 1, 1, 200, 0, 0, + false, true, "Default value"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtilsHelper.GET_ALL_COLUMN_METADATA, colmetadataRS1); + + MockResultSet indexRS = preparedstatementHandler.createResultSet(); + indexRS.addColumn("oid"); + indexRS.addColumn("tableId"); + indexRS.addColumn("indexname"); + indexRS.addColumn("namespaceid"); + indexRS.addColumn("accessmethodid"); + indexRS.addColumn("isunique"); + indexRS.addColumn("isprimary"); + indexRS.addColumn("isexclusion"); + indexRS.addColumn("isimmediate"); + indexRS.addColumn("isclustered"); + indexRS.addColumn("checkmin"); + indexRS.addColumn("isready"); + indexRS.addColumn("cols"); + indexRS.addColumn("reloptions"); + + indexRS.addRow(new Object[] {1, 1, "IndexName", 1, 1, true, false, + false, false, false, false, false, "1", ""}); + preparedstatementHandler + .prepareResultSet(CommonLLTUtilsHelper.GET_ALL_INDEXES, indexRS); + + MockResultSet constraintRS1 = preparedstatementHandler + .createResultSet(); + constraintRS1.addColumn("constraintid"); + constraintRS1.addColumn("tableid"); + constraintRS1.addColumn("namespaceid"); + constraintRS1.addColumn("constraintname"); + constraintRS1.addColumn("constrainttype"); + constraintRS1.addColumn("deferrable"); + constraintRS1.addColumn("deferred"); + constraintRS1.addColumn("validate"); + constraintRS1.addColumn("indexid"); + constraintRS1.addColumn("fkeytableId"); + constraintRS1.addColumn("updatetype"); + constraintRS1.addColumn("deletetype"); + constraintRS1.addColumn("matchtype"); + constraintRS1.addColumn("expr"); + constraintRS1.addColumn("columnlist"); + constraintRS1.addColumn("fkeycolumnlist"); + + constraintRS1.addRow( + new Object[] {1, 1, 1, "ConstraintName", "ConstraintType", + false, false, false, 1, 1, "", "", "", "", "1", "1"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtilsHelper.GET_ALL_CONSTRAINTS, constraintRS1); + + MockResultSet indexRS1 = preparedstatementHandler.createResultSet(); + indexRS1.addColumn("oid"); + indexRS1.addColumn("tableId"); + indexRS1.addColumn("indexname"); + indexRS1.addColumn("namespaceid"); + indexRS1.addColumn("accessmethodid"); + indexRS1.addColumn("isunique"); + indexRS1.addColumn("isprimary"); + indexRS1.addColumn("isexclusion"); + indexRS1.addColumn("isimmediate"); + indexRS1.addColumn("isclustered"); + indexRS1.addColumn("checkmin"); + indexRS1.addColumn("isready"); + indexRS1.addColumn("cols"); + indexRS1.addColumn("reloptions"); + indexRS1.addColumn("indexdef"); + indexRS1.addRow(new Object[] {1, 1, "IndexName", 1, 1, true, false, + false, false, false, false, false, "1", "", ""}); + String GET_ALL_INDEXES_BYNAMESPACE_1 = "SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, ci.relnamespace as namespaceid, " + + "ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, i.indisexclusion as isexclusion," + + " i.indimmediate as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, i.indisready as isready, " + + "i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions, def.indexdef " + + "FROM pg_index i" + + " LEFT JOIN pg_class t on (t.oid = i.indrelid) " + + "LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) " + + "LEFT JOIN pg_namespace ns on (ci.relnamespace = ns.oid) " + + "LEFT JOIN pg_indexes def on (ci.relname = def.indexname and ns.nspname = def.schemaname)" + + " WHERE t.relkind = 'r' and ci.relnamespace = " + 1 + ';'; + preparedstatementHandler.prepareResultSet(GET_ALL_INDEXES_BYNAMESPACE_1, + indexRS1); + + MockResultSet shallowLoadTablesRS = preparedstatementHandler + .createResultSet(); + shallowLoadTablesRS.addColumn("oid"); + shallowLoadTablesRS.addColumn("relname"); + shallowLoadTablesRS.addColumn("relnamespace"); + shallowLoadTablesRS.addColumn("relpersistence"); + shallowLoadTablesRS.addRow(new Object[] {1, "order_7", 1, "p"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtilsHelper.GET_ALL_SHALLOWLOADTABLES, shallowLoadTablesRS); + + MockResultSet loadFuncTriggerRS = preparedstatementHandler + .createResultSet(); + loadFuncTriggerRS.addColumn("oid"); + loadFuncTriggerRS.addColumn("objname"); + loadFuncTriggerRS.addColumn("namespace"); + loadFuncTriggerRS.addColumn("ret"); + loadFuncTriggerRS.addColumn("alltype"); + loadFuncTriggerRS.addColumn("nargs"); + loadFuncTriggerRS.addColumn("argtype"); + loadFuncTriggerRS.addColumn("argname"); + loadFuncTriggerRS.addColumn("argmod"); + loadFuncTriggerRS.addColumn("secdef"); + loadFuncTriggerRS.addColumn("vola"); + loadFuncTriggerRS.addColumn("isstrict"); + loadFuncTriggerRS.addColumn("retset"); + loadFuncTriggerRS.addColumn("procost"); + loadFuncTriggerRS.addColumn("setrows"); + loadFuncTriggerRS.addRow(new Object[] {1, "auto1", 1, 23, null, 0, null, + null, null, "f", "v", "f", "f", 100, 0}); + // loadFuncTriggerRS.addRow(new Object[] + // {17830,"calculateoutput",1,2278,"{23,23}",1,23,"{id,value}","{i,o}","f","v","f","f",100,0}); + preparedstatementHandler.prepareResultSet(CommonLLTUtilsHelper.TRIGGERONLY, + loadFuncTriggerRS); + MockResultSet loadTriggerRS = preparedstatementHandler + .createResultSet(); + loadTriggerRS.addColumn("oid"); + loadTriggerRS.addColumn("objname"); + loadTriggerRS.addColumn("namespace"); + loadTriggerRS.addColumn("ret"); + loadTriggerRS.addColumn("alltype"); + loadTriggerRS.addColumn("nargs"); + loadTriggerRS.addColumn("argtype"); + loadTriggerRS.addColumn("argname"); + loadTriggerRS.addColumn("argmod"); + loadTriggerRS.addColumn("secdef"); + loadTriggerRS.addColumn("vola"); + loadTriggerRS.addColumn("isstrict"); + loadTriggerRS.addColumn("retset"); + loadTriggerRS.addColumn("procost"); + loadTriggerRS.addColumn("setrows"); + loadTriggerRS.addRow(new Object[] {1, "auto1", 1, 23, null, 0, null, + null, null, "f", "v", "f", "f", 100, 0}); + // loadTriggerRS.addRow(new Object[] + // {17830,"calculateoutput",1,2278,"{23,23}",1,23,"{id,value}","{i,o}","f","v","f","f",100,0}); + preparedstatementHandler.prepareResultSet(CommonLLTUtilsHelper.TRIGGERONLY1, + loadTriggerRS); + MockResultSet functionRS = preparedstatementHandler.createResultSet(); + functionRS.addColumn("oid"); + functionRS.addColumn("objname"); + functionRS.addColumn("namespace"); + functionRS.addColumn("ret"); + functionRS.addColumn("alltype"); + functionRS.addColumn("nargs"); + functionRS.addColumn("argtype"); + functionRS.addColumn("argname"); + functionRS.addColumn("argmod"); + functionRS.addColumn("secdef"); + functionRS.addColumn("vola"); + functionRS.addColumn("isstrict"); + functionRS.addColumn("retset"); + functionRS.addColumn("procost"); + functionRS.addColumn("setrows"); + + // 11389,pgxc_prepared_xact,11,25,,0,,,,f,v,f,t,100,1000 + functionRS.addRow(new Object[] {1, "pgxc_prepared_xact", 1, 1, null, 0, + " ", null, null, "f", "v", "f", "t", 1, 1}); + preparedstatementHandler.prepareResultSet(CommonLLTUtilsHelper.FUNCTIONONLY, + functionRS); + MockResultSet Shallowload1RS = preparedstatementHandler + .createResultSet(); + Shallowload1RS.addColumn("oid"); + Shallowload1RS.addColumn("relname"); + Shallowload1RS.addColumn("relnamespace"); + Shallowload1RS.addColumn("relpersistence"); + Shallowload1RS.addColumn("reltablespace"); + // 736937,AAA,2200,p + // 11389,pgxc_prepared_xact,11,25,,0,,,,f,v,f,t,100,1000 + Shallowload1RS + .addRow(new Object[] {1, "Table1", 1, "p", "tablespace1"}); + Shallowload1RS + .addRow(new Object[] {1, "Table2", 1, "t", "tablespace2"}); + Shallowload1RS + .addRow(new Object[] {1, "Table3", 1, "u", "tablespace3"}); + preparedstatementHandler.prepareResultSet(CommonLLTUtilsHelper.Shallowload1, + Shallowload1RS); + MockResultSet shallowLoadQueryRS = preparedstatementHandler + .createResultSet(); + shallowLoadQueryRS.addColumn("oid"); + shallowLoadQueryRS.addColumn("objname"); + shallowLoadQueryRS.addColumn("namespace"); + shallowLoadQueryRS.addColumn("ret"); + shallowLoadQueryRS.addColumn("alltype"); + shallowLoadQueryRS.addColumn("nargs"); + shallowLoadQueryRS.addColumn("argtype"); + shallowLoadQueryRS.addColumn("argname"); + shallowLoadQueryRS.addColumn("argmod"); + shallowLoadQueryRS.addColumn("secdef"); + shallowLoadQueryRS.addColumn("vola"); + shallowLoadQueryRS.addColumn("isstrict"); + shallowLoadQueryRS.addColumn("retset"); + shallowLoadQueryRS.addColumn("procost"); + shallowLoadQueryRS.addColumn("setrows"); + shallowLoadQueryRS.addRow(new Object[] {1, "auto1", 1, 23, null, 0, + null, null, null, "f", "v", "f", "f", 100, 0}); + // shallowLoadQueryRS.addRow(new Object[] + // {17830,"calculateoutput",1,2278,"{23,23}",1,23,"{id,value}","{i,o}","f","v","f","f",100,0}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtilsHelper.SHALLOWLOADQUERY, shallowLoadQueryRS); + + MockResultSet shallowLoadQueryDefaultRS = preparedstatementHandler + .createResultSet(); + shallowLoadQueryDefaultRS.addColumn("oid"); + shallowLoadQueryDefaultRS.addColumn("objname"); + shallowLoadQueryDefaultRS.addColumn("namespace"); + shallowLoadQueryDefaultRS.addColumn("ret"); + shallowLoadQueryDefaultRS.addColumn("alltype"); + shallowLoadQueryDefaultRS.addColumn("nargs"); + shallowLoadQueryDefaultRS.addColumn("argtype"); + shallowLoadQueryDefaultRS.addColumn("argname"); + shallowLoadQueryDefaultRS.addColumn("argmod"); + shallowLoadQueryDefaultRS.addColumn("secdef"); + shallowLoadQueryDefaultRS.addColumn("vola"); + shallowLoadQueryDefaultRS.addColumn("isstrict"); + shallowLoadQueryDefaultRS.addColumn("retset"); + shallowLoadQueryDefaultRS.addColumn("procost"); + shallowLoadQueryDefaultRS.addColumn("setrows"); + shallowLoadQueryDefaultRS.addRow(new Object[] {1, "auto1", 1, 23, null, + 0, null, null, null, "f", "v", "f", "f", 100, 0}); + // shallowLoadQueryRS.addRow(new Object[] + // {17830,"calculateoutput",1,2278,"{23,23}",1,23,"{id,value}","{i,o}","f","v","f","f",100,0}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtilsHelper.SHALLOWLOADQUERYDEFAULT, + shallowLoadQueryDefaultRS); + + MockResultSet listnerResultSet = preparedstatementHandler + .createResultSet(); + + listnerResultSet.addColumn("oid"); + listnerResultSet.addColumn("objname"); + listnerResultSet.addColumn("namespace"); + listnerResultSet.addColumn("ret"); + listnerResultSet.addColumn("alltype"); + listnerResultSet.addColumn("nargs"); + listnerResultSet.addColumn("argtype"); + listnerResultSet.addColumn("argname"); + listnerResultSet.addColumn("argmod"); + listnerResultSet.addColumn("secdef"); + listnerResultSet.addColumn("vola"); + listnerResultSet.addColumn("isstrict"); + listnerResultSet.addColumn("retset"); + listnerResultSet.addColumn("procost"); + listnerResultSet.addColumn("setrows"); + + ObjectParameter retParam = new ObjectParameter(); + retParam.setDataType("int"); + retParam.setName("a"); + retParam.setType(PARAMETERTYPE.IN); + + listnerResultSet.addRow(new Object[] {new Integer(2), "function2", 1, + new Integer(16), null, "1", "20 21 21", "{arg1, arg2, arg3}", + "{i,o,b}", false, "volatile", false, false, 10, 10}); + + preparedstatementHandler.prepareResultSet(GET_ALL_FUNCTION_QUERY, + listnerResultSet); + + MockResultSet triggerResultSet = preparedstatementHandler + .createResultSet(); + + triggerResultSet.addColumn("oid"); + triggerResultSet.addColumn("objname"); + triggerResultSet.addColumn("namespace"); + triggerResultSet.addColumn("ret"); + triggerResultSet.addColumn("alltype"); + triggerResultSet.addColumn("nargs"); + triggerResultSet.addColumn("argtype"); + triggerResultSet.addColumn("argname"); + triggerResultSet.addColumn("argmod"); + triggerResultSet.addColumn("secdef"); + triggerResultSet.addColumn("vola"); + triggerResultSet.addColumn("isstrict"); + triggerResultSet.addColumn("retset"); + triggerResultSet.addColumn("procost"); + triggerResultSet.addColumn("setrows"); + + ObjectParameter tretParam = new ObjectParameter(); + tretParam.setDataType("int"); + tretParam.setName("a"); + tretParam.setType(PARAMETERTYPE.IN); + + triggerResultSet.addRow(new Object[] {new Integer(1), "trigger1", 1, + new Integer(2279), null, null, null, null, "mode", false, + "volatile", false, false, 10, 10}); + + preparedstatementHandler.prepareResultSet(GET_ALL_TRIGGER_QUERY, + triggerResultSet); + getViewMockRS(preparedstatementHandler); + + MockResultSet searchpath = preparedstatementHandler.createResultSet(); + searchpath.addColumn("search_path"); + + searchpath.addRow(new Object[] {"public,abc,pg_catalog"}); + preparedstatementHandler.prepareResultSet("SHOW search_path", + searchpath); + + MockResultSet getUserRoleRs = preparedstatementHandler.createResultSet(); + getUserRoleRs.addColumn("rolname"); + getUserRoleRs.addColumn("rolcanlogin"); + getUserRoleRs.addColumn("oid"); + getUserRoleRs.addRow(new Object[] {"chris", true, 16408}); + getUserRoleRs.addRow(new Object[] {"tom", false, 16410}); + preparedstatementHandler.prepareResultSet( + "SELECT rolname,rolcanlogin,oid FROM pg_catalog.pg_roles WHERE rolsuper = false;", getUserRoleRs); + + MockResultSet serverEncodingRs = preparedstatementHandler.createResultSet(); + serverEncodingRs.addColumn("server_encoding"); + serverEncodingRs.addRow(new Object[] {"UTF-8"}); + preparedstatementHandler.prepareResultSet("show server_encoding", serverEncodingRs); + } + + public static void getViewMockRS( + PreparedStatementResultSetHandler preparedstatementHandler) + { + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("oid"); + getdbsrs.addColumn("nspoid"); + getdbsrs.addColumn("schemaname"); + getdbsrs.addColumn("viewname"); + getdbsrs.addColumn("viewowner"); + getdbsrs.addRow(new Object[] {2, 1, "public", "mytestview", "owner1"}); + preparedstatementHandler.prepareResultSet( + "SELECT c.oid, n.oid as nspoid, n.nspname AS schemaname, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner " + + "FROM (pg_class c LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace))) WHERE (c.relkind = 'v'::\"char\" or c.relkind = 'm'::\"char\") and has_table_privilege(c.oid,'SELECT') ", + getdbsrs); + + MockResultSet getdbsrs1 = preparedstatementHandler.createResultSet(); + getdbsrs1.addColumn("oid"); + getdbsrs1.addColumn("nspoid"); + getdbsrs1.addColumn("schemaname"); + getdbsrs1.addColumn("viewname"); + getdbsrs1.addColumn("viewowner"); + getdbsrs1.addRow(new Object[] {2, 1, "public", "mytestview", "owner1"}); + preparedstatementHandler.prepareResultSet( + "SELECT c.oid, n.oid as nspoid, n.nspname AS schemaname, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner " + + "FROM (pg_class c LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace))) WHERE (c.relkind = 'v'::\"char\" or c.relkind = 'm'::\"char\") ", + getdbsrs1); + } + + public static void prepareProxyInfoForGetAllNamespaces( + PreparedStatementResultSetHandler preparedstatementHandler) + { + + MockResultSet namespaceRS = preparedstatementHandler.createResultSet(); + namespaceRS.addColumn("oid"); + namespaceRS.addColumn("nspname"); + namespaceRS.addRow(new Object[] {1, "pg_catalog"}); + namespaceRS.addRow(new Object[] {2, "information_schema"}); + preparedstatementHandler.prepareResultSet( + CommonLLTUtilsHelper.GET_ALL_NAMESPACE, namespaceRS); + } + + public static void datatypes( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String qry = "select typ.oid as oid, typ.typname as typname, typ.typnamespace as typnamespace, typ.typlen as typlen, pg_catalog.format_type(oid,typ.typtypmod) as displaycolumns , typ.typbyval as typbyval, typ.typtype as typtype, typ.typcategory as typcategory, typ.typtypmod as typtypmod, typ.typnotnull as typnotnull, typ.typarray as typarray, des.description as desc from pg_type typ left join pg_description des on (typ.oid = des.objoid) where typ.typnamespace in (select oid from pg_namespace where nspname in ('information_schema', 'pg_catalog')) order by typ.typname"; + MockResultSet dbrs = preparedstatementHandler.createResultSet(); + dbrs.addColumn("oid"); + dbrs.addColumn("typname"); + dbrs.addColumn("typnamespace"); + dbrs.addColumn("typlen"); + dbrs.addColumn("displaycolumns"); + dbrs.addColumn("typbyval"); + dbrs.addColumn("typtype"); + dbrs.addColumn("typcategory"); + dbrs.addColumn("typtypmod"); + dbrs.addColumn("typnotnull"); + dbrs.addColumn("typarray"); + dbrs.addColumn("desc"); + + dbrs.addRow(new Object[] {2, "bigint", 1, 1, "character", true, "type", + "category", 1, true, 12, "description", "bigint"}); + dbrs.addRow(new Object[] {1, "char", 1, 1, "character", true, "type", + "category", 1, true, 12, "description", "char"}); + /* + * dbrs.addRow(new Object[] {2, "int8", 1, 1, true, "type", "category", + * 1, true, 12, "description2"}); + */ + + /* + * datatypeRS.addRow(new Object[] {3, "bit", 1, 1, true, "type", + * "category", 1, true, 12, "description","bit"}); datatypeRS.addRow(new + * Object[] {4, "varbit", 1, 1, true, "type", "category", 1, true, 12, + * "description","varbit"}); datatypeRS.addRow(new Object[] {5, "bool", + * 1, 1, true, "type", "category", 1, true, 12, "description","bool"}); + * datatypeRS.addRow(new Object[] {6, "box", 1, 1, true, "type", + * "category", 1, true, 12, "description","box"}); datatypeRS.addRow(new + * Object[] {7, "bytea", 1, 1, true, "type", "category", 1, true, 12, + * "description","bytea"}); datatypeRS.addRow(new Object[] {8, + * "varchar", 1, 1, true, "type", "category", 1, true, 12, + * "description","varchar"}); datatypeRS.addRow(new Object[] {9, "char", + * 1, 1, true, "type", "category", 1, true, 12, "description","char"}); + * datatypeRS.addRow(new Object[] {10, "cidr", 1, 1, true, "type", + * "category", 1, true, 12, "description","cidr"}); + * datatypeRS.addRow(new Object[] {11, "circle", 1, 1, true, "type", + * "category", 1, true, 12, "description","circle"}); + * datatypeRS.addRow(new Object[] {12, "date", 1, 1, true, "type", + * "category", 1, true, 12, "description","date"}); + * + * datatypeRS.addRow(new Object[] {13, "float8", 1, 1, true, "type", + * "category", 1, true, 12, "description","float"}); + * datatypeRS.addRow(new Object[] {14, "inet", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {15, "int4", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); datatypeRS.addRow(new Object[] {16, "interval", + * 1, 1, true, "type", "category", 1, true, 12, "description",""}); + * datatypeRS.addRow(new Object[] {17, "line", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {18, "lseg", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); datatypeRS.addRow(new Object[] {19, "macaddr", 1, + * 1, true, "type", "category", 1, true, 12, "description",""}); + * datatypeRS.addRow(new Object[] {20, "money", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {21, "numeric", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); datatypeRS.addRow(new Object[] {22, "numeric", 1, + * 1, true, "type", "category", 1, true, 12, "description",""}); + * datatypeRS.addRow(new Object[] {23, "path", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {24, "point", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); datatypeRS.addRow(new Object[] {25, "polygon", 1, + * 1, true, "type", "category", 1, true, 12, "description",""}); + * datatypeRS.addRow(new Object[] {26, "float4", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {27, "int2", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); + * + * datatypeRS.addRow(new Object[] {28, "text", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {29, "time", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); datatypeRS.addRow(new Object[] {30, "timetz", 1, + * 1, true, "type", "category", 1, true, 12, "description",""}); + * datatypeRS.addRow(new Object[] {31, "timestamp", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {32, "timestamptz", 1, 1, true, "type", "category", 1, true, + * 12, "description",""}); datatypeRS.addRow(new Object[] {33, + * "tsquery", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); datatypeRS.addRow(new Object[] {34, "tsvector", + * 1, 1, true, "type", "category", 1, true, 12, "description",""}); + * datatypeRS.addRow(new Object[] {35, "txid_snapshot", 1, 1, true, + * "type", "category", 1, true, 12, "description",""}); + * datatypeRS.addRow(new Object[] {36, "uuid", 1, 1, true, "type", + * "category", 1, true, 12, "description",""}); datatypeRS.addRow(new + * Object[] {37, "xml", 1, 1, true, "type", "category", 1, true, 12, + * "description",""}); + */ + preparedstatementHandler.prepareResultSet(qry, dbrs); + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/Connfactory.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/Connfactory.java new file mode 100644 index 0000000000000000000000000000000000000000..49d7cf264f060b9a141d135d87f0fd0fb763cfdd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/Connfactory.java @@ -0,0 +1,395 @@ +package org.opengauss.mppdbide.mock.presentation; + +import java.io.IOException; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.util.List; +import java.util.Set; +import java.util.TimeZone; + +import org.postgresql.PGNotification; +import org.postgresql.copy.CopyOperation; +import org.postgresql.core.CachedQuery; +import org.postgresql.core.Encoding; +import org.postgresql.core.NativeQuery; +import org.postgresql.core.ParameterList; +import org.postgresql.core.Query; +import org.postgresql.core.QueryExecutor; +import org.postgresql.core.ReplicationProtocol; +import org.postgresql.core.ResultCursor; +import org.postgresql.core.ResultHandler; +import org.postgresql.core.TransactionState; +import org.postgresql.jdbc.AutoSave; +import org.postgresql.jdbc.BatchResultHandler; +import org.postgresql.jdbc.PreferQueryMode; +import org.postgresql.util.HostSpec; + +public class Connfactory implements QueryExecutor +{ + + private boolean isSQLExceptionReq; + + public Connfactory(boolean isSQLExceptionReq) + { + this.isSQLExceptionReq = isSQLExceptionReq; + } + + @Override + public void execute(Query query, ParameterList parameters, + ResultHandler handler, int maxRows, int fetchSize, int flags) + throws SQLException + { + + + } + + @Override + public void fetch(ResultCursor cursor, ResultHandler handler, int fetchSize) + throws SQLException + { + + + } + + @Override + public Query createSimpleQuery(String sql) + { + + return null; + } + + + @Override + public void processNotifies() throws SQLException + { + + + } + + @Override + public ParameterList createFastpathParameters(int count) + { + + return null; + } + + @Override + public byte[] fastpathCall(int fnid, ParameterList params, + boolean suppressBegin) throws SQLException + { + + return null; + } + + @Override + public CopyOperation startCopy(String sql, boolean suppressBegin) + throws SQLException + { + + if(isSQLExceptionReq) + { + isSQLExceptionReq = false; + throw new SQLException(); + } + + return new CopyOperationHelper(); + } + + @Override + public boolean useBinaryForReceive(int arg0) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean useBinaryForSend(int arg0) { + // TODO Auto-generated method stub + return false; + } + + @Override + public void abort() { + // TODO Auto-generated method stub + + } + + @Override + public CachedQuery borrowCallableQuery(String arg0) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public CachedQuery borrowQuery(String arg0) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public CachedQuery borrowQueryByKey(Object arg0) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public CachedQuery borrowReturningQuery(String arg0, String[] arg1) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public void close() { + // TODO Auto-generated method stub + + } + + @Override + public CachedQuery createQuery(String arg0, boolean arg1, boolean arg2, String... arg3) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public CachedQuery createQueryByKey(Object arg0) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public Object createQueryKey(String arg0, boolean arg1, boolean arg2, String... arg3) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void execute(Query[] arg0, ParameterList[] arg1, BatchResultHandler arg2, int arg3, int arg4, int arg5) + throws SQLException { + // TODO Auto-generated method stub + + } + + @Override + public void executeBatch(Query[] arg0, ParameterList[] arg1, BatchResultHandler arg2, int arg3, int arg4, int arg5) + throws SQLException { + // TODO Auto-generated method stub + + } + + @Override + public String getApplicationName() { + // TODO Auto-generated method stub + return null; + } + + @Override + public AutoSave getAutoSave() { + // TODO Auto-generated method stub + return null; + } + + @Override + public int getBackendPID() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public String getDatabase() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Encoding getEncoding() { + // TODO Auto-generated method stub + return null; + } + + @Override + public HostSpec getHostSpec() { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean getIntegerDateTimes() { + // TODO Auto-generated method stub + return false; + } + + @Override + public int getNetworkTimeout() throws IOException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public PGNotification[] getNotifications() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public PreferQueryMode getPreferQueryMode() { + // TODO Auto-generated method stub + return null; + } + + @Override + public int getProtocolVersion() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public ReplicationProtocol getReplicationProtocol() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getServerVersion() { + // TODO Auto-generated method stub + return null; + } + + @Override + public int getServerVersionNum() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public boolean getStandardConformingStrings() { + // TODO Auto-generated method stub + return false; + } + + @Override + public TimeZone getTimeZone() { + // TODO Auto-generated method stub + return null; + } + + @Override + public TransactionState getTransactionState() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getUser() { + // TODO Auto-generated method stub + return null; + } + + @Override + public SQLWarning getWarnings() { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean isClosed() { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isColumnSanitiserDisabled() { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isReWriteBatchedInsertsEnabled() { + // TODO Auto-generated method stub + return false; + } + + @Override + public void processNotifies(int arg0) throws SQLException { + // TODO Auto-generated method stub + + } + + @Override + public void releaseQuery(CachedQuery arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void sendQueryCancel() throws SQLException { + // TODO Auto-generated method stub + + } + + @Override + public void setAutoSave(AutoSave arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void setBinaryReceiveOids(Set arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void setBinarySendOids(Set arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void setFlushCacheOnDeallocate(boolean arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void setNetworkTimeout(int arg0) throws IOException { + // TODO Auto-generated method stub + + } + + @Override + public void setProtocolVersion(int arg0) { + // TODO Auto-generated method stub + + } + + @Override + public boolean willHealOnRetry(SQLException arg0) { + // TODO Auto-generated method stub + return false; + } + + @Override + public Query wrap(List arg0) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getSocketAddress() { + return ""; + } + + @Override + public void setGaussdbVersion(String gaussdbVersion) { + + } + + @Override + public String getApplicationType() { + return ""; + } + + @Override + public String getGaussdbVersion() { + return ""; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/CopyOperationHelper.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/CopyOperationHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..9f9b274d49c10894145d72f2fa384a805e7c347f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/CopyOperationHelper.java @@ -0,0 +1,90 @@ +package org.opengauss.mppdbide.mock.presentation; + +import java.sql.SQLException; + +import org.postgresql.copy.CopyIn; +import org.postgresql.copy.CopyOut; + +public class CopyOperationHelper implements CopyOut, CopyIn +{ + + byte[] bytearray = new String("\u7528\u6237\u53EF\u5B9A\u5236\u754C\u9762\u5E03\u5C40").getBytes(); + @Override + public int getFieldCount() + { + + return 0; + } + + @Override + public int getFormat() + { + + return 0; + } + + @Override + public int getFieldFormat(int field) + { + + return 0; + } + + @Override + public boolean isActive() + { + + return false; + } + + @Override + public void cancelCopy() throws SQLException + { + + + } + + @Override + public long getHandledRowCount() + { + + return 0; + } + + @Override + public byte[] readFromCopy() throws SQLException + { + + byte[] dummy = bytearray; + bytearray = null; + return dummy; + } + + @Override + public void writeToCopy(byte[] buf, int off, int siz) throws SQLException + { + + + } + + @Override + public void flushCopy() throws SQLException + { + + + } + + @Override + public long endCopy() throws SQLException + { + + return 0; + } + + @Override + public byte[] readFromCopy(boolean arg0) throws SQLException { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/EncodingHelper.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/EncodingHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..508aaa5b33d19d8ddace4bebbe27fdba5cffab1b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/EncodingHelper.java @@ -0,0 +1,17 @@ +package org.opengauss.mppdbide.mock.presentation; + +import org.postgresql.core.Encoding; + +public class EncodingHelper extends Encoding +{ + protected EncodingHelper(String encoding) + { + super(encoding); + } + + public static Encoding getDatabaseEncoding(String databaseEncoding) + { + return new EncodingHelper(""); + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/EncryptionHelper.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/EncryptionHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..7ead2f2f6542698a5c8f64310410d3e1559506f7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/EncryptionHelper.java @@ -0,0 +1,54 @@ +package org.opengauss.mppdbide.mock.presentation; + +import org.opengauss.mppdbide.utils.security.EncryptionUtil; +import org.opengauss.mppdbide.utils.security.SecureUtil; + +public class EncryptionHelper extends EncryptionUtil +{ + + private boolean throwNoSuchAlogoException; + private boolean throwInvalidKeyException; + private boolean throwNoSuchPaddingException; + private boolean throwInvalidAlgorithmParameterException; + private boolean throwIllegalBlockSizeException; + private boolean throwBadPaddingException; + + public EncryptionHelper(SecureUtil encryptionDecryption) + { + super(encryptionDecryption); + } + + public void setThrowNoSuchAlogoException(boolean throwNoSuchAlogoException) + { + this.throwNoSuchAlogoException = throwNoSuchAlogoException; + } + + public void setThrowInvalidKeyException(boolean throwInvalidKeyException) + { + this.throwInvalidKeyException = throwInvalidKeyException; + } + + public void setThrowNoSuchPaddingException( + boolean throwNoSuchPaddingException) + { + this.throwNoSuchPaddingException = throwNoSuchPaddingException; + } + + public void setThrowInvalidAlgorithmParameterException( + boolean throwInvalidAlgorithmParameterException) + { + this.throwInvalidAlgorithmParameterException = throwInvalidAlgorithmParameterException; + } + + public void setThrowIllegalBlockSizeException( + boolean throwIllegalBlockSizeException) + { + this.throwIllegalBlockSizeException = throwIllegalBlockSizeException; + } + + public void setThrowBadPaddingException(boolean throwBadPaddingException) + { + this.throwBadPaddingException = throwBadPaddingException; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionConnection.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionConnection.java new file mode 100644 index 0000000000000000000000000000000000000000..f586d36fa224fcf6cdaf62366925772a9995a85b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionConnection.java @@ -0,0 +1,483 @@ +package org.opengauss.mppdbide.mock.presentation; + +import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; + +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils.EXCEPTIONENUM; +import com.mockrunner.mock.jdbc.MockConnection; + +public class ExceptionConnection extends MockConnection +{ + boolean throwExceptioForPrepareStmt = false; + boolean throwExceptioForStmt = false; + boolean needExceptioStatement = false; + boolean throwExceptionClose = false; + boolean throwExceptionMetaData = false; + boolean throwExceptionSetLong = false; + boolean throwExceptionCloseResultSet = false; + boolean throwExceptionCloseStmt = false; + boolean throwExceptionClosePreparedStmt = false; + boolean throwExceptionGetInt = false; + boolean throwExceptionSetInt = false; + boolean throwExceptionGetLong = false; + boolean throwExceptionGetString = false; + boolean throwExceptionSetString = false; + boolean throwExceptionGetBoolean = false; + EXCEPTIONENUM thrownResultSetNext = EXCEPTIONENUM.NO; + boolean needExceptionResultset = false; + private boolean needExecuteException = false; + boolean throwoutofmemerrorinrs = false; + private boolean throwExceptionNext = false; + String sqlState = ""; + boolean throwExceptionExecuteBatch = false; + SQLException sqlException = null; + boolean throwExceptionGetStatement = false; + boolean throwExceptionAddBatch = false; + boolean throwExceptionRollback = false; + boolean throwExceptionCommit=false; + + public boolean isThrowExceptionCommit() { + return throwExceptionCommit; + } + + public void setThrowExceptionCommit(boolean throwExceptionCommit) { + this.throwExceptionCommit = throwExceptionCommit; + } + + boolean throwExceptionSetAutoCommitTrue = false; + boolean throwExceptionGetAutoCommitTrue=false; + public boolean isThrowExceptionGetAutoCommitTrue() + { + return throwExceptionGetAutoCommitTrue; + } + + public void setThrowExceptionGetAutoCommitTrue( + boolean throwExceptionGetAutoCommitTrue) + { + this.throwExceptionGetAutoCommitTrue = throwExceptionGetAutoCommitTrue; + } + + private boolean throwIndexoutOfBondException=false; + String exceptionForNextOn; + + String counter; + + public void setExceptionForNextOn(String exceptionForNextOn) + { + this.exceptionForNextOn = exceptionForNextOn; + } + + public void setCounter(String counter) + { + this.counter = counter; + } + + public ExceptionConnection() + { + counter = null; + } + + public void setThrowExceptionSetAutoCommitTrue( + boolean throwExceptionSetAutoCommitTrue) + { + this.throwExceptionSetAutoCommitTrue = throwExceptionSetAutoCommitTrue; + } + + public void setThrowExceptionRollback(boolean throwExceptionRollback) + { + this.throwExceptionRollback = throwExceptionRollback; + } + + public void setThrowExceptionClosePreparedStmt( + boolean throwExceptionClosePreparedStmt) + { + this.throwExceptionClosePreparedStmt = throwExceptionClosePreparedStmt; + } + + public void setThrowIndexoutOfBondException(boolean throwIndexoutOfBondException) { + this.throwIndexoutOfBondException = throwIndexoutOfBondException; + } + + public void setThrowExceptionCloseStmt(boolean throwExceptionCloseStmt) + { + this.throwExceptionCloseStmt = throwExceptionCloseStmt; + } + + boolean throwIndexOutOfBoundEx = false; + private boolean isExceptionFromUser; + + public void setThrowIndexOutOfBoundEx(boolean throwIndexOutOfBoundEx) + { + this.throwIndexOutOfBoundEx = throwIndexOutOfBoundEx; + } + + public void setThrowExceptionAddBatch(boolean throwExceptionAddBatch) + { + this.throwExceptionAddBatch = throwExceptionAddBatch; + } + + public void setThrowExceptionGetStatement(boolean throwExceptionGetStatement) + { + this.throwExceptionGetStatement = throwExceptionGetStatement; + } + + + public void setSqlException(SQLException sqlException) + { + this.sqlException = sqlException; + } + + + public void setThrowExceptionNext(boolean throwExceptionNext) + { + this.throwExceptionNext = throwExceptionNext; + } + + + public void setThrowoutofmemerrorinrs(boolean throwoutofmemerrorinrs) + { + this.throwoutofmemerrorinrs = throwoutofmemerrorinrs; + } + + public void setNeedExceptionResultset(boolean needExceptionResultset) + { + this.needExceptionResultset = needExceptionResultset; + } + + public void setThrowExceptioForPrepareStmt(boolean throwExceptioForPrepareStmt) + { + this.throwExceptioForPrepareStmt = throwExceptioForPrepareStmt; + } + + public void setNeedExceptioStatement(boolean needExceptioStatement) + { + this.needExceptioStatement = needExceptioStatement; + } + + public void setThrowExceptionGetInt(boolean throwExceptionGetInt) + { + this.throwExceptionGetInt = throwExceptionGetInt; + } + public void setThrowExceptionGetLong(boolean throwExceptionGetLong) { + this.throwExceptionGetLong = throwExceptionGetLong; + } + + public void setThrowExceptionSetInt(boolean throwExceptionSetInt) + { + this.throwExceptionSetInt = throwExceptionSetInt; + } + + public void setThrowExceptionGetString(boolean throwExceptionGetString) + { + this.throwExceptionGetString = throwExceptionGetString; + } + + public void setThrowExceptionSetString(boolean throwExceptionSetString) + { + this.throwExceptionSetString = throwExceptionSetString; + } + + public void setThrowExceptionGetBoolean(boolean throwExceptionGetBoolean) + { + this.throwExceptionGetBoolean = throwExceptionGetBoolean; + } + + public void setThrowExceptionClose(boolean throwExceptionClose) + { + this.throwExceptionClose = throwExceptionClose; + } + + public void setThrowExceptionMetaData(boolean throwExceptionMetaData) + { + this.throwExceptionMetaData = throwExceptionMetaData; + } + + public void setThrowExceptioForStmt(boolean throwExceptioForStmt) + { + this.throwExceptioForStmt = throwExceptioForStmt; + } + + public void setThrowExceptionSetLong(boolean throwExceptionSetLong) + { + this.throwExceptionSetLong = throwExceptionSetLong; + } + + public void setThrowExceptionCloseResultSet(boolean throwExceptionCloseResultSet) + { + this.throwExceptionCloseResultSet = throwExceptionCloseResultSet; + } + + public void setSqlState(String sqlState) + { + this.sqlState = sqlState; + } + + public void setThrownResultSetNext(EXCEPTIONENUM thrownResultSetNext) + { + this.thrownResultSetNext = thrownResultSetNext; + } + + public void setThrowExceptionExecuteBatch(boolean throwExceptionExecuteBatch) + { + this.throwExceptionExecuteBatch = throwExceptionExecuteBatch; + } + + @Override + public PreparedStatement prepareStatement(String arg0) throws SQLException,IndexOutOfBoundsException + { + counter = arg0; + + if(throwExceptioForPrepareStmt) + { + throwExceptioForPrepareStmt = false; + if(null != sqlState && sqlState.length() > 0) + { + throw new SQLException(sqlState, sqlState); + } + else + { + throw new SQLException(); + } + + } + else if(needExceptioStatement) + { + ExceptionPreparedStatement exceptionPreparedStatement = new ExceptionPreparedStatement(); + + if (needExecuteException) + { + exceptionPreparedStatement.setNeedExecuteException(true); + if (isSetException()) + { + exceptionPreparedStatement.setExp(sqlException); + } + } + if(needExceptionResultset) + { + exceptionPreparedStatement.setNeedExceptionResultset(true); + } + if (throwExceptionSetLong) + { + exceptionPreparedStatement.setLongExceptionRequired(true); + } + + if (throwExceptionGetInt) + { + exceptionPreparedStatement.setThrowExceptionGetInt(true); + } + + if (throwExceptionGetLong) + { + exceptionPreparedStatement.setThrowExceptionGetLong(true); + } + + if (throwExceptionSetInt) + { + exceptionPreparedStatement.setThrowExceptionSetInt(true); + } + + if (throwExceptionGetString) + { + exceptionPreparedStatement.setThrowExceptionGetString(true); + } + + if (throwExceptionSetString) + { + exceptionPreparedStatement.setThrowExceptionSetString(true); + } + + if (throwExceptionGetBoolean) + { + exceptionPreparedStatement.setThrowExceptionGetBoolean(true); + } + + if (!thrownResultSetNext.equals(EXCEPTIONENUM.NO)) + { + exceptionPreparedStatement.setThrownResultSetNext(thrownResultSetNext); + } + + if (throwExceptionCloseResultSet) + { + exceptionPreparedStatement.setThrowExceptionCloseResultSet(true); + } + + if(throwExceptionClosePreparedStmt) + { + exceptionPreparedStatement.setStmtCloseSQLExceptionNeede(true); + } + + if(throwExceptionGetStatement) + { + exceptionPreparedStatement.setThrowExceptionGetStatement(true); + } + + if(throwoutofmemerrorinrs) + { + exceptionPreparedStatement.setOutOfMemoryErrorRequired(true); + } + + if(throwIndexoutOfBondException){ + exceptionPreparedStatement.setThrowIndexoutOfBondException(true); + } + if(sqlState != null) + { + exceptionPreparedStatement.setSQLSTate(sqlState); + } + if(exceptionForNextOn != null) + { + exceptionPreparedStatement.setExceptionForNextOn(exceptionForNextOn); + exceptionPreparedStatement.setCounter(counter); + } + + exceptionPreparedStatement.setExceptionResultSetRequired(true); + return exceptionPreparedStatement; + } + + + return super.prepareStatement(arg0); + } + + private boolean isSetException() + { + return isExceptionFromUser(); + } + + @Override + public Statement createStatement() throws SQLException + { + if(throwExceptioForStmt) + { + throwExceptioForStmt = false; + throw new SQLException(); + } + else if(needExceptioStatement) + { + ExceptionStatement exceptionStatement = new ExceptionStatement(); + exceptionStatement.setConnection(this); + if(needExceptionResultset) + { + exceptionStatement.setNeedExceptionResultset(true); + } + if(throwoutofmemerrorinrs) + { + exceptionStatement.setThrowoutofmemerror(throwoutofmemerrorinrs); + } + if(throwExceptionNext) + { + exceptionStatement.setThrowExceptionNext(true); + } + if(throwExceptionExecuteBatch) + { + exceptionStatement.setSqlException(sqlException); + } + + if(throwExceptionGetStatement) + { + exceptionStatement.setThrowExceptionGetStatement(true); + } + + if(throwExceptionAddBatch) + { + exceptionStatement.setThrowExceptionAddBatch(true); + } + exceptionStatement.setSqlException(sqlException); + + if(throwIndexOutOfBoundEx) + { + exceptionStatement.setThrowIndexOutOfBoundEx(true); + } + + if(throwExceptionCloseStmt) + { + exceptionStatement.setStmtCloseSQLExceptionNeede(throwExceptionCloseStmt); + } + if(throwExceptionCloseResultSet) + { + exceptionStatement.setThrowExceptionCloseResultSet(throwExceptionCloseResultSet); + } + return exceptionStatement; + } + return super.createStatement(); + } + + @Override + public void close() throws SQLException + { + if(throwExceptionClose) + { + throw new SQLException(); + } + super.close(); + } + + @Override + public DatabaseMetaData getMetaData() throws SQLException + { + if(throwExceptionMetaData) + { + throw new SQLException(); + } + return super.getMetaData(); + } + + @Override + public void rollback() throws SQLException + { + if(throwExceptionRollback) + { + throw sqlException; + } + super.rollback(); + } + + @Override + public void setAutoCommit(boolean arg0) throws SQLException + { + if(arg0 && throwExceptionSetAutoCommitTrue) + { + throw sqlException; + } + super.setAutoCommit(arg0); + } + + @Override + public boolean getAutoCommit() throws SQLException + { + if(throwExceptionGetAutoCommitTrue) + { + throw sqlException; + } + return super.getAutoCommit(); + } + + @Override + public void commit() throws SQLException { + + if (throwExceptionCommit) { + throw new SQLException(); + } + super.commit(); + } + + public boolean isNeedExecuteException() + { + return needExecuteException; + } + + public void setNeedExecuteException(boolean needExecuteException) + { + this.needExecuteException = needExecuteException; + } + + public boolean isExceptionFromUser() + { + return isExceptionFromUser; + } + + public void setExceptionFromUser(boolean isExceptionFromUser) + { + this.isExceptionFromUser = isExceptionFromUser; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionConnectionHelper.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionConnectionHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..f3dcd672a2d08cfbf365f65666fd2443ce9759d4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionConnectionHelper.java @@ -0,0 +1,263 @@ +package org.opengauss.mppdbide.mock.presentation; + +import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Map; + +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtilsHelper.EXCEPTIONENUM; +import com.mockrunner.mock.jdbc.MockConnection; + +public class ExceptionConnectionHelper extends MockConnection { + boolean throwExceptioForPrepareStmt = false; + boolean throwExceptioForStmt = false; + boolean needExceptioStatement = false; + boolean throwExceptionClose = false; + boolean throwExceptionMetaData = false; + boolean throwExceptionSetLong = false; + boolean throwExceptionCloseResultSet = false; + boolean throwExceptionGetInt = false; + boolean throwExceptionSetInt = false; + boolean throwExceptionGetString = false; + boolean throwExceptionSetString = false; + boolean throwExceptionGetBoolean = false; + boolean throwExceptionRollback = false; + boolean throwExceptionCommit=false; + + EXCEPTIONENUM thrownResultSetNext = EXCEPTIONENUM.NO; + boolean needExceptionResultset = false; + boolean throwoutofmemerrorinrs = false; + private boolean throwExceptionNext = false; + String sqlState = ""; + private boolean throwExceptionGetLong = false; + private boolean throwIndexoutOfBondException = false; + private boolean stmtCloseSQLExceptionNeede = false; + + public void setThrowExceptionNext(boolean throwExceptionNext) { + this.throwExceptionNext = throwExceptionNext; + } + + public void setThrowIndexoutOfBondException( + boolean throwIndexoutOfBondException) { + this.throwIndexoutOfBondException = throwIndexoutOfBondException; + } + + public void setStmtCloseSQLExceptionNeede(boolean stmtCloseSQLExceptionNeede) { + this.stmtCloseSQLExceptionNeede = stmtCloseSQLExceptionNeede; + } + + public void setThrowoutofmemerrorinrs(boolean throwoutofmemerrorinrs) { + this.throwoutofmemerrorinrs = throwoutofmemerrorinrs; + } + + public void setNeedExceptionResultset(boolean needExceptionResultset) { + this.needExceptionResultset = needExceptionResultset; + } + + public void setThrowExceptioForPrepareStmt( + boolean throwExceptioForPrepareStmt) { + this.throwExceptioForPrepareStmt = throwExceptioForPrepareStmt; + } + + public void setNeedExceptioStatement(boolean needExceptioStatement) { + this.needExceptioStatement = needExceptioStatement; + } + + public void setThrowExceptionGetInt(boolean throwExceptionGetInt) { + this.throwExceptionGetInt = throwExceptionGetInt; + } + + public void setThrowExceptionSetInt(boolean throwExceptionSetInt) { + this.throwExceptionSetInt = throwExceptionSetInt; + } + + public void setThrowExceptionGetString(boolean throwExceptionGetString) { + this.throwExceptionGetString = throwExceptionGetString; + } + + public void setThrowExceptionGetLong(boolean throwExceptionGetLong) { + this.throwExceptionGetLong = throwExceptionGetLong; + } + + public void setThrowExceptionSetString(boolean throwExceptionSetString) { + this.throwExceptionSetString = throwExceptionSetString; + } + + public void setThrowExceptionGetBoolean(boolean throwExceptionGetBoolean) { + this.throwExceptionGetBoolean = throwExceptionGetBoolean; + } + + public void setThrowExceptionClose(boolean throwExceptionClose) { + this.throwExceptionClose = throwExceptionClose; + } + + public void setThrowExceptionMetaData(boolean throwExceptionMetaData) { + this.throwExceptionMetaData = throwExceptionMetaData; + } + + public void setThrowExceptioForStmt(boolean throwExceptioForStmt) { + this.throwExceptioForStmt = throwExceptioForStmt; + } + + public void setThrowExceptionSetLong(boolean throwExceptionSetLong) { + this.throwExceptionSetLong = throwExceptionSetLong; + } + + public void setThrowExceptionCloseResultSet( + boolean throwExceptionCloseResultSet) { + this.throwExceptionCloseResultSet = throwExceptionCloseResultSet; + } + + public void setSqlState(String sqlState) { + this.sqlState = sqlState; + } + + public void setThrownResultSetNext(EXCEPTIONENUM thrownResultSetNext) { + this.thrownResultSetNext = thrownResultSetNext; + } + + public boolean isThrowExceptionRollback() { + return throwExceptionRollback; + } + + public void setThrowExceptionRollback(boolean throwExceptionRollback) { + this.throwExceptionRollback = throwExceptionRollback; + } + + public boolean isThrowExceptionCommit() { + return throwExceptionCommit; + } + + public void setThrowExceptionCommit(boolean throwExceptionCommit) { + this.throwExceptionCommit = throwExceptionCommit; + } + + + @Override + public PreparedStatement prepareStatement(String arg0) throws SQLException, + IndexOutOfBoundsException { + if (throwExceptioForPrepareStmt) { + throwExceptioForPrepareStmt = false; + if (null != sqlState && sqlState.length() > 0) { + throw new SQLException(sqlState, sqlState); + } else { + throw new SQLException(); + } + + } else if (needExceptioStatement) { + ExceptionPreparedStatementHelper exceptionPreparedStatement = new ExceptionPreparedStatementHelper(); + if (throwExceptionSetLong) { + exceptionPreparedStatement.setLongExceptionRequired(true); + } + + if (throwExceptionGetInt) { + exceptionPreparedStatement.setThrowExceptionGetInt(true); + } + + if (throwExceptionGetLong) { + exceptionPreparedStatement.setThrowExceptionGetLong(true); + } + + if (throwExceptionSetInt) { + exceptionPreparedStatement.setThrowExceptionSetInt(true); + } + + if (throwExceptionGetString) { + exceptionPreparedStatement.setThrowExceptionGetString(true); + } + + if (throwExceptionSetString) { + exceptionPreparedStatement.setThrowExceptionSetString(true); + } + + if (throwExceptionGetBoolean) { + exceptionPreparedStatement.setThrowExceptionGetBoolean(true); + } + + if (!thrownResultSetNext.equals(EXCEPTIONENUM.NO)) { + exceptionPreparedStatement + .setThrownResultSetNext(thrownResultSetNext); + } + + if (throwExceptionCloseResultSet) { + exceptionPreparedStatement + .setThrowExceptionCloseResultSet(true); + } + + if (throwIndexoutOfBondException) { + exceptionPreparedStatement + .setThrowIndexoutOfBondException(true); + } + if (stmtCloseSQLExceptionNeede) { + exceptionPreparedStatement.setStmtCloseSQLExceptionNeede(true); + } + exceptionPreparedStatement.setExceptionResultSetRequired(true); + return exceptionPreparedStatement; + } + + return super.prepareStatement(arg0); + } + + @Override + public Statement createStatement() throws SQLException { + if (throwExceptioForStmt) { + throwExceptioForStmt = false; + throw new SQLException(); + } else if (needExceptioStatement) { + ExceptionStatement exceptionStatement = new ExceptionStatement(); + if (needExceptionResultset) { + exceptionStatement.setNeedExceptionResultset(true); + } + if (throwoutofmemerrorinrs) { + exceptionStatement + .setThrowoutofmemerror(throwoutofmemerrorinrs); + } + if (throwIndexoutOfBondException) + exceptionStatement.setThrowIndexoutOfBondException(true); + if (throwExceptionNext) { + exceptionStatement.setThrowExceptionNext(true); + } + if (stmtCloseSQLExceptionNeede) { + exceptionStatement.setStmtCloseSQLExceptionNeede(true); + } + return exceptionStatement; + } + return super.createStatement(); + } + + @Override + public void close() throws SQLException { + if (throwExceptionClose) { + throw new SQLException(); + } + super.close(); + } + + @Override + public DatabaseMetaData getMetaData() throws SQLException { + if (throwExceptionMetaData) { + throw new SQLException(); + } + return super.getMetaData(); + } + + @Override + public void rollback() throws SQLException { + + if (throwExceptionRollback) { + throw new SQLException(); + } + super.rollback(); + } + + @Override + public void commit() throws SQLException { + + if (throwExceptionCommit) { + throw new SQLException(); + } + super.commit(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionPreparedStatement.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionPreparedStatement.java new file mode 100644 index 0000000000000000000000000000000000000000..a7c42d7e051eabd9ec26227f5d6da2236290a723 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionPreparedStatement.java @@ -0,0 +1,1054 @@ +package org.opengauss.mppdbide.mock.presentation; + +import java.io.InputStream; +import java.io.Reader; +import java.math.BigDecimal; +import java.net.URL; +import java.sql.Array; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.Date; +import java.sql.NClob; +import java.sql.ParameterMetaData; +import java.sql.PreparedStatement; +import java.sql.Ref; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.RowId; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.SQLXML; +import java.sql.Time; +import java.sql.Timestamp; +import java.util.Calendar; + +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils.EXCEPTIONENUM; + + +public class ExceptionPreparedStatement implements PreparedStatement +{ + private boolean outOfMemoryErrorRequired = false; + private boolean stmtCloseSQLExceptionNeede = false; + private boolean setLongExceptionRequired = false; + private boolean setExceptionResultSetRequired = false; + private boolean throwExceptionCloseResultSet = false; + private boolean throwExceptionGetInt = false; + private boolean throwExceptionSetInt = false; + private EXCEPTIONENUM thrownResultSetNext = EXCEPTIONENUM.NO; + private boolean throwExceptionGetString = false; + private boolean throwExceptionGetBoolean = false; + private boolean throwExceptionSetString = false; + private boolean throwExceptionGetLong = false; + private boolean throwIndexoutOfBondException=false; + private boolean needExceptionResultset = false; + private boolean needExecuteException = false; + @SuppressWarnings("unused") + private boolean throwExceptionClosePreparedStmt = false; + private ExceptionResultset exceptionResultset = null; + + private SQLException exp; + String exceptionForNextOn; + + String counter; + + public void setExceptionForNextOn(String exceptionForNextOn) + { + this.exceptionForNextOn = exceptionForNextOn; + } + + public void setCounter(String counter) + { + this.counter = counter; + } + + private String sqlState = null; + + private boolean throwExceptionGetStatement = false; + + public void setSQLSTate(String sqlState) + { + this.sqlState = sqlState; + } + + public void setThrowExceptionClosePreparedStmt( + boolean throwExceptionClosePreparedStmt) + { + this.throwExceptionClosePreparedStmt = throwExceptionClosePreparedStmt; + } + + public void setThrowIndexoutOfBondException(boolean throwIndexoutOfBondException) { + this.throwIndexoutOfBondException = throwIndexoutOfBondException; + } + + public void setThrowExceptionGetStatement(boolean throwExceptionGetStatement) + { + this.throwExceptionGetStatement = throwExceptionGetStatement; + } + + public void setLongExceptionRequired(boolean setLongExceptionRequired) + { + this.setLongExceptionRequired = setLongExceptionRequired; + } + + public void setThrowExceptionGetLong(boolean throwExceptionGetLong) { + this.throwExceptionGetLong = throwExceptionGetLong; + } + + public void setThrowExceptionGetInt(boolean throwExceptionGetInt) + { + this.throwExceptionGetInt = throwExceptionGetInt; + } + + public void setThrowExceptionSetInt(boolean throwExceptionSetInt) + { + this.throwExceptionSetInt = throwExceptionSetInt; + } + + public void setThrowExceptionGetBoolean(boolean throwExceptionGetBoolean) + { + this.throwExceptionGetBoolean = throwExceptionGetBoolean; + } + + public void setThrowExceptionGetString(boolean throwExceptionGetString) + { + this.throwExceptionGetString = throwExceptionGetString; + } + + public void setThrowExceptionSetString(boolean throwExceptionSetString) + { + this.throwExceptionSetString = throwExceptionSetString; + } + + public void setStmtCloseSQLExceptionNeede(boolean stmtCloseSQLExceptionNeede) + { + this.stmtCloseSQLExceptionNeede = stmtCloseSQLExceptionNeede; + } + + public void setExceptionResultSetRequired(boolean setExceptionResultSetRequired) + { + this.setExceptionResultSetRequired = setExceptionResultSetRequired; + } + + public void setThrowExceptionCloseResultSet(boolean throwExceptionCloseResultSet) + { + this.throwExceptionCloseResultSet = throwExceptionCloseResultSet; + } + + public void setThrownResultSetNext(EXCEPTIONENUM thrownResultSetNext) + { + this.thrownResultSetNext = thrownResultSetNext; + } + + @Override + public void addBatch(String arg0) throws SQLException + { + + + } + + @Override + public void cancel() throws SQLException + { + throw new SQLException(); + } + + @Override + public void clearBatch() throws SQLException + { + + + } + + @Override + public void clearWarnings() throws SQLException + { + + + } + + @Override + public void close() throws SQLException + { + if(stmtCloseSQLExceptionNeede) + { + throw new SQLException(); + } + } + + @Override + public boolean execute(String arg0) throws SQLException + { + if (needExceptionResultset) + { + if(null == exceptionResultset) + { + exceptionResultset = new ExceptionResultset(); + exceptionResultset.setStatement(this); + } + } + return true; + } + + @Override + public boolean execute(String arg0, int arg1) throws SQLException + { + + return false; + } + + @Override + public boolean execute(String arg0, int[] arg1) throws SQLException + { + + return false; + } + + @Override + public boolean execute(String arg0, String[] arg1) throws SQLException + { + + if (outOfMemoryErrorRequired) + { + throw new OutOfMemoryError(); + } + + + return false; + } + + @Override + public int[] executeBatch() throws SQLException + { + + return null; + } + + @Override + public ResultSet executeQuery(String arg0) throws SQLException,IndexOutOfBoundsException + { + if (setExceptionResultSetRequired) + { + ExceptionResultset exceptionResultset = new ExceptionResultset(); + + if (throwExceptionCloseResultSet) + { + exceptionResultset.setThrowExceptionCloseResultSet(true); + } + + if (!thrownResultSetNext.equals(EXCEPTIONENUM.NO)) + { + exceptionResultset.setResultSetNext(thrownResultSetNext); + } + + if (throwExceptionGetInt) + { + exceptionResultset.setThrowExceptionGetInt(true); + } + if (throwExceptionGetLong) + { + exceptionResultset.setThrowExceptionGetLong(true); + } + if (throwExceptionGetBoolean) + { + exceptionResultset.setThrowExceptionGetBoolean(true); + } + + if (throwExceptionGetString) + { + exceptionResultset.setThrowExceptionGetString(true); + } + + if(throwExceptionGetStatement) + { + exceptionResultset.setThrowExceptionGetStatement(true); + } + + if(sqlState != null) + { + exceptionResultset.setSqlState(sqlState); + } + if(throwIndexoutOfBondException){ + throw new IndexOutOfBoundsException(); + } + if(exceptionForNextOn != null) + { + exceptionResultset.setExceptionForNextOn(exceptionForNextOn); + exceptionResultset.setExceptioncounter(arg0); + } + exceptionResultset.setStatement(this); + return exceptionResultset; + } + + return null; + } + + @Override + public int executeUpdate(String arg0) throws SQLException + { + + return 0; + } + + @Override + public int executeUpdate(String arg0, int arg1) throws SQLException + { + + return 0; + } + + @Override + public int executeUpdate(String arg0, int[] arg1) throws SQLException + { + + return 0; + } + + @Override + public int executeUpdate(String arg0, String[] arg1) throws SQLException + { + + return 0; + } + + @Override + public Connection getConnection() throws SQLException + { + + return null; + } + + @Override + public int getFetchDirection() throws SQLException + { + + return 0; + } + + @Override + public int getFetchSize() throws SQLException + { + + return 0; + } + + @Override + public ResultSet getGeneratedKeys() throws SQLException + { + + return null; + } + + @Override + public int getMaxFieldSize() throws SQLException + { + + return 0; + } + + @Override + public int getMaxRows() throws SQLException + { + + return 0; + } + + @Override + public boolean getMoreResults() throws SQLException + { + + return false; + } + + @Override + public boolean getMoreResults(int arg0) throws SQLException + { + + return false; + } + + @Override + public int getQueryTimeout() throws SQLException + { + + return 0; + } + + @Override + public ResultSet getResultSet() throws SQLException + { + if (setExceptionResultSetRequired) + { + ExceptionResultset exceptionResultset = new ExceptionResultset(); + + if (throwExceptionCloseResultSet) + { + exceptionResultset.setThrowExceptionCloseResultSet(true); + } + if(sqlState != null) + { + exceptionResultset.setSqlState(sqlState); + } + exceptionResultset.setStatement(this); + return exceptionResultset; + } + + + return null; + } + + @Override + public int getResultSetConcurrency() throws SQLException + { + + return 0; + } + + @Override + public int getResultSetHoldability() throws SQLException + { + + return 0; + } + + @Override + public int getResultSetType() throws SQLException + { + + return 0; + } + + @Override + public int getUpdateCount() throws SQLException + { + + return 0; + } + + @Override + public SQLWarning getWarnings() throws SQLException + { + + return null; + } + + @Override + public boolean isClosed() throws SQLException + { + + return false; + } + + @Override + public boolean isPoolable() throws SQLException + { + + return false; + } + + @Override + public void setCursorName(String arg0) throws SQLException + { + + + } + + @Override + public void setEscapeProcessing(boolean arg0) throws SQLException + { + + + } + + @Override + public void setFetchDirection(int arg0) throws SQLException + { + + + } + + @Override + public void setFetchSize(int arg0) throws SQLException + { + + + } + + @Override + public void setMaxFieldSize(int arg0) throws SQLException + { + + + } + + @Override + public void setMaxRows(int arg0) throws SQLException + { + + + } + + @Override + public void setPoolable(boolean arg0) throws SQLException + { + + + } + + @Override + public void setQueryTimeout(int arg0) throws SQLException + { + + + } + + @Override + public boolean isWrapperFor(Class arg0) throws SQLException + { + + return false; + } + + @Override + public T unwrap(Class arg0) throws SQLException + { + + return null; + } + + @Override + public void addBatch() throws SQLException + { + + + } + + @Override + public void clearParameters() throws SQLException + { + + + } + + @Override + public boolean execute() throws SQLException + { + if (outOfMemoryErrorRequired) + { + throw new OutOfMemoryError(); + } + + if (needExceptionResultset) + { + if(null == exceptionResultset) + { + exceptionResultset = new ExceptionResultset(); + exceptionResultset.setStatement(this); + } + } + else if (isNeedExecuteException()) + { + if (getExp() != null) + { + throw getExp(); + } + else + { + throw new SQLException(); + } + } + return true; + } + + @Override + public ResultSet executeQuery() throws SQLException + { + + if (outOfMemoryErrorRequired) + { + throw new OutOfMemoryError(); + } + + if (setExceptionResultSetRequired) + { + ExceptionResultset exceptionResultset = new ExceptionResultset(); + + if (throwExceptionCloseResultSet) + { + exceptionResultset.setThrowExceptionCloseResultSet(true); + } + + exceptionResultset.setResultSetNext(thrownResultSetNext); + + if (throwExceptionGetInt) + { + exceptionResultset.setThrowExceptionGetInt(true); + } + if (throwExceptionGetLong) + { + exceptionResultset.setThrowExceptionGetLong(true); + } + if (throwExceptionGetBoolean) + { + exceptionResultset.setThrowExceptionGetBoolean(true); + } + + if (throwExceptionGetString) + { + exceptionResultset.setThrowExceptionGetString(true); + } + if(sqlState != null) + { + exceptionResultset.setSqlState(sqlState); + } + if(exceptionForNextOn != null) + { + exceptionResultset.setExceptionForNextOn(exceptionForNextOn); + exceptionResultset.setExceptioncounter(counter); + } + exceptionResultset.setStatement(this); + return exceptionResultset; + } + + return null; + } + + @Override + public int executeUpdate() throws SQLException + { + + return 0; + } + + @Override + public ResultSetMetaData getMetaData() throws SQLException + { + + return null; + } + + @Override + public ParameterMetaData getParameterMetaData() throws SQLException + { + + return null; + } + + @Override + public void setArray(int arg0, Array arg1) throws SQLException + { + + + } + + @Override + public void setAsciiStream(int arg0, InputStream arg1) throws SQLException + { + + + } + + @Override + public void setAsciiStream(int arg0, InputStream arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void setAsciiStream(int arg0, InputStream arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void setBigDecimal(int arg0, BigDecimal arg1) throws SQLException + { + + + } + + @Override + public void setBinaryStream(int arg0, InputStream arg1) throws SQLException + { + + + } + + @Override + public void setBinaryStream(int arg0, InputStream arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void setBinaryStream(int arg0, InputStream arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void setBlob(int arg0, Blob arg1) throws SQLException + { + + + } + + @Override + public void setBlob(int arg0, InputStream arg1) throws SQLException + { + + + } + + @Override + public void setBlob(int arg0, InputStream arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void setBoolean(int arg0, boolean arg1) throws SQLException + { + + + } + + @Override + public void setByte(int arg0, byte arg1) throws SQLException + { + + + } + + @Override + public void setBytes(int arg0, byte[] arg1) throws SQLException + { + + + } + + @Override + public void setCharacterStream(int arg0, Reader arg1) throws SQLException + { + + + } + + @Override + public void setCharacterStream(int arg0, Reader arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void setCharacterStream(int arg0, Reader arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void setClob(int arg0, Clob arg1) throws SQLException + { + + + } + + @Override + public void setClob(int arg0, Reader arg1) throws SQLException + { + + + } + + @Override + public void setClob(int arg0, Reader arg1, long arg2) throws SQLException + { + + + } + + @Override + public void setDate(int arg0, Date arg1) throws SQLException + { + + + } + + @Override + public void setDate(int arg0, Date arg1, Calendar arg2) throws SQLException + { + + + } + + @Override + public void setDouble(int arg0, double arg1) throws SQLException + { + + + } + + @Override + public void setFloat(int arg0, float arg1) throws SQLException + { + + + } + + @Override + public void setInt(int arg0, int arg1) throws SQLException + { + if (throwExceptionSetInt) + { + throw new SQLException(); + } + } + + @Override + public void setLong(int arg0, long arg1) throws SQLException + { + if (setLongExceptionRequired) + { + throw new SQLException(); + } + } + + @Override + public void setNCharacterStream(int arg0, Reader arg1) throws SQLException + { + + + } + + @Override + public void setNCharacterStream(int arg0, Reader arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void setNClob(int arg0, NClob arg1) throws SQLException + { + + + } + + @Override + public void setNClob(int arg0, Reader arg1) throws SQLException + { + + + } + + @Override + public void setNClob(int arg0, Reader arg1, long arg2) throws SQLException + { + + + } + + @Override + public void setNString(int arg0, String arg1) throws SQLException + { + + + } + + @Override + public void setNull(int arg0, int arg1) throws SQLException + { + + + } + + @Override + public void setNull(int arg0, int arg1, String arg2) throws SQLException + { + + + } + + @Override + public void setObject(int arg0, Object arg1) throws SQLException + { + + + } + + @Override + public void setObject(int arg0, Object arg1, int arg2) throws SQLException + { + + + } + + @Override + public void setObject(int arg0, Object arg1, int arg2, int arg3) + throws SQLException + { + + + } + + @Override + public void setRef(int arg0, Ref arg1) throws SQLException + { + + + } + + @Override + public void setRowId(int arg0, RowId arg1) throws SQLException + { + + + } + + @Override + public void setSQLXML(int arg0, SQLXML arg1) throws SQLException + { + + + } + + @Override + public void setShort(int arg0, short arg1) throws SQLException + { + + + } + + @Override + public void setString(int arg0, String arg1) throws SQLException + { + if (throwExceptionSetString) + { + throw new SQLException(); + } + // throw new SQLException(); + } + + @Override + public void setTime(int arg0, Time arg1) throws SQLException + { + + + } + + @Override + public void setTime(int arg0, Time arg1, Calendar arg2) throws SQLException + { + + + } + + @Override + public void setTimestamp(int arg0, Timestamp arg1) throws SQLException + { + + + } + + @Override + public void setTimestamp(int arg0, Timestamp arg1, Calendar arg2) + throws SQLException + { + + + } + + @Override + public void setURL(int arg0, URL arg1) throws SQLException + { + + + } + + @Override + public void setUnicodeStream(int arg0, InputStream arg1, int arg2) + throws SQLException + { + + + } + + public boolean isOutOfMemoryErrorRequired() + { + return outOfMemoryErrorRequired; + } + + public void setOutOfMemoryErrorRequired(boolean outOfMemoryErrorRequired) + { + this.outOfMemoryErrorRequired = outOfMemoryErrorRequired; + } + + @Override + public void closeOnCompletion() throws SQLException { + + + } + + @Override + public boolean isCloseOnCompletion() throws SQLException { + + return false; + } + + public boolean isNeedExceptionResultset() + { + return needExceptionResultset; + } + + public void setNeedExceptionResultset(boolean needExceptionResultset) + { + this.needExceptionResultset = needExceptionResultset; + } + + public ExceptionResultset getExceptionResultset() + { + return exceptionResultset; + } + + public void setExceptionResultset(ExceptionResultset exceptionResultset) + { + this.exceptionResultset = exceptionResultset; + } + + public boolean isNeedExecuteException() + { + return needExecuteException; + } + + public void setNeedExecuteException(boolean needExecuteException) + { + this.needExecuteException = needExecuteException; + } + + public SQLException getExp() + { + return exp; + } + + public void setExp(SQLException exp) + { + this.exp = exp; + } + + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionPreparedStatementHelper.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionPreparedStatementHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..582117a61939c92032e93e77d64967392a6feaa2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionPreparedStatementHelper.java @@ -0,0 +1,913 @@ +package org.opengauss.mppdbide.mock.presentation; + +import java.io.InputStream; +import java.io.Reader; +import java.math.BigDecimal; +import java.net.URL; +import java.sql.Array; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.Date; +import java.sql.NClob; +import java.sql.ParameterMetaData; +import java.sql.PreparedStatement; +import java.sql.Ref; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.RowId; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.SQLXML; +import java.sql.Time; +import java.sql.Timestamp; +import java.util.Calendar; + +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtilsHelper.EXCEPTIONENUM; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockPreparedStatement; + +public class ExceptionPreparedStatementHelper implements PreparedStatement +{ + private boolean outOfMemoryErrorRequired = false; + private boolean stmtCloseSQLExceptionNeede = false; + private boolean setLongExceptionRequired = false; + private boolean setExceptionResultSetRequired = false; + private boolean throwExceptionCloseResultSet = false; + private boolean throwExceptionGetInt = false; + private boolean throwExceptionSetInt = false; + private EXCEPTIONENUM thrownResultSetNext = EXCEPTIONENUM.NO; + private boolean throwExceptionGetString = false; + private boolean throwExceptionGetBoolean = false; + private boolean throwExceptionSetString = false; + private boolean throwExceptionGetLong = false; + private boolean throwIndexoutOfBondException=false; + public void setLongExceptionRequired(boolean setLongExceptionRequired) + { + this.setLongExceptionRequired = setLongExceptionRequired; + } + + public void setThrowExceptionGetInt(boolean throwExceptionGetInt) + { + this.throwExceptionGetInt = throwExceptionGetInt; + } + + public void setThrowIndexoutOfBondException(boolean throwIndexoutOfBondException) { + this.throwIndexoutOfBondException = throwIndexoutOfBondException; + } + + public void setThrowExceptionGetLong(boolean throwExceptionGetLong) + { + this.throwExceptionGetLong = throwExceptionGetLong; + } + + public void setThrowExceptionSetInt(boolean throwExceptionSetInt) + { + this.throwExceptionSetInt = throwExceptionSetInt; + } + + public void setThrowExceptionGetBoolean(boolean throwExceptionGetBoolean) + { + this.throwExceptionGetBoolean = throwExceptionGetBoolean; + } + + public void setThrowExceptionGetString(boolean throwExceptionGetString) + { + this.throwExceptionGetString = throwExceptionGetString; + } + + public void setThrowExceptionSetString(boolean throwExceptionSetString) + { + this.throwExceptionSetString = throwExceptionSetString; + } + + public void setStmtCloseSQLExceptionNeede(boolean stmtCloseSQLExceptionNeede) + { + this.stmtCloseSQLExceptionNeede = stmtCloseSQLExceptionNeede; + } + + public void setExceptionResultSetRequired(boolean setExceptionResultSetRequired) + { + this.setExceptionResultSetRequired = setExceptionResultSetRequired; + } + + public void setThrowExceptionCloseResultSet(boolean throwExceptionCloseResultSet) + { + this.throwExceptionCloseResultSet = throwExceptionCloseResultSet; + } + + public void setThrownResultSetNext(EXCEPTIONENUM thrownResultSetNext) + { + this.thrownResultSetNext = thrownResultSetNext; + } + + @Override + public void addBatch(String arg0) throws SQLException + { + + + } + + @Override + public void cancel() throws SQLException + { + throw new SQLException(); + } + + @Override + public void clearBatch() throws SQLException + { + + + } + + @Override + public void clearWarnings() throws SQLException + { + + + } + + @Override + public void close() throws SQLException + { + if(stmtCloseSQLExceptionNeede) + { + throw new SQLException(); + } + } + + @Override + public boolean execute(String arg0) throws SQLException + { + + return false; + } + + @Override + public boolean execute(String arg0, int arg1) throws SQLException + { + + return false; + } + + @Override + public boolean execute(String arg0, int[] arg1) throws SQLException + { + + return false; + } + + @Override + public boolean execute(String arg0, String[] arg1) throws SQLException + { + + if (outOfMemoryErrorRequired) + { + throw new OutOfMemoryError(); + } + + + return false; + } + + @Override + public int[] executeBatch() throws SQLException + { + + return null; + } + + @Override + public ResultSet executeQuery(String arg0) throws SQLException,IndexOutOfBoundsException + { + if (setExceptionResultSetRequired) + { + ExceptionResultsetHelper exceptionResultset = new ExceptionResultsetHelper(); + + if (throwExceptionCloseResultSet) + { + exceptionResultset.setThrowExceptionCloseResultSet(true); + } + + if (!thrownResultSetNext.equals(EXCEPTIONENUM.NO)) + { + exceptionResultset.setResultSetNext(thrownResultSetNext); + } + + if (throwExceptionGetInt) + { + exceptionResultset.setThrowExceptionGetInt(true); + } + if (throwExceptionGetLong) + { + exceptionResultset.setThrowExceptionGetLong(true); + } + if (throwExceptionGetBoolean) + { + exceptionResultset.setThrowExceptionGetBoolean(true); + } + + if (throwExceptionGetString) + { + exceptionResultset.setThrowExceptionGetString(true); + } + + if(throwIndexoutOfBondException){ + throw new IndexOutOfBoundsException(); + } + return exceptionResultset; + } + + return null; + } + + @Override + public int executeUpdate(String arg0) throws SQLException + { + + return 0; + } + + @Override + public int executeUpdate(String arg0, int arg1) throws SQLException + { + + return 0; + } + + @Override + public int executeUpdate(String arg0, int[] arg1) throws SQLException + { + + return 0; + } + + @Override + public int executeUpdate(String arg0, String[] arg1) throws SQLException + { + + return 0; + } + + @Override + public Connection getConnection() throws SQLException + { + + return null; + } + + @Override + public int getFetchDirection() throws SQLException + { + + return 0; + } + + @Override + public int getFetchSize() throws SQLException + { + + return 0; + } + + @Override + public ResultSet getGeneratedKeys() throws SQLException + { + + return null; + } + + @Override + public int getMaxFieldSize() throws SQLException + { + + return 0; + } + + @Override + public int getMaxRows() throws SQLException + { + + return 0; + } + + @Override + public boolean getMoreResults() throws SQLException + { + + return false; + } + + @Override + public boolean getMoreResults(int arg0) throws SQLException + { + + return false; + } + + @Override + public int getQueryTimeout() throws SQLException + { + + return 0; + } + + @Override + public ResultSet getResultSet() throws SQLException + { + if (setExceptionResultSetRequired) + { + ExceptionResultset exceptionResultset = new ExceptionResultset(); + + if (throwExceptionCloseResultSet) + { + exceptionResultset.setThrowExceptionCloseResultSet(true); + } + + return exceptionResultset; + } + + + return null; + } + + @Override + public int getResultSetConcurrency() throws SQLException + { + + return 0; + } + + @Override + public int getResultSetHoldability() throws SQLException + { + + return 0; + } + + @Override + public int getResultSetType() throws SQLException + { + + return 0; + } + + @Override + public int getUpdateCount() throws SQLException + { + + return 0; + } + + @Override + public SQLWarning getWarnings() throws SQLException + { + + return null; + } + + @Override + public boolean isClosed() throws SQLException + { + + return false; + } + + @Override + public boolean isPoolable() throws SQLException + { + + return false; + } + + @Override + public void setCursorName(String arg0) throws SQLException + { + + + } + + @Override + public void setEscapeProcessing(boolean arg0) throws SQLException + { + + + } + + @Override + public void setFetchDirection(int arg0) throws SQLException + { + + + } + + @Override + public void setFetchSize(int arg0) throws SQLException + { + + + } + + @Override + public void setMaxFieldSize(int arg0) throws SQLException + { + + + } + + @Override + public void setMaxRows(int arg0) throws SQLException + { + + + } + + @Override + public void setPoolable(boolean arg0) throws SQLException + { + + + } + + @Override + public void setQueryTimeout(int arg0) throws SQLException + { + + + } + + @Override + public boolean isWrapperFor(Class arg0) throws SQLException + { + + return false; + } + + @Override + public T unwrap(Class arg0) throws SQLException + { + + return null; + } + + @Override + public void addBatch() throws SQLException + { + + + } + + @Override + public void clearParameters() throws SQLException + { + + + } + + @Override + public boolean execute() throws SQLException + { + + return false; + } + + @Override + public ResultSet executeQuery() throws SQLException,IndexOutOfBoundsException + { + if (setExceptionResultSetRequired) + { + ExceptionResultsetHelper exceptionResultset = new ExceptionResultsetHelper(); + + if (throwExceptionCloseResultSet) + { + exceptionResultset.setThrowExceptionCloseResultSet(true); + } + + exceptionResultset.setResultSetNext(thrownResultSetNext); + + if (throwExceptionGetInt) + { + exceptionResultset.setThrowExceptionGetInt(true); + } + if (throwExceptionGetLong) + { + exceptionResultset.setThrowExceptionGetLong(true); + } + if (throwExceptionGetBoolean) + { + exceptionResultset.setThrowExceptionGetBoolean(true); + } + + if (throwExceptionGetString) + { + exceptionResultset.setThrowExceptionGetString(true); + } + if(throwIndexoutOfBondException){ + throw new IndexOutOfBoundsException(); + } + + return exceptionResultset; + } + + return null; + } + + @Override + public int executeUpdate() throws SQLException + { + + return 0; + } + + @Override + public ResultSetMetaData getMetaData() throws SQLException + { + + return null; + } + + @Override + public ParameterMetaData getParameterMetaData() throws SQLException + { + + return null; + } + + @Override + public void setArray(int arg0, Array arg1) throws SQLException + { + + + } + + @Override + public void setAsciiStream(int arg0, InputStream arg1) throws SQLException + { + + + } + + @Override + public void setAsciiStream(int arg0, InputStream arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void setAsciiStream(int arg0, InputStream arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void setBigDecimal(int arg0, BigDecimal arg1) throws SQLException + { + + + } + + @Override + public void setBinaryStream(int arg0, InputStream arg1) throws SQLException + { + + + } + + @Override + public void setBinaryStream(int arg0, InputStream arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void setBinaryStream(int arg0, InputStream arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void setBlob(int arg0, Blob arg1) throws SQLException + { + + + } + + @Override + public void setBlob(int arg0, InputStream arg1) throws SQLException + { + + + } + + @Override + public void setBlob(int arg0, InputStream arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void setBoolean(int arg0, boolean arg1) throws SQLException + { + + + } + + @Override + public void setByte(int arg0, byte arg1) throws SQLException + { + + + } + + @Override + public void setBytes(int arg0, byte[] arg1) throws SQLException + { + + + } + + @Override + public void setCharacterStream(int arg0, Reader arg1) throws SQLException + { + + + } + + @Override + public void setCharacterStream(int arg0, Reader arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void setCharacterStream(int arg0, Reader arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void setClob(int arg0, Clob arg1) throws SQLException + { + + + } + + @Override + public void setClob(int arg0, Reader arg1) throws SQLException + { + + + } + + @Override + public void setClob(int arg0, Reader arg1, long arg2) throws SQLException + { + + + } + + @Override + public void setDate(int arg0, Date arg1) throws SQLException + { + + + } + + @Override + public void setDate(int arg0, Date arg1, Calendar arg2) throws SQLException + { + + + } + + @Override + public void setDouble(int arg0, double arg1) throws SQLException + { + + + } + + @Override + public void setFloat(int arg0, float arg1) throws SQLException + { + + + } + + @Override + public void setInt(int arg0, int arg1) throws SQLException + { + if (throwExceptionSetInt) + { + throw new SQLException(); + } + } + + @Override + public void setLong(int arg0, long arg1) throws SQLException + { + if (setLongExceptionRequired) + { + throw new SQLException(); + } + } + + @Override + public void setNCharacterStream(int arg0, Reader arg1) throws SQLException + { + + + } + + @Override + public void setNCharacterStream(int arg0, Reader arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void setNClob(int arg0, NClob arg1) throws SQLException + { + + + } + + @Override + public void setNClob(int arg0, Reader arg1) throws SQLException + { + + + } + + @Override + public void setNClob(int arg0, Reader arg1, long arg2) throws SQLException + { + + + } + + @Override + public void setNString(int arg0, String arg1) throws SQLException + { + + + } + + @Override + public void setNull(int arg0, int arg1) throws SQLException + { + + + } + + @Override + public void setNull(int arg0, int arg1, String arg2) throws SQLException + { + + + } + + @Override + public void setObject(int arg0, Object arg1) throws SQLException + { + + + } + + @Override + public void setObject(int arg0, Object arg1, int arg2) throws SQLException + { + + + } + + @Override + public void setObject(int arg0, Object arg1, int arg2, int arg3) + throws SQLException + { + + + } + + @Override + public void setRef(int arg0, Ref arg1) throws SQLException + { + + + } + + @Override + public void setRowId(int arg0, RowId arg1) throws SQLException + { + + + } + + @Override + public void setSQLXML(int arg0, SQLXML arg1) throws SQLException + { + + + } + + @Override + public void setShort(int arg0, short arg1) throws SQLException + { + + + } + + @Override + public void setString(int arg0, String arg1) throws SQLException + { + if (throwExceptionSetString) + { + throw new SQLException(); + } + // throw new SQLException(); + } + + @Override + public void setTime(int arg0, Time arg1) throws SQLException + { + + + } + + @Override + public void setTime(int arg0, Time arg1, Calendar arg2) throws SQLException + { + + + } + + @Override + public void setTimestamp(int arg0, Timestamp arg1) throws SQLException + { + + + } + + @Override + public void setTimestamp(int arg0, Timestamp arg1, Calendar arg2) + throws SQLException + { + + + } + + @Override + public void setURL(int arg0, URL arg1) throws SQLException + { + + + } + + @Override + public void setUnicodeStream(int arg0, InputStream arg1, int arg2) + throws SQLException + { + + + } + + public boolean isOutOfMemoryErrorRequired() + { + return outOfMemoryErrorRequired; + } + + public void setOutOfMemoryErrorRequired(boolean outOfMemoryErrorRequired) + { + this.outOfMemoryErrorRequired = outOfMemoryErrorRequired; + } + + @Override + public void closeOnCompletion() throws SQLException { + + + } + + @Override + public boolean isCloseOnCompletion() throws SQLException { + + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionRSMetadata.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionRSMetadata.java new file mode 100644 index 0000000000000000000000000000000000000000..573b2f8e461276ec1a0dd812a02b57dabe2d76c0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionRSMetadata.java @@ -0,0 +1,169 @@ +package org.opengauss.mppdbide.mock.presentation; + +import java.sql.ResultSetMetaData; +import java.sql.SQLException; + +public class ExceptionRSMetadata implements ResultSetMetaData +{ + + @Override + public boolean isWrapperFor(Class arg0) throws SQLException + { + + return false; + } + + @Override + public T unwrap(Class arg0) throws SQLException + { + + return null; + } + + @Override + public String getCatalogName(int arg0) throws SQLException + { + + return null; + } + + @Override + public String getColumnClassName(int arg0) throws SQLException + { + + return null; + } + + @Override + public int getColumnCount() throws SQLException + { + + return 1; + } + + @Override + public int getColumnDisplaySize(int arg0) throws SQLException + { + + return 0; + } + + @Override + public String getColumnLabel(int arg0) throws SQLException + { + + return null; + } + + @Override + public String getColumnName(int arg0) throws SQLException + { + throw new SQLException(); + } + + @Override + public int getColumnType(int arg0) throws SQLException + { + + return 0; + } + + @Override + public String getColumnTypeName(int arg0) throws SQLException + { + + return null; + } + + @Override + public int getPrecision(int arg0) throws SQLException + { + + return 0; + } + + @Override + public int getScale(int arg0) throws SQLException + { + + return 0; + } + + @Override + public String getSchemaName(int arg0) throws SQLException + { + + return null; + } + + @Override + public String getTableName(int arg0) throws SQLException + { + + return null; + } + + @Override + public boolean isAutoIncrement(int arg0) throws SQLException + { + + return false; + } + + @Override + public boolean isCaseSensitive(int arg0) throws SQLException + { + + return false; + } + + @Override + public boolean isCurrency(int arg0) throws SQLException + { + + return false; + } + + @Override + public boolean isDefinitelyWritable(int arg0) throws SQLException + { + + return false; + } + + @Override + public int isNullable(int arg0) throws SQLException + { + + return 0; + } + + @Override + public boolean isReadOnly(int arg0) throws SQLException + { + + return false; + } + + @Override + public boolean isSearchable(int arg0) throws SQLException + { + + return false; + } + + @Override + public boolean isSigned(int arg0) throws SQLException + { + + return false; + } + + @Override + public boolean isWritable(int arg0) throws SQLException + { + + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionResultset.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionResultset.java new file mode 100644 index 0000000000000000000000000000000000000000..81c3e2a748c824115603bd4b7826b304564b2fb2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionResultset.java @@ -0,0 +1,1585 @@ +package org.opengauss.mppdbide.mock.presentation; + +import java.io.InputStream; +import java.io.Reader; +import java.math.BigDecimal; +import java.net.URL; +import java.sql.Array; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Date; +import java.sql.NClob; +import java.sql.Ref; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.RowId; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.SQLXML; +import java.sql.Statement; +import java.sql.Time; +import java.sql.Timestamp; +import java.util.Calendar; +import java.util.Map; + +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils.EXCEPTIONENUM; + + +public class ExceptionResultset implements ResultSet +{ + + private boolean throwExceptionCloseResultSet = false; + private boolean throwExceptionGetInt = false; + private boolean throwExceptionGetString = false; + private boolean throwExceptionGetLong= false; + private boolean throwExceptionGetBoolean = false; + private EXCEPTIONENUM resultSetNext = EXCEPTIONENUM.NO; + + private Statement statement = null; + + String sqlState = ""; + + private boolean throwExceptionGetStatement = false; + private int counter; + + String exceptionForNextOn; + + String exceptioncounter; + + public ExceptionResultset() + { + counter = 0; + } + + public void setExceptioncounter(String exceptioncounter) + { + this.exceptioncounter = exceptioncounter; + } + + public void setExceptionForNextOn(String exceptionForNextOn) + { + this.exceptionForNextOn = exceptionForNextOn; + } + + + public void setStatement(Statement statement) + { + this.statement = statement; + } + + public void setSqlState(String sqlState) + { + this.sqlState = sqlState; + } + + public void setThrowExceptionGetStatement(boolean throwExceptionGetStatement) + { + this.throwExceptionGetStatement = throwExceptionGetStatement; + } + + public void setThrowExceptionCloseResultSet(boolean throwExceptionCloseResultSet) + { + this.throwExceptionCloseResultSet = throwExceptionCloseResultSet; + } + + public void setThrowExceptionGetLong(boolean throwExceptionGetLong) { + this.throwExceptionGetLong = throwExceptionGetLong; + } + + public void setThrowExceptionGetInt(boolean throwExceptionGetInt) + { + this.throwExceptionGetInt = throwExceptionGetInt; + } + + public void setThrowExceptionGetString(boolean throwExceptionGetString) + { + this.throwExceptionGetString = throwExceptionGetString; + } + + public void setThrowExceptionGetBoolean(boolean throwExceptionGetBoolean) + { + this.throwExceptionGetBoolean = throwExceptionGetBoolean; + } + + public void setResultSetNext(EXCEPTIONENUM resultSetNext) + { + this.resultSetNext = resultSetNext; + } + + @Override + public boolean isWrapperFor(Class arg0) throws SQLException + { + + return false; + } + + @Override + public T unwrap(Class arg0) throws SQLException + { + + return null; + } + + @Override + public boolean absolute(int arg0) throws SQLException + { + + return false; + } + + @Override + public void afterLast() throws SQLException + { + + + } + + @Override + public void beforeFirst() throws SQLException + { + + + } + + @Override + public void cancelRowUpdates() throws SQLException + { + + + } + + @Override + public void clearWarnings() throws SQLException + { + + + } + + @Override + public void close() throws SQLException + { + if (throwExceptionCloseResultSet) + { + throw new SQLException(); + } + } + + @Override + public void deleteRow() throws SQLException + { + + + } + + @Override + public int findColumn(String arg0) throws SQLException + { + + return 0; + } + + @Override + public boolean first() throws SQLException + { + + return false; + } + + @Override + public Array getArray(int arg0) throws SQLException + { + + return null; + } + + @Override + public Array getArray(String arg0) throws SQLException + { + + return null; + } + + @Override + public InputStream getAsciiStream(int arg0) throws SQLException + { + + return null; + } + + @Override + public InputStream getAsciiStream(String arg0) throws SQLException + { + + return null; + } + + @Override + public BigDecimal getBigDecimal(int arg0) throws SQLException + { + + return null; + } + + @Override + public BigDecimal getBigDecimal(String arg0) throws SQLException + { + + return null; + } + + @Override + public BigDecimal getBigDecimal(int arg0, int arg1) throws SQLException + { + + return null; + } + + @Override + public BigDecimal getBigDecimal(String arg0, int arg1) throws SQLException + { + + return null; + } + + @Override + public InputStream getBinaryStream(int arg0) throws SQLException + { + + return null; + } + + @Override + public InputStream getBinaryStream(String arg0) throws SQLException + { + + return null; + } + + @Override + public Blob getBlob(int arg0) throws SQLException + { + + return null; + } + + @Override + public Blob getBlob(String arg0) throws SQLException + { + + return null; + } + + @Override + public boolean getBoolean(int arg0) throws SQLException + { + if (throwExceptionGetBoolean) + { + throw new SQLException(); + } + + return false; + } + + @Override + public boolean getBoolean(String arg0) throws SQLException + { + if (throwExceptionGetBoolean) + { + throw new SQLException(); + } + + return false; + } + + @Override + public byte getByte(int arg0) throws SQLException + { + + return 0; + } + + @Override + public byte getByte(String arg0) throws SQLException + { + + return 0; + } + + @Override + public byte[] getBytes(int arg0) throws SQLException + { + + return null; + } + + @Override + public byte[] getBytes(String arg0) throws SQLException + { + + return null; + } + + @Override + public Reader getCharacterStream(int arg0) throws SQLException + { + + return null; + } + + @Override + public Reader getCharacterStream(String arg0) throws SQLException + { + + return null; + } + + @Override + public Clob getClob(int arg0) throws SQLException + { + + return null; + } + + @Override + public Clob getClob(String arg0) throws SQLException + { + + return null; + } + + @Override + public int getConcurrency() throws SQLException + { + + return 0; + } + + @Override + public String getCursorName() throws SQLException + { + + return null; + } + + @Override + public Date getDate(int arg0) throws SQLException + { + + return null; + } + + @Override + public Date getDate(String arg0) throws SQLException + { + + return null; + } + + @Override + public Date getDate(int arg0, Calendar arg1) throws SQLException + { + + return null; + } + + @Override + public Date getDate(String arg0, Calendar arg1) throws SQLException + { + + return null; + } + + @Override + public double getDouble(int arg0) throws SQLException + { + + return 0; + } + + @Override + public double getDouble(String arg0) throws SQLException + { + + return 0; + } + + @Override + public int getFetchDirection() throws SQLException + { + + return 0; + } + + @Override + public int getFetchSize() throws SQLException + { + + return 0; + } + + @Override + public float getFloat(int arg0) throws SQLException + { + + return 0; + } + + @Override + public float getFloat(String arg0) throws SQLException + { + + return 0; + } + + @Override + public int getHoldability() throws SQLException + { + + return 0; + } + + @Override + public int getInt(int arg0) throws SQLException + { + if (throwExceptionGetInt) + { + if(null != sqlState && sqlState.length() > 0) + { + throw new SQLException(sqlState, sqlState); + } + else + { + throw new SQLException(); + } + } + + + return 0; + } + + @Override + public int getInt(String arg0) throws SQLException + { + if (throwExceptionGetInt) + { + if(null != sqlState && sqlState.length() > 0) + { + throw new SQLException(sqlState, sqlState); + } + else + { + throw new SQLException(); + } + } + + return 0; + } + + @Override + public long getLong(int arg0) throws SQLException + { + if (throwExceptionGetLong) + { + if(null != sqlState && sqlState.length() > 0) + { + throw new SQLException(sqlState, sqlState); + } + else + { + throw new SQLException(); + } + } + + return 0; + } + + @Override + public long getLong(String arg0) throws SQLException + { + if (throwExceptionGetLong) + { + if(null != sqlState && sqlState.length() > 0) + { + throw new SQLException(sqlState, sqlState); + } + else + { + throw new SQLException(); + } + } + return 0; + } + + @Override + public ResultSetMetaData getMetaData() throws SQLException + { + + return new ExceptionRSMetadata(); + } + + @Override + public Reader getNCharacterStream(int arg0) throws SQLException + { + + return null; + } + + @Override + public Reader getNCharacterStream(String arg0) throws SQLException + { + + return null; + } + + @Override + public NClob getNClob(int arg0) throws SQLException + { + + return null; + } + + @Override + public NClob getNClob(String arg0) throws SQLException + { + + return null; + } + + @Override + public String getNString(int arg0) throws SQLException + { + + return null; + } + + @Override + public String getNString(String arg0) throws SQLException + { + + return null; + } + + @Override + public Object getObject(int arg0) throws SQLException + { + + return null; + } + + @Override + public Object getObject(String arg0) throws SQLException + { + + return null; + } + + @Override + public Object getObject(int arg0, Map> arg1) + throws SQLException + { + + return null; + } + + @Override + public Object getObject(String arg0, Map> arg1) + throws SQLException + { + + return null; + } + + @Override + public Ref getRef(int arg0) throws SQLException + { + + return null; + } + + @Override + public Ref getRef(String arg0) throws SQLException + { + + return null; + } + + @Override + public int getRow() throws SQLException + { + + return 0; + } + + @Override + public RowId getRowId(int arg0) throws SQLException + { + + return null; + } + + @Override + public RowId getRowId(String arg0) throws SQLException + { + + return null; + } + + @Override + public SQLXML getSQLXML(int arg0) throws SQLException + { + + return null; + } + + @Override + public SQLXML getSQLXML(String arg0) throws SQLException + { + + return null; + } + + @Override + public short getShort(int arg0) throws SQLException + { + + return 0; + } + + @Override + public short getShort(String arg0) throws SQLException + { + + return 0; + } + + @Override + public Statement getStatement() throws SQLException + { + if(throwExceptionGetStatement) + { + throwExceptionGetStatement = false; + if(null != sqlState && sqlState.length() > 0) + { + throw new SQLException(sqlState, sqlState); + } + else + { + throw new SQLException(); + } + } + + return statement; + } + + @Override + public String getString(int arg0) throws SQLException + { + if (throwExceptionGetString) + { + throw new SQLException(); + } + + return null; + } + + @Override + public String getString(String arg0) throws SQLException + { + if (throwExceptionGetString) + { + throw new SQLException(); + } + + return "(Dummy )"; + } + + @Override + public Time getTime(int arg0) throws SQLException + { + + return null; + } + + @Override + public Time getTime(String arg0) throws SQLException + { + + return null; + } + + @Override + public Time getTime(int arg0, Calendar arg1) throws SQLException + { + + return null; + } + + @Override + public Time getTime(String arg0, Calendar arg1) throws SQLException + { + + return null; + } + + @Override + public Timestamp getTimestamp(int arg0) throws SQLException + { + + return null; + } + + @Override + public Timestamp getTimestamp(String arg0) throws SQLException + { + + return null; + } + + @Override + public Timestamp getTimestamp(int arg0, Calendar arg1) throws SQLException + { + + return null; + } + + @Override + public Timestamp getTimestamp(String arg0, Calendar arg1) + throws SQLException + { + + return null; + } + + @Override + public int getType() throws SQLException + { + + return 0; + } + + @Override + public URL getURL(int arg0) throws SQLException + { + + return null; + } + + @Override + public URL getURL(String arg0) throws SQLException + { + + return null; + } + + @Override + public InputStream getUnicodeStream(int arg0) throws SQLException + { + + return null; + } + + @Override + public InputStream getUnicodeStream(String arg0) throws SQLException + { + + return null; + } + + @Override + public SQLWarning getWarnings() throws SQLException + { + + return null; + } + + @Override + public void insertRow() throws SQLException + { + + + } + + @Override + public boolean isAfterLast() throws SQLException + { + throw new SQLException(); + } + + @Override + public boolean isBeforeFirst() throws SQLException + { + + return false; + } + + @Override + public boolean isClosed() throws SQLException + { + + return false; + } + + @Override + public boolean isFirst() throws SQLException + { + + return false; + } + + @Override + public boolean isLast() throws SQLException + { + + return false; + } + + @Override + public boolean last() throws SQLException + { + + return false; + } + + @Override + public void moveToCurrentRow() throws SQLException + { + + + } + + @Override + public void moveToInsertRow() throws SQLException + { + + + } + + @Override + public boolean next() throws SQLException + { + if (EXCEPTIONENUM.EXCEPTION.equals(resultSetNext)) + { + counter++; + if(exceptionForNextOn != null && exceptionForNextOn.equals("loadview")) + { + if("SELECT c.oid, n.oid as nspoid, n.nspname AS schemaname, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner FROM (pg_class c LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace))) WHERE (c.relkind = 'v'::\"char\" or c.relkind = 'm'::\"char\") and has_table_privilege(c.oid,'SELECT') ".equals(exceptioncounter)) + if(null != sqlState && sqlState.length() > 0) + { + throw new SQLException(sqlState, sqlState); + } + else + { + throw new SQLException(); + } + } + else + { + if(null != sqlState && sqlState.length() > 0) + { + throw new SQLException(sqlState, sqlState); + } + else + { + throw new SQLException(); + } + } + + } + else if(EXCEPTIONENUM.YES.equals(resultSetNext)) + { + return true; + } + + return false; + } + + @Override + public boolean previous() throws SQLException + { + + return false; + } + + @Override + public void refreshRow() throws SQLException + { + + + } + + @Override + public boolean relative(int arg0) throws SQLException + { + + return false; + } + + @Override + public boolean rowDeleted() throws SQLException + { + + return false; + } + + @Override + public boolean rowInserted() throws SQLException + { + + return false; + } + + @Override + public boolean rowUpdated() throws SQLException + { + + return false; + } + + @Override + public void setFetchDirection(int arg0) throws SQLException + { + + + } + + @Override + public void setFetchSize(int arg0) throws SQLException + { + + + } + + @Override + public void updateArray(int arg0, Array arg1) throws SQLException + { + + + } + + @Override + public void updateArray(String arg0, Array arg1) throws SQLException + { + + + } + + @Override + public void updateAsciiStream(int arg0, InputStream arg1) + throws SQLException + { + + + } + + @Override + public void updateAsciiStream(String arg0, InputStream arg1) + throws SQLException + { + + + } + + @Override + public void updateAsciiStream(int arg0, InputStream arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void updateAsciiStream(String arg0, InputStream arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void updateAsciiStream(int arg0, InputStream arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateAsciiStream(String arg0, InputStream arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateBigDecimal(int arg0, BigDecimal arg1) throws SQLException + { + + + } + + @Override + public void updateBigDecimal(String arg0, BigDecimal arg1) + throws SQLException + { + + + } + + @Override + public void updateBinaryStream(int arg0, InputStream arg1) + throws SQLException + { + + + } + + @Override + public void updateBinaryStream(String arg0, InputStream arg1) + throws SQLException + { + + + } + + @Override + public void updateBinaryStream(int arg0, InputStream arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void updateBinaryStream(String arg0, InputStream arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void updateBinaryStream(int arg0, InputStream arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateBinaryStream(String arg0, InputStream arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateBlob(int arg0, Blob arg1) throws SQLException + { + + + } + + @Override + public void updateBlob(String arg0, Blob arg1) throws SQLException + { + + + } + + @Override + public void updateBlob(int arg0, InputStream arg1) throws SQLException + { + + + } + + @Override + public void updateBlob(String arg0, InputStream arg1) throws SQLException + { + + + } + + @Override + public void updateBlob(int arg0, InputStream arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateBlob(String arg0, InputStream arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateBoolean(int arg0, boolean arg1) throws SQLException + { + + + } + + @Override + public void updateBoolean(String arg0, boolean arg1) throws SQLException + { + + + } + + @Override + public void updateByte(int arg0, byte arg1) throws SQLException + { + + + } + + @Override + public void updateByte(String arg0, byte arg1) throws SQLException + { + + + } + + @Override + public void updateBytes(int arg0, byte[] arg1) throws SQLException + { + + + } + + @Override + public void updateBytes(String arg0, byte[] arg1) throws SQLException + { + + + } + + @Override + public void updateCharacterStream(int arg0, Reader arg1) + throws SQLException + { + + + } + + @Override + public void updateCharacterStream(String arg0, Reader arg1) + throws SQLException + { + + + } + + @Override + public void updateCharacterStream(int arg0, Reader arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void updateCharacterStream(String arg0, Reader arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void updateCharacterStream(int arg0, Reader arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateCharacterStream(String arg0, Reader arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateClob(int arg0, Clob arg1) throws SQLException + { + + + } + + @Override + public void updateClob(String arg0, Clob arg1) throws SQLException + { + + + } + + @Override + public void updateClob(int arg0, Reader arg1) throws SQLException + { + + + } + + @Override + public void updateClob(String arg0, Reader arg1) throws SQLException + { + + + } + + @Override + public void updateClob(int arg0, Reader arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateClob(String arg0, Reader arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateDate(int arg0, Date arg1) throws SQLException + { + + + } + + @Override + public void updateDate(String arg0, Date arg1) throws SQLException + { + + + } + + @Override + public void updateDouble(int arg0, double arg1) throws SQLException + { + + + } + + @Override + public void updateDouble(String arg0, double arg1) throws SQLException + { + + + } + + @Override + public void updateFloat(int arg0, float arg1) throws SQLException + { + + + } + + @Override + public void updateFloat(String arg0, float arg1) throws SQLException + { + + + } + + @Override + public void updateInt(int arg0, int arg1) throws SQLException + { + + + } + + @Override + public void updateInt(String arg0, int arg1) throws SQLException + { + + + } + + @Override + public void updateLong(int arg0, long arg1) throws SQLException + { + + + } + + @Override + public void updateLong(String arg0, long arg1) throws SQLException + { + + + } + + @Override + public void updateNCharacterStream(int arg0, Reader arg1) + throws SQLException + { + + + } + + @Override + public void updateNCharacterStream(String arg0, Reader arg1) + throws SQLException + { + + + } + + @Override + public void updateNCharacterStream(int arg0, Reader arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateNCharacterStream(String arg0, Reader arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateNClob(int arg0, NClob arg1) throws SQLException + { + + + } + + @Override + public void updateNClob(String arg0, NClob arg1) throws SQLException + { + + + } + + @Override + public void updateNClob(int arg0, Reader arg1) throws SQLException + { + + + } + + @Override + public void updateNClob(String arg0, Reader arg1) throws SQLException + { + + + } + + @Override + public void updateNClob(int arg0, Reader arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateNClob(String arg0, Reader arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateNString(int arg0, String arg1) throws SQLException + { + + + } + + @Override + public void updateNString(String arg0, String arg1) throws SQLException + { + + + } + + @Override + public void updateNull(int arg0) throws SQLException + { + + + } + + @Override + public void updateNull(String arg0) throws SQLException + { + + + } + + @Override + public void updateObject(int arg0, Object arg1) throws SQLException + { + + + } + + @Override + public void updateObject(String arg0, Object arg1) throws SQLException + { + + + } + + @Override + public void updateObject(int arg0, Object arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void updateObject(String arg0, Object arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void updateRef(int arg0, Ref arg1) throws SQLException + { + + + } + + @Override + public void updateRef(String arg0, Ref arg1) throws SQLException + { + + + } + + @Override + public void updateRow() throws SQLException + { + + + } + + @Override + public void updateRowId(int arg0, RowId arg1) throws SQLException + { + + + } + + @Override + public void updateRowId(String arg0, RowId arg1) throws SQLException + { + + + } + + @Override + public void updateSQLXML(int arg0, SQLXML arg1) throws SQLException + { + + + } + + @Override + public void updateSQLXML(String arg0, SQLXML arg1) throws SQLException + { + + + } + + @Override + public void updateShort(int arg0, short arg1) throws SQLException + { + + + } + + @Override + public void updateShort(String arg0, short arg1) throws SQLException + { + + + } + + @Override + public void updateString(int arg0, String arg1) throws SQLException + { + + + } + + @Override + public void updateString(String arg0, String arg1) throws SQLException + { + + + } + + @Override + public void updateTime(int arg0, Time arg1) throws SQLException + { + + + } + + @Override + public void updateTime(String arg0, Time arg1) throws SQLException + { + + + } + + @Override + public void updateTimestamp(int arg0, Timestamp arg1) throws SQLException + { + + + } + + @Override + public void updateTimestamp(String arg0, Timestamp arg1) + throws SQLException + { + + + } + + @Override + public boolean wasNull() throws SQLException + { + + return false; + } + + @Override + public T getObject(int columnIndex, Class type) throws SQLException { + + return null; + } + + @Override + public T getObject(String columnLabel, Class type) + throws SQLException { + + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionResultsetHelper.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionResultsetHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..87bbccd7bb49fd7f4acfadd2335b9f400a25859e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionResultsetHelper.java @@ -0,0 +1,1477 @@ +package org.opengauss.mppdbide.mock.presentation; + +import java.io.InputStream; +import java.io.Reader; +import java.math.BigDecimal; +import java.net.URL; +import java.sql.Array; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Date; +import java.sql.NClob; +import java.sql.Ref; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.RowId; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.SQLXML; +import java.sql.Statement; +import java.sql.Time; +import java.sql.Timestamp; +import java.util.Calendar; +import java.util.Map; + +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtilsHelper.EXCEPTIONENUM; + +public class ExceptionResultsetHelper implements ResultSet +{ + + private boolean throwExceptionCloseResultSet = false; + private boolean throwExceptionGetInt = false; + private boolean throwExceptionGetLong = false; + private boolean throwExceptionGetString = false; + private boolean throwExceptionGetBoolean = false; + private EXCEPTIONENUM resultSetNext = EXCEPTIONENUM.NO; + + public void setThrowExceptionCloseResultSet(boolean throwExceptionCloseResultSet) + { + this.throwExceptionCloseResultSet = throwExceptionCloseResultSet; + } + + public void setThrowExceptionGetInt(boolean throwExceptionGetInt) + { + this.throwExceptionGetInt = throwExceptionGetInt; + } + + public void setThrowExceptionGetLong(boolean throwExceptionGetLong) { + this.throwExceptionGetLong = throwExceptionGetLong; + } + + public void setThrowExceptionGetString(boolean throwExceptionGetString) + { + this.throwExceptionGetString = throwExceptionGetString; + } + + public void setThrowExceptionGetBoolean(boolean throwExceptionGetBoolean) + { + this.throwExceptionGetBoolean = throwExceptionGetBoolean; + } + + public void setResultSetNext(EXCEPTIONENUM resultSetNext) + { + this.resultSetNext = resultSetNext; + } + + @Override + public boolean isWrapperFor(Class arg0) throws SQLException + { + + return false; + } + + @Override + public T unwrap(Class arg0) throws SQLException + { + + return null; + } + + @Override + public boolean absolute(int arg0) throws SQLException + { + + return false; + } + + @Override + public void afterLast() throws SQLException + { + + + } + + @Override + public void beforeFirst() throws SQLException + { + + + } + + @Override + public void cancelRowUpdates() throws SQLException + { + + + } + + @Override + public void clearWarnings() throws SQLException + { + + + } + + @Override + public void close() throws SQLException + { + if (throwExceptionCloseResultSet) + { + throw new SQLException(); + } + } + + @Override + public void deleteRow() throws SQLException + { + + + } + + @Override + public int findColumn(String arg0) throws SQLException + { + + return 0; + } + + @Override + public boolean first() throws SQLException + { + + return false; + } + + @Override + public Array getArray(int arg0) throws SQLException + { + + return null; + } + + @Override + public Array getArray(String arg0) throws SQLException + { + + return null; + } + + @Override + public InputStream getAsciiStream(int arg0) throws SQLException + { + + return null; + } + + @Override + public InputStream getAsciiStream(String arg0) throws SQLException + { + + return null; + } + + @Override + public BigDecimal getBigDecimal(int arg0) throws SQLException + { + + return null; + } + + @Override + public BigDecimal getBigDecimal(String arg0) throws SQLException + { + + return null; + } + + @Override + public BigDecimal getBigDecimal(int arg0, int arg1) throws SQLException + { + + return null; + } + + @Override + public BigDecimal getBigDecimal(String arg0, int arg1) throws SQLException + { + + return null; + } + + @Override + public InputStream getBinaryStream(int arg0) throws SQLException + { + + return null; + } + + @Override + public InputStream getBinaryStream(String arg0) throws SQLException + { + + return null; + } + + @Override + public Blob getBlob(int arg0) throws SQLException + { + + return null; + } + + @Override + public Blob getBlob(String arg0) throws SQLException + { + + return null; + } + + @Override + public boolean getBoolean(int arg0) throws SQLException + { + if (throwExceptionGetBoolean) + { + throw new SQLException(); + } + + return false; + } + + @Override + public boolean getBoolean(String arg0) throws SQLException + { + if (throwExceptionGetBoolean) + { + throw new SQLException(); + } + + return false; + } + + @Override + public byte getByte(int arg0) throws SQLException + { + + return 0; + } + + @Override + public byte getByte(String arg0) throws SQLException + { + + return 0; + } + + @Override + public byte[] getBytes(int arg0) throws SQLException + { + + return null; + } + + @Override + public byte[] getBytes(String arg0) throws SQLException + { + + return null; + } + + @Override + public Reader getCharacterStream(int arg0) throws SQLException + { + + return null; + } + + @Override + public Reader getCharacterStream(String arg0) throws SQLException + { + + return null; + } + + @Override + public Clob getClob(int arg0) throws SQLException + { + + return null; + } + + @Override + public Clob getClob(String arg0) throws SQLException + { + + return null; + } + + @Override + public int getConcurrency() throws SQLException + { + + return 0; + } + + @Override + public String getCursorName() throws SQLException + { + + return null; + } + + @Override + public Date getDate(int arg0) throws SQLException + { + + return null; + } + + @Override + public Date getDate(String arg0) throws SQLException + { + + return null; + } + + @Override + public Date getDate(int arg0, Calendar arg1) throws SQLException + { + + return null; + } + + @Override + public Date getDate(String arg0, Calendar arg1) throws SQLException + { + + return null; + } + + @Override + public double getDouble(int arg0) throws SQLException + { + + return 0; + } + + @Override + public double getDouble(String arg0) throws SQLException + { + + return 0; + } + + @Override + public int getFetchDirection() throws SQLException + { + + return 0; + } + + @Override + public int getFetchSize() throws SQLException + { + + return 0; + } + + @Override + public float getFloat(int arg0) throws SQLException + { + + return 0; + } + + @Override + public float getFloat(String arg0) throws SQLException + { + + return 0; + } + + @Override + public int getHoldability() throws SQLException + { + + return 0; + } + + @Override + public int getInt(int arg0) throws SQLException + { + if (throwExceptionGetInt) + { + throw new SQLException(); + } + + + return 0; + } + + @Override + public int getInt(String arg0) throws SQLException + { + if (throwExceptionGetInt) + { + throw new SQLException(); + } + + return 0; + } + + @Override + public long getLong(int arg0) throws SQLException + { + if (throwExceptionGetLong) + { + throw new SQLException(); + } + + return 0; + } + + @Override + public long getLong(String arg0) throws SQLException + { + if (throwExceptionGetLong) + { + throw new SQLException(); + } + return 0; + } + + @Override + public ResultSetMetaData getMetaData() throws SQLException + { + + return new ExceptionRSMetadata(); + } + + @Override + public Reader getNCharacterStream(int arg0) throws SQLException + { + + return null; + } + + @Override + public Reader getNCharacterStream(String arg0) throws SQLException + { + + return null; + } + + @Override + public NClob getNClob(int arg0) throws SQLException + { + + return null; + } + + @Override + public NClob getNClob(String arg0) throws SQLException + { + + return null; + } + + @Override + public String getNString(int arg0) throws SQLException + { + + return null; + } + + @Override + public String getNString(String arg0) throws SQLException + { + + return null; + } + + @Override + public Object getObject(int arg0) throws SQLException + { + + return null; + } + + @Override + public Object getObject(String arg0) throws SQLException + { + + return null; + } + + @Override + public Object getObject(int arg0, Map> arg1) + throws SQLException + { + + return null; + } + + @Override + public Object getObject(String arg0, Map> arg1) + throws SQLException + { + + return null; + } + + @Override + public Ref getRef(int arg0) throws SQLException + { + + return null; + } + + @Override + public Ref getRef(String arg0) throws SQLException + { + + return null; + } + + @Override + public int getRow() throws SQLException + { + + return 0; + } + + @Override + public RowId getRowId(int arg0) throws SQLException + { + + return null; + } + + @Override + public RowId getRowId(String arg0) throws SQLException + { + + return null; + } + + @Override + public SQLXML getSQLXML(int arg0) throws SQLException + { + + return null; + } + + @Override + public SQLXML getSQLXML(String arg0) throws SQLException + { + + return null; + } + + @Override + public short getShort(int arg0) throws SQLException + { + + return 0; + } + + @Override + public short getShort(String arg0) throws SQLException + { + + return 0; + } + + @Override + public Statement getStatement() throws SQLException + { + + return null; + } + + @Override + public String getString(int arg0) throws SQLException + { + if (throwExceptionGetString) + { + throw new SQLException(); + } + + return null; + } + + @Override + public String getString(String arg0) throws SQLException + { + if (throwExceptionGetString) + { + throw new SQLException(); + } + + return "(Dummy )"; + } + + @Override + public Time getTime(int arg0) throws SQLException + { + + return null; + } + + @Override + public Time getTime(String arg0) throws SQLException + { + + return null; + } + + @Override + public Time getTime(int arg0, Calendar arg1) throws SQLException + { + + return null; + } + + @Override + public Time getTime(String arg0, Calendar arg1) throws SQLException + { + + return null; + } + + @Override + public Timestamp getTimestamp(int arg0) throws SQLException + { + + return null; + } + + @Override + public Timestamp getTimestamp(String arg0) throws SQLException + { + + return null; + } + + @Override + public Timestamp getTimestamp(int arg0, Calendar arg1) throws SQLException + { + + return null; + } + + @Override + public Timestamp getTimestamp(String arg0, Calendar arg1) + throws SQLException + { + + return null; + } + + @Override + public int getType() throws SQLException + { + + return 0; + } + + @Override + public URL getURL(int arg0) throws SQLException + { + + return null; + } + + @Override + public URL getURL(String arg0) throws SQLException + { + + return null; + } + + @Override + public InputStream getUnicodeStream(int arg0) throws SQLException + { + + return null; + } + + @Override + public InputStream getUnicodeStream(String arg0) throws SQLException + { + + return null; + } + + @Override + public SQLWarning getWarnings() throws SQLException + { + + return null; + } + + @Override + public void insertRow() throws SQLException + { + + + } + + @Override + public boolean isAfterLast() throws SQLException + { + throw new SQLException(); + } + + @Override + public boolean isBeforeFirst() throws SQLException + { + + return false; + } + + @Override + public boolean isClosed() throws SQLException + { + + return false; + } + + @Override + public boolean isFirst() throws SQLException + { + + return false; + } + + @Override + public boolean isLast() throws SQLException + { + + return false; + } + + @Override + public boolean last() throws SQLException + { + + return false; + } + + @Override + public void moveToCurrentRow() throws SQLException + { + + + } + + @Override + public void moveToInsertRow() throws SQLException + { + + + } + + @Override + public boolean next() throws SQLException + { + if (EXCEPTIONENUM.EXCEPTION.equals(resultSetNext)) + { + throw new SQLException(); + } + else if(EXCEPTIONENUM.YES.equals(resultSetNext)) + { + return true; + } + + return false; + } + + @Override + public boolean previous() throws SQLException + { + + return false; + } + + @Override + public void refreshRow() throws SQLException + { + + + } + + @Override + public boolean relative(int arg0) throws SQLException + { + + return false; + } + + @Override + public boolean rowDeleted() throws SQLException + { + + return false; + } + + @Override + public boolean rowInserted() throws SQLException + { + + return false; + } + + @Override + public boolean rowUpdated() throws SQLException + { + + return false; + } + + @Override + public void setFetchDirection(int arg0) throws SQLException + { + + + } + + @Override + public void setFetchSize(int arg0) throws SQLException + { + + + } + + @Override + public void updateArray(int arg0, Array arg1) throws SQLException + { + + + } + + @Override + public void updateArray(String arg0, Array arg1) throws SQLException + { + + + } + + @Override + public void updateAsciiStream(int arg0, InputStream arg1) + throws SQLException + { + + + } + + @Override + public void updateAsciiStream(String arg0, InputStream arg1) + throws SQLException + { + + + } + + @Override + public void updateAsciiStream(int arg0, InputStream arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void updateAsciiStream(String arg0, InputStream arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void updateAsciiStream(int arg0, InputStream arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateAsciiStream(String arg0, InputStream arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateBigDecimal(int arg0, BigDecimal arg1) throws SQLException + { + + + } + + @Override + public void updateBigDecimal(String arg0, BigDecimal arg1) + throws SQLException + { + + + } + + @Override + public void updateBinaryStream(int arg0, InputStream arg1) + throws SQLException + { + + + } + + @Override + public void updateBinaryStream(String arg0, InputStream arg1) + throws SQLException + { + + + } + + @Override + public void updateBinaryStream(int arg0, InputStream arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void updateBinaryStream(String arg0, InputStream arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void updateBinaryStream(int arg0, InputStream arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateBinaryStream(String arg0, InputStream arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateBlob(int arg0, Blob arg1) throws SQLException + { + + + } + + @Override + public void updateBlob(String arg0, Blob arg1) throws SQLException + { + + + } + + @Override + public void updateBlob(int arg0, InputStream arg1) throws SQLException + { + + + } + + @Override + public void updateBlob(String arg0, InputStream arg1) throws SQLException + { + + + } + + @Override + public void updateBlob(int arg0, InputStream arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateBlob(String arg0, InputStream arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateBoolean(int arg0, boolean arg1) throws SQLException + { + + + } + + @Override + public void updateBoolean(String arg0, boolean arg1) throws SQLException + { + + + } + + @Override + public void updateByte(int arg0, byte arg1) throws SQLException + { + + + } + + @Override + public void updateByte(String arg0, byte arg1) throws SQLException + { + + + } + + @Override + public void updateBytes(int arg0, byte[] arg1) throws SQLException + { + + + } + + @Override + public void updateBytes(String arg0, byte[] arg1) throws SQLException + { + + + } + + @Override + public void updateCharacterStream(int arg0, Reader arg1) + throws SQLException + { + + + } + + @Override + public void updateCharacterStream(String arg0, Reader arg1) + throws SQLException + { + + + } + + @Override + public void updateCharacterStream(int arg0, Reader arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void updateCharacterStream(String arg0, Reader arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void updateCharacterStream(int arg0, Reader arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateCharacterStream(String arg0, Reader arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateClob(int arg0, Clob arg1) throws SQLException + { + + + } + + @Override + public void updateClob(String arg0, Clob arg1) throws SQLException + { + + + } + + @Override + public void updateClob(int arg0, Reader arg1) throws SQLException + { + + + } + + @Override + public void updateClob(String arg0, Reader arg1) throws SQLException + { + + + } + + @Override + public void updateClob(int arg0, Reader arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateClob(String arg0, Reader arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateDate(int arg0, Date arg1) throws SQLException + { + + + } + + @Override + public void updateDate(String arg0, Date arg1) throws SQLException + { + + + } + + @Override + public void updateDouble(int arg0, double arg1) throws SQLException + { + + + } + + @Override + public void updateDouble(String arg0, double arg1) throws SQLException + { + + + } + + @Override + public void updateFloat(int arg0, float arg1) throws SQLException + { + + + } + + @Override + public void updateFloat(String arg0, float arg1) throws SQLException + { + + + } + + @Override + public void updateInt(int arg0, int arg1) throws SQLException + { + + + } + + @Override + public void updateInt(String arg0, int arg1) throws SQLException + { + + + } + + @Override + public void updateLong(int arg0, long arg1) throws SQLException + { + + + } + + @Override + public void updateLong(String arg0, long arg1) throws SQLException + { + + + } + + @Override + public void updateNCharacterStream(int arg0, Reader arg1) + throws SQLException + { + + + } + + @Override + public void updateNCharacterStream(String arg0, Reader arg1) + throws SQLException + { + + + } + + @Override + public void updateNCharacterStream(int arg0, Reader arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateNCharacterStream(String arg0, Reader arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateNClob(int arg0, NClob arg1) throws SQLException + { + + + } + + @Override + public void updateNClob(String arg0, NClob arg1) throws SQLException + { + + + } + + @Override + public void updateNClob(int arg0, Reader arg1) throws SQLException + { + + + } + + @Override + public void updateNClob(String arg0, Reader arg1) throws SQLException + { + + + } + + @Override + public void updateNClob(int arg0, Reader arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateNClob(String arg0, Reader arg1, long arg2) + throws SQLException + { + + + } + + @Override + public void updateNString(int arg0, String arg1) throws SQLException + { + + + } + + @Override + public void updateNString(String arg0, String arg1) throws SQLException + { + + + } + + @Override + public void updateNull(int arg0) throws SQLException + { + + + } + + @Override + public void updateNull(String arg0) throws SQLException + { + + + } + + @Override + public void updateObject(int arg0, Object arg1) throws SQLException + { + + + } + + @Override + public void updateObject(String arg0, Object arg1) throws SQLException + { + + + } + + @Override + public void updateObject(int arg0, Object arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void updateObject(String arg0, Object arg1, int arg2) + throws SQLException + { + + + } + + @Override + public void updateRef(int arg0, Ref arg1) throws SQLException + { + + + } + + @Override + public void updateRef(String arg0, Ref arg1) throws SQLException + { + + + } + + @Override + public void updateRow() throws SQLException + { + + + } + + @Override + public void updateRowId(int arg0, RowId arg1) throws SQLException + { + + + } + + @Override + public void updateRowId(String arg0, RowId arg1) throws SQLException + { + + + } + + @Override + public void updateSQLXML(int arg0, SQLXML arg1) throws SQLException + { + + + } + + @Override + public void updateSQLXML(String arg0, SQLXML arg1) throws SQLException + { + + + } + + @Override + public void updateShort(int arg0, short arg1) throws SQLException + { + + + } + + @Override + public void updateShort(String arg0, short arg1) throws SQLException + { + + + } + + @Override + public void updateString(int arg0, String arg1) throws SQLException + { + + + } + + @Override + public void updateString(String arg0, String arg1) throws SQLException + { + + + } + + @Override + public void updateTime(int arg0, Time arg1) throws SQLException + { + + + } + + @Override + public void updateTime(String arg0, Time arg1) throws SQLException + { + + + } + + @Override + public void updateTimestamp(int arg0, Timestamp arg1) throws SQLException + { + + + } + + @Override + public void updateTimestamp(String arg0, Timestamp arg1) + throws SQLException + { + + + } + + @Override + public boolean wasNull() throws SQLException + { + + return false; + } + + @Override + public T getObject(int arg0, Class arg1) throws SQLException { + + return null; + } + + @Override + public T getObject(String arg0, Class arg1) throws SQLException { + + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionStatement.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionStatement.java new file mode 100644 index 0000000000000000000000000000000000000000..2696114b8cea50c79ff139b1ca1134875cbd647b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ExceptionStatement.java @@ -0,0 +1,461 @@ +package org.opengauss.mppdbide.mock.presentation; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.Statement; + +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils.EXCEPTIONENUM; + + +public class ExceptionStatement implements Statement +{ + private boolean stmtCloseSQLExceptionNeede = false; + + private boolean needExceptionResultset = false; + + private boolean throwoutofmemerror = false; + + private boolean throwExceptionNext = false; + + private SQLException sqlException = null; + + private boolean throwExecuteBatchSQLException = false; + + Connection connection = null; + + private boolean throwExceptionGetStatement = false; + + private boolean throwExceptionAddBatch = false; + + private boolean throwIndexOutOfBoundEx = false; + + private boolean throwExceptionCloseResultSet = false; + + private boolean throwIndexoutOfBondException=false; + + private ExceptionResultset exceptionResultset = null; + + public void setThrowIndexOutOfBoundEx(boolean throwIndexOutOfBoundEx) + { + this.throwIndexOutOfBoundEx = throwIndexOutOfBoundEx; + } + + public void setThrowExceptionAddBatch(boolean throwExceptionAddBatch) + { + this.throwExceptionAddBatch = throwExceptionAddBatch; + } + + public void setThrowIndexoutOfBondException(boolean throwIndexoutOfBondException) { + this.throwIndexoutOfBondException = throwIndexoutOfBondException; + } + + public void setThrowExceptionGetStatement(boolean throwExceptionGetStatement) + { + this.throwExceptionGetStatement = throwExceptionGetStatement; + } + + public void setThrowExecuteBatchSQLException(boolean throwExecuteBatchSQLException) + { + this.throwExecuteBatchSQLException = throwExecuteBatchSQLException; + } + + public void setThrowExceptionCloseResultSet(boolean throwExceptionCloseResultSet) + { + this.throwExceptionCloseResultSet = throwExceptionCloseResultSet; + } + + public void setConnection(Connection connection) + { + this.connection = connection; + } + + public void setSqlException(SQLException sqlException) + { + this.sqlException = sqlException; + } + + public void setThrowExceptionNext(boolean throwExceptionNext) + { + this.throwExceptionNext = throwExceptionNext; + } + + public void setThrowoutofmemerror(boolean throwoutofmemerror) + { + this.throwoutofmemerror = throwoutofmemerror; + } + + public void setNeedExceptionResultset(boolean needExceptionResultset) + { + this.needExceptionResultset = needExceptionResultset; + } + + public void setStmtCloseSQLExceptionNeede(boolean stmtCloseSQLExceptionNeede) + { + this.stmtCloseSQLExceptionNeede = stmtCloseSQLExceptionNeede; + } + + @Override + public boolean isWrapperFor(Class arg0) throws SQLException + { + + return false; + } + + @Override + public T unwrap(Class arg0) throws SQLException + { + + return null; + } + + @Override + public void addBatch(String arg0) throws SQLException + { + if(throwExceptionAddBatch) + { + throw sqlException; + } + + if(throwIndexOutOfBoundEx) + { + throw new IndexOutOfBoundsException(); + } + + } + + @Override + public void cancel() throws SQLException + { + throw new SQLException(); + + } + + @Override + public void clearBatch() throws SQLException + { + + + } + + @Override + public void clearWarnings() throws SQLException + { + throw new SQLException(); + + } + + @Override + public void close() throws SQLException + { + if (stmtCloseSQLExceptionNeede) + { + throw new SQLException(); + } + } + + @Override + public boolean execute(String arg0) throws SQLException, OutOfMemoryError + { + if (throwoutofmemerror) + { + throw new OutOfMemoryError(); + } + + if (needExceptionResultset) + { + if(null == exceptionResultset) + { + exceptionResultset = new ExceptionResultset(); + exceptionResultset.setStatement(this); + } + } + + if (throwExceptionCloseResultSet && exceptionResultset != null) + { + exceptionResultset.setThrowExceptionCloseResultSet(true); + } + return true; + } + + @Override + public boolean execute(String arg0, int arg1) throws SQLException + { + + return false; + } + + @Override + public boolean execute(String arg0, int[] arg1) throws SQLException + { + + return false; + } + + @Override + public boolean execute(String arg0, String[] arg1) throws SQLException + { + + return false; + } + + @Override + public int[] executeBatch() throws SQLException + { + if(throwExecuteBatchSQLException) + { + throw sqlException; + } + return new int[1]; + } + + @Override + public ResultSet executeQuery(String arg0) throws IndexOutOfBoundsException + { + if(throwIndexoutOfBondException){ + throw new IndexOutOfBoundsException(); + } + return null; + } + + @Override + public int executeUpdate(String arg0) throws SQLException + { + + return 0; + } + + @Override + public int executeUpdate(String arg0, int arg1) throws SQLException + { + + return 0; + } + + @Override + public int executeUpdate(String arg0, int[] arg1) throws SQLException + { + + return 0; + } + + @Override + public int executeUpdate(String arg0, String[] arg1) throws SQLException + { + + return 0; + } + + @Override + public Connection getConnection() throws SQLException + { + + return connection; + } + + @Override + public int getFetchDirection() throws SQLException + { + + return 0; + } + + @Override + public int getFetchSize() throws SQLException + { + + return 0; + } + + @Override + public ResultSet getGeneratedKeys() throws SQLException + { + + return null; + } + + @Override + public int getMaxFieldSize() throws SQLException + { + + return 0; + } + + @Override + public int getMaxRows() throws SQLException + { + + return 0; + } + + @Override + public boolean getMoreResults() throws SQLException + { + + return false; + } + + @Override + public boolean getMoreResults(int arg0) throws SQLException + { + + return false; + } + + @Override + public int getQueryTimeout() throws SQLException + { + + return 0; + } + + @Override + public ResultSet getResultSet() throws SQLException + { + if (needExceptionResultset) + { + + if(null == exceptionResultset) + { + exceptionResultset = new ExceptionResultset(); + exceptionResultset.setStatement(this); + } + + + if(throwExceptionGetStatement) + { + exceptionResultset.setThrowExceptionGetStatement(true); + } + + if (throwExceptionNext) + { + exceptionResultset.setResultSetNext(EXCEPTIONENUM.EXCEPTION); + } + else + { + exceptionResultset.setResultSetNext(EXCEPTIONENUM.YES); + } + return exceptionResultset; + } + return null; + } + + @Override + public int getResultSetConcurrency() throws SQLException + { + + return 0; + } + + @Override + public int getResultSetHoldability() throws SQLException + { + + return 0; + } + + @Override + public int getResultSetType() throws SQLException + { + + return 0; + } + + @Override + public int getUpdateCount() throws SQLException + { + + return 0; + } + + @Override + public SQLWarning getWarnings() throws SQLException + { + throw new SQLException(); + + } + + @Override + public boolean isClosed() throws SQLException + { + + return false; + } + + @Override + public boolean isPoolable() throws SQLException + { + + return false; + } + + @Override + public void setCursorName(String arg0) throws SQLException + { + + + } + + @Override + public void setEscapeProcessing(boolean arg0) throws SQLException + { + + + } + + @Override + public void setFetchDirection(int arg0) throws SQLException + { + + + } + + @Override + public void setFetchSize(int arg0) throws SQLException + { + + + } + + @Override + public void setMaxFieldSize(int arg0) throws SQLException + { + + + } + + @Override + public void setMaxRows(int arg0) throws SQLException + { + + + } + + @Override + public void setPoolable(boolean arg0) throws SQLException + { + + + } + + @Override + public void setQueryTimeout(int arg0) throws SQLException + { + + + } + + @Override + public void closeOnCompletion() throws SQLException { + + + } + + @Override + public boolean isCloseOnCompletion() throws SQLException { + + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/MockDebugServiceHelper.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/MockDebugServiceHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..fb6a12d7dd06888bd653d957df5c11671c071a6a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/MockDebugServiceHelper.java @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.mock.presentation; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.opengauss.mppdbide.debuger.vo.FunctionVo; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockResultSet; + +/** + * Title: MockDebugServiceHelper for use + * + * @since 3.0.0 + */ +public class MockDebugServiceHelper { + private PreparedStatementResultSetHandler handler; + private FunctionVo funcVo; + public MockDebugServiceHelper(PreparedStatementResultSetHandler handler, + FunctionVo funcVo) { + this.handler = handler; + this.funcVo = funcVo; + } + + public void mockVariable(String sql) { + String[] variables = new String[] {"name", "varclass", "linenumber", + "isunique", "isconst", "isnotnull", "dtype", + "value"}; + Object[] oneRow = new Object[] {"v1", "int", new Integer(1), true, false, + true, 22L, 1}; + mockOneRow(sql, variables, oneRow); + } + + public void mockStack(String sql) { + String[] stackColumn = new String[] {"level", "targetname", "func", + "linenumber", "args"}; + Object[] oneRowValues = new Object[] {1, funcVo.proname, funcVo.oid, + 1, null}; + mockOneRow(sql, stackColumn, oneRowValues); + } + + public void mockBreakPoint(String sql) { + mockPositionOneLine(sql); + } + + public void mockPositionOneLine(String sql) { + String[] breakPointTitle = new String[] {"func", "linenumber", "targetname"}; + Object[] oneRow = new Object[] {new Long(funcVo.oid), + new Integer(-1), + funcVo.proname}; + mockOneRow(sql, breakPointTitle, oneRow); + } + + public void mockAbortDebug(String sql) { + mockOneRow(sql, new String[] {"result"}, new Object[] {new Boolean(true)}); + } + + public void mockAttachDebug(String sql, Object port) { + mockOneRow(sql, new String[] {"port"}, new Object[] {port}); + } + + public void mockStartDebug(String sql, Object ret) { + mockOneRow(sql, new String[] {"result"}, new Object[] {ret}); + } + + public void mockPrepareDebug(String sql) { + mockHelper(sql, new ResultColumnHelper()); + } + + public void mockFunctionVo(String sql, Object[] args) { + String[] columns = new String[] {"oid", "proname", "proretset", + "prorettype", "pronargs", "pronargdefaults", + "proargtypes", "proallargtypes", "proargmodes", + "proargnames", "proargdefaults", "prodefaultargpos", + "prosrc"}; + mockOneRow(sql, columns, args); + } + + private void mockOneRow(String sql, String[] columns, Object[] oneRow) { + ResultColumnHelper helper = new ResultColumnHelper(columns); + helper.addRow(oneRow); + mockHelper(sql, helper); + } + + private void mockHelper(String sql, ResultColumnHelper helper) { + MockResultSet rs = handler.createResultSet(); + helper.setResultSet(rs); + handler.prepareResultSet(sql, rs); + } + + public static class ResultColumnHelper { + public List columns; + public List> rows = new ArrayList>(1); + public ResultColumnHelper() { + columns = null; + } + + public ResultColumnHelper(String[] columns) { + this(Arrays.asList(columns)); + } + + public ResultColumnHelper(List columns) { + this.columns = columns; + } + + public void addRow(Object[] objRowCol) { + addRow(Arrays.asList(objRowCol)); + } + + public void addRow(List rowCol) { + List newRow = new ArrayList(rowCol); + if (rowCol.size() < columns.size()) { + for (int i = 0, size = columns.size() - rowCol.size(); + i < size ; i ++) { + newRow.add(null); + } + } + rows.add(newRow); + } + + public void setResultSet(MockResultSet rs) { + if (columns == null || columns.size() == 0) { + return; + } + for (String col: columns) { + rs.addColumn(col); + } + for (List row: rows) { + rs.addRow(row); + } + } + } + + public static class FunctionDesc { + public String proname; + public List params; + public FunctionDesc(String proname, List params) { + this.proname = proname; + this.params = params; + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/MockERPresentationUtils.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/MockERPresentationUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..2b0bf3600eddbcef420144318846fb713e52f99e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/MockERPresentationUtils.java @@ -0,0 +1,71 @@ + +package org.opengauss.mppdbide.mock.presentation; + +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockResultSet; + +public class MockERPresentationUtils { + + public static void getForeignKeysConstraintDetailsQuery( + PreparedStatementResultSetHandler preparedStatementResultSetHandler) { + String functions = "SELECT CONS.OWNER, CONS.TABLE_NAME, CONS.CONSTRAINT_NAME, CONS.CONSTRAINT_TYPE, CONS.R_OWNER, CONS.R_TABLE_NAME, CONS.R_CONSTRAINT_NAME, SCD.COL_LIST FROM SYS.ALL_CONSTRAINTS CONS, SYS.CONSDEF$ SCD WHERE (CONS.R_OWNER=? OR CONS.OWNER=?) AND CONS.CONSTRAINT_TYPE ='R' AND CONS.CONSTRAINT_NAME = SCD.CONS_NAME"; + MockResultSet functionsResultSet = preparedStatementResultSetHandler.createResultSet(); + functionsResultSet.addColumn("OWNER"); + functionsResultSet.addColumn("TABLE_NAME"); + functionsResultSet.addColumn("CONSTRAINT_NAME"); + functionsResultSet.addColumn("CONSTRAINT_TYPE"); + functionsResultSet.addColumn("R_OWNER"); + functionsResultSet.addColumn("R_TABLE_NAME"); + functionsResultSet.addColumn("R_CONSTRAINT_NAME"); + functionsResultSet.addColumn("COL_LIST"); + functionsResultSet + .addRow(new Object[] {"TEST_OWNER12", "TABLE8", "FORKKK", "R", "PUBLIC", "TEST3", "PK_TEST3", "1"}); + preparedStatementResultSetHandler.prepareResultSet(functions, functionsResultSet, + (new Object[] {"MT1", "MT1"})); + } + + public static void getTableForeignKeysConstraintDetails( + PreparedStatementResultSetHandler preparedStatementResultSetHandler) { + String functions = "SELECT CONS.OWNER, CONS.TABLE_NAME, CONS.CONSTRAINT_NAME, CONS.CONSTRAINT_TYPE, CONS.R_OWNER, CONS.R_TABLE_NAME, CONS.R_CONSTRAINT_NAME, SCD.COL_LIST FROM SYS.ALL_CONSTRAINTS CONS, SYS.CONSDEF$ SCD WHERE CONS.R_OWNER=? AND CONS.R_TABLE_NAME=? AND CONS.CONSTRAINT_TYPE ='R' AND CONS.CONSTRAINT_NAME = SCD.CONS_NAME"; + MockResultSet functionsResultSet = preparedStatementResultSetHandler.createResultSet(); + functionsResultSet.addColumn("OWNER"); + functionsResultSet.addColumn("TABLE_NAME"); + functionsResultSet.addColumn("CONSTRAINT_NAME"); + functionsResultSet.addColumn("CONSTRAINT_TYPE"); + functionsResultSet.addColumn("R_OWNER"); + functionsResultSet.addColumn("R_TABLE_NAME"); + functionsResultSet.addColumn("R_CONSTRAINT_NAME"); + functionsResultSet.addColumn("COL_LIST"); + functionsResultSet.addRow(new Object[] {"TEST_OWNER12", "TEST8", "FKKKKKKKKK", "R", "PUBLIC", "TEST3", "PK_TEST3", "0"}); + preparedStatementResultSetHandler.prepareResultSet(functions, functionsResultSet, + (new Object[] {"MT1", "TEST3"})); + } + + public static void getTableKeysConstraintDetails( + PreparedStatementResultSetHandler preparedStatementResultSetHandler) { + String functions = "SELECT CONS.OWNER, CONS.TABLE_NAME, CONS.CONSTRAINT_NAME, CONS.CONSTRAINT_TYPE, CONS.R_OWNER, CONS.R_TABLE_NAME, CONS.R_CONSTRAINT_NAME, SCD.COL_LIST FROM SYS.ALL_CONSTRAINTS CONS, SYS.CONSDEF$ SCD WHERE CONS.OWNER=? AND CONS.TABLE_NAME=? AND CONS.CONSTRAINT_TYPE <>'C' AND CONS.CONSTRAINT_NAME = SCD.CONS_NAME"; + MockResultSet functionsResultSet = preparedStatementResultSetHandler.createResultSet(); + functionsResultSet.addColumn("OWNER"); + functionsResultSet.addColumn("TABLE_NAME"); + functionsResultSet.addColumn("CONSTRAINT_NAME"); + functionsResultSet.addColumn("CONSTRAINT_TYPE"); + functionsResultSet.addColumn("R_OWNER"); + functionsResultSet.addColumn("R_TABLE_NAME"); + functionsResultSet.addColumn("R_CONSTRAINT_NAME"); + functionsResultSet.addColumn("COL_LIST"); + functionsResultSet.addRow(new Object[] {"TEST_OWNER", "TEST3", "FK_TEST3", "R", "SYS", "TEST4", "PK_TEST3", "1"}); + preparedStatementResultSetHandler.prepareResultSet(functions, functionsResultSet, + (new Object[] {"MT1", "TEST3"})); + } + + public static void getTableColumnComments(PreparedStatementResultSetHandler preparedStatementResultSetHandler) { + String functions = "SELECT TAB.COLUMN_NAME, COM.COMMENTS, TAB.CHAR_USED FROM SYS.ALL_TAB_COLUMNS TAB LEFT JOIN SYS.DBA_COL_COMMENTS COM ON TAB.TABLE_NAME = COM.TABLE_NAME AND TAB.COLUMN_NAME = COM.COLUMN_NAME WHERE TAB.OWNER=? AND TAB.TABLE_NAME=?"; + MockResultSet functionsResultSet = preparedStatementResultSetHandler.createResultSet(); + functionsResultSet.addColumn("COLUMN_NAME"); + functionsResultSet.addColumn("COMMENTS"); + functionsResultSet.addColumn("CHAR_USED"); + functionsResultSet.addRow(new Object[] {"INFO", " ", "C"}); + preparedStatementResultSetHandler.prepareResultSet(functions, functionsResultSet, + (new Object[] {"MT1", "TEST3"})); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/MockUserRoleManagerUtils.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/MockUserRoleManagerUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..d9f6e1d09e3dcdb35a5ddaf7ebf10df1f0613a29 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/MockUserRoleManagerUtils.java @@ -0,0 +1,342 @@ +package org.opengauss.mppdbide.mock.presentation; + +import java.sql.Date; + +import org.opengauss.mppdbide.bl.serverdatacache.UserRole; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockResultSet; + +public class MockUserRoleManagerUtils { + + + + public static void test_isSysAdmin_001_RS(PreparedStatementResultSetHandler preparedstatementHandler) + { + String query = "SELECT rolsystemadmin FROM pg_catalog.pg_roles WHERE rolname = user;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("rolsystemadmin"); + rs.addRow(new Object[] {true}); + preparedstatementHandler.prepareResultSet(query, rs); + } + + public static void test_isSysAdmin_002_RS(PreparedStatementResultSetHandler preparedstatementHandler) + { + String query = "SELECT rolsystemadmin FROM pg_catalog.pg_roles WHERE rolname = user;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("rolsystemadmin"); + rs.addRow(new Object[] {false}); + preparedstatementHandler.prepareResultSet(query, rs); + } + + public static void test_isSysAdmin_003_RS(PreparedStatementResultSetHandler preparedstatementHandler) + { + String query = "SELECT rolsystemadmin FROM pg_catalog.pg_roles WHERE rolname = user;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("rolsystemadmin"); + preparedstatementHandler.prepareResultSet(query, rs); + } + + public static void test_fetchAllUserRole_001_RS(PreparedStatementResultSetHandler preparedstatementHandler) + { + String query = "SELECT rolname,rolcanlogin,oid FROM pg_catalog.pg_roles;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("rolname"); + rs.addColumn("rolcanlogin"); + rs.addColumn("oid"); + rs.addRow(new Object[] {"Chris", true, 001}); + rs.addRow(new Object[] {"Martin", false, 002}); + preparedstatementHandler.prepareResultSet(query, rs); + } + + public static void test_fetchAllUserRole_002_RS(PreparedStatementResultSetHandler preparedstatementHandler) + { + String query = "SELECT rolname,rolcanlogin,oid FROM pg_catalog.pg_roles;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("rolname"); + rs.addColumn("rolcanlogin"); + rs.addColumn("oid"); + preparedstatementHandler.prepareResultSet(query, rs); + } + + public static void + test_fetchAllUserRoleWithOutSuperUser_001_RS(PreparedStatementResultSetHandler preparedstatementHandler) + { + String query = "SELECT rolname,rolcanlogin,oid FROM pg_catalog.pg_roles WHERE rolsuper = false;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("rolname"); + rs.addColumn("rolcanlogin"); + rs.addColumn("oid"); + rs.addRow(new Object[] {"Chris", true, 001}); + rs.addRow(new Object[] {"Martin", false, 002}); + preparedstatementHandler.prepareResultSet(query, rs); + } + + public static void + test_fetchAllUserRoleWithOutSuperUser_002_RS(PreparedStatementResultSetHandler preparedstatementHandler) + { + String query = "SELECT rolname,rolcanlogin,oid FROM pg_catalog.pg_roles WHERE rolsuper = false;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("rolname"); + rs.addColumn("rolcanlogin"); + rs.addColumn("oid"); + preparedstatementHandler.prepareResultSet(query, rs); + } + + public static void test_fetchUserRoleDetailInfoByOid_001_RS( + PreparedStatementResultSetHandler preparedstatementHandler, UserRole userRole) + { + String query = "SELECT rolname,rolinherit,rolcreaterole,rolcreatedb,rolcanlogin,rolreplication" + + ",rolauditadmin,rolsystemadmin,rolconnlimit,rolvalidbegin,rolvaliduntil,oid,rolrespool" + + " FROM pg_catalog.pg_roles WHERE oid = ?::oid;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("rolname"); + rs.addColumn("rolinherit"); + rs.addColumn("rolcreaterole"); + rs.addColumn("rolcreatedb"); + rs.addColumn("rolcanlogin"); + rs.addColumn("rolreplication"); + rs.addColumn("rolauditadmin"); + rs.addColumn("rolsystemadmin"); + rs.addColumn("rolconnlimit"); + rs.addColumn("rolvalidbegin"); + rs.addColumn("rolvaliduntil"); + rs.addColumn("oid"); + rs.addColumn("rolrespool"); + rs.addRow(new Object[] {"Chris", true, true, true, true, true, true, true, -1, new Date(0), new Date(0), + userRole.getOid(), "default_pool"}); + preparedstatementHandler.prepareResultSet(query, rs, new Object[] {String.valueOf(userRole.getOid())}); + } + + public static void test_fetchUserRoleDetailInfoByOid_002_RS( + PreparedStatementResultSetHandler preparedstatementHandler, UserRole userRole) + { + String query = "SELECT rolname,rolinherit,rolcreaterole,rolcreatedb,rolcanlogin,rolreplication" + + ",rolauditadmin,rolsystemadmin,rolconnlimit,rolvalidbegin,rolvaliduntil,oid,rolrespool" + + " FROM pg_catalog.pg_roles WHERE oid = ?::oid;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("rolname"); + rs.addColumn("rolinherit"); + rs.addColumn("rolcreaterole"); + rs.addColumn("rolcreatedb"); + rs.addColumn("rolcanlogin"); + rs.addColumn("rolreplication"); + rs.addColumn("rolauditadmin"); + rs.addColumn("rolsystemadmin"); + rs.addColumn("rolconnlimit"); + rs.addColumn("rolvalidbegin"); + rs.addColumn("rolvaliduntil"); + rs.addColumn("oid"); + rs.addColumn("rolrespool"); + preparedstatementHandler.prepareResultSet(query, rs, new Object[] {String.valueOf(userRole.getOid())}); + } + + public static void test_fetchUserRoleSimpleInfoByOid_001_RS( + PreparedStatementResultSetHandler preparedstatementHandler, UserRole userRole) + { + String query = "SELECT rolname,rolcanlogin,oid FROM pg_catalog.pg_roles WHERE oid = ?::oid;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("rolname"); + rs.addColumn("rolcanlogin"); + rs.addColumn("oid"); + rs.addRow(new Object[] {"Chris", true, userRole.getOid()}); + preparedstatementHandler.prepareResultSet(query, rs, new Object[] {String.valueOf(userRole.getOid())}); + } + + public static void test_fetchUserRoleSimpleInfoByOid_002_RS( + PreparedStatementResultSetHandler preparedstatementHandler, UserRole userRole) + { + String query = "SELECT rolname,rolcanlogin,oid FROM pg_catalog.pg_roles WHERE oid = ?::oid;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("rolname"); + rs.addColumn("rolcanlogin"); + rs.addColumn("oid"); + preparedstatementHandler.prepareResultSet(query, rs, new Object[] {String.valueOf(userRole.getOid())}); + } + + public static void test_fetchAllParent_001_RS(PreparedStatementResultSetHandler preparedstatementHandler, + UserRole userRole) + { + String query = "SELECT r.oid, r.rolname FROM pg_catalog.pg_roles r, pg_catalog.pg_auth_members m" + + " WHERE r.oid = m.roleid AND member = ?::oid;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("oid"); + rs.addColumn("rolname"); + rs.addRow(new Object[] {102L, "Martin"}); + rs.addRow(new Object[] {103L, "Arun"}); + preparedstatementHandler.prepareResultSet(query, rs, new Object[] {String.valueOf(userRole.getOid())}); + } + + public static void test_fetchAllParent_002_RS(PreparedStatementResultSetHandler preparedstatementHandler, + UserRole userRole) + { + String query = "SELECT r.oid, r.rolname FROM pg_catalog.pg_roles r, pg_catalog.pg_auth_members m" + + " WHERE r.oid = m.roleid AND member = ?::oid;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("oid"); + rs.addColumn("rolname"); + preparedstatementHandler.prepareResultSet(query, rs, new Object[] {String.valueOf(userRole.getOid())}); + } + + public static void test_fetchAllMember_001_RS(PreparedStatementResultSetHandler preparedstatementHandler, + UserRole userRole) + { + String query = "SELECT r.oid, r.rolname FROM pg_catalog.pg_roles r, pg_catalog.pg_auth_members m" + + " WHERE r.oid = m.member AND roleid = ?::oid;"; + ; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("oid"); + rs.addColumn("rolname"); + rs.addRow(new Object[] {102L, "Martin"}); + rs.addRow(new Object[] {103L, "Arun"}); + rs.addRow(new Object[] {104L, "Mark"}); + preparedstatementHandler.prepareResultSet(query, rs, new Object[] {String.valueOf(userRole.getOid())}); + } + + public static void test_fetchAllMember_002_RS(PreparedStatementResultSetHandler preparedstatementHandler, + UserRole userRole) + { + String query = "SELECT r.oid, r.rolname FROM pg_catalog.pg_roles r, pg_catalog.pg_auth_members m" + + " WHERE r.oid = m.member AND roleid = ?::oid;"; + ; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("oid"); + rs.addColumn("rolname"); + preparedstatementHandler.prepareResultSet(query, rs, new Object[] {String.valueOf(userRole.getOid())}); + } + + public static void test_generatePropertyChangePreviewSQL_001_RS01( + PreparedStatementResultSetHandler preparedstatementHandler, UserRole userRole) + { + String query = "SELECT r.rolname FROM pg_catalog.pg_roles r, pg_catalog.pg_auth_members m" + + " WHERE r.oid = m.roleid AND m.member = ?::oid;"; + ; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("rolname"); + rs.addRow(new Object[] {"Martin"}); + rs.addRow(new Object[] {"Arun"}); + rs.addRow(new Object[] {"Tom"}); + preparedstatementHandler.prepareResultSet(query, rs, new Object[] {String.valueOf(userRole.getOid())}); + } + + public static void test_generatePropertyChangePreviewSQL_001_RS02( + PreparedStatementResultSetHandler preparedstatementHandler, UserRole userRole) + { + String query = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid = ?::oid;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("rolname"); + rs.addRow(new Object[] {"chris"}); + preparedstatementHandler.prepareResultSet(query, rs, new Object[] {String.valueOf(userRole.getOid())}); + } + + public static void test_fetchDescriptionOfUserRole_001_RS( + PreparedStatementResultSetHandler preparedstatementHandler, UserRole userRole) + { + String query = "SELECT pg_catalog.shobj_description(?::oid, 'pg_authid') description;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("description"); + rs.addRow(new Object[] {"Winner"}); + preparedstatementHandler.prepareResultSet(query, rs, new Object[] {String.valueOf(userRole.getOid())}); + } + + public static void test_fetchDescriptionOfUserRole_002_RS( + PreparedStatementResultSetHandler preparedstatementHandler, UserRole userRole) + { + String query = "SELECT pg_catalog.shobj_description(?::oid, 'pg_authid') description;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("description"); + preparedstatementHandler.prepareResultSet(query, rs, new Object[] {String.valueOf(userRole.getOid())}); + } + + public static void test_fetchResourcePool_001_RS(PreparedStatementResultSetHandler preparedstatementHandler) + { + String query = "SELECT respool_name FROM pg_resource_pool;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("respool_name"); + rs.addRow(new Object[] {"default_pool"}); + preparedstatementHandler.prepareResultSet(query, rs); + } + + public static void test_fetchResourcePool_002_RS(PreparedStatementResultSetHandler preparedstatementHandler) + { + String query = "SELECT respool_name FROM pg_resource_pool;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("respool_name"); + preparedstatementHandler.prepareResultSet(query, rs); + } + + public static void test_isUserRoleExist_001_RS(PreparedStatementResultSetHandler preparedstatementHandler, + UserRole userRole) + { + String query = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid = ?::oid;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("rolname"); + rs.addRow(new Object[] {"chris"}); + preparedstatementHandler.prepareResultSet(query, rs, new Object[] {String.valueOf(userRole.getOid())}); + + } + + public static void test_isUserRoleExist_002_RS(PreparedStatementResultSetHandler preparedstatementHandler, + UserRole userRole) + { + String query = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid = ?::oid;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("rolname"); + preparedstatementHandler.prepareResultSet(query, rs, new Object[] {String.valueOf(userRole.getOid())}); + + } + + public static void test_fetchLockStatusOfUserRole_001_RS(PreparedStatementResultSetHandler preparedstatementHandler, + UserRole userRole) + { + String query = "SELECT rolstatus FROM pg_catalog.pg_user_status WHERE roloid = ?::oid;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("rolstatus"); + rs.addRow(new Object[] {"2"}); + preparedstatementHandler.prepareResultSet(query, rs, new Object[] {String.valueOf(userRole.getOid())}); + + } + + public static void test_fetchLockStatusOfUserRole_002_RS(PreparedStatementResultSetHandler preparedstatementHandler, + UserRole userRole) + { + String query = "SELECT rolstatus FROM pg_catalog.pg_user_status WHERE roloid = ?::oid;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("rolstatus"); + rs.addRow(new Object[] {"0"}); + preparedstatementHandler.prepareResultSet(query, rs, new Object[] {String.valueOf(userRole.getOid())}); + + } + + public static void test_fetchLockStatusOfUserRole_003_RS(PreparedStatementResultSetHandler preparedstatementHandler, + UserRole userRole) + { + String query = "SELECT rolstatus FROM pg_catalog.pg_user_status WHERE roloid = ?::oid;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("rolstatus"); + preparedstatementHandler.prepareResultSet(query, rs, new Object[] {String.valueOf(userRole.getOid())}); + + } + + public static void test_getUserRoleNameByOid_001_RS(PreparedStatementResultSetHandler preparedstatementHandler, + long oid) + { + String query = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid = ?::oid;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("rolname"); + rs.addRow(new Object[] {"chris"}); + preparedstatementHandler.prepareResultSet(query, rs, new Object[] {String.valueOf(oid)}); + } + + public static void test_getUserRoleloginByOid_001_RS(PreparedStatementResultSetHandler preparedstatementHandler, + long oid) + { + String query = "SELECT rolcanlogin FROM pg_catalog.pg_roles WHERE oid = ?::oid;"; + MockResultSet rs = preparedstatementHandler.createResultSet(); + rs.addColumn("rolcanlogin"); + rs.addRow(new Object[] {false}); + preparedstatementHandler.prepareResultSet(query, rs, new Object[] {String.valueOf(oid)}); + } + + + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/MockViewUtils.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/MockViewUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..878e821445a22a144bafce397de2ad3cdb059513 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/MockViewUtils.java @@ -0,0 +1,438 @@ +package org.opengauss.mppdbide.mock.presentation; + +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockResultSet; + +public class MockViewUtils +{ + public enum EXCEPTIONENUM + { + YES, NO; + } + + public static final String GETNAMESPACEQUERY = "SELECT oid, nspname from pg_namespace where ((oid < 16384 and nspname NOT LIKE 'public') or nspname LIKE 'pg_%') and has_schema_privilege(nspname, 'USAGE') ORDER BY nspname;"; + public static final String GETVIEWQUERY = "SELECT c.oid, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner , c.relkind as relkind FROM pg_class c WHERE (c.relkind = 'v'::char or c.relkind = 'm'::char) and has_table_privilege(c.oid,'SELECT') and c.relnamespace = 10"; + + private static final String VIEWQUERY_SCHEMA = "and n.nspname="; + private static final String VIEWQUERY_OID = "and c.oid="; + + public static void createNamespace( + PreparedStatementResultSetHandler preparedstatementHandler, + int nsid, String nsname) + { + MockResultSet namespaceRS = preparedstatementHandler.createResultSet(); + namespaceRS.addColumn("oid"); + namespaceRS.addColumn("nspname"); + namespaceRS.addRow(new Object[] {1, "pg_catalog"}); + namespaceRS.addRow(new Object[] {2, "information_schema"}); + namespaceRS.addRow(new Object[] {nsid, nsname}); + preparedstatementHandler.prepareResultSet( + GETNAMESPACEQUERY, namespaceRS); + } + + public static void createViewMetadata( + PreparedStatementResultSetHandler preparedstatementHandler, + int nsid,int input) + { + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + MockResultSet viewDdlRs; + getdbsrs.addColumn("oid"); + getdbsrs.addColumn("viewname"); + getdbsrs.addColumn("viewowner"); + getdbsrs.addColumn("relkind"); + for(int i=1;i<=input;i++) { + getdbsrs.addRow(new Object[] {i,"mytestview"+i, "owner1", "v"}); + viewDdlRs = preparedstatementHandler.createResultSet(); + viewDdlRs.addRow(new Object[] {"select * from something"+i}); + preparedstatementHandler.prepareResultSet("SELECT * FROM pg_get_viewdef(" + i + ')', viewDdlRs); + } + preparedstatementHandler.prepareResultSet(GETVIEWQUERY, getdbsrs); + + } + public static void createViewMetadataAutoSuggest( + PreparedStatementResultSetHandler preparedstatementHandler, + int nsid,int input) + { + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + MockResultSet viewDdlRs; + getdbsrs.addColumn("oid"); + getdbsrs.addColumn("viewname"); + getdbsrs.addColumn("viewowner"); + getdbsrs.addColumn("relkind"); + for(int i=1;i<=input;i++) { + getdbsrs.addRow(new Object[] {i,"mytestview"+i, "owner1", "v"}); + viewDdlRs = preparedstatementHandler.createResultSet(); + viewDdlRs.addRow(new Object[] {"select * from something"+i}); + preparedstatementHandler.prepareResultSet("SELECT * FROM pg_get_viewdef(" + i + ')', viewDdlRs); + } + preparedstatementHandler.prepareResultSet("SELECT c.oid, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner , c.relkind as relkind FROM pg_class c WHERE (c.relkind = 'v'::char or c.relkind = 'm'::char) and has_table_privilege(c.oid,'SELECT') and c.relnamespace = 1", getdbsrs); + + MockResultSet getdbsrs1 = preparedstatementHandler.createResultSet(); + MockResultSet viewDdlRs1; + getdbsrs1.addColumn("oid"); + getdbsrs1.addColumn("viewname"); + getdbsrs1.addColumn("viewowner"); + getdbsrs1.addColumn("relkind"); + for(int i=1;i<=input;i++) { + getdbsrs1.addRow(new Object[] {i,"mytestview"+i, "owner1", "v"}); + viewDdlRs1 = preparedstatementHandler.createResultSet(); + viewDdlRs1.addRow(new Object[] {"select * from something"+i}); + preparedstatementHandler.prepareResultSet("SELECT * FROM pg_get_viewdef(" + i + ')', viewDdlRs1); + } + preparedstatementHandler.prepareResultSet("SELECT c.oid, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner FROM pg_class c WHERE (c.relkind = 'v'::char or c.relkind = 'm'::char) and has_table_privilege(c.oid,'SELECT') and c.relnamespace = 2", getdbsrs1); + + + MockResultSet getdbsrs2 = preparedstatementHandler.createResultSet(); + MockResultSet viewDdlRs2; + getdbsrs2.addColumn("oid"); + getdbsrs2.addColumn("viewname"); + getdbsrs2.addColumn("viewowner"); + getdbsrs2.addColumn("relkind"); + for(int i=1;i<=input;i++) { + getdbsrs2.addRow(new Object[] {i,"mytestview"+i, "owner1", "v"}); + viewDdlRs2 = preparedstatementHandler.createResultSet(); + viewDdlRs2.addRow(new Object[] {"select * from something"+i}); + preparedstatementHandler.prepareResultSet("SELECT * FROM pg_get_viewdef(" + i + ')', viewDdlRs2); + } + preparedstatementHandler.prepareResultSet("SELECT c.oid, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner , c.relkind as relkind FROM pg_class c WHERE (c.relkind = 'v'::char or c.relkind = 'm'::char) and has_table_privilege(c.oid,'SELECT') and c.relnamespace = 3", getdbsrs2); + + + MockResultSet getdbsrs3 = preparedstatementHandler.createResultSet(); + MockResultSet viewDdlRs3; + getdbsrs3.addColumn("oid"); + getdbsrs3.addColumn("viewname"); + getdbsrs3.addColumn("viewowner"); + getdbsrs3.addColumn("relkind"); + for(int i=1;i<=input;i++) { + getdbsrs3.addRow(new Object[] {i,"mytestview"+i, "owner1", "v"}); + viewDdlRs3 = preparedstatementHandler.createResultSet(); + viewDdlRs3.addRow(new Object[] {"select * from something"+i}); + preparedstatementHandler.prepareResultSet("SELECT * FROM pg_get_viewdef(" + i + ')', viewDdlRs3); + } + preparedstatementHandler.prepareResultSet("SELECT c.oid, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner , c.relkind as relkind FROM pg_class c WHERE (c.relkind = 'v'::char or c.relkind = 'm'::char) and has_table_privilege(c.oid,'SELECT') and c.relnamespace = 4", getdbsrs3); + + + MockResultSet getdbsrs4 = preparedstatementHandler.createResultSet(); + MockResultSet viewDdlRs4; + getdbsrs4.addColumn("oid"); + getdbsrs4.addColumn("viewname"); + getdbsrs4.addColumn("viewowner"); + getdbsrs4.addColumn("relkind"); + for(int i=1;i<=input;i++) { + getdbsrs4.addRow(new Object[] {i,"mytestview"+i, "owner1", "v"}); + viewDdlRs4 = preparedstatementHandler.createResultSet(); + viewDdlRs4.addRow(new Object[] {"select * from something"+i}); + preparedstatementHandler.prepareResultSet("SELECT * FROM pg_get_viewdef(" + i + ')', viewDdlRs4); + } + preparedstatementHandler.prepareResultSet("SELECT c.oid, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner , c.relkind as relkind FROM pg_class c WHERE (c.relkind = 'v'::char or c.relkind = 'm'::char) and has_table_privilege(c.oid,'SELECT') and c.relnamespace = 5", getdbsrs4); + + MockResultSet getdbsrs5 = preparedstatementHandler.createResultSet(); + MockResultSet viewDdlRs5; + getdbsrs5.addColumn("oid"); + getdbsrs5.addColumn("viewname"); + getdbsrs5.addColumn("viewowner"); + getdbsrs5.addColumn("relkind"); + for(int i=1;i<=input;i++) { + getdbsrs5.addRow(new Object[] {i,"mytestview"+i, "owner1", "v"}); + viewDdlRs5 = preparedstatementHandler.createResultSet(); + viewDdlRs5.addRow(new Object[] {"select * from something"+i}); + preparedstatementHandler.prepareResultSet("SELECT * FROM pg_get_viewdef(" + i + ')', viewDdlRs5); + } + preparedstatementHandler.prepareResultSet("SELECT c.oid, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner , c.relkind as relkind FROM pg_class c WHERE (c.relkind = 'v'::char or c.relkind = 'm'::char) and has_table_privilege(c.oid,'SELECT') and c.relnamespace = 6", getdbsrs5); + + } + + public static void createViewMetadata_SchemaName( + PreparedStatementResultSetHandler preparedstatementHandler,int schemaId, + int nsid, String schemaName) + { + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("oid"); + getdbsrs.addColumn("nspoid"); + getdbsrs.addColumn("schemaname"); + getdbsrs.addColumn("viewname"); + getdbsrs.addColumn("viewowner"); + getdbsrs.addColumn("definition"); + getdbsrs.addRow(new Object[] {schemaId, nsid, schemaName, "mytestview"+schemaId, "owner1", + "select * from something"}); + preparedstatementHandler.prepareResultSet(GETVIEWQUERY + + VIEWQUERY_SCHEMA + "'" + schemaName + "'", getdbsrs); + } + + public static void createViewMetadata_Oid( + PreparedStatementResultSetHandler preparedstatementHandler,int schemaId, + int nsid, String schemaName, Namespace ns) + { + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("oid"); + getdbsrs.addColumn("nspoid"); + getdbsrs.addColumn("schemaname"); + getdbsrs.addColumn("viewname"); + getdbsrs.addColumn("viewowner"); + getdbsrs.addColumn("relkind"); + getdbsrs.addColumn("definition"); + getdbsrs.addRow(new Object[] {schemaId, nsid, schemaName, "mytestview"+schemaId, "owner1","v", + "select * from something"}); + preparedstatementHandler.prepareResultSet(GETVIEWQUERY + VIEWQUERY_OID + + ns.getOid(), getdbsrs); + } + + public static void createViewColunmMetadata( + PreparedStatementResultSetHandler preparedstatementHandler, + int viewid, int nsid) + { + String query = "select v.oid as viewid, v.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, c.atttypid as datatypeoid, typ.typnamespace as dtns, " + + "c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, " + + "d.adsrc as default_value from pg_class v left join pg_attribute c on (v.oid = c.attrelid and v.relkind = 'v') " + + "left join pg_attrdef d on (v.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) " + + "where c.attisdropped = 'f' and c.attnum > 0 and v.relnamespace = " + + nsid + " order by v.oid, c.attnum"; + + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("viewid"); + getdbsrs.addColumn("namespaceid"); + getdbsrs.addColumn("columnidx"); + getdbsrs.addColumn("name"); + getdbsrs.addColumn("datatypeoid"); + getdbsrs.addColumn("dtns"); + getdbsrs.addColumn("length"); + getdbsrs.addColumn("precision"); + getdbsrs.addColumn("dimentions"); + getdbsrs.addColumn("notnull"); + getdbsrs.addColumn("isdefaultvalueavailable"); + getdbsrs.addColumn("default_value"); + + getdbsrs.addRow(new Object[] {1, nsid, 1, "col1", 2, 1, 64, -1, 0, + 'f', 'f', ""}); + getdbsrs.addRow(new Object[] {1, nsid, 2, "col2", 1, 1, 64, -1, 0, + 'f', 'f', ""}); + /* getdbsrs.addRow(new Object[] {2, nsid, 1, "col3", 2, 1, 64, -1, 0, + 'f', 'f', ""}); + getdbsrs.addRow(new Object[] {2, nsid, 2, "col4", 1, 1, 64, -1, 0, + 'f', 'f', ""}); + getdbsrs.addRow(new Object[] {3, nsid, 1, "col5", 2, 1, 64, -1, 0, + 'f', 'f', ""}); + getdbsrs.addRow(new Object[] {3, nsid, 2, "col6", 1, 1, 64, -1, 0, + 'f', 'f', ""}); + getdbsrs.addRow(new Object[] {3, nsid, 2, "col6", 1, 1, -1, -1, 0, + 'f', 'f', ""}); + getdbsrs.addRow(new Object[] {3, nsid, 2, "col6", 11, 1, -1, -1, 0, + 'f', 'f', ""});*/ + preparedstatementHandler.prepareResultSet(query, getdbsrs); + } + + public static void createViewColunmMetadataAutoSuggest( + PreparedStatementResultSetHandler preparedstatementHandler) + { + String query1 = "select v.oid as viewid, v.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class v left join pg_attribute c on (v.oid = c.attrelid and v.relkind = 'v') left join pg_attrdef d on (v.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and v.relnamespace = 1 order by v.oid, c.attnum"; + String query2 = "select v.oid as viewid, v.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class v left join pg_attribute c on (v.oid = c.attrelid and v.relkind = 'v') left join pg_attrdef d on (v.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and v.relnamespace = 2 order by v.oid, c.attnum"; + String query3 = "select v.oid as viewid, v.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class v left join pg_attribute c on (v.oid = c.attrelid and v.relkind = 'v') left join pg_attrdef d on (v.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and v.relnamespace = 3 order by v.oid, c.attnum"; + String query4 = "select v.oid as viewid, v.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class v left join pg_attribute c on (v.oid = c.attrelid and v.relkind = 'v') left join pg_attrdef d on (v.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and v.relnamespace = 4 order by v.oid, c.attnum"; + String query5 = "select v.oid as viewid, v.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class v left join pg_attribute c on (v.oid = c.attrelid and v.relkind = 'v') left join pg_attrdef d on (v.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and v.relnamespace = 5 order by v.oid, c.attnum"; + String query6 = "select v.oid as viewid, v.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class v left join pg_attribute c on (v.oid = c.attrelid and v.relkind = 'v') left join pg_attrdef d on (v.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and v.relnamespace = 6 order by v.oid, c.attnum"; + + + + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("viewid"); + getdbsrs.addColumn("namespaceid"); + getdbsrs.addColumn("columnidx"); + getdbsrs.addColumn("name"); + getdbsrs.addColumn("displayColumns"); + getdbsrs.addColumn("datatypeoid"); + getdbsrs.addColumn("dtns"); + getdbsrs.addColumn("length"); + getdbsrs.addColumn("precision"); + getdbsrs.addColumn("dimentions"); + getdbsrs.addColumn("notnull"); + getdbsrs.addColumn("isdefaultvalueavailable"); + getdbsrs.addColumn("default_value"); + getdbsrs.addColumn("attDefStr"); + + getdbsrs.addRow(new Object[] {1, 1, 1, "col1", "",2, 1, 64, -1, 0, + 'f', 'f', "", ""}); + getdbsrs.addRow(new Object[] {1, 1, 2, "col2","", 1, 1, 64, -1, 0, + 'f', 'f', "", ""}); + /* getdbsrs.addRow(new Object[] {2, nsid, 1, "col3", 2, 1, 64, -1, 0, + 'f', 'f', ""}); + getdbsrs.addRow(new Object[] {2, nsid, 2, "col4", 1, 1, 64, -1, 0, + 'f', 'f', ""}); + getdbsrs.addRow(new Object[] {3, nsid, 1, "col5", 2, 1, 64, -1, 0, + 'f', 'f', ""}); + getdbsrs.addRow(new Object[] {3, nsid, 2, "col6", 1, 1, 64, -1, 0, + 'f', 'f', ""}); + getdbsrs.addRow(new Object[] {3, nsid, 2, "col6", 1, 1, -1, -1, 0, + 'f', 'f', ""}); + getdbsrs.addRow(new Object[] {3, nsid, 2, "col6", 11, 1, -1, -1, 0, + 'f', 'f', ""});*/ + preparedstatementHandler.prepareResultSet(query1, getdbsrs); + preparedstatementHandler.prepareResultSet(query2, getdbsrs); + preparedstatementHandler.prepareResultSet(query3, getdbsrs); + preparedstatementHandler.prepareResultSet(query4, getdbsrs); + preparedstatementHandler.prepareResultSet(query5, getdbsrs); + preparedstatementHandler.prepareResultSet(query6, getdbsrs); + } + + public static void createView( + PreparedStatementResultSetHandler preparedstatementHandler, + String newSchemaName, Namespace ns, String oldName) + { + String createView = "ALTER VIEW " + ns.getQualifiedObjectName() + '.' + + oldName + " SET schema " + newSchemaName; + + MockResultSet colmetadataRS = preparedstatementHandler + .createResultSet(); + colmetadataRS.addColumn("messaage"); + + colmetadataRS.addRow(new Object[] {"View Altered"}); + preparedstatementHandler.prepareResultSet(createView, colmetadataRS); + } + + public static void DropView( + PreparedStatementResultSetHandler preparedstatementHandler, + String viewName) + { + String dropView = "DROP VIEW " + viewName; + + MockResultSet colmetadataRS = preparedstatementHandler + .createResultSet(); + colmetadataRS.addColumn("messaage"); + + colmetadataRS.addRow(new Object[] {"View droped"}); + preparedstatementHandler.prepareResultSet(dropView, colmetadataRS); + } + + public static void setNamespace( + PreparedStatementResultSetHandler preparedstatementHandler,int nsid, + String viewName) + { + String str="ALTER VIEW schema2.mytestview1 SET schema newSchema2"; + MockResultSet colmetadataRS = preparedstatementHandler + .createResultSet(); + colmetadataRS.addColumn("messaage"); + + colmetadataRS.addRow(new Object[] {"namespace set"}); + preparedstatementHandler.prepareResultSet(str, + colmetadataRS); + } + + public static void setDefault( + PreparedStatementResultSetHandler preparedstatementHandler,int nsid, + String viewName) + { + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("oid"); + getdbsrs.addColumn("nspoid"); + getdbsrs.addColumn("schemaname"); + getdbsrs.addColumn("viewname"); + getdbsrs.addColumn("viewowner"); + getdbsrs.addColumn("definition"); + getdbsrs.addRow(new Object[] {2, nsid, "newschema", viewName, "owner1", + "select * from something"}); + + preparedstatementHandler.prepareResultSet("", getdbsrs); + } + + public static void renameView( + PreparedStatementResultSetHandler preparedstatementHandler) + { + + String GETRENAMEVIEWQUERY = "ALTER VIEW \"newSchema\".mytestview1 RENAME TO mytestview11"; + MockResultSet colmetadataRS = preparedstatementHandler + .createResultSet(); + colmetadataRS.addColumn("messaage"); + + colmetadataRS.addRow(new Object[] {"View renamed"}); + preparedstatementHandler.prepareResultSet(GETRENAMEVIEWQUERY, + colmetadataRS); + + } + + public static void renameViewWithException( + PreparedStatementResultSetHandler preparedstatementHandler, + Namespace ns, String oldView, String newView) + { + + String GETRENAMEVIEWQUERY = "ALTER VIEW" + ns.getName() + "." + oldView + + " RENAME TO " + newView; + MockResultSet colmetadataRS = preparedstatementHandler + .createResultSet(); + colmetadataRS.addColumn("messaage"); + + colmetadataRS.addRow(new Object[] {"View renamed"}); + preparedstatementHandler.prepareResultSet(GETRENAMEVIEWQUERY, + colmetadataRS); + preparedstatementHandler + .prepareThrowsSQLException("Invalid valid query"); + + } + public static void DropViewWithException( + PreparedStatementResultSetHandler preparedstatementHandler, + String viewName) + { + + String dropView = "DROP VIEW " + viewName; + + MockResultSet colmetadataRS = preparedstatementHandler + .createResultSet(); + colmetadataRS.addColumn("messaage"); + + colmetadataRS.addRow(new Object[] {"View droped"}); + preparedstatementHandler.prepareResultSet(dropView, colmetadataRS); + preparedstatementHandler + .prepareThrowsSQLException("Invalid valid query"); + } + + public static void refreshNameSpace(PreparedStatementResultSetHandler preparedstatementHandler) + { + String str="select v.oid as viewid, v.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value from pg_class v left join pg_attribute c on (v.oid = c.attrelid and v.relkind = 'v') left join pg_attrdef d on (v.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and v.oid = 1 order by v.oid, c.attnum"; + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("viewid"); + getdbsrs.addColumn("namespaceid"); + getdbsrs.addColumn("columnidx"); + getdbsrs.addColumn("name"); + getdbsrs.addColumn("datatypeoid"); + getdbsrs.addColumn("dtns"); + getdbsrs.addColumn("length"); + getdbsrs.addColumn("precision"); + getdbsrs.addColumn("dimentions"); + getdbsrs.addColumn("notnull"); + getdbsrs.addColumn("isdefaultvalueavailable"); + getdbsrs.addColumn("default_value"); + + getdbsrs.addRow(new Object[] {1, 10, 1, "col1", 2, 1, 64, -1, 0, + 'f', 'f', ""}); + getdbsrs.addRow(new Object[] {1, 10, 2, "col2", 1, 1, 64, -1, 0, + 'f', 'f', ""}); + getdbsrs.addRow(new Object[] {2, 10, 1, "col1", 2, 1, 64, -1, 0, + 'f', 'f', ""}); + getdbsrs.addRow(new Object[] {2, 10, 2, "col2", 1, 1, 64, -1, 0, + 'f', 'f', ""}); + preparedstatementHandler.prepareResultSet(str, getdbsrs); + + } + public static String getMockedCreateViewTemplate(Namespace ns) + { + StringBuilder strbldr = new StringBuilder("CREATE OR REPLACE [ TEMP | TEMPORARY | MATERIALIZED ] VIEW "); + strbldr.append(ns.getQualifiedObjectName()) + .append(".") + .append("") + .append(" [ ( column_name [, ...] ) ] ") + .append(System.lineSeparator()) + .append("[ WITH ( {view_option_name [= view_option_value]} [, ... ] ) ]") + .append(System.lineSeparator()) + .append("\tAS ") + .append(System.lineSeparator()) + .append("") + .append(";"); + return strbldr.toString(); + } + + public static void refreshNameSpaceid( + PreparedStatementResultSetHandler preparedstatementHandler) + { + + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ResultSetMetaDataImplementation.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ResultSetMetaDataImplementation.java new file mode 100644 index 0000000000000000000000000000000000000000..b6a990eab94ab62b802d6b294255a1e3fd5ea28d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/mock/presentation/ResultSetMetaDataImplementation.java @@ -0,0 +1,252 @@ +package org.opengauss.mppdbide.mock.presentation; + +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Types; + +public class ResultSetMetaDataImplementation implements ResultSetMetaData +{ + @Override + public T unwrap(Class iface) throws SQLException + { + + return null; + } + + @Override + public boolean isWrapperFor(Class iface) throws SQLException + { + + return false; + } + + @Override + public boolean isWritable(int column) throws SQLException + { + + return false; + } + + @Override + public boolean isSigned(int column) throws SQLException + { + + return false; + } + + @Override + public boolean isSearchable(int column) throws SQLException + { + + return false; + } + + @Override + public boolean isReadOnly(int column) throws SQLException + { + + return false; + } + + @Override + public int isNullable(int column) throws SQLException + { + + return 0; + } + + @Override + public boolean isDefinitelyWritable(int column) throws SQLException + { + + return false; + } + + @Override + public boolean isCurrency(int column) throws SQLException + { + + return false; + } + + @Override + public boolean isCaseSensitive(int column) throws SQLException + { + + return false; + } + + @Override + public boolean isAutoIncrement(int column) throws SQLException + { + + return false; + } + + @Override + public String getTableName(int column) throws SQLException + { + + return null; + } + + @Override + public String getSchemaName(int column) throws SQLException + { + + return null; + } + + @Override + public int getScale(int column) throws SQLException + { + + return 0; + } + + @Override + public int getPrecision(int column) throws SQLException + { + + return 0; + } + + @Override + public String getColumnTypeName(int column) throws SQLException + { + if(column == 1) + { + return "bigint"; + } + if(column == 2) + { + return "float8"; + } + if(column == 3) + { + return "float4"; + } + if(column == 4) + { + return "date"; + } + if(column == 5) + { + return "timestamp"; + } + if(column == 6) + { + return "timestamptz"; + } + if(column ==7) + { + return "bool"; + } + return null; + } + + @Override + public int getColumnType(int column) throws SQLException + { + if(column == 1) + { + return Types.BIGINT; + } + if(column == 2) + { + return Types.BOOLEAN; + } + if(column == 3) + { + return Types.NUMERIC; + } + if(column == 4) + { + return Types.DATE; + } + if(column == 5) + { + return Types.TIMESTAMP_WITH_TIMEZONE; + } + if(column == 6) + { + return Types.CLOB; + } + if(column ==7) + { + return Types.INTEGER; + } + return 0; + } + + @Override + public String getColumnName(int column) throws SQLException + { + if(column == 1) + { + return "Col1"; + } + if(column == 2) + { + return "Col2"; + } + if(column == 3) + { + return "Col3"; + } + if(column == 4) + { + return "Col4"; + } + if(column == 5) + { + return "Col5"; + } + if(column == 6) + { + return "Col6"; + } + if(column ==7) + { + return "Col7"; + } + return null; + } + + @Override + public String getColumnLabel(int column) throws SQLException + { + + return null; + } + + @Override + public int getColumnDisplaySize(int column) throws SQLException + { + + return 0; + } + + @Override + public int getColumnCount() throws SQLException + { + + return 7; + } + + @Override + public String getColumnClassName(int column) throws SQLException + { + + return null; + } + + @Override + public String getCatalogName(int column) throws SQLException + { + + return null; + } +} + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/AutoSuggestTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/AutoSuggestTest.java new file mode 100644 index 0000000000000000000000000000000000000000..142a98abf03f11fb1adf4abcd7a7c1ea9b823032 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/AutoSuggestTest.java @@ -0,0 +1,1540 @@ +package org.opengauss.mppdbide.test.presentation.properties; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.SortedMap; +import static org.junit.Assert.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.contentassist.ContentAssistKeywords; +import org.opengauss.mppdbide.bl.contentassist.ContentAssistProcesserData; +import org.opengauss.mppdbide.bl.keyword.KeywordObject; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DatabaseUtils; +import org.opengauss.mppdbide.bl.serverdatacache.DebugObjects; +import org.opengauss.mppdbide.bl.serverdatacache.ForeignTable; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.PartitionTable; +import org.opengauss.mppdbide.bl.serverdatacache.SequenceMetadata; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TypeMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.UserNamespace; +import org.opengauss.mppdbide.bl.serverdatacache.ViewColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.presentation.autorefresh.AutoRefreshQueryFormation; +import org.opengauss.mppdbide.presentation.autorefresh.RefreshObjectDetails; +import org.opengauss.mppdbide.presentation.contentassistprocesser.ContentAssistProcesserCore; +import org.opengauss.mppdbide.presentation.view.ViewViewDataCore; +import org.opengauss.mppdbide.test.presentation.table.MockPresentationBLPreferenceImpl; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import org.opengauss.mppdbide.utils.files.FileValidationUtils; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; +import com.mockrunner.mock.jdbc.MockResultSet; + +public class AutoSuggestTest extends BasicJDBCTestCaseAdapter +{ + + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + ContentAssistProcesserCore core; + ContentAssistProcesserCore core1; + ContentAssistProcesserData data; + Database database; + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#setUp() + */ + @Before + public void setUp() throws Exception + { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + connection = new MockConnection(); + // test for logging + MPPDBIDELoggerUtility.setArgs(new String[] {"-logfolder=.", "-detailLogging=true"}); + + // MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + preparedstatementHandler = connection.getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + + connProfCache = DBConnProfCache.getInstance(); + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + // serverInfo.setSslPassword("12345"); + // serverInfo.setServerType(DATABASETYPE.GAUSS); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + database = connProfCache.getDbForProfileId(profileId); + core = new ContentAssistProcesserCore(database); + core1 = new ContentAssistProcesserCore(null); + data = new ContentAssistProcesserData(database); + getAllDatabaseObjects(); + } + + private void getAllDatabaseObjects() + { + // MockViewUtils.DropView(preparedstatementHandler, "mytestview1"); + try + { + + database.getServer().refresh(); + Namespace ns1 = new UserNamespace(6, "ns1", database); + Namespace ns2 = new UserNamespace(2, "NS1", database); + Namespace ns3 = new UserNamespace(3, "NS2", database); + Namespace ns4 = new UserNamespace(4, "yns2", database); + Namespace ns6 = new UserNamespace(5, "\"NS1\"", database); + Namespace ns7 = new UserNamespace(7, "Namespc", database); + + + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns1); + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns2); + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns3); + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns4); + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns6); + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns7); + + TableMetaData ptab1 = new PartitionTable(ns7); + ns7.addTableToSearchPool(ptab1); + + TableMetaData tbl1 = new TableMetaData(1, "tbl1", ns1, ""); + ColumnMetaData clm = new ColumnMetaData(tbl1, 1, "Col1", new TypeMetaData(11, "Integer", ns3)); + tbl1.addColumn(clm); + TableMetaData tbl2 = new TableMetaData(2, "tbl2", ns1, ""); + ColumnMetaData clm1 = new ColumnMetaData(tbl2, 1, "Col2", null); + tbl2.addColumn(clm1); + TableMetaData tbl3 = new TableMetaData(3, "TBL1", ns1, ""); + ColumnMetaData clm2 = new ColumnMetaData(tbl3, 1, "Col3", null); + tbl3.addColumn(clm2); + + ns1.addTableToSearchPool(tbl1); + ns1.addTableToSearchPool(tbl2); + ns1.addTableToSearchPool(tbl3); + + TableMetaData tbl4 = new TableMetaData(4, "tbl1", ns2, ""); + ColumnMetaData clm3 = new ColumnMetaData(tbl4, 1, "Col4", new TypeMetaData(11, "Integer", ns3)); + tbl4.addColumn(clm3); + TableMetaData tbl5 = new TableMetaData(5, "tbl2", ns2, ""); + ColumnMetaData clm4 = new ColumnMetaData(tbl5, 1, "Col5", null); + tbl5.addColumn(clm4); + TableMetaData tbl6 = new TableMetaData(6, "TBL1", ns2, ""); + ColumnMetaData clm5 = new ColumnMetaData(tbl6, 1, "Col6", null); + tbl6.addColumn(clm5); + TableMetaData tbl7 = new TableMetaData(7, "TBL2", ns2, ""); + ColumnMetaData clm6 = new ColumnMetaData(tbl7, 1, "Col7", null); + tbl7.addColumn(clm6); + TableMetaData tbl110 = new TableMetaData(110, "T}BL1", ns2, ""); + ColumnMetaData clm110 = new ColumnMetaData(tbl110, 1, "Col7", null); + tbl7.addColumn(clm110); + + ViewMetaData view = new ViewMetaData(1, "Yiew1", ns2,ns2.getDatabase()); + ViewColumnMetaData viewCol = new ViewColumnMetaData(view, 2, "viewclm", new TypeMetaData(0, "int", ns2)); + view.getColumns().addItem(viewCol); + + SequenceMetadata seq = new SequenceMetadata(ns2); + seq.setName("seq"); + + ns2.addTableToSearchPool(tbl5); + ns2.addTableToSearchPool(tbl6); + ns2.addTableToSearchPool(tbl7); + ns2.addTableToSearchPool(tbl4); + ns2.addTableToSearchPool(tbl110); + ns2.addView(view); + ns2.addSequence(seq); + database.getSearchPoolManager().addsequenceToSearchPool(seq); + + TableMetaData tbl8 = new TableMetaData(8, "tbl1", ns3, ""); + ColumnMetaData clm8 = new ColumnMetaData(tbl8, 1, "Col8", new TypeMetaData(11, "Integer", ns3)); + tbl8.addColumn(clm8); + TableMetaData tbl9 = new TableMetaData(9, "tbl2", ns3, ""); + ColumnMetaData clm9 = new ColumnMetaData(tbl9, 1, "Col9", null); + tbl9.addColumn(clm9); + + ns3.addTableToSearchPool(tbl8); + ns3.addTableToSearchPool(tbl9); + + TableMetaData tbl10 = new TableMetaData(10, "Tbl11", ns4, ""); + ColumnMetaData clm10 = new ColumnMetaData(tbl10, 1, "Col10", null); + tbl10.addColumn(clm10); + TableMetaData tbl11 = new TableMetaData(11, "xtbl2", ns4, ""); + ColumnMetaData clm11 = new ColumnMetaData(tbl11, 1, "Col11", null); + tbl11.addColumn(clm11); + TableMetaData tbl12 = new TableMetaData(12, "NS1", ns4, ""); + ColumnMetaData clm12 = new ColumnMetaData(tbl12, 1, "Col12", null); + tbl12.addColumn(clm12); + + ns4.addTableToSearchPool(tbl10); + ns4.addTableToSearchPool(tbl11); + ns4.addTableToSearchPool(tbl12); + + TableMetaData tbl14 = new TableMetaData(13, "ybl1", ns6, ""); + ColumnMetaData clm14 = new ColumnMetaData(tbl14, 1, "Col14", null); + tbl14.addColumn(clm14); + + ns6.addTableToSearchPool(tbl14); + + + ForeignTable ForeignTbl = new ForeignTable(ns1, OBJECTTYPE.FOREIGN_TABLE_GDS); + ForeignTbl.setName("Ftable1"); + ForeignTbl.setOid(1); + ns1.addForeignTableToGroup(ForeignTbl); + ns1.addTableToSearchPool(ForeignTbl); + ColumnMetaData fClm10 = new ColumnMetaData(ForeignTbl, 1, "FCol10", null); + ForeignTbl.addColumn(fClm10); + + ForeignTable ForeignTbl2 = new ForeignTable(ns1, OBJECTTYPE.FOREIGN_TABLE_GDS); + ForeignTbl2.setName("Ftable2"); + ForeignTbl.setOid(2); + ns1.addForeignTableToGroup(ForeignTbl2); + ns1.addTableToSearchPool(ForeignTbl2); + ColumnMetaData fClm11 = new ColumnMetaData(ForeignTbl, 1, "FCol11", null); + ForeignTbl2.addColumn(fClm11); + + PartitionTable ptab = new PartitionTable(ns2); + ptab.setName("partTable"); + ptab.setOid(1); + ns2.addTableToGroup(ptab); + ns2.addTableToSearchPool(ptab); + ColumnMetaData pClm11 = new ColumnMetaData(ptab, 1, "PCol11", null); + ptab.addColumn(pClm11); + + PartitionTable ptab11 = new PartitionTable(ns2); + ptab11.setName("partTable1"); + ptab.setOid(2); + ns2.addTableToGroup(ptab11); + ns2.addTableToSearchPool(ptab11); + ColumnMetaData pClm12 = new ColumnMetaData(ptab11, 1, "PCol12", null); + ptab11.addColumn(pClm12); + + + System.out.println(database.getAllNameSpaces()); + + + + /* + * System.out.println(namespaces.size()); for (Namespace namespace : + * namespaces) { + * namespace.getAllObjects(database.getObjBrowserConn()); } + */ + + } + catch (DatabaseOperationException e) + { + + e.printStackTrace(); + } + catch (DatabaseCriticalException e) + { + + e.printStackTrace(); + } + catch (Exception e) + { + + e.printStackTrace(); + } + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception + { + super.tearDown(); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().close(); + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) + { + connProfCache.removeServer(itr.next().getId()); + } + + connProfCache.closeAllNodes(); + + } + + @Test + public void testAutoSuggestForPrefixNull() + { + LinkedHashMap map = core.getContextProposals("", " "); + int noOfNameSpaces = 0; + int noOfTables = 0; + int noOfViews = 0; + int noOfSequences = 0; + int noOfFunctios = 0; + int noOfDatatypes = 0; + int noOfKeywords = 0; + for (ServerObject obj : map.values()) + { + if (obj instanceof Namespace) { + noOfNameSpaces++; + } else if (obj instanceof TableMetaData) { + noOfTables++; + } else if (obj instanceof DebugObjects) { + noOfFunctios++; + } else if (obj instanceof SequenceMetadata) { + noOfSequences++; + } else if (obj instanceof ViewMetaData) { + noOfViews++; + } else if (obj instanceof TypeMetaData) { + noOfDatatypes++; + }else if(obj instanceof KeywordObject){ + noOfKeywords++; + } + } + int sum = noOfNameSpaces + noOfTables + noOfFunctios + noOfViews + + noOfSequences+noOfDatatypes+noOfKeywords; + assertEquals(map.size(), sum); + } + + @Test + public void testAutoSuggestForPrefix1() + { + LinkedHashMap map = core.getContextProposals("y", + "select * from y"); + for (ServerObject obj : map.values()) + { + if (obj instanceof Namespace) + { + assertEquals("yns2", obj.getName()); + } + else if (obj instanceof TableMetaData) + { + assertEquals("ybl1", obj.getName()); + } + else if (obj instanceof ViewMetaData) + { + assertEquals("Yiew1", obj.getName()); + } + } + assertEquals(5, map.size()); + + } + + @Test + public void testAutoSuggestForPrefix2() + { + LinkedHashMap map = core.getContextProposals("\"NS\"", + "select * from \"NS\""); + for (ServerObject obj : map.values()) + { + if (obj instanceof Namespace) + { + assertTrue(obj.getName().equals("ns1") + || obj.getName().equals("NS1") + || obj.getName().equals("NS2")); + ; + } + else if (obj instanceof TableMetaData) + { + assertEquals("NS1", obj.getName()); + } + } + assertEquals(4, map.size()); + } + + @Test + public void testAutoSuggestForPrefix3() + { + LinkedHashMap map = core + .getContextProposals("\"NS1\"", "select * from \"NS1\""); + for (ServerObject obj : map.values()) + { + if (obj instanceof Namespace) + { + assertTrue(obj.getName().equals("ns1") + || obj.getName().equals("NS1")); + } + else if (obj instanceof TableMetaData) + { + assertEquals("NS1", obj.getName()); + } + } + assertEquals(3, map.size()); + } + + @Test + public void testAutoSuggestForPrefix4() + { + LinkedHashMap map = core + .getContextProposals("\"NS1\".", "select * from \"NS1\"."); + // try{ + Namespace ns; + try + { + ns = database.getNameSpaceById(2); + for (ServerObject obj : map.values()) + { + if (obj instanceof TableMetaData) + { + TableMetaData tbl = (TableMetaData) obj; + Namespace ns1 = (Namespace) tbl.getParent(); + assertEquals(ns.getName(), ns1.getName()); + } + else if (obj instanceof SequenceMetadata) + { + SequenceMetadata seq = (SequenceMetadata) obj; + Namespace ns1 = (Namespace) seq.getParent(); + assertEquals(ns.getName(), ns1.getName()); + } + else if (obj instanceof ViewMetaData) + { + ViewMetaData view = (ViewMetaData) obj; + Namespace ns1 = (Namespace) view.getParent(); + assertEquals(ns.getName(), ns1.getName()); + } + else if (obj instanceof ColumnMetaData) + { + ColumnMetaData clm = (ColumnMetaData) obj; + TableMetaData tbl = (TableMetaData) clm.getParent(); + assertEquals("NS1", tbl.getName()); + } + } + assertEquals(10, map.size()); + } + catch (DatabaseOperationException e) + { + + e.printStackTrace(); + } + } + + @Test + public void testAutoSuggestForPrefix5() + { + LinkedHashMap map = core.getContextProposals( + "\"NS1\".\"TBL\"", "select * from \"NS1\".\"TBL\""); + for (ServerObject obj : map.values()) + { + assertTrue(obj.getName().startsWith("TBL") + || obj.getName().startsWith("tbl")); + } + assertEquals(4, map.size()); + } + + @Test + public void testAutoSuggestForPrefix6() + { + LinkedHashMap map = core.getContextProposals( + "\"NS1\".\"TBL1\"", "select * from \"NS1\".\"TBL1\""); + for (ServerObject obj : map.values()) + { + assertTrue(obj.getName().startsWith("TBL1") + || obj.getName().startsWith("tbl1")); + } + assertEquals(2, map.size()); + } + + @Test + public void testAutoSuggestForPrefix7() + { + LinkedHashMap map = core.getContextProposals( + "\"NS1\".\"TBL1\".", "select * from \"NS1\".\"TBL1\"."); + for (ServerObject obj : map.values()) + { + if (obj instanceof ColumnMetaData) + { + TableMetaData tbl = (TableMetaData) obj.getParent(); + Namespace ns = (Namespace) tbl.getParent(); + assertTrue(tbl.getName().equals("TBL1")); + assertTrue(ns.getName().equals("NS1")); + } + } + assertEquals(1, map.size()); + } + + @Test + public void testAutoSuggestForPrefix8() + { + String[] name = {"Yiew1"}; + LinkedHashMap map = data + .findExactMatchingObjects(name); + + for (ServerObject obj : map.values()) + { + if (obj instanceof ViewMetaData) + { + Namespace ns = (Namespace) obj.getParent(); + assertTrue(ns.getName().equals("NS1")); + } + } + assertEquals(1, map.size()); + } + + @Test + public void testAutoSuggestForNull() + { + if (core != null) + { + core.autoSuggectForNullPrefix(); + core.getCurrentPrefix(); + core.getReplaceLength(); + } + assertFalse(core.isAnyNonLoadedObject()); + } + + @Test + public void testTableTableNameSpace() { + try { + Namespace ns = database.getNameSpaceById(1); + TableMetaData tableMetaData = new TableMetaData(1, "t1", ns, null); + ns.addTableToGroup(tableMetaData); + ns.addTableToSearchPool(tableMetaData); + + + String query ="select spcname from pg_class as class " + + "left join pg_tablespace as tablespace" + + " on class.reltablespace=tablespace.oid where class.oid=1"; + + String stardandTsName = "ts_1"; + MockResultSet queryRS = preparedstatementHandler.createResultSet(); + queryRS.addColumn("spcname"); + queryRS.addRow(new Object[] {stardandTsName}); + preparedstatementHandler.prepareResultSet(query, queryRS); + String tsName = tableMetaData.getTablespaceForTable(null); + assertEquals(tsName, stardandTsName); + } catch (MPPDBIDEException e) { + fail("can\'t run here"); + } + } + + @Test + public void testTableTableNameSpaceQueryDefault() { + try { + Namespace ns = database.getNameSpaceById(1); + TableMetaData tableMetaData = new TableMetaData(1, "t1", ns, null); + ns.addTableToGroup(tableMetaData); + ns.addTableToSearchPool(tableMetaData); + + + String query ="select spcname from pg_class as class " + + "left join pg_tablespace as tablespace" + + " on class.reltablespace=tablespace.oid where class.oid=1"; + + MockResultSet queryRS = preparedstatementHandler.createResultSet(); + queryRS.addColumn("spcname"); + preparedstatementHandler.prepareResultSet(query, queryRS); + String tsName = tableMetaData.getTablespaceForTable(null); + assertEquals(tsName, ""); + } catch (MPPDBIDEException e) { + fail("can\'t run here"); + } + } + + @Test + public void testTableTableNameSpaceWithConnection() { + try { + Namespace ns = database.getNameSpaceById(1); + TableMetaData tableMetaData = new TableMetaData(1, "t1", ns, null); + ns.addTableToGroup(tableMetaData); + ns.addTableToSearchPool(tableMetaData); + + + String query ="select spcname from pg_class as class " + + "left join pg_tablespace as tablespace" + + " on class.reltablespace=tablespace.oid where class.oid=1"; + + String stardandTsName = "ts_1"; + MockResultSet queryRS = preparedstatementHandler.createResultSet(); + queryRS.addColumn("spcname"); + queryRS.addRow(new Object[] {stardandTsName}); + preparedstatementHandler.prepareResultSet(query, queryRS); + DBConnection connection = database.getConnectionManager().getFreeConnection(); + String tsName = tableMetaData.getTablespaceForTable(connection); + assertEquals(tsName, stardandTsName); + } catch (MPPDBIDEException e) { + fail("can\'t run here"); + } + } + @Test + public void testAutoSuggestForPrefixSpecialCharacter() + { + LinkedHashMap map = core.getContextProposals( + "\"NS1\".\"T}BL1\".", "select * from \"NS1\".\"T}BL1\"."); + assertEquals(0, map.size()); + } + + @Test + public void testAutoSuggestForNonLoaded() + { + CommonLLTUtils.createTableRS(preparedstatementHandler); + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getConstaraintForTableRSEx(preparedstatementHandler); + CommonLLTUtils.getIndexcCOnstaByNamespace(preparedstatementHandler); + CommonLLTUtils.fetchAllSynonyms(preparedstatementHandler); + + String getShallowDebuggableQRYOnDemand = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs, pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod, pr.proretset retset, lng.lanname lang FROM pg_proc pr JOIN pg_language lng ON lng.oid=prolang WHERE lng.lanname in ('plpgsql','sql','c') and has_function_privilege(pr.oid, 'EXECUTE') and pr.pronamespace= 1 ORDER BY objname"; + MockResultSet shallowDbgObjOnDmd = preparedstatementHandler + .createResultSet(); + shallowDbgObjOnDmd.addColumn("oid"); + shallowDbgObjOnDmd.addColumn("objname"); + shallowDbgObjOnDmd.addColumn("namespace"); + shallowDbgObjOnDmd.addColumn("ret"); + shallowDbgObjOnDmd.addColumn("alltype"); + shallowDbgObjOnDmd.addColumn("nargs"); + shallowDbgObjOnDmd.addColumn("argtype"); + shallowDbgObjOnDmd.addColumn("argname"); + shallowDbgObjOnDmd.addColumn("argmod"); + shallowDbgObjOnDmd.addColumn("retset"); + shallowDbgObjOnDmd.addColumn("lang"); + shallowDbgObjOnDmd.addRow(new Object[] {1, "auto1", 1, 23, null, 1, + null, null, null, 'f', "plpgsql"}); + preparedstatementHandler.prepareResultSet( + getShallowDebuggableQRYOnDemand, shallowDbgObjOnDmd); + + String refreshAllMetadataInNamespaceOnDemandQRY = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions from pg_class tbl left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relkind in ('r','v','f') and tbl.parttype in ('n', 'p', 'v') and tbl.relnamespace = 1"; + MockResultSet refereshInNmspcOnDmd = preparedstatementHandler + .createResultSet(); + refereshInNmspcOnDmd.addColumn("oid"); + refereshInNmspcOnDmd.addColumn("relname"); + refereshInNmspcOnDmd.addColumn("relnamespace"); + refereshInNmspcOnDmd.addColumn("relkind"); + refereshInNmspcOnDmd.addColumn("parttype"); + refereshInNmspcOnDmd.addColumn("foptions"); + refereshInNmspcOnDmd + .addRow(new Object[] {1, "pg_type", 1, 'r', 'n', null}); + refereshInNmspcOnDmd + .addRow(new Object[] {1, "pg_type", 1, 'v', 'n', null}); + preparedstatementHandler.prepareResultSet( + refreshAllMetadataInNamespaceOnDemandQRY, refereshInNmspcOnDmd); + try + { + database.getNameSpaceById(1); + + LinkedHashMap map = core.getContextProposals( + "\"pg_catalog\".", "select * from \"pg_catalog\"."); + assertEquals(0, map.size()); + LinkedHashMap mapLoaded = core + .findNonLoadedDatabaseObjectsOnDemand( + database.getConnectionManager().getFreeConnection()); + assertEquals(6, mapLoaded.size()); + } + catch (DatabaseOperationException e) + { + fail("Not Excepted to come here"); + } + catch (MPPDBIDEException e) + { + + fail("Not Excepted to come here"); + } + } + + @Test + public void testAutoSuggestForNonLoadedChild() + { + + CommonLLTUtils.createTableRS(preparedstatementHandler); + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getConstaraintForTableRSEx(preparedstatementHandler); + CommonLLTUtils.getIndexcCOnstaByNamespace(preparedstatementHandler); + + String getShallowDebuggableQRYOnDemand = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs, pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod, pr.proretset retset, lng.lanname lang FROM pg_proc pr JOIN pg_language lng ON lng.oid=prolang WHERE lng.lanname in ('plpgsql','sql') and has_function_privilege(pr.oid, 'EXECUTE') and pr.pronamespace= 1 ORDER BY objname"; + MockResultSet shallowDbgObjOnDmd = preparedstatementHandler + .createResultSet(); + shallowDbgObjOnDmd.addColumn("oid"); + shallowDbgObjOnDmd.addColumn("objname"); + shallowDbgObjOnDmd.addColumn("namespace"); + shallowDbgObjOnDmd.addColumn("ret"); + shallowDbgObjOnDmd.addColumn("alltype"); + shallowDbgObjOnDmd.addColumn("nargs"); + shallowDbgObjOnDmd.addColumn("argtype"); + shallowDbgObjOnDmd.addColumn("argname"); + shallowDbgObjOnDmd.addColumn("argmod"); + shallowDbgObjOnDmd.addColumn("retset"); + shallowDbgObjOnDmd.addColumn("lang"); + shallowDbgObjOnDmd.addRow(new Object[] {1, "auto1", 1, 23, null, 1, + null, null, null, 'f', "plpgsql"}); + preparedstatementHandler.prepareResultSet( + getShallowDebuggableQRYOnDemand, shallowDbgObjOnDmd); + + String refreshAllMetadataInNamespaceOnDemandQRY = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions from pg_class tbl left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relkind in ('r','v','f') and tbl.parttype in ('n', 'p', 'v') and tbl.relnamespace = 1"; + MockResultSet refereshInNmspcOnDmd = preparedstatementHandler + .createResultSet(); + refereshInNmspcOnDmd.addColumn("oid"); + refereshInNmspcOnDmd.addColumn("relname"); + refereshInNmspcOnDmd.addColumn("relnamespace"); + refereshInNmspcOnDmd.addColumn("relkind"); + refereshInNmspcOnDmd.addColumn("parttype"); + refereshInNmspcOnDmd.addColumn("foptions"); + refereshInNmspcOnDmd + .addRow(new Object[] {1, "pg_type", 1, 'r', 'n', null}); + refereshInNmspcOnDmd + .addRow(new Object[] {1, "pg_type", 1, 'v', 'n', null}); + preparedstatementHandler.prepareResultSet( + refreshAllMetadataInNamespaceOnDemandQRY, refereshInNmspcOnDmd); + try + { + LinkedHashMap map = core.getContextProposals( + "\"pg_am\".", "select * from \"pg_am\"."); + assertEquals(0, map.size()); + LinkedHashMap mapLoaded = core + .findNonLoadedDatabaseObjectsOnDemand( + database.getConnectionManager().getFreeConnection()); + assertEquals(0, mapLoaded.size()); + } + catch (DatabaseOperationException e) + { + fail("Not Excepted to come here"); + } + catch (MPPDBIDEException e) + { + + fail("Not Excepted to come here"); + } + + } + + @Test + public void testAutoSuggestForDisconnectedDB() + { + DBConnProfCache.getInstance().destroyConnection(database); + LinkedHashMap map = core + .getContextProposals("\"pg_am\".", "select * from \"pg_am\". "); + assertEquals(0, map.size()); + } + + @Test + public void testAutoSuggestForPrefixPartitionTable() + { + LinkedHashMap map = core.getContextProposals("notable", + "select * from Namespc"); + for (ServerObject obj : map.values()) + { + if (obj instanceof PartitionTable) + { + assertEquals("notablename", obj.getName()); + } + } + assertEquals(1, map.size()); + + } + + @Test + public void testAutoSuggestForNullPrefixPartitionTable() + { + LinkedHashMap map = core.getContextProposals(null, + "select * from Namespc"); + assertTrue(!map.isEmpty()); + + } + + @Test + public void testAutoSuggestFindString() + { + String prefix=core.findString("Select * from tab", DatabaseUtils.getCharacterList(database)); + assertEquals("tab", prefix); + + } + + @Test + public void testAutoSuggestFindString1() + { + String prefix=core.findString("Select * from tab.", DatabaseUtils.getCharacterList(database)); + assertEquals("tab.", prefix); + + prefix=core.findString("Select * from \"tab\"", DatabaseUtils.getCharacterList(database)); + assertEquals("\"tab\"", prefix); + + prefix=core.findString("\"tab\"", DatabaseUtils.getCharacterList(database)); + assertEquals("\"tab\"", prefix); + + prefix=core.findString("\"\\\"tab\"", DatabaseUtils.getCharacterList(database)); + assertEquals("\"\\\"tab\"", prefix); + + prefix=core.findString("Select * from \n", DatabaseUtils.getCharacterList(database)); + assertEquals("", prefix); + + prefix=core.findString("Insert into tab(", DatabaseUtils.getCharacterList(database)); + assertEquals("tab", prefix); + + prefix=core.findString("Insert into tab(c1,", DatabaseUtils.getCharacterList(database)); + assertEquals("tab", prefix); + + prefix=core.findString("Select into tab(c1,", DatabaseUtils.getCharacterList(database)); + assertEquals("", prefix); + + prefix=core.findString("Select into tab(c1,c2) ,", DatabaseUtils.getCharacterList(database)); + assertEquals("", prefix); + + prefix=core.findString("Insert into tab(c", DatabaseUtils.getCharacterList(database)); + assertEquals("tab.c", prefix); + + prefix=core.findString("Insert into tab(c1,c2", DatabaseUtils.getCharacterList(database)); + assertEquals("tab.c2", prefix); + + String st = "qwertyuiopasdfghjklzxcvbnmqwreeewurqwyetrytqwerqwerqyweryqtwerytqwertyqwerqytwetr" + + "hsdghfgsdhfgshdfgshdddfdgjfhgsdjfhghsdgfhsgdddfsjdgfhkajsdfgjasdfgjhhhfgsjdgfalsjdgfjhasgdjfgsjdgksjjjjjjjjfgkajsdgfakjsdfgajsdgfhjdgfasjldfgajksdgfhaaafghagsdfjaaaafgjagsfjghjasdfgaafgjaaafgaagau7234587134gsdgfcvgjhsdgfjhfghdcvnbzxxxxxxvfguyyyyyrtyudsfvgajksdgsfhgwe73472345hjfggghsdfhadfakjsdfgajsgdfgasdfakjsdgfmxzc,bxxxxvhjjjfgeiurt2873445689134589ISDHFUASKGDGAHSGDGHASDJKGFAKDFGGJHHFGAKDFGADUFQ9WOEUIWEOYEQORYGIVBBBBasdjhgakjdfgakjdfgadjkfgjdfggsdkfjg"; + prefix = core.findString(st, DatabaseUtils.getCharacterList(database)); + assertTrue(!prefix.isEmpty()); + + } + + @Test + public void testAutoSuggestFindAllChildObjectsForeignTab() { + String[] name = {"Ftable1"}; + LinkedHashMap map = data.findExactMatchingObjects(name); + assertEquals(1, map.size()); + + LinkedHashMap map1 = core.getContextProposals("\"Ftable1\".FCo", + "select * from Ftable1.FCo"); + assertEquals(1, map1.size()); + + LinkedHashMap map3 = core.getContextProposals("ns1.\"Ftable1\".", + "select * from Ftable1.FCo"); + assertEquals(1, map3.size()); + + LinkedHashMap map4 = core.getContextProposals("\"Ftable1\".\"FCol10\".", + "select * from Ftable1.FCo"); + assertEquals(0, map4.size()); + + } + + @Test + public void testAutoSuggestFindAllChildObjectsForPartTable() { + String[] name = {"partTable1"}; + LinkedHashMap map = data.findExactMatchingObjects(name); + assertEquals(1, map.size()); + + LinkedHashMap map1 = core.getContextProposals("\"partTable1\".PCo", + "select * from partTable1.PCo"); + assertEquals(1, map1.size()); + + LinkedHashMap map3 = core.getContextProposals("\"NS1\".\"partTable1\".", + "select * from Ftable1.FCo"); + assertEquals(1, map3.size()); + + LinkedHashMap map4 = core.getContextProposals("\"partTable1\".\"PCol11\".", + "select * from partTable1.PCo"); + assertEquals(0, map4.size()); + } + + @Test + public void testAutoSuggestFindAllChildObjectsForView() { + String[] name = {"Yiew1"}; + LinkedHashMap map = data.findExactMatchingObjects(name); + assertEquals(1, map.size()); + + LinkedHashMap map1 = core.getContextProposals("\"Yiew1\".viewc", + "select * from partTable1.PCo"); + assertEquals(1, map1.size()); + + LinkedHashMap map3 = core.getContextProposals("\"NS1\".\"Yiew1\".", + "select * from partTable1.PCo"); + assertEquals(1, map3.size()); + + LinkedHashMap map4 = core.getContextProposals("\"Yiew1\".viewclm.", + "select * from partTable1.PCo"); + assertEquals(0, map4.size()); + } + + + + @Test + public void testAutoSuggestFindAllChildObjectsForSeq() { + String[] name = {"seq"}; + LinkedHashMap map = data.findExactMatchingObjects(name); + assertEquals(0, map.size()); + + } + + @Test + public void testAutoSuggestFindAllChildObjectsForDebugObj() { + String[] name = {"add"}; + LinkedHashMap map = data.findExactMatchingObjects(name); + assertEquals(0, map.size()); + + } + + @Test + public void testInsertAutoSuggestFindColumnsForTable() { + String prefix=core.findString("Insert into tbl1(", DatabaseUtils.getCharacterList(database)); + LinkedHashMap map1 = core.getContextProposals(prefix, + "select * from partTable1.PCo"); + assertTrue(map1.size() > 0); + + } + + @Test + public void testInsertAutoSuggestFindColumnsForView() { + String prefix=core.findString("Insert into \"Yiew1\"(", DatabaseUtils.getCharacterList(database)); + LinkedHashMap map1 = core.getContextProposals(prefix, + "select * from partTable1.PCo"); + assertEquals(1, map1.size()); + String[] str=data.getContentAssistUtil().getPrefixHyperLink("ns1.tbl"); + assertEquals(2,str.length); + str=data.getContentAssistUtil().getPrefixHyperLink("\"Ns1\".tbl"); + assertEquals(2,str.length); + str=data.getContentAssistUtil().getPrefixHyperLink("\"N\"\"s1\".tbl"); + assertEquals(2,str.length); + + } + + @Test + public void testAutoSuggestForDbNull() { + String prefix=core1.findString("select * from tab", DatabaseUtils.getCharacterList(null)); + assertEquals("tab",prefix); + + prefix=core1.findString("", DatabaseUtils.getCharacterList(null)); + assertNull(prefix); + + prefix=core1.findString("insert into tab(", DatabaseUtils.getCharacterList(null)); + assertEquals("tab(",prefix); + + ContentAssistProcesserData contentData = new ContentAssistProcesserData(null); + String[] strArray = contentData.getContentAssistUtil().getPrefixHyperLink("sel"); + assertTrue(strArray!=null); + + LinkedHashMap map1 = core1.getContextProposals(prefix, + "select * from partTable1.PCo"); + int noOfObjects=0; + for (ServerObject obj : map1.values()) + { + if (obj instanceof KeywordObject) + { + assertEquals("TABLE", obj.getName()); + noOfObjects++; + } + } + assertEquals(map1.size(),noOfObjects); + + LinkedHashMap map2 = core1.getContextProposals("TAB.", + "select * from partTable1.PCo"); + + assertEquals(0,map2.size()); + + } + + @Test + public void testAutoSuggestForNonLoadedTable() { + + try { + + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getConstaraintForTableRS(preparedstatementHandler); + CommonLLTUtils.getIndexForTableRS(preparedstatementHandler); + CommonLLTUtils.fetchColumnMetaDataRS(preparedstatementHandler); + Namespace ns = database.getNameSpaceById(1); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", ns, "tablespace"); + ns.addTableToGroup(tablemetaData); + ns.addTableToSearchPool(tablemetaData); + + core.getContextProposals("\"Table1\".", "select * from partTable1.PCo"); + LinkedHashMap map2 = core + .findNonLoadedDatabaseObjectsOnDemand(database.getConnectionManager().getFreeConnection()); + assertEquals(1, map2.size()); + + } catch (MPPDBIDEException e) { + fail("Not expected to come here"); + } + + } + + @Test + public void testAutoSuggestForNonLoadedForeignTable() { + + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getConstaraintForTableRS(preparedstatementHandler); + CommonLLTUtils.getIndexForTableRS(preparedstatementHandler); + CommonLLTUtils.fetchColumnMetaDataRS(preparedstatementHandler); + try { + Namespace ns = database.getNameSpaceById(1); + + ForeignTable ForeignTbl = new ForeignTable(ns, OBJECTTYPE.FOREIGN_TABLE_GDS); + ForeignTbl.setName("FTable1"); + ForeignTbl.setOid(1); + ns.addForeignTableToGroup(ForeignTbl); + ns.addTableToSearchPool(ForeignTbl); + + core.getContextProposals("\"FTable1\".", "select * from partTable1.PCo"); + LinkedHashMap map2 = core + .findNonLoadedDatabaseObjectsOnDemand(database.getConnectionManager().getFreeConnection()); + assertEquals(1, map2.size()); + } catch (MPPDBIDEException e) { + fail("Not expected to come here"); + } + + } + + @Test + public void testAutoSuggestForNonLoadedPartTable() { + + try { + Namespace ns = database.getNameSpaceById(1); + PartitionTable ptab = new PartitionTable(ns); + ptab.setName("partTable"); + ptab.setOid(1); + ns.addTableToGroup(ptab); + ns.addTableToSearchPool(ptab); + + MockResultSet getcolumninfoRSptble_1 = preparedstatementHandler + .createResultSet(); + getcolumninfoRSptble_1.addColumn("tableid"); + getcolumninfoRSptble_1.addColumn("namespaceid"); + getcolumninfoRSptble_1.addColumn("columnidx"); + getcolumninfoRSptble_1.addColumn("name"); + getcolumninfoRSptble_1.addColumn("datatypeoid"); + getcolumninfoRSptble_1.addColumn("dtns"); + getcolumninfoRSptble_1.addColumn("length"); + getcolumninfoRSptble_1.addColumn("precision"); + getcolumninfoRSptble_1.addColumn("dimentions"); + getcolumninfoRSptble_1.addColumn("notnull"); + getcolumninfoRSptble_1.addColumn("isdefaultvalueavailable"); + getcolumninfoRSptble_1.addColumn("default_value"); + getcolumninfoRSptble_1.addColumn("attDefStr"); + getcolumninfoRSptble_1.addColumn("displayColumns"); + getcolumninfoRSptble_1 + .addRow(new Object[] {1, 1, 1, "ColName", 1, 1, 200, 0, 0, + false, true, "Default value", "attrString", "bigint"}); + preparedstatementHandler.prepareResultSet( + "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.parttype in ('p', 'v')) left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and t.oid = 2 and t.relkind <> 'i' order by c.attnum;", + getcolumninfoRSptble_1); + + preparedstatementHandler.prepareResultSet( + "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.parttype in ('p', 'v')) left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and t.oid = 1 and t.relkind <> 'i' order by c.attnum;", + getcolumninfoRSptble_1); + + MockResultSet partitionConstraintRS = preparedstatementHandler + .createResultSet(); + partitionConstraintRS.addColumn("constraintid"); + partitionConstraintRS.addColumn("tableid"); + partitionConstraintRS.addColumn("namespaceid"); + partitionConstraintRS.addColumn("constraintname"); + partitionConstraintRS.addColumn("constrainttype"); + partitionConstraintRS.addColumn("deferrable"); + partitionConstraintRS.addColumn("deferred"); + partitionConstraintRS.addColumn("validate"); + partitionConstraintRS.addColumn("indexid"); + partitionConstraintRS.addColumn("fkeytableId"); + partitionConstraintRS.addColumn("updatetype"); + partitionConstraintRS.addColumn("deletetype"); + partitionConstraintRS.addColumn("matchtype"); + partitionConstraintRS.addColumn("expr"); + partitionConstraintRS.addColumn("columnlist"); + partitionConstraintRS.addColumn("fkeycolumnlist"); + partitionConstraintRS.addColumn("const_def"); + partitionConstraintRS.addRow(new Object[] {1, 1, 1, "ConstraintName", + "ConstraintType", false, false, false, 1, 1, "", "", "", "", + "1", "1", ""}); + preparedstatementHandler.prepareResultSet( + "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c join pg_class cl on c.conrelid = cl.oid where c.conrelid=2 and cl.parttype in ('p','v') and c.conrelid <> 0;", + partitionConstraintRS); + preparedstatementHandler.prepareResultSet("SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c join pg_class cl on c.conrelid = cl.oid where c.conrelid=1 and cl.parttype in ('p','v') and c.conrelid <> 0;", partitionConstraintRS); + + + MockResultSet indexRS = preparedstatementHandler + .createResultSet(); + indexRS.addColumn("oid"); + indexRS.addColumn("tableId"); + indexRS.addColumn("indexname"); + indexRS.addColumn("namespaceid"); + indexRS.addColumn("accessmethodid"); + indexRS.addColumn("isunique"); + indexRS.addColumn("isprimary"); + indexRS.addColumn("isexclusion"); + indexRS.addColumn("isimmediate"); + indexRS.addColumn("isclustered"); + indexRS.addColumn("checkmin"); + indexRS.addColumn("isready"); + indexRS.addColumn("cols"); + indexRS.addColumn("reloptions"); + indexRS.addColumn("indexdef"); + indexRS.addColumn("tablespace"); + indexRS.addRow(new Object[] {1, 1, "IndexName", 1, 1, true, false, + false, false, false, false, false, "1", "", "", ""}); + preparedstatementHandler.prepareResultSet( + "SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, ci.relnamespace as namespaceid, ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, i.indisexclusion as isexclusion, i.indimmediate as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, i.indisready as isready, i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions, def.indexdef, def.tablespace FROM pg_index i LEFT JOIN pg_class t on (t.oid = i.indrelid) LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) LEFT JOIN pg_namespace ns on (ci.relnamespace = ns.oid) LEFT JOIN pg_indexes def on (ci.relname = def.indexname and ns.nspname = def.schemaname) WHERE t.relkind in ('r', 'f', 'I') and ci.parttype in ('p','n') and ci.relnamespace = 2 and tableid= 2;", indexRS); + + preparedstatementHandler.prepareResultSet( + "SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, ci.relnamespace as namespaceid, ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, i.indisexclusion as isexclusion, i.indimmediate as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, i.indisready as isready, i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions, def.indexdef, def.tablespace FROM pg_index i LEFT JOIN pg_class t on (t.oid = i.indrelid) LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) LEFT JOIN pg_namespace ns on (ci.relnamespace = ns.oid) LEFT JOIN pg_indexes def on (ci.relname = def.indexname and ns.nspname = def.schemaname) WHERE t.relkind in ('r', 'f', 'I') and ci.parttype in ('p','n') and ci.relnamespace = 1 and tableid= 1;", indexRS); MockResultSet getPartitionsRS_1 = preparedstatementHandler + .createResultSet(); + getPartitionsRS_1.addColumn("partition_id"); + getPartitionsRS_1.addColumn("partition_name"); + getPartitionsRS_1.addColumn("partition_type"); + getPartitionsRS_1.addColumn("table_id"); + + getPartitionsRS_1.addRow(new Object[] {1, "part_1", "r", 1}); + preparedstatementHandler.prepareResultSet("select p.oid AS partition_id , p.relname AS partition_name, p.partstrategy as partition_type, p.parentid AS table_id from pg_class c, pg_partition p where c.oid = 2 and c.parttype = 'p' and p.parentid = c.oid and p.parttype = 'p' order by p.boundaries;", + getPartitionsRS_1); + preparedstatementHandler.prepareResultSet("select p.oid AS partition_id , p.relname AS partition_name, p.partstrategy as partition_type, p.parentid AS table_id from pg_class c, pg_partition p where c.oid = 1 and c.parttype = 'p' and p.parentid = c.oid and p.parttype = 'p' order by p.boundaries;", + getPartitionsRS_1); + core.getContextProposals("\"partTable\".", "select * from partTable1.PCo"); + LinkedHashMap map2; + + map2 = core + .findNonLoadedDatabaseObjectsOnDemand(database.getConnectionManager().getFreeConnection()); + assertEquals(2, map2.size()); + } catch (MPPDBIDEException e) { + fail("Not expected to come here"); + } + + + } + + + + @Test + public void testAutoSuggestForNonLoadedPartTable1() { + + try { + Namespace ns = database.getNameSpaceById(1); + PartitionTable ptab = new PartitionTable(ns); + ptab.setName("partTable"); + ptab.setOid(1); + ns.addTableToGroup(ptab); + ns.addTableToSearchPool(ptab); + + MockResultSet getcolumninfoRSptble_1 = preparedstatementHandler + .createResultSet(); + getcolumninfoRSptble_1.addColumn("tableid"); + getcolumninfoRSptble_1.addColumn("namespaceid"); + getcolumninfoRSptble_1.addColumn("columnidx"); + getcolumninfoRSptble_1.addColumn("name"); + getcolumninfoRSptble_1.addColumn("datatypeoid"); + getcolumninfoRSptble_1.addColumn("dtns"); + getcolumninfoRSptble_1.addColumn("length"); + getcolumninfoRSptble_1.addColumn("precision"); + getcolumninfoRSptble_1.addColumn("dimentions"); + getcolumninfoRSptble_1.addColumn("notnull"); + getcolumninfoRSptble_1.addColumn("isdefaultvalueavailable"); + getcolumninfoRSptble_1.addColumn("default_value"); + getcolumninfoRSptble_1.addColumn("attDefStr"); + getcolumninfoRSptble_1.addColumn("displayColumns"); + getcolumninfoRSptble_1 + .addRow(new Object[] {1, 1, 1, "ColName", 1, 1, 200, 0, 0, + false, true, "Default value", "attrString", "bigint"}); + preparedstatementHandler.prepareResultSet( + "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.parttype in ('p', 'v')) left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and t.oid = 2 and t.relkind <> 'i' order by c.attnum;", + getcolumninfoRSptble_1); + + preparedstatementHandler.prepareResultSet( + "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.parttype in ('p', 'v')) left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and t.oid = 1 and t.relkind <> 'i' order by c.attnum;", + getcolumninfoRSptble_1); + + MockResultSet partitionConstraintRS = preparedstatementHandler + .createResultSet(); + partitionConstraintRS.addColumn("constraintid"); + partitionConstraintRS.addColumn("tableid"); + partitionConstraintRS.addColumn("namespaceid"); + partitionConstraintRS.addColumn("constraintname"); + partitionConstraintRS.addColumn("constrainttype"); + partitionConstraintRS.addColumn("deferrable"); + partitionConstraintRS.addColumn("deferred"); + partitionConstraintRS.addColumn("validate"); + partitionConstraintRS.addColumn("indexid"); + partitionConstraintRS.addColumn("fkeytableId"); + partitionConstraintRS.addColumn("updatetype"); + partitionConstraintRS.addColumn("deletetype"); + partitionConstraintRS.addColumn("matchtype"); + partitionConstraintRS.addColumn("expr"); + partitionConstraintRS.addColumn("columnlist"); + partitionConstraintRS.addColumn("fkeycolumnlist"); + partitionConstraintRS.addColumn("const_def"); + partitionConstraintRS.addRow(new Object[] {1, 1, 1, "ConstraintName", + "ConstraintType", false, false, false, 1, 1, "", "", "", "", + "1", "1", ""}); + preparedstatementHandler.prepareResultSet( + "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c join pg_class cl on c.conrelid = cl.oid where c.conrelid=2 and cl.parttype in ('p','v') and c.conrelid <> 0;", + partitionConstraintRS); + preparedstatementHandler.prepareResultSet("SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c join pg_class cl on c.conrelid = cl.oid where c.conrelid=1 and cl.parttype in ('p','v') and c.conrelid <> 0;", partitionConstraintRS); + + + MockResultSet indexRS = preparedstatementHandler + .createResultSet(); + indexRS.addColumn("oid"); + indexRS.addColumn("tableId"); + indexRS.addColumn("indexname"); + indexRS.addColumn("namespaceid"); + indexRS.addColumn("accessmethodid"); + indexRS.addColumn("isunique"); + indexRS.addColumn("isprimary"); + indexRS.addColumn("isexclusion"); + indexRS.addColumn("isimmediate"); + indexRS.addColumn("isclustered"); + indexRS.addColumn("checkmin"); + indexRS.addColumn("isready"); + indexRS.addColumn("cols"); + indexRS.addColumn("reloptions"); + indexRS.addColumn("indexdef"); + indexRS.addColumn("tablespace"); + indexRS.addRow(new Object[] {1, 1, "IndexName", 1, 1, true, false, + false, false, false, false, false, "1", "", "", ""}); + preparedstatementHandler.prepareResultSet( + "SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, ci.relnamespace as namespaceid, ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, i.indisexclusion as isexclusion, i.indimmediate as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, i.indisready as isready, i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions, def.indexdef, def.tablespace FROM pg_index i LEFT JOIN pg_class t on (t.oid = i.indrelid) LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) LEFT JOIN pg_namespace ns on (ci.relnamespace = ns.oid) LEFT JOIN pg_indexes def on (ci.relname = def.indexname and ns.nspname = def.schemaname) WHERE t.relkind in ('r', 'f') and ci.parttype in ('p','v') and ci.oid = 2;", indexRS); + + preparedstatementHandler.prepareResultSet( + "SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, ci.relnamespace as namespaceid, ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, i.indisexclusion as isexclusion, i.indimmediate as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, i.indisready as isready, i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions, def.indexdef, def.tablespace FROM pg_index i LEFT JOIN pg_class t on (t.oid = i.indrelid) LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) LEFT JOIN pg_namespace ns on (ci.relnamespace = ns.oid) LEFT JOIN pg_indexes def on (ci.relname = def.indexname and ns.nspname = def.schemaname) WHERE t.relkind in ('r', 'f') and ci.parttype in ('p','v') and ci.oid = 1;", indexRS); + MockResultSet getPartitionsRS_1 = preparedstatementHandler + .createResultSet(); + getPartitionsRS_1.addColumn("partition_id"); + getPartitionsRS_1.addColumn("partition_name"); + getPartitionsRS_1.addColumn("partition_type"); + getPartitionsRS_1.addColumn("table_id"); + + getPartitionsRS_1.addRow(new Object[] {1, "part_1", "r", 1}); + preparedstatementHandler.prepareResultSet("select p.oid AS partition_id , p.relname AS partition_name, p.partstrategy as partition_type, p.parentid AS table_id from pg_class c, pg_partition p where c.oid = 2 and c.parttype = 'p' and p.parentid = c.oid and p.parttype = 'p' order by p.boundaries;", + getPartitionsRS_1); + preparedstatementHandler.prepareResultSet("select p.oid AS partition_id , p.relname AS partition_name, p.partstrategy as partition_type, p.parentid AS table_id from pg_class c, pg_partition p where c.oid = 1 and c.parttype = 'p' and p.parentid = c.oid and p.parttype = 'p' order by p.boundaries;", + getPartitionsRS_1); + core.getContextProposals("pg_catalog.\"partTable\".\"PCo\"", "select * from pg_catalog.partTable.PCo"); + LinkedHashMap map2; + + map2 = core + .findNonLoadedDatabaseObjectsOnDemand(database.getConnectionManager().getFreeConnection()); + ContentAssistKeywords.getInstance().clearOLAPKeywords(database.getServer().getAllDatabases()); + ContentAssistKeywords.getInstance().clear(); + } catch (MPPDBIDEException e) { + fail("Not expected to come here"); + } + } + + + @Test + public void testAutoSuggestForNonLoadedPartTable11() { + + try { + Namespace ns = database.getNameSpaceById(1); + PartitionTable ptab = new PartitionTable(ns); + ptab.setName("partTable"); + ptab.setOid(1); + ns.addTableToGroup(ptab); + ns.addTableToSearchPool(ptab); + + MockResultSet getcolumninfoRSptble_1 = preparedstatementHandler + .createResultSet(); + getcolumninfoRSptble_1.addColumn("tableid"); + getcolumninfoRSptble_1.addColumn("namespaceid"); + getcolumninfoRSptble_1.addColumn("columnidx"); + getcolumninfoRSptble_1.addColumn("name"); + getcolumninfoRSptble_1.addColumn("datatypeoid"); + getcolumninfoRSptble_1.addColumn("dtns"); + getcolumninfoRSptble_1.addColumn("length"); + getcolumninfoRSptble_1.addColumn("precision"); + getcolumninfoRSptble_1.addColumn("dimentions"); + getcolumninfoRSptble_1.addColumn("notnull"); + getcolumninfoRSptble_1.addColumn("isdefaultvalueavailable"); + getcolumninfoRSptble_1.addColumn("default_value"); + getcolumninfoRSptble_1.addColumn("attDefStr"); + getcolumninfoRSptble_1.addColumn("displayColumns"); + getcolumninfoRSptble_1 + .addRow(new Object[] {1, 1, 1, "ColName", 1, 1, 200, 0, 0, + false, true, "Default value", "attrString", "bigint"}); + preparedstatementHandler.prepareResultSet( + "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.parttype in ('p', 'v')) left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and t.oid = 2 and t.relkind <> 'i' order by c.attnum;", + getcolumninfoRSptble_1); + + preparedstatementHandler.prepareResultSet( + "select t.oid as tableid, t.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class t left join pg_attribute c on (t.oid = c.attrelid and t.parttype in ('p', 'v')) left join pg_attrdef d on (t.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and t.oid = 1 and t.relkind <> 'i' order by c.attnum;", + getcolumninfoRSptble_1); + + MockResultSet partitionConstraintRS = preparedstatementHandler + .createResultSet(); + partitionConstraintRS.addColumn("constraintid"); + partitionConstraintRS.addColumn("tableid"); + partitionConstraintRS.addColumn("namespaceid"); + partitionConstraintRS.addColumn("constraintname"); + partitionConstraintRS.addColumn("constrainttype"); + partitionConstraintRS.addColumn("deferrable"); + partitionConstraintRS.addColumn("deferred"); + partitionConstraintRS.addColumn("validate"); + partitionConstraintRS.addColumn("indexid"); + partitionConstraintRS.addColumn("fkeytableId"); + partitionConstraintRS.addColumn("updatetype"); + partitionConstraintRS.addColumn("deletetype"); + partitionConstraintRS.addColumn("matchtype"); + partitionConstraintRS.addColumn("expr"); + partitionConstraintRS.addColumn("columnlist"); + partitionConstraintRS.addColumn("fkeycolumnlist"); + partitionConstraintRS.addColumn("const_def"); + partitionConstraintRS.addRow(new Object[] {1, 1, 1, "ConstraintName", + "ConstraintType", false, false, false, 1, 1, "", "", "", "", + "1", "1", ""}); + preparedstatementHandler.prepareResultSet( + "SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c join pg_class cl on c.conrelid = cl.oid where c.conrelid=2 and cl.parttype in ('p','v') and c.conrelid <> 0;", + partitionConstraintRS); + preparedstatementHandler.prepareResultSet("SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c join pg_class cl on c.conrelid = cl.oid where c.conrelid=1 and cl.parttype in ('p','v') and c.conrelid <> 0;", partitionConstraintRS); + + + MockResultSet indexRS = preparedstatementHandler + .createResultSet(); + indexRS.addColumn("oid"); + indexRS.addColumn("tableId"); + indexRS.addColumn("indexname"); + indexRS.addColumn("namespaceid"); + indexRS.addColumn("accessmethodid"); + indexRS.addColumn("isunique"); + indexRS.addColumn("isprimary"); + indexRS.addColumn("isexclusion"); + indexRS.addColumn("isimmediate"); + indexRS.addColumn("isclustered"); + indexRS.addColumn("checkmin"); + indexRS.addColumn("isready"); + indexRS.addColumn("cols"); + indexRS.addColumn("reloptions"); + indexRS.addColumn("indexdef"); + indexRS.addColumn("tablespace"); + indexRS.addRow(new Object[] {1, 1, "IndexName", 1, 1, true, false, + false, false, false, false, false, "1", "", "", ""}); + preparedstatementHandler.prepareResultSet( + "SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, ci.relnamespace as namespaceid, ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, i.indisexclusion as isexclusion, i.indimmediate as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, i.indisready as isready, i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions, def.indexdef, def.tablespace FROM pg_index i LEFT JOIN pg_class t on (t.oid = i.indrelid) LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) LEFT JOIN pg_namespace ns on (ci.relnamespace = ns.oid) LEFT JOIN pg_indexes def on (ci.relname = def.indexname and ns.nspname = def.schemaname) WHERE t.relkind in ('r', 'f') and ci.parttype in ('p','v') and ci.oid = 2;", indexRS); + + preparedstatementHandler.prepareResultSet( + "SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, ci.relnamespace as namespaceid, ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, i.indisexclusion as isexclusion, i.indimmediate as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, i.indisready as isready, i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions, def.indexdef, def.tablespace FROM pg_index i LEFT JOIN pg_class t on (t.oid = i.indrelid) LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) LEFT JOIN pg_namespace ns on (ci.relnamespace = ns.oid) LEFT JOIN pg_indexes def on (ci.relname = def.indexname and ns.nspname = def.schemaname) WHERE t.relkind in ('r', 'f') and ci.parttype in ('p','v') and ci.oid = 1;", indexRS); MockResultSet getPartitionsRS_1 = preparedstatementHandler + .createResultSet(); + getPartitionsRS_1.addColumn("partition_id"); + getPartitionsRS_1.addColumn("partition_name"); + getPartitionsRS_1.addColumn("table_id"); + + getPartitionsRS_1.addRow(new Object[] {1, "part_1", 1}); + preparedstatementHandler.prepareResultSet("select p.oid AS partition_id , p.relname AS partition_name , p.parentid AS table_id from pg_class c, pg_partition p where c.oid = 2 and c.parttype = 'p' and p.parentid = c.oid and p.parttype = 'p' order by p.boundaries;", + getPartitionsRS_1); + preparedstatementHandler.prepareResultSet("select p.oid AS partition_id , p.relname AS partition_name , p.parentid AS table_id from pg_class c, pg_partition p where c.oid = 1 and c.parttype = 'p' and p.parentid = c.oid and p.parttype = 'p' order by p.boundaries;", + getPartitionsRS_1); + core.findString("insert into pg_catalog.\"partTable\"(PCo", DatabaseUtils.getCharacterList(database)); + core.getContextProposals("pg_catalog.\"partTable\".\"PCo\"", "select * from pg_catalog.partTable.PCo"); + LinkedHashMap map2; + + map2 = core + .findNonLoadedDatabaseObjectsOnDemand(database.getConnectionManager().getFreeConnection()); + } catch (MPPDBIDEException e) { + fail("Not expected to come here"); + } + } + + @Test + public void testAutoSuggestForNonLoadedView() { + try { + Namespace ns = database.getNameSpaceById(1); + ViewMetaData view = new ViewMetaData(1, "Yiew1", ns,ns.getDatabase()); + ns.addView(view); + ns.addViewInSearchPool(view); + + + String query = "select v.oid as viewid, v.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class v left join pg_attribute c on (v.oid = c.attrelid and v.relkind = 'v') left join pg_attrdef d on (v.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and v.oid = 1 order by v.oid, c.attnum"; + + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("viewid"); + getdbsrs.addColumn("namespaceid"); + getdbsrs.addColumn("columnidx"); + getdbsrs.addColumn("name"); + getdbsrs.addColumn("datatypeoid"); + getdbsrs.addColumn("dtns"); + getdbsrs.addColumn("length"); + getdbsrs.addColumn("precision"); + getdbsrs.addColumn("dimentions"); + getdbsrs.addColumn("notnull"); + getdbsrs.addColumn("isdefaultvalueavailable"); + getdbsrs.addColumn("default_value"); + getdbsrs.addColumn("displayColumns"); + + getdbsrs.addRow( + new Object[] {2, 1, 1, "col1", 2, 1, 64, -1, 0, 'f', 'f', "",""}); + getdbsrs.addRow( + new Object[] {2, 2, 2, "col2", 1, 1, 64, -1, 0, 'f', 'f', "",""}); + + preparedstatementHandler.prepareResultSet(query, getdbsrs); + + LinkedHashMap map2=core.getContextProposals("\"Yiew1\".", "select * from partTable1.PCo"); + LinkedHashMap map1 = core + .findNonLoadedDatabaseObjectsOnDemand(database.getConnectionManager().getFreeConnection()); + assertEquals(1, map2.size()); + + }catch(MPPDBIDEException e) { + fail("Not expected to come here"); + } + + } + + @Test + public void testAutoSuggestForNonLoadedView11() { + try { + Namespace ns = database.getNameSpaceById(1); + ViewMetaData view = new ViewMetaData(1, "Yiew1", ns,ns.getDatabase()); + ns.addView(view); + ns.addViewInSearchPool(view); + + + String query = "select v.oid as viewid, v.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class v left join pg_attribute c on (v.oid = c.attrelid and v.relkind = 'v') left join pg_attrdef d on (v.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and v.oid = 1 order by v.oid, c.attnum"; + + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("viewid"); + getdbsrs.addColumn("namespaceid"); + getdbsrs.addColumn("columnidx"); + getdbsrs.addColumn("name"); + getdbsrs.addColumn("datatypeoid"); + getdbsrs.addColumn("dtns"); + getdbsrs.addColumn("length"); + getdbsrs.addColumn("precision"); + getdbsrs.addColumn("dimentions"); + getdbsrs.addColumn("notnull"); + getdbsrs.addColumn("isdefaultvalueavailable"); + getdbsrs.addColumn("default_value"); + getdbsrs.addColumn("displayColumns"); + + getdbsrs.addRow( + new Object[] {2, 1, 1, "col1", 2, 1, 64, -1, 0, 'f', 'f', "",""}); + getdbsrs.addRow( + new Object[] {2, 2, 2, "col2", 1, 1, 64, -1, 0, 'f', 'f', "",""}); + + preparedstatementHandler.prepareResultSet(query, getdbsrs); + + LinkedHashMap map2=core.getContextProposals("\"Yiew1\".", "select * from partTable1.PCo"); + LinkedHashMap map1 = core + .findNonLoadedDatabaseObjectsOnDemand(database.getConnectionManager().getFreeConnection()); + assertEquals(1, map2.size()); + + }catch(MPPDBIDEException e) { + fail("Not expected to come here"); + } + + } + + @Test + public void test_viewViewData_01() { + try { + Namespace ns = database.getNameSpaceById(1); + ViewMetaData vmd = new ViewMetaData(2, "anything", ns,ns.getDatabase()); + vmd.setNamespace(ns); + ViewViewDataCore viewViewDataCore = new ViewViewDataCore(); + viewViewDataCore.init(vmd); + assertNotNull(viewViewDataCore.getProgressBarLabel()); + assertNotNull(viewViewDataCore.getWindowDetails().getShortTitle()); + assertNotNull(viewViewDataCore.getWindowDetails().getTitle()); + assertNotNull(viewViewDataCore.getWindowDetails().getUniqueID()); + assertNotNull(viewViewDataCore.getQuery()); + assertNotNull(viewViewDataCore.getWindowTitle()); + assertTrue(viewViewDataCore.isTableDropped()); + assertEquals(vmd, viewViewDataCore.getServerObject()); + assertTrue(vmd.isDbConnected()); + + } catch (OutOfMemoryError | MPPDBIDEException e) { + e.printStackTrace(); + } + } + + @Test + public void test_AutoRefreshForCreateTable() { + + String tableQuery = "select tbl.relname relname,tbl.parttype parttype,tbl.relnamespace relnamespace,tbl.oid oid,ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.relname = 'table1' and tbl.relnamespace= 6"; + MockResultSet createTableRS = preparedstatementHandler.createResultSet(); + createTableRS.addColumn("relname"); + createTableRS.addColumn("parttype"); + createTableRS.addColumn("relnamespace"); + createTableRS.addColumn("oid"); + createTableRS.addColumn("reltablespace"); + createTableRS.addColumn("relpersistence"); + createTableRS.addColumn("desc"); + createTableRS.addColumn("nodes"); + createTableRS.addColumn("reloptions"); + createTableRS.addRow(new Object[] {"table1","n",6,1,"","","","",""}); + preparedstatementHandler.prepareResultSet( + tableQuery, createTableRS); + + String viewQuery = "SELECT c.oid, n.oid as nspoid, n.nspname AS schemaname, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner, c.relkind as relkind FROM (pg_class c LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace))) WHERE (c.relkind = 'v'::\"char\") and c.relname='table1' and n.nspname='ns1';"; + MockResultSet createViewRS = preparedstatementHandler.createResultSet(); + createViewRS.addColumn("oid"); + createViewRS.addColumn("viewname"); + createViewRS.addColumn("viewowner"); + createViewRS.addColumn("relkind"); + createViewRS.addRow(new Object[] {7,"table1", "", "v"}); + preparedstatementHandler.prepareResultSet( + viewQuery, createViewRS); + + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getConstaraintForTableRS(preparedstatementHandler); + CommonLLTUtils.getIndexForTableRS(preparedstatementHandler); + CommonLLTUtils.fetchColumnMetaDataRS(preparedstatementHandler); + + Database database = connProfCache.getDbForProfileId(profileId); + RefreshObjectDetails refreshObj = new RefreshObjectDetails(); + Namespace ns1 = new UserNamespace(6, "ns1", database); + refreshObj.setDesctNamespace(ns1); + refreshObj.setObjToBeRefreshed(ns1); + refreshObj.setOperationType("CREATE_TABLE"); + refreshObj.setObjectName("table1"); + refreshObj.setParent(ns1); + refreshObj.setNamespace(ns1); + HashSet listOfObjects = new HashSet<>(); + AutoRefreshQueryFormation.getObjectToBeRefreshed(refreshObj, listOfObjects); + assertTrue(!listOfObjects.isEmpty()); + refreshObj.setOperationType("CREATE_VIEW"); + AutoRefreshQueryFormation.getObjectToBeRefreshed(refreshObj, listOfObjects); + assertTrue(!listOfObjects.isEmpty()); + } + + @Test + public void test_fileValidationUtilTest() { + String fileName = "testfile"; + assertEquals(true, FileValidationUtils.validateFileName(fileName)); + } + + @Test + public void test_filePathValidationTest() { + String fileName = "D:\\testfile"; + assertEquals(true, FileValidationUtils.validateFilePathName(fileName)); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/DebugerConstantTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/DebugerConstantTest.java new file mode 100644 index 0000000000000000000000000000000000000000..92fb71ab0d17558e5eeeb592f57af6061ab615e7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/DebugerConstantTest.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.test.presentation.properties; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +import org.opengauss.mppdbide.debuger.debug.DebugConstants; +import org.opengauss.mppdbide.debuger.debug.DebugConstants.DebugOpt; +import org.opengauss.mppdbide.debuger.vo.FunctionVo; +import org.opengauss.mppdbide.debuger.vo.PositionVo; +import org.opengauss.mppdbide.debuger.vo.SessionVo; +import org.opengauss.mppdbide.debuger.vo.SourceCodeVo; +import org.opengauss.mppdbide.debuger.vo.StackVo; +import org.opengauss.mppdbide.debuger.vo.TotalSourceCodeVo; +import org.opengauss.mppdbide.debuger.vo.VariableVo; + +/** + * Title: DebugerDebugOptTest for use + * + * @since 3.0.0 + */ +public class DebugerConstantTest { + @Test + public void testNoParam() { + String sql1 = DebugConstants.getSql(DebugOpt.DEBUG_ON); + String compareResults = "select * from pldbg_on()"; + assertEquals(compareResults, sql1); + } + + @Test + public void testOneParam() { + String sql1 = DebugConstants.getSql(DebugConstants.DebugOpt.START_SESSION); + assertEquals(sql1, "select * from plpgsql_oid_debug(?)"); + } + + @Test + public void testThreeParam() { + String sql1 = DebugConstants.getSql(DebugConstants.DebugOpt.SET_BREAKPOINT); + assertEquals(sql1, "select * from pldbg_set_breakpoint(?,?,?)"); + } + + @Test + public void testAnotherInput() { + String sql1 = DebugConstants.getSql("test_function", 3); + String result = "select * from test_function(?,?,?)"; + assertEquals(sql1, result); + } + + @Test + public void testVoCreate() { + FunctionVo funVo = new FunctionVo(); + assertNotNull(funVo); + + PositionVo positionVo = new PositionVo(); + assertNotNull(positionVo); + + PositionVo positionVo2 = new PositionVo(new Long(0), 1, null); + assertNotNull(positionVo2); + assertEquals(positionVo2.linenumber.intValue(), 1); + assertNotEquals(PositionVo.title(), ""); + assertNotEquals(positionVo2.formatSelf(), ""); + + SessionVo sessionVo = new SessionVo(); + assertNotNull(sessionVo); + + SourceCodeVo codeVo = new SourceCodeVo(); + assertNotNull(codeVo); + codeVo.pldbg_get_source = "test"; + assertEquals(codeVo.getSourceCode(), "test"); + + StackVo stackVo = new StackVo(); + assertNotNull(stackVo); + stackVo.level = new Integer(1); + stackVo.targetname = "name"; + assertNotEquals(stackVo.toString(), ""); + + TotalSourceCodeVo totalSourceCodeVo = new TotalSourceCodeVo(); + assertNotNull(totalSourceCodeVo); + totalSourceCodeVo.definition = "test11"; + totalSourceCodeVo.headerlines = new Integer(1); + assertEquals(totalSourceCodeVo.getHeadlines(), 1); + assertEquals(totalSourceCodeVo.getSourceCode(), "test11/"); + + VariableVo variableVo = new VariableVo(); + assertNotNull(variableVo); + variableVo.name = "var1"; + variableVo.linenumber = new Integer(1); + variableVo.value = "value"; + variableVo.dtype = new Long(3); + variableVo.isnotnull = new Boolean(true); + assertNotEquals(VariableVo.title(), ""); + assertNotEquals(variableVo.formatSelf(), ""); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/DebugerFunctionTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/DebugerFunctionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..466ad97acd992e879c3432f42c8b27c44401a89a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/DebugerFunctionTest.java @@ -0,0 +1,545 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.test.presentation.properties; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Optional; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.contentassist.ContentAssistProcesserData; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DebugObjects; +import org.opengauss.mppdbide.bl.serverdatacache.ForeignTable; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.PartitionTable; +import org.opengauss.mppdbide.bl.serverdatacache.SequenceMetadata; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TypeMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.UserNamespace; +import org.opengauss.mppdbide.bl.serverdatacache.ViewColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.common.DBConnectionAdapter; +import org.opengauss.mppdbide.common.IConnection; +import org.opengauss.mppdbide.common.IConnectionDisconnect; +import org.opengauss.mppdbide.common.IConnectionProvider; +import org.opengauss.mppdbide.debuger.dao.FunctionDao; +import org.opengauss.mppdbide.debuger.debug.DebugConstants; +import org.opengauss.mppdbide.debuger.debug.DebugConstants.DebugOpt; +import org.opengauss.mppdbide.debuger.exception.DebugExitException; +import org.opengauss.mppdbide.debuger.service.DebugService; +import org.opengauss.mppdbide.debuger.service.QueryService; +import org.opengauss.mppdbide.debuger.service.ServiceFactory; +import org.opengauss.mppdbide.debuger.service.chain.PrepareMsgChian; +import org.opengauss.mppdbide.debuger.service.chain.ServerPortMsgChain; +import org.opengauss.mppdbide.debuger.thread.DebugServerThreadProxy; +import org.opengauss.mppdbide.debuger.vo.FunctionVo; +import org.opengauss.mppdbide.debuger.vo.PositionVo; +import org.opengauss.mppdbide.debuger.vo.StackVo; +import org.opengauss.mppdbide.debuger.vo.VariableVo; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.mock.presentation.MockDebugServiceHelper; +import org.opengauss.mppdbide.presentation.contentassistprocesser.ContentAssistProcesserCore; +import org.opengauss.mppdbide.test.presentation.table.MockPresentationBLPreferenceImpl; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; + +/** + * Title: DebugerFunctionTest for use + * + * @since 3.0.0 + */ +public class DebugerFunctionTest extends BasicJDBCTestCaseAdapter { + MockConnection connection = null; + Database connectionProfile = null; + DebugObjects debugObject = null; + DebugObjects nestedDebugObject = null; + StatementResultSetHandler statementHandler = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + ServerConnectionInfo serverInfo = null; + ConnectionProfileId profileId = null; + + DBConnProfCache connProfCache = null; + ContentAssistProcesserCore core; + ContentAssistProcesserCore core1; + ContentAssistProcesserData data; + Database database = null; + + FunctionDesc funcDescAddTest = new FunctionDesc("add_test", + Arrays.asList(new Integer(1), new Integer(2))); + ServiceFactory serviceFactory = null; + DebugService debugService = null; + QueryService queryService = null; + FunctionVo functionVo = null; + DebugServerThreadProxy serverThreadProxy = null; + + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#setUp() + */ + @Before + public void setUp() throws Exception + { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + connection = new MockConnection(); + // test for logging + MPPDBIDELoggerUtility.setArgs(new String[] {"-logfolder=.", "-detailLogging=true"}); + + // MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + preparedstatementHandler = connection.getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + + connProfCache = DBConnProfCache.getInstance(); + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + database = connProfCache.getDbForProfileId(profileId); + core = new ContentAssistProcesserCore(database); + core1 = new ContentAssistProcesserCore(null); + data = new ContentAssistProcesserData(database); + getAllDatabaseObjects(); + + prepareDebugResultSets(); + serviceFactory = createServiceFactory(); + queryService = serviceFactory.getQueryService(); + functionVo = queryService.queryFunction(funcDescAddTest.proname); + debugService = serviceFactory.getDebugService(functionVo); + debugService.init(); + debugService.prepareDebug(); + debugService.noticeReceived(new SQLWarning(PrepareMsgChian.PREPARE_SUCCESS + " SERVER ")); + debugService.noticeReceived(new SQLWarning(ServerPortMsgChain.SERVER_PORT_MATCH + "0")); + debugService.attachDebug(); + Thread.sleep(50); + debugService.startDebug(funcDescAddTest.params); + Thread.sleep(50); + } + + private ServiceFactory createServiceFactory() { + ServiceFactory serviceFactory = new ServiceFactory(new IConnectionProvider() { + @Override + public Optional getFreeConnection() { + DBConnection dbConn; + try { + dbConn = database.getConnectionManager().getFreeConnection(); + return Optional.of(new DBConnectionAdapter( + dbConn, + new IConnectionDisconnect() { + @Override + public void releaseConnection( + DBConnection connection) { + database + .getConnectionManager() + .releaseAndDisconnection(connection); + } + })); + } catch (MPPDBIDEException e) { + } + return Optional.empty(); + } + }); + return serviceFactory; + } + private void prepareDebugResultSets() { + String sql = new FunctionDao().getSql(funcDescAddTest.proname); + MockDebugServiceHelper mockHelper = new MockDebugServiceHelper( + preparedstatementHandler, functionVo); + mockHelper.mockFunctionVo(sql, new Object[] {new Long(1), funcDescAddTest.proname}); + mockHelper.mockPrepareDebug( + DebugConstants.getSql(DebugOpt.START_SESSION)); + mockHelper.mockStartDebug( + DebugConstants.getSql(funcDescAddTest.proname, funcDescAddTest.params.size()), + new Integer(7)); + mockHelper.mockAttachDebug(DebugConstants.getSql(DebugOpt.ATTACH_SESSION), + new Integer(1)); + mockHelper.mockAbortDebug(DebugConstants.getSql(DebugOpt.ABORT_TARGET)); + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception + { + super.tearDown(); + + debugService.end(); + debugService = null; + queryService.closeService(); + queryService = null; + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearThrowsSQLException(); + connectionProfile = null; + + Iterator itr = DBConnProfCache.getInstance().getServers().iterator(); + + while(itr.hasNext()) + { + DBConnProfCache.getInstance().removeServer(itr.next().getId()); + } + } + + @Test + public void testBreakPoints() { + MockDebugServiceHelper helper = new MockDebugServiceHelper(preparedstatementHandler, + functionVo); + helper.mockBreakPoint(DebugConstants.getSql(DebugOpt.GET_BREAKPOINTS)); + try { + List breakpoints = debugService.getBreakPoints(); + assertEquals(1, breakpoints.size()); + PositionVo positionVo = breakpoints.get(0); + assertEquals(positionVo.func.longValue(), functionVo.oid.longValue()); + assertEquals(positionVo.linenumber.intValue(), -1); + assertEquals(positionVo.targetname, functionVo.proname); + } catch (SQLException e) { + fail("get breakpoints failed!"); + } + } + + @Test + public void testVariable() { + MockDebugServiceHelper helper = new MockDebugServiceHelper(preparedstatementHandler, + functionVo); + helper.mockVariable(DebugConstants.getSql(DebugOpt.GET_VARIABLES)); + try { + List variables = debugService.getVariables(); + assertEquals(1, variables.size()); + VariableVo var = variables.get(0); + assertEquals(var.name, "v1"); + assertTrue(var.value instanceof Integer); + assertEquals(((Integer)var.value).intValue(), 1); + } catch (SQLException e) { + fail("get breakpoints failed!"); + } + } + + @Test + public void testStack() { + MockDebugServiceHelper helper = new MockDebugServiceHelper(preparedstatementHandler, + functionVo); + helper.mockStack(DebugConstants.getSql(DebugOpt.GET_STACKS)); + try { + List stacks = debugService.getStacks(); + assertEquals(1, stacks.size()); + StackVo stackVo = stacks.get(0); + assertEquals(stackVo.targetname, funcDescAddTest.proname); + assertEquals(stackVo.func.longValue(), functionVo.oid.longValue()); + assertEquals(stackVo.level.intValue(), 1); + } catch (SQLException e) { + fail("get breakpoints failed!"); + } + } + + @Test + public void testStepDebug() { + MockDebugServiceHelper helper = new MockDebugServiceHelper(preparedstatementHandler, + functionVo); + DebugOpt[] toTestOpt = new DebugOpt[] {DebugOpt.STEP_INTO, DebugOpt.STEP_OVER, + DebugOpt.CONTINUE_EXEC}; + for (DebugOpt opt: toTestOpt) { + helper.mockPositionOneLine(DebugConstants.getSql(opt)); + } + + for (DebugOpt opt: toTestOpt) { + try { + PositionVo positionVo = debugService.getPositionVo(opt).get(); + assertEquals(positionVo.func.longValue(), functionVo.oid.longValue()); + assertEquals(positionVo.linenumber.intValue(), -1); + assertEquals(positionVo.targetname, functionVo.proname); + } catch (SQLException e) { + fail("get step pos failed!"); + } catch (DebugExitException e) { + assertTrue(true); + } + } + } + + @Test + public void testStepInto() { + MockDebugServiceHelper helper = new MockDebugServiceHelper( + preparedstatementHandler, functionVo); + helper.mockPositionOneLine(DebugConstants.getSql(DebugOpt.STEP_INTO)); + try { + debugService.stepInto().get(); + assertTrue(true); + } catch (SQLException sqlExp) { + fail("can\'t run here!"); + } catch (DebugExitException e) { + assertTrue(true); + } + } + + @Test + public void testStepOver() { + MockDebugServiceHelper helper = new MockDebugServiceHelper( + preparedstatementHandler, functionVo); + helper.mockPositionOneLine(DebugConstants.getSql(DebugOpt.STEP_OVER)); + try { + debugService.stepOver().get(); + assertTrue(true); + } catch (SQLException sqlExp) { + fail("can\'t run here!"); + } catch (DebugExitException e) { + assertTrue(true); + } + } + + @Test + public void testContinue() { + MockDebugServiceHelper helper = new MockDebugServiceHelper( + preparedstatementHandler, functionVo); + helper.mockPositionOneLine(DebugConstants.getSql(DebugOpt.CONTINUE_EXEC)); + try { + debugService.continueExec().get(); + assertTrue(true); + } catch (SQLException sqlExp) { + fail("can\'t run here!"); + } catch (DebugExitException e) { + assertTrue(true); + } + } + + @Test + public void testStepOutDebug() { + try { + debugService.stepOut().get(); + fail("can\'t run here!"); + } catch (SQLException sqlExp) { + assertTrue(true); + } catch (DebugExitException e) { + fail("can\'t run here!"); + } + } + + public static class FunctionDesc { + public String proname; + public List params; + public FunctionDesc(String proname, List params) { + this.proname = proname; + this.params = params; + } + } + + private void getAllDatabaseObjects() + { + try + { + + database.getServer().refresh(); + Namespace ns1 = new UserNamespace(6, "ns1", database); + Namespace ns2 = new UserNamespace(2, "NS1", database); + Namespace ns3 = new UserNamespace(3, "NS2", database); + Namespace ns4 = new UserNamespace(4, "yns2", database); + Namespace ns6 = new UserNamespace(5, "\"NS1\"", database); + Namespace ns7 = new UserNamespace(7, "Namespc", database); + + + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns1); + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns2); + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns3); + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns4); + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns6); + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns7); + + TableMetaData ptab1 = new PartitionTable(ns7); + ns7.addTableToSearchPool(ptab1); + + TableMetaData tbl1 = new TableMetaData(1, "tbl1", ns1, ""); + ColumnMetaData clm = new ColumnMetaData(tbl1, 1, "Col1", new TypeMetaData(11, "Integer", ns3)); + tbl1.addColumn(clm); + TableMetaData tbl2 = new TableMetaData(2, "tbl2", ns1, ""); + ColumnMetaData clm1 = new ColumnMetaData(tbl2, 1, "Col2", null); + tbl2.addColumn(clm1); + TableMetaData tbl3 = new TableMetaData(3, "TBL1", ns1, ""); + ColumnMetaData clm2 = new ColumnMetaData(tbl3, 1, "Col3", null); + tbl3.addColumn(clm2); + + ns1.addTableToSearchPool(tbl1); + ns1.addTableToSearchPool(tbl2); + ns1.addTableToSearchPool(tbl3); + + TableMetaData tbl4 = new TableMetaData(4, "tbl1", ns2, ""); + ColumnMetaData clm3 = new ColumnMetaData(tbl4, 1, "Col4", new TypeMetaData(11, "Integer", ns3)); + tbl4.addColumn(clm3); + TableMetaData tbl5 = new TableMetaData(5, "tbl2", ns2, ""); + ColumnMetaData clm4 = new ColumnMetaData(tbl5, 1, "Col5", null); + tbl5.addColumn(clm4); + TableMetaData tbl6 = new TableMetaData(6, "TBL1", ns2, ""); + ColumnMetaData clm5 = new ColumnMetaData(tbl6, 1, "Col6", null); + tbl6.addColumn(clm5); + TableMetaData tbl7 = new TableMetaData(7, "TBL2", ns2, ""); + ColumnMetaData clm6 = new ColumnMetaData(tbl7, 1, "Col7", null); + tbl7.addColumn(clm6); + TableMetaData tbl110 = new TableMetaData(110, "T}BL1", ns2, ""); + ColumnMetaData clm110 = new ColumnMetaData(tbl110, 1, "Col7", null); + tbl7.addColumn(clm110); + + ViewMetaData view = new ViewMetaData(1, "Yiew1", ns2,ns2.getDatabase()); + ViewColumnMetaData viewCol = new ViewColumnMetaData(view, 2, "viewclm", new TypeMetaData(0, "int", ns2)); + view.getColumns().addItem(viewCol); + + SequenceMetadata seq = new SequenceMetadata(ns2); + seq.setName("seq"); + + ns2.addTableToSearchPool(tbl5); + ns2.addTableToSearchPool(tbl6); + ns2.addTableToSearchPool(tbl7); + ns2.addTableToSearchPool(tbl4); + ns2.addTableToSearchPool(tbl110); + ns2.addView(view); + ns2.addSequence(seq); + database.getSearchPoolManager().addsequenceToSearchPool(seq); + + TableMetaData tbl8 = new TableMetaData(8, "tbl1", ns3, ""); + ColumnMetaData clm8 = new ColumnMetaData(tbl8, 1, "Col8", new TypeMetaData(11, "Integer", ns3)); + tbl8.addColumn(clm8); + TableMetaData tbl9 = new TableMetaData(9, "tbl2", ns3, ""); + ColumnMetaData clm9 = new ColumnMetaData(tbl9, 1, "Col9", null); + tbl9.addColumn(clm9); + + ns3.addTableToSearchPool(tbl8); + ns3.addTableToSearchPool(tbl9); + + TableMetaData tbl10 = new TableMetaData(10, "Tbl11", ns4, ""); + ColumnMetaData clm10 = new ColumnMetaData(tbl10, 1, "Col10", null); + tbl10.addColumn(clm10); + TableMetaData tbl11 = new TableMetaData(11, "xtbl2", ns4, ""); + ColumnMetaData clm11 = new ColumnMetaData(tbl11, 1, "Col11", null); + tbl11.addColumn(clm11); + TableMetaData tbl12 = new TableMetaData(12, "NS1", ns4, ""); + ColumnMetaData clm12 = new ColumnMetaData(tbl12, 1, "Col12", null); + tbl12.addColumn(clm12); + + ns4.addTableToSearchPool(tbl10); + ns4.addTableToSearchPool(tbl11); + ns4.addTableToSearchPool(tbl12); + + TableMetaData tbl14 = new TableMetaData(13, "ybl1", ns6, ""); + ColumnMetaData clm14 = new ColumnMetaData(tbl14, 1, "Col14", null); + tbl14.addColumn(clm14); + + ns6.addTableToSearchPool(tbl14); + + + ForeignTable ForeignTbl = new ForeignTable(ns1, OBJECTTYPE.FOREIGN_TABLE_GDS); + ForeignTbl.setName("Ftable1"); + ForeignTbl.setOid(1); + ns1.addForeignTableToGroup(ForeignTbl); + ns1.addTableToSearchPool(ForeignTbl); + ColumnMetaData fClm10 = new ColumnMetaData(ForeignTbl, 1, "FCol10", null); + ForeignTbl.addColumn(fClm10); + + ForeignTable ForeignTbl2 = new ForeignTable(ns1, OBJECTTYPE.FOREIGN_TABLE_GDS); + ForeignTbl2.setName("Ftable2"); + ForeignTbl.setOid(2); + ns1.addForeignTableToGroup(ForeignTbl2); + ns1.addTableToSearchPool(ForeignTbl2); + ColumnMetaData fClm11 = new ColumnMetaData(ForeignTbl, 1, "FCol11", null); + ForeignTbl2.addColumn(fClm11); + + PartitionTable ptab = new PartitionTable(ns2); + ptab.setName("partTable"); + ptab.setOid(1); + ns2.addTableToGroup(ptab); + ns2.addTableToSearchPool(ptab); + ColumnMetaData pClm11 = new ColumnMetaData(ptab, 1, "PCol11", null); + ptab.addColumn(pClm11); + + PartitionTable ptab11 = new PartitionTable(ns2); + ptab11.setName("partTable1"); + ptab.setOid(2); + ns2.addTableToGroup(ptab11); + ns2.addTableToSearchPool(ptab11); + ColumnMetaData pClm12 = new ColumnMetaData(ptab11, 1, "PCol12", null); + ptab11.addColumn(pClm12); + + + System.out.println(database.getAllNameSpaces()); + + + } + catch (DatabaseOperationException e) + { + + e.printStackTrace(); + } + catch (DatabaseCriticalException e) + { + + e.printStackTrace(); + } + catch (Exception e) + { + + e.printStackTrace(); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/DebugerUiRelatedTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/DebugerUiRelatedTest.java new file mode 100644 index 0000000000000000000000000000000000000000..7873e005f61e9d7226fcea3a1ffe3a591f6cb25c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/DebugerUiRelatedTest.java @@ -0,0 +1,33 @@ +package org.opengauss.mppdbide.test.presentation.properties; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.util.HashMap; + +import org.junit.Test; + +import org.opengauss.mppdbide.debuger.vo.BreakpointList; +import org.opengauss.mppdbide.debuger.vo.BreakpointVo; + +public class DebugerUiRelatedTest { + @Test + public void testVoCreate() { + BreakpointVo breakpointVo = new BreakpointVo(1, "begin", true); + assertNotNull(breakpointVo); + breakpointVo.setLineNum(2); + breakpointVo.setStatement("end"); + breakpointVo.setEnable(false); + assertEquals(breakpointVo.getLineNum(), 2); + assertEquals(breakpointVo.getStatement(), "end"); + assertEquals(breakpointVo.getEnable(), false); + + BreakpointList.resetInstance(); + assertNull(BreakpointList.getInstance()); + BreakpointList.initialInstance(); + assertNotNull(BreakpointList.getInstance()); + BreakpointList.setBreakpointList(new HashMap()); + assertNotNull(BreakpointList.getInstance()); + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/DsResultSetGridDataProviderTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/DsResultSetGridDataProviderTest.java new file mode 100644 index 0000000000000000000000000000000000000000..5ab358170366044bd2b06b106c6cb9d67fff5b4a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/DsResultSetGridDataProviderTest.java @@ -0,0 +1,1288 @@ +package org.opengauss.mppdbide.test.presentation.properties; + +import java.math.BigDecimal; +import java.sql.Time; +import java.sql.Timestamp; +import java.sql.Types; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.TimeZone; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.*; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.StmtExecutor; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DatabaseUtils; +import org.opengauss.mppdbide.bl.serverdatacache.DefaultParameter; +import org.opengauss.mppdbide.bl.serverdatacache.IQueryResult; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.ObjectParameter.PARAMETERTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.QueryResult; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.SynonymMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.SynonymUtil; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.UserNamespace; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.groups.SynonymObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.bl.sqlhistory.IQueryExecutionSummary; +import org.opengauss.mppdbide.bl.sqlhistory.QueryExecutionSummary; +import org.opengauss.mppdbide.bl.sqlhistory.SQLHistoryFactory; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.presentation.TerminalExecutionConnectionInfra; +import org.opengauss.mppdbide.presentation.autorefresh.AutoRefreshQueryFormation; +import org.opengauss.mppdbide.presentation.autorefresh.RefreshObjectDetails; +import org.opengauss.mppdbide.presentation.edittabledata.DSResultSetGridColumnDataProvider; +import org.opengauss.mppdbide.presentation.edittabledata.DSResultSetGridDataProvider; +import org.opengauss.mppdbide.presentation.edittabledata.DSResultSetGridDataRow; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.presentation.grid.resultset.ColumnValueSqlTypeComparator; +import org.opengauss.mppdbide.presentation.objectproperties.ConstraintInfo; +import org.opengauss.mppdbide.presentation.objectproperties.DSObjectPropertiesGridDataRow; +import org.opengauss.mppdbide.presentation.objectproperties.PropertiesSynonymImpl; +import org.opengauss.mppdbide.presentation.resultset.ActionAfterResultFetch; +import org.opengauss.mppdbide.presentation.resultsetif.IResultConfig; +import org.opengauss.mppdbide.presentation.synonym.olap.SynonymInfo; +import org.opengauss.mppdbide.presentation.synonym.olap.SynonymWrapper; +import org.opengauss.mppdbide.test.presentation.table.MockPresentationBLPreferenceImpl; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.MessageQueue; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.utils.observer.DSEventTable; +import org.opengauss.mppdbide.utils.observer.IDSListener; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; +import com.mockrunner.mock.jdbc.MockResultSet; + +public class DsResultSetGridDataProviderTest extends BasicJDBCTestCaseAdapter +{ + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + int actionFetchResult; + DSResultSetGridColumnDataProvider colData; + + public int getActionFetchResult() + { + return actionFetchResult; + } + + public void setActionFetchResult(int actionFetchResult) + { + this.actionFetchResult = actionFetchResult; + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#setUp() + */ + @Before + public void setUp() throws Exception + { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + connection = new MockConnection(); + // test for logging + MPPDBIDELoggerUtility + .setArgs(new String[] {"-logfolder=.", "-detailLogging=true"}); + + // MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + MockPresentationBLPreferenceImpl.setFileEncoding("UTF-8"); + MockPresentationBLPreferenceImpl.setDateFormat("yyyy-MM-dd"); + MockPresentationBLPreferenceImpl.setTimeFormat("HH:mm:ss"); + + connProfCache = DBConnProfCache.getInstance(); + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + // serverInfo.setSslPassword("12345"); + // serverInfo.setServerType(DATABASETYPE.GAUSS); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception + { + super.tearDown(); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().close(); + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) + { + connProfCache.removeServer(itr.next().getId()); + } + + connProfCache.closeAllNodes(); + + } + + @Test + public void testINIT_FUNC_001_001_1() + { + final class IResultConfigTest implements IResultConfig + { + + @Override + public int getFetchCount() + { + return 1; + } + + @Override + public ActionAfterResultFetch getActionAfterFetch() + { + return ActionAfterResultFetch.ISSUE_COMMIT_CONNECTION_AFTER_FETCH; + } + } + try + { + Database database = connProfCache.getDbForProfileId(profileId); + CommonLLTUtils.runOnSQLTerminalRS(preparedstatementHandler); + IQueryResult result = DatabaseUtils.executeOnSqlTerminal( + "select * from tbl1", 1000, database.getConnectionManager().getFreeConnection(), + new MessageQueue()); + long elapsedTimeLong = 109; + String input = "2016-12-16 18:29:09"; + SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + sdf1.setTimeZone(TimeZone.getTimeZone("UTC")); + Date date = sdf1.parse(input); + String dt = sdf1.format(date); + QueryExecutionSummary summary = new QueryExecutionSummary( + "postgres", "ds", "select * from pg_class", true, dt, + elapsedTimeLong, 0); + DSResultSetGridDataProvider dsr = new DSResultSetGridDataProvider( + result, new IResultConfigTest(), summary); + new DsResultSetGridDataProviderTest().setActionFetchResult(10); + dsr.init(); + List rows = dsr.getAllFetchedRows(); + //assertEquals("1", rows.get(0).getValue(0).toString()); + // assertEquals("PUBLIC", rows.get(0).getValue(1)); + assertNotNull(dsr.getAllFetchedRows()); + assertNotNull(dsr.isEndOfRecords()); + assertNotNull(dsr.getColumnDataProvider()); + assertNotNull(dsr.getRecordCount()); + assertNotNull(dsr.getSummary()); + assertNotNull(dsr.getDataProviderConfig()); + } + catch (Exception e) + { + e.printStackTrace(); + fail("Not Expected to come here"); + } + } + + @Test + public void testINIT_FUNC_001_001_2() + { + + final class DSResultSetGridDataProviderInnerTest + extends DSResultSetGridDataProvider + { + private IQueryResult queryResult; + private IResultConfig config; + private IQueryExecutionSummary summary; + private IDSGridColumnProvider columnDataProvider; + private List rows; + private boolean isEndOfRecordsReached; + private DSEventTable eventTable; + + public DSResultSetGridDataProviderInnerTest(IQueryResult result, + IResultConfig rsConfig, IQueryExecutionSummary summary) + { + super(result, rsConfig, summary); + this.queryResult = result; + this.config = rsConfig; + this.summary = summary; + this.rows = new ArrayList(5); + this.eventTable = new DSEventTable(); + } + + @Override + public void init() + throws DatabaseOperationException, DatabaseCriticalException + { + colData = new DSResultSetGridColumnDataProvider(); + colData.init(queryResult); + this.columnDataProvider = colData; + getNextBatch(); + } + } + final class IResultConfigTest implements IResultConfig + { + + @Override + public int getFetchCount() + { + return 2; + } + + @Override + public ActionAfterResultFetch getActionAfterFetch() + { + return ActionAfterResultFetch.ISSUE_ROLLBACK_CONNECTION_AFTER_FETCH; + } + } + try + { + Database database = connProfCache.getDbForProfileId(profileId); + CommonLLTUtils.runOnSQLTerminalRS(preparedstatementHandler); + IQueryResult result = DatabaseUtils.executeOnSqlTerminal( + "select * from tbl1", 1000, database.getConnectionManager().getFreeConnection(), + new MessageQueue()); + long elapsedTimeLong = 109; + String input = "2016-12-16 18:29:09"; + SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + sdf1.setTimeZone(TimeZone.getTimeZone("UTC")); + Date date = sdf1.parse(input); + String dt = sdf1.format(date); + QueryExecutionSummary summary = new QueryExecutionSummary( + "postgres", "ds", "select * from pg_class", true, dt, + elapsedTimeLong, 0); + DSResultSetGridDataProviderInnerTest dsr = new DSResultSetGridDataProviderInnerTest( + result, new IResultConfigTest(), summary); + dsr.init(); + assertEquals("id", colData.getColumnName(0)); + assertEquals("name - ", colData.getColumnDesc(1)); + assertNotNull(colData.getDataTypeName(0)); + assertNotNull(colData.getColumnCount()); + assertNotNull(colData.getColumnIndex("")); + assertNotNull(colData.getColumnIndex("name")); + assertNotNull(colData.getDataTypeNames()); + assertNotNull(colData.getColumnNames()); + assertNotNull(colData.getComparator(1)); + assertNotNull(colData.getPrecision(0)); + assertNotNull(colData.getScale(0)); + assertNotNull(colData.getMaxLength(0)); + } + catch (Exception e) + { + e.printStackTrace(); + fail("Not Expected to come here"); + } + } + + @Test + public void testINIT_FUNC_001_001_3() + { + final class IResultConfigTest implements IResultConfig + { + + @Override + public int getFetchCount() + { + return 1; + } + + @Override + public ActionAfterResultFetch getActionAfterFetch() + { + return ActionAfterResultFetch.CLOSE_CONNECTION_AFTER_FETCH; + } + } + try + { + Database database = connProfCache.getDbForProfileId(profileId); + CommonLLTUtils.runOnSQLTerminalRS(preparedstatementHandler); + IQueryResult result = DatabaseUtils.executeOnSqlTerminal( + "select * from tbl1", 1000, database.getConnectionManager().getFreeConnection(), + new MessageQueue()); + long elapsedTimeLong = 109; + String input = "2016-12-16 18:29:09"; + SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + sdf1.setTimeZone(TimeZone.getTimeZone("UTC")); + Date date = sdf1.parse(input); + String dt = sdf1.format(date); + QueryExecutionSummary summary = new QueryExecutionSummary( + "postgres", "ds", "select * from pg_class", true, dt, + elapsedTimeLong, 0); + DSResultSetGridDataProvider dsr = new DSResultSetGridDataProvider( + result, new IResultConfigTest(), summary); + dsr.init(); + //Observation point - It shouldn't throw any exception while closing the connection after fetching all records + assertTrue(dsr != null); + } + catch (Exception e) + { + e.printStackTrace(); + fail("Not Expected to come here"); + } + } + + @Test + public void testINIT_FUNC_001_004() + { + final class IResultConfigTest implements IResultConfig + { + + @Override + public int getFetchCount() + { + return 1; + } + + @Override + public ActionAfterResultFetch getActionAfterFetch() + { + return ActionAfterResultFetch.ISSUE_COMMIT_CONNECTION_AFTER_FETCH; + } + } + try + { + Database database = connProfCache.getDbForProfileId(profileId); + CommonLLTUtils.runOnSQLTerminalRS(preparedstatementHandler); + IQueryResult result = DatabaseUtils.executeOnSqlTerminal( + "select * from tbl1", 1000, database.getConnectionManager().getFreeConnection(), + new MessageQueue()); + long elapsedTimeLong = 109; + String input = "2016-12-16 18:29:09"; + SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + sdf1.setTimeZone(TimeZone.getTimeZone("UTC")); + Date date = sdf1.parse(input); + String dt = sdf1.format(date); + QueryExecutionSummary summary = new QueryExecutionSummary( + "postgres", "ds", "select * from pg_class", true, dt, + elapsedTimeLong, 0); + DSResultSetGridDataProvider dsr = new DSResultSetGridDataProvider( + result, new IResultConfigTest(), summary); + new DsResultSetGridDataProviderTest().setActionFetchResult(10); + + DefaultParameter dp1 = new DefaultParameter("N1", "BINARY_INTEGER", "5", PARAMETERTYPE.IN); + DefaultParameter dp2 = new DefaultParameter("N2", "BINARY_INTEGER", "5", PARAMETERTYPE.IN); + DefaultParameter dp3 = new DefaultParameter("TEMP_RESULT", "BINARY_INTEGER", "500", PARAMETERTYPE.OUT); + ArrayList debugInputValueList = new ArrayList(); + debugInputValueList.add(dp1); + debugInputValueList.add(dp2); + debugInputValueList.add(dp3); + dsr.init(result, debugInputValueList, true); + } + catch (Exception e) + { + e.printStackTrace(); + fail("Not Expected to come here"); + } + } + + @Test + public void testINIT_FUNC_001_001_5() + { + try + { + ColumnValueSqlTypeComparator cvstTinyInt = new ColumnValueSqlTypeComparator( + new Integer(-6)); + assertEquals(1, cvstTinyInt.compare(Byte.valueOf((byte) 1), + Byte.valueOf((byte) 2))); + ColumnValueSqlTypeComparator cvstSmallInt = new ColumnValueSqlTypeComparator( + new Integer(5)); + assertEquals(1, cvstSmallInt.compare(Short.valueOf((short) 20), + Short.valueOf((short) 10))); + ColumnValueSqlTypeComparator cvstInt = new ColumnValueSqlTypeComparator( + new Integer(4)); + assertEquals(0, cvstInt.compare(100, 100)); + ColumnValueSqlTypeComparator cvstBigInt = new ColumnValueSqlTypeComparator( + new Integer(-5)); + assertEquals(-1, + cvstBigInt.compare(Long.valueOf(10), Long.valueOf(20))); + ColumnValueSqlTypeComparator cvsFloat = new ColumnValueSqlTypeComparator( + new Integer(6)); + assertEquals(0, cvsFloat.compare(20.5f, 20.5f)); + ColumnValueSqlTypeComparator cvsDouble = new ColumnValueSqlTypeComparator( + new Integer(8)); + assertEquals(-1, cvsDouble.compare(Double.valueOf(10.5), + Double.valueOf(15.5))); + ColumnValueSqlTypeComparator cvsNumeric = new ColumnValueSqlTypeComparator( + new Integer(2)); + assertEquals(1, cvsNumeric.compare(new BigDecimal(101.1), new BigDecimal(1.10))); + ColumnValueSqlTypeComparator cvstBool = new ColumnValueSqlTypeComparator( + new Integer(16)); + assertEquals(0, cvstBool.compare(true, true)); + ColumnValueSqlTypeComparator cvstDate = new ColumnValueSqlTypeComparator( + new Integer(91)); + Date date1 = new Date(98, 5, 21); + Date date2 = new Date(99, 1, 9); + java.sql.Date sqlDate1 = new java.sql.Date(date1.getTime()); + java.sql.Date sqlDate2 = new java.sql.Date(date2.getTime()); + assertEquals(-1, cvstDate.compare(sqlDate1, sqlDate2)); + ColumnValueSqlTypeComparator cvstTime = new ColumnValueSqlTypeComparator( + new Integer(92)); + assertEquals(-1, cvstTime.compare(Time.valueOf("00:00:00"), + Time.valueOf("23:59:59"))); + ColumnValueSqlTypeComparator cvstTimeStamp = new ColumnValueSqlTypeComparator( + new Integer(93)); + assertEquals(-1, + cvstTimeStamp.compare(new Timestamp(date1.getTime()), + new Timestamp(date2.getTime()))); + ColumnValueSqlTypeComparator cvstString = new ColumnValueSqlTypeComparator( + new Integer(12)); + assertEquals(-23, cvstString.compare("abc", "xyz")); + ColumnValueSqlTypeComparator cvstNull = new ColumnValueSqlTypeComparator( + new Integer(0)); + assertEquals(1, cvstNull.compare(null, "pqr")); + } + catch (Exception e) + { + e.printStackTrace(); + fail("Not Expected to come here"); + } + } + + @Test + public void testTTA_DSResultSetGridDataRow_test_001() { + final class IResultConfigTest implements IResultConfig { + + @Override + public int getFetchCount() { + return 1; + } + + @Override + public ActionAfterResultFetch getActionAfterFetch() { + return ActionAfterResultFetch.CLOSE_CONNECTION_AFTER_FETCH; + } + } + + try { + Database database = connProfCache.getDbForProfileId(profileId); + + CommonLLTUtils.runOnSQLTerminalBytesRS(preparedstatementHandler); + IQueryResult result = DatabaseUtils.executeOnSqlTerminal("select * from bytes_table", 1000, + database.getConnectionManager().getFreeConnection(), new MessageQueue()); + long elapsedTimeLong = 109; + String input = "2016-12-16 18:29:09"; + SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + sdf1.setTimeZone(TimeZone.getTimeZone("UTC")); + + Date date = sdf1.parse(input); + String dt = sdf1.format(date); + QueryExecutionSummary summary = new QueryExecutionSummary("postgres", "ds", "select * from pg_class", true, + dt, elapsedTimeLong, 0); + DSResultSetGridDataProvider dsr = new DSResultSetGridDataProvider(result, new IResultConfigTest(), summary); + dsr.init(); + + DSResultSetGridDataRow row = new DSResultSetGridDataRow(dsr); + Object[] values = {"A".getBytes(), "B".getBytes(), "C".getBytes(), "D".getBytes(), "E".getBytes()}; + row.setValues(values); + row.setIncludeEncoding(true); + row.setEncoding("UTF-8"); + + assertEquals(row.getValue(0), "A"); + assertEquals(row.getValue(1), "B"); + assertEquals(row.getValue(2), "C"); + assertEquals(row.getValue(3), "D"); + assertEquals(row.getValue(4), "E"); + + assertEquals(row.getEncoding(), "UTF-8"); + + row.setEncoding("Garbage"); + assertFalse(row.getValue(0).equals("A")); + assertFalse(row.getValue(1).equals("B")); + assertFalse(row.getValue(2).equals("C")); + assertFalse(row.getValue(3).equals("D")); + assertFalse(row.getValue(4).equals("E")); + + row.setEncoding("GBK"); + assertTrue(row.getValue(0).equals("A")); + assertTrue(row.getValue(1).equals("B")); + assertTrue(row.getValue(2).equals("C")); + assertTrue(row.getValue(3).equals("D")); + assertTrue(row.getValue(4).equals("E")); + } catch (Exception e) { + e.printStackTrace(); + fail("Not Expected to come here"); + } + + } + + public static class MockListener implements IDSListener + { + + @Override + public void handleEvent(DSEvent event) + { + assertTrue(true); + } + } + + @Test + public void testINIT_FUNC_001_001_4() + { + final class IResultConfigTest implements IResultConfig + { + + @Override + public int getFetchCount() + { + return 1; + } + + @Override + public ActionAfterResultFetch getActionAfterFetch() + { + return ActionAfterResultFetch.CLOSE_CONNECTION_AFTER_FETCH; + } + } + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + CommonLLTUtils.runOnSQLTerminalRS(preparedstatementHandler); + IQueryResult result = DatabaseUtils.executeOnSqlTerminal( + "select * from tbl1", 1000, database.getConnectionManager().getFreeConnection(), + new MessageQueue()); + long elapsedTimeLong = 109; + String input = "2016-12-16 18:29:09"; + SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + sdf1.setTimeZone(TimeZone.getTimeZone("UTC")); + Date date = sdf1.parse(input); + String dt = sdf1.format(date); + QueryExecutionSummary summary = new QueryExecutionSummary( + "postgres", "ds", "select * from pg_class", true, dt, + elapsedTimeLong, 0); + DSResultSetGridDataProvider dsr = new DSResultSetGridDataProvider( + result, new IResultConfigTest(), summary); + dsr.init(); + //Observation point - It shouldn't throw any exception while closing the connection after fetching all records + assertTrue(dsr != null); + dsr.setDatabase(database); + + assertEquals(dsr.getDatabse(), database); + MockListener l = new MockListener(); + dsr.addListener(2, l); + + assertNull(dsr.getTable()); + assertNull(dsr.getColumnGroupProvider()); + assertFalse(dsr.getResultTabDirtyFlag()); + + dsr.setEditSupported(true); + dsr.setEncodingChanged(true); + dsr.changeEncoding("UTF-8"); + + assertTrue(dsr.isEditSupported()); + + dsr.changeEncoding("GBK"); + assertTrue(dsr.isEncodingChanged()); + dsr.preDestroy(); + assertNull(dsr.getSummary()); + } + catch (Exception e) + { + e.printStackTrace(); + fail("Not Expected to come here"); + } + } + + @Test + public void testINIT_FUNC_PROC_001_001() + { + final class IResultConfigTest implements IResultConfig + { + + @Override + public int getFetchCount() + { + return 1; + } + + @Override + public ActionAfterResultFetch getActionAfterFetch() + { + return ActionAfterResultFetch.CLOSE_CONNECTION_AFTER_FETCH; + } + } + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + CommonLLTUtils.runOnSQLTerminalRS(preparedstatementHandler); + String query = "EXEC DSUSER."+"\"ADD_PROC1\""+"\r\n(\r\n\t5,\t--N1 BINARY_INTEGER\r\n\t5,\t--N2 BINARY_INTEGER" + +"\r\n\t?,\t--TEMP_RESULT BINARY_INTEGER" + +"\r\n\t?\t--RESULT BINARY_INTEGER\r\n)"; + IQueryExecutionSummary summary = SQLHistoryFactory.getNewExlainQueryExecutionSummary("DataBase","Server", + "conn", query); + StmtExecutor executor = new StmtExecutor(query, database.getConnectionManager().getFreeConnection()); + StmtExecutor executor1 = new StmtExecutor(query, database.getConnectionManager().getFreeConnection()); + ArrayList outResultList = new ArrayList(); + outResultList.add(500); + executor1.setOutResultList(outResultList ); + QueryResult queryResult = new QueryResult(executor, database.getConnectionManager().getFreeConnection(), + true); + QueryResult queryResult1 = new QueryResult(executor1, database.getConnectionManager().getFreeConnection(), + true); + DSResultSetGridDataProvider dsr = new DSResultSetGridDataProvider( + queryResult, new IResultConfigTest(), summary); + + DSResultSetGridDataProvider dsr1 = new DSResultSetGridDataProvider( + queryResult1, new IResultConfigTest(), summary); + + DefaultParameter dp1 = new DefaultParameter("N1", "BINARY_INTEGER", "5", PARAMETERTYPE.IN); + DefaultParameter dp2 = new DefaultParameter("N2", "BINARY_INTEGER", "5", PARAMETERTYPE.IN); + DefaultParameter dp3 = new DefaultParameter("TEMP_RESULT", "BINARY_INTEGER", "500", PARAMETERTYPE.OUT); + ArrayList debugInputValueList = new ArrayList(); + debugInputValueList.add(dp1); + debugInputValueList.add(dp2); + debugInputValueList.add(dp3); + dsr.init(queryResult, debugInputValueList, true); + dsr1.init(queryResult1, debugInputValueList, true); + assertTrue(dsr != null); + dsr.preDestroy(); + assertNull(dsr.getSummary()); + } + catch (Exception e) + { + e.printStackTrace(); + fail("Not Expected to come here"); + } + } + + + @Test + public void testINIT_FUNC_001_001_Boolean() + { + ColumnValueSqlTypeComparator csvBool = new ColumnValueSqlTypeComparator(Types.BOOLEAN); + assertEquals(1, csvBool.compare("true", "false")); + assertEquals(-1, csvBool.compare("false", "true")); + assertEquals(0,csvBool.compare(1, 2)); + try + { + csvBool.compare("random", "NULL"); + } + catch (Exception e) + { + assertTrue(true); + } + } + + @Test + public void testINIT_FUNC_001_001_Double() + { + ColumnValueSqlTypeComparator csvBool = new ColumnValueSqlTypeComparator(Types.DOUBLE); + assertEquals(1, csvBool.compare("33.67", "23.67")); + assertEquals(-1, csvBool.compare("25.67", "35.67")); + assertEquals(1, csvBool.compare("+33.67", "-23.67")); + assertEquals(1, csvBool.compare("-25.67", "-35.67")); + assertEquals(1,csvBool.compare(1, 2)); + try + { + csvBool.compare("random", "NULL"); + } + catch (Exception e) + { + assertTrue(true); + } + } + + @Test + public void testINIT_FUNC_001_001_Float() + { + ColumnValueSqlTypeComparator csvBool = new ColumnValueSqlTypeComparator(Types.FLOAT); + assertEquals(1, csvBool.compare("33.67", "23.67")); + assertEquals(-1, csvBool.compare("25.67", "35.67")); + assertEquals(1,csvBool.compare(1, 2)); + try + { + csvBool.compare("random", "NULL"); + } + catch (Exception e) + { + assertTrue(true); + } + } + + @Test + public void testINIT_FUNC_001_001_Long() + { + ColumnValueSqlTypeComparator csvBool = new ColumnValueSqlTypeComparator(Types.BIGINT); + assertEquals(1, csvBool.compare("3399999", "34560")); + assertEquals(-1, csvBool.compare("3456", "800000000000000000")); + assertEquals(1,csvBool.compare(1, 2)); + try + { + csvBool.compare("77.0", "23.0"); + } + catch (Exception e) + { + assertTrue(true); + } + } + + @Test + public void testINIT_FUNC_001_001_TimeStamp() + { + ColumnValueSqlTypeComparator csvBool = new ColumnValueSqlTypeComparator(Types.TIMESTAMP); + assertEquals(1, csvBool.compare("02-04-2013 11:35:42", "03-04-2013 11:35:42")); + assertEquals(1, csvBool.compare("03-04-2013 11:35:42", "02-04-2013 11:35:42")); + assertEquals(1, csvBool.compare("02-04-2013 11:40:42", "02-04-2013 11:35:42")); + assertEquals(1, csvBool.compare("11:35:42", "11:35:45")); + assertEquals(1,csvBool.compare(1, 2)); + try + { + csvBool.compare("random", "NULL"); + } + catch (Exception e) + { + assertTrue(true); + } + } + + @Test + public void testINIT_FUNC_001_001_Time() + { + ColumnValueSqlTypeComparator csvBool = new ColumnValueSqlTypeComparator(Types.TIME); + assertEquals(1, csvBool.compare("02-04-2013 11:35:42", "03-04-2013 11:35:42")); + assertEquals(1, csvBool.compare("03-04-2013 11:35:42", "02-04-2013 11:35:42")); + assertEquals(1, csvBool.compare("02-04-2013 11:40:42", "02-04-2013 11:35:42")); + assertEquals(1, csvBool.compare("11:35:42", "11:35:42")); + assertEquals(1,csvBool.compare(1, 2)); + try + { + csvBool.compare("random", "NULL"); + } + catch (Exception e) + { + assertTrue(true); + } + } + + @Test + public void testINIT_FUNC_001_001_Date() + { + ColumnValueSqlTypeComparator csvBool = new ColumnValueSqlTypeComparator(Types.DATE); + assertEquals(1, csvBool.compare("2015-03-31", "2015-02-31")); + assertEquals(-1, csvBool.compare("2015-01-23", "2015-03-31")); + assertEquals(1,csvBool.compare(1, 2)); + try + { + csvBool.compare("03-04-2013:00:00:00", "02-04-2013:00:00:00"); + } + catch (Exception e) + { + assertTrue(true); + } + } + + private void fetchALLDBMSJobs() { + String query = "SELECT job,log_user," + + "priv_user,dbname,last_date,this_date,next_date,broken,interval,failures,what FROM USER_JOBS where dbname = ?"; + MockResultSet functionParamRs = preparedstatementHandler.createResultSet(); + functionParamRs.addColumn("job"); + functionParamRs.addColumn("log_user"); + functionParamRs.addColumn("priv_user"); + functionParamRs.addColumn("dbname"); + functionParamRs.addColumn("last_date"); + functionParamRs.addColumn("this_date"); + functionParamRs.addColumn("next_date"); + functionParamRs.addColumn("broken"); + functionParamRs.addColumn("interval"); + functionParamRs.addColumn("failures"); + functionParamRs.addColumn("what"); + functionParamRs.addRow(new Object[] {1, "DSUSER", "DSUSER", "DSUSER", "2020-2-11 00:00:00.0", null, + "2020-2-11 00:00:00.0", "N", "sysdate", 0, "function();"}); + preparedstatementHandler.prepareResultSet(query, functionParamRs); + } + + private void fetchALLSynonyms() { + String fetchAllsynonys = SynonymUtil.FETCH_SYNONYM_STATEMENT; + MockResultSet fetchAllsynonysRS = preparedstatementHandler.createResultSet(); + fetchAllsynonysRS.addColumn("synonym_name"); + fetchAllsynonysRS.addColumn("owner"); + fetchAllsynonysRS.addColumn("schema_name"); + fetchAllsynonysRS.addColumn("table_name"); + fetchAllsynonysRS.addRow(new Object[] {"syn1", "user", "user", "tbl1"}); + preparedstatementHandler.prepareResultSet(fetchAllsynonys, fetchAllsynonysRS); + + String refresh = SynonymMetaData.REFRESH_SYNONYM_STATEMENT; + MockResultSet fetchAllsynonysRefresh = preparedstatementHandler.createResultSet(); + fetchAllsynonysRefresh.addColumn("synonym_name"); + fetchAllsynonysRefresh.addColumn("owner"); + fetchAllsynonysRefresh.addColumn("schema_name"); + fetchAllsynonysRefresh.addColumn("table_name"); + fetchAllsynonysRefresh.addRow(new Object[] {"syn1", "user", "user", "tbl1"}); + preparedstatementHandler.prepareResultSet(refresh, fetchAllsynonysRefresh); + } + + @Test + public void test_AutoRefresh_01() { + Database database = connProfCache.getDbForProfileId(profileId); + RefreshObjectDetails refreshObj = new RefreshObjectDetails(); + Namespace ns1 = new UserNamespace(6, "ns1", database); + refreshObj.setDesctNamespace(ns1); + assertNotNull(refreshObj.getDesctNamespace()); + refreshObj.setObjToBeRefreshed(ns1); + assertNotNull(refreshObj.getObjToBeRefreshed()); + refreshObj.setOperationType("NameSpace"); + assertEquals(refreshObj.getOperationType(), "NameSpace"); + refreshObj.setObjectName("table1"); + assertEquals(refreshObj.getObjectName(), "table1"); + refreshObj.setParent(ns1); + assertNotNull(refreshObj.getParent()); + refreshObj.setNamespace(ns1); + assertNotNull(refreshObj.getNamespace()); + assertNotNull(refreshObj.getClone()); + } + + @Test + public void test_ConstraintInfo() { + ConstraintInfo info = new ConstraintInfo(); + info.setConstraintExpr("where"); + info.setColumns("col1"); + info.setConstraintType("conditional"); + info.setConstraintName("WHERE"); + info.setTablespace("TablseSpace1"); + info.setConsSchema("DS_USER"); + info.setDeferred(true); + assertEquals(info.getConstraintExpr(), "where"); + assertEquals(info.getColumns(), "col1"); + assertEquals(info.getConstraintType(), "conditional"); + assertEquals(info.getConstraintName(), "WHERE"); + assertEquals(info.getTableSpace(), "TablseSpace1"); + assertEquals(info.getConsSchema(), "DS_USER"); + assertTrue(info.isDeferred()); + } + + @Test + public void test_TerminalExecutionConnectionInfra() { + Database database = connProfCache.getDbForProfileId(profileId); + TerminalExecutionConnectionInfra infra = new TerminalExecutionConnectionInfra(); + try { + infra.setConnection(database.getConnectionManager().getFreeConnection()); + assertNotNull(infra.getConnection()); + infra.setDatabase(database); + assertNotNull(infra.getDatabase()); + assertTrue(infra.isConnected()); + infra.releaseConnection(); + infra.setReconnectOnTerminal(true); + assertTrue(infra.isReconnectOnTerminal()); + + + } catch (MPPDBIDEException e) { + fail("not expected to come here"); + } + } + + @Test + public void test_DSObjectPropertiesGridDataRow() { + Object[] row = new Object[] {"row1"}; + DSObjectPropertiesGridDataRow gridRow = new DSObjectPropertiesGridDataRow(row); + gridRow.getValues(); + gridRow.getValue(0); + } + + @Test + public void test_AutoRefresh_02() { + Database database = connProfCache.getDbForProfileId(profileId); + RefreshObjectDetails refreshObj = new RefreshObjectDetails(); + Namespace ns1 = new UserNamespace(6, "ns1", database); + refreshObj.setDesctNamespace(ns1); + refreshObj.setObjToBeRefreshed(ns1); + refreshObj.setParent(ns1); + refreshObj.setNamespace(ns1); + HashSet listOfObjects = new HashSet(); + + refreshObj.setOperationType(MPPDBIDEConstants.CREATE_TABLE); + refreshObj.setObjectName("table1"); + String newlycreatedTableQuery = "select tbl.relname relname,tbl.parttype parttype,tbl.relnamespace relnamespace" + + ",tbl.oid oid,ts.spcname as reltablespace,tbl.relpersistence relpersistence," + + " d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions" + + " from pg_class tbl left join (select d.description, d.objoid from pg_description" + + " d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on " + + "(tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace" + + " where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.relname = 'table1'" + + " and tbl.relnamespace= 6"; + MockResultSet fetchRS = preparedstatementHandler.createResultSet(); + fetchRS.addColumn(""); + fetchRS.addRow(new Object[] {}); + preparedstatementHandler.prepareResultSet(newlycreatedTableQuery, fetchRS); + + AutoRefreshQueryFormation.getObjectToBeRefreshed(refreshObj, listOfObjects); + assertFalse(listOfObjects.isEmpty()); + } + @Test + public void test_set_schema_table() { + Database database = connProfCache.getDbForProfileId(profileId); + RefreshObjectDetails refreshObj = new RefreshObjectDetails(); + Namespace ns1 = new UserNamespace(6, "ns1", database); + + Namespace ns2 = new UserNamespace(7, "ns2", database); + TableMetaData table=new TableMetaData(1,"table1",ns2,""); + ns2.addTableToGroup(table); + + refreshObj.setDesctNamespace(ns1); + refreshObj.setObjToBeRefreshed(ns1); + refreshObj.setParent(ns1); + refreshObj.setNamespace(ns2); + HashSet listOfObjects = new HashSet(); + + refreshObj.setOperationType(MPPDBIDEConstants.SET_SCHEMA_TABLE); + refreshObj.setObjectName("table1"); + String newlycreatedTableQuery = "select tbl.relname relname,tbl.parttype parttype,tbl.relnamespace relnamespace" + + ",tbl.oid oid,ts.spcname as reltablespace,tbl.relpersistence relpersistence," + + " d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions" + + " from pg_class tbl left join (select d.description, d.objoid from pg_description" + + " d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on " + + "(tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace" + + " where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.relname = 'table1'" + + " and tbl.relnamespace= 6"; + MockResultSet fetchRS = preparedstatementHandler.createResultSet(); + fetchRS.addColumn(""); + fetchRS.addRow(new Object[] {}); + preparedstatementHandler.prepareResultSet(newlycreatedTableQuery, fetchRS); + + AutoRefreshQueryFormation.getObjectToBeRefreshed(refreshObj, listOfObjects); + assertFalse(listOfObjects.isEmpty()); + } + @Test + public void test_AutoRefresh_create_view() { + Database database = connProfCache.getDbForProfileId(profileId); + RefreshObjectDetails refreshObj = new RefreshObjectDetails(); + Namespace ns1 = new UserNamespace(6, "ns1", database); + refreshObj.setDesctNamespace(ns1); + refreshObj.setObjToBeRefreshed(ns1); + refreshObj.setParent(ns1); + refreshObj.setNamespace(ns1); + HashSet listOfObjects = new HashSet(); + + refreshObj.setOperationType(MPPDBIDEConstants.CREATE_VIEW); + refreshObj.setObjectName("table1"); + String newlycreatedTableQuery = "SELECT c.oid, n.oid as nspoid, n.nspname AS schemaname, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner, c.relkind as relkind FROM (pg_class c LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace))) WHERE (c.relkind = 'v'::\"char\") and c.relname='table1' and n.nspname='ns1';"; + MockResultSet fetchRS = preparedstatementHandler.createResultSet(); + fetchRS.addColumn(""); + fetchRS.addRow(new Object[] {}); + preparedstatementHandler.prepareResultSet(newlycreatedTableQuery, fetchRS); + + AutoRefreshQueryFormation.getObjectToBeRefreshed(refreshObj, listOfObjects); + assertFalse(listOfObjects.isEmpty()); + } + @Test + public void test_AutoRefresh_setSchema_view() { + Database database = connProfCache.getDbForProfileId(profileId); + RefreshObjectDetails refreshObj = new RefreshObjectDetails(); + Namespace ns1 = new UserNamespace(6, "ns1", database); + + Namespace ns2 = new UserNamespace(7, "ns2", database); + ViewMetaData view=new ViewMetaData(1,"table1",ns2,database); + ns2.addView(view); + + refreshObj.setDesctNamespace(ns1); + refreshObj.setObjToBeRefreshed(ns1); + refreshObj.setParent(ns1); + refreshObj.setNamespace(ns2); + HashSet listOfObjects = new HashSet(); + + refreshObj.setOperationType(MPPDBIDEConstants.SET_SCHEMA_VIEW); + refreshObj.setObjectName("table1"); + String newlycreatedTableQuery = "SELECT c.oid, n.oid as nspoid, n.nspname AS schemaname, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner, c.relkind as relkind FROM (pg_class c LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace))) WHERE (c.relkind = 'v'::\"char\") and c.relname='table1' and n.nspname='ns1';"; + MockResultSet fetchRS = preparedstatementHandler.createResultSet(); + fetchRS.addColumn(""); + fetchRS.addRow(new Object[] {}); + preparedstatementHandler.prepareResultSet(newlycreatedTableQuery, fetchRS); + + AutoRefreshQueryFormation.getObjectToBeRefreshed(refreshObj, listOfObjects); + assertFalse(listOfObjects.isEmpty()); + } + @Test + public void test_AutoRefresh_alter_table() { + Database database = connProfCache.getDbForProfileId(profileId); + RefreshObjectDetails refreshObj = new RefreshObjectDetails(); + Namespace ns1 = new UserNamespace(6, "ns1", database); + TableMetaData table=new TableMetaData(1,"table1",ns1,""); + ns1.addTableToGroup(table); + refreshObj.setDesctNamespace(ns1); + refreshObj.setObjToBeRefreshed(table); + refreshObj.setParent(ns1); + refreshObj.setNamespace(ns1); + HashSet listOfObjects = new HashSet(); + + refreshObj.setOperationType(MPPDBIDEConstants.ALTER_TABLE); + refreshObj.setObjectName("table1"); + String newlycreatedTableQuery = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1;"; + MockResultSet fetchRS = preparedstatementHandler.createResultSet(); + fetchRS.addColumn(""); + fetchRS.addRow(new Object[] {}); + preparedstatementHandler.prepareResultSet(newlycreatedTableQuery, fetchRS); + + + String constraint="SELECT c.oid as constraintid, c.conrelid as tableid, c.connamespace as namespaceid, c.conname as constraintname, c.contype as constrainttype, c.condeferrable as deferrable, c.condeferred as deferred, c.convalidated as validate, c.conindid as indexid, c.confrelid as fkeytableId, c.confupdtype as updatetype, c.confdeltype as deletetype, c.confmatchtype as matchtype, c.consrc as expr, c.conkey as columnlist, c.confkey as fkeycolumnlist, pg_get_constraintdef(c.oid) as const_def FROM pg_constraint c where c.conrelid = 1;"; + MockResultSet fetchRS1 = preparedstatementHandler.createResultSet(); + fetchRS1.addColumn(""); + fetchRS1.addRow(new Object[] {}); + preparedstatementHandler.prepareResultSet(constraint, fetchRS1); + + String index="SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, ci.relnamespace as namespaceid, ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, i.indisexclusion as isexclusion, i.indimmediate as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, i.indisready as isready, i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions, def.indexdef , def.tablespace FROM pg_index i LEFT JOIN pg_class t on (t.oid = i.indrelid) LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) LEFT JOIN pg_namespace ns on (ci.relnamespace = ns.oid) LEFT JOIN pg_indexes def on (ci.relname = def.indexname and ns.nspname = def.schemaname) WHERE t.relkind = 'r' and t.oid = 1;"; + MockResultSet fetchRS2 = preparedstatementHandler.createResultSet(); + fetchRS2.addColumn(""); + fetchRS2.addRow(new Object[] {}); + preparedstatementHandler.prepareResultSet(index, fetchRS2); + AutoRefreshQueryFormation.getObjectToBeRefreshed(refreshObj, listOfObjects); + assertFalse(listOfObjects.isEmpty()); + } + @Test + public void test_AutoRefresh_alter_View() { + Database database = connProfCache.getDbForProfileId(profileId); + RefreshObjectDetails refreshObj = new RefreshObjectDetails(); + Namespace ns1 = new UserNamespace(6, "ns1", database); + ViewMetaData view=new ViewMetaData(1,"table1",ns1,database); + ns1.addView(view); + refreshObj.setDesctNamespace(ns1); + refreshObj.setObjToBeRefreshed(view); + refreshObj.setParent(ns1); + refreshObj.setNamespace(ns1); + HashSet listOfObjects = new HashSet(); + + refreshObj.setOperationType(MPPDBIDEConstants.ALTER_VIEW); + refreshObj.setObjectName("table1"); + String newlycreatedTableQuery = "SELECT c.oid, n.oid as nspoid, n.nspname AS schemaname, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner FROM (pg_class c LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace))) WHERE (c.relkind = 'v'::\"char\") and c.oid=1;"; + MockResultSet fetchRS = preparedstatementHandler.createResultSet(); + fetchRS.addColumn(""); + fetchRS.addRow(new Object[] {}); + preparedstatementHandler.prepareResultSet(newlycreatedTableQuery, fetchRS); + + + String constraint="select v.oid as viewid, v.relnamespace as namespaceid, c.attnum as columnidx, c.attname as name, pg_catalog.format_type(c.atttypid, c.atttypmod) as displayColumns, c.atttypid as datatypeoid, typ.typnamespace as dtns, c.attlen as length, c.atttypmod as precision, c.attndims as dimentions, c.attnotnull as notnull, c.atthasdef as isdefaultvalueavailable, d.adsrc as default_value, d.adbin as attDefStr from pg_class v left join pg_attribute c on (v.oid = c.attrelid and v.relkind = 'v') left join pg_attrdef d on (v.oid = d.adrelid and c.attnum = d.adnum) left join pg_type typ on (c.atttypid = typ.oid) where c.attisdropped = 'f' and c.attnum > 0 and v.oid = 1 order by v.oid, c.attnum"; + MockResultSet fetchRS1 = preparedstatementHandler.createResultSet(); + fetchRS1.addColumn(""); + fetchRS1.addRow(new Object[] {}); + preparedstatementHandler.prepareResultSet(constraint, fetchRS1); + + String index="SELECT i.indexrelid as oid, i.indrelid as tableId, ci.relname as indexname, ci.relnamespace as namespaceid, ci.relam as accessmethodid, i.indisunique as isunique, i.indisprimary as isprimary, i.indisexclusion as isexclusion, i.indimmediate as isimmediate, i.indisclustered as isclustered, i.indcheckxmin as checkmin, i.indisready as isready, i.indkey as cols, array_to_string(ci.reloptions, ',') as reloptions, def.indexdef , def.tablespace FROM pg_index i LEFT JOIN pg_class t on (t.oid = i.indrelid) LEFT JOIN pg_class ci on (i.indexrelid = ci.oid) LEFT JOIN pg_namespace ns on (ci.relnamespace = ns.oid) LEFT JOIN pg_indexes def on (ci.relname = def.indexname and ns.nspname = def.schemaname) WHERE t.relkind = 'r' and t.oid = 1;"; + MockResultSet fetchRS2 = preparedstatementHandler.createResultSet(); + fetchRS2.addColumn(""); + fetchRS2.addRow(new Object[] {}); + preparedstatementHandler.prepareResultSet(index, fetchRS2); + AutoRefreshQueryFormation.getObjectToBeRefreshed(refreshObj, listOfObjects); + assertFalse(listOfObjects.isEmpty()); + } + @Test + public void test_AutoRefresh_drop_View() { + Database database = connProfCache.getDbForProfileId(profileId); + RefreshObjectDetails refreshObj = new RefreshObjectDetails(); + Namespace ns1 = new UserNamespace(6, "ns1", database); + ViewMetaData view=new ViewMetaData(1,"table1",ns1,database); + ns1.addView(view); + refreshObj.setDesctNamespace(ns1); + refreshObj.setObjToBeRefreshed(view); + refreshObj.setParent(ns1); + refreshObj.setNamespace(ns1); + HashSet listOfObjects = new HashSet(); + + refreshObj.setOperationType(MPPDBIDEConstants.DROP_VIEW); + refreshObj.setObjectName("table1"); + + AutoRefreshQueryFormation.getObjectToBeRefreshed(refreshObj, listOfObjects); + assertFalse(listOfObjects.isEmpty()); + } + @Test + public void test_AutoRefresh_drop_table() { + Database database = connProfCache.getDbForProfileId(profileId); + RefreshObjectDetails refreshObj = new RefreshObjectDetails(); + Namespace ns1 = new UserNamespace(6, "ns1", database); + TableMetaData table=new TableMetaData(1,"table1",ns1,""); + ns1.addTableToGroup(table); + refreshObj.setDesctNamespace(ns1); + refreshObj.setObjToBeRefreshed(table); + refreshObj.setParent(ns1); + refreshObj.setNamespace(ns1); + HashSet listOfObjects = new HashSet(); + + refreshObj.setOperationType(MPPDBIDEConstants.DROP_TABLE); + refreshObj.setObjectName("table1"); + + AutoRefreshQueryFormation.getObjectToBeRefreshed(refreshObj, listOfObjects); + assertFalse(listOfObjects.isEmpty()); + } + + + @Test + public void test_SynonymInfo_01() { + fetchALLSynonyms(); + Database database = connProfCache.getDbForProfileId(profileId); + Namespace ns1 = new UserNamespace(6, "ns1", database); + try { + ns1.loadSynonyms(database.getConnectionManager().getFreeConnection()); + } catch (MPPDBIDEException e) { + e.printStackTrace(); + } + SynonymInfo info = new SynonymInfo(ns1.getSynonymGroup()); + info.setObjectName("objName"); + assertNotNull(info.getObjectName()); + info.setObjectOwner("objOwner"); + assertNotNull(info.getObjectOwner()); + info.setObjectType("objType"); + assertNotNull(info.getObjectType()); + info.setOwner("owner"); + assertNotNull(info.getOwner()); + info.setSynonymName("syn1"); + assertNotNull(info.getSynonymName()); + info.setReplaceIfExist(true); + assertNotNull(info.getNamespace()); + assertNotNull(info.getNameSpaceName()); + assertNotNull(info.generateCreateSynonymSql()); + + SynonymWrapper wrapper = new SynonymWrapper(ns1.getSynonymGroup(), info); + assertNotNull(wrapper.getMetadata()); + assertNotNull(wrapper.getMetadata().getDatabaseName()); + assertNotNull(wrapper.getMetadata().getServer()); + assertNotNull(wrapper.getMetadata().getServerName()); + assertNotNull(wrapper.getMetadata().getDatabase()); + assertNotNull(wrapper.getMetadata().getDropName()); + assertNotNull(wrapper.getMetadata().getWindowTitleName()); + assertNotNull(wrapper.getDatabase()); + + String fetchsynonyProp = "select * from sys.all_synonyms sy1 where sy1.schema_name = ? and sy1.synonym_name = ?"; + MockResultSet fetchsynonyPropRS = preparedstatementHandler.createResultSet(); + fetchsynonyPropRS.addColumn("synonym_name"); + fetchsynonyPropRS.addColumn("owner"); + fetchsynonyPropRS.addColumn("schema_name"); + fetchsynonyPropRS.addColumn("table_name"); + fetchsynonyPropRS.addRow(new Object[] {"syn1", "user", "user", "tbl1"}); + preparedstatementHandler.prepareResultSet(fetchsynonyProp, fetchsynonyPropRS); + try { + DBConnection conn = wrapper.getDatabase().getConnectionManager().getFreeConnection(); + wrapper.getMetadata().refresh(conn); + wrapper.executeComposeQuery(conn); + wrapper.refresh(conn); + wrapper.getMetadata().dropSynonym(conn, false); + PropertiesSynonymImpl impl = new PropertiesSynonymImpl(wrapper.getMetadata()); + assertNotNull(impl.getDatabase()); + assertNotNull(impl.getHeader()); + assertNotNull(impl.getObjectName()); + assertNotNull(impl.getUniqueID()); + assertNotNull(impl.getAllProperties(conn)); + + } catch (MPPDBIDEException e) { + e.printStackTrace(); + } + } + + @Test + public void test_SynonymInfo_02() { + fetchALLSynonyms(); + Database database = connProfCache.getDbForProfileId(profileId); + Namespace ns1 = new UserNamespace(6, "ns1", database); + try { + ns1.loadSynonyms(database.getConnectionManager().getFreeConnection()); + } catch (MPPDBIDEException e) { + e.printStackTrace(); + } + String all = "select tbl.relname relname from pg_class tbl left join" + + " pg_partition part on(tbl.oid=part.parentid and part.parttype='r')" + + " where tbl.relkind = 'r' and tbl.relnamespace = 6 UNION SELECT" + + " c.relname AS relname FROM pg_class c WHERE (c.relkind = 'f' :: char)" + + " and c.relnamespace = 6 UNION SELECT c.relname AS relname " + + "FROM pg_class c WHERE (c.relkind = 'v' :: char or c.relkind = 'm' :: char) and c.relnamespace = 6" + + " UNION SELECT pr.proname relname FROM pg_proc pr JOIN pg_type typ ON" + + " typ.oid = prorettype JOIN pg_namespace typns ON typns.oid = typ.typnamespace" + + " JOIN pg_language lng ON lng.oid = prolang and pronamespace = 6 and" + + " has_function_privilege(pr.oid, 'EXECUTE') ORDER BY relname"; + MockResultSet fetchAllRS = preparedstatementHandler.createResultSet(); + fetchAllRS.addColumn("relname"); + fetchAllRS.addRow(new Object[] {"table1"}); + fetchAllRS.addRow(new Object[] {"function1"}); + fetchAllRS.addRow(new Object[] {"view1"}); + fetchAllRS.addRow(new Object[] {"materview1"}); + preparedstatementHandler.prepareResultSet(all, fetchAllRS); + + String funcProc = "SELECT pr.proname relname FROM pg_proc pr JOIN pg_type typ " + + "ON typ.oid = prorettype JOIN pg_namespace typns ON typns.oid = typ.typnamespace" + + " JOIN pg_language lng ON lng.oid = prolang and pronamespace = 6 " + + "and has_function_privilege(pr.oid, 'EXECUTE') ORDER BY relname"; + MockResultSet fetchfuncProcRS = preparedstatementHandler.createResultSet(); + fetchfuncProcRS.addColumn("relname"); + fetchfuncProcRS.addRow(new Object[] {"function1"}); + preparedstatementHandler.prepareResultSet(funcProc, fetchfuncProcRS); + + String table = "select tbl.relname relname from pg_class tbl left join pg_partition" + + " part on(tbl.oid=part.parentid and part.parttype='r') where tbl.relkind = 'r'" + + " and tbl.relnamespace = 6 UNION SELECT c.relname AS relname FROM pg_class c" + + " WHERE (c.relkind = 'f' :: char) and c.relnamespace = 6"; + MockResultSet fetchtableRS = preparedstatementHandler.createResultSet(); + fetchtableRS.addColumn("relname"); + fetchtableRS.addRow(new Object[] {"table1"}); + preparedstatementHandler.prepareResultSet(table, fetchtableRS); + + String view = "SELECT c.relname AS relname FROM pg_class c WHERE (c.relkind = 'v' :: char or c.relkind = 'm' :: char)" + + " and c.relnamespace = 6 "; + MockResultSet fetchviewRS = preparedstatementHandler.createResultSet(); + fetchviewRS.addColumn("relname"); + fetchviewRS.addRow(new Object[] {"view1"}); + fetchviewRS.addRow(new Object[] {"materview1"}); + preparedstatementHandler.prepareResultSet(view, fetchviewRS); + + DBConnection conn; + try { + conn = database.getConnectionManager().getFreeConnection(); + assertNotNull(SynonymObjectGroup.fetchObjectName(ns1, conn, "owner", MPPDBIDEConstants.PRIVILEGE_ALL)); + assertNotNull(SynonymObjectGroup.fetchObjectName(ns1, conn, "owner", "Functions/Procedures")); + assertNotNull(SynonymObjectGroup.fetchObjectName(ns1, conn, "owner", "Regular Tables")); + assertNotNull(SynonymObjectGroup.fetchObjectName(ns1, conn, "owner", "Views")); + assertNotNull(SynonymObjectGroup.fetchObjectName(ns1, conn, "owner", "")); + } catch (MPPDBIDEException e) { + fail("Not Expected to come here"); + } + SynonymObjectGroup objGrp = ns1.getSynonymGroup(); + assertTrue(objGrp.equals(objGrp)); + assertNotNull(objGrp.hashCode()); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/ExportExcelApachePOITest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/ExportExcelApachePOITest.java new file mode 100644 index 0000000000000000000000000000000000000000..2bd24e7988ddac6d59b96e3eda42696f0235b64e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/ExportExcelApachePOITest.java @@ -0,0 +1,1715 @@ +package org.opengauss.mppdbide.test.presentation.properties; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.Date; +import java.sql.Timestamp; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.Properties; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.postgresql.util.HostSpec; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.importexportdata.ImportExportDataExecuter; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintType; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DefaultParameter; +import org.opengauss.mppdbide.bl.serverdatacache.ImportExportOption; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.ObjectParameter.PARAMETERTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.bl.serverdatacache.SystemNamespace; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TypeMetaData; +import org.opengauss.mppdbide.mock.presentation.BaseConnectionHelper; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.mock.presentation.ResultSetMetaDataImplementation; +import org.opengauss.mppdbide.presentation.exportdata.ExportCursorExecuteVisitor; +import org.opengauss.mppdbide.presentation.exportdata.ExportCursorExecuteVisitor.ColumnDataType; +import org.opengauss.mppdbide.test.presentation.table.MockPresentationBLPreferenceImpl; +import org.opengauss.mppdbide.presentation.exportdata.ExportCursorQueryExecuter; +import org.opengauss.mppdbide.presentation.exportdata.ExportExcelApachePOI; +import org.opengauss.mppdbide.presentation.exportdata.ImportExportDataCore; +import org.opengauss.mppdbide.utils.CustomStringUtility; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DataStudioSecurityException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.exceptions.PasswordExpiryException; +import org.opengauss.mppdbide.utils.exceptions.TableImporExportException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; +import com.mockrunner.mock.jdbc.MockResultSet; +import static org.junit.Assert.*; + +public class ExportExcelApachePOITest extends BasicJDBCTestCaseAdapter +{ + + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + private DBConnection dbconn; + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#setUp() + */ + @Before + public void setUp() throws Exception + { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + connection = new MockConnection(); + MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + this.dbconn = CommonLLTUtils.getDBConnection(); + preparedstatementHandler = connection.getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + + connProfCache = DBConnProfCache.getInstance(); + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + MockPresentationBLPreferenceImpl.setFileEncoding("UTF-8"); + MockPresentationBLPreferenceImpl.setDateFormat("yyyy-MM-dd"); + MockPresentationBLPreferenceImpl.setTimeFormat("HH:mm:ss"); + + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + // serverInfo.setSslPassword("12345"); + // serverInfo.setServerType(DATABASETYPE.GAUSS); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception + { + super.tearDown(); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().close(); + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) + { + connProfCache.removeServer(itr.next().getId()); + } + + connProfCache.closeAllNodes(); + + } + + @Test + public void testTTA_EXPORT_RESULT_001_01() + { + try + { + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + Server server = new Server(serverInfo); + Database database = new Database(server, 2, "Gauss"); + Properties properties = new Properties(); + + properties.setProperty("user", serverInfo.getDsUsername()); + properties.setProperty("password", new String(serverInfo.getPrd())); + properties.setProperty("allowEncodingChanges", "true"); + String encoding = System.getProperty("file.encoding"); + properties.setProperty("characterEncoding", encoding); + properties.setProperty("ApplicationName", "Data Studio"); + + BaseConnectionHelper connectionHelper = new BaseConnectionHelper("", properties, + new HostSpec[] {new HostSpec("127.0.0.1", 1111)}, "db", "user", false); + + getJDBCMockObjectFactory().getMockDriver().setupConnection(connectionHelper); + CommonLLTUtils.mockServerEncoding(connectionHelper.getPreparedStatementResultSetHandler()); + CommonLLTUtils.mockCheckDebugSupport(connectionHelper.getPreparedStatementResultSetHandler()); + CommonLLTUtils.mockCheckExplainPlanSupport(connectionHelper.getPreparedStatementResultSetHandler()); + database.connectToServer(); + Namespace namespace = new SystemNamespace(1, "pg_catalog", database); + database.getSystemNamespaceGroup().addToGroup((SystemNamespace) namespace); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(true); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(database, new ArrayList(Arrays.asList("col1")), + "select * from pg_catalog.\"MyTable\" ;", "", null); + core.setImportExportoptions(option); + core.validateImportExportOptParameters(); + core.initializeCore(); + core.setFilePath(Paths.get("myfile.csv")); + String query = core.composeQuery(); + assertEquals("COPY (select * from pg_catalog.\"MyTable\" ;) TO STDOUT DELIMITER ',' HEADER CSV ;", query); + core.executeExportData(CommonLLTUtils.getDBConnection(), false); + assertTrue(true); + } + catch (DatabaseOperationException e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void testTTA_EXPORT_RESULT_001_02() + { + try + { + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + Server server = new Server(serverInfo); + Database database = new Database(server, 2, "Gauss"); + Properties properties = new Properties(); + + properties.setProperty("user", serverInfo.getDsUsername()); + properties.setProperty("password", new String(serverInfo.getPrd())); + properties.setProperty("allowEncodingChanges", "true"); + String encoding = System.getProperty("file.encoding"); + properties.setProperty("characterEncoding", encoding); + properties.setProperty("ApplicationName", "Data Studio"); + + BaseConnectionHelper connectionHelper = new BaseConnectionHelper("", properties, + new HostSpec[] {new HostSpec("127.0.0.1", 1111)}, "db", "user", false); + + getJDBCMockObjectFactory().getMockDriver().setupConnection(connectionHelper); + CommonLLTUtils.mockServerEncoding(connectionHelper.getPreparedStatementResultSetHandler()); + CommonLLTUtils.mockCheckDebugSupport(connectionHelper.getPreparedStatementResultSetHandler()); + CommonLLTUtils.mockCheckExplainPlanSupport(connectionHelper.getPreparedStatementResultSetHandler()); + database.connectToServer(); + Namespace namespace = new SystemNamespace(1, "pg_catalog", database); + database.getSystemNamespaceGroup().addToGroup((SystemNamespace) namespace); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Binary"); + option.setHeader(true); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(database, new ArrayList(Arrays.asList("col1")), + "select * from pg_catalog.\"MyTable\" ;", "", null); + core.setImportExportoptions(option); + core.validateImportExportOptParameters(); + core.initializeCore(); + core.setFilePath(Paths.get("myfile.bin")); + String query = core.composeQuery(); + assertEquals("COPY (select * from pg_catalog.\"MyTable\" ;) TO STDOUT BINARY ;", query); + core.executeExportData(CommonLLTUtils.getDBConnection(), false); + assertTrue(true); + } + catch (DatabaseOperationException e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void testTTA_EXPORT_RESULT_001_03() + { + + try + { + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + Server server = new Server(serverInfo); + Database database = new Database(server, 2, "Gauss"); + Properties properties = new Properties(); + + properties.setProperty("user", serverInfo.getDsUsername()); + properties.setProperty("password", new String(serverInfo.getPrd())); + properties.setProperty("allowEncodingChanges", "true"); + String encoding = System.getProperty("file.encoding"); + properties.setProperty("characterEncoding", encoding); + properties.setProperty("ApplicationName", "Data Studio"); + + BaseConnectionHelper connectionHelper = new BaseConnectionHelper("", properties, + new HostSpec[] {new HostSpec("127.0.0.1", 1111)}, "db", "user", false); + + getJDBCMockObjectFactory().getMockDriver().setupConnection(connectionHelper); + CommonLLTUtils.mockServerEncoding(connectionHelper.getPreparedStatementResultSetHandler()); + CommonLLTUtils.mockCheckDebugSupport(connectionHelper.getPreparedStatementResultSetHandler()); + CommonLLTUtils.mockCheckExplainPlanSupport(connectionHelper.getPreparedStatementResultSetHandler()); + database.connectToServer(); + Namespace namespace = new SystemNamespace(1, "pg_catalog", database); + database.getSystemNamespaceGroup().addToGroup((SystemNamespace) namespace); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter("#"); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = + new ImportExportDataCore(database, new ArrayList(Arrays.asList("col1")), + "select * from pg_catalog.\"MyTable\" ;", "", null); + core.setImportExportoptions(option); + core.initializeCore(); + core.setFilePath(Paths.get("myfile.csv")); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY (select * from pg_catalog.\"MyTable\" ;) TO STDOUT DELIMITER '#' CSV ;", query); + core.executeExportData(CommonLLTUtils.getDBConnection(), false); + assertTrue(true); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void testTTA_EXPORT_RESULT_001_04() + { + + try + { + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + Server server = new Server(serverInfo); + Database database = new Database(server, 2, "Gauss"); + Properties properties = new Properties(); + + properties.setProperty("user", serverInfo.getDsUsername()); + properties.setProperty("password", new String(serverInfo.getPrd())); + properties.setProperty("allowEncodingChanges", "true"); + String encoding = System.getProperty("file.encoding"); + properties.setProperty("characterEncoding", encoding); + properties.setProperty("ApplicationName", "Data Studio"); + + BaseConnectionHelper connectionHelper = new BaseConnectionHelper("", properties, + new HostSpec[] {new HostSpec("127.0.0.1", 1111)}, "db", "user", false); + + getJDBCMockObjectFactory().getMockDriver().setupConnection(connectionHelper); + CommonLLTUtils.mockServerEncoding(connectionHelper.getPreparedStatementResultSetHandler()); + CommonLLTUtils.mockCheckDebugSupport(connectionHelper.getPreparedStatementResultSetHandler()); + CommonLLTUtils.mockCheckExplainPlanSupport(connectionHelper.getPreparedStatementResultSetHandler()); + database.connectToServer(); + Namespace namespace = new SystemNamespace(1, "pg_catalog", database); + database.getSystemNamespaceGroup().addToGroup((SystemNamespace) namespace); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(false); + option.setQuotes("\""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding("UTF-8"); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = + new ImportExportDataCore(database, new ArrayList(Arrays.asList("col1")), + "select * from pg_catalog.\"MyTable\" ;", "", null); + core.setImportExportoptions(option); + core.initializeCore(); + core.setFilePath(Paths.get("myfile.csv")); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals( + "COPY (select * from pg_catalog.\"MyTable\" ;) TO STDOUT DELIMITER ',' CSV QUOTE '\"' ENCODING 'UTF-8' ;", + query); + core.executeExportData(CommonLLTUtils.getDBConnection(), false); + assertTrue(true); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void testTTA_EXPORT_RESULT_001_05() + { + + try + { + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + Server server = new Server(serverInfo); + Database database = new Database(server, 2, "Gauss"); + Properties properties = new Properties(); + + properties.setProperty("user", serverInfo.getDsUsername()); + properties.setProperty("password", new String(serverInfo.getPrd())); + properties.setProperty("allowEncodingChanges", "true"); + String encoding = System.getProperty("file.encoding"); + properties.setProperty("characterEncoding", encoding); + properties.setProperty("ApplicationName", "Data Studio"); + + BaseConnectionHelper connectionHelper = new BaseConnectionHelper("", properties, + new HostSpec[] {new HostSpec("127.0.0.1", 1111)}, "db", "user", false); + + getJDBCMockObjectFactory().getMockDriver().setupConnection(connectionHelper); + CommonLLTUtils.mockServerEncoding(connectionHelper.getPreparedStatementResultSetHandler()); + CommonLLTUtils.mockCheckDebugSupport(connectionHelper.getPreparedStatementResultSetHandler()); + CommonLLTUtils.mockCheckExplainPlanSupport(connectionHelper.getPreparedStatementResultSetHandler()); + database.connectToServer(); + Namespace namespace = new SystemNamespace(1, "pg_catalog", database); + database.getSystemNamespaceGroup().addToGroup((SystemNamespace) namespace); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + // Empty Quote + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("CSV"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding("UTF-8"); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = + new ImportExportDataCore(database, new ArrayList(Arrays.asList("col1")), + "select * from pg_catalog.\"MyTable\" ;", "", null); + core.setImportExportoptions(option); + core.initializeCore(); + core.setFilePath(Paths.get("myfile.csv")); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals( + "COPY (select * from pg_catalog.\"MyTable\" ;) TO STDOUT DELIMITER ',' CSV ENCODING 'UTF-8' ;", + query); + core.executeExportData(CommonLLTUtils.getDBConnection(), false); + assertTrue(core != null); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + + // Quote with special character && Empty Escape character && Empty + // NULL string + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("CSV"); + option.setHeader(false); + option.setQuotes("&"); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding("UTF-8"); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = + new ImportExportDataCore(database, new ArrayList(Arrays.asList("col1")), + "select * from pg_catalog.\"MyTable\" ;", "", null); + core.setImportExportoptions(option); + core.initializeCore(); + core.setFilePath(Paths.get("myfile.csv")); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals( + "COPY (select * from pg_catalog.\"MyTable\" ;) TO STDOUT DELIMITER ',' CSV QUOTE '&' ENCODING 'UTF-8' ;", + query); + core.executeExportData(CommonLLTUtils.getDBConnection(), false); + assertTrue(core != null); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + + // Single Escape character + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("CSV"); + option.setHeader(false); + option.setQuotes("&"); + option.setEscape("g"); + option.setReplaceNull(""); + option.setEncoding("UTF-8"); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = + new ImportExportDataCore(database, new ArrayList(Arrays.asList("col1")), + "select * from pg_catalog.\"MyTable\" ;", "", null); + core.setImportExportoptions(option); + core.initializeCore(); + core.setFilePath(Paths.get("myfile.csv")); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals( + "COPY (select * from pg_catalog.\"MyTable\" ;) TO STDOUT DELIMITER ',' CSV QUOTE '&' ESCAPE 'g' ENCODING 'UTF-8' ;", + query); + core.executeExportData(CommonLLTUtils.getDBConnection(), false); + assertTrue(core != null); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + + // Escape character with special character + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("CSV"); + option.setHeader(false); + option.setQuotes("&"); + option.setEscape("@"); + option.setReplaceNull(""); + option.setEncoding("UTF-8"); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = + new ImportExportDataCore(database, new ArrayList(Arrays.asList("col1")), + "select * from pg_catalog.\"MyTable\" ;", "", null); + core.setImportExportoptions(option); + core.initializeCore(); + core.setFilePath(Paths.get("myfile.csv")); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals( + "COPY (select * from pg_catalog.\"MyTable\" ;) TO STDOUT DELIMITER ',' CSV QUOTE '&' ESCAPE '@' ENCODING 'UTF-8' ;", + query); + core.executeExportData(CommonLLTUtils.getDBConnection(), false); + assertTrue(core != null); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + + // Having NULL parameter less than 100 character && Empty Encoding + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("CSV"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull("1234"); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = + new ImportExportDataCore(database, new ArrayList(Arrays.asList("col1")), + "select * from pg_catalog.\"MyTable\" ;", "", null); + core.setImportExportoptions(option); + core.initializeCore(); + core.setFilePath(Paths.get("myfile.csv")); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY (select * from pg_catalog.\"MyTable\" ;) TO STDOUT DELIMITER ',' NULL '1234' CSV ;", + query); + core.executeExportData(CommonLLTUtils.getDBConnection(), false); + assertTrue(core != null); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + + // Having NULL parameter as Special character + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("CSV"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull("&"); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = + new ImportExportDataCore(database, new ArrayList(Arrays.asList("col1")), + "select * from pg_catalog.\"MyTable\" ;", "", null); + core.setImportExportoptions(option); + core.initializeCore(); + core.setFilePath(Paths.get("myfile.csv")); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY (select * from pg_catalog.\"MyTable\" ;) TO STDOUT DELIMITER ',' NULL '&' CSV ;", + query); + core.executeExportData(CommonLLTUtils.getDBConnection(), false); + assertTrue(core != null); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void testTTA_ImportExportDataCore() + { + Database database = connProfCache.getDbForProfileId(profileId); + + try + { + TableMetaData tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + ImportExportOption option = new ImportExportOption(); + option.setFileFormat("Csv"); + option.setQuotes(""); + option.setEscape("a"); + option.getQuotes().length(); + option.getEscape().length(); + String exec = "executedQuery"; + + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col1")), exec, null, null); + + String tablename = tableMetaData.getDisplayName(); + assertEquals("Exported data from table: pg_catalog.\"MyTable\"", core.getDisplayName()); + } + + catch (DatabaseOperationException e) + { + fail(e.getMessage()); + + } + } + + @Test + public void testTTA_ImportExportDataCore_getDisplayTableName() + { + Database database = connProfCache.getDbForProfileId(profileId); + + try + { + TableMetaData tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + ImportExportOption option = new ImportExportOption(); + option.setFileFormat("Csv"); + option.setQuotes(""); + option.setEscape("a"); + option.getQuotes().length(); + option.getEscape().length(); + String exec = "executedQuery"; + + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col1")), exec, null, null); + + + } + + catch (DatabaseOperationException e) + { + fail(e.getMessage()); + + } + } + + @Test + public void testTTA_ImportExportDataCore_getDatabase() + { + Database database = connProfCache.getDbForProfileId(profileId); + + try + { + TableMetaData tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + ImportExportOption option = new ImportExportOption(); + option.setFileFormat("Csv"); + option.setQuotes(""); + option.setEscape("a"); + option.getQuotes().length(); + option.getEscape().length(); + String exec = "executedQuery"; + + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col1")), exec, null, null); + + String tablename = tableMetaData.getDisplayName(); + String name = tableMetaData.getBottombarDisplayName(); + + Database db = core.getDatabase(); + assertEquals(tableMetaData.getDatabase(), core.getDatabase()); + assertEquals("pg_catalog.MyTable", name); + } + + catch (DatabaseOperationException e) + { + fail(e.getMessage()); + + } + + } + + @Test + public void testTTA_ImportExportDataCore_getPath() + { + Database database = connProfCache.getDbForProfileId(profileId); + + try + { + TableMetaData tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + Path path = Paths.get("D:/dstest/abc1.sql"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + ImportExportOption option = new ImportExportOption(); + option.setFileFormat("Csv"); + option.setQuotes(""); + option.setEscape("a"); + option.getQuotes().length(); + option.getEscape().length(); + String exec = "executedQuery"; + + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col1")), exec, null, null); + core.setFilePath(path); + Path print = core.getFilePath(); + + assertEquals(print, core.getFilePath()); + } + + catch (DatabaseOperationException e) + { + fail(e.getMessage()); + + } + + } + + @Test + public void testTTA_ImportExportDataCore_getFileName() + { + Database database = connProfCache.getDbForProfileId(profileId); + + try + { + TableMetaData tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + ImportExportOption option = new ImportExportOption(); + option.setFileFormat("Csv"); + option.setQuotes(""); + option.setEscape("a"); + option.getQuotes().length(); + option.getEscape().length(); + String exec = "executedQuery"; + + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col1")), exec, null, null); + + core.getFileName(); + + assertEquals("MyTable", core.getFileName()); + } + + catch (DatabaseOperationException e) + { + fail(e.getMessage()); + + } + + } + + + public void testTTA_ExportExcel_XLSX_001() + { + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Excel(xlsx)"); + option.setHeader(true); + option.setQuotes("\""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.setFilePath(Paths.get("./firstExcel.xlsx")); + ExportCursorQueryExecuter exportExecuter = new ExportCursorQueryExecuter( + "select * from pg_catalog.MyTable;", database.getConnectionManager().getFreeConnection()); + String uniqCursorName = exportExecuter.getUniqCursorName(); + MockResultSet getselectrs = statementHandler.createResultSet(); + getselectrs.addColumn("Col1"); + getselectrs.addRow(new Object[] {2}); + + statementHandler.prepareResultSet(uniqCursorName, getselectrs); + ExportCursorExecuteVisitor executeVisitor = new ExportCursorExecuteVisitor(core.getFilePath(), + option.getEncoding(), option.getFileFormat(), core.getSafeSheetName(), true); + long exportExcelData = exportExecuter.exportExcelData(executeVisitor, false); + assertEquals(1, exportExcelData); + + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void testTTA_ExportExcel_XLS_002() + { + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Excel(xls)"); + option.setHeader(true); + option.setQuotes("\""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.setFilePath(Paths.get("./firstExcel.xls")); + ExportCursorQueryExecuter exportExecuter = new ExportCursorQueryExecuter( + "select * from pg_catalog.MyTable;", database.getConnectionManager().getFreeConnection()); + String uniqCursorName = exportExecuter.getUniqCursorName(); + MockResultSet getselectrs = statementHandler.createResultSet(); + getselectrs.addColumn("Col1"); + getselectrs.addRow(new Object[] {2}); + + statementHandler.prepareResultSet(uniqCursorName, getselectrs); + ExportCursorExecuteVisitor executeVisitor = new ExportCursorExecuteVisitor(core.getFilePath(), + option.getEncoding(), option.getFileFormat(), core.getSafeSheetName(), true); + long exportExcelData = exportExecuter.exportExcelData(executeVisitor, false); + assertEquals(1, exportExcelData); + executeVisitor.cleanUpworkbook(); + + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + + public void testTTA_ExportExcel_XLSX_MultipleDatatype_003() + { + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn1 = new ColumnMetaData(tablemetaData, 2, "Col2", + new TypeMetaData(1, "float8", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn2 = new ColumnMetaData(tablemetaData, 3, "Col3", + new TypeMetaData(1, "float4", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn3 = new ColumnMetaData(tablemetaData, 4, "Col4", + new TypeMetaData(1, "date", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn4 = new ColumnMetaData(tablemetaData, 5, "Col5", + new TypeMetaData(1, "timestamp", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn5 = new ColumnMetaData(tablemetaData, 6, "Col6", + new TypeMetaData(1, "timestamptz", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn6 = new ColumnMetaData(tablemetaData, 7, "Col7", + new TypeMetaData(1, "bool", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + tablemetaData.getColumns().addItem(newTempColumn1); + tablemetaData.getColumns().addItem(newTempColumn2); + tablemetaData.getColumns().addItem(newTempColumn3); + tablemetaData.getColumns().addItem(newTempColumn4); + tablemetaData.getColumns().addItem(newTempColumn5); + tablemetaData.getColumns().addItem(newTempColumn6); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Excel(xlsx)"); + option.setHeader(true); + option.setQuotes("\""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns( + new ArrayList(Arrays.asList("col1", "col2", "col3", "col4", "col5", "col6", "col7"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1", "col2", "col3", "col4", "col5", "col6", "col7")), + null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.setFilePath(Paths.get("./firstExcel.xlsx")); + ExportCursorQueryExecuter exportExecuter = new ExportCursorQueryExecuter( + "select * from pg_catalog.MyTable;", database.getConnectionManager().getFreeConnection()); + String uniqCursorName = exportExecuter.getUniqCursorName(); + MockResultSet getselectrs = statementHandler.createResultSet(); + getselectrs.setResultSetMetaData(new ResultSetMetaDataImplementation()); + getselectrs.addColumn("Col1"); + getselectrs.addColumn("Col2"); + getselectrs.addColumn("Col3"); + getselectrs.addColumn("Col4"); + getselectrs.addColumn("Col5"); + getselectrs.addColumn("Col6"); + getselectrs.addColumn("Col7"); + getselectrs.addRow(new Object[] {2, 2.04, 1.004, "2018-09-18 16:37:06", "2018-09-18 16:37:06", + "2018-09-18 16:37:06", true}); + + statementHandler.prepareResultSet(uniqCursorName, getselectrs); + ExportCursorExecuteVisitor executeVisitor = new ExportCursorExecuteVisitor(core.getFilePath(), + option.getEncoding(), option.getFileFormat(), core.getSafeSheetName(), true); + long exportExcelData = exportExecuter.exportExcelData(executeVisitor, false); + assertEquals(1, exportExcelData); + + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void testTTA_ExportExcel_XLS_MultipleDatatype_004() + { + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn1 = new ColumnMetaData(tablemetaData, 2, "Col2", + new TypeMetaData(1, "float8", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn2 = new ColumnMetaData(tablemetaData, 3, "Col3", + new TypeMetaData(1, "float4", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn3 = new ColumnMetaData(tablemetaData, 4, "Col4", + new TypeMetaData(1, "date", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn4 = new ColumnMetaData(tablemetaData, 5, "Col5", + new TypeMetaData(1, "timestamp", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn5 = new ColumnMetaData(tablemetaData, 6, "Col6", + new TypeMetaData(1, "timestamptz", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn6 = new ColumnMetaData(tablemetaData, 7, "Col7", + new TypeMetaData(1, "bool", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + tablemetaData.getColumns().addItem(newTempColumn1); + tablemetaData.getColumns().addItem(newTempColumn2); + tablemetaData.getColumns().addItem(newTempColumn3); + tablemetaData.getColumns().addItem(newTempColumn4); + tablemetaData.getColumns().addItem(newTempColumn5); + tablemetaData.getColumns().addItem(newTempColumn6); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Excel(xls)"); + option.setHeader(true); + option.setQuotes("\""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setEncoding("UTF-8"); + option.setTablecolumns( + new ArrayList(Arrays.asList("col1", "col2", "col3", "col4", "col5", "col6", "col7"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1", "col2", "col3", "col4", "col5", "col6", "col7")), + null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.setFilePath(Paths.get("./firstExcel.xls")); + ExportCursorQueryExecuter exportExecuter = new ExportCursorQueryExecuter( + "select * from pg_catalog.MyTable;", database.getConnectionManager().getFreeConnection()); + String uniqCursorName = exportExecuter.getUniqCursorName(); + MockResultSet getselectrs = statementHandler.createResultSet(); + getselectrs.setResultSetMetaData(new ResultSetMetaDataImplementation()); + getselectrs.addColumn("Col1"); + getselectrs.addColumn("Col2"); + getselectrs.addColumn("Col3"); + getselectrs.addColumn("Col4"); + getselectrs.addColumn("Col5"); + getselectrs.addColumn("Col6"); + getselectrs.addColumn("Col7"); + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + long time = sdf.parse("2018-09-18 16:37:06").getTime(); + Timestamp timeStampValue = new Timestamp(time); + + getselectrs.addRow(new Object[] {2, 2.04, 1.004, new Date(System.currentTimeMillis()), timeStampValue, + timeStampValue, true}); + statementHandler.prepareResultSet(uniqCursorName, getselectrs); + ExportCursorExecuteVisitor executeVisitor = new ExportCursorExecuteVisitor(core.getFilePath(), + option.getEncoding(), option.getFileFormat(), core.getSafeSheetName(), true); + long exportExcelData = exportExecuter.exportExcelData(executeVisitor, false); + assertEquals(1, exportExcelData); + + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + + public void testTTA_ExportExcel_XLSX_cleanupWorkbook() + { + try + { + + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Excel(xlsx)"); + option.setHeader(true); + option.setQuotes("\""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.setFilePath(Paths.get("./firstExcel.xlsx")); + ExportCursorQueryExecuter exportExecuter = new ExportCursorQueryExecuter( + "select * from pg_catalog.MyTable;", database.getConnectionManager().getFreeConnection()); + String uniqCursorName = exportExecuter.getUniqCursorName(); + MockResultSet getselectrs = statementHandler.createResultSet(); + getselectrs.addColumn("Col1"); + getselectrs.addRow(new Object[] {2}); + statementHandler.prepareResultSet(uniqCursorName, getselectrs); + ExportCursorExecuteVisitor executeVisitor = new ExportCursorExecuteVisitor(core.getFilePath(), + option.getEncoding(), option.getFileFormat(), core.getSafeSheetName(), true); + executeVisitor.getHeaderOfRecord(getselectrs, true, false); + core.cleanUp(); + executeVisitor.cleanUpworkbook(); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void testExportExcel_without_cursor() + { + Database database = connProfCache.getDbForProfileId(profileId); + try + { + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Excel(xlsx)"); + option.setHeader(true); + option.setQuotes("\""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(database, + new ArrayList(Arrays.asList("col1")), "select * from pg_catalog.MyTable;", "Result_Tab", "20180909"); + core.setImportExportoptions(option); + core.initializeCore(); + core.getFileFormat(); + core.getImportExportServerObj(); + core.getImportExportoptions(); + core.importExportCleanUp(); + core.cancelImportExportOperation(); + core.setFilePath(Paths.get("./firstExcel.xlsx")); + assertTrue(core.isOLAPDB()); + assertEquals(core.getFileName(), "Result_Tab" + '_' + + CustomStringUtility.convertStringDateFormat("20180909", + MPPDBIDEConstants.DATE_COLLAPSE_FORMAT)); + core.setFileLocation("./firstExcel.xlsx"); + assertEquals(core.getFileLocation(), "./firstExcel.xlsx"); + core.setExportIsInProgress(true); + core.setExport(true); + assertEquals(option.isExport(), true); + String uniqCursorName = core.composeExcelQuery(); + DefaultParameter dp1 = new DefaultParameter("N1", "BINARY_INTEGER", "5", PARAMETERTYPE.IN); + DefaultParameter dp2 = new DefaultParameter("N2", "BINARY_INTEGER", "5", PARAMETERTYPE.IN); + DefaultParameter dp3 = new DefaultParameter("TEMP_RESULT", "BINARY_INTEGER", "500", PARAMETERTYPE.OUT); + ArrayList debugInputValueList = new ArrayList(); + debugInputValueList.add(dp1); + debugInputValueList.add(dp2); + debugInputValueList.add(dp3); + ArrayList outResultList = new ArrayList(); + outResultList.add(500); + MockResultSet getselectrs = statementHandler.createResultSet(); + getselectrs.addColumn("Col1"); + getselectrs.addColumn("col02"); + getselectrs.addColumn("col03"); + getselectrs.addColumn("col04"); + getselectrs.addColumn("col05"); + getselectrs.addColumn("col06"); + getselectrs.addRow(new Object[] {2, "ITEMT1", 25, 12.25, false, "2019-10-16 11:00:00"}); + getselectrs.addRow(new Object[] {2}); + statementHandler.prepareResultSet(uniqCursorName, getselectrs); + ExportCursorExecuteVisitor executeVisitor = new ExportCursorExecuteVisitor(core.getFilePath(), + option.getEncoding(), option.getFileFormat(), core.getSafeSheetName(), true); + executeVisitor.getHeaderOfRecord(getselectrs, true, false); + } + catch (MPPDBIDEException e1) + { + fail("Not excepted to come here"); + } + } + + @Test + public void testTTA_ExportExcel_XLSX_rowCount() + { + ExportExcelApachePOI exportExcel = new ExportExcelApachePOI("Excel(xlsx)"); + boolean lessRows = exportExcel.checkRowLength(10); + boolean moreRows = exportExcel.checkRowLength(1000001); + assertTrue(lessRows); + assertFalse(moreRows); + } + + @Test + public void testTTA_ExportExcel_XLS_rowCount() + { + ExportExcelApachePOI exportExcel = new ExportExcelApachePOI("Excel(xls)"); + boolean lessRows = exportExcel.checkRowLength(10); + boolean moreRows = exportExcel.checkRowLength(64001); + assertTrue(lessRows); + assertFalse(moreRows); + } + + @Test + public void testTTA_ExportExcel_XLSX_colCount() + { + ExportExcelApachePOI exportExcel = new ExportExcelApachePOI("Excel(xlsx)"); + try + { + exportExcel.createSheet("xlsxSheet"); + exportExcel.setCellValue(Arrays.asList("2", "", "false", "2019-10-16 11:00:00", "25.2"), 1); + } + catch (ParseException e) + { + fail("Not excepted to come here"); + } + catch (DatabaseOperationException e) + { + fail("Not excepted to come here"); + } + boolean lessCol = exportExcel.checkColLength(10); + boolean moreCol = exportExcel.checkColLength(16385); + assertTrue(lessCol); + assertFalse(moreCol); + } + + @Test + public void testTTA_ExportExcel_XLS_colCount() + { + ExportExcelApachePOI exportExcel = new ExportExcelApachePOI("Excel(xls)"); + try + { + exportExcel.createSheet("xlsSheet"); + exportExcel.setCellValue(Arrays.asList("2", "", "false"), 1); + } + catch (ParseException e) + { + fail("Not excepted to come here"); + } + catch (DatabaseOperationException e) + { + fail("Not excepted to come here"); + } + boolean lessCol = exportExcel.checkColLength(10); + boolean moreCol = exportExcel.checkColLength(257); + assertTrue(lessCol); + assertFalse(moreCol); + } + + @Test + public void testTTA_ExportExcel_executeExportData() + { + try + { + + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Excel(xlsx)"); + option.setHeader(true); + option.setQuotes("\""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(database, + new ArrayList(Arrays.asList("col1")), "select * from pg_catalog.MyTable;", "Result_Tab", "20180909"); + core.setImportExportoptions(option); + core.initializeCore(); + core.getFileFormat(); + core.getImportExportServerObj(); + core.getImportExportoptions(); + core.importExportCleanUp(); + core.cancelImportExportOperation(); + core.setFilePath(Paths.get("./firstExcel.xlsx")); + assertTrue(core.isOLAPDB()); + assertEquals(core.getFileName(), "Result_Tab" + '_' + + CustomStringUtility.convertStringDateFormat("20180909", + MPPDBIDEConstants.DATE_COLLAPSE_FORMAT)); + core.setFileLocation("./firstExcel.xlsx"); + assertEquals(core.getFileLocation(), "./firstExcel.xlsx"); + core.setExportIsInProgress(true); + core.setExport(true); + assertEquals(option.isExport(), true); + String uniqCursorName = core.composeExcelQuery(); + MockResultSet getselectrs = statementHandler.createResultSet(); + getselectrs.addColumn("Col1"); + getselectrs.addRow(new Object[] {2}); + statementHandler.prepareResultSet(uniqCursorName, getselectrs); + core.executeExportData(database.getConnectionManager().getFreeConnection(), true); + assertTrue(core!=null); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + assertTrue(true); + } + } + + @Test + public void testTTA_ImportExportDataCore_getProgressLabelName() + { + Database database = connProfCache.getDbForProfileId(profileId); + + try + { + TableMetaData tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + ImportExportOption option = new ImportExportOption(); + option.setFileFormat("Excel(xls)"); + option.setEncoding("UTF-8"); + option.setExport(true); + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + + String progressLabelName = core.getProgressLabelName(); + assertEquals("MyTable.pg_catalog.Gauss@TestConnectionName", progressLabelName); + } + + catch (DatabaseOperationException e) + { + fail(e.getMessage()); + + } + catch (MPPDBIDEException e) + { + fail(e.getMessage()); + + } + } + + @Test + public void testTTA_ExportExcel_XLSX_createTitle() { + try { + ExportExcelApachePOI poi = new ExportExcelApachePOI("Excel(xlsx)", true); + poi.createSheet("xsshSheet"); + poi.createHeaderRow(Arrays.asList("c1", "c2")); + poi.setCellValue(Arrays.asList("11", "22"), 1); + } catch (Exception e) { + fail("can\'t run here"); + } + } + + @Test + public void testTTA_ExportExcel_XLSX_createTitle_01() { + try { + ExportExcelApachePOI poi = new ExportExcelApachePOI("Excel(xlsx)"); + poi.createSheet("xsshSheet"); + poi.createHeaderRow(Arrays.asList("c1", "c2")); + poi.setCellValue(Arrays.asList("11", "22"), 1); + } catch (Exception e) { + fail("can\'t run here"); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/PropertiesTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/PropertiesTest.java new file mode 100644 index 0000000000000000000000000000000000000000..046db519e8196bacc3d131be67d6f1b7628abaca --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/PropertiesTest.java @@ -0,0 +1,4146 @@ +package org.opengauss.mppdbide.test.presentation.properties; + +import java.io.IOException; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintType; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DebugObjects; +import org.opengauss.mppdbide.bl.serverdatacache.IndexMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.PartitionMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.PartitionTable; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.SystemNamespace; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TypeMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.UserRole; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils.EXCEPTIONENUM; +import org.opengauss.mppdbide.mock.presentation.ExceptionConnection; +import org.opengauss.mppdbide.mock.presentation.MockUserRoleManagerUtils; +import org.opengauss.mppdbide.presentation.PropertyOperationType; +import org.opengauss.mppdbide.presentation.edittabledata.CommitStatus; +import org.opengauss.mppdbide.presentation.edittabledata.IDSGridEditDataRow; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.presentation.objectproperties.DSObjectPropertiesGridDataProvider; +import org.opengauss.mppdbide.presentation.objectproperties.DSObjectPropertiesGridDataRow; +import org.opengauss.mppdbide.presentation.objectproperties.IObjectPropertyData; +import org.opengauss.mppdbide.presentation.objectproperties.IServerObjectProperties; +import org.opengauss.mppdbide.presentation.objectproperties.ObjectPropColumnTabInfo; +import org.opengauss.mppdbide.presentation.objectproperties.PropertiesDatabaseImpl; +import org.opengauss.mppdbide.presentation.objectproperties.PropertiesPartitionTableImpl; +import org.opengauss.mppdbide.presentation.objectproperties.PropertiesTableImpl; +import org.opengauss.mppdbide.presentation.objectproperties.factory.ServerFactory; +import org.opengauss.mppdbide.presentation.objectproperties.handler.IPropertyDetail; +import org.opengauss.mppdbide.presentation.objectproperties.handler.PropertyHandlerCore; +import org.opengauss.mppdbide.test.presentation.table.MockPresentationBLPreferenceImpl; +import org.opengauss.mppdbide.test.presentation.table.ServerVersionTest; +import org.opengauss.mppdbide.utils.JSQLParserUtils; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.exceptions.PasswordExpiryException; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; +import com.mockrunner.mock.jdbc.MockResultSet; +import static org.junit.Assert.*; + +public class PropertiesTest extends BasicJDBCTestCaseAdapter +{ + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + ServerConnectionInfo serverInfo; + JobCancelStatus status; + public static final String serverip = "127.0.0.1"; + private StringBuilder builder; + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#setUp() + */ + @Before + public void setUp() throws Exception + { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + connection = new MockConnection(); + MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + preparedstatementHandler = connection.getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + CommonLLTUtils.columnComments(preparedstatementHandler); + CommonLLTUtils.getPartitionData(preparedstatementHandler); + CommonLLTUtils.getConstaraintForTableRS(preparedstatementHandler); + CommonLLTUtils.getPropertiesConstraint(preparedstatementHandler); + CommonLLTUtils.getIndexForTableRS(preparedstatementHandler); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + connProfCache = DBConnProfCache.getInstance(); + + serverInfo = new ServerConnectionInfo(); + status = new JobCancelStatus(); + status.setCancel(false); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + MockPresentationBLPreferenceImpl.setFileEncoding("UTF-8"); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + // serverInfo.setSslPassword("12345"); + // serverInfo.setServerType(DATABASETYPE.GAUSS); + + // Database database = connProfCache.getDbForProfileId(profileId); + // database.getServer().setServerCompatibleToNodeGroup(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception + { + super.tearDown(); + + Database database = connProfCache.getDbForProfileId(profileId); + if (database != null) + { + database.getServer().close(); + } + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) + { + connProfCache.removeServer(itr.next().getId()); + itr = connProfCache.getServers().iterator(); + } + + connProfCache.closeAllNodes(); + + } + + @Test + public void testgetServerfactoryObject() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + ServerFactory factory = new ServerFactory(); + Database database = connProfCache.getDbForProfileId(profileId); + IServerObjectProperties iServerObject1 = factory.getObject(null, null); + assertTrue(iServerObject1 == null); + IServerObjectProperties iServerObject = factory.getObject(database, PropertyOperationType.PROPERTY_OPERATION_VIEW); + assertTrue(iServerObject instanceof PropertiesDatabaseImpl); + TableMetaData tablemetaData = null; + PartitionTable partTable = null; + try + { + tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + partTable = new PartitionTable(database.getNameSpaceById(1)); + } + catch (DatabaseOperationException e) + { + e.printStackTrace(); + } + IServerObjectProperties iServerObject3 = factory.getObject(tablemetaData, PropertyOperationType.PROPERTY_OPERATION_VIEW); + assertTrue(iServerObject3 instanceof PropertiesTableImpl); + IServerObjectProperties iServerObject4 = factory.getObject(partTable, PropertyOperationType.PROPERTY_OPERATION_VIEW); + assertTrue(iServerObject4 instanceof PropertiesPartitionTableImpl); + IServerObjectProperties iServerObject5 = factory.getObject(new Object(), PropertyOperationType.PROPERTY_OPERATION_VIEW); + assertTrue(iServerObject5 == null); + } + + @Test + public void testIsExecutableForDatabase() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + boolean istrue; + PropertyHandlerCore core = new PropertyHandlerCore(database); + istrue = core.isExecutable(); + assertTrue(istrue); + } + + @Test + public void testIsExecutableForTable() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = null; + try + { + tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + } + catch (DatabaseOperationException e) + { + + + e.printStackTrace(); + } + boolean istrue; + PropertyHandlerCore core1 = new PropertyHandlerCore(tablemetaData); + istrue = core1.isExecutable(); + assertTrue(istrue); + } + + @Test + public void testIsExecutableForInvalidServerObject() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Namespace namespace = database.getAllNameSpaces().get(0); + + boolean istrue; + PropertyHandlerCore core1 = new PropertyHandlerCore(namespace); + istrue = core1.isExecutable(); + assertFalse(istrue); + } + + @Test + public void testgetpropertyWindowUId() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + try + { + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().setServerCompatibleToNodeGroup(true); + CommonLLTUtils.getDataBasePtropertiesRS(preparedstatementHandler); + PropertyHandlerCore core = new PropertyHandlerCore(database); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + String tableType = "u"; + + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, tableType); + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getConstaraintForTableRS(preparedstatementHandler); + CommonLLTUtils.getIndexForTableRS(preparedstatementHandler); + PropertyHandlerCore coret = new PropertyHandlerCore(tablemetaData); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + coret.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + IPropertyDetail prop = core.getproperty(); + IPropertyDetail propt = coret.getproperty(); + assertEquals("65TestConnectionNameproperties", propt.getUniqueID()); + assertEquals("65TestConnectionNameproperties", prop.getUniqueID()); + } + catch (MPPDBIDEException e) + { + fail("not expected"); + } + catch (SQLException e) + { + fail("not expected"); + } + } + + @Test + public void testgetpropertyWindowTitle() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + try + { + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().setServerCompatibleToNodeGroup(true); + CommonLLTUtils.getDataBasePtropertiesRS(preparedstatementHandler); + + PropertyHandlerCore core = new PropertyHandlerCore(database); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + String tableType = "u"; + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getConstaraintForTableRS(preparedstatementHandler); + CommonLLTUtils.getIndexForTableRS(preparedstatementHandler); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, tableType); + + PropertyHandlerCore coret = new PropertyHandlerCore(tablemetaData); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + coret.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + IPropertyDetail prop = core.getproperty(); + IPropertyDetail propt = coret.getproperty(); + assertEquals("pg_catalog.MyTable-Gauss@TestConnectionName", propt.getHeader()); + assertEquals("Gauss@TestConnectionName", prop.getHeader()); + } + catch (MPPDBIDEException e) + { + fail("not expected"); + } + catch (SQLException e) + { + fail("not expected"); + } + } + + @Test + public void testgetPropertyDatabase() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + try + { + CommonLLTUtils.createDataBaseRS(preparedstatementHandler); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + + Database database = connProfCache.getDbForProfileId(profileId); + + CommonLLTUtils.getDataBasePtropertiesRS(preparedstatementHandler); + + PropertyHandlerCore core = new PropertyHandlerCore(database); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + IPropertyDetail prop = core.getproperty(); + assertTrue(prop.objectproperties().size() > 0); + + } + catch (Exception e) + { + fail(e.getMessage()); + } + } + + @Test + public void testtablegetProperty() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + try + { + CommonLLTUtils.createTableRS(preparedstatementHandler); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().setServerCompatibleToNodeGroup(true); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + String tableType = "u"; + + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, tableType); + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getIndexForTableRS(preparedstatementHandler); + PropertyHandlerCore core = new PropertyHandlerCore(tablemetaData); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + IPropertyDetail prop = core.getproperty(); + assertTrue(prop.objectproperties().size() > 0); + } + catch (Exception e) + { + fail(e.getMessage()); + } + } + + @Test + public void testtablegetProperty_forOptions() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + try + { + CommonLLTUtils.createTableRS(preparedstatementHandler); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().setServerCompatibleToNodeGroup(true); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + String tableType = "u"; + + CommonLLTUtils.getTablePtropertiesRS_forOptions(preparedstatementHandler, tableType); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, tableType); + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getIndexForTableRS(preparedstatementHandler); + PropertyHandlerCore core = new PropertyHandlerCore(tablemetaData); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + IPropertyDetail prop = core.getproperty(); + assertTrue(prop.objectproperties().size() > 0); + } + catch (Exception e) + { + fail(e.getMessage()); + } + } + + @Test + public void test_tablegetProperty_TableDoesNotExist() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + try + { + CommonLLTUtils.createTableRS(preparedstatementHandler); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().setServerCompatibleToNodeGroup(true); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + String tableType = "u"; + + CommonLLTUtils.getTablePtropertiesRS_TableDoesNotExist(preparedstatementHandler, tableType); + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getIndexForTableRS(preparedstatementHandler); + PropertyHandlerCore core = new PropertyHandlerCore(tablemetaData); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + IPropertyDetail prop = core.getproperty(); + } + catch (DatabaseOperationException e) + { + assertTrue(true); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + } + + catch (SQLException e) + { + fail("not expected"); + } + } + + public void test_tablegetProperty_SQLException() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + + ExceptionConnection exceptionConnection = new ExceptionConnection(); + exceptionConnection.setNeedExceptioStatement(true); + exceptionConnection.setNeedExceptionResultset(true); + exceptionConnection.setThrowExceptionNext(true); + exceptionConnection.setThrownResultSetNext(EXCEPTIONENUM.EXCEPTION); + + getJDBCMockObjectFactory().getMockDriver().setupConnection(exceptionConnection); + + String query = + "SELECT tbl.relpersistence as relpersistence, case when tbl.reltablespace = 0 then 'DEFAULT' else tblsp.spcname end, auth.rolname as owner, tbl.relpages pages, tbl.reltuples as rows_count, tbl.relhasindex as has_index, tbl.relisshared as is_shared, tbl.relchecks as check_count, tbl.relhaspkey as has_pkey, tbl.relhasrules as has_rules, tbl.relhastriggers as has_triggers, array_to_string(tbl.reloptions, ',') as options,tbl.relhasoids as hashoid, d.description as tbl_desc FROM pg_class tbl LEFT JOIN pg_roles auth on (tbl.relowner = auth.oid) left join pg_description d on (tbl.oid = d.objoid) LEFT JOIN pg_tablespace tblsp ON (tbl.reltablespace = tblsp.oid) WHERE tbl.oid = 1;"; + String tableType = "u"; + MockResultSet getdbsrs = preparedstatementHandler.createResultSet(); + getdbsrs.addColumn("relpersistence"); + getdbsrs.addColumn("owner"); + getdbsrs.addColumn("pages"); + getdbsrs.addColumn("rows_count"); + getdbsrs.addColumn("has_index"); + getdbsrs.addColumn("is_shared"); + getdbsrs.addColumn("check_count"); + getdbsrs.addColumn("has_pkey"); + getdbsrs.addColumn("has_rules"); + getdbsrs.addColumn("has_triggers"); + getdbsrs.addColumn("options"); + getdbsrs.addColumn("hashoid"); + getdbsrs.addColumn("tbl_desc"); + getdbsrs.addColumn("spcname"); + getdbsrs.addRow(new Object[] {tableType, "GaussMPPDB", "12", "1200", false, false, false, true, true, false, + "1 2 3", true, "Tbl Description", "tblspc_prop"}); + + preparedstatementHandler.prepareResultSet(query, getdbsrs); + try + { + CommonLLTUtils.createTableRS(preparedstatementHandler); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().setServerCompatibleToNodeGroup(true); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getIndexForTableRS(preparedstatementHandler); + PropertyHandlerCore core = new PropertyHandlerCore(tablemetaData); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + IPropertyDetail prop = core.getproperty(); + } + catch (DatabaseOperationException e) + { + assertTrue(true); + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + + catch (SQLException e) + { + fail("not expected"); + } + } + + @Test + public void testgetdbemptyProperty() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + try + { + CommonLLTUtils.createDataBaseRS(preparedstatementHandler); + + Database database = connProfCache.getDbForProfileId(profileId); + database.setOid(23); + + CommonLLTUtils.getDataBasePtropertiesemptyRS(preparedstatementHandler); + + PropertyHandlerCore core = new PropertyHandlerCore(database); + core.getproperty(); + fail("not expected here"); + + } + catch (Exception e) + { + System.out.println("as expected"); + } + } + + @Test + public void testtablegetEmptyProperty() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + try + { + CommonLLTUtils.createTableRS(preparedstatementHandler); + + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + String tableType = "u"; + + CommonLLTUtils.getTablePtropertiesemptyRS(preparedstatementHandler, tableType); + tablemetaData.setOid(2); + PropertyHandlerCore core = new PropertyHandlerCore(tablemetaData); + core.getproperty(); + fail("not to come here"); + } + catch (Exception e) + { + System.out.println("as expected"); + } + } + + @Test + public void testPropertyDatabaseOperationalException() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + try + { + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + Server server = new Server(serverInfo); + Database database = new Database(server, 2, "Gauss"); + + preparedstatementHandler.prepareThrowsSQLException( + "SELECT oid as oid, datname AS name, pg_encoding_to_char(encoding) as encoding, datallowconn as allow_conn, datconnlimit as max_conn_limit, (select spcname from pg_tablespace where oid=dattablespace) as default_tablespace, datcollate as collation, datctype as char_type from pg_database where oid = 2;"); + + database.connectToServer(); + PropertyHandlerCore core = new PropertyHandlerCore(database); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + core.getproperty(); + } + catch (SQLException e) + { + fail(); + } + catch (DatabaseOperationException e) + { + assertTrue(true); + } + catch (MPPDBIDEException e) + { + fail(); + } catch (IOException e) { + fail(); + } + } + + @Test + public void testPropertyDatabasecriticalException() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + try + { + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + Server server = new Server(serverInfo); + Database database = new Database(server, 2, "Gauss"); + + ArrayList list = new ArrayList(); + SQLException sqlException = new SQLException("Throwing SQL exception intentionally.", "57PSQLException"); + preparedstatementHandler.prepareThrowsSQLException( + "SELECT oid as oid, datname AS name, pg_encoding_to_char(encoding) as encoding, datallowconn as allow_conn, datconnlimit as max_conn_limit, (select spcname from pg_tablespace where oid=dattablespace) as default_tablespace, datcollate as collation, datctype as char_type from pg_database where oid = 2;", + sqlException, list); + database.connectToServer(); + PropertyHandlerCore core = new PropertyHandlerCore(database); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + core.getproperty(); + } + catch (SQLException e) + { + fail(); + } + catch (DatabaseCriticalException e) + { + assertTrue(true); + } + catch (MPPDBIDEException e) + { + fail(); + } catch (IOException e) { + // TODO Auto-generated catch block + fail(); + } + } + + public void testTTA_BL_TABLE_FUNC_001_005_table_type_P() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + try + { + CommonLLTUtils.createTableRS(preparedstatementHandler); + + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + String tableType = "p"; + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + constraintMetaData.setNamespace(database.getNameSpaceById(1)); + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + ColumnMetaData newTempColumn1 = new ColumnMetaData(tablemetaData, 1, "Col2", + new TypeMetaData(1, "text", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn1); + + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, tableType); + PropertyHandlerCore core = new PropertyHandlerCore(tablemetaData); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + assertNotNull(core.getproperty()); + + } + catch (Exception e) + { + fail(e.getMessage()); + } + } + + public void testTTA_BL_TABLE_FUNC_001_005_table_type_T() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + try + { + CommonLLTUtils.createTableRS(preparedstatementHandler); + + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + String tableType = "t"; + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + constraintMetaData.setNamespace(database.getNameSpaceById(1)); + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + ColumnMetaData newTempColumn1 = new ColumnMetaData(tablemetaData, 1, "Col2", + new TypeMetaData(1, "text", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn1); + + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, tableType); + PropertyHandlerCore core = new PropertyHandlerCore(tablemetaData); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + assertNotNull(core.getproperty()); + + } + catch (Exception e) + { + fail(e.getMessage()); + } + } + + /* + * public void testTTA_BL_TABLE_FUNC_001_005_Table_Type_U() { try { + * CommonLLTUtils.createTableRS(preparedstatementHandler); + * CommonLLTUtils.getConstaraintForTableRS(preparedstatementHandler); + * Database database = connProfCache.getDbForProfileId(profileId); Namespace + * nm = database.getNameSpaceById(1); TableMetaData tablemetaData = new + * TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + * tablemetaData.setTempTable(true); tablemetaData.setIfExists(true); + * tablemetaData.setName("MyTable"); tablemetaData.setHasOid(true); + * tablemetaData.setDistributeOptions("HASH"); + * tablemetaData.setNodeOptions("Node1"); tablemetaData.setDescription( + * "Table description"); String tableType = "u"; + * nm.addTableToSearchPool(tablemetaData); + * + * ConstraintMetaData constraintMetaData = new ConstraintMetaData(1, + * "MyConstarint", CONSTRAINT_TYPE.UNIQUE_KEY_CONSTRSINT); + * constraintMetaData.setNamespace(nm); + * tablemetaData.addConstraint(constraintMetaData); + * + * ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, + * "Col1", new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + * tablemetaData.getColumns().addItem(newTempColumn); + * + * ColumnMetaData newTempColumn1 = new ColumnMetaData(tablemetaData, 1, + * "Col2", new TypeMetaData(1, "text", database.getNameSpaceById(1))); + * tablemetaData.getColumns().addItem(newTempColumn1); + * + * CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, + * tableType); tablemetaData.belongsTo(database, database.getServer()); + * PropertyHandlerCore core = new PropertyHandlerCore(tablemetaData); + * core.getTermConnection() .setConnection(database.getFreeConnection()); + * IPropertyDetail prop = core.getproperty(); // + * tablemetaData.getProperties(this.dbconn); ArrayList list = + * tablemetaData .getDistributedColumnNamesForEdit( + * database.getFreeConnection()); assertTrue(list.size() == 1); + * + * } catch (Exception e) { fail(e.getMessage()); } } + */ + + public void testTTA_BL_TABLE_FUNC_001_005_Table_Type_V() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + try + { + CommonLLTUtils.createTableRS(preparedstatementHandler); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + String tableType = "u"; + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + constraintMetaData.setNamespace(database.getNameSpaceById(1)); + tablemetaData.addConstraint(constraintMetaData); + + IndexMetaData index = new IndexMetaData(1, "Index_1"); + index.setNamespace(database.getNameSpaceById(1)); + index.setTable(tablemetaData); + index.setTablespace("pg_default"); + tablemetaData.addIndex(index); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + ColumnMetaData newTempColumn1 = new ColumnMetaData(tablemetaData, 1, "Col2", + new TypeMetaData(1, "text", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn1); + + PropertyHandlerCore core = new PropertyHandlerCore(tablemetaData); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + assertNotNull(core.getproperty()); + + } + catch (Exception e) + { + fail("not expected"); + } + } + + @Test + public void test_getObjectName() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + CommonLLTUtils.createDataBaseRS(preparedstatementHandler); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + + Database database = connProfCache.getDbForProfileId(profileId); + + CommonLLTUtils.getDataBasePtropertiesRS(preparedstatementHandler); + + PropertyHandlerCore core = new PropertyHandlerCore(database); + + + } + + @Test + public void testTTA_BL_TABLE_EXCEPTIONS_FUNC_001_014() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + try + { + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + Server server = new Server(serverInfo); + Database database = new Database(server, 2, "Gauss"); + + ExceptionConnection exceptionConnection = new ExceptionConnection(); + exceptionConnection.setNeedExceptioStatement(true); + exceptionConnection.setNeedExceptionResultset(true); + exceptionConnection.setThrowExceptionNext(true); + exceptionConnection.setThrownResultSetNext(EXCEPTIONENUM.EXCEPTION); + + getJDBCMockObjectFactory().getMockDriver().setupConnection(exceptionConnection); + + database.connectToServer(); + + Namespace namespace = new Namespace(1, "pg_catalog", database); + database.getSystemNamespaceGroup().addToGroup((SystemNamespace) namespace); + DebugObjects debugObject = new DebugObjects(1, "name", OBJECTTYPE.PLSQLFUNCTION, database); + debugObject.setNamespace(namespace); + TableMetaData tableMetaData = new TableMetaData(namespace); + PropertyHandlerCore core = new PropertyHandlerCore(tableMetaData); + core.getproperty(); + fail("Not expected to come here"); + } + catch (Exception e) + { + System.out.println("as expected"); + } + } +@Test + public void test_viewProperty() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + + CommonLLTUtils.getViewMockRS(preparedstatementHandler); + CommonLLTUtils.fetchViewQuery(preparedstatementHandler); + CommonLLTUtils.createViewColunmMetadata(preparedstatementHandler); + CommonLLTUtils.fetchViewColumnInfo(preparedstatementHandler); + try + { + Database database = connProfCache.getDbForProfileId(profileId); + Namespace namespace = database.getNameSpaceById(1); + namespace.refreshAllViewsInNamespace(database.getConnectionManager().getObjBrowserConn()); + ArrayList views = namespace.getViewGroup().getSortedServerObjectList(); + + ViewMetaData view = views.get(0); + PropertyHandlerCore core = new PropertyHandlerCore(view); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + IPropertyDetail detail = core.getproperty(); + assertEquals(3, detail.objectproperties().get(0).getAllFetchedRows().size()); + + assertEquals("Gauss1234", detail.objectproperties().get(0).getAllFetchedRows().get(1).getValue(1)); + } + catch (Exception e) + { + fail("not expected here"); + } + + } + + @Test + public void test_partitionTableProperty() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.versionOLAPV1r7c10}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getIndexForTableRS(preparedstatementHandler); + CommonLLTUtils.refreshTableForPartitionTable(preparedstatementHandler); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + MockResultSet partitionTablemetadataRS = preparedstatementHandler.createResultSet(); + partitionTablemetadataRS.addColumn("oid"); + partitionTablemetadataRS.addColumn("relname"); + partitionTablemetadataRS.addColumn("relnamespace"); + partitionTablemetadataRS.addColumn("reltablespace"); + partitionTablemetadataRS.addColumn("relpersistence"); + partitionTablemetadataRS.addColumn("desc"); + partitionTablemetadataRS.addColumn("nodes"); + partitionTablemetadataRS.addColumn("reloptions"); + + partitionTablemetadataRS.addRow(new Object[] {1, "MyTable", 1, 1, true, "description", "1 2", ""}); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes, tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.parttype in ('p', 'v') and tbl.oid = 1 and tbl.relkind <> 'i' and oid in (select pcrelid from pgxc_class where has_nodegroup_privilege(pgroup, 'USAGE'))) select * from x where has_table_privilege(x.oid,'SELECT')", + partitionTablemetadataRS); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().setServerCompatibleToNodeGroup(true); + } + + @Test + public void test_connectionProperty_4() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version6}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + String incorrectVersion = "ORACleV1R00C10"; + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(incorrectVersion); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(incorrectVersion); + PropertyHandlerCore core = new PropertyHandlerCore(server); + try + { + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + IPropertyDetail getproperty = core.getproperty(); + IObjectPropertyData iObjectPropertyData = getproperty.objectproperties().get(0); + Object value = iObjectPropertyData.getAllFetchedRows().get(6).getValue(1); + Object value2 = iObjectPropertyData.getAllFetchedRows().get(5).getValue(1); + core.getWindowDetails().isCloseable(); + core.getWindowDetails().getShortTitle(); + core.getWindowDetails().getTitle(); + core.getWindowDetails().getIcon(); + core.getWindowDetails().getUniqueID(); + assertEquals("1.0 build e2c0f862", value); + assertEquals("openGauss", value2); + } + catch (MPPDBIDEException | SQLException e) + { + fail("not expected"); + } + + } + + @Test + public void test_ServerIPProperty_1() + { + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + String serverIP = database.fetchServerIP(); + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + IPropertyDetail getproperty = core.getproperty(); + IObjectPropertyData iObjectPropertyData = getproperty.objectproperties().get(0); + Object value = iObjectPropertyData.getAllFetchedRows().get(4).getValue(1); + assertEquals("127.0.0.1", value); + } + catch (MPPDBIDEException | SQLException e) + { + fail("not expected"); + } + } + + @Test + public void test_ServerIPProperty_2() + { + MockResultSet serverResultset = preparedstatementHandler.createResultSet(); + serverResultset.addColumn("SERVERIP"); + preparedstatementHandler.prepareResultSet("select inet_server_addr();", serverResultset); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + String serverIP = database.fetchServerIP(); + System.out.println("server ip is " + serverIP); + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + IPropertyDetail getproperty = core.getproperty(); + IObjectPropertyData iObjectPropertyData = getproperty.objectproperties().get(0); + Object value = iObjectPropertyData.getAllFetchedRows().get(4).getValue(1); + assertEquals("127.0.0.1", value); + } + catch (DatabaseOperationException e) + { + e.printStackTrace(); + } + catch (OutOfMemoryError e) + { + + e.printStackTrace(); + } + catch (PasswordExpiryException e) + { + + e.printStackTrace(); + } + catch (MPPDBIDEException | SQLException e) + { + + e.printStackTrace(); + } + } + + @Test + public void test_init_general() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "propertiesTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "Emp_ID", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + List tabNameList = new ArrayList<>(); + tabNameList.add("General"); + tabNameList.add("Columns"); + tabNameList.add("Constraints"); + tabNameList.add("Index"); + + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + Map commentsList = propertiestable.getComments(table.getConnectionManager().getFreeConnection()); + List generalProperty = + propertiestable.getGeneralProperty(table.getConnectionManager().getFreeConnection(), commentsList); + + List columnInfo = propertiestable.getColumnInfo(table.getConnectionManager().getFreeConnection(), commentsList); + + List constraintInfo = propertiestable.getConstraintInfo(table.getConnectionManager().getFreeConnection()); + + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(generalProperty, "General", table, propertiestable); + dataProvider.init(); + List allFetchedRows = dataProvider.getAllFetchedRows(); + assertEquals(18, allFetchedRows.size()); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + } + + @Test + public void test_init_columns() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "propertiesTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "Emp_ID", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + List tabNameList = new ArrayList<>(); + tabNameList.add("General"); + tabNameList.add("Columns"); + tabNameList.add("Constraints"); + tabNameList.add("Index"); + + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + Map commentsList = propertiestable.getComments(table.getConnectionManager().getFreeConnection()); + List columnInfo = propertiestable.getColumnInfo(table.getConnectionManager().getFreeConnection(), commentsList); + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(columnInfo, "columns", table, propertiestable); + dataProvider.init(); + List allFetchedRows = dataProvider.getAllFetchedRows(); + for (IDSGridDataRow idsGridDataRow : allFetchedRows) + { + if (idsGridDataRow.getValue(0).equals("Emp_ID")) + { + ((IDSGridEditDataRow) idsGridDataRow).setValue(1, "bigint"); + ((IDSGridEditDataRow) idsGridDataRow).setValue(3, "employee id"); + + } + else if (idsGridDataRow.getValue(0).equals("Emp_NAME")) + { + ((IDSGridEditDataRow) idsGridDataRow).setValue(1, "varchar"); + } + else + { + ((IDSGridEditDataRow) idsGridDataRow).setValue(1, "integer"); + } + } + assertEquals(3, allFetchedRows.size()); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + } + + @Test + public void test_init_constraint() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "propertiesTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "Emp_ID", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + List tabNameList = new ArrayList<>(); + tabNameList.add("General"); + tabNameList.add("Columns"); + tabNameList.add("Constraints"); + tabNameList.add("Index"); + + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + List constraintInfo = propertiestable.getConstraintInfo(table.getConnectionManager().getFreeConnection()); + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(constraintInfo, "constraints", table, propertiestable); + dataProvider.init(); + List allFetchedRows = dataProvider.getAllFetchedRows(); + assertEquals(1, allFetchedRows.size()); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + } + + @Test + public void test_init_index() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + CommonLLTUtils.getIndexWhereExpr(preparedstatementHandler); + getServerVersionResult.addColumn("VERSION"); + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "propertiesTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "Emp_ID", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + + IndexMetaData index1 = new IndexMetaData(1, "index1"); + index1.setTable(table); + index1.setNamespace(database.getNameSpaceById(1)); + index1.addColumn(empId); + table.addIndex(index1); + List tabNameList = new ArrayList<>(); + tabNameList.add("General"); + tabNameList.add("Columns"); + tabNameList.add("Constraints"); + tabNameList.add("Index"); + + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + List indexInfo = propertiestable.getIndexInfo(table.getConnectionManager().getFreeConnection()); + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(indexInfo, "index", table, propertiestable); + dataProvider.init(); + List allFetchedRows = dataProvider.getAllFetchedRows(); + assertEquals(1, allFetchedRows.size()); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + } + + @Test + public void test_init_createEmptyRow_general() + { + + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + + MockResultSet refreshtablemetada = preparedstatementHandler.createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "propertiesTable", 1, 1, true, "description", "1 2", ""}); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1) select * from x where has_table_privilege(x.oid,'SELECT');", + refreshtablemetada); + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "propertiesTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "ColName", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + List tabNameList = new ArrayList<>(); + tabNameList.add("General"); + tabNameList.add("Columns"); + tabNameList.add("Constraints"); + tabNameList.add("Index"); + + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + + Map commentsList = propertiestable.getComments(table.getConnectionManager().getFreeConnection()); + List generalProperty = + propertiestable.getGeneralProperty(table.getConnectionManager().getFreeConnection(), commentsList); + + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(generalProperty, "General", table, propertiestable); + dataProvider.init(); + String objectPropertyName = dataProvider.getObjectPropertyName(); + assertEquals("General", objectPropertyName); + assertEquals("propertiesTable", dataProvider.getTable().getName()); + assertEquals(18,dataProvider.getRecordCount() ); + builder = new StringBuilder(); + if (builder.length() == 0) + { + for (int i = 0; i < 5200; i++) + { + builder.append("a"); + } + } + String validObjectName = + dataProvider.isValidObjectName(1, builder.toString(), dataProvider.getAllFetchedRows().get(17)); + assertEquals("Maximum 5000 characters allowed for table description.", validObjectName); + List allFetchedRows = dataProvider.getAllFetchedRows(); + IDSGridDataRow idsGridDataRow = allFetchedRows.get(12); + ((IDSGridEditDataRow) idsGridDataRow).setValue(1, "my descrption"); + CommitStatus commit2 = dataProvider.commit(); + assertEquals(1, commit2.getListOfSuccessRows().size()); + dataProvider.refresh(); + + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + + } + + @Test + public void test_init_createEmptyRow_column() + { + + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + + MockResultSet refreshtablemetada = preparedstatementHandler.createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "propertiesTable", 1, 1, true, "description", "1 2", ""}); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1) select * from x where has_table_privilege(x.oid,'SELECT');", + refreshtablemetada); + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "propertiesTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "ColName", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + List tabNameList = new ArrayList<>(); + tabNameList.add("General"); + tabNameList.add("Columns"); + tabNameList.add("Constraints"); + tabNameList.add("Index"); + + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + Map commentsList = propertiestable.getComments(table.getConnectionManager().getFreeConnection()); + List columnInfo = propertiestable.getColumnInfo(table.getConnectionManager().getFreeConnection(), commentsList); + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(columnInfo, "Columns", table, propertiestable); + dataProvider.init(); + IDSGridEditDataRow createNewRow = dataProvider.createNewRow(table, 1); + createNewRow.setValue(0, "ColName"); + createNewRow.setValue(1, "bigint"); + createNewRow.setValue(2, true); + createNewRow.setValue(3, "newComment"); + ((DSObjectPropertiesGridDataRow) createNewRow).setServerObject(empId); + assertEquals(1, dataProvider.getInsertedRowCount()); + CommitStatus commit = dataProvider.commit(); + assertEquals(1, commit.getListOfSuccessRows().size()); + dataProvider.deleteRecord(createNewRow, false); + dataProvider.commit(); + assertEquals(1, commit.getListOfSuccessRows().size()); + IDSGridDataRow idsGridDataRow = dataProvider.getAllFetchedRows().get(0); + ((IDSGridEditDataRow) idsGridDataRow).setValue(0, "colnew"); + ObjectPropColumnTabInfo tabInfo = new ObjectPropColumnTabInfo(); + tabInfo.setColDataType(type1); + tabInfo.setPrecision(1); + tabInfo.setScale(1); + tabInfo.setDataTypeSchema("testschema"); + ((IDSGridEditDataRow) idsGridDataRow).setValue(1, tabInfo); + ((IDSGridEditDataRow) idsGridDataRow).setValue(2, true); + ((IDSGridEditDataRow) idsGridDataRow).setValue(3, "newComment"); + assertEquals(1, dataProvider.getUpdatedRowCount()); + CommitStatus commit2 = dataProvider.commit(); + assertEquals(1, commit2.getListOfSuccessRows().size()); + dataProvider.refresh(); + dataProvider.getAllRows(); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + } + + @Test + public void test_init_createEmptyRow_constraint() + { + + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + + MockResultSet refreshtablemetada = preparedstatementHandler.createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "propertiesTable", 1, 1, true, "description", "1 2", ""}); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1) select * from x where has_table_privilege(x.oid,'SELECT');", + refreshtablemetada); + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "propertiesTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "ColName", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + primaryCons.setTable(table); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + ConstraintMetaData checkCons = new ConstraintMetaData(3, "ConstraintName", ConstraintType.CHECK_CONSTRSINT); + table.addConstraint(checkCons); + checkCons.setTable(table); + checkCons.setCheckConstraintExpr(ServerObject.getQualifiedObjectName("ColName")); + checkCons.setCheckConstraintExpr(ServerObject.getQualifiedObjectName("all")); + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + List constraintInfo = propertiestable.getConstraintInfo(table.getConnectionManager().getFreeConnection()); + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(constraintInfo, "Constraints", table, propertiestable); + dataProvider.init(); + IDSGridEditDataRow createNewRow = dataProvider.createNewRow(checkCons, 1); + + assertEquals(1, dataProvider.getInsertedRowCount()); + CommitStatus commit = dataProvider.commit(); + assertEquals(1, commit.getListOfSuccessRows().size()); + dataProvider.deleteRecord(createNewRow, false); + assertEquals(1, dataProvider.commit().getListOfSuccessRows().size()); + IDSGridDataRow idsGridDataRow = dataProvider.getAllFetchedRows().get(0); + ((IDSGridEditDataRow) idsGridDataRow).setValue(0, "colnew"); + CommitStatus commit2 = dataProvider.commit(); + assertEquals(1, commit2.getListOfSuccessRows().size()); + dataProvider.refresh(); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + + } + + @Test + public void test_init_createEmptyRow_index() + { + + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + + MockResultSet refreshtablemetada = preparedstatementHandler.createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "propertiesTable", 1, 1, true, "description", "1 2", ""}); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1) select * from x where has_table_privilege(x.oid,'SELECT');", + refreshtablemetada); + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "propertiesTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "ColName", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + primaryCons.setTable(table); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + + IndexMetaData index1 = new IndexMetaData(1, "IndexName"); + index1.setTable(table); + index1.setNamespace(database.getNameSpaceById(1)); + index1.addColumn(empId); + table.addIndex(index1); + + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + List indexInfo = propertiestable.getIndexInfo(table.getConnectionManager().getFreeConnection()); + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(indexInfo, "Index", table, propertiestable); + dataProvider.init(); + IDSGridEditDataRow createNewRow = dataProvider.createNewRow(index1, 1); + createNewRow.setValue(0, "IndexName"); + createNewRow.setValue(1, "age"); + createNewRow.setValue(2, "false"); + createNewRow.setValue(3, "c<1"); + createNewRow.setValue(4, "pg_default"); + + ((DSObjectPropertiesGridDataRow) createNewRow).setServerObject(index1); + assertEquals(1, dataProvider.getInsertedRowCount()); + CommitStatus commit = dataProvider.commit(); + assertEquals(1, commit.getListOfSuccessRows().size()); + dataProvider.deleteRecord(createNewRow, false); + assertEquals(1, dataProvider.commit().getListOfSuccessRows().size()); + IDSGridDataRow idsGridDataRow = dataProvider.getAllFetchedRows().get(0); + ((IDSGridEditDataRow) idsGridDataRow).setValue(0, "idx_1"); + CommitStatus commit2 = dataProvider.commit(); + assertEquals(1, commit2.getListOfSuccessRows().size()); + dataProvider.refresh(); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + + } + + @Test + public void test_rearrangeInsertedRowIndex() + { + + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + + MockResultSet refreshtablemetada = preparedstatementHandler.createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "propertiesTable", 1, 1, true, "description", "1 2", ""}); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1) select * from x where has_table_privilege(x.oid,'SELECT');", + refreshtablemetada); + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + try + { + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "propertiesTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "ColName", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + primaryCons.setTable(table); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + + IndexMetaData index1 = new IndexMetaData(1, "IndexName"); + index1.setTable(table); + index1.setNamespace(database.getNameSpaceById(1)); + index1.addColumn(empId); + table.addIndex(index1); + + IndexMetaData index2 = new IndexMetaData(2, "IndexName2"); + index2.setTable(table); + index2.setNamespace(database.getNameSpaceById(1)); + index2.addColumn(empAge); + table.addIndex(index2); + + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + List indexInfo = propertiestable.getIndexInfo(table.getConnectionManager().getFreeConnection()); + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(indexInfo, "Index", table, propertiestable); + dataProvider.init(); + IDSGridEditDataRow createNewRow1 = dataProvider.createNewRow(index2, 2); + createNewRow1.setValue(0, "IndexName1"); + createNewRow1.setValue(1, "age1"); + createNewRow1.setValue(2, "false"); + createNewRow1.setValue(3, "c<2"); + createNewRow1.setValue(4, "pg_default"); + IDSGridEditDataRow createNewRow = dataProvider.createNewRow(index1, 1); + createNewRow.setValue(0, "IndexName"); + createNewRow.setValue(1, "age"); + createNewRow.setValue(2, "false"); + createNewRow.setValue(3, "c<1"); + createNewRow.setValue(4, "pg_default"); + + dataProvider.deleteRecord(createNewRow, true); + + ((DSObjectPropertiesGridDataRow) createNewRow).setServerObject(index1); + assertEquals(1, dataProvider.getInsertedRowCount()); + } + catch (DatabaseOperationException e) + { + + e.printStackTrace(); + } + catch (DatabaseCriticalException e) + { + + e.printStackTrace(); + } + catch (MPPDBIDEException e) + { + + e.printStackTrace(); + } + + } + + @Test + public void test_rollback() + { + + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + + MockResultSet refreshtablemetada = preparedstatementHandler.createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "propertiesTable", 1, 1, true, "description", "1 2", ""}); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1) select * from x where has_table_privilege(x.oid,'SELECT');", + refreshtablemetada); + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "propertiesTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "ColName", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + primaryCons.setTable(table); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + + IndexMetaData index1 = new IndexMetaData(1, "IndexName"); + index1.setTable(table); + index1.setNamespace(database.getNameSpaceById(1)); + index1.addColumn(empId); + table.addIndex(index1); + + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + List indexInfo = propertiestable.getIndexInfo(table.getConnectionManager().getFreeConnection()); + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(indexInfo, "Index", table, propertiestable); + dataProvider.init(); + IDSGridEditDataRow createNewRow = dataProvider.createNewRow(table, 1); + createNewRow.setValue(0, "IndexName"); + createNewRow.setValue(1, "age"); + createNewRow.setValue(2, "false"); + createNewRow.setValue(3, "c<1"); + createNewRow.setValue(4, "pg_default"); + ((DSObjectPropertiesGridDataRow) createNewRow).setServerObject(index1); + assertEquals(2, dataProvider.getConsolidatedRows().size()); + dataProvider.deleteRecord(createNewRow, false); + dataProvider.rollBackProvider(); + assertEquals(0, dataProvider.getDeletedRowCount()); + + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + + } + + @Test + public void test_Objectpropinfo() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + + MockResultSet refreshtablemetada = preparedstatementHandler.createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "propertiesTable", 1, 1, true, "description", "1 2", ""}); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1) select * from x where has_table_privilege(x.oid,'SELECT');", + refreshtablemetada); + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "propertiesTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "ColName", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + List tabNameList = new ArrayList<>(); + tabNameList.add("General"); + tabNameList.add("Columns"); + tabNameList.add("Constraints"); + tabNameList.add("Index"); + + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + Map commentsList = propertiestable.getComments(table.getConnectionManager().getFreeConnection()); + List columnInfo = propertiestable.getColumnInfo(table.getConnectionManager().getFreeConnection(), commentsList); + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(columnInfo, "Columns", table, propertiestable); + dataProvider.init(); + IDSGridEditDataRow createNewRow = dataProvider.createNewRow(empId, 1); + + ObjectPropColumnTabInfo tabInfo = new ObjectPropColumnTabInfo(); + tabInfo.setColDataType(type1); + tabInfo.setPrecision(1); + tabInfo.setScale(1); + createNewRow.setValue(0, "ColName"); + createNewRow.setValue(1, tabInfo); + createNewRow.setValue(2, true); + createNewRow.setValue(3, "newComment"); + assertEquals(1, dataProvider.getInsertedRowCount()); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + + } + + @Test + public void test_init_createEmptyRow_column_negative() + { + + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + + MockResultSet refreshtablemetada = preparedstatementHandler.createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "propertiesTable", 1, 1, true, "description", "1 2", ""}); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1) select * from x where has_table_privilege(x.oid,'SELECT');", + refreshtablemetada); + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "propertiesTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "ColName1", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + List tabNameList = new ArrayList<>(); + tabNameList.add("General"); + tabNameList.add("Columns"); + tabNameList.add("Constraints"); + tabNameList.add("Index"); + + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + Map commentsList = propertiestable.getComments(table.getConnectionManager().getFreeConnection()); + List columnInfo = propertiestable.getColumnInfo(table.getConnectionManager().getFreeConnection(), commentsList); + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(columnInfo, "Columns", table, propertiestable); + dataProvider.init(); + IDSGridEditDataRow createNewRow = dataProvider.createNewRow(table, 1); + createNewRow.setValue(0, "c1"); + createNewRow.setValue(1, "bigint"); + createNewRow.setValue(2, true); + createNewRow.setValue(3, "newComment"); + ((DSObjectPropertiesGridDataRow) createNewRow).setServerObject(empId); + assertEquals(1, dataProvider.getInsertedRowCount()); + CommitStatus commit = dataProvider.commit(); + assertEquals(1, commit.getListOfSuccessRows().size()); + dataProvider.deleteRecord(createNewRow, false); + dataProvider.commit(); + assertEquals(1, commit.getListOfSuccessRows().size()); + IDSGridDataRow idsGridDataRow = dataProvider.getAllFetchedRows().get(0); + ((IDSGridEditDataRow) idsGridDataRow).setValue(0, "colnew"); + assertEquals(1, dataProvider.getUpdatedRowCount()); + boolean checkneg = dataProvider.isGridDataEdited(); + assertEquals(checkneg, dataProvider.isGridDataEdited()); + CommitStatus commit2 = dataProvider.commit(); + assertEquals(2, commit2.getListOfFailureRows().size()); + dataProvider.refresh(); + dataProvider.getAllRows(); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + } + + @Test + public void test_init_createEmptyRow_constraint_negative() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + + MockResultSet refreshtablemetada = preparedstatementHandler.createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "propertiesTable", 1, 1, true, "description", "1 2", ""}); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1) select * from x where has_table_privilege(x.oid,'SELECT');", + refreshtablemetada); + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "propertiesTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "ColName", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + primaryCons.setTable(table); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + ConstraintMetaData checkCons = new ConstraintMetaData(3, "Cons3", ConstraintType.CHECK_CONSTRSINT); + table.addConstraint(checkCons); + checkCons.setTable(table); + checkCons.setCheckConstraintExpr(ServerObject.getQualifiedObjectName("ColName")); + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + List constraintInfo = propertiestable.getConstraintInfo(table.getConnectionManager().getFreeConnection()); + + String[] strings = constraintInfo.get(1); + strings[0] = "ConstraintNameModified"; + constraintInfo.set(1, strings); + /* + * String[] strings2 = constraintInfo.get(1); strings2[0] = ""; + * constraintInfo.add(strings2); + */ + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(constraintInfo, "Constraints", table, propertiestable); + dataProvider.init(); + IDSGridEditDataRow createNewRow = dataProvider.createNewRow(checkCons, 1); + createNewRow.setValue(0, "ConstraintName1"); + createNewRow.setValue(1, "age"); + createNewRow.setValue(2, "c"); + createNewRow.setValue(3, "c<1"); + createNewRow.setValue(4, "false"); + createNewRow.setValue(5, "public"); + createNewRow.setValue(6, "pg_default"); + + ((DSObjectPropertiesGridDataRow) createNewRow).setServerObject(primaryCons); + assertEquals(1, dataProvider.getInsertedRowCount()); + CommitStatus commit = dataProvider.commit(); + assertEquals(1, commit.getListOfSuccessRows().size()); + dataProvider.deleteRecord(createNewRow, false); + assertEquals(1, dataProvider.commit().getListOfFailureRows().size()); + IDSGridDataRow idsGridDataRow = dataProvider.getAllFetchedRows().get(0); + ((IDSGridEditDataRow) idsGridDataRow).setValue(0, "colnew"); + CommitStatus commit2 = dataProvider.commit(); + assertEquals(2, commit2.getListOfFailureRows().size()); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + } + + @Test + public void test_init_createEmptyRow_constraint_negative_1() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + + MockResultSet refreshtablemetada = preparedstatementHandler.createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "MyTable", 1, 1, true, "description", "1 2", ""}); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1) select * from x where has_table_privilege(x.oid,'SELECT');", + refreshtablemetada); + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "MyTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "ColName", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + primaryCons.setTable(table); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + ConstraintMetaData checkCons = new ConstraintMetaData(3, "Cons3", ConstraintType.CHECK_CONSTRSINT); + table.addConstraint(checkCons); + checkCons.setTable(table); + checkCons.setCheckConstraintExpr(ServerObject.getQualifiedObjectName("ColName")); + checkCons.setCheckConstraintExpr(ServerObject.getQualifiedObjectName("like")); + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + List constraintInfo = propertiestable.getConstraintInfo(table.getConnectionManager().getFreeConnection()); + + String[] strings2 = constraintInfo.get(1); + strings2[0] = ""; + constraintInfo.set(1, strings2); + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(constraintInfo, "Constraints", table, propertiestable); + dataProvider.init(); + IDSGridEditDataRow createNewRow = dataProvider.createNewRow(checkCons, 1); + createNewRow.setValue(0, ""); + createNewRow.setValue(1, "age"); + createNewRow.setValue(2, "c"); + createNewRow.setValue(3, "c<1"); + createNewRow.setValue(4, "false"); + createNewRow.setValue(5, "public"); + createNewRow.setValue(6, "pg_default"); + + ((DSObjectPropertiesGridDataRow) createNewRow).setServerObject(primaryCons); + assertEquals(1, dataProvider.getInsertedRowCount()); + CommitStatus commit = dataProvider.commit(); + assertEquals(1, commit.getListOfSuccessRows().size()); + dataProvider.deleteRecord(createNewRow, false); + assertEquals(1, dataProvider.commit().getListOfFailureRows().size()); + IDSGridDataRow idsGridDataRow = dataProvider.getAllFetchedRows().get(0); + ((IDSGridEditDataRow) idsGridDataRow).setValue(0, "colnew"); + CommitStatus commit2 = dataProvider.commit(); + assertEquals(2, commit2.getListOfFailureRows().size()); + boolean val=JSQLParserUtils.isQueryResultEditSupported("select * from temp"); + assertEquals(true, val); + String str=JSQLParserUtils.getQualifiedTableName("select * from temp"); + assertEquals("temp", str); + String strCreateView=JSQLParserUtils.getQualifiedTblRViewName("create view temp_view as select column1 from temp"); + assertEquals("temp_view", strCreateView); + String strAlterTable=JSQLParserUtils.getQualifiedTblRViewName("ALTER TABLE alter_table ADD (col1 varchar2(50), col2 varchar2(50))"); + assertEquals("alter_table", strAlterTable); + String strDropTable=JSQLParserUtils.getQualifiedTblRViewName("drop table drop_table"); + assertEquals("drop_table", strDropTable); + String strObjType=JSQLParserUtils.setObjectType("create view temp_view as select column1 from temp"); + assertEquals("CREATE_VIEW", strObjType); + String strAlterType=JSQLParserUtils.setObjectType("ALTER TABLE alter_table ADD (col1 varchar2(50), col2 varchar2(50))"); + assertEquals("ALTER_TABLE", strAlterType); + String strDropType=JSQLParserUtils.setObjectType("drop table drop_table"); + assertEquals("DROP_TABLE", strDropType); + String qualifiedObjectName = ServerObject.getQualifiedObjectName(table.getName()); + String[] splitQualifiedName2 = JSQLParserUtils.getSplitQualifiedName(qualifiedObjectName, false); + assertEquals("\"MyTable\"",splitQualifiedName2[0] ); + String string="\"public\".\"table\""; + String[] splitQualifiedName = JSQLParserUtils.getSplitQualifiedName(string, true); + assertEquals("public", splitQualifiedName[0]); + + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + } + + public void test_performIndex_negative() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + + MockResultSet refreshtablemetada = preparedstatementHandler.createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "propertiesTable", 1, 1, true, "description", "1 2", ""}); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1) select * from x where has_table_privilege(x.oid,'SELECT');", + refreshtablemetada); + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "propertiesTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "ColName", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + primaryCons.setTable(table); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + + IndexMetaData index1 = new IndexMetaData(1, "IndexName2"); + index1.setTable(table); + index1.setNamespace(database.getNameSpaceById(1)); + index1.addColumn(empId); + table.addIndex(index1); + + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + List indexInfo = propertiestable.getIndexInfo(table.getConnectionManager().getFreeConnection()); + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(indexInfo, "Index", table, propertiestable); + dataProvider.init(); + IDSGridEditDataRow createNewRow = dataProvider.createNewRow(index1, 1); + createNewRow.setValue(0, "IndexName1"); + createNewRow.setValue(1, "age"); + createNewRow.setValue(2, "false"); + createNewRow.setValue(3, "c<1"); + createNewRow.setValue(4, "pg_default"); + + ((DSObjectPropertiesGridDataRow) createNewRow).setServerObject(index1); + assertEquals(1, dataProvider.getInsertedRowCount()); + CommitStatus commit = dataProvider.commit(); + assertEquals(1, commit.getListOfSuccessRows().size()); + dataProvider.deleteRecord(createNewRow, false); + assertEquals(1, dataProvider.commit().getListOfFailureRows().size()); + IDSGridDataRow idsGridDataRow = dataProvider.getAllFetchedRows().get(0); + ((IDSGridEditDataRow) idsGridDataRow).setValue(0, "idx_1"); + CommitStatus commit2 = dataProvider.commit(); + assertEquals(2, commit2.getListOfFailureRows().size()); + dataProvider.refresh(); + + dataProvider.isEditSupported(); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + } + + @Test + public void test_isEditSupported() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + + MockResultSet refreshtablemetada = preparedstatementHandler.createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "propertiesTable", 1, 1, true, "description", "1 2", ""}); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1) select * from x where has_table_privilege(x.oid,'SELECT');", + refreshtablemetada); + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "propertiesTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "ColName", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + primaryCons.setTable(table); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + + IndexMetaData index1 = new IndexMetaData(1, "IndexName2"); + index1.setTable(table); + index1.setNamespace(database.getNameSpaceById(1)); + index1.addColumn(empId); + table.addIndex(index1); + + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + List indexInfo = propertiestable.getIndexInfo(table.getConnectionManager().getFreeConnection()); + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(indexInfo, "Index", table, propertiestable); + boolean editSupported = dataProvider.isEditSupported(); + + String validObjectName = dataProvider.isValidObjectName(0, + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", null); + assertEquals("Maximum 64 characters allowed for table, column, constraint, and index name.", validObjectName); + assertEquals(true, editSupported); + DSObjectPropertiesGridDataProvider dataProvider1 = + new DSObjectPropertiesGridDataProvider(indexInfo, "Index", null, propertiestable); + assertEquals(false, dataProvider1.isEditSupported()); + + PartitionTable partTable = new PartitionTable(database.getNameSpaceById(1)); + DSObjectPropertiesGridDataProvider dataProvider2 = + new DSObjectPropertiesGridDataProvider(indexInfo, "Index", partTable, propertiestable); + assertEquals(false, dataProvider2.isEditSupported()); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + } + + + @Test + public void test__addColumnQuery_SQLException_CriticalException() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + + MockResultSet refreshtablemetada = preparedstatementHandler.createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "propertiesTable", 1, 1, true, "description", "1 2", ""}); + SQLException sqlException = new SQLException("Throwing SQL exception intentionally.", "57PSQLException"); + preparedstatementHandler.prepareThrowsSQLException("ALTER TABLE pg_catalog.\"propertiesTable\" ADD COLUMN \"ColName\" bigint DEFAULT '1'",sqlException); + + SQLException sqlException1 = new SQLException("Throwing SQL exception intentionally.", "57PSQLException"); + preparedstatementHandler.prepareThrowsSQLException("ALTER TABLE pg_catalog.\"propertiesTable\" DROP COLUMN \"ColName\";",sqlException1); + + + preparedstatementHandler.prepareThrowsSQLException("ALTER TABLE pg_catalog.\"propertiesTable\" RENAME COLUMN \"ColName\" TO colnew",sqlException); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1) select * from x where has_table_privilege(x.oid,'SELECT');", + refreshtablemetada); + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "propertiesTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "ColName", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + List tabNameList = new ArrayList<>(); + tabNameList.add("General"); + tabNameList.add("Columns"); + tabNameList.add("Constraints"); + tabNameList.add("Index"); + + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + Map commentsList = propertiestable.getComments(table.getConnectionManager().getFreeConnection()); + List columnInfo = propertiestable.getColumnInfo(table.getConnectionManager().getFreeConnection(), commentsList); + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(columnInfo, "Columns", table, propertiestable); + dataProvider.init(); + IDSGridEditDataRow createNewRow = dataProvider.createNewRow(table, 1); + createNewRow.setValue(0, "ColName"); + createNewRow.setValue(1, "bigint"); + createNewRow.setValue(2, true); + createNewRow.setValue(3, "newComment"); + ((DSObjectPropertiesGridDataRow) createNewRow).setServerObject(empId); + assertEquals(1, dataProvider.getInsertedRowCount()); + CommitStatus commit = dataProvider.commit(); + assertEquals(1, commit.getListOfFailureRows().size()); + dataProvider.deleteRecord(createNewRow, false); + dataProvider.commit(); + IDSGridDataRow idsGridDataRow = dataProvider.getAllFetchedRows().get(0); + ((IDSGridEditDataRow) idsGridDataRow).setValue(0, "colnew"); + dataProvider.commit(); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + } + + + @Test + public void test__addColumnQuery_SQLException_DatabaseOperationException() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + + MockResultSet refreshtablemetada = preparedstatementHandler.createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "propertiesTable", 1, 1, true, "description", "1 2", ""}); + preparedstatementHandler.prepareThrowsSQLException("ALTER TABLE pg_catalog.\"propertiesTable\" ADD COLUMN \"ColName\" bigint DEFAULT '1'"); + preparedstatementHandler.prepareThrowsSQLException("ALTER TABLE pg_catalog.\"propertiesTable\" DROP COLUMN \"ColName\";"); + preparedstatementHandler.prepareThrowsSQLException("ALTER TABLE pg_catalog.\"propertiesTable\" RENAME COLUMN \"ColName\" TO colnew"); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1) select * from x where has_table_privilege(x.oid,'SELECT');", + refreshtablemetada); + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "propertiesTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "ColName", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + List tabNameList = new ArrayList<>(); + tabNameList.add("General"); + tabNameList.add("Columns"); + tabNameList.add("Constraints"); + tabNameList.add("Index"); + + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + Map commentsList = propertiestable.getComments(table.getConnectionManager().getFreeConnection()); + List columnInfo = propertiestable.getColumnInfo(table.getConnectionManager().getFreeConnection(), commentsList); + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(columnInfo, "Columns", table, propertiestable); + dataProvider.init(); + IDSGridEditDataRow createNewRow = dataProvider.createNewRow(table, 1); + createNewRow.setValue(0, "ColName"); + createNewRow.setValue(1, "bigint"); + createNewRow.setValue(2, true); + createNewRow.setValue(3, "newComment"); + ((DSObjectPropertiesGridDataRow) createNewRow).setServerObject(empId); + assertEquals(1, dataProvider.getInsertedRowCount()); + CommitStatus commit = dataProvider.commit(); + assertEquals(1, commit.getListOfFailureRows().size()); + dataProvider.deleteRecord(createNewRow, false); + dataProvider.commit(); + IDSGridDataRow idsGridDataRow = dataProvider.getAllFetchedRows().get(0); + ((IDSGridEditDataRow) idsGridDataRow).setValue(0, "colnew"); + dataProvider.commit(); + + + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + } + @Test + public void test__addConstraint_SQLException_CriticalException() + { + + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + + MockResultSet refreshtablemetada = preparedstatementHandler.createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "MyTable", 1, 1, true, "description", "1 2", ""}); + SQLException sqlException = new SQLException("Throwing SQL exception intentionally.", "57PSQLException"); + preparedstatementHandler.prepareThrowsSQLException("ALTER TABLE pg_catalog.\"MyTable\" ADD CONSTRAINT \"Cons1\" PRIMARY KEY ()WITH (fillfactor=100)",sqlException); + preparedstatementHandler.prepareThrowsSQLException("ALTER TABLE pg_catalog.\"MyTable\" DROP CONSTRAINT \"ConstraintName\";",sqlException); + preparedstatementHandler.prepareThrowsSQLException("ALTER TABLE pg_catalog.\"MyTable\" RENAME CONSTRAINT \"ConstraintName\" TO colnew",sqlException); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1) select * from x where has_table_privilege(x.oid,'SELECT');", + refreshtablemetada); + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "MyTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "ColName", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + primaryCons.setTable(table); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + ConstraintMetaData checkCons = new ConstraintMetaData(3, "Cons3", ConstraintType.CHECK_CONSTRSINT); + table.addConstraint(checkCons); + checkCons.setTable(table); + checkCons.setCheckConstraintExpr(ServerObject.getQualifiedObjectName("ColName")); + checkCons.setCheckConstraintExpr(ServerObject.getQualifiedObjectName("all")); + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + List constraintInfo = propertiestable.getConstraintInfo(table.getConnectionManager().getFreeConnection()); + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(constraintInfo, "Constraints", table, propertiestable); + dataProvider.init(); + IDSGridEditDataRow createNewRow = dataProvider.createNewRow(checkCons, 1); + createNewRow.setValue(0, "ConstraintName"); + createNewRow.setValue(1, "age"); + createNewRow.setValue(2, "c"); + createNewRow.setValue(3, "c<1"); + createNewRow.setValue(4, "false"); + createNewRow.setValue(5, "public"); + createNewRow.setValue(6, "pg_default"); + + ((DSObjectPropertiesGridDataRow) createNewRow).setServerObject(primaryCons); + assertEquals(1, dataProvider.getInsertedRowCount()); + CommitStatus commit = dataProvider.commit(); + assertEquals(1, commit.getListOfFailureRows().size()); + dataProvider.deleteRecord(createNewRow, false); + assertEquals(2, dataProvider.commit().getListOfFailureRows().size()); + IDSGridDataRow idsGridDataRow = dataProvider.getAllFetchedRows().get(0); + ((IDSGridEditDataRow) idsGridDataRow).setValue(0, "colnew"); + CommitStatus commit2 = dataProvider.commit(); + assertEquals(3, commit2.getListOfFailureRows().size()); + dataProvider.refresh(); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + + } + + + + @Test + public void test__addConstraint_SQLException_DatabaseOperationException() + { + + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + + MockResultSet refreshtablemetada = preparedstatementHandler.createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "MyTable", 1, 1, true, "description", "1 2", ""}); + preparedstatementHandler.prepareThrowsSQLException("ALTER TABLE pg_catalog.\"MyTable\" ADD CONSTRAINT \"Cons1\" PRIMARY KEY ()WITH (fillfactor=100)"); + preparedstatementHandler.prepareThrowsSQLException("ALTER TABLE pg_catalog.\"MyTable\" DROP CONSTRAINT \"ConstraintName\";"); + preparedstatementHandler.prepareThrowsSQLException("ALTER TABLE pg_catalog.\"MyTable\" RENAME CONSTRAINT \"ConstraintName\" TO colnew"); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1) select * from x where has_table_privilege(x.oid,'SELECT');", + refreshtablemetada); + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "MyTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "ColName", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + primaryCons.setTable(table); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + ConstraintMetaData checkCons = new ConstraintMetaData(3, "Cons3", ConstraintType.CHECK_CONSTRSINT); + table.addConstraint(checkCons); + checkCons.setTable(table); + checkCons.setCheckConstraintExpr(ServerObject.getQualifiedObjectName("ColName")); + checkCons.setCheckConstraintExpr(ServerObject.getQualifiedObjectName("all")); + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + List constraintInfo = propertiestable.getConstraintInfo(table.getConnectionManager().getFreeConnection()); + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(constraintInfo, "Constraints", table, propertiestable); + dataProvider.init(); + IDSGridEditDataRow createNewRow = dataProvider.createNewRow(checkCons, 1); + createNewRow.setValue(0, "ConstraintName"); + createNewRow.setValue(1, "age"); + createNewRow.setValue(2, "c"); + createNewRow.setValue(3, "c<1"); + createNewRow.setValue(4, "false"); + createNewRow.setValue(5, "public"); + createNewRow.setValue(6, "pg_default"); + + ((DSObjectPropertiesGridDataRow) createNewRow).setServerObject(primaryCons); + assertEquals(1, dataProvider.getInsertedRowCount()); + CommitStatus commit = dataProvider.commit(); + assertEquals(1, commit.getListOfFailureRows().size()); + dataProvider.deleteRecord(createNewRow, false); + assertEquals(2, dataProvider.commit().getListOfFailureRows().size()); + IDSGridDataRow idsGridDataRow = dataProvider.getAllFetchedRows().get(0); + ((IDSGridEditDataRow) idsGridDataRow).setValue(0, "colnew"); + CommitStatus commit2 = dataProvider.commit(); + assertEquals(3, commit2.getListOfFailureRows().size()); + dataProvider.refresh(); + CommitStatus commit3 = dataProvider.commit(); + commit3.setListOfFailureRows(commit2.getListOfFailureRows()); + assertEquals(3, commit3.getListOfFailureRows().size()); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + + } + + @Test + public void test__addIndex_SQLException_DatabaseOperationException() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + + MockResultSet refreshtablemetada = preparedstatementHandler.createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "propertiesTable", 1, 1, true, "description", "1 2", ""}); + preparedstatementHandler.prepareThrowsSQLException("CREATE INDEX pg_default ON pg_catalog.\"propertiesTable\" (\"ColName\") ;"); + preparedstatementHandler.prepareThrowsSQLException("drop index pg_catalog.\"IndexName\";"); + preparedstatementHandler.prepareThrowsSQLException("ALTER INDEX pg_catalog.\"IndexName\" RENAME TO idx_1 ;"); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1) select * from x where has_table_privilege(x.oid,'SELECT');", + refreshtablemetada); + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "propertiesTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "ColName", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + primaryCons.setTable(table); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + + IndexMetaData index1 = new IndexMetaData(1, "IndexName"); + index1.setTable(table); + index1.setNamespace(database.getNameSpaceById(1)); + index1.addColumn(empId); + table.addIndex(index1); + + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + List indexInfo = propertiestable.getIndexInfo(table.getConnectionManager().getFreeConnection()); + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(indexInfo, "Index", table, propertiestable); + dataProvider.init(); + IDSGridEditDataRow createNewRow = dataProvider.createNewRow(index1, 1); + createNewRow.setValue(0, "IndexName"); + createNewRow.setValue(1, "age"); + createNewRow.setValue(2, "false"); + createNewRow.setValue(3, "c<1"); + createNewRow.setValue(4, "pg_default"); + + ((DSObjectPropertiesGridDataRow) createNewRow).setServerObject(index1); + assertEquals(1, dataProvider.getInsertedRowCount()); + CommitStatus commit = dataProvider.commit(); + assertEquals(0, commit.getListOfSuccessRows().size()); + dataProvider.deleteRecord(createNewRow, false); + assertEquals(0, dataProvider.commit().getListOfSuccessRows().size()); + IDSGridDataRow idsGridDataRow = dataProvider.getAllFetchedRows().get(0); + ((IDSGridEditDataRow) idsGridDataRow).setValue(0, "idx_1"); + CommitStatus commit2 = dataProvider.commit(); + assertEquals(0, commit2.getListOfSuccessRows().size()); + dataProvider.refresh(); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + + + + } + + + @Test + public void test__addIndex_SQLException_CriticalException() + { + + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + + MockResultSet refreshtablemetada = preparedstatementHandler.createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "propertiesTable", 1, 1, true, "description", "1 2", ""}); + SQLException sqlException = new SQLException("Throwing SQL exception intentionally.", "57PSQLException"); + preparedstatementHandler.prepareThrowsSQLException("CREATE INDEX pg_default ON pg_catalog.\"propertiesTable\" (\"ColName\") ;",sqlException); + preparedstatementHandler.prepareThrowsSQLException("drop index pg_catalog.\"IndexName\";",sqlException); + preparedstatementHandler.prepareThrowsSQLException("ALTER INDEX pg_catalog.\"IndexName\" RENAME TO idx_1 ;",sqlException); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1) select * from x where has_table_privilege(x.oid,'SELECT');", + refreshtablemetada); + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "propertiesTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "ColName", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + primaryCons.setTable(table); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + + IndexMetaData index1 = new IndexMetaData(1, "IndexName"); + index1.setTable(table); + index1.setNamespace(database.getNameSpaceById(1)); + index1.addColumn(empId); + table.addIndex(index1); + + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + List indexInfo = propertiestable.getIndexInfo(table.getConnectionManager().getFreeConnection()); + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(indexInfo, "Index", table, propertiestable); + dataProvider.init(); + IDSGridEditDataRow createNewRow = dataProvider.createNewRow(index1, 1); + createNewRow.setValue(0, "IndexName"); + createNewRow.setValue(1, "age"); + createNewRow.setValue(2, "false"); + createNewRow.setValue(3, "c<1"); + createNewRow.setValue(4, "pg_default"); + + ((DSObjectPropertiesGridDataRow) createNewRow).setServerObject(index1); + assertEquals(1, dataProvider.getInsertedRowCount()); + CommitStatus commit = dataProvider.commit(); + assertEquals(0, commit.getListOfSuccessRows().size()); + dataProvider.deleteRecord(createNewRow, false); + assertEquals(0, dataProvider.commit().getListOfSuccessRows().size()); + IDSGridDataRow idsGridDataRow = dataProvider.getAllFetchedRows().get(0); + ((IDSGridEditDataRow) idsGridDataRow).setValue(0, "idx_1"); + CommitStatus commit2 = dataProvider.commit(); + assertEquals(0, commit2.getListOfSuccessRows().size()); + dataProvider.refresh(); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + + } + + @Test + public void test__setTableDesc_SQLException_CriticalException() + { + + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + + MockResultSet refreshtablemetada = preparedstatementHandler.createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "propertiesTable", 1, 1, true, "description", "1 2", ""}); + SQLException sqlException = new SQLException("Throwing SQL exception intentionally.", "57PSQLException"); + preparedstatementHandler.prepareThrowsSQLException("COMMENT ON TABLE pg_catalog.\"propertiesTable\" IS 'my descrption';",sqlException); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1) select * from x where has_table_privilege(x.oid,'SELECT');", + refreshtablemetada); + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "propertiesTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "ColName", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + List tabNameList = new ArrayList<>(); + tabNameList.add("General"); + tabNameList.add("Columns"); + tabNameList.add("Constraints"); + tabNameList.add("Index"); + + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + + Map commentsList = propertiestable.getComments(table.getConnectionManager().getFreeConnection()); + List generalProperty = + propertiestable.getGeneralProperty(table.getConnectionManager().getFreeConnection(), commentsList); + + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(generalProperty, "General", table, propertiestable); + dataProvider.init(); + String objectPropertyName = dataProvider.getObjectPropertyName(); + assertEquals("General", objectPropertyName); + assertEquals("propertiesTable", dataProvider.getTable().getName()); + assertEquals(18,dataProvider.getRecordCount() ); + builder = new StringBuilder(); + if (builder.length() == 0) + { + for (int i = 0; i < 5200; i++) + { + builder.append("a"); + } + } + String validObjectName = + dataProvider.isValidObjectName(1, builder.toString(), dataProvider.getAllFetchedRows().get(17)); + assertEquals("Maximum 5000 characters allowed for table description.", validObjectName); + List allFetchedRows = dataProvider.getAllFetchedRows(); + IDSGridDataRow idsGridDataRow = allFetchedRows.get(12); + ((IDSGridEditDataRow) idsGridDataRow).setValue(1, "my descrption"); + CommitStatus commit2 = dataProvider.commit(); + assertEquals(0, commit2.getListOfSuccessRows().size()); + dataProvider.refresh(); + + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + + + } + @Test + public void test__setDesc_SQLException_DatabaseOperationException() + { + + + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + + MockResultSet refreshtablemetada = preparedstatementHandler.createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "propertiesTable", 1, 1, true, "description", "1 2", ""}); + preparedstatementHandler.prepareThrowsSQLException("COMMENT ON TABLE pg_catalog.\"propertiesTable\" IS 'my descrption';"); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1) select * from x where has_table_privilege(x.oid,'SELECT');", + refreshtablemetada); + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + CommonLLTUtils.getTablePtropertiesRS(preparedstatementHandler, "u"); + try + { + PropertyHandlerCore core = new PropertyHandlerCore(server); + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + + TableMetaData table = new TableMetaData(1, "propertiesTable", database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(table, 1, "ColName", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(table, 2, "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(table, 3, "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + table.addColumn(empId); + table.addColumn(empName); + table.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", ConstraintType.PRIMARY_KEY_CONSTRSINT); + table.addConstraint(primaryCons); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", ConstraintType.UNIQUE_KEY_CONSTRSINT); + table.addConstraint(uniqueCons); + List tabNameList = new ArrayList<>(); + tabNameList.add("General"); + tabNameList.add("Columns"); + tabNameList.add("Constraints"); + tabNameList.add("Index"); + + PropertiesTableImpl propertiestable = new PropertiesTableImpl(table); + + Map commentsList = propertiestable.getComments(table.getConnectionManager().getFreeConnection()); + List generalProperty = + propertiestable.getGeneralProperty(table.getConnectionManager().getFreeConnection(), commentsList); + + DSObjectPropertiesGridDataProvider dataProvider = + new DSObjectPropertiesGridDataProvider(generalProperty, "General", table, propertiestable); + dataProvider.init(); + String objectPropertyName = dataProvider.getObjectPropertyName(); + assertEquals("General", objectPropertyName); + assertEquals("propertiesTable", dataProvider.getTable().getName()); + assertEquals(18,dataProvider.getRecordCount() ); + builder = new StringBuilder(); + if (builder.length() == 0) + { + for (int i = 0; i < 5200; i++) + { + builder.append("a"); + } + } + String validObjectName = + dataProvider.isValidObjectName(1, builder.toString(), dataProvider.getAllFetchedRows().get(17)); + assertEquals("Maximum 5000 characters allowed for table description.", validObjectName); + List allFetchedRows = dataProvider.getAllFetchedRows(); + IDSGridDataRow idsGridDataRow = allFetchedRows.get(12); + ((IDSGridEditDataRow) idsGridDataRow).setValue(1, "my descrption"); + CommitStatus commit2 = dataProvider.commit(); + assertEquals(0, commit2.getListOfSuccessRows().size()); + dataProvider.refresh(); + + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (OutOfMemoryError e) + { + fail("not expected"); + + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + + + + } + + @Test + public void test_getAllProperties_001() + { + MockResultSet getServerVersionResult = preparedstatementHandler.createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] {ServerVersionTest.version4}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", getServerVersionResult); + + MockResultSet refreshtablemetada = preparedstatementHandler.createResultSet(); + refreshtablemetada.addColumn("oid"); + refreshtablemetada.addColumn("relname"); + refreshtablemetada.addColumn("relnamespace"); + refreshtablemetada.addColumn("reltablespace"); + refreshtablemetada.addColumn("relpersistence"); + refreshtablemetada.addColumn("desc"); + refreshtablemetada.addColumn("nodes"); + refreshtablemetada.addColumn("reloptions"); + + refreshtablemetada.addRow(new Object[] {1, "propertiesTable", 1, 1, true, "description", "1 2", ""}); + preparedstatementHandler.prepareResultSet( + "with x as (select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ts.spcname as reltablespace,tbl.relpersistence relpersistence, d.description as desc, xctbl.nodeoids as nodes ,tbl.reloptions as reloptions from pg_class tbl left join (select d.description, d.objoid from pg_description d where d.objsubid=0) d on (tbl.oid = d.objoid) left join pgxc_class xctbl on (tbl.oid = xctbl.pcrelid) left join pg_tablespace ts on ts.oid = tbl.reltablespace where tbl.relkind = 'r' and tbl.parttype in ('n','p') and tbl.oid = 1) select * from x where has_table_privilege(x.oid,'SELECT');", + refreshtablemetada); + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + fail("not exptected"); + } + MockUserRoleManagerUtils.test_isSysAdmin_001_RS(preparedstatementHandler); + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(ServerVersionTest.version4); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + /*Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer();*/ + UserRole userRole = new UserRole(); + userRole.setName("Chris"); + userRole.setServer(server); + userRole.setOid(101L); + userRole.setRolCanLogin(false); + userRole.setIsUser(false); + MockUserRoleManagerUtils.test_getUserRoleNameByOid_001_RS(preparedstatementHandler, 101); + MockUserRoleManagerUtils.test_fetchUserRoleDetailInfoByOid_001_RS(preparedstatementHandler, userRole); + MockUserRoleManagerUtils.test_getUserRoleloginByOid_001_RS(preparedstatementHandler, 101); + MockUserRoleManagerUtils.test_fetchAllParent_001_RS(preparedstatementHandler, userRole); + MockUserRoleManagerUtils.test_fetchDescriptionOfUserRole_001_RS(preparedstatementHandler, userRole); + MockUserRoleManagerUtils.test_fetchLockStatusOfUserRole_001_RS(preparedstatementHandler, userRole); + PropertyHandlerCore core = new PropertyHandlerCore(userRole); + try { + core.getTermConnection().setConnection(database.getConnectionManager().getFreeConnection()); + List objectproperties = core.getproperty().objectproperties(); + DSObjectPropertiesGridDataProvider p = (DSObjectPropertiesGridDataProvider)objectproperties.get(0); + List allRows = p.getAllRows(); + IDSGridEditDataRow idsGridDataRow1 = (IDSGridEditDataRow)allRows.get(2); + idsGridDataRow1.setValue(1, "10"); + IDSGridEditDataRow idsGridDataRow2=(IDSGridEditDataRow)allRows.get(3); + idsGridDataRow2.setValue(1, "2019-06-04"); + IDSGridEditDataRow idsGridDataRow3=(IDSGridEditDataRow)allRows.get(4); + idsGridDataRow3.setValue(1,"2019-06-04"); + IDSGridEditDataRow idsGridDataRow4=(IDSGridEditDataRow)allRows.get(5); + idsGridDataRow4.setValue(1, "Default_value"); + IDSGridEditDataRow idsGridDataRow6=(IDSGridEditDataRow)allRows.get(6); + idsGridDataRow6.setValue(1, "comment userrole"); + List generateUserRolePropertyChangePreviewSql = p.generateUserRolePropertyChangePreviewSql(database.getConnectionManager().getFreeConnection()); + DSObjectPropertiesGridDataProvider p1 = (DSObjectPropertiesGridDataProvider)objectproperties.get(1); + List allRows2 = p1.getAllRows(); + allRows2.stream().forEach(row->{ + ((IDSGridEditDataRow)row).setValue(1, false); + }); + p1.generateUserRolePropertyChangePreviewSql(database.getConnectionManager().getFreeConnection()); + DSObjectPropertiesGridDataProvider p2 = (DSObjectPropertiesGridDataProvider)objectproperties.get(2); + List allRows3 = p2.getAllRows(); + IDSGridDataRow idsGridDataRow = allRows3.get(0); + IDSGridEditDataRow row = (IDSGridEditDataRow)idsGridDataRow; + row.setValue(1, "chris"); + p2.generateUserRolePropertyChangePreviewSql(database.getConnectionManager().getFreeConnection()); + p.commitUserRoleProperty(database.getConnectionManager().getFreeConnection(), generateUserRolePropertyChangePreviewSql); + + assertNotNull(core.getproperty()); + } catch (MPPDBIDEException | SQLException e) { + fail("not expected"); + } catch (Exception e) { + + fail("not expected"); + } finally {} + + } + + + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/SearchTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/SearchTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ce23f75aa23a213f030217d1ae29757995ad0868 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/SearchTest.java @@ -0,0 +1,1762 @@ +package org.opengauss.mppdbide.test.presentation.properties; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Iterator; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.search.SearchNameMatchEnum; +import org.opengauss.mppdbide.bl.search.SearchObjectEnum; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ForeignTable; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.SequenceMetadata; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.bl.serverdatacache.SystemNamespace; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtilsHelper.EXCEPTIONENUM; +import org.opengauss.mppdbide.mock.presentation.ExceptionConnectionHelper; +import org.opengauss.mppdbide.presentation.search.AbstractSearchObjUtils; +import org.opengauss.mppdbide.presentation.search.SearchObjCore; +import org.opengauss.mppdbide.presentation.search.SearchObjInfo; +import org.opengauss.mppdbide.test.presentation.table.MockPresentationBLPreferenceImpl; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; +import com.mockrunner.mock.jdbc.MockResultSet; +import static org.junit.Assert.*; + +public class SearchTest extends BasicJDBCTestCaseAdapter +{ + + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + SearchObjCore core=null; + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#setUp() + */ + @Before + public void setUp() throws Exception + { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + connection = new MockConnection(); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + CommonLLTUtils.addViewTableData(preparedstatementHandler); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + + connProfCache = DBConnProfCache.getInstance(); + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + // serverInfo.setSslPassword("12345"); + // serverInfo.setServerType(DATABASETYPE.GAUSS); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + profileId = connProfCache.initConnectionProfile(serverInfo,status); + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().setServerCompatibleToNodeGroup(true); + core = new SearchObjCore(); + SearchObjInfo obj=new SearchObjInfo(); + core.setSearchInfo(obj); + core.setSearchStatus(SearchObjectEnum.DATABASELIST_UPDATE); + core.setSearchStatus(SearchObjectEnum.SEARCH_INI); + core.getAllProfiles(); + core.getSearchInfo().setSelectedserver(0); + core.getAllDatabases(); + core.getSearchInfo().setSelectedDB(0); + core.getNamespaceList(); + core.getSearchInfo().setSelectedNamespace(0); + + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception + { + super.tearDown(); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().close(); + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) + { + connProfCache.removeServer(itr.next().getId()); + itr = connProfCache.getServers().iterator(); + } + + connProfCache.closeAllNodes(); + + } + + @Test + public void test_connection_db_ns(){ + + assertEquals("TestConnectionName", core.getSelectedServer().getName()); + assertEquals("Gauss", core.getSelectedDb().getName()); + assertEquals("PUBLIC", core.getSelectedNs().getName()); + assertEquals(4, core.getNameMatchList().size()); + assertEquals(0, core.getObjectBrowserSelectedServer("TestConnectionName (127.0.0.1:5432)")); + assertEquals(0, core.getObjectBrowserSelectedDatabase("Gauss")); + assertEquals(1, core.getObjectBrowserSelectedSchema("information_schema")); + assertEquals(0, core.getObjectBrowserSelectedSchema("intion_schema")); + + + } + + @Test + public void test_search_only_regulartables() + { + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =3 and ( (tbl.relkind='r' or tbl.relkind='f' and tbl.oid in (with x as (select pcrelid from pgxc_class where has_nodegroup_privilege(pgroup, 'USAGE')) select * from x where has_table_privilege(x.pcrelid, 'SELECT')))) and tbl.parttype in ('n', 'p', 'v') and relname LIKE ? ;"; + + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + + formSearchQuery.addRow(new Object[] {1,"abc","3","PUBLIC","r","n",null}); + preparedstatementHandler.prepareResultSet(Query, + formSearchQuery); + + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(true); + core.getSearchInfo().setFunProcSelected(false); + core.getSearchInfo().setViewsSelected(false); + core.getSearchInfo().setSearchText("bc"); + core.getSearchInfo().setNameMatch(0); + core.getSearchInfo().setMatchCase(true); + core.setSearchStatus(SearchObjectEnum.SEARCH_START); + core.search(); + core.setSearchStatus(SearchObjectEnum.SEARCH_END); + + assertEquals(1, core.getSearchNamespace().getTables().getSize()); + assertEquals(0, core.getSearchNamespace().getForeignTablesGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getViewGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getFunctions().getSize()); + + } + catch (DatabaseOperationException | DatabaseCriticalException e) + { + fail("not expected"); + } + finally{ + core.clearData(); + core.cleanUpSearch(); + } + } + @Test + public void test_search_partitionForeign_table(){ + + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =3 and ( (tbl.relkind='r' or tbl.relkind='f' and tbl.oid in (with x as (select pcrelid from pgxc_class where has_nodegroup_privilege(pgroup, 'USAGE')) select * from x where has_table_privilege(x.pcrelid, 'SELECT')))) and tbl.parttype in ('n', 'p', 'v') and relname LIKE ? ;"; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + + formSearchQuery.addRow(new Object[] {1,"abc","3","PUBLIC","r","p",null}); + formSearchQuery.addRow(new Object[] {2,"abcd","3","PUBLIC","f",null,"{location=gsffs://10.18.96.123:5000/,format=orc,delimiter=|,encoding=UTF-8}"}); + preparedstatementHandler.prepareResultSet(Query, + formSearchQuery); + + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(true); + core.getSearchInfo().setFunProcSelected(false); + core.getSearchInfo().setViewsSelected(false); + core.getSearchInfo().setSearchText("ab"); + core.getSearchInfo().setNameMatch(1); + core.getSearchInfo().setMatchCase(true); + + core.search(); + + assertEquals(1, core.getSearchNamespace().getTables().getSize()); + assertEquals(1, core.getSearchNamespace().getForeignTablesGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getViewGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getFunctions().getSize()); + + } + catch (DatabaseOperationException | DatabaseCriticalException e) + { + fail("not expected"); + } + finally{ + core.clearData(); + core.cleanUpSearch(); + } + + + } + + @Test + public void test_search_partitionForeign_table1(){ + + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =3 and ( (tbl.relkind='r' or tbl.relkind='f' and tbl.oid in (with x as (select pcrelid from pgxc_class where has_nodegroup_privilege(pgroup, 'USAGE')) select * from x where has_table_privilege(x.pcrelid, 'SELECT')))) and tbl.parttype in ('n', 'p', 'v') and relname LIKE ? ;"; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + + formSearchQuery.addRow(new Object[] {0,"notablename","3","pg_catalog","f",null,"{location=gsffs://10.18.96.123:5000/,format=orc,delimiter=|,encoding=UTF-8}"}); + preparedstatementHandler.prepareResultSet(Query, + formSearchQuery); + Namespace ns=new SystemNamespace(1, "pg_catalog", core.getSelectedDb()); + ForeignTable forTable = new ForeignTable(ns, + OBJECTTYPE.FOREIGN_TABLE_HDFS); + ns.getForeignTablesGroup().addToGroup(forTable); + core.getSelectedDb().getSystemNamespaceGroup().addToGroup((SystemNamespace) ns); + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(true); + core.getSearchInfo().setFunProcSelected(false); + core.getSearchInfo().setViewsSelected(false); + core.getSearchInfo().setSearchText("ab"); + core.getSearchInfo().setNameMatch(1); + core.getSearchInfo().setMatchCase(true); + + core.search(); + + + } + catch (DatabaseOperationException | DatabaseCriticalException e) + { + fail("not expected"); + } + finally{ + core.clearData(); + core.cleanUpSearch(); + } + + + } + + @Test + public void test_search_partitionForeign_table2(){ + + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =3 and ( (tbl.relkind='r' or tbl.relkind='f' and tbl.oid in (with x as (select pcrelid from pgxc_class where has_nodegroup_privilege(pgroup, 'USAGE')) select * from x where has_table_privilege(x.pcrelid, 'SELECT')))) and tbl.parttype in ('n', 'p', 'v') and relname LIKE ? ;"; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + + formSearchQuery.addRow(new Object[] {0,"notablename","3","pg_catalog","f","p","{location=gsffs://10.18.96.123:5000/,format=orc,delimiter=|,encoding=UTF-8}"}); + preparedstatementHandler.prepareResultSet(Query, + formSearchQuery); + Namespace ns=new SystemNamespace(1, "pg_catalog", core.getSelectedDb()); + ForeignTable forTable = new ForeignTable(ns, + OBJECTTYPE.FOREIGN_TABLE_HDFS); + ns.getForeignTablesGroup().addToGroup(forTable); + core.getSelectedDb().getSystemNamespaceGroup().addToGroup((SystemNamespace) ns); + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(true); + core.getSearchInfo().setFunProcSelected(false); + core.getSearchInfo().setViewsSelected(false); + core.getSearchInfo().setSearchText("ab"); + core.getSearchInfo().setNameMatch(1); + core.getSearchInfo().setMatchCase(true); + + core.search(); + + assertEquals(0, core.getSearchNamespace().getTables().getSize()); + assertEquals(1, core.getSearchNamespace().getForeignTablesGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getViewGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getFunctions().getSize()); + + + } + catch (DatabaseOperationException | DatabaseCriticalException e) + { + fail("not expected"); + } + finally{ + core.clearData(); + core.cleanUpSearch(); + } + + + } + + + @Test +public void test_search_only_views(){ + + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =3 and ( (tbl.relkind='v' and has_table_privilege(tbl.oid, 'SELECT'))) and tbl.parttype in ('n', 'p', 'v') and relname LIKE ? ;"; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + + formSearchQuery.addRow(new Object[] {1,"view","3","PUBLIC","v","n",null}); + preparedstatementHandler.prepareResultSet(Query, + formSearchQuery); + + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(false); + core.getSearchInfo().setFunProcSelected(false); + core.getSearchInfo().setViewsSelected(true); + core.getSearchInfo().setSearchText("view"); + core.getSearchInfo().setNameMatch(2); + core.getSearchInfo().setMatchCase(true); + + core.search(); + + assertEquals(0, core.getSearchNamespace().getTables().getSize()); + //assertEquals(0, core.getSearchNamespace().getPartitionTablesGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getForeignTablesGroup().getSize()); + assertEquals(1, core.getSearchNamespace().getViewGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getFunctions().getSize()); + + } + catch (DatabaseOperationException | DatabaseCriticalException e) + { + fail("not expected"); + } + finally{ + core.clearData(); + core.cleanUpSearch(); + } + + + } + +@Test +public void test_search_only_funcProc(){ + + String Query = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs, pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod, pr.proretset retset, lng.lanname lang,ns.nspname nsname , regexp_matches(objname, ?) FROM pg_proc pr JOIN pg_language lng ON lng.oid=prolang left join pg_namespace ns ON ns.oid=pr.pronamespace WHERE lng.lanname in ('plpgsql','sql','c') and pr.pronamespace=3"; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("objname"); + formSearchQuery.addColumn("namespace"); + formSearchQuery.addColumn("ret"); + formSearchQuery.addColumn("alltype"); + formSearchQuery.addColumn("nargs"); + formSearchQuery.addColumn("argtype"); + formSearchQuery.addColumn("argname"); + formSearchQuery.addColumn("argmod"); + formSearchQuery.addColumn("retset"); + formSearchQuery.addColumn("lang"); + formSearchQuery.addColumn("nsname"); + + formSearchQuery.addRow(new Object[] {1,"function","3",1,null,0,null,null,null,"f","plpgsql","PUBLIC"}); + preparedstatementHandler.prepareResultSet(Query, + formSearchQuery); + + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(false); + core.getSearchInfo().setFunProcSelected(true); + core.getSearchInfo().setViewsSelected(false); + core.getSearchInfo().setSearchText("function%"); + core.getSearchInfo().setNameMatch(3); + core.getSearchInfo().setMatchCase(true); + + core.search(); + + assertEquals(0, core.getSearchNamespace().getTables().getSize()); + //assertEquals(0, core.getSearchNamespace().getPartitionTablesGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getForeignTablesGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getViewGroup().getSize()); + assertEquals(1, core.getSearchNamespace().getFunctions().getSize()); + + } + catch (DatabaseOperationException | DatabaseCriticalException e) + { + fail("not expected"); + } + finally{ + core.clearData(); + core.cleanUpSearch(); + } + + +} +@Test +public void test_table_view_matchCase(){ + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =3 and ( (tbl.relkind='r' or tbl.relkind='f' and tbl.oid in (with x as (select pcrelid from pgxc_class where has_nodegroup_privilege(pgroup, 'USAGE')) select * from x where has_table_privilege(x.pcrelid, 'SELECT'))) or (tbl.relkind='v' and has_table_privilege(tbl.oid, 'SELECT'))) and tbl.parttype in ('n', 'p', 'v') and relname LIKE ? ;"; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + + formSearchQuery.addRow(new Object[] {1,"abc","3","PUBLIC","r","n",null}); + formSearchQuery.addRow(new Object[] {1,"view","3","PUBLIC","v","n",null}); + preparedstatementHandler.prepareResultSet(Query, + formSearchQuery); + + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(true); + core.getSearchInfo().setFunProcSelected(false); + core.getSearchInfo().setViewsSelected(true); + core.getSearchInfo().setSearchText("abc"); + core.getSearchInfo().setNameMatch(0); + core.getSearchInfo().setMatchCase(true); + + core.search(); + + assertEquals(1, core.getSearchNamespace().getTables().getSize()); + //assertEquals(0, core.getSearchNamespace().getPartitionTablesGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getForeignTablesGroup().getSize()); + assertEquals(1, core.getSearchNamespace().getViewGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getFunctions().getSize()); + + } + catch (DatabaseOperationException | DatabaseCriticalException e) + { + fail("not expected"); + } + finally{ + core.clearData(); + core.cleanUpSearch(); + } + + +} + @Test +public void test_tables_view_funProc_matchCase(){ + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions , regexp_matches(relname,?) from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =3 and ( (tbl.relkind='r' or tbl.relkind='f' and tbl.oid in (with x as (select pcrelid from pgxc_class where has_nodegroup_privilege(pgroup, 'USAGE')) select * from x where has_table_privilege(x.pcrelid, 'SELECT'))) or (tbl.relkind='v' and has_table_privilege(tbl.oid, 'SELECT'))) and tbl.parttype in ('n', 'p', 'v') "; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + formSearchQuery.addRow(new Object[] {1,"abc","3","PUBLIC","r","n",null}); + formSearchQuery.addRow(new Object[] {3,"abc","3","PUBLIC","r","p",null}); + formSearchQuery.addRow(new Object[] {2,"abcd","3","PUBLIC","f",null,"{location=gsfs://10.18.96.123:5000/,format=csv,delimiter=|,encoding=UTF-8}"}); + formSearchQuery.addRow(new Object[] {1,"view","3","PUBLIC","v","n",null}); + + preparedstatementHandler.prepareResultSet(Query, + formSearchQuery); + + String Query2 = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs, pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod, pr.proretset retset, lng.lanname lang,ns.nspname nsname , regexp_matches(objname, ?) FROM pg_proc pr JOIN pg_language lng ON lng.oid=prolang left join pg_namespace ns ON ns.oid=pr.pronamespace WHERE lng.lanname in ('plpgsql','sql','c') and pr.pronamespace=3 and has_function_privilege(pr.oid, 'EXECUTE')"; + MockResultSet formSearchQuery2 = preparedstatementHandler + .createResultSet(); + formSearchQuery2.addColumn("oid"); + formSearchQuery2.addColumn("objname"); + formSearchQuery2.addColumn("namespace"); + formSearchQuery2.addColumn("ret"); + formSearchQuery2.addColumn("alltype"); + formSearchQuery2.addColumn("nargs"); + formSearchQuery2.addColumn("argtype"); + formSearchQuery2.addColumn("argname"); + formSearchQuery2.addColumn("argmod"); + formSearchQuery2.addColumn("retset"); + formSearchQuery2.addColumn("lang"); + formSearchQuery2.addColumn("nsname"); + + formSearchQuery2.addRow(new Object[] {1,"function","3",1,null,0,null,null,null,"f","plpgsql","PUBLIC"}); + preparedstatementHandler.prepareResultSet(Query2, + formSearchQuery2); + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(true); + core.getSearchInfo().setFunProcSelected(true); + core.getSearchInfo().setViewsSelected(true); + core.getSearchInfo().setSearchText("%"); + core.getSearchInfo().setNameMatch(3); + core.getSearchInfo().setMatchCase(true); + + core.search(); + core.getSearchNamespace().getChildren(); + core.getSearchNamespace().getTablesGroup(); + assertEquals(2, core.getSearchNamespace().getTables().getSize()); + assertEquals(1, core.getSearchNamespace().getForeignTablesGroup().getSize()); + assertEquals(1, core.getSearchNamespace().getViewGroup().getSize()); + assertEquals(1, core.getSearchNamespace().getFunctions().getSize()); + assertEquals(1, core.getSearchNamespace().getFunctions().getSize()); + assertTrue(core.getSearchNamespace().getChildren()!=null); + + } + catch (DatabaseOperationException | DatabaseCriticalException e) + { + fail("not expected"); + } + finally{ + core.clearData(); + core.cleanUpSearch(); + } + + +} +@Test +public void test_view_funProc_matchCase(){ + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =3 and ( (tbl.relkind='v' and has_table_privilege(tbl.oid, 'SELECT'))) and tbl.parttype in ('n', 'p', 'v') "; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + + formSearchQuery.addRow(new Object[] {1,"abdcf","3","PUBLIC","v","n",null}); + + preparedstatementHandler.prepareResultSet(Query, + formSearchQuery); + + String Query2 = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs, pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod, pr.proretset retset, lng.lanname lang,ns.nspname nsname FROM pg_proc pr JOIN pg_language lng ON lng.oid=prolang left join pg_namespace ns ON ns.oid=pr.pronamespace WHERE lng.lanname in ('plpgsql','sql','c') and pr.pronamespace=3 and has_function_privilege(pr.oid, 'EXECUTE') and objname LIKE ? ;"; + MockResultSet formSearchQuery2 = preparedstatementHandler + .createResultSet(); + formSearchQuery2.addColumn("oid"); + formSearchQuery2.addColumn("objname"); + formSearchQuery2.addColumn("namespace"); + formSearchQuery2.addColumn("ret"); + formSearchQuery2.addColumn("alltype"); + formSearchQuery2.addColumn("nargs"); + formSearchQuery2.addColumn("argtype"); + formSearchQuery2.addColumn("argname"); + formSearchQuery2.addColumn("argmod"); + formSearchQuery2.addColumn("retset"); + formSearchQuery2.addColumn("lang"); + formSearchQuery2.addColumn("nsname"); + + formSearchQuery2.addRow(new Object[] {1,"abdfghj","3",1,null,0,null,null,null,"f","plpgsql","PUBLIC"}); + preparedstatementHandler.prepareResultSet(Query2, + formSearchQuery2); + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(false); + core.getSearchInfo().setFunProcSelected(true); + core.getSearchInfo().setViewsSelected(true); + core.getSearchInfo().setSearchText("abd"); + core.getSearchInfo().setNameMatch(1); + core.getSearchInfo().setMatchCase(true); + + core.search(); + + assertEquals(0, core.getSearchNamespace().getTables().getSize()); + //assertEquals(0, core.getSearchNamespace().getPartitionTablesGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getForeignTablesGroup().getSize()); + assertEquals(1, core.getSearchNamespace().getViewGroup().getSize()); + assertEquals(1, core.getSearchNamespace().getFunctions().getSize()); + + } + catch (DatabaseOperationException | DatabaseCriticalException e) + { + fail("not expected"); + } + finally{ + core.clearData(); + core.cleanUpSearch(); + } + + +} +@Test + public void test_tables_funProc_matchCase() + { + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =3 and ( (tbl.relkind='r' or tbl.relkind='f' and tbl.oid in (with x as (select pcrelid from pgxc_class where has_nodegroup_privilege(pgroup, 'USAGE')) select * from x where has_table_privilege(x.pcrelid, 'SELECT')))) and tbl.parttype in ('n', 'p', 'v') "; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + formSearchQuery + .addRow(new Object[] {3, "abc", "3", "PUBLIC", "r", "n", null}); + formSearchQuery.addRow(new Object[] {3, "abcd", "3", "PUBLIC", "f", + null, + "{location=gsfs://10.18.96.123:5000/,format=csv,delimiter=|,encoding=UTF-8}"}); + + preparedstatementHandler.prepareResultSet(Query, formSearchQuery); + + String Query2 = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs, pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod, pr.proretset retset, lng.lanname lang,ns.nspname nsname FROM pg_proc pr JOIN pg_language lng ON lng.oid=prolang left join pg_namespace ns ON ns.oid=pr.pronamespace WHERE lng.lanname in ('plpgsql','sql','c') and pr.pronamespace=3 and has_function_privilege(pr.oid, 'EXECUTE') and objname LIKE ? ;"; + MockResultSet formSearchQuery2 = preparedstatementHandler + .createResultSet(); + formSearchQuery2.addColumn("oid"); + formSearchQuery2.addColumn("objname"); + formSearchQuery2.addColumn("namespace"); + formSearchQuery2.addColumn("ret"); + formSearchQuery2.addColumn("alltype"); + formSearchQuery2.addColumn("nargs"); + formSearchQuery2.addColumn("argtype"); + formSearchQuery2.addColumn("argname"); + formSearchQuery2.addColumn("argmod"); + formSearchQuery2.addColumn("retset"); + formSearchQuery2.addColumn("lang"); + formSearchQuery2.addColumn("nsname"); + + formSearchQuery2.addRow(new Object[] {3,"function","3",1,null,0,null,null,null,"f","plpgsql","PUBLIC"}); + preparedstatementHandler.prepareResultSet(Query2, formSearchQuery2); + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(true); + core.getSearchInfo().setFunProcSelected(true); + core.getSearchInfo().setViewsSelected(false); + core.getSearchInfo().setSearchText("abc"); + core.getSearchInfo().setNameMatch(2); + core.getSearchInfo().setMatchCase(true); + + core.search(); + + assertEquals(1, core.getSearchNamespace().getTables().getSize()); +// assertEquals(1, core.getSearchNamespace().getPartitionTablesGroup() +// .getSize()); + assertEquals(1, core.getSearchNamespace().getForeignTablesGroup() + .getSize()); + assertEquals(0, core.getSearchNamespace().getViewGroup().getSize()); + assertEquals(1, core.getSearchNamespace().getFunctions().getSize()); + + } + catch (DatabaseOperationException | DatabaseCriticalException e) + { + fail("not expected"); + } + finally + { + core.clearData(); + core.cleanUpSearch(); + } + + } + @Test + public void test_table_view(){ + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =3 and ( (tbl.relkind='r' or tbl.relkind='f' and tbl.oid in (with x as (select pcrelid from pgxc_class where has_nodegroup_privilege(pgroup, 'USAGE')) select * from x where has_table_privilege(x.pcrelid, 'SELECT'))) or (tbl.relkind='v' and has_table_privilege(tbl.oid, 'SELECT'))) and tbl.parttype in ('n', 'p', 'v') and relname ILIKE ? ;"; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + + formSearchQuery.addRow(new Object[] {1,"abc","3","PUBLIC","r","n",null}); + formSearchQuery.addRow(new Object[] {1,"view","3","PUBLIC","v","n",null}); + preparedstatementHandler.prepareResultSet(Query, + formSearchQuery); + + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(true); + core.getSearchInfo().setFunProcSelected(false); + core.getSearchInfo().setViewsSelected(true); + core.getSearchInfo().setSearchText("abc"); + core.getSearchInfo().setNameMatch(0); + core.getSearchInfo().setMatchCase(false); + + core.search(); + + assertEquals(1, core.getSearchNamespace().getTables().getSize()); +// assertEquals(0, core.getSearchNamespace().getPartitionTablesGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getForeignTablesGroup().getSize()); + assertEquals(1, core.getSearchNamespace().getViewGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getFunctions().getSize()); + + } + catch (DatabaseOperationException | DatabaseCriticalException e) + { + fail("not expected"); + } + finally{ + core.clearData(); + core.cleanUpSearch(); + } + + + } + @Test + public void test_tables_view_funProc(){ + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions , regexp_matches(relname,?) from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =3 and ( (tbl.relkind='r' or tbl.relkind='f' and tbl.oid in (with x as (select pcrelid from pgxc_class where has_nodegroup_privilege(pgroup, 'USAGE')) select * from x where has_table_privilege(x.pcrelid, 'SELECT'))) or (tbl.relkind='v' and has_table_privilege(tbl.oid, 'SELECT'))) and tbl.parttype in ('n', 'p', 'v') "; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + formSearchQuery.addRow(new Object[] {1,"abc","3","PUBLIC","r","n",null}); + formSearchQuery.addRow(new Object[] {3,"abc","3","PUBLIC","r","p",null}); + formSearchQuery.addRow(new Object[] {2,"abcd","3","PUBLIC","f",null,"{location=gsfs://10.18.96.123:5000/,format=csv,delimiter=|,encoding=UTF-8}"}); + formSearchQuery.addRow(new Object[] {1,"view","3","PUBLIC","v","n",null}); + + preparedstatementHandler.prepareResultSet(Query, + formSearchQuery); + + String Query2 = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs, pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod, pr.proretset retset, lng.lanname lang,ns.nspname nsname , regexp_matches(objname, ?,'i') FROM pg_proc pr JOIN pg_language lng ON lng.oid=prolang left join pg_namespace ns ON ns.oid=pr.pronamespace WHERE lng.lanname in ('plpgsql','sql','c') and pr.pronamespace=3 and has_function_privilege(pr.oid, 'EXECUTE')"; + MockResultSet formSearchQuery2 = preparedstatementHandler + .createResultSet(); + formSearchQuery2.addColumn("oid"); + formSearchQuery2.addColumn("objname"); + formSearchQuery2.addColumn("namespace"); + formSearchQuery2.addColumn("ret"); + formSearchQuery2.addColumn("alltype"); + formSearchQuery2.addColumn("nargs"); + formSearchQuery2.addColumn("argtype"); + formSearchQuery2.addColumn("argname"); + formSearchQuery2.addColumn("argmod"); + formSearchQuery2.addColumn("retset"); + formSearchQuery2.addColumn("lang"); + formSearchQuery2.addColumn("nsname"); + + formSearchQuery2.addRow(new Object[] {1,"abdfghj","3",1,null,0,null,null,null,"f","plpgsql","PUBLIC"}); + preparedstatementHandler.prepareResultSet(Query2, + formSearchQuery2); + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(true); + core.getSearchInfo().setFunProcSelected(true); + core.getSearchInfo().setViewsSelected(true); + core.getSearchInfo().setSearchText("%"); + core.getSearchInfo().setNameMatch(3); + core.getSearchInfo().setMatchCase(false); + + core.search(); + + assertEquals(2, core.getSearchNamespace().getTables().getSize()); + assertEquals(1, core.getSearchNamespace().getForeignTablesGroup().getSize()); + assertEquals(1, core.getSearchNamespace().getViewGroup().getSize()); + assertEquals(1, core.getSearchNamespace().getFunctions().getSize()); + + } + catch (DatabaseOperationException | DatabaseCriticalException e) + { + fail("not expected"); + } + finally{ + core.clearData(); + core.cleanUpSearch(); + } + + + } + + @Test + public void test_view_funProc(){ + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =3 and ( (tbl.relkind='v' and has_table_privilege(tbl.oid, 'SELECT'))) and tbl.parttype in ('n', 'p', 'v') "; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + + formSearchQuery.addRow(new Object[] {1,"abdcf","3","PUBLIC","v","n",null}); + + preparedstatementHandler.prepareResultSet(Query, + formSearchQuery); + + String Query2 = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs, pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod, pr.proretset retset, lng.lanname lang,ns.nspname nsname FROM pg_proc pr JOIN pg_language lng ON lng.oid=prolang left join pg_namespace ns ON ns.oid=pr.pronamespace WHERE lng.lanname in ('plpgsql','sql','c') and pr.pronamespace=3 and has_function_privilege(pr.oid, 'EXECUTE') and objname ILIKE ? ;"; + MockResultSet formSearchQuery2 = preparedstatementHandler + .createResultSet(); + formSearchQuery2.addColumn("oid"); + formSearchQuery2.addColumn("objname"); + formSearchQuery2.addColumn("namespace"); + formSearchQuery2.addColumn("ret"); + formSearchQuery2.addColumn("alltype"); + formSearchQuery2.addColumn("nargs"); + formSearchQuery2.addColumn("argtype"); + formSearchQuery2.addColumn("argname"); + formSearchQuery2.addColumn("argmod"); + formSearchQuery2.addColumn("retset"); + formSearchQuery2.addColumn("lang"); + formSearchQuery2.addColumn("nsname"); + + formSearchQuery2.addRow(new Object[] {1,"abdfghj","3",1,null,0,null,null,null,"f","sql","PUBLIC"}); + preparedstatementHandler.prepareResultSet(Query2, + formSearchQuery2); + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(false); + core.getSearchInfo().setFunProcSelected(true); + core.getSearchInfo().setViewsSelected(true); + core.getSearchInfo().setSearchText("abd"); + core.getSearchInfo().setNameMatch(1); + core.getSearchInfo().setMatchCase(false); + + core.search(); + + assertEquals(0, core.getSearchNamespace().getTables().getSize()); +// assertEquals(0, core.getSearchNamespace().getPartitionTablesGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getForeignTablesGroup().getSize()); + assertEquals(1, core.getSearchNamespace().getViewGroup().getSize()); + assertEquals(1, core.getSearchNamespace().getFunctions().getSize()); + + } + catch (DatabaseOperationException | DatabaseCriticalException e) + { + fail("not expected"); + } + finally{ + core.clearData(); + core.cleanUpSearch(); + } + + + } + + @Test + public void test_getConnection_failure() + { + try + { + for (int i = 1; i <= 20; i++) + { + + core.getSelectedDb().getConnectionManager().getFreeConnection(); + } + core.getConnection(); + fail("Connection should be successful"); + } + catch (MPPDBIDEException e) + { + assertTrue(true); + + } + + } + + @Test + public void test_search_only_regulartables_DBOperationException() + { + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =3 and ( (tbl.relkind='r' or tbl.relkind='f' and tbl.oid in (with x as (select pcrelid from pgxc_class where has_nodegroup_privilege(pgroup, 'USAGE')) select * from x where has_table_privilege(x.pcrelid, 'SELECT')))) and tbl.parttype in ('n', 'p', 'v') and relname LIKE ? ;"; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + + formSearchQuery + .addRow(new Object[] {3, "abc", "3", "PUBLIC", "r", "n", null}); + preparedstatementHandler.prepareThrowsSQLException(Query); + + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(true); + core.getSearchInfo().setFunProcSelected(false); + core.getSearchInfo().setViewsSelected(false); + core.getSearchInfo().setSearchText("bc"); + core.getSearchInfo().setNameMatch(0); + core.getSearchInfo().setMatchCase(true); + + core.search(); + fail("Not Excepted to come here"); + + } + catch (DatabaseCriticalException e) + { + + fail("Not Excepted to come here"); + } + catch (DatabaseOperationException e) + { + assertTrue(true); + } + + finally + { + core.clearData(); + core.cleanUpSearch(); + } + } + + @Test + public void test_search_only_regulartables_DBCriticleException() + { + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =3 and ( (tbl.relkind='r' or tbl.relkind='f' and tbl.oid in (with x as (select pcrelid from pgxc_class where has_nodegroup_privilege(pgroup, 'USAGE')) select * from x where has_table_privilege(x.pcrelid, 'SELECT')))) and tbl.parttype in ('n', 'p', 'v') and relname LIKE ? ;"; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + + formSearchQuery + .addRow(new Object[] {1, "abc", "3", "PUBLIC", "r", "n", null}); + ArrayList list = new ArrayList(); + preparedstatementHandler.prepareThrowsSQLException(Query,new SQLException( + "Throwing SQL exception intentionally.", "57PSQLException"), list); + + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(true); + core.getSearchInfo().setFunProcSelected(false); + core.getSearchInfo().setViewsSelected(false); + core.getSearchInfo().setSearchText("bc"); + core.getSearchInfo().setNameMatch(0); + core.getSearchInfo().setMatchCase(true); + + core.search(); + fail("Not Excepted to come here"); + + } + catch (DatabaseCriticalException e) + { + + assertTrue(true); + + } + catch (DatabaseOperationException e) + { + fail("Not Excepted to come here"); + } + + finally + { + core.clearData(); + core.cleanUpSearch(); + } + } + + @Test + public void test_search_only_funcProc_DBOperation(){ + + String Query = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs, pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod, pr.proretset retset, lng.lanname lang,ns.nspname nsname , regexp_matches(objname, ?) FROM pg_proc pr JOIN pg_language lng ON lng.oid=prolang left join pg_namespace ns ON ns.oid=pr.pronamespace WHERE lng.lanname in ('plpgsql','sql','c') and pr.pronamespace=3"; + MockResultSet formSearchQuery2 = preparedstatementHandler + .createResultSet(); + formSearchQuery2.addColumn("oid"); + formSearchQuery2.addColumn("objname"); + formSearchQuery2.addColumn("namespace"); + formSearchQuery2.addColumn("ret"); + formSearchQuery2.addColumn("alltype"); + formSearchQuery2.addColumn("nargs"); + formSearchQuery2.addColumn("argtype"); + formSearchQuery2.addColumn("argname"); + formSearchQuery2.addColumn("argmod"); + formSearchQuery2.addColumn("retset"); + formSearchQuery2.addColumn("lang"); + formSearchQuery2.addColumn("nsname"); + + formSearchQuery2.addRow(new Object[] {1,"abdfghj","3",1,null,0,null,null,null,"f","sql","PUBLIC"}); + preparedstatementHandler.prepareThrowsSQLException(Query); + + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(false); + core.getSearchInfo().setFunProcSelected(true); + core.getSearchInfo().setViewsSelected(false); + core.getSearchInfo().setSearchText("function%"); + core.getSearchInfo().setNameMatch(3); + core.getSearchInfo().setMatchCase(true); + + core.search(); + fail("not expected"); + + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + assertTrue(true); + } + + finally{ + core.clearData(); + core.cleanUpSearch(); + } + + + } + + @Test + public void test_search_only_funcProc_DBCriticle(){ + String Query = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs, pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod, pr.proretset retset, lng.lanname lang,ns.nspname nsname , regexp_matches(objname, ?) FROM pg_proc pr JOIN pg_language lng ON lng.oid=prolang left join pg_namespace ns ON ns.oid=pr.pronamespace WHERE lng.lanname in ('plpgsql','sql','c') and pr.pronamespace=3"; + MockResultSet formSearchQuery2 = preparedstatementHandler + .createResultSet(); + formSearchQuery2.addColumn("oid"); + formSearchQuery2.addColumn("objname"); + formSearchQuery2.addColumn("namespace"); + formSearchQuery2.addColumn("ret"); + formSearchQuery2.addColumn("alltype"); + formSearchQuery2.addColumn("nargs"); + formSearchQuery2.addColumn("argtype"); + formSearchQuery2.addColumn("argname"); + formSearchQuery2.addColumn("argmod"); + formSearchQuery2.addColumn("retset"); + formSearchQuery2.addColumn("lang"); + formSearchQuery2.addColumn("nsname"); + + formSearchQuery2.addRow(new Object[] {1,"abdfghj","3",1,null,0,null,null,null,"f","sql","PUBLIC"}); + ArrayList list = new ArrayList(); + preparedstatementHandler.prepareThrowsSQLException(Query,new SQLException( + "Throwing SQL exception intentionally.", "57PSQLException"), list); + + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(false); + core.getSearchInfo().setFunProcSelected(true); + core.getSearchInfo().setViewsSelected(false); + core.getSearchInfo().setSearchText("function%"); + core.getSearchInfo().setNameMatch(3); + core.getSearchInfo().setMatchCase(true); + + core.search(); + fail("not expected"); + + } + catch (DatabaseCriticalException e) + { + assertTrue(true); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + + finally{ + core.clearData(); + core.cleanUpSearch(); + } + + + } + + @Test + public void test_search_only_funcProc_SQLEXception(){ + + ExceptionConnectionHelper exceptionConnection = new ExceptionConnectionHelper(); + exceptionConnection.setNeedExceptioStatement(true); + exceptionConnection.setNeedExceptionResultset(true); + exceptionConnection.setThrowExceptionNext(true); + exceptionConnection.setThrownResultSetNext(EXCEPTIONENUM.EXCEPTION); + + getJDBCMockObjectFactory().getMockDriver().setupConnection(exceptionConnection); + + String Query = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs, pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod, pr.proretset retset, lng.lanname lang,ns.nspname nsname , regexp_matches(objname,'function%') FROM pg_proc pr JOIN pg_language lng ON lng.oid=prolang left join pg_namespace ns ON ns.oid=pr.pronamespace WHERE lng.lanname in ('plpgsql','sql') and pr.pronamespace=1;"; + MockResultSet formSearchQuery2 = preparedstatementHandler + .createResultSet(); + formSearchQuery2.addColumn("oid"); + formSearchQuery2.addColumn("objname"); + formSearchQuery2.addColumn("namespace"); + formSearchQuery2.addColumn("ret"); + formSearchQuery2.addColumn("alltype"); + formSearchQuery2.addColumn("nargs"); + formSearchQuery2.addColumn("argtype"); + formSearchQuery2.addColumn("argname"); + formSearchQuery2.addColumn("argmod"); + formSearchQuery2.addColumn("retset"); + formSearchQuery2.addColumn("lang"); + formSearchQuery2.addColumn("nsname"); + + formSearchQuery2.addRow(new Object[] {1,"abdfghj","1",1,null,0,null,null,null,"f","sql","PUBLIC"}); + preparedstatementHandler.prepareResultSet(Query,formSearchQuery2); + + + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(false); + core.getSearchInfo().setFunProcSelected(true); + core.getSearchInfo().setViewsSelected(false); + core.getSearchInfo().setSearchText("function%"); + core.getSearchInfo().setNameMatch(3); + core.getSearchInfo().setMatchCase(true); + + core.search(); + fail("not expected"); + + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + assertTrue(true); + } + catch (Exception e) + { + assertTrue(true); + } + finally + { + core.clearData(); + core.cleanUpSearch(); + } + + + } + + @Test + public void test_search_only_views_SQLException(){ + + ExceptionConnectionHelper exceptionConnection = new ExceptionConnectionHelper(); + exceptionConnection.setNeedExceptioStatement(true); + exceptionConnection.setNeedExceptionResultset(true); + exceptionConnection.setThrowExceptionNext(true); + exceptionConnection.setThrownResultSetNext(EXCEPTIONENUM.EXCEPTION); + + getJDBCMockObjectFactory().getMockDriver().setupConnection(exceptionConnection); + + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =1 and ( (tbl.relkind='v' and has_table_privilege(tbl.oid, 'SELECT'))) and tbl.parttype in ('n', 'p', 'v') and relname LIKE ? ;"; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + + formSearchQuery.addRow(new Object[] {1,"view","1","PUBLIC","v","n",null}); + preparedstatementHandler.prepareResultSet(Query, + formSearchQuery); + + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(false); + core.getSearchInfo().setFunProcSelected(false); + core.getSearchInfo().setViewsSelected(true); + core.getSearchInfo().setSearchText("view"); + core.getSearchInfo().setNameMatch(2); + core.getSearchInfo().setMatchCase(true); + + core.search(); + + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + assertTrue(true); + } + catch (Exception e) + { + assertTrue(true); + } + finally + { + core.clearData(); + core.cleanUpSearch(); + } + + + } + + @Test + public void test_search_only_funcProc_1(){ + String Query = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs, pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod, pr.proretset retset, lng.lanname lang,ns.nspname nsname , regexp_matches(objname, ?) FROM pg_proc pr JOIN pg_language lng ON lng.oid=prolang left join pg_namespace ns ON ns.oid=pr.pronamespace WHERE lng.lanname in ('plpgsql','sql','c') and pr.pronamespace=3"; + MockResultSet formSearchQuery2 = preparedstatementHandler + .createResultSet(); + formSearchQuery2.addColumn("oid"); + formSearchQuery2.addColumn("objname"); + formSearchQuery2.addColumn("namespace"); + formSearchQuery2.addColumn("ret"); + formSearchQuery2.addColumn("alltype"); + formSearchQuery2.addColumn("nargs"); + formSearchQuery2.addColumn("argtype"); + formSearchQuery2.addColumn("argname"); + formSearchQuery2.addColumn("argmod"); + formSearchQuery2.addColumn("retset"); + formSearchQuery2.addColumn("lang"); + formSearchQuery2.addColumn("nsname"); + + formSearchQuery2.addRow(new Object[] {1,"function","3",1,null,0,null,null,null,"f","sql","information_schema"}); + + + preparedstatementHandler.prepareResultSet(Query,formSearchQuery2); + + + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(false); + core.getSearchInfo().setFunProcSelected(true); + core.getSearchInfo().setViewsSelected(false); + core.getSearchInfo().setSearchText("function%"); + core.getSearchInfo().setNameMatch(3); + core.getSearchInfo().setMatchCase(true); + + core.search(); + assertEquals(0, core.getSearchNamespace().getTables().getSize()); +// assertEquals(0, core.getSearchNamespace().getPartitionTablesGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getForeignTablesGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getViewGroup().getSize()); + assertEquals(1, core.getSearchNamespace().getFunctions().getSize()); + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + + finally + { + core.clearData(); + core.cleanUpSearch(); + } + + } + + + @Test + public void test_search_only_views_2(){ + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =3 and ( (tbl.relkind='v' and has_table_privilege(tbl.oid, 'SELECT'))) and tbl.parttype in ('n', 'p', 'v') and relname LIKE ? ;"; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + + formSearchQuery.addRow(new Object[] {1,"view","3","information_schema","v","n",null}); + preparedstatementHandler.prepareResultSet(Query, + formSearchQuery); + + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(false); + core.getSearchInfo().setFunProcSelected(false); + core.getSearchInfo().setViewsSelected(true); + core.getSearchInfo().setSearchText("view"); + core.getSearchInfo().setNameMatch(2); + core.getSearchInfo().setMatchCase(true); + + core.search(); + core.getSearchedDatabase(); + core.setExecutionTime("1ms"); + assertEquals(0, core.getSearchNamespace().getTables().getSize()); +// assertEquals(0, core.getSearchNamespace().getPartitionTablesGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getForeignTablesGroup().getSize()); + assertEquals(1, core.getSearchNamespace().getViewGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getFunctions().getSize()); + assertEquals(1, core.getRowsFetched()); + assertEquals("1ms", core.getExecutionTime()); + assertEquals("Gauss", core.getSearchedDatabase().getDbName()); + assertEquals(1, core.getSearchedDatabase().getAllSearchNameSpaces().size()); + assertTrue(core.getSearchedDatabase().getDb()!=null); + assertFalse(core.getSearchedDatabase().equals(null)); + assertFalse(core.getSearchNamespace().equals(null)); + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + + finally + { + core.clearData(); + core.cleanUpSearch(); + } + + + } + + @Test + public void test_search_only_views_3(){ + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =3 and ( (tbl.relkind='v' and has_table_privilege(tbl.oid, 'SELECT'))) and tbl.parttype in ('n', 'p', 'v') and relname LIKE ? ;"; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + + formSearchQuery.addRow(new Object[] {1,"view","3","information_schema","v","n",null}); + preparedstatementHandler.prepareResultSet(Query, + formSearchQuery); + + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(false); + core.getSearchInfo().setFunProcSelected(false); + core.getSearchInfo().setViewsSelected(true); + core.getSearchInfo().setSearchText("view"); + core.getSearchInfo().setNameMatch(2); + core.getSearchInfo().setMatchCase(true); + + core.search(); + core.cancelQuery(); + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + + finally + { + core.clearData(); + core.cleanUpSearch(); + } + + + } + + @Test + public void test_tables_view_funProc_sequences(){ + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions , regexp_matches(relname,?) from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =3 and ( (tbl.relkind='r' or tbl.relkind='f' and tbl.oid in (with x as (select pcrelid from pgxc_class where has_nodegroup_privilege(pgroup, 'USAGE')) select * from x where has_table_privilege(x.pcrelid, 'SELECT'))) or (tbl.relkind='v' and has_table_privilege(tbl.oid, 'SELECT')) or (tbl.relkind='S' and has_sequence_privilege('\"'|| ns.nspname||'\"'||'.'||'\"'||tbl.relname||'\"', 'USAGE'))) and tbl.parttype in ('n', 'p', 'v') "; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relowner"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + formSearchQuery.addRow(new Object[] {1,"abc","3","PUBLIC",null,"r","n",null}); + formSearchQuery.addRow(new Object[] {3,"abd","3","PUBLIC",null,"r","p",null}); + formSearchQuery.addRow(new Object[] {2,"abcd","3","PUBLIC",null,"f",null,"{location=gsfs://10.18.96.123:5000/,format=csv,delimiter=|,encoding=UTF-8}"}); + formSearchQuery.addRow(new Object[] {1,"view","3","PUBLIC",null,"v","n",null}); + formSearchQuery.addRow(new Object[] {1,"s1","3","PUBLIC",null,"S","n",null}); + preparedstatementHandler.prepareResultSet(Query, + formSearchQuery); + + String Query2 = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, pr.proallargtypes alltype, pr.pronargs nargs, pr.proargtypes argtype, pr.proargnames argname, pr.proargmodes argmod, pr.proretset retset, lng.lanname lang,ns.nspname nsname , regexp_matches(objname, ?,'i') FROM pg_proc pr JOIN pg_language lng ON lng.oid=prolang left join pg_namespace ns ON ns.oid=pr.pronamespace WHERE lng.lanname in ('plpgsql','sql','c') and pr.pronamespace=3 and has_function_privilege(pr.oid, 'EXECUTE')"; + MockResultSet formSearchQuery2 = preparedstatementHandler + .createResultSet(); + formSearchQuery2.addColumn("oid"); + formSearchQuery2.addColumn("objname"); + formSearchQuery2.addColumn("namespace"); + formSearchQuery2.addColumn("ret"); + formSearchQuery2.addColumn("alltype"); + formSearchQuery2.addColumn("nargs"); + formSearchQuery2.addColumn("argtype"); + formSearchQuery2.addColumn("argname"); + formSearchQuery2.addColumn("argmod"); + formSearchQuery2.addColumn("retset"); + formSearchQuery2.addColumn("lang"); + formSearchQuery2.addColumn("nsname"); + + formSearchQuery2.addRow(new Object[] {1,"abdfghj","3",1,null,0,null,null,null,"f","plpgsql","PUBLIC"}); + preparedstatementHandler.prepareResultSet(Query2, + formSearchQuery2); + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(true); + core.getSearchInfo().setFunProcSelected(true); + core.getSearchInfo().setViewsSelected(true); + core.getSearchInfo().setSearchText("%"); + core.getSearchInfo().setNameMatch(3); + core.getSearchInfo().setMatchCase(false); + core.getSearchInfo().setSequenceSelected(true); + + core.search(); + + assertEquals(2, core.getSearchNamespace().getTables().getSize()); + assertEquals(1, core.getSearchNamespace().getForeignTablesGroup().getSize()); + assertEquals(1, core.getSearchNamespace().getViewGroup().getSize()); + assertEquals(1, core.getSearchNamespace().getFunctions().getSize()); + assertEquals(1, core.getSearchNamespace().getSequenceGroup().getSize()); + + } + catch (DatabaseOperationException | DatabaseCriticalException e) + { + fail("not expected"); + } + finally{ + core.clearData(); + core.cleanUpSearch(); + } + + + } + + @Test + public void test_tables_view_sequences(){ + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions , regexp_matches(relname,?) from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =3 and ( (tbl.relkind='r' or tbl.relkind='f' and tbl.oid in (with x as (select pcrelid from pgxc_class where has_nodegroup_privilege(pgroup, 'USAGE')) select * from x where has_table_privilege(x.pcrelid, 'SELECT'))) or (tbl.relkind='v' and has_table_privilege(tbl.oid, 'SELECT')) or (tbl.relkind='S' and has_sequence_privilege('\"'|| ns.nspname||'\"'||'.'||'\"'||tbl.relname||'\"', 'USAGE'))) and tbl.parttype in ('n', 'p', 'v') "; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relowner"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + formSearchQuery.addRow(new Object[] {1,"abc","3","PUBLIC",null,"r","n",null}); + formSearchQuery.addRow(new Object[] {1,"view","3","PUBLIC",null,"v","n",null}); + formSearchQuery.addRow(new Object[] {1,"s1","3","PUBLIC",null,"S","n",null}); + + preparedstatementHandler.prepareResultSet(Query, + formSearchQuery); + + + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(true); + core.getSearchInfo().setFunProcSelected(false); + core.getSearchInfo().setViewsSelected(true); + core.getSearchInfo().setSearchText("%"); + core.getSearchInfo().setNameMatch(3); + core.getSearchInfo().setMatchCase(false); + core.getSearchInfo().setSequenceSelected(true); + + core.search(); + + assertEquals(1, core.getSearchNamespace().getTables().getSize()); +// assertEquals(0, core.getSearchNamespace().getPartitionTablesGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getForeignTablesGroup().getSize()); + assertEquals(1, core.getSearchNamespace().getViewGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getFunctions().getSize()); + assertEquals(1, core.getSearchNamespace().getSequenceGroup().getSize()); + + + } + catch (DatabaseOperationException | DatabaseCriticalException e) + { + fail("not expected"); + } + finally{ + core.clearData(); + core.cleanUpSearch(); + } + + + } + + @Test + public void test_tables_sequences(){ + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions , regexp_matches(relname,?) from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =3 and ( (tbl.relkind='r' or tbl.relkind='f' and tbl.oid in (with x as (select pcrelid from pgxc_class where has_nodegroup_privilege(pgroup, 'USAGE')) select * from x where has_table_privilege(x.pcrelid, 'SELECT'))) or (tbl.relkind='S' and has_sequence_privilege('\"'|| ns.nspname||'\"'||'.'||'\"'||tbl.relname||'\"', 'USAGE'))) and tbl.parttype in ('n', 'p', 'v') "; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relowner"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + formSearchQuery.addRow(new Object[] {1,"abc","3","PUBLIC",null,"r","n",null}); + formSearchQuery.addRow(new Object[] {1,"s1","3","PUBLIC",null,"S","n",null}); + preparedstatementHandler.prepareResultSet(Query, + formSearchQuery); + + + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(true); + core.getSearchInfo().setFunProcSelected(false); + core.getSearchInfo().setViewsSelected(false); + core.getSearchInfo().setSearchText("%"); + core.getSearchInfo().setNameMatch(3); + core.getSearchInfo().setMatchCase(false); + core.getSearchInfo().setSequenceSelected(true); + + core.search(); + + assertEquals(1, core.getSearchNamespace().getTables().getSize()); +// assertEquals(0, core.getSearchNamespace().getPartitionTablesGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getForeignTablesGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getViewGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getFunctions().getSize()); + assertEquals(1, core.getSearchNamespace().getSequenceGroup().getSize()); + + + } + catch (DatabaseOperationException | DatabaseCriticalException e) + { + fail("not expected"); + } + finally{ + core.clearData(); + core.cleanUpSearch(); + } + + + } + + @Test + public void test_only_sequences(){ + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions , regexp_matches(relname,?) from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =3 and ( (tbl.relkind='S' and has_sequence_privilege('\"'|| ns.nspname||'\"'||'.'||'\"'||tbl.relname||'\"', 'USAGE'))) and tbl.parttype in ('n', 'p', 'v') "; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relowner"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + formSearchQuery.addRow(new Object[] {1,"s1","3","PUBLIC",null,"S","n",null}); + preparedstatementHandler.prepareResultSet(Query, + formSearchQuery); + + + try + { + + core.getConnection(); + core.getSearchInfo().setTableSelected(false); + core.getSearchInfo().setFunProcSelected(false); + core.getSearchInfo().setViewsSelected(false); + core.getSearchInfo().setSearchText("%"); + core.getSearchInfo().setNameMatch(3); + core.getSearchInfo().setMatchCase(false); + core.getSearchInfo().setSequenceSelected(true); + + core.search(); + + assertEquals(0, core.getSearchNamespace().getTables().getSize()); +// assertEquals(0, core.getSearchNamespace().getPartitionTablesGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getForeignTablesGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getViewGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getFunctions().getSize()); + assertEquals(1, core.getSearchNamespace().getSequenceGroup().getSize()); + core.getSearchNamespace().getChildren(); + assertEquals(6, SearchObjectEnum.values().length); + assertEquals(SearchObjectEnum.SEARCH_INI,SearchObjectEnum.valueOf("SEARCH_INI")); + assertEquals(SearchNameMatchEnum.CONTAINS,SearchNameMatchEnum.valueOf("CONTAINS")); + } + catch (DatabaseOperationException | DatabaseCriticalException e) + { + fail("not expected"); + } + finally{ + core.clearData(); + core.cleanUpSearch(); + } + + + } + + @Test + public void test_AbstractSearchObjUtils_methods(){ + ArrayList array = new ArrayList(); + array.add("test1"); + array.add("test2"); + assertEquals(0,AbstractSearchObjUtils.getIndexByValue(array, "test1")); + assertEquals(1,AbstractSearchObjUtils.getIndexByValue(array, "test2")); + assertEquals(0,AbstractSearchObjUtils.getIndexByValue(array, "test3")); + } + + @Test + public void test_SearchObjCore_methods(){ + SearchObjCore searchObjCore = new SearchObjCore(); + assertNotNull(searchObjCore.getNameMatchList()); + } + + @Test + public void test_only_sequences1(){ + String Query = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname,tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions , regexp_matches(relname,?) from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) where tbl.relnamespace =3 and ( (tbl.relkind='S' and has_sequence_privilege('\"'|| ns.nspname||'\"'||'.'||'\"'||tbl.relname||'\"', 'USAGE'))) and tbl.parttype in ('n', 'p', 'v') "; + MockResultSet formSearchQuery = preparedstatementHandler + .createResultSet(); + formSearchQuery.addColumn("oid"); + formSearchQuery.addColumn("relname"); + formSearchQuery.addColumn("relnamespace"); + formSearchQuery.addColumn("nsname"); + formSearchQuery.addColumn("relowner"); + formSearchQuery.addColumn("relkind"); + formSearchQuery.addColumn("parttype"); + formSearchQuery.addColumn("ftoptions"); + formSearchQuery.addRow(new Object[] {1,"s1","3","pg_catalog",null,"S","n",null}); + preparedstatementHandler.prepareResultSet(Query, + formSearchQuery); + + + try + { + Namespace ns=new SystemNamespace(1, "pg_catalog", core.getSelectedDb()); + + SequenceMetadata seq = new SequenceMetadata(1, "s1", + ns); + ns.getSequenceGroup().addToGroup(seq); + core.getSelectedDb().getSystemNamespaceGroup().addToGroup((SystemNamespace) ns); + core.getConnection(); + core.getSearchInfo().setTableSelected(false); + core.getSearchInfo().setFunProcSelected(false); + core.getSearchInfo().setViewsSelected(false); + core.getSearchInfo().setSearchText("%"); + core.getSearchInfo().setNameMatch(3); + core.getSearchInfo().setMatchCase(false); + core.getSearchInfo().setSequenceSelected(true); + + core.search(); + + assertEquals(0, core.getSearchNamespace().getTables().getSize()); +// assertEquals(0, core.getSearchNamespace().getPartitionTablesGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getForeignTablesGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getViewGroup().getSize()); + assertEquals(0, core.getSearchNamespace().getFunctions().getSize()); + assertEquals(1, core.getSearchNamespace().getSequenceGroup().getSize()); + } + catch (DatabaseOperationException | DatabaseCriticalException e) + { + fail("not expected"); + } + finally{ + core.clearData(); + core.cleanUpSearch(); + } + + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/SequenceTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/SequenceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..02e5c5304255e7f3f96b54e18c52805915e3a84f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/properties/SequenceTest.java @@ -0,0 +1,791 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.test.presentation.properties; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.contentassist.ContentAssistProcesserData; +import org.opengauss.mppdbide.bl.contentassist.ContentAssistUtilIf; +import org.opengauss.mppdbide.bl.contentassist.ContentAssistUtilOLAP; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.SequenceMetadata; +import org.opengauss.mppdbide.bl.serverdatacache.SequenceMetadataUtil; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.groups.SequenceObjectGroup; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.mock.presentation.MockViewUtils; +import org.opengauss.mppdbide.presentation.SequenceDataCore; +import org.opengauss.mppdbide.presentation.objectbrowser.ObjectBrowserObjectRefreshPresentation; +import org.opengauss.mppdbide.test.presentation.table.MockPresentationBLPreferenceImpl; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; +import com.mockrunner.mock.jdbc.MockResultSet; + +import static org.junit.Assert.*; + +/** + * Title: SequenceTest + * + * @since 3.0.0 + */ +public class SequenceTest extends BasicJDBCTestCaseAdapter +{ + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + JobCancelStatus status = null; + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#setUp() + */ + @Before + public void setUp() throws Exception + { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + connection = new MockConnection(); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + status=new JobCancelStatus(); + preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + CommonLLTUtils.fetchViewQuery(preparedstatementHandler); + CommonLLTUtils.refreshTableinnamespace(preparedstatementHandler); + CommonLLTUtils.createViewColunmMetadata(preparedstatementHandler); + CommonLLTUtils.fetchViewColumnInfo(preparedstatementHandler); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + CommonLLTUtils.fetchAllSynonyms(preparedstatementHandler); + CommonLLTUtils.fetchTriggerQuery(preparedstatementHandler); + connProfCache = DBConnProfCache.getInstance(); + + serverInfo.setConectionName("Conn1"); + serverInfo.setServerIp(""); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception + { + super.tearDown(); + + Database database = connProfCache.getDbForProfileId(profileId); + if (null != database) + { + database.getServer().close(); + } + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) + { + connProfCache.removeServer(itr.next().getId()); + itr = connProfCache.getServers().iterator(); + } + + connProfCache.closeAllNodes(); + + } + + @Test + public void test_Sequence_Creation_001_01() + { + + try + { + + profileId = connProfCache.initConnectionProfile(serverInfo, status); + Database database = connProfCache.getDbForProfileId(profileId); + Namespace namespace = database.getNameSpaceById(1); + namespace.refreshSequences(database.getConnectionManager().getObjBrowserConn()); + CommonLLTUtils.createSequence(preparedstatementHandler); + SequenceDataCore sequenceDataCore = new SequenceDataCore(namespace); + sequenceDataCore.getSequenceMetadata().setSequenceName("Seq_01"); + sequenceDataCore.getSequenceMetadata().setMinValue("10"); + sequenceDataCore.getSequenceMetadata().setMaxValue("10000"); + sequenceDataCore.getSequenceMetadata().setIncrementBy("2"); + sequenceDataCore.getSequenceMetadata().setStartValue("10"); + sequenceDataCore.getSequenceMetadata().setCache("1"); + sequenceDataCore.getSequenceMetadata().setCycle(true); + SequenceObjectGroup sequenceObjectGroup = new SequenceObjectGroup( + OBJECTTYPE.SEQUENCE_GROUP, namespace); + sequenceObjectGroup.getDisplayLabel(); + sequenceObjectGroup.getNamespace(); + + sequenceDataCore.createConnection(); + sequenceDataCore.executeCreateSequence(); + assertEquals(namespace.getSequenceGroup().getSortedServerObjectList().size(), 2); + sequenceDataCore.releaseConnection(); + + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + @Test + public void test_Sequence_Creation_001_02() + { + + try + { + + profileId = connProfCache.initConnectionProfile(serverInfo,status); + Database database = connProfCache.getDbForProfileId(profileId); + Namespace namespace = database.getNameSpaceById(1); + namespace.refreshSequences(database.getConnectionManager().getObjBrowserConn()); + CommonLLTUtils.createSequenceWithOwner(preparedstatementHandler); + SequenceDataCore sequenceDataCore = new SequenceDataCore(namespace); + sequenceDataCore.getSequenceMetadata().setSequenceName("Seq_01"); + sequenceDataCore.getSequenceMetadata().setMinValue("10"); + sequenceDataCore.getSequenceMetadata().setMaxValue("10000"); + sequenceDataCore.getSequenceMetadata().setIncrementBy("2"); + sequenceDataCore.getSequenceMetadata().setStartValue("10"); + sequenceDataCore.getSequenceMetadata().setCache("1"); + sequenceDataCore.getSequenceMetadata().setCycle(true); + + sequenceDataCore.createConnection(); + sequenceDataCore.executeCreateSequence(); + assertEquals(namespace.getSequenceGroup() + .getSortedServerObjectList().size(), 2); + + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + @Test + public void test_Sequence_Creation_001_03() + { + + try + { + + profileId = connProfCache.initConnectionProfile(serverInfo,status); + Database database = connProfCache.getDbForProfileId(profileId); + Namespace namespace = database.getNameSpaceById(1); + namespace.refreshSequences(database.getConnectionManager().getObjBrowserConn()); + CommonLLTUtils.createSequenceWithOwner(preparedstatementHandler); + SequenceDataCore sequenceDataCore = new SequenceDataCore(namespace); + sequenceDataCore.getSequenceMetadata().setSequenceName("Seq_01"); + sequenceDataCore.getSequenceMetadata().setMinValue("10"); + sequenceDataCore.getSequenceMetadata().setMaxValue("10000"); + sequenceDataCore.getSequenceMetadata().setIncrementBy("2"); + sequenceDataCore.getSequenceMetadata().setStartValue("10"); + sequenceDataCore.getSequenceMetadata().setCache("1"); + sequenceDataCore.getSequenceMetadata().setCycle(true); + sequenceDataCore.getSequenceMetadata().setSchemaName("pg_catalog"); + sequenceDataCore.getSequenceMetadata().setTableName("table1"); + sequenceDataCore.getSequenceMetadata().setColumnName("col1"); + sequenceDataCore.createConnection(); + sequenceDataCore.executeCreateSequence(); + assertEquals(namespace.getSequenceGroup() + .getSortedServerObjectList().size(), 2); + + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + @Test + public void test_Listsequence_001() + { + try + { + profileId = connProfCache.initConnectionProfile(serverInfo,status); + Database database = connProfCache.getDbForProfileId(profileId); + Namespace namespace = database.getNameSpaceById(1); + namespace.refreshSequences(database.getConnectionManager().getObjBrowserConn()); + ArrayList views = namespace.getSequenceGroup() + .getSortedServerObjectList(); + System.out.println(views.size() ); + assertTrue(views.size() == 2); + + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_Listsequence_002() + { + try + { + profileId = connProfCache.initConnectionProfile(serverInfo,status); + Database database = connProfCache.getDbForProfileId(profileId); + Namespace namespace = database.getNameSpaceById(1); + namespace.refreshSequences(database.getConnectionManager().getObjBrowserConn()); + ArrayList views = namespace.getSequenceGroup() + .getSortedServerObjectList(); + + + SequenceMetadata vmd = views.get(0); + assertTrue(vmd.getOid() == 1); + assertTrue(vmd.getName().equals("sequence1")); + assertTrue(vmd.getNamespace().getName().equals("pg_catalog")); + + vmd = views.get(1); + assertTrue(vmd.getOid() == 2); + assertTrue(vmd.getName().equals("sequence2")); + assertTrue(vmd.getNamespace().getName().equals("pg_catalog")); + + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + + @Test + public void test_sequenceCreationLazyLoad_001_06() + { + try + { + profileId = connProfCache.initConnectionProfile(serverInfo,status); + Database database = connProfCache.getDbForProfileId(profileId); + Namespace namespace = database.getNameSpaceById(1); + namespace.refreshSequences(database.getConnectionManager().getObjBrowserConn()); + SortedMap seq = namespace.getSequenceGroup() + .getMatching("sequence1"); + SequenceMetadata meta = seq.get("sequence1 - pg_catalog - Sequence"); + assertNotNull(meta); + } + catch (Exception e) + { + fail(e.getMessage()); + } + } + + + @Test + public void test_sequenceDropSucces_001_08() + { + try + { + CommonLLTUtils.createTableRS(preparedstatementHandler); + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getConstaraintForTableRSEx(preparedstatementHandler); + CommonLLTUtils.getIndexcCOnstaByNamespace(preparedstatementHandler); + CommonLLTUtils.Dropsequence(preparedstatementHandler); + CommonLLTUtils.fetchViewQuery(preparedstatementHandler); + CommonLLTUtils.refreshTableinnamespace(preparedstatementHandler); + profileId = connProfCache.initConnectionProfile(serverInfo,status); + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().setServerCompatibleToNodeGroup(true); + + Namespace nm=database.getNameSpaceById(1); + nm.getAllObjects(database.getConnectionManager().getObjBrowserConn(),status); + + + ArrayList views = nm.getSequenceGroup() + .getSortedServerObjectList(); + SequenceMetadata vmd = views.get(0); + assertEquals(views.size(), 2); + vmd.dropSequence(database.getConnectionManager().getObjBrowserConn(), false); + views = nm.getSequenceGroup() + .getSortedServerObjectList(); + assertEquals(views.size(), 1); + + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + @Test + public void test_ViewCreation_001_09() + { + + try + { + CommonLLTUtils.createTableRS(preparedstatementHandler); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getConstaraintForTableRSEx(preparedstatementHandler); + CommonLLTUtils.getIndexcCOnstaByNamespace(preparedstatementHandler); + CommonLLTUtils.fetchViewQuery(preparedstatementHandler); + CommonLLTUtils.createViewColunmMetadata(preparedstatementHandler); + CommonLLTUtils.refreshTableinnamespace(preparedstatementHandler); + + MockViewUtils.createNamespace(preparedstatementHandler, 10, + "newSchema"); + profileId = connProfCache.initConnectionProfile(serverInfo,status); + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().setServerCompatibleToNodeGroup(true); + + Namespace nm = database.getNameSpaceById(1); + nm.getAllObjects(database.getConnectionManager().getObjBrowserConn(),status); + + SortedMap views = nm.getViewGroup() + .getMatching("myview"); + for (Entry entry : views.entrySet()) + { + System.out.println("Key = " + entry.getKey() + ", Value = " + + entry.getValue()); + } + ViewMetaData viewMeta = views.get("myview - pg_catalog - View"); + assertNotNull(viewMeta); + viewMeta.dropView( database.getConnectionManager().getFreeConnection(), false); + views = nm.getViewGroup().getMatching("mytestview2"); + assertEquals(views.size(), 1); + + SequenceMetadata seq = new SequenceMetadata(1, "s1", nm); + nm.getSequenceGroup().addToGroup(seq); + + String qry = "select oid,relnamespace,relowner,relname from pg_class where relkind='S' and oid=1 and has_sequence_privilege(oid, 'USAGE');"; + MockResultSet refreshtablemetadatainnamspace = preparedstatementHandler.createResultSet(); + refreshtablemetadatainnamspace.addColumn("oid"); + refreshtablemetadatainnamspace.addColumn("relnamespace"); + refreshtablemetadatainnamspace.addColumn("relowner"); + refreshtablemetadatainnamspace.addColumn("relname"); + refreshtablemetadatainnamspace.addRow(new Object[] {}); + preparedstatementHandler.prepareResultSet(qry, refreshtablemetadatainnamspace); + + try { + SequenceMetadataUtil.refresh(1, database, seq); + } catch (DatabaseOperationException exe) { + System.out.println("Expected Result"); + } + + seq = new SequenceMetadata(1, "s1", nm); + nm.getSequenceGroup().addToGroup(seq); + + refreshtablemetadatainnamspace.addRow(new Object[] {1, 1, "newSchema", "TestSeq"}); + preparedstatementHandler.prepareResultSet(qry, refreshtablemetadatainnamspace); + + SequenceMetadataUtil.refresh(1, database, seq); + + + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + + @Test + public void test_createViewRename_Failure_001() + { + try + { + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getConstaraintForTableRSEx(preparedstatementHandler); + CommonLLTUtils.getIndexcCOnstaByNamespace(preparedstatementHandler); + + MockViewUtils.createNamespace(preparedstatementHandler, 10, + "newSchema"); + MockViewUtils.renameView(preparedstatementHandler); + MockViewUtils.refreshNameSpace(preparedstatementHandler); + profileId = connProfCache.initConnectionProfile(serverInfo,status); + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().setServerCompatibleToNodeGroup(true); + + Namespace nm=database.getNameSpaceById(1); + nm.getAllObjects(database.getConnectionManager().getObjBrowserConn(),status); + + + DBConnection conn = database.getConnectionManager().getFreeConnection(); + + ArrayList views = nm.getViewGroup() + .getSortedServerObjectList(); + + assertTrue(views.size() == 2); + SQLException sqlException = new SQLException("57P sql expection", + "57P sql expection"); + statementHandler + .prepareThrowsSQLException( + "ALTER VIEW \"newSchema\".mytestview1 RENAME TO mytestview11", + sqlException); + views.get(0).rename("mytestview11", conn); + + SortedMap view1 = nm + .findMatchingHyperlink("mytestview11"); + assertNotNull(view1); + + } + catch (DatabaseCriticalException e) + { + System.out.println("As expected"); + } + catch (DatabaseOperationException e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_createViewRename_Failure_002() + { + try + { + CommonLLTUtils.createTableRS(preparedstatementHandler); + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getConstaraintForTableRSEx(preparedstatementHandler); + CommonLLTUtils.getIndexcCOnstaByNamespace(preparedstatementHandler); + + MockViewUtils.createNamespace(preparedstatementHandler, 10, + "newSchema"); + MockViewUtils.createViewMetadata(preparedstatementHandler, 10, 2); + MockViewUtils.createViewColunmMetadata(preparedstatementHandler, 1, + 10); + MockViewUtils.renameView(preparedstatementHandler); + MockViewUtils.refreshNameSpace(preparedstatementHandler); + profileId = connProfCache.initConnectionProfile(serverInfo,status); + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().setServerCompatibleToNodeGroup(true); + + Namespace namespace = database.getNameSpaceById(10); + Namespace nm=database.getNameSpaceById(1); + nm.getAllObjects(database.getConnectionManager().getObjBrowserConn(),status); + + + DBConnection conn = database.getConnectionManager().getFreeConnection(); + + ArrayList views = nm.getViewGroup() + .getSortedServerObjectList(); + + assertTrue(views.size() == 2); + SQLException sqlException = new SQLException("57P sql expection", + "57P sql expection"); + statementHandler + .prepareThrowsSQLException("ALTER VIEW \"newSchema\".mytestview1 RENAME TO mytestview11"); + views.get(0).rename("mytestview11", conn); + ObjectBrowserObjectRefreshPresentation.refreshSeverObject(views.get(0)); + SortedMap view1 = nm + .findMatchingHyperlink("mytestview11"); + assertNotNull(view1); + + } + catch (DatabaseCriticalException e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + catch (DatabaseOperationException e) + { + System.out.println("As expected"); + + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_createViewDrop_Failure_001() + { + try + { + CommonLLTUtils.createTableRS(preparedstatementHandler); + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getConstaraintForTableRSEx(preparedstatementHandler); + CommonLLTUtils.getIndexcCOnstaByNamespace(preparedstatementHandler); + + MockViewUtils.createNamespace(preparedstatementHandler, 10, + "newSchema"); + MockViewUtils.createViewMetadata(preparedstatementHandler, 10, 2); + MockViewUtils.createViewColunmMetadata(preparedstatementHandler, 1, + 10); + MockViewUtils.DropView(preparedstatementHandler, "mytestview1"); + profileId = connProfCache.initConnectionProfile(serverInfo,status); + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().setServerCompatibleToNodeGroup(true); + + Namespace namespace = database.getNameSpaceById(10); + Namespace nm=database.getNameSpaceById(1); + nm.getAllObjects(database.getConnectionManager().getObjBrowserConn(),status); + + + ArrayList views = nm.getViewGroup() + .getSortedServerObjectList(); + ViewMetaData vmd = views.get(0); + assertEquals(views.size(), 2); + + SQLException sqlException = new SQLException("57P sql expection", + "57P sql expection"); + statementHandler.prepareThrowsSQLException( + "DROP VIEW \"newSchema\".mytestview1", sqlException); + vmd.dropView( database.getConnectionManager().getFreeConnection(), false); + + } + catch (DatabaseCriticalException e) + { + System.out.println("As expected"); + } + catch (DatabaseOperationException e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + @Test + public void test_createViewdrop_Failure_002() + { + try + { + CommonLLTUtils.createTableRS(preparedstatementHandler); + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getConstaraintForTableRSEx(preparedstatementHandler); + CommonLLTUtils.getIndexcCOnstaByNamespace(preparedstatementHandler); + + CommonLLTUtils.Dropsequence(preparedstatementHandler); + profileId = connProfCache.initConnectionProfile(serverInfo,status); + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().setServerCompatibleToNodeGroup(true); + + Namespace namespace = database.getNameSpaceById(1); + Namespace nm=database.getNameSpaceById(1); + nm.getAllObjects(database.getConnectionManager().getObjBrowserConn(),status); + + + ArrayList views = namespace.getSequenceGroup() + .getSortedServerObjectList(); + SequenceMetadata vmd = views.get(0); + assertEquals(views.size(), 2); + + statementHandler + .prepareThrowsSQLException("DROP SEQUENCE \"newSchema\".sequence1"); + vmd.dropSequence(database.getConnectionManager().getFreeConnection(), false); + } + catch (DatabaseCriticalException e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + catch (DatabaseOperationException e) + { + System.out.println("Expected to throw exception here"); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_sequencefindMatchingPrefix_success() + { + + try + { + profileId = connProfCache.initConnectionProfile(serverInfo,status); + Database database = connProfCache.getDbForProfileId(profileId); + Namespace nmd = database.getNameSpaceById(1); + nmd.refreshSequences(database.getConnectionManager().getObjBrowserConn()); + ArrayList views = nmd.getSequenceGroup() + .getSortedServerObjectList(); + for (SequenceMetadata v : views) + { + System.out.println(v.getName()); + } + views = nmd.getSequenceGroup().getSortedServerObjectList(); + for (SequenceMetadata v : views) + { + System.out.println(v.getName()); + } + + SortedMap retObj = new TreeMap(); + ContentAssistUtilIf conUtil = new ContentAssistUtilOLAP(database); + retObj.putAll(conUtil.findMatchingSequenceObject("sequence1")); + System.out.println(conUtil.findMatchingViewsObject("sequence1")); + assertEquals(retObj.size(),1); + + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_sequenceRefreshFailure_001_08() + { + try + { + CommonLLTUtils.createTableRS(preparedstatementHandler); + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getConstaraintForTableRSEx(preparedstatementHandler); + CommonLLTUtils.getIndexcCOnstaByNamespace(preparedstatementHandler); + CommonLLTUtils.Dropsequence(preparedstatementHandler); + CommonLLTUtils.fetchViewQuery(preparedstatementHandler); + CommonLLTUtils.refreshTableinnamespace(preparedstatementHandler); + profileId = connProfCache.initConnectionProfile(serverInfo,status); + Database database = connProfCache.getDbForProfileId(profileId); + + Namespace nm=database.getNameSpaceById(1); + nm.getAllObjects(database.getConnectionManager().getObjBrowserConn(),status); + + + ArrayList views = nm.getSequenceGroup() + .getSortedServerObjectList(); + SequenceMetadata vmd = views.get(0); + SequenceMetadataUtil.refresh(vmd.getOid(), database,vmd); + + } + catch (Exception e) + { + System.out.println("As expected"); + } + } + + @Test + public void test_autosuggest_findstring_1() { + try { + CommonLLTUtils.createTableRS(preparedstatementHandler); + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getConstaraintForTableRSEx(preparedstatementHandler); + CommonLLTUtils.getIndexcCOnstaByNamespace(preparedstatementHandler); + CommonLLTUtils.Dropsequence(preparedstatementHandler); + CommonLLTUtils.fetchViewQuery(preparedstatementHandler); + CommonLLTUtils.refreshTableinnamespace(preparedstatementHandler); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + Database database = connProfCache.getDbForProfileId(profileId); + + ContentAssistUtilOLAP contentAssist = new ContentAssistUtilOLAP(database); + assertEquals(null, contentAssist.findString("", null)); + List li = new ArrayList(); + li.add('t'); + assertEquals("example", contentAssist.findString("content.assistexample", li)); + assertEquals(".", contentAssist.findString("content.", li)); + assertEquals("", contentAssist.findString("content\n", li)); + assertEquals(".\"assist\".example", contentAssist.findString("content.\"assist\".example", li)); + assertEquals(".\"\"", contentAssist.findString("content.assist.\"\"", li)); + } catch (Exception e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + + @Test + public void test_autosuggest_getPrefixHyperLink_1() { + try { + CommonLLTUtils.createTableRS(preparedstatementHandler); + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getConstaraintForTableRSEx(preparedstatementHandler); + CommonLLTUtils.getIndexcCOnstaByNamespace(preparedstatementHandler); + CommonLLTUtils.Dropsequence(preparedstatementHandler); + CommonLLTUtils.fetchViewQuery(preparedstatementHandler); + CommonLLTUtils.refreshTableinnamespace(preparedstatementHandler); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + Database database = connProfCache.getDbForProfileId(profileId); + + ContentAssistUtilOLAP contentAssist = new ContentAssistUtilOLAP(database); + assertEquals("content", contentAssist.getPrefixHyperLink("content.\"assist\".\'ds\'")[0]); + assertEquals("assist", contentAssist.getPrefixHyperLink("content.\"assist\".\'ds\'")[1]); + assertEquals("\"DataStudio\"", contentAssist.getPrefixHyperLink("content.\"assist\".\"\"\"DataStudio\"\"\"")[2]); + } catch (Exception e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/BatchDropDataProviderTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/BatchDropDataProviderTest.java new file mode 100644 index 0000000000000000000000000000000000000000..fc0f460dac842fb7badf058778c8b220674f5de9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/BatchDropDataProviderTest.java @@ -0,0 +1,1195 @@ +package org.opengauss.mppdbide.test.presentation.table; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Types; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.*; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintType; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.IndexMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TypeMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.mock.presentation.ExceptionConnection; +import org.opengauss.mppdbide.presentation.EditTableDataCore; +import org.opengauss.mppdbide.presentation.grid.IDSEditGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.presentation.grid.batchdrop.BatchDropDataProvider; +import org.opengauss.mppdbide.presentation.grid.batchdrop.BatchDropDataRow; +import org.opengauss.mppdbide.presentation.grid.batchdrop.BatchDropStatusEnum; +import org.opengauss.mppdbide.utils.exceptions.DataStudioSecurityException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.FileOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.exceptions.PasswordExpiryException; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.observer.DSEventTable; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; + +public class BatchDropDataProviderTest extends BasicJDBCTestCaseAdapter +{ + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + EditTableDataHelper helper; + IDSEditGridDataProvider dataProvider; + EditTableDataCore coreObject; + + ConstraintMetaData constraintMetaData = null; + ColumnMetaData newTempColumn = null; + + DSEventTable eventTable = null; + JobCancelStatus status =null; + ServerConnectionInfo serverInfo =null; + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#setUp() + */ + @Before + public void setUp() throws Exception + { + super.setUp(); + connection = new MockConnection(); + setupBase(connection); + } + + private void setupBase(MockConnection connectionLocal) throws OutOfMemoryError, Exception { + CommonLLTUtils.runLinuxFilePermissionInstance(); + + MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connectionLocal); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + MockPresentationBLPreferenceImpl.setFileEncoding("UTF-8"); + + preparedstatementHandler = connectionLocal.getPreparedStatementResultSetHandler(); + statementHandler = connectionLocal.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + connProfCache = DBConnProfCache.getInstance(); + status = new JobCancelStatus(); + status.setCancel(false); + + serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + + // serverInfo.setSslPassword("12345"); + // serverInfo.setServerType(DATABASETYPE.GAUSS); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + + init(); + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception + { + super.tearDown(); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().close(); + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) + { + connProfCache.removeServer(itr.next().getId()); + itr = connProfCache.getServers().iterator(); + } + + connProfCache.closeAllNodes(); + } + + private void init() + { + try + { + CommonLLTUtils.createTableRS(preparedstatementHandler); + CommonLLTUtils.getConstaraintForTableRSEx(preparedstatementHandler); + CommonLLTUtils.getIndexForTableRS(preparedstatementHandler); + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData; + + tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + constraintMetaData = new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + constraintMetaData.setTable(tablemetaData); + tablemetaData.addConstraint(constraintMetaData); + + newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + ColumnMetaData newTempColumn1 = new ColumnMetaData(tablemetaData, 1, "Col2", + new TypeMetaData(1, "text", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn1); + + IndexMetaData indexMetaData = new IndexMetaData("Idx1"); + + indexMetaData.setTable(tablemetaData); + indexMetaData.setNamespace(tablemetaData.getNamespace()); + tablemetaData.addIndex(indexMetaData); + CommonLLTUtils.getIndexcCOnstaByNamespace(preparedstatementHandler); + // tablemetaData.execCreate(database.getObjBrowserConn()); + + eventTable = new DSEventTable(); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + @Test + public void test_BatchDataProvider_verifyRowMetadata() + { + try + { + List objectsToDrop = new ArrayList(); + objectsToDrop.add((ServerObject) constraintMetaData); + objectsToDrop.add((ServerObject) newTempColumn); + BatchDropDataProvider batchDropProvider = new BatchDropDataProvider(objectsToDrop); + batchDropProvider.init(); + batchDropProvider.setEventTable(eventTable); + + List rows = batchDropProvider.getAllFetchedRows(); + List rows1 = batchDropProvider.getNextBatch(); + + if (rows.size() != rows1.size()) + { + fail("Record Batch Match Failed"); + return; + } + + if (batchDropProvider.getRecordCount() != 2) + { + fail("Record Count Match Failed"); + return; + } + + assertEquals(batchDropProvider.getTable(), null); + assertEquals(batchDropProvider.isEndOfRecords(), true); + assertEquals(false, batchDropProvider.getResultTabDirtyFlag()); + batchDropProvider.setResultTabDirtyFlag(true); + batchDropProvider.preDestroy(); + batchDropProvider.close(); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_BatchDataProvider_verifyRowData() + { + try + { + List objectsToDrop = new ArrayList(); + objectsToDrop.add((ServerObject) constraintMetaData); + objectsToDrop.add((ServerObject) newTempColumn); + BatchDropDataProvider batchDropProvider = new BatchDropDataProvider(objectsToDrop); + batchDropProvider.init(); + batchDropProvider.setEventTable(eventTable); + + List rows = batchDropProvider.getAllFetchedRows(); + + if (null != batchDropProvider.getColumnGroupProvider()) + { + fail("Group provider should not be set"); + return; + } + + IDSGridColumnProvider columnMD = batchDropProvider.getColumnDataProvider(); + int columnCnt = columnMD.getColumnCount(); + IDSGridDataRow row = rows.get(0); + + Object obj[] = row.getValues(); + if (obj.length > 0) + { + fail("Record Data Values set wrong"); + return; + } + + for (int j = 0; j < columnCnt; j++) + { + Object val = row.getValue(j); + if (j == 3 && !(val instanceof BatchDropStatusEnum)) + { + fail("Value is not correct"); + return; + } + else if (j != 3 && !(val instanceof String)) + { + fail("Value is not correct"); + return; + } + + String str = val.toString(); + if (j == 0 && !str.equals(constraintMetaData.getObjectTypeName())) + { + fail("Value is not correct"); + return; + } + else if (j == 1 && !str.equals(constraintMetaData.getObjectFullName())) + { + fail("Value is not correct"); + return; + } + else if (j == 2 && !str.equals(constraintMetaData.getDropQuery(false))) + { + fail("Value is not correct"); + return; + } + else if (j == 3 && !str.equals("To start")) + { + fail("Value is not correct"); + return; + } + else if (j == 4 && !str.equals("")) + { + fail("Value is not correct"); + return; + } + } + + if (!((BatchDropDataRow) row).getServerObject().equals(constraintMetaData)) + { + fail("Values Object is not correct"); + return; + } + + if (((BatchDropDataRow) row).isDropped()) + { + fail("Values Object is not correct"); + return; + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_BatchDataProvider_verifyRowCloneValue() + { + try + { + List objectsToDrop = new ArrayList(); + objectsToDrop.add((ServerObject) constraintMetaData); + objectsToDrop.add((ServerObject) newTempColumn); + BatchDropDataProvider batchDropProvider = new BatchDropDataProvider(objectsToDrop); + batchDropProvider.init(); + batchDropProvider.setEventTable(eventTable); + + List rows = batchDropProvider.getAllFetchedRows(); + + if (null != batchDropProvider.getColumnGroupProvider()) + { + fail("Group provider should not be set"); + return; + } + + IDSGridColumnProvider columnMD = batchDropProvider.getColumnDataProvider(); + int columnCnt = columnMD.getColumnCount(); + IDSGridDataRow row = rows.get(0); + + Object obj[] = row.getClonedValues(); + if (obj == null) + { + fail("Record Data Values set wrong"); + return; + } + + for (int j = 0; j < columnCnt; j++) + { + Object val = obj[j]; + if (j == 3 && !(val instanceof BatchDropStatusEnum)) + { + fail("Value is not correct"); + return; + } + else if (j != 3 && !(val instanceof String)) + { + fail("Value is not correct"); + return; + } + + String str = (String) val.toString(); + if (j == 0 && !str.equals(constraintMetaData.getObjectTypeName())) + { + fail("Value is not correct"); + return; + } + else if (j == 1 && !str.equals(constraintMetaData.getObjectFullName())) + { + fail("Value is not correct"); + return; + } + else if (j == 2 && !str.equals(constraintMetaData.getDropQuery(false))) + { + fail("Value is not correct"); + return; + } + else if (j == 3 && !str.equals("To start")) + { + fail("Value is not correct"); + return; + } + else if (j == 4 && !str.equals("")) + { + fail("Value is not correct"); + return; + } + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_BatchDataProvider_verifyColumnProvider() + { + try + { + List objectsToDrop = new ArrayList(); + objectsToDrop.add((ServerObject) constraintMetaData); + objectsToDrop.add((ServerObject) newTempColumn); + BatchDropDataProvider batchDropProvider = new BatchDropDataProvider(objectsToDrop); + batchDropProvider.init(); + batchDropProvider.setEventTable(eventTable); + + IDSGridColumnProvider columnMD = batchDropProvider.getColumnDataProvider(); + int columnCnt = columnMD.getColumnCount(); + if (columnCnt != 5) + { + fail("Column Count is wrong"); + return; + } + + String columnName[] = columnMD.getColumnNames(); + if (columnName.length != columnCnt) + { + fail("Column Name Array is wrong"); + return; + } + + String validColumnList[] = new String[5]; + validColumnList[0] = "Type"; + validColumnList[1] = "Name"; + validColumnList[2] = "Query"; + validColumnList[3] = "Status"; + validColumnList[4] = "Error Message"; + + for (int i = 0; i < columnCnt; i++) + { + if (!columnName[i].equals(validColumnList[i])) + { + fail("Column Name Value is wrong"); + return; + } + + if (!columnMD.getColumnDesc(i).equals(validColumnList[i])) + { + fail("Column Name Get is wrong"); + return; + } + + if (columnMD.getColumnIndex(validColumnList[i]) != 0) + { + fail("Column Name Filler info wrong"); + return; + } + + if (columnMD.getColumnDatatype(i) != Types.VARCHAR) + { + fail("Column Name Filler info wrong"); + return; + } + + if (!columnMD.getColumnDataTypeName(i).equals("varchar")) + { + fail("Column Name Filler info wrong"); + return; + } + + if (columnMD.getPrecision(i) != 0) + { + fail("Column Name Filler info wrong"); + return; + } + + if (columnMD.getScale(i) != 0) + { + fail("Column Name Filler info wrong"); + return; + } + + if (columnMD.getMaxLength(i) != 0) + { + fail("Column Name Filler info wrong"); + return; + } + + if (columnMD.getComparator(i) == null) + { + fail("Column Name Filler info wrong"); + return; + } + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_BatchDataProvider_verifyCascade() + { + try + { + List objectsToDrop = new ArrayList(); + objectsToDrop.add((ServerObject) constraintMetaData); + objectsToDrop.add((ServerObject) newTempColumn); + BatchDropDataProvider batchDropProvider = new BatchDropDataProvider(objectsToDrop); + batchDropProvider.init(); + batchDropProvider.setEventTable(eventTable); + + batchDropProvider.setCascade(true); + batchDropProvider.setAtomic(true); + + List rows = batchDropProvider.getAllFetchedRows(); + + IDSGridColumnProvider columnMD = batchDropProvider.getColumnDataProvider(); + int columnCnt = columnMD.getColumnCount(); + IDSGridDataRow row = rows.get(0); + + for (int j = 0; j < columnCnt; j++) + { + Object val = row.getValue(j); + if (j == 3 && !(val instanceof BatchDropStatusEnum)) + { + fail("Value is not correct"); + return; + } + else if (j != 3 && !(val instanceof String)) + { + fail("Value is not correct"); + return; + } + + String str = val.toString(); + if (j == 0 && !str.equals(constraintMetaData.getObjectTypeName())) + { + fail("Value is not correct"); + return; + } + else if (j == 1 && !str.equals(constraintMetaData.getObjectFullName())) + { + fail("Value is not correct"); + return; + } + else if (j == 2 && !str.equals(constraintMetaData.getDropQuery(true))) + { + fail("Value is not correct"); + return; + } + else if (j == 3 && !str.equals("To start")) + { + fail("Value is not correct"); + return; + } + else if (j == 4 && !str.equals("")) + { + fail("Value is not correct"); + return; + } + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_BatchDataProvider_verifyRowStatusChange() + { + try + { + List objectsToDrop = new ArrayList(); + objectsToDrop.add((ServerObject) constraintMetaData); + objectsToDrop.add((ServerObject) newTempColumn); + BatchDropDataProvider batchDropProvider = new BatchDropDataProvider(objectsToDrop); + batchDropProvider.init(); + batchDropProvider.setEventTable(eventTable); + + batchDropProvider.setCascade(true); + batchDropProvider.setAtomic(true); + + List rows = batchDropProvider.getAllFetchedRows(); + + BatchDropDataRow row = (BatchDropDataRow) rows.get(0); + + row.updateStatus(BatchDropStatusEnum.IN_PROGRESS, false); + + Object val = row.getValue(3).toString(); + String str = val.toString(); + assertEquals("In progress", str); + + row.updateStatus(BatchDropStatusEnum.ERROR, false); + row.updateError("Error Occured"); + + val = row.getValue(3).toString(); + str = val.toString(); + assertEquals("Error", str); + + val = row.getValue(4); + str = (String)val; + assertEquals("Error Occured", str); + + row.updateStatus(BatchDropStatusEnum.COMPLETED, true); + row.updateError(""); + + val = row.getValue(3).toString(); + str = val.toString(); + assertEquals("Completed", str); + + val = row.getValue(4); + str = (String) val; + assertEquals("", str); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_BatchDataProvider_atomicExecute_Success() + { + try + { + List objectsToDrop = new ArrayList(); + objectsToDrop.add((ServerObject) constraintMetaData); + objectsToDrop.add((ServerObject) newTempColumn); + BatchDropDataProvider batchDropProvider = new BatchDropDataProvider(objectsToDrop); + batchDropProvider.init(); + batchDropProvider.setEventTable(eventTable); + + batchDropProvider.setAtomic(true); + + Database database = connProfCache.getDbForProfileId(profileId); + DBConnection conn = database.getConnectionManager().getFreeConnection(); + batchDropProvider.startExecute(conn); + + List rows = batchDropProvider.getAllFetchedRows(); + + BatchDropDataRow row = (BatchDropDataRow) rows.get(0); + + Object val = row.getValue(3).toString(); + String str = (String) val; + assertEquals("Completed", str); + assertEquals(true, row.isDropped()); + + row = (BatchDropDataRow) rows.get(1); + + val = row.getValue(3).toString(); + str = (String) val; + assertEquals("Completed", str); + assertEquals(true, row.isDropped()); + batchDropProvider.setPauseStopOperation(batchDropProvider.isPauseStopOperation()); + batchDropProvider.setEditSupported(batchDropProvider.isEditSupported()); + batchDropProvider.setFuncProcExport(batchDropProvider.isFuncProcExport()); + batchDropProvider.setCancelOperation(batchDropProvider.isCancelOperation()); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_BatchDataProvider_atomicExecute_Failure() + { + try + { + tearDown(); + ExceptionConnection exceptionConnection = new ExceptionConnection(); + exceptionConnection.setThrowExceptioForPrepareStmt(true); + getJDBCMockObjectFactory().getMockDriver().setupConnection(exceptionConnection); + setupBase(exceptionConnection); + List objectsToDrop = new ArrayList(); + objectsToDrop.add((ServerObject) constraintMetaData); + objectsToDrop.add((ServerObject) newTempColumn); + BatchDropDataProvider batchDropProvider = new BatchDropDataProvider(objectsToDrop); + batchDropProvider.init(); + batchDropProvider.setEventTable(eventTable); + + batchDropProvider.setAtomic(true); + int totalcnt = batchDropProvider.getTotalObjectCnt(); + assertEquals(totalcnt, batchDropProvider.getTotalObjectCnt()); + Database database = connProfCache.getDbForProfileId(profileId); + DBConnection conn = database.getConnectionManager().getFreeConnection(); + + exceptionConnection.setNeedExceptioStatement(true); + exceptionConnection.setNeedExecuteException(true); + exceptionConnection.setSqlException(new SQLException("Error: Failed!!!")); + + try + { + batchDropProvider.startExecute(conn); + fail("Execute should fail"); + } + catch (DatabaseOperationException e1) + { + + } + + List rows = batchDropProvider.getAllFetchedRows(); + + BatchDropDataRow row = (BatchDropDataRow) rows.get(0); + + Object val = row.getValue(3).toString(); + String str = (String) val; + assertEquals("Error", str); + assertEquals(false, row.isDropped()); + + row = (BatchDropDataRow) rows.get(1); + + val = row.getValue(3).toString(); + str = (String) val; + assertEquals("To start", str); + assertEquals(false, row.isDropped()); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_BatchDataProvider_execute_Failure() + { + try + { + tearDown(); + ExceptionConnection exceptionConnection = new ExceptionConnection(); + exceptionConnection.setThrowExceptioForPrepareStmt(true); + getJDBCMockObjectFactory().getMockDriver().setupConnection(exceptionConnection); + setupBase(exceptionConnection); + List objectsToDrop = new ArrayList(); + objectsToDrop.add((ServerObject) constraintMetaData); + objectsToDrop.add((ServerObject) newTempColumn); + BatchDropDataProvider batchDropProvider = new BatchDropDataProvider(objectsToDrop); + batchDropProvider.init(); + batchDropProvider.setEventTable(eventTable); + + batchDropProvider.setAtomic(false); + + Database database = connProfCache.getDbForProfileId(profileId); + DBConnection conn = database.getConnectionManager().getFreeConnection(); + + exceptionConnection.setNeedExceptioStatement(true); + exceptionConnection.setNeedExecuteException(true); + exceptionConnection.setSqlException(new SQLException("Error: Failed!!!")); + try + { + batchDropProvider.startExecute(conn); + } + catch (DatabaseOperationException e1) + { + fail("Execute should fail"); + } + + List rows = batchDropProvider.getAllFetchedRows(); + + BatchDropDataRow row = (BatchDropDataRow) rows.get(0); + + Object val = row.getValue(3).toString(); + String str = (String) val; + assertEquals("Error", str); + assertEquals(false, row.isDropped()); + + row = (BatchDropDataRow) rows.get(1); + + val = row.getValue(3).toString(); + str = (String) val; + assertEquals("Error", str); + assertEquals(false, row.isDropped()); + + // Try Rollback to return the states after setting the Atomic flag + batchDropProvider.setAtomic(true); + batchDropProvider.rollbackAndNotifyUIMgr(conn); + val = row.getValue(3).toString(); + str = (String) val; + assertEquals("To start", str); + assertEquals(false, row.isDropped()); + + row = (BatchDropDataRow) rows.get(1); + + val = row.getValue(3).toString(); + str = (String) val; + assertEquals("To start", str); + assertEquals(false, row.isDropped()); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + /* @Test + public void test_BatchDataProvider_execute_Failure_DoesNotExist() + { + try + { + ExceptionConnection exceptionConnection = new ExceptionConnection(); + exceptionConnection.setThrowExceptioForPrepareStmt(true); + getJDBCMockObjectFactory().getMockDriver().setupConnection(exceptionConnection); + + List objectsToDrop = new ArrayList(); + objectsToDrop.add((ServerObject) constraintMetaData); + objectsToDrop.add((ServerObject) newTempColumn); + BatchDropDataProvider batchDropProvider = new BatchDropDataProvider(objectsToDrop); + batchDropProvider.init(); + batchDropProvider.setEventTable(eventTable); + + batchDropProvider.setAtomic(false); + + Database database = connProfCache.getDbForProfileId(profileId); + DBConnection conn = database.getFreeConnection(); + + exceptionConnection.setNeedExceptioStatement(true); + exceptionConnection.setNeedExecuteException(true); + exceptionConnection.setExceptionFromUser(true); + + SQLException exp = new SQLException("Object does not exist", "42704"); + exceptionConnection.setSqlException(exp); + try + { + batchDropProvider.startExecute(conn); + } + catch (DatabaseOperationException e1) + { + fail("Execute should fail"); + } + + List rows = batchDropProvider.getAllFetchedRows(); + + BatchDropDataRow row = (BatchDropDataRow) rows.get(0); + + Object val = row.getValue(3).toString(); + String str = (String) val; + assertEquals("Completed", str); + assertEquals(true, row.isDropped()); + + row = (BatchDropDataRow) rows.get(1); + + val = row.getValue(3).toString(); + str = (String) val; + assertEquals("Completed", str); + assertEquals(true, row.isDropped()); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + }*/ + + @Test + public void test_BatchDataProvider_execute_CommitSetFailure() + { + try + { + tearDown(); + ExceptionConnection exceptionConnection = new ExceptionConnection(); + exceptionConnection.setThrowExceptioForPrepareStmt(true); + getJDBCMockObjectFactory().getMockDriver().setupConnection(exceptionConnection); + setupBase(exceptionConnection); + + List objectsToDrop = new ArrayList(); + objectsToDrop.add((ServerObject) constraintMetaData); + objectsToDrop.add((ServerObject) newTempColumn); + BatchDropDataProvider batchDropProvider = new BatchDropDataProvider(objectsToDrop); + batchDropProvider.init(); + batchDropProvider.setEventTable(eventTable); + + batchDropProvider.setAtomic(false); + + Database database = connProfCache.getDbForProfileId(profileId); + DBConnection conn = database.getConnectionManager().getFreeConnection(); + + exceptionConnection.setThrowExceptionSetAutoCommitTrue(true); + exceptionConnection.setSqlException(new SQLException("Error: Failed!!!")); + // exceptionConnection.setNeedExceptioStatement(true); + // exceptionConnection.setNeedExecuteException(true); + try + { + batchDropProvider.startExecute(conn); + fail("Execute should fail"); + } + catch (DatabaseOperationException e1) + { + + } + + List rows = batchDropProvider.getAllFetchedRows(); + + BatchDropDataRow row = (BatchDropDataRow) rows.get(0); + + Object val = row.getValue(3).toString(); + String str = (String) val; + assertEquals("To start", str); + assertEquals(false, row.isDropped()); + + val = row.getValue(4); + str = (String) val; + assertEquals("", str); + + row = (BatchDropDataRow) rows.get(1); + + val = row.getValue(3).toString(); + str = (String) val; + assertEquals("To start", str); + assertEquals(false, row.isDropped()); + + val = row.getValue(4); + str = (String) val; + assertEquals("", str); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + /* @Test + public void test_BatchDataProvider_atomicexecute_CommitFailure() + { + try + { + ExceptionConnection exceptionConnection = new ExceptionConnection(); + exceptionConnection.setThrowExceptioForPrepareStmt(true); + getJDBCMockObjectFactory().getMockDriver().setupConnection(exceptionConnection); + + List objectsToDrop = new ArrayList(); + objectsToDrop.add((ServerObject) constraintMetaData); + objectsToDrop.add((ServerObject) newTempColumn); + BatchDropDataProvider batchDropProvider = new BatchDropDataProvider(objectsToDrop); + batchDropProvider.init(); + batchDropProvider.setEventTable(eventTable); + + batchDropProvider.setAtomic(true); + + Database database = connProfCache.getDbForProfileId(profileId); + DBConnection conn = database.getFreeConnection(); + + exceptionConnection.setThrowExceptionCommit(true); + exceptionConnection.setSqlException(new SQLException("Error: Failed!!!")); + // exceptionConnection.setNeedExceptioStatement(true); + // exceptionConnection.setNeedExecuteException(true); + try + { + batchDropProvider.startExecute(conn); + fail("Execute should fail"); + } + catch (DatabaseOperationException e1) + { + + } + + List rows = batchDropProvider.getAllFetchedRows(); + + BatchDropDataRow row = (BatchDropDataRow) rows.get(0); + + Object val = row.getValue(3).toString(); + String str = (String) val; + assertEquals("Completed", str); + assertEquals(true, row.isDropped()); + + val = row.getValue(4); + str = (String) val; + assertEquals("", str); + + row = (BatchDropDataRow) rows.get(1); + + val = row.getValue(3).toString(); + str = (String) val; + assertEquals("Completed", str); + assertEquals(true, row.isDropped()); + + val = row.getValue(4); + str = (String) val; + assertEquals("", str); + + // Fire Rollback as Commit Failed + batchDropProvider.rollbackAndNotifyUIMgr(conn); + + val = row.getValue(3).toString(); + str = (String) val; + assertEquals("To start", str); + assertEquals(false, row.isDropped()); + + val = row.getValue(4); + str = (String) val; + assertEquals("", str); + + row = (BatchDropDataRow) rows.get(1); + + val = row.getValue(3).toString(); + str = (String) val; + assertEquals("To start", str); + assertEquals(false, row.isDropped()); + + val = row.getValue(4); + str = (String) val; + assertEquals("", str); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } +*/ + /* @Test + public void test_BatchDataProvider_atomicexecute_CommitAndRollbackFailure() + { + try + { + ExceptionConnection exceptionConnection = new ExceptionConnection(); + exceptionConnection.setThrowExceptioForPrepareStmt(true); + getJDBCMockObjectFactory().getMockDriver().setupConnection(exceptionConnection); + + List objectsToDrop = new ArrayList(); + objectsToDrop.add((ServerObject) constraintMetaData); + objectsToDrop.add((ServerObject) newTempColumn); + BatchDropDataProvider batchDropProvider = new BatchDropDataProvider(objectsToDrop); + batchDropProvider.init(); + batchDropProvider.setEventTable(eventTable); + + batchDropProvider.setAtomic(true); + + assertEquals(batchDropProvider.getTotalObjectCnt(), 2); + assertEquals(batchDropProvider.isCancelOperation(), false); + assertEquals(batchDropProvider.isPauseStopOperation(), false); + + Database database = connProfCache.getDbForProfileId(profileId); + DBConnection conn = database.getFreeConnection(); + + exceptionConnection.setThrowExceptionCommit(true); + exceptionConnection.setSqlException(new SQLException("Error: Failed!!!")); + // exceptionConnection.setNeedExceptioStatement(true); + // exceptionConnection.setNeedExecuteException(true); + try + { + batchDropProvider.startExecute(conn); + fail("Execute should fail"); + } + catch (DatabaseOperationException e1) + { + + } + + List rows = batchDropProvider.getAllFetchedRows(); + + BatchDropDataRow row = (BatchDropDataRow) rows.get(0); + + Object val = row.getValue(3).toString(); + String str = (String) val; + assertEquals("Completed", str); + assertEquals(true, row.isDropped()); + + val = row.getValue(4); + str = (String) val; + assertEquals("", str); + + row = (BatchDropDataRow) rows.get(1); + + val = row.getValue(3).toString(); + str = (String) val; + assertEquals("Completed", str); + assertEquals(true, row.isDropped()); + + val = row.getValue(4); + str = (String) val; + assertEquals("", str); + + // Fire Rollback as Commit Failed + exceptionConnection.setThrowExceptionRollback(true); + batchDropProvider.rollbackAndNotifyUIMgr(conn); + + val = row.getValue(3).toString(); + str = (String) val; + assertEquals("To start", str); + assertEquals(false, row.isDropped()); + + val = row.getValue(4); + str = (String) val; + assertEquals("", str); + + row = (BatchDropDataRow) rows.get(1); + + val = row.getValue(3).toString(); + str = (String) val; + assertEquals("To start", str); + assertEquals(false, row.isDropped()); + + val = row.getValue(4); + str = (String) val; + assertEquals("", str); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + }*/ + + /*@Test + public void test_BatchDataProvider_execute_PauseCancel() + { + try + { + ExceptionConnection exceptionConnection = new ExceptionConnection(); + exceptionConnection.setThrowExceptioForPrepareStmt(true); + getJDBCMockObjectFactory().getMockDriver().setupConnection(exceptionConnection); + + List objectsToDrop = new ArrayList(); + objectsToDrop.add((ServerObject) constraintMetaData); + objectsToDrop.add((ServerObject) newTempColumn); + BatchDropDataProvider batchDropProvider = new BatchDropDataProvider(objectsToDrop); + batchDropProvider.init(); + batchDropProvider.setEventTable(eventTable); + batchDropProvider.setCancelOperation(true); + batchDropProvider.setPauseStopOperation(true); + + batchDropProvider.setAtomic(false); + + assertEquals(batchDropProvider.getTotalObjectCnt(), 2); + assertEquals(batchDropProvider.isCancelOperation(), true); + assertEquals(batchDropProvider.isPauseStopOperation(), true); + + Database database = connProfCache.getDbForProfileId(profileId); + DBConnection conn = database.getFreeConnection(); + + try + { + batchDropProvider.startExecute(conn); + } + catch (DatabaseOperationException e1) + { + fail("Execute should fail"); + } + + List rows = batchDropProvider.getAllFetchedRows(); + + BatchDropDataRow row = (BatchDropDataRow) rows.get(0); + + Object val = row.getValue(3).toString(); + String str = (String) val; + assertEquals("Completed", str); + assertEquals(true, row.isDropped()); + + val = row.getValue(4); + str = (String) val; + assertEquals("", str); + + row = (BatchDropDataRow) rows.get(1); + + val = row.getValue(3).toString(); + str = (String) val; + assertEquals("To start", str); + assertEquals(false, row.isDropped()); + + val = row.getValue(4); + str = (String) val; + assertEquals("", str); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + }*/ +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ConvertToObjectPropertyDataTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ConvertToObjectPropertyDataTest.java new file mode 100644 index 0000000000000000000000000000000000000000..32576b1b135d50a44d83d24c18e180f4550cbde6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ConvertToObjectPropertyDataTest.java @@ -0,0 +1,98 @@ +package org.opengauss.mppdbide.test.presentation.table; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.presentation.objectproperties.ConvertToObjectPropertyData; +import org.opengauss.mppdbide.presentation.objectproperties.DNIntraNodeDetailsColumn; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import static org.junit.Assert.*; +public class ConvertToObjectPropertyDataTest extends BasicJDBCTestCaseAdapter +{ + @Before + public void setUp() throws Exception + { + CommonLLTUtils.runLinuxFilePermissionInstance(); + } + @After + public void tearDown() throws Exception + { + + } + @Test + public void test_ConvertToObjectPropertyData_getObjectPropertyDataGeneric(){ + List> properties = new ArrayList>(); + List list = new ArrayList(); + List strList = new ArrayList(); + strList.add(0, "class"); + strList.add(1, "class1"); + Object[] element = {"name", "type", "column", "table"}; + list.add(0, element); + properties.add(0, list); + properties.add(1, list); + try + { + ConvertToObjectPropertyData.getObjectPropertyDataGeneric(strList, properties); + assertNotNull(ConvertToObjectPropertyData.getObjectPropertyDataGeneric(strList, properties)); + } + catch (DatabaseOperationException e) + { + fail("not expected to come here"); + } + catch (DatabaseCriticalException e) + { + fail("not expected to come here"); + } + } + + @Test + public void test_ConvertToObjectPropertyData_getObjectPropertyDataGenericGroupedColumn(){ + + List strList = new ArrayList(); + strList.add(0, "class"); + strList.add(1, "class1"); + + List list = new ArrayList(); + list.add(0, "name"); + list.add(1, "type"); + + Map> data = new HashMap>(); + data.put("name", list); + data.put("type", list); + + List colgrp = new ArrayList(); + DNIntraNodeDetailsColumn element = new DNIntraNodeDetailsColumn(); + element.setColCount(1); + element.setGroupColumnName("Columns"); + List colList = new ArrayList(); + colList.add(0, "name"); + colList.add(1, "types"); + colgrp.add(0, element); + colgrp.add(1, element); + element.setColnames(colList); + + try + { + ConvertToObjectPropertyData.getObjectPropertyDataGenericGroupedColumn(strList, data, colgrp); + assertNotNull(ConvertToObjectPropertyData.getObjectPropertyDataGenericGroupedColumn(strList, data, colgrp)); + } + catch (DatabaseOperationException e) + { + fail("not expected to come here"); + } + catch (DatabaseCriticalException e) + { + fail("not expected to come here"); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/CursorQueryExecutorTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/CursorQueryExecutorTest.java new file mode 100644 index 0000000000000000000000000000000000000000..a25335fc065f00c27cc10b2d2dc17b4163577d3d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/CursorQueryExecutorTest.java @@ -0,0 +1,590 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.test.presentation.table; + +import java.sql.Timestamp; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.sql.Date; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.TimeZone; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.opengauss.mppdbide.adapter.gauss.StmtExecutor.GetFuncProcResultValueParam; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DefaultParameter; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.ObjectParameter.PARAMETERTYPE; +import org.opengauss.mppdbide.bl.sqlhistory.IQueryExecutionSummary; +import org.opengauss.mppdbide.bl.sqlhistory.QueryExecutionSummary; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.mock.presentation.ResultSetMetaDataImplementation; +import org.opengauss.mppdbide.presentation.ContextExecutionOperationType; +import org.opengauss.mppdbide.presentation.ExecutionFailureActionOptions; +import org.opengauss.mppdbide.presentation.IExecutionContext; +import org.opengauss.mppdbide.presentation.IResultDisplayUIManager; +import org.opengauss.mppdbide.presentation.TerminalExecutionConnectionInfra; +import org.opengauss.mppdbide.presentation.edittabledata.CursorQueryExecutor; +import org.opengauss.mppdbide.presentation.resultset.ActionAfterResultFetch; +import org.opengauss.mppdbide.presentation.resultsetif.IResultConfig; +import org.opengauss.mppdbide.utils.ResultSetDatatypeMapping; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.MessageQueue; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; +import com.mockrunner.mock.jdbc.MockResultSet; +import static org.junit.Assert.*; + +/** + * Query executor and materialize Test + * + * @since 3.0.0 + */ +public class CursorQueryExecutorTest extends BasicJDBCTestCaseAdapter +{ + + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + JobCancelStatus status = null; + private Database database; + ArrayList debugInputValueList = new ArrayList(); + + @Before + public void setUp() throws Exception + { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + connection = new MockConnection(); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + preparedstatementHandler = connection.getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + CommonLLTUtils.addViewTableData(preparedstatementHandler); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + + connProfCache = DBConnProfCache.getInstance(); + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + database = connProfCache.getDbForProfileId(profileId); + database.getServer().setServerCompatibleToNodeGroup(true); + } + + @After + public void tearDown() throws Exception + { + super.tearDown(); + + Database database = connProfCache.getDbForProfileId(profileId); + if (null != database) + { + database.getServer().close(); + } + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) + { + connProfCache.removeServer(itr.next().getId()); + itr = connProfCache.getServers().iterator(); + } + + connProfCache.closeAllNodes(); + + } + + public IExecutionContext getExecutionContext() + { + return new IExecutionContext() + { + + @Override + public void setWorkingJobContext(Object jobContext) + { + + } + + @Override + public void setJobDone() + { + + + } + + @Override + public void setCurrentExecution(ContextExecutionOperationType contextOperationTypeNewPlSqlCreation) + { + + } + + @Override + public void setCriticalErrorThrown(boolean b) + { + + + } + + @Override + public boolean needQueryParseAndSplit() + { + + return false; + } + + @Override + public String jobType() + { + + return null; + } + + @Override + public void handleSuccessfullCompletion() + { + + + } + + @Override + public void handleExecutionException(Exception e) + { + + + } + + @Override + public Object getWorkingJobContext() + { + + return null; + } + + @Override + public TerminalExecutionConnectionInfra getTermConnection() + { + + return getTermConnn(); + } + + @Override + public IResultDisplayUIManager getResultDisplayUIManager() + { + + return handleResultDisplay(); + } + + @Override + public IResultConfig getResultConfig() + { + + return new IResultConfig() + { + + @Override + public int getFetchCount() + { + + return 1000; + } + + @Override + public ActionAfterResultFetch getActionAfterFetch() + { + + return ActionAfterResultFetch.CLOSE_CONNECTION_AFTER_FETCH; + } + }; + } + + @Override + public String getQuery() + { + + return null; + } + + @Override + public MessageQueue getNoticeMessageQueue() + { + + return null; + } + + @Override + public ServerObject getCurrentServerObject() + { + + return null; + } + + @Override + public ContextExecutionOperationType getCurrentExecution() + { + + return null; + } + + @Override + public String getContextName() + { + + return null; + } + + @Override + public String getConnectionProfileID() + { + + return null; + } + + @Override + public ExecutionFailureActionOptions getActionOnQueryFailure() + { + + return null; + } + + @Override + public boolean canFreeConnectionAfterUse() + { + + return false; + } + + @Override + public ArrayList getInputValues() { + return debugInputValueList; + } + }; + } + + public IResultDisplayUIManager handleResultDisplay() + { + + + return null; + } + + public TerminalExecutionConnectionInfra getTermConnn() + { + TerminalExecutionConnectionInfra termConn = new TerminalExecutionConnectionInfra(); + try + { + termConn.setConnection(database.getConnectionManager().getFreeConnection()); + } + catch (MPPDBIDEException e) + { + + e.printStackTrace(); + } + return termConn; + + } + + public IQueryExecutionSummary getQueryExecutionSummary() + { + QueryExecutionSummary queryExcSummary = null; + String input = "2016-12-16 18:29:09"; + + SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + sdf1.setTimeZone(TimeZone.getTimeZone("UTC")); + java.util.Date date; + try + { + date = sdf1.parse(input); + String dt = sdf1.format(date); + queryExcSummary = new QueryExecutionSummary("Gauss", "ds", CommonLLTUtils.EDIT_TABLE_DATA_SELECT_QUERY, + true, dt, 109, 0); + } + catch (ParseException e) + { + System.out.println("Parse exception occurred"); + } + + return queryExcSummary; + } + + public IResultConfig getResultConfig() + { + return new IResultConfig() + { + + @Override + public int getFetchCount() + { + + return 100; + } + + @Override + public ActionAfterResultFetch getActionAfterFetch() + { + + return ActionAfterResultFetch.CLOSE_CONNECTION_AFTER_FETCH; + } + }; + } + + @Test + public void test_cursor_query_executor_001_01() throws MPPDBIDEException + { + + IQueryExecutionSummary summary = getQueryExecutionSummary(); + QueryExecutionSummary qrySummery = (QueryExecutionSummary) summary; + IExecutionContext context = getExecutionContext(); + CommonLLTUtils.updateSelectQryCursorExecRS(statementHandler); + + + CursorQueryExecutor curExecutor = + new CursorQueryExecutor("select * from pg_amop;", context, qrySummery, true, true,database.getConnectionManager().getFreeConnection()); + String query = curExecutor.getUniqCursorName(); + + MockResultSet getselectrs = preparedstatementHandler.createResultSet(); + getselectrs.addColumn("amopfamily"); + getselectrs.addColumn("amoplefttype"); + getselectrs.addColumn("amoprighttype"); + getselectrs.addColumn("amopstrategy"); + getselectrs.addColumn("amoppurpose"); + getselectrs.addColumn("amopopr"); + getselectrs.addColumn("amopmethod"); + getselectrs.addColumn("amopsortfamily"); + + getselectrs.addRow(new Object[] {2, 22, 23, 7, 's', 88, 403, 0 }); + + statementHandler.prepareResultSet(query, getselectrs); + curExecutor.execute(qrySummery); + } + + @Test + public void test_cursor_query_executor_001_02() throws MPPDBIDEException + { + IQueryExecutionSummary summary = getQueryExecutionSummary(); + QueryExecutionSummary qrySummery = (QueryExecutionSummary) summary; + IExecutionContext context = getExecutionContext(); + CommonLLTUtils.updateSelectQryCursorExecRS(statementHandler); + + CursorQueryExecutor curExecutor = + new CursorQueryExecutor("select * from pg_amop;", context, qrySummery, false, false,database.getConnectionManager().getFreeConnection()); + + + String query = curExecutor.getUniqCursorName(); + MockResultSet getselectrs = preparedstatementHandler.createResultSet(); + getselectrs.addColumn("amopfamily"); + getselectrs.addColumn("amoplefttype"); + getselectrs.addColumn("amoprighttype"); + getselectrs.addColumn("amopstrategy"); + getselectrs.addColumn("amoppurpose"); + getselectrs.addColumn("amopopr"); + getselectrs.addColumn("amopmethod"); + getselectrs.addColumn("amopsortfamily"); + + getselectrs.addRow(new Object[] {2, 22, 23, 7, 's', 88, 403, 0 }); + + statementHandler.prepareResultSet(query, getselectrs); + curExecutor.execute(qrySummery); + } + + @Test + public void test_cursor_query_executor_001_03() throws MPPDBIDEException + { + IQueryExecutionSummary summary = getQueryExecutionSummary(); + QueryExecutionSummary qrySummery = (QueryExecutionSummary) summary; + IExecutionContext context = getExecutionContext(); + CommonLLTUtils.updateSelectQryCursorExecRS(statementHandler); + + CursorQueryExecutor curExecutor = + new CursorQueryExecutor("select * from pg_amop;", context, qrySummery, false, false,database.getConnectionManager().getFreeConnection()); + + + String query = curExecutor.getUniqCursorName(); + MockResultSet getselectrs = preparedstatementHandler.createResultSet(); + getselectrs.setResultSetMetaData(new ResultSetMetaDataImplementation()); + getselectrs.addColumn("amopfamily"); + getselectrs.addColumn("amoplefttype"); + getselectrs.addColumn("amoprighttype"); + getselectrs.addColumn("amopstrategy"); + getselectrs.addColumn("amoppurpose"); + getselectrs.addColumn("amopopr"); + getselectrs.addColumn("amopmethod"); + getselectrs.addColumn("amopsortfamily"); + getselectrs.addRow(new Object[] {12345678, false, 10000.56, new Date(100001456), new Timestamp(100001456), "fdhfeufhuf", 403, 0 }); + statementHandler.prepareResultSet(query, getselectrs); + ResultSetDatatypeMapping.setIncludeEncoding(true); + curExecutor.execute(qrySummery); + assertNotNull(curExecutor); + } + + @Test + public void test_cursor_query_executor_001_04() throws MPPDBIDEException + { + IQueryExecutionSummary summary = getQueryExecutionSummary(); + QueryExecutionSummary qrySummery = (QueryExecutionSummary) summary; + DefaultParameter dp1 = new DefaultParameter("N1", "BINARY_INTEGER", "5", PARAMETERTYPE.IN); + DefaultParameter dp2 = new DefaultParameter("N2", "BINARY_INTEGER", "5", PARAMETERTYPE.IN); + DefaultParameter dp3 = new DefaultParameter("TEMP_RESULT", "BINARY_INTEGER", "500", PARAMETERTYPE.OUT); + debugInputValueList.add(dp1); + debugInputValueList.add(dp2); + debugInputValueList.add(dp3); + IExecutionContext context = getExecutionContext(); + CommonLLTUtils.updateSelectQryCursorExecRS(statementHandler); + + CursorQueryExecutor curExecutor = + new CursorQueryExecutor("select * from pg_amop;", context, qrySummery, false, false,database.getConnectionManager().getFreeConnection()); + + + String query = curExecutor.getUniqCursorName(); + MockResultSet getselectrs = preparedstatementHandler.createResultSet(); + getselectrs.setResultSetMetaData(new ResultSetMetaDataImplementation() { + @Override + public int getColumnCount() throws SQLException + { + return 1; + } + @Override + public String getColumnTypeName(int column) throws SQLException + { + return "refcursor"; + } + }); + getselectrs.addColumn("amopfamily"); + List> listObj = new ArrayList>(); + ArrayList listObj1 = new ArrayList(); + listObj1.add(500); + listObj.add(listObj1); + getselectrs.addRow(new Object[] {listObj}); + statementHandler.prepareResultSet(query, getselectrs); + ResultSetDatatypeMapping.setIncludeEncoding(true); + curExecutor.execute(qrySummery); + assertNotNull(curExecutor); + } + + @Test + public void test_cursor_query_executor_001_05() throws MPPDBIDEException + { + IQueryExecutionSummary summary = getQueryExecutionSummary(); + QueryExecutionSummary qrySummery = (QueryExecutionSummary) summary; + DefaultParameter dp1 = new DefaultParameter("N1", "BINARY_INTEGER", "5", PARAMETERTYPE.IN); + DefaultParameter dp2 = new DefaultParameter("N2", "BINARY_INTEGER", "5", PARAMETERTYPE.IN); + DefaultParameter dp3 = new DefaultParameter("TEMP_RESULT", "BINARY_INTEGER", "500", PARAMETERTYPE.OUT); + debugInputValueList.add(dp1); + debugInputValueList.add(dp2); + debugInputValueList.add(dp3); + IExecutionContext context = getExecutionContext(); + CommonLLTUtils.updateSelectQryCursorExecRS(statementHandler); + + CursorQueryExecutor curExecutor = + new CursorQueryExecutor("select * from pg_amop;", context, qrySummery, false, false,database.getConnectionManager().getFreeConnection()); + + + String query = curExecutor.getUniqCursorName(); + MockResultSet getselectrs = preparedstatementHandler.createResultSet(); + getselectrs.setResultSetMetaData(new ResultSetMetaDataImplementation() { + @Override + public int getColumnCount() throws SQLException + { + return 2; + } + @Override + public String getColumnTypeName(int column) throws SQLException + { + return "refcursor"; + } + }); + getselectrs.addColumn("amopfamily"); + getselectrs.addColumn("amoplefttype"); + List> listObj = new ArrayList>(); + ArrayList listObj1 = new ArrayList(); + listObj1.add(500); + listObj.add(listObj1); + getselectrs.addRow(new Object[] {listObj, false}); + statementHandler.prepareResultSet(query, getselectrs); + ResultSetDatatypeMapping.setIncludeEncoding(true); + curExecutor.execute(qrySummery); + assertNotNull(curExecutor); + } + + @Test + public void test_StmtExecutor_GetFuncProcResultValueParam() + { + try + { + GetFuncProcResultValueParam param = new GetFuncProcResultValueParam(0, false, false); + param.setColumnCount(0); + param.setCallableStmt(true); + param.setInputParaVisited(true); + assertEquals(param.getColumnCount(), 0); + assertTrue(param.isCallableStmt()); + assertTrue(param.isInputParaVisited()); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/DNIntraNodeDetailsColumnTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/DNIntraNodeDetailsColumnTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d32e193366c6c9d525742a145c519591f42b893a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/DNIntraNodeDetailsColumnTest.java @@ -0,0 +1,424 @@ +package org.opengauss.mppdbide.test.presentation.table; + +import java.text.ParseException; +import static org.junit.Assert.*; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.presentation.CanContextContinueExecuteRule; +import org.opengauss.mppdbide.presentation.ContextExecutionOperationType; +import org.opengauss.mppdbide.presentation.DummyTerminalExecutionConnectionInfra; +import org.opengauss.mppdbide.presentation.ExecutionFailureActionOptions; +import org.opengauss.mppdbide.presentation.TerminalExecutionConnectionInfra; +import org.opengauss.mppdbide.presentation.exportdata.ImportExportDataCore; +import org.opengauss.mppdbide.presentation.objectproperties.ColumnValuePropertiesComparator; +import org.opengauss.mppdbide.presentation.objectproperties.DNIntraNodeDetailsColumn; +import org.opengauss.mppdbide.presentation.objectproperties.DSGeneraicGridDataProvider; +import org.opengauss.mppdbide.presentation.objectproperties.DSGenericGridColumnProvider; +import org.opengauss.mppdbide.presentation.objectproperties.DSGenericGroupedGridColumnProvider; +import org.opengauss.mppdbide.presentation.objectproperties.DSObjectPropertiesGridColumnDataProvider; +import org.opengauss.mppdbide.presentation.objectproperties.DSObjectPropertiesGridDataProvider; +import org.opengauss.mppdbide.presentation.objectproperties.DSObjectPropertiesGridDataRow; +import org.opengauss.mppdbide.presentation.util.DataTypeUtility; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; + +public class DNIntraNodeDetailsColumnTest extends BasicJDBCTestCaseAdapter +{ + DummyTerminalExecutionConnectionInfra dummyconn = null; + ExecutionFailureActionOptions enumObj = null; + TerminalExecutionConnectionInfra termConnInfra = null; + DNIntraNodeDetailsColumn dnDetailCol = null; + ImportExportDataCore impoExpoCore = null; + DSObjectPropertiesGridColumnDataProvider objectproertiescolData = null; + DSObjectPropertiesGridDataRow dsGridDataRow = null; + DSGenericGridColumnProvider dsgenericGridColProvider = null; + DSGenericGroupedGridColumnProvider dsColProvider = null; + DSGeneraicGridDataProvider dsDataProvider = null; + DSObjectPropertiesGridDataProvider dsObjectGridDataProvider = null; + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#setUp() + */ + @Before + public void setUp() throws Exception + { + CommonLLTUtils.runLinuxFilePermissionInstance(); + dummyconn = new DummyTerminalExecutionConnectionInfra(); + termConnInfra = new TerminalExecutionConnectionInfra(); + dnDetailCol = new DNIntraNodeDetailsColumn(); + objectproertiescolData = new DSObjectPropertiesGridColumnDataProvider(); + Object[] rows = {1, "name"}; + dsGridDataRow = new DSObjectPropertiesGridDataRow(rows); + dsgenericGridColProvider = new DSGenericGridColumnProvider(); + List colgrpDetails = new ArrayList(); + DNIntraNodeDetailsColumn element = new DNIntraNodeDetailsColumn(); + element.setColCount(1); + element.setGroupColumnName("Columns"); + List colList = new ArrayList(); + colList.add(0, "name"); + colList.add(1, "types"); + colgrpDetails.add(0, element); + colgrpDetails.add(1, element); + element.setColnames(colList); + dsColProvider = new DSGenericGroupedGridColumnProvider(colgrpDetails); + List colList1 = new ArrayList(); + String[] element1 = {"name", "desc", "type", "table"}; + colList1.add(0, element1); + colList1.add(1, element1); + dsDataProvider = new DSGeneraicGridDataProvider(colList1, "name", colgrpDetails); + + List colListArr = new ArrayList(); + String[] data = {"name", "desc", "type", "table"}; + colListArr.add(0, data); + colListArr.add(1, data); + dsObjectGridDataProvider = new DSObjectPropertiesGridDataProvider(colListArr, "name", null, null); + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception + { + + } + + @Test + public void test_Dummy_Connection() + { + dummyconn.isConnected(); + assertNotNull(ExecutionFailureActionOptions.EXECUTION_FAILURE_ACTION_ABORT); + assertNotNull(ExecutionFailureActionOptions.EXECUTION_FAILURE_ACTION_CONTINUE); + assertEquals(dummyconn.isConnected(), true); + } + + @Test + public void test_terminal_execution_connection_infra() + { + if (termConnInfra != null) + { + termConnInfra.setAutoCommitFlag(true); + termConnInfra.getAutoCommitFlag(); + termConnInfra.resetInformation(); + termConnInfra.releaseConnection(); + termConnInfra.isConnected(); + assertEquals(termConnInfra.isConnected(), false); + assertEquals(termConnInfra.getAutoCommitFlag(), true); + } + } + + @Test + public void test_CanContextContinueExecuteRule() + { + assertNotNull(CanContextContinueExecuteRule.CONTEXT_EXECUTION_PROCEED); + assertNotNull(CanContextContinueExecuteRule.CONTEXT_EXECUTION_STOP); + assertNotNull(CanContextContinueExecuteRule.CONTEXT_EXECUTION_UNKNOWN); + } + + @Test + public void test_ContextExecutionOperationType() + { + assertNotNull(ContextExecutionOperationType.CONTEXT_OPERATION_TYPE_NEW_PL_SQL_CREATION); + assertNotNull(ContextExecutionOperationType.CONTEXT_OPERATION_TYPE_PL_SQL_COMPILATION); + assertNotNull(ContextExecutionOperationType.CONTEXT_OPERATION_TYPE_SQL_TERMINAL_EXECUTION); + assertNotNull(ContextExecutionOperationType.CONTEXT_OPERATION_TYPE_VIEW_OBJECT_DATA); + assertNotNull(ContextExecutionOperationType.CONTEXT_OPERATION_TYPE_VIEW_OBJECT_PROPERTY); + } + + @Test + public void test_DNIntraNodeDetailsColumn() + { + List colnames = new ArrayList(); + colnames.add("A"); + colnames.add("B"); + colnames.add("C"); + dnDetailCol.setColCount(5); + dnDetailCol.getColCount(); + dnDetailCol.setColnames(colnames); + dnDetailCol.getColnames(); + dnDetailCol.setGroupColumnName("Columns"); + dnDetailCol.getGroupColumnName(); + assertNotNull(colnames.size()); + assertEquals(colnames.size(), 3); + assertEquals(dnDetailCol.getColCount(), 5); + } + + @Test + public void test_DataTypeUtility_convertToDateObj() + { + try + { + java.util.Date date = DataTypeUtility.convertToDateObj("2018-02-27 12:10:22", "yyyy-MM-dd HH:mm:ss"); + assertNotNull(date); + } + catch (ParseException e) + { + fail("Not expected to come here"); + } + } + + @Test + public void test_DataTypeUtility_convertToTimeObj() + { + try + { + java.util.Date date = DataTypeUtility.convertToTimeObj("12:10:2200", "HH:mm:ss"); + assertNotNull(date); + } + catch (ParseException e) + { + fail("Not expected to come here"); + } + } + + @Test + public void test_DataTypeUtility_convertToTimeObj1() + { + + assertEquals("char", DataTypeUtility.convertToDisplayDatatype("bpchar")); + assertEquals("boolean", DataTypeUtility.convertToDisplayDatatype("bool")); + assertEquals("binary double", DataTypeUtility.convertToDisplayDatatype("float")); + assertEquals("smallint", DataTypeUtility.convertToDisplayDatatype("int2")); + assertEquals("integer", DataTypeUtility.convertToDisplayDatatype("int4")); + assertEquals("bigint", DataTypeUtility.convertToDisplayDatatype("int8")); + assertEquals("double precision", DataTypeUtility.convertToDisplayDatatype("float8")); + assertEquals("real", DataTypeUtility.convertToDisplayDatatype("float4")); + assertEquals("time with time zone", DataTypeUtility.convertToDisplayDatatype("timetz")); + assertEquals("timestamp with time zone", DataTypeUtility.convertToDisplayDatatype("timestamptz")); + assertEquals("time without time zone", DataTypeUtility.convertToDisplayDatatype("time")); + assertEquals("timestamp without time zone", DataTypeUtility.convertToDisplayDatatype("timestamp")); + } + + @Test + public void test_DSObjectPropertiesGridColumnDataProvider() + { + if (objectproertiescolData != null) + { + List colList = new ArrayList(); + String[] element = {"name", "desc", "type", "table"}; + colList.add(0, element); + colList.add(1, element); + objectproertiescolData.init(colList); + objectproertiescolData.getColumnCount(); + objectproertiescolData.getColumnName(0); + objectproertiescolData.getColumnNames(); + objectproertiescolData.getColumnDesc(0); + objectproertiescolData.getColumnIndex("ABC"); + ColumnValuePropertiesComparator comparator = (ColumnValuePropertiesComparator) objectproertiescolData.getComparator(0); + comparator.compare(new Object(), new Object()); + objectproertiescolData.getColumnDatatype(0); + objectproertiescolData.getColumnDataTypeName(0); + objectproertiescolData.getPrecision(0); + objectproertiescolData.getScale(0); + objectproertiescolData.getMaxLength(0); + assertEquals(objectproertiescolData.getColumnCount(), 4); + assertEquals(objectproertiescolData.getColumnName(0), "name"); + assertEquals(objectproertiescolData.getColumnDesc(0), "name"); + } + } + + @Test + public void test_DSObjectPropertiesGridDataRow() + { + if (dsGridDataRow != null) + { + dsGridDataRow.getValue(1); + dsGridDataRow.getClonedValues(); + assertEquals(dsGridDataRow.getValue(1), "name"); + } + } + + @Test + public void test_DSGenericGridColumnProvider() + { + if (dsgenericGridColProvider != null) + { + List colList = new ArrayList(); + String[] element = {"name", "desc", "type", "table"}; + colList.add(0, element); + colList.add(1, element); + dsgenericGridColProvider.init(colList); + dsgenericGridColProvider.getColumnCount(); + dsgenericGridColProvider.getColumnDatatype(0); + dsgenericGridColProvider.getColumnDataTypeName(0); + dsgenericGridColProvider.getColumnDesc(0); + dsgenericGridColProvider.getColumnIndex("name"); + dsgenericGridColProvider.getColumnName(0); + dsgenericGridColProvider.getColumnNames(); + dsgenericGridColProvider.getComparator(0); + dsgenericGridColProvider.getPrecision(0); + dsgenericGridColProvider.getScale(0); + dsgenericGridColProvider.getMaxLength(0); + + assertEquals(dsgenericGridColProvider.getColumnCount(), 4); + assertEquals(dsgenericGridColProvider.getColumnName(0), "name"); + assertEquals(dsgenericGridColProvider.getColumnDesc(0), "name"); + } + } + + @Test + public void test_DSGenericGroupedGridColumnProvider() + { + if (dsColProvider != null) + { + dsColProvider.getColumnGroupIndex(1); + dsColProvider.getColumnGroupName(1); + dsColProvider.getColumnIndexInGroup(1); + dsColProvider.getGroupCount(); + + assertEquals(dsColProvider.getGroupCount(), 2); + assertEquals(dsColProvider.getColumnGroupName(1), "Columns"); + } + } + + @Test + public void test_DSGeneraicGridDataProvider() + { + if (dsDataProvider != null) + { + try + { + dsDataProvider.init(); + assertTrue(true); + } + catch (DatabaseOperationException e1) + { + fail("not expected to come here"); + } + catch (DatabaseCriticalException e1) + { + fail("not expected to come here"); + } + dsDataProvider.getAllFetchedRows(); + + dsDataProvider.getColumnDataProvider(); + dsDataProvider.getColumnGroupProvider(); + try + { + dsDataProvider.getNextBatch(); + assertEquals(dsDataProvider.getNextBatch(), null); + } + catch (DatabaseOperationException e) + { + fail("not expected to come here"); + } + catch (DatabaseCriticalException e) + { + fail("not expected to come here"); + } + dsDataProvider.getObjectPropertyName(); + assertEquals(dsDataProvider.getObjectPropertyName(), "name"); + dsDataProvider.getRecordCount(); + assertEquals(dsDataProvider.getRecordCount(), 0); + dsDataProvider.isEndOfRecords(); + try + { + dsDataProvider.close(); + } + catch (DatabaseOperationException e) + { + fail("not expected to come here"); + } + catch (DatabaseCriticalException e) + { + fail("not expected to come here"); + } + } + } + + @Test + public void test_DSObjectPropertiesGridDataProvider() + { + if (dsObjectGridDataProvider != null) + { + try + { + dsObjectGridDataProvider.init(); + assertTrue(true); + } + catch (DatabaseOperationException e) + { + fail("not expected to come here"); + } + catch (DatabaseCriticalException e) + { + fail("not expected to come here"); + } + dsObjectGridDataProvider.getAllFetchedRows(); + dsObjectGridDataProvider.getColumnDataProvider(); + dsObjectGridDataProvider.getColumnGroupProvider(); + assertNull(dsObjectGridDataProvider.getTableName()); + dsObjectGridDataProvider.setResultTabDirtyFlag(false); + assertNull(dsObjectGridDataProvider.getColumnNames()); + assertNull(dsObjectGridDataProvider.getEmptyRowForInsert(0)); + assertEquals(0,dsObjectGridDataProvider.getColumnCount()); + dsObjectGridDataProvider.setCancel(false); + assertEquals(false, dsObjectGridDataProvider.isUniqueKeyPresent()); + assertEquals(false, dsObjectGridDataProvider.isDistributionColumnsRequired()); + dsObjectGridDataProvider.setFuncProcExport(false); + try + { + dsObjectGridDataProvider.getNextBatch(); + assertEquals(dsObjectGridDataProvider.getNextBatch(), null); + } + catch (DatabaseOperationException e) + { + fail("not expected to come here"); + } + catch (DatabaseCriticalException e) + { + fail("not expected to come here"); + } + dsObjectGridDataProvider.getObjectPropertyName(); + + assertEquals(dsObjectGridDataProvider.getObjectPropertyName(), "name"); + dsObjectGridDataProvider.getRecordCount(); + System.out.println("DNIntraNodeDetailsColumnTest.test_DSObjectPropertiesGridDataProvider()" + + dsObjectGridDataProvider.getRecordCount()); + assertEquals(dsObjectGridDataProvider.getRecordCount(), 1); + dsObjectGridDataProvider.isEndOfRecords(); + + assertEquals(dsObjectGridDataProvider.isEndOfRecords(), true); + assertEquals(false, dsObjectGridDataProvider.getResultTabDirtyFlag()); + assertEquals(false, dsObjectGridDataProvider.isDistributionColumn(0)); + assertEquals(false, dsObjectGridDataProvider.isFuncProcExport()); + try { + dsObjectGridDataProvider.cancelCommit(); + boolean canc = dsObjectGridDataProvider.isCancelled(); + assertEquals(canc, dsObjectGridDataProvider.isCancelled()); + dsObjectGridDataProvider.preDestroy(); + } catch (DatabaseCriticalException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (DatabaseOperationException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + try + { + dsObjectGridDataProvider.close(); + } + catch (DatabaseOperationException e) + { + fail("not expected to come here"); + } + catch (DatabaseCriticalException e) + { + fail("not expected to come here"); + } + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/DebugerConstantTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/DebugerConstantTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ef9aedacc5804281c123e63d0d614ddb05e0b0c2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/DebugerConstantTest.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.test.presentation.table; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +import org.opengauss.mppdbide.debuger.debug.DebugConstants; +import org.opengauss.mppdbide.debuger.debug.DebugConstants.DebugOpt; +import org.opengauss.mppdbide.debuger.vo.FunctionVo; +import org.opengauss.mppdbide.debuger.vo.PositionVo; +import org.opengauss.mppdbide.debuger.vo.SessionVo; +import org.opengauss.mppdbide.debuger.vo.SourceCodeVo; +import org.opengauss.mppdbide.debuger.vo.StackVo; +import org.opengauss.mppdbide.debuger.vo.TotalSourceCodeVo; +import org.opengauss.mppdbide.debuger.vo.VariableVo; + +/** + * Title: DebugerDebugOptTest for use + * + * @since 3.0.0 + */ +public class DebugerConstantTest { + @Test + public void testNoParam() { + String sql1 = DebugConstants.getSql(DebugOpt.DEBUG_ON); + String compareResults = "select * from pldbg_on()"; + assertEquals(compareResults, sql1); + } + + @Test + public void testOneParam() { + String sql1 = DebugConstants.getSql(DebugConstants.DebugOpt.START_SESSION); + assertEquals(sql1, "select * from plpgsql_oid_debug(?)"); + } + + @Test + public void testThreeParam() { + String sql1 = DebugConstants.getSql(DebugConstants.DebugOpt.SET_BREAKPOINT); + assertEquals(sql1, "select * from pldbg_set_breakpoint(?,?,?)"); + } + + @Test + public void testAnotherInput() { + String sql1 = DebugConstants.getSql("test_function", 3); + String result = "select * from test_function(?,?,?)"; + assertEquals(sql1, result); + } + + @Test + public void testVoCreate() { + FunctionVo funVo = new FunctionVo(); + assertNotNull(funVo); + + PositionVo positionVo = new PositionVo(); + assertNotNull(positionVo); + + PositionVo positionVo2 = new PositionVo(new Long(0), 1, null); + assertNotNull(positionVo2); + assertEquals(positionVo2.linenumber.intValue(), 1); + assertNotEquals(PositionVo.title(), ""); + assertNotEquals(positionVo2.formatSelf(), ""); + + SessionVo sessionVo = new SessionVo(); + assertNotNull(sessionVo); + + SourceCodeVo codeVo = new SourceCodeVo(); + assertNotNull(codeVo); + codeVo.pldbg_get_source = "test"; + assertEquals(codeVo.getSourceCode(), "test"); + + StackVo stackVo = new StackVo(); + assertNotNull(stackVo); + stackVo.level = new Integer(1); + stackVo.targetname = "name"; + assertNotEquals(stackVo.toString(), ""); + + TotalSourceCodeVo totalSourceCodeVo = new TotalSourceCodeVo(); + assertNotNull(totalSourceCodeVo); + totalSourceCodeVo.definition = "test11"; + totalSourceCodeVo.headerlines = new Integer(1); + assertEquals(totalSourceCodeVo.getHeadlines(), 1); + assertEquals(totalSourceCodeVo.getSourceCode(), "test11/"); + + VariableVo variableVo = new VariableVo(); + assertNotNull(variableVo); + variableVo.name = "var1"; + variableVo.linenumber = new Integer(1); + variableVo.value = "value"; + variableVo.dtype = new Long(3); + variableVo.isnotnull = new Boolean(true); + assertNotEquals(VariableVo.title(), ""); + assertNotEquals(variableVo.formatSelf(), ""); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/DebugerFunctionTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/DebugerFunctionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..3feed901525e62bcc27c895eb7d3aceb357e00c2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/DebugerFunctionTest.java @@ -0,0 +1,535 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.test.presentation.table; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Optional; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.contentassist.ContentAssistProcesserData; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DebugObjects; +import org.opengauss.mppdbide.bl.serverdatacache.ForeignTable; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.PartitionTable; +import org.opengauss.mppdbide.bl.serverdatacache.SequenceMetadata; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TypeMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.UserNamespace; +import org.opengauss.mppdbide.bl.serverdatacache.ViewColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.common.DBConnectionAdapter; +import org.opengauss.mppdbide.common.IConnection; +import org.opengauss.mppdbide.common.IConnectionDisconnect; +import org.opengauss.mppdbide.common.IConnectionProvider; +import org.opengauss.mppdbide.debuger.dao.FunctionDao; +import org.opengauss.mppdbide.debuger.debug.DebugConstants; +import org.opengauss.mppdbide.debuger.debug.DebugConstants.DebugOpt; +import org.opengauss.mppdbide.debuger.exception.DebugExitException; +import org.opengauss.mppdbide.debuger.service.DebugService; +import org.opengauss.mppdbide.debuger.service.QueryService; +import org.opengauss.mppdbide.debuger.service.ServiceFactory; +import org.opengauss.mppdbide.debuger.service.chain.PrepareMsgChian; +import org.opengauss.mppdbide.debuger.service.chain.ServerPortMsgChain; +import org.opengauss.mppdbide.debuger.thread.DebugServerThreadProxy; +import org.opengauss.mppdbide.debuger.vo.FunctionVo; +import org.opengauss.mppdbide.debuger.vo.PositionVo; +import org.opengauss.mppdbide.debuger.vo.StackVo; +import org.opengauss.mppdbide.debuger.vo.VariableVo; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.mock.presentation.MockDebugServiceHelper; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; + +/** + * Title: DebugerFunctionTest for use + * + * @since 3.0.0 + */ +public class DebugerFunctionTest extends BasicJDBCTestCaseAdapter { + MockConnection connection = null; + Database connectionProfile = null; + DebugObjects debugObject = null; + DebugObjects nestedDebugObject = null; + StatementResultSetHandler statementHandler = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + ServerConnectionInfo serverInfo = null; + ConnectionProfileId profileId = null; + + DBConnProfCache connProfCache = null; + ContentAssistProcesserData data; + Database database = null; + + FunctionDesc funcDescAddTest = new FunctionDesc("add_test", + Arrays.asList(new Integer(1), new Integer(2))); + ServiceFactory serviceFactory = null; + DebugService debugService = null; + QueryService queryService = null; + FunctionVo functionVo = null; + DebugServerThreadProxy serverThreadProxy = null; + + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#setUp() + */ + @Before + public void setUp() throws Exception + { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + connection = new MockConnection(); + MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + connProfCache = DBConnProfCache.getInstance(); + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + MockPresentationBLPreferenceImpl.setFileEncoding("UTF-8"); + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + database = connProfCache.getDbForProfileId(profileId); + data = new ContentAssistProcesserData(database); + getAllDatabaseObjects(); + + prepareDebugResultSets(); + serviceFactory = createServiceFactory(); + queryService = serviceFactory.getQueryService(); + functionVo = queryService.queryFunction(funcDescAddTest.proname); + debugService = serviceFactory.getDebugService(functionVo); + debugService.init(); + debugService.prepareDebug(); + debugService.noticeReceived(new SQLWarning(PrepareMsgChian.PREPARE_SUCCESS + " SERVER ")); + debugService.noticeReceived(new SQLWarning(ServerPortMsgChain.SERVER_PORT_MATCH + "0")); + debugService.attachDebug(); + Thread.sleep(50); + debugService.startDebug(funcDescAddTest.params); + Thread.sleep(50); + } + + private ServiceFactory createServiceFactory() { + ServiceFactory serviceFactory = new ServiceFactory(new IConnectionProvider() { + @Override + public Optional getFreeConnection() { + DBConnection dbConn; + try { + dbConn = database.getConnectionManager().getFreeConnection(); + return Optional.of(new DBConnectionAdapter( + dbConn, + new IConnectionDisconnect() { + @Override + public void releaseConnection(DBConnection connection) { + database + .getConnectionManager() + .releaseAndDisconnection(connection); + } + })); + } catch (MPPDBIDEException e) { + } + return Optional.empty(); + } + }); + return serviceFactory; + } + private void prepareDebugResultSets() { + String sql = new FunctionDao().getSql(funcDescAddTest.proname); + MockDebugServiceHelper mockHelper = new MockDebugServiceHelper( + preparedstatementHandler, functionVo); + mockHelper.mockFunctionVo(sql, new Object[] {new Long(1), funcDescAddTest.proname}); + mockHelper.mockPrepareDebug( + DebugConstants.getSql(DebugOpt.START_SESSION)); + mockHelper.mockStartDebug( + DebugConstants.getSql(funcDescAddTest.proname, funcDescAddTest.params.size()), + new Integer(7)); + mockHelper.mockAttachDebug(DebugConstants.getSql(DebugOpt.ATTACH_SESSION), + new Integer(1)); + mockHelper.mockAbortDebug(DebugConstants.getSql(DebugOpt.ABORT_TARGET)); + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception + { + super.tearDown(); + + debugService.end(); + debugService = null; + queryService.closeService(); + queryService = null; + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearThrowsSQLException(); + connectionProfile = null; + + Iterator itr = DBConnProfCache.getInstance().getServers().iterator(); + + while(itr.hasNext()) + { + DBConnProfCache.getInstance().removeServer(itr.next().getId()); + } + } + + @Test + public void testBreakPoints() { + MockDebugServiceHelper helper = new MockDebugServiceHelper(preparedstatementHandler, + functionVo); + helper.mockBreakPoint(DebugConstants.getSql(DebugOpt.GET_BREAKPOINTS)); + try { + List breakpoints = debugService.getBreakPoints(); + assertEquals(1, breakpoints.size()); + PositionVo positionVo = breakpoints.get(0); + assertEquals(positionVo.func.longValue(), functionVo.oid.longValue()); + assertEquals(positionVo.linenumber.intValue(), -1); + assertEquals(positionVo.targetname, functionVo.proname); + } catch (SQLException e) { + fail("get breakpoints failed!"); + } + } + + @Test + public void testVariable() { + MockDebugServiceHelper helper = new MockDebugServiceHelper(preparedstatementHandler, + functionVo); + helper.mockVariable(DebugConstants.getSql(DebugOpt.GET_VARIABLES)); + try { + List variables = debugService.getVariables(); + assertEquals(1, variables.size()); + VariableVo var = variables.get(0); + assertEquals(var.name, "v1"); + assertTrue(var.value instanceof Integer); + assertEquals(((Integer)var.value).intValue(), 1); + } catch (SQLException e) { + fail("get breakpoints failed!"); + } + } + + @Test + public void testStack() { + MockDebugServiceHelper helper = new MockDebugServiceHelper(preparedstatementHandler, + functionVo); + helper.mockStack(DebugConstants.getSql(DebugOpt.GET_STACKS)); + try { + List stacks = debugService.getStacks(); + assertEquals(1, stacks.size()); + StackVo stackVo = stacks.get(0); + assertEquals(stackVo.targetname, funcDescAddTest.proname); + assertEquals(stackVo.func.longValue(), functionVo.oid.longValue()); + assertEquals(stackVo.level.intValue(), 1); + } catch (SQLException e) { + fail("get breakpoints failed!"); + } + } + + @Test + public void testStepDebug() { + MockDebugServiceHelper helper = new MockDebugServiceHelper(preparedstatementHandler, + functionVo); + DebugOpt[] toTestOpt = new DebugOpt[] {DebugOpt.STEP_INTO, DebugOpt.STEP_OVER, + DebugOpt.CONTINUE_EXEC}; + for (DebugOpt opt: toTestOpt) { + helper.mockPositionOneLine(DebugConstants.getSql(opt)); + } + + for (DebugOpt opt: toTestOpt) { + try { + PositionVo positionVo = debugService.getPositionVo(opt).get(); + assertEquals(positionVo.func.longValue(), functionVo.oid.longValue()); + assertEquals(positionVo.linenumber.intValue(), -1); + assertEquals(positionVo.targetname, functionVo.proname); + } catch (SQLException e) { + fail("get step pos failed!"); + } catch (DebugExitException e) { + assertTrue(true); + } + } + } + + @Test + public void testStepInto() { + MockDebugServiceHelper helper = new MockDebugServiceHelper( + preparedstatementHandler, functionVo); + helper.mockPositionOneLine(DebugConstants.getSql(DebugOpt.STEP_INTO)); + try { + debugService.stepInto().get(); + assertTrue(true); + } catch (SQLException sqlExp) { + fail("can\'t run here!"); + } catch (DebugExitException e) { + assertTrue(true); + } + } + + @Test + public void testStepOver() { + MockDebugServiceHelper helper = new MockDebugServiceHelper( + preparedstatementHandler, functionVo); + helper.mockPositionOneLine(DebugConstants.getSql(DebugOpt.STEP_OVER)); + try { + debugService.stepOver().get(); + assertTrue(true); + } catch (SQLException sqlExp) { + fail("can\'t run here!"); + } catch (DebugExitException e) { + assertTrue(true); + } + } + + @Test + public void testContinue() { + MockDebugServiceHelper helper = new MockDebugServiceHelper( + preparedstatementHandler, functionVo); + helper.mockPositionOneLine(DebugConstants.getSql(DebugOpt.CONTINUE_EXEC)); + try { + debugService.continueExec().get(); + assertTrue(true); + } catch (SQLException sqlExp) { + fail("can\'t run here!"); + } catch (DebugExitException e) { + assertTrue(true); + } + } + + @Test + public void testStepOutDebug() { + try { + debugService.stepOut().get(); + fail("can\'t run here!"); + } catch (SQLException sqlExp) { + assertTrue(true); + } catch (DebugExitException e) { + fail("can\'t run here!"); + } + } + + public static class FunctionDesc { + public String proname; + public List params; + public FunctionDesc(String proname, List params) { + this.proname = proname; + this.params = params; + } + } + + private void getAllDatabaseObjects() + { + try + { + + database.getServer().refresh(); + Namespace ns1 = new UserNamespace(6, "ns1", database); + Namespace ns2 = new UserNamespace(2, "NS1", database); + Namespace ns3 = new UserNamespace(3, "NS2", database); + Namespace ns4 = new UserNamespace(4, "yns2", database); + Namespace ns6 = new UserNamespace(5, "\"NS1\"", database); + Namespace ns7 = new UserNamespace(7, "Namespc", database); + + + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns1); + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns2); + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns3); + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns4); + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns6); + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns7); + + TableMetaData ptab1 = new PartitionTable(ns7); + ns7.addTableToSearchPool(ptab1); + + TableMetaData tbl1 = new TableMetaData(1, "tbl1", ns1, ""); + ColumnMetaData clm = new ColumnMetaData(tbl1, 1, "Col1", new TypeMetaData(11, "Integer", ns3)); + tbl1.addColumn(clm); + TableMetaData tbl2 = new TableMetaData(2, "tbl2", ns1, ""); + ColumnMetaData clm1 = new ColumnMetaData(tbl2, 1, "Col2", null); + tbl2.addColumn(clm1); + TableMetaData tbl3 = new TableMetaData(3, "TBL1", ns1, ""); + ColumnMetaData clm2 = new ColumnMetaData(tbl3, 1, "Col3", null); + tbl3.addColumn(clm2); + + ns1.addTableToSearchPool(tbl1); + ns1.addTableToSearchPool(tbl2); + ns1.addTableToSearchPool(tbl3); + + TableMetaData tbl4 = new TableMetaData(4, "tbl1", ns2, ""); + ColumnMetaData clm3 = new ColumnMetaData(tbl4, 1, "Col4", new TypeMetaData(11, "Integer", ns3)); + tbl4.addColumn(clm3); + TableMetaData tbl5 = new TableMetaData(5, "tbl2", ns2, ""); + ColumnMetaData clm4 = new ColumnMetaData(tbl5, 1, "Col5", null); + tbl5.addColumn(clm4); + TableMetaData tbl6 = new TableMetaData(6, "TBL1", ns2, ""); + ColumnMetaData clm5 = new ColumnMetaData(tbl6, 1, "Col6", null); + tbl6.addColumn(clm5); + TableMetaData tbl7 = new TableMetaData(7, "TBL2", ns2, ""); + ColumnMetaData clm6 = new ColumnMetaData(tbl7, 1, "Col7", null); + tbl7.addColumn(clm6); + TableMetaData tbl110 = new TableMetaData(110, "T}BL1", ns2, ""); + ColumnMetaData clm110 = new ColumnMetaData(tbl110, 1, "Col7", null); + tbl7.addColumn(clm110); + + ViewMetaData view = new ViewMetaData(1, "Yiew1", ns2,ns2.getDatabase()); + ViewColumnMetaData viewCol = new ViewColumnMetaData(view, 2, "viewclm", new TypeMetaData(0, "int", ns2)); + view.getColumns().addItem(viewCol); + + SequenceMetadata seq = new SequenceMetadata(ns2); + seq.setName("seq"); + + ns2.addTableToSearchPool(tbl5); + ns2.addTableToSearchPool(tbl6); + ns2.addTableToSearchPool(tbl7); + ns2.addTableToSearchPool(tbl4); + ns2.addTableToSearchPool(tbl110); + ns2.addView(view); + ns2.addSequence(seq); + database.getSearchPoolManager().addsequenceToSearchPool(seq); + + TableMetaData tbl8 = new TableMetaData(8, "tbl1", ns3, ""); + ColumnMetaData clm8 = new ColumnMetaData(tbl8, 1, "Col8", new TypeMetaData(11, "Integer", ns3)); + tbl8.addColumn(clm8); + TableMetaData tbl9 = new TableMetaData(9, "tbl2", ns3, ""); + ColumnMetaData clm9 = new ColumnMetaData(tbl9, 1, "Col9", null); + tbl9.addColumn(clm9); + + ns3.addTableToSearchPool(tbl8); + ns3.addTableToSearchPool(tbl9); + + TableMetaData tbl10 = new TableMetaData(10, "Tbl11", ns4, ""); + ColumnMetaData clm10 = new ColumnMetaData(tbl10, 1, "Col10", null); + tbl10.addColumn(clm10); + TableMetaData tbl11 = new TableMetaData(11, "xtbl2", ns4, ""); + ColumnMetaData clm11 = new ColumnMetaData(tbl11, 1, "Col11", null); + tbl11.addColumn(clm11); + TableMetaData tbl12 = new TableMetaData(12, "NS1", ns4, ""); + ColumnMetaData clm12 = new ColumnMetaData(tbl12, 1, "Col12", null); + tbl12.addColumn(clm12); + + ns4.addTableToSearchPool(tbl10); + ns4.addTableToSearchPool(tbl11); + ns4.addTableToSearchPool(tbl12); + + TableMetaData tbl14 = new TableMetaData(13, "ybl1", ns6, ""); + ColumnMetaData clm14 = new ColumnMetaData(tbl14, 1, "Col14", null); + tbl14.addColumn(clm14); + + ns6.addTableToSearchPool(tbl14); + + + ForeignTable ForeignTbl = new ForeignTable(ns1, OBJECTTYPE.FOREIGN_TABLE_GDS); + ForeignTbl.setName("Ftable1"); + ForeignTbl.setOid(1); + ns1.addForeignTableToGroup(ForeignTbl); + ns1.addTableToSearchPool(ForeignTbl); + ColumnMetaData fClm10 = new ColumnMetaData(ForeignTbl, 1, "FCol10", null); + ForeignTbl.addColumn(fClm10); + + ForeignTable ForeignTbl2 = new ForeignTable(ns1, OBJECTTYPE.FOREIGN_TABLE_GDS); + ForeignTbl2.setName("Ftable2"); + ForeignTbl.setOid(2); + ns1.addForeignTableToGroup(ForeignTbl2); + ns1.addTableToSearchPool(ForeignTbl2); + ColumnMetaData fClm11 = new ColumnMetaData(ForeignTbl, 1, "FCol11", null); + ForeignTbl2.addColumn(fClm11); + + PartitionTable ptab = new PartitionTable(ns2); + ptab.setName("partTable"); + ptab.setOid(1); + ns2.addTableToGroup(ptab); + ns2.addTableToSearchPool(ptab); + ColumnMetaData pClm11 = new ColumnMetaData(ptab, 1, "PCol11", null); + ptab.addColumn(pClm11); + + PartitionTable ptab11 = new PartitionTable(ns2); + ptab11.setName("partTable1"); + ptab.setOid(2); + ns2.addTableToGroup(ptab11); + ns2.addTableToSearchPool(ptab11); + ColumnMetaData pClm12 = new ColumnMetaData(ptab11, 1, "PCol12", null); + ptab11.addColumn(pClm12); + + + System.out.println(database.getAllNameSpaces()); + + + } + catch (DatabaseOperationException e) + { + + e.printStackTrace(); + } + catch (DatabaseCriticalException e) + { + + e.printStackTrace(); + } + catch (Exception e) + { + + e.printStackTrace(); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/DsCursorTableDataGridDataProviderTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/DsCursorTableDataGridDataProviderTest.java new file mode 100644 index 0000000000000000000000000000000000000000..b19e4ea1fa988d09a8abbf42b6b02168e158041c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/DsCursorTableDataGridDataProviderTest.java @@ -0,0 +1,216 @@ +package org.opengauss.mppdbide.test.presentation.table; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Iterator; +import java.util.TimeZone; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.*; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DatabaseUtils; +import org.opengauss.mppdbide.bl.serverdatacache.IQueryResult; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.bl.sqlhistory.QueryExecutionSummary; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.presentation.edittabledata.DSCursorDataGridRow; +import org.opengauss.mppdbide.presentation.edittabledata.DSCursorTableDataGridDataProvider; +import org.opengauss.mppdbide.presentation.edittabledata.DSResultSetGridColumnDataProvider; +import org.opengauss.mppdbide.presentation.edittabledata.DSResultSetGridDataRow; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableCellState; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableRecordStates; +import org.opengauss.mppdbide.presentation.edittabledata.IDSGridEditDataRow; +import org.opengauss.mppdbide.presentation.resultset.ActionAfterResultFetch; +import org.opengauss.mppdbide.presentation.resultsetif.IResultConfig; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.MessageQueue; +import org.opengauss.mppdbide.utils.observer.DSEventTable; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; + +public class DsCursorTableDataGridDataProviderTest extends BasicJDBCTestCaseAdapter +{ + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + int actionFetchResult; + DSResultSetGridColumnDataProvider colData; + + public int getActionFetchResult() + { + return actionFetchResult; + } + + public void setActionFetchResult(int actionFetchResult) + { + this.actionFetchResult = actionFetchResult; + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#setUp() + */ + @Before + public void setUp() throws Exception + { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + connection = new MockConnection(); + // test for logging + MPPDBIDELoggerUtility + .setArgs(new String[] {"-logfolder=.", "-detailLogging=true"}); + + // MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + MockPresentationBLPreferenceImpl.setFileEncoding("UTF-8"); + + connProfCache = DBConnProfCache.getInstance(); + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + // serverInfo.setSslPassword("12345"); + // serverInfo.setServerType(DATABASETYPE.GAUSS); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception + { + super.tearDown(); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().close(); + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) + { + connProfCache.removeServer(itr.next().getId()); + } + + connProfCache.closeAllNodes(); + + } + + @Test + public void testINIT_FUNC_001_001_1() + { + try + { + Object[] valueList = new Object[]{"empid", "ename", "salary"}; + DSCursorTableDataGridDataProvider cdsr = new DSCursorTableDataGridDataProvider(valueList); + cdsr.initByVisitor(valueList); + DSResultSetGridDataRow gridDataRow = new DSResultSetGridDataRow(cdsr); + cdsr.visit(gridDataRow); + cdsr.setEndOfRecords(); + cdsr.rollBackProvider(); + cdsr.decrementUpdatedRowCount(); + cdsr.incrementUpdatedRowCount(); + cdsr.cancelCommit(); + assertNotNull(cdsr.getConsolidatedRows()); + assertNotNull(cdsr.getColumnDataProvider()); + assertTrue(cdsr.isEndOfRecords()); + assertEquals(cdsr.isEditSupported(), false); + assertEquals(cdsr.isGridDataEdited(), false); + assertEquals(cdsr.getUpdatedRowCount(), 0); + assertEquals(cdsr.getInsertedRowCount(), 0); + assertEquals(cdsr.getDeletedRowCount(), 0); + assertEquals(cdsr.getEmptyRowForInsert(0), null); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Not Expected to come here"); + } + } + + @Test + public void testINIT_FUNC_001_001_2() + { + try + { + Object[] valueList = new Object[]{"empid", "ename", "salary"}; + DSCursorTableDataGridDataProvider cdsr = new DSCursorTableDataGridDataProvider(valueList); + + DSCursorDataGridRow gridRow = new DSCursorDataGridRow(false, 1, new DSEventTable(), cdsr); + gridRow.setCellSatus(EditTableCellState.MODIFIED, 0); + gridRow.setUpdatedRecords(0); + gridRow.setCommitStatusMessage("commited"); + gridRow.setRowIndex(0); + gridRow.setValue(0, "101"); + assertEquals(EditTableCellState.MODIFIED, gridRow.getCellStatus(0)); + assertEquals(gridRow.getUpdatedRecords(), 0); + assertEquals(gridRow.getCommitStatusMessage(), "commited"); + assertEquals(gridRow.getRowIndex(), 0); + assertEquals(gridRow.getValue(0), "101"); + assertEquals(gridRow.getUpdatedState(0), EditTableRecordStates.UPDATE); + assertNotNull(gridRow.getOriginalValue(0)); + assertNotNull(gridRow.getExecutionStatus()); + assertNotNull(gridRow.getModifiedColumns()); + Object[] value = new Object[] {"101"}; + gridRow.createNewRow(value); + assertNotNull(gridRow.getValues()); + assertNotNull(gridRow.getClonedValues()); + gridRow.undo(0); + gridRow.clearAllRowUpdates(); + gridRow.setStateDelete(); + } + catch (Exception e) + { + e.printStackTrace(); + fail("Not Expected to come here"); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ERDiagramPresentationTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ERDiagramPresentationTest.java new file mode 100644 index 0000000000000000000000000000000000000000..923dc6bf8a2487b19f4aed6ef0605181ad3a2487 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ERDiagramPresentationTest.java @@ -0,0 +1,121 @@ +package org.opengauss.mppdbide.test.presentation.table; + +import static org.junit.Assert.assertTrue; + +import java.sql.SQLException; +import java.util.Arrays; +import java.util.Iterator; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.groups.TableObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.presentation.erd.ERDiagramPresentation; +import org.opengauss.mppdbide.presentation.userrole.GrantRevokeCore; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; + +public class ERDiagramPresentationTest extends BasicJDBCTestCaseAdapter { + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + + Database database; + DBConnection dbconn; + GrantRevokeCore grantRevokeCore; + + @Before + public void setUp() throws Exception + { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + connection = new MockConnection(); + MPPDBIDELoggerUtility.setArgs(new String[] {"-logfolder=.", "-detailLogging=true"}); + + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + preparedstatementHandler = connection.getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + + connProfCache = DBConnProfCache.getInstance(); + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + database = connProfCache.getDbForProfileId(profileId); + + dbconn = CommonLLTUtils.getDBConnection(); + } + + @After + public void tearDown() throws Exception + { + super.tearDown(); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().close(); + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) + { + connProfCache.removeServer(itr.next().getId()); + } + + connProfCache.closeAllNodes(); + } + + @Test + public void init_test() throws DatabaseCriticalException, DatabaseOperationException, SQLException { + TableObjectGroup tablesGroup = database.getAllNameSpaces().get(0).getTablesGroup(); + ERDiagramPresentation presentation = new ERDiagramPresentation(tablesGroup, dbconn); + presentation.initERPresentation(); + assertTrue(presentation.getWindowTitle() != null); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/EditTableDataHelper.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/EditTableDataHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..e6bd1ebe72f69ccae7baf67dca75a5ffda9b7f69 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/EditTableDataHelper.java @@ -0,0 +1,381 @@ +package org.opengauss.mppdbide.test.presentation.table; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; + +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintType; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DatabaseUtils; +import org.opengauss.mppdbide.bl.serverdatacache.DefaultParameter; +import org.opengauss.mppdbide.bl.serverdatacache.QueryResult; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TypeMetaData; +import org.opengauss.mppdbide.bl.sqlhistory.IQueryExecutionSummary; +import org.opengauss.mppdbide.bl.sqlhistory.QueryExecutionSummary; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.presentation.ContextExecutionOperationType; +import org.opengauss.mppdbide.presentation.EditTableDataCore; +import org.opengauss.mppdbide.presentation.ExecutionFailureActionOptions; +import org.opengauss.mppdbide.presentation.IEditTableDataCore; +import org.opengauss.mppdbide.presentation.IExecutionContext; +import org.opengauss.mppdbide.presentation.IResultDisplayUIManager; +import org.opengauss.mppdbide.presentation.TerminalExecutionConnectionInfra; +import org.opengauss.mppdbide.presentation.edittabledata.DSEditTableDataGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSEditGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IRowEffectedConfirmation; +import org.opengauss.mppdbide.presentation.resultset.ActionAfterResultFetch; +import org.opengauss.mppdbide.presentation.resultsetif.IResultConfig; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import org.opengauss.mppdbide.utils.messaging.MessageQueue; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import static org.junit.Assert.*; + +public class EditTableDataHelper +{ + + private Database database; + + private QueryResult result; + + public EditTableDataHelper(Database database) + { + this.database = database; + } + + public QueryResult getQueryResult() + { + return this.result; + } + + public EditTableDataCore getCoreObject() + { + IEditTableDataCore core = null; + try + { + Database database = this.database; + TableMetaData editTableMetadata = new TableMetaData(1, "EditTable", + database.getNameSpaceById(1), "tablespace"); + // add datatype to columns of a table + TypeMetaData type1 = new TypeMetaData(1, "bigint", + database.getNameSpaceById(1)); + TypeMetaData type2 = new TypeMetaData(2, "varchar", + database.getNameSpaceById(1)); + TypeMetaData type3 = new TypeMetaData(3, "integer", + database.getNameSpaceById(1)); + // add columns to the table + ColumnMetaData empId = new ColumnMetaData(editTableMetadata, 1, + "Emp_ID", type1); + empId.setDefaultValue("1"); + empId.setAttDefString(""); + ColumnMetaData empName = new ColumnMetaData(editTableMetadata, 2, + "Emp_NAME", type2); + empName.setDefaultValue("empname"); + empName.setAttDefString(""); + ColumnMetaData empAge = new ColumnMetaData(editTableMetadata, 3, + "EMP_AGE", type3); + empAge.setDefaultValue("21"); + empAge.setAttDefString("{CONST"); + empAge.setHasDefVal(true); + editTableMetadata.addColumn(empId); + editTableMetadata.addColumn(empName); + editTableMetadata.addColumn(empAge); + + // add constraint to the table + ConstraintMetaData primaryCons = new ConstraintMetaData(1, "Cons1", + ConstraintType.PRIMARY_KEY_CONSTRSINT); + editTableMetadata.addConstraint(primaryCons); + ConstraintMetaData uniqueCons = new ConstraintMetaData(2, "Cons2", + ConstraintType.UNIQUE_KEY_CONSTRSINT); + editTableMetadata.addConstraint(uniqueCons); + + // create edit table data core + core = new EditTableDataCore(); + core.init(editTableMetadata); + core.getTermConnection() + .setConnection(database.getConnectionManager().getFreeConnection()); + } + catch (DatabaseOperationException e) + { + System.out.println("database operation occurred"); + } + catch (MPPDBIDEException e) + { + System.out.println("MPPDBIDEException occurred"); + } + return (EditTableDataCore) core; + + } + + public IDSEditGridDataProvider getDataProvider( + PreparedStatementResultSetHandler preparedstatementHandler) + throws DatabaseCriticalException, DatabaseOperationException, + MPPDBIDEException + { + return prepareObjectsForProvider(preparedstatementHandler); + } + + public DSEditTableDataGridDataProvider prepareObjectsForProvider( + PreparedStatementResultSetHandler preparedstatementHandler) + throws DatabaseCriticalException, DatabaseOperationException, + MPPDBIDEException + { + CommonLLTUtils.prepareEditTableDataResultSet(preparedstatementHandler); + Database database = this.database; + DSEditTableDataGridDataProvider dataProvider = null; + EditTableDataCore coreObject = getCoreObject(); + result = DatabaseUtils.executeOnSqlTerminal(coreObject.getQuery(), 10, + database.getConnectionManager().getFreeConnection(), new MessageQueue()); + IResultConfig rsConfig = getResultConfig(); + IQueryExecutionSummary summary = getQueryExecutionSummary(); + IExecutionContext context = getExecutionContext(); + dataProvider = new DSEditTableDataGridDataProvider(result, rsConfig, + summary, context, false); + + return dataProvider; + } + + public IQueryExecutionSummary getQueryExecutionSummary() + { + QueryExecutionSummary queryExcSummary = null; + String input = "2016-12-16 18:29:09"; + + SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + sdf1.setTimeZone(TimeZone.getTimeZone("UTC")); + Date date; + try + { + date = sdf1.parse(input); + String dt = sdf1.format(date); + queryExcSummary = new QueryExecutionSummary("Gauss", "ds", + CommonLLTUtils.EDIT_TABLE_DATA_SELECT_QUERY, true, dt, 109, + 0); + } + catch (ParseException e) + { + System.out.println("Parse exception occurred"); + } + + return queryExcSummary; + } + + public List getUniqueKeys() + { + List uniqueKeyList = new ArrayList(); + uniqueKeyList.add("Emp_ID"); + uniqueKeyList.add("Emp_NAME"); + return uniqueKeyList; + + } + + public IRowEffectedConfirmation getRowEffectedConfirm(boolean success) + { + if (success) + { + return new IRowEffectedConfirmation() + { + + @Override + public void promptUerConfirmation() + { + + } + + }; + } + return new IRowEffectedConfirmation() + { + + @Override + public void promptUerConfirmation() + { + + } + + }; + } + + public IResultConfig getResultConfig() + { + return new IResultConfig() + { + + @Override + public int getFetchCount() + { + + return 100; + } + + @Override + public ActionAfterResultFetch getActionAfterFetch() + { + + return ActionAfterResultFetch.CLOSE_CONNECTION_AFTER_FETCH; + } + }; + } + + public IExecutionContext getExecutionContext() + { + return new IExecutionContext() + { + + @Override + public void setWorkingJobContext(Object jobContext) + { + + + } + + @Override + public void setJobDone() + { + + + } + + @Override + public void setCurrentExecution( + ContextExecutionOperationType contextOperationTypeNewPlSqlCreation) + { + + + } + + @Override + public void setCriticalErrorThrown(boolean b) + { + + + } + + @Override + public boolean needQueryParseAndSplit() + { + + return false; + } + + @Override + public String jobType() + { + + return null; + } + + @Override + public void handleSuccessfullCompletion() + { + + + } + + @Override + public void handleExecutionException(Exception e) + { + + + } + + @Override + public Object getWorkingJobContext() + { + + return null; + } + + @Override + public TerminalExecutionConnectionInfra getTermConnection() + { + + return getCoreObject().getTermConnection(); + } + + @Override + public IResultDisplayUIManager getResultDisplayUIManager() + { + + return null; + } + + @Override + public IResultConfig getResultConfig() + { + + return getResultConfig(); + } + + @Override + public String getQuery() + { + + return null; + } + + @Override + public MessageQueue getNoticeMessageQueue() + { + + return null; + } + + @Override + public ServerObject getCurrentServerObject() + { + + return getCoreObject().getTable(); + } + + @Override + public ContextExecutionOperationType getCurrentExecution() + { + + return null; + } + + @Override + public String getContextName() + { + + return null; + } + + @Override + public String getConnectionProfileID() + { + + return null; + } + + @Override + public ExecutionFailureActionOptions getActionOnQueryFailure() + { + + return null; + } + + @Override + public boolean canFreeConnectionAfterUse() + { + + return false; + } + + @Override + public ArrayList getInputValues() { + return null; + } + }; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/EditTableDataTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/EditTableDataTest.java new file mode 100644 index 0000000000000000000000000000000000000000..547414ed668b9b9ade2866649bf4eec2a2912620 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/EditTableDataTest.java @@ -0,0 +1,1304 @@ +package org.opengauss.mppdbide.test.presentation.table; + +import java.sql.Connection; +import java.sql.SQLException; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.sqlhistory.QueryExecutionSummary; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.presentation.EditTableDataCore; +import org.opengauss.mppdbide.presentation.IWindowDetail; +import org.opengauss.mppdbide.presentation.TerminalExecutionConnectionInfra; +import org.opengauss.mppdbide.presentation.edittabledata.CommitStatus; +import org.opengauss.mppdbide.presentation.edittabledata.DSEditTableDataGridDataProvider; +import org.opengauss.mppdbide.presentation.edittabledata.DSEditTableDataGridRow; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableCellState; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableRecordStates; +import org.opengauss.mppdbide.presentation.edittabledata.IDSGridEditDataRow; +import org.opengauss.mppdbide.presentation.edittabledata.QueryResultMaterializer; +import org.opengauss.mppdbide.presentation.grid.IDSEditGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.presentation.resultset.ConsoleDataWrapper; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.observer.DSEventTable; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; +import static org.junit.Assert.*; + +public class EditTableDataTest extends BasicJDBCTestCaseAdapter +{ + + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + EditTableDataHelper helper; + IDSEditGridDataProvider dataProvider; + EditTableDataCore coreObject; + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#setUp() + */ + @Before + public void setUp() throws Exception + { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + connection = new MockConnection(); + MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + MockPresentationBLPreferenceImpl.setFileEncoding("UTF-8"); + + preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + connProfCache = DBConnProfCache.getInstance(); + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + // serverInfo.setSslPassword("12345"); + // serverInfo.setServerType(DATABASETYPE.GAUSS); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + initializeHelper(); + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception + { + super.tearDown(); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().close(); + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) + { + connProfCache.removeServer(itr.next().getId()); + itr = connProfCache.getServers().iterator(); + } + + connProfCache.closeAllNodes(); + + } + + public void initializeHelper() + { + helper = new EditTableDataHelper( + connProfCache.getDbForProfileId(profileId)); + try + { + dataProvider = helper.getDataProvider(preparedstatementHandler); + coreObject = helper.getCoreObject(); + + } + catch (DatabaseCriticalException e) + { + e.printStackTrace(); + } + catch (DatabaseOperationException e) + { + e.printStackTrace(); + } + catch (MPPDBIDEException e) + { + e.printStackTrace(); + } + } + + // Edit Table Data core test begins + @Test + public void test_EditTableDataCore_getQuery() + { + + String query = coreObject.getQuery(); + assertEquals("select * from " + "pg_catalog.\"EditTable\"", query); + + } + + @Test + public void test_EditTableDataCore_getWindowTitle() + { + String windowTitle = coreObject.getWindowTitle(); + assertEquals("pg_catalog.EditTable-Gauss@TestConnectionName", + windowTitle); + } + + @Test + public void test_EditTableDataCore_getWindowDetails() + { + IWindowDetail windowDetail = null; + windowDetail = coreObject.getWindowDetails(); + assertNotNull(windowDetail); + assertEquals("pg_catalog.\"EditTable\"", + windowDetail.getShortTitle()); + assertEquals("pg_catalog.EditTable-Gauss@TestConnectionName", + windowDetail.getTitle()); + assertEquals( + "EDIT_TABLE_DATA" + + "pg_catalog.EditTable-Gauss@TestConnectionName", + windowDetail.getUniqueID()); + assertNull(windowDetail.getIcon()); + assertEquals(true, windowDetail.isCloseable()); + + } + + @Test + public void test_EditTableDataCore_getTermConnection() + { + TerminalExecutionConnectionInfra termConnection = coreObject + .getTermConnection(); + assertNotNull(termConnection); + } + + @Test + public void test_EditTableDataCore_getTable() + { + TableMetaData table = coreObject.getTable(); + assertEquals("EditTable", table.getName()); + } + + @Test + public void test_EditTableDataCore_getProgressBarLabel() { + String progressBarLabel = coreObject.getProgressBarLabel(); + assertEquals("Editing table data query: EditTable.pg_catalog.Gauss@TestConnectionName", progressBarLabel); + } + + @Test + public void test_EditTableDataCore_isTableDropped() { + + assertEquals(true, coreObject.isTableDropped()); + } + // Edit Table Data core test ends + + + @Test + public void test_DSEditTableDataGridProvider_init_WithReplicationDistribution() + { + + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithReplicationDistribution( + preparedstatementHandler); + try + { + this.dataProvider.init(); + assertEquals(0, + this.dataProvider.getDistributedColumnList().size()); + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + + } + + @Test + public void test_DSEditTableDataGridProvider_getEmptyRowForInsert_1() + { + + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + try + { + dataProvider.init(); + + assertNotNull(dataProvider.getEmptyRowForInsert(0)); + + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + + } + + @Test + public void test_DSEditTableDataGridProvider_getEmptyRowForInsert_2() + { + + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + try + { + dataProvider.init(); + + IDSGridEditDataRow emptyRowForInsert = this.dataProvider + .getEmptyRowForInsert(0); + assertEquals(null, emptyRowForInsert.getValue(2)); + + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + + } + + @Test + public void test_DSEditTableDataGridProvider_isEditSupported() + { + assertTrue(this.dataProvider.isEditSupported()); + } + + @Test + public void test_QueryResultMaterializer_materializeQueryResult_1() throws SQLException + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + try + { + QueryExecutionSummary queryExecutionSummary = (QueryExecutionSummary) helper + .getQueryExecutionSummary(); + queryExecutionSummary.startQueryTimer(); + Object obj = QueryResultMaterializer.materializeQueryResult( + helper.getQueryResult(), helper.getResultConfig(), + queryExecutionSummary, new ConsoleDataWrapper(), + helper.getExecutionContext(), true, false, null, false); + assertNotNull(obj); + } + catch (DatabaseCriticalException e) + { + fail("not exptected"); + } + catch (DatabaseOperationException e) + { + fail("not exptected"); + + } + + } + + @Test + public void test_QueryResultMaterializer_materializeQueryResult_2() throws SQLException + { + try + { + QueryExecutionSummary queryExecutionSummary = (QueryExecutionSummary) helper + .getQueryExecutionSummary(); + queryExecutionSummary.startQueryTimer(); + Object obj = QueryResultMaterializer.materializeQueryResult( + helper.getQueryResult(), helper.getResultConfig(), + queryExecutionSummary, new ConsoleDataWrapper(), + helper.getExecutionContext(), false, false, null, false); + assertNotNull(obj); + } + catch (DatabaseCriticalException e) + { + fail("not exptected"); + } + catch (DatabaseOperationException e) + { + fail("not exptected"); + + } + + } + + @Test + public void test_DSEditTableDataGridProvider_getConsolidatedRows_1() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + try + { + dataProvider.init(); + dataProvider.getEmptyRowForInsert(0); + int size = dataProvider.getConsolidatedRows().size(); + assertEquals(8, size); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (DatabaseCriticalException e) + { + fail("not exptected"); + + } + } + + @Test + public void test_DSEditTableDataGridProvider_getConsolidatedRows_2() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + try + { + dataProvider.init(); + int size = dataProvider.getConsolidatedRows().size(); + assertEquals(7, size); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + + } + } + + @Test + public void test_DSEditTableDataGridProvider_deleteRecord_1() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + try + { + dataProvider.init(); + List consolidatedRows = dataProvider + .getConsolidatedRows(); + dataProvider.deleteRecord( + (IDSGridEditDataRow) consolidatedRows.get(0), false); + int deleteListSize = dataProvider.getDeletedRowCount(); + assertEquals(1, deleteListSize); + + } + catch (DatabaseOperationException e) + { + fail("not exptected"); + + } + catch (DatabaseCriticalException e) + { + fail("not exptected"); + + } + } + + @Test + public void test_DSEditTableDataGridProvider_deleteRecord_2() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + try + { + dataProvider.init(); + dataProvider.getEmptyRowForInsert(0); + dataProvider.getEmptyRowForInsert(1); + List consolidatedRows = dataProvider + .getConsolidatedRows(); + assertEquals(2, dataProvider.getInsertedRowCount()); + dataProvider.deleteRecord( + (IDSGridEditDataRow) consolidatedRows.get(0), true); + int deleteListSize = dataProvider.getDeletedRowCount(); + int insertListSize = dataProvider.getInsertedRowCount(); + assertEquals(0, deleteListSize); + assertEquals(1, insertListSize); + + } + catch (DatabaseOperationException e) + { + fail("not exptected"); + + } + catch (DatabaseCriticalException e) + { + fail("not exptected"); + + } + } + + @Test + public void test_DSEditTableDataGridProvider_getUniquekeys() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + try + { + dataProvider.init(); + assertTrue(dataProvider.isUniqueKeyPresent()); + + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + } + + @Test + public void test_DSEditTableDataGridProvider_getEditTable() + { + DSEditTableDataGridDataProvider provider = (DSEditTableDataGridDataProvider)dataProvider; + TableMetaData editTable = (TableMetaData) provider.getTable(); + assertEquals("EditTable", editTable.getName()); + } + + @Test + public void test_DSEditTableDataGridProvider_isDistributionColumn() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + try + { + this.dataProvider.init(); + dataProvider.getDistributedColumnList().add("Emp_ID"); + assertEquals(false, this.dataProvider.isDistributionColumn(0)); + assertEquals(false, this.dataProvider.isDistributionColumn(1)); + assertEquals(false, this.dataProvider.isDistributionColumn(2)); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + } + + @Test + public void test_DSEditTableDataGridProvider_getUniqueKeys() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + + try + { + this.dataProvider.init(); + List uniqueKeys = ((DSEditTableDataGridDataProvider) this.dataProvider) + .getUniqueKeys(); + int numberOfUniquekeys = ((TableMetaData) this.dataProvider.getTable()) + .getColumnMetaDataList().size(); + assertEquals(numberOfUniquekeys, uniqueKeys.size()); + + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + + } + + } + + @Test + public void test_DSEditTableDataGridProvider_isGridDataEdited() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + + try + { + boolean gridDataEdited = this.dataProvider.isGridDataEdited(); + this.dataProvider.init(); + assertEquals(false, gridDataEdited); + IDSGridDataRow idsGridDataRow = this.dataProvider + .getConsolidatedRows().get(0); + this.dataProvider.deleteRecord((IDSGridEditDataRow) idsGridDataRow, + false); + boolean afterDeleting = this.dataProvider.isGridDataEdited(); + ; + assertTrue(afterDeleting); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + + } + + @Test + public void test_DSEditTableDataGridProvider_rollBack() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + try + { + this.dataProvider.init(); + IDSGridEditDataRow emptyRowForInsert = this.dataProvider.getEmptyRowForInsert(0); + this.dataProvider.getEmptyRowForInsert(1); + this.dataProvider.getEmptyRowForInsert(2); + List consolidatedRows = this.dataProvider + .getConsolidatedRows(); + assertEquals(10, consolidatedRows.size()); + assertEquals(3, this.dataProvider.getInsertedRowCount()); + this.dataProvider.rollBackProvider(); + assertEquals(7, this.dataProvider.getConsolidatedRows().size()); + assertEquals(0, this.dataProvider.getInsertedRowCount()); + + assertEquals(emptyRowForInsert.getCommitStatusMessage(), ""); + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + + } + + @Test + public void test_getOriginalValue_success() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + + try + { + this.dataProvider.init(); + IDSGridEditDataRow emptyRowForInsert = this.dataProvider + .getEmptyRowForInsert(0); + emptyRowForInsert.setValue(0, "11"); + assertNull(emptyRowForInsert.getOriginalValue(0)); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + + } + + } + + @Test + public void test_getUpdatedState_success() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + + try + { + this.dataProvider.init(); + IDSGridEditDataRow emptyRowForInsert = this.dataProvider + .getEmptyRowForInsert(0); + assertEquals(EditTableRecordStates.INSERT, + emptyRowForInsert.getUpdatedState()); + + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + + } + + } + + @Test + public void test_DSEditTableDataGridProvider_isDistributionColumnsRequired() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + + try + { + this.dataProvider.init(); + assertEquals(false, + this.dataProvider.isDistributionColumnsRequired()); + this.dataProvider + .deleteRecord((IDSGridEditDataRow) this.dataProvider + .getConsolidatedRows().get(0), false); + assertTrue(this.dataProvider.isDistributionColumnsRequired()); + + } + catch (DatabaseOperationException e) + { + fail("not expected"); + + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + + } + } + + @Test + public void test_DSEditTableDataGridProvider_Commit_updateRowsFailure() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + CommonLLTUtils.prepareUpdateQueryForEditTableData( + preparedstatementHandler, connection); + + try + { + dataProvider.init(); + IDSGridDataRow idsGridDataRow = this.dataProvider + .getAllFetchedRows().get(0); + ((IDSGridEditDataRow) idsGridDataRow).setValue(0, "101"); + ((IDSGridEditDataRow) idsGridDataRow).setValue(1, "newItem1"); + ((IDSGridEditDataRow) idsGridDataRow).setValue(2, "25"); + dataProvider.commit(helper.getUniqueKeys(), true, + helper.getRowEffectedConfirm(false), CommonLLTUtils.getDBConnection()); + + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + assertTrue(true); + } + catch (MPPDBIDEException e) + { + fail("not expected"); + } + } + + @Test + public void test_DSEditTableDataGridProvider_Commit_insertRows() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + CommonLLTUtils.prepareInsertQueryForEditTableData( + preparedstatementHandler, connection); + + try + { + dataProvider.init(); + IDSGridEditDataRow emptyRowForInsert = dataProvider + .getEmptyRowForInsert(0); + ((IDSGridEditDataRow) emptyRowForInsert).setValue(0, "101"); + ((IDSGridEditDataRow) emptyRowForInsert).setValue(1, "newItem1"); + ((IDSGridEditDataRow) emptyRowForInsert).setValue(2, "25"); + dataProvider.commit(helper.getUniqueKeys(), true, + helper.getRowEffectedConfirm(false), CommonLLTUtils.getDBConnection()); + + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (MPPDBIDEException e) + { + fail("not expected"); + } + } + + @Test + public void test_DSEditTableDataGridProvider_Commit_deleteRows() + { + + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + + try + { + dataProvider.init(); + IDSGridDataRow idsGridDataRow = this.dataProvider + .getAllFetchedRows().get(0); + this.dataProvider.deleteRecord((IDSGridEditDataRow) idsGridDataRow, + false); + CommitStatus commit = dataProvider.commit(helper.getUniqueKeys(), + true, helper.getRowEffectedConfirm(false), CommonLLTUtils.getDBConnection()); + assertEquals(1, commit.getListOfFailureRows().size()); + + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + assertTrue(true); + } + catch (MPPDBIDEException e) + { + fail("not expected"); + } + } + + + + @Test + public void test_DSEditTableDataGridProvider_Commit_updateRows_success() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + CommonLLTUtils.prepareUpdateQueryForEditTableData( + preparedstatementHandler, connection); + + try + { + dataProvider.init(); + this.dataProvider.getEmptyRowForInsert(0); + int size = this.dataProvider.getAllFetchedRows().size(); + IDSGridDataRow idsGridDataRowForDeletion = this.dataProvider + .getAllFetchedRows().get(size - 1); + this.dataProvider.deleteRecord( + (IDSGridEditDataRow) idsGridDataRowForDeletion, false); + IDSGridDataRow idsGridDataRow = this.dataProvider + .getAllFetchedRows().get(0); + ((IDSGridEditDataRow) idsGridDataRow).setValue(0, "101"); + ((IDSGridEditDataRow) idsGridDataRow).setValue(1, "newItem1"); + ((IDSGridEditDataRow) idsGridDataRow).setValue(2, "25"); + dataProvider.getDistributedColumnList().add("Emp_ID"); + dataProvider.commit(helper.getUniqueKeys(), true, + helper.getRowEffectedConfirm(false), CommonLLTUtils.getDBConnection()); + + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + assertTrue(true); + } + catch (MPPDBIDEException e) + { + fail("not expected"); + } + } + + @Test + public void test_insertRowsNotAtomic() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + CommonLLTUtils.prepareInsertQueryForEditTableData( + preparedstatementHandler, connection); + + try + { + dataProvider.init(); + IDSGridEditDataRow emptyRowForInsert = dataProvider + .getEmptyRowForInsert(0); + ((IDSGridEditDataRow) emptyRowForInsert).setValue(0, "101"); + ((IDSGridEditDataRow) emptyRowForInsert).setValue(1, "newItem1"); + ((IDSGridEditDataRow) emptyRowForInsert).setValue(2, "25"); + dataProvider.commit(helper.getUniqueKeys(), false, + helper.getRowEffectedConfirm(false), CommonLLTUtils.getDBConnection()); + + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (MPPDBIDEException e) + { + fail("not expected"); + } + } + + @Test + public void test_undoRowUpdate() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + CommonLLTUtils.prepareInsertQueryForEditTableData( + preparedstatementHandler, connection); + + try + { + dataProvider.init(); + IDSGridEditDataRow emptyRowForInsert = dataProvider + .getEmptyRowForInsert(0); + ((IDSGridEditDataRow) emptyRowForInsert).setValue(0, "101"); + ((IDSGridEditDataRow) emptyRowForInsert).undo(0); + Object value = ((IDSGridEditDataRow) emptyRowForInsert).getValue(0); + assertNull(value); +// ((IDSGridEditDataRow) emptyRowForInsert).setValue(1, "newItem1"); +// ((IDSGridEditDataRow) emptyRowForInsert).setValue(2, "25"); +// dataProvider.commit(helper.getUniqueKeys(), false, +// helper.getRowEffectedConfirm(false)); + + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (MPPDBIDEException e) + { + fail("not expected"); + } + } + + @Test + public void test_undo_For_UPDATED_ROW() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + CommonLLTUtils.prepareInsertQueryForEditTableData( + preparedstatementHandler, connection); + + try + { + dataProvider.init(); + List allFetchedRows = dataProvider.getAllFetchedRows(); + if (allFetchedRows.size() > 0) + { + IDSGridEditDataRow editRow = (IDSGridEditDataRow) allFetchedRows.get(0); + Object earlierVal = ((IDSGridEditDataRow) editRow).getValue(0); + editRow.setValue(0, "101"); + ((IDSGridEditDataRow) editRow).undo(0); + Object value = ((IDSGridEditDataRow) editRow).getValue(0); + assertEquals(earlierVal, value); + } + else + { + fail("Expected rows more than 0"); + } + + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (MPPDBIDEException e) + { + fail("not expected"); + } + } + + @Test + public void test_getClonedValues() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + CommonLLTUtils.prepareInsertQueryForEditTableData( + preparedstatementHandler, connection); + + try + { + dataProvider.init(); + IDSGridEditDataRow emptyRowForInsert = dataProvider + .getEmptyRowForInsert(0); + ((IDSGridEditDataRow) emptyRowForInsert).setValue(0, "101"); + Object[] clonedValues = emptyRowForInsert.getClonedValues(); + + assertEquals(clonedValues.length, 3); + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (MPPDBIDEException e) + { + fail("not expected"); + } + } + + @Test + public void test_getUpdatedState_INSERTED_ROW() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + CommonLLTUtils.prepareInsertQueryForEditTableData( + preparedstatementHandler, connection); + + try + { + dataProvider.init(); + IDSGridEditDataRow emptyRowForInsert = dataProvider + .getEmptyRowForInsert(0); + + emptyRowForInsert.setValue(0, "101"); + assertEquals(emptyRowForInsert.getUpdatedState(0), EditTableRecordStates.INSERT); + + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (MPPDBIDEException e) + { + fail("not expected"); + } + } + + @Test + public void test_getUpdatedState_UPDATED_ROW() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + CommonLLTUtils.prepareInsertQueryForEditTableData( + preparedstatementHandler, connection); + + try + { + dataProvider.init(); + List allFetchedRows = dataProvider.getAllFetchedRows(); + if (allFetchedRows.size() > 0) + { + IDSGridEditDataRow editRow = (IDSGridEditDataRow) allFetchedRows.get(0); + editRow.setValue(0, "101"); + assertEquals(editRow.getUpdatedState(0), EditTableRecordStates.UPDATE); + } + else + { + fail("Expected rows more than 0"); + } + + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (MPPDBIDEException e) + { + fail("not expected"); + } + } + + @Test + public void test_updateRowsNotAtomic() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + CommonLLTUtils.prepareUpdateQueryForEditTableData( + preparedstatementHandler, connection); + + try + { + dataProvider.init(); + IDSGridDataRow idsGridDataRow = this.dataProvider + .getAllFetchedRows().get(0); + ((IDSGridEditDataRow) idsGridDataRow).setValue(0, "101"); + ((IDSGridEditDataRow) idsGridDataRow).setValue(1, "newItem1"); + ((IDSGridEditDataRow) idsGridDataRow).setValue(2, "25"); + dataProvider.commit(helper.getUniqueKeys(), false, + helper.getRowEffectedConfirm(false), CommonLLTUtils.getDBConnection()); + + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + assertTrue(true); + } + catch (MPPDBIDEException e) + { + fail("not expected"); + } + } + + @Test + public void test_deleteRowsNotAtomic() + { + + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + + try + { + dataProvider.init(); + IDSGridDataRow idsGridDataRow = this.dataProvider + .getAllFetchedRows().get(0); + this.dataProvider.deleteRecord((IDSGridEditDataRow) idsGridDataRow, + false); + dataProvider.commit(helper.getUniqueKeys(), false, + helper.getRowEffectedConfirm(false), CommonLLTUtils.getDBConnection()); + + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + assertTrue(true); + } + catch (MPPDBIDEException e) + { + fail("not expected"); + } + } + + @Test + public void test_successRowsCount() + { + + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + CommonLLTUtils.prepareInsertQueryForEditTableData( + preparedstatementHandler, connection); + + try + { + dataProvider.init(); + IDSGridEditDataRow emptyRowForInsert = dataProvider + .getEmptyRowForInsert(0); + ((IDSGridEditDataRow) emptyRowForInsert).setValue(0, "101"); + ((IDSGridEditDataRow) emptyRowForInsert).setValue(1, "newItem1"); + ((IDSGridEditDataRow) emptyRowForInsert).setValue(2, "25"); + + CommitStatus commit = dataProvider.commit(helper.getUniqueKeys(), + true, helper.getRowEffectedConfirm(false), CommonLLTUtils.getDBConnection()); + List listOfRows = new ArrayList<>(); + + for (IDSGridDataRow row : dataProvider.getAllFetchedRows()) + { + listOfRows.add((IDSGridEditDataRow) row); + } + commit.setListOfSuccessRows(listOfRows); + assertEquals(7, commit.getListOfSuccessRows().size()); + + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (MPPDBIDEException e) + { + fail("not expected"); + } + } + + @Test + public void test_updateRowsCount() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + CommonLLTUtils.prepareInsertQueryForEditTableData( + preparedstatementHandler, connection); + try + { + + dataProvider.init(); + IDSGridEditDataRow emptyRowForInsert = dataProvider + .getEmptyRowForInsert(0); + ((IDSGridEditDataRow) emptyRowForInsert).setValue(0, "101"); + ((IDSGridEditDataRow) emptyRowForInsert).setValue(1, "newItem1"); + ((IDSGridEditDataRow) emptyRowForInsert).setValue(2, "25"); + + CommitStatus commit = dataProvider.commit(helper.getUniqueKeys(), + true, helper.getRowEffectedConfirm(false), CommonLLTUtils.getDBConnection()); + List listOfRows = new ArrayList<>(); + + for (IDSGridDataRow row : dataProvider.getAllFetchedRows()) + { + listOfRows.add((IDSGridEditDataRow) row); + } + commit.setUpdatedRecords(listOfRows.size()); + + IDSGridEditDataRow idsGridEditDataRow = listOfRows.get(0); + idsGridEditDataRow.setCellSatus(EditTableCellState.MODIFIED, 0); + assertEquals(EditTableCellState.MODIFIED, idsGridEditDataRow.getCellStatus(0)); + assertEquals(7, commit.getUpdatedRecords()); + + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (DatabaseOperationException e) + { + assertTrue(true); + } + catch (MPPDBIDEException e) + { + fail("not expected"); + } + } + + @Test + public void test_getUpdatedRecords() + { + DSEventTable eventTable = new DSEventTable(); + + DSEditTableDataGridRow gridRow = new DSEditTableDataGridRow(false, 0, + eventTable, (DSEditTableDataGridDataProvider) dataProvider); + assertEquals(0, gridRow.getUpdatedRecords()); + + } + + @Test + public void test_EditTableDataGridDataProvider_NoColumnDetails() + { + assertEquals(dataProvider.getColumnCount(), 0); + assertNull(dataProvider.getColumnDataProvider()); + assertNull(dataProvider.getColumnNames()); + assertNull(dataProvider.getColumnDataTypeNames()); + ((DSEditTableDataGridDataProvider) dataProvider).changeEncoding("UTF-8"); + dataProvider.preDestroy(); + assertFalse(dataProvider.isDistributionColumn(0)); + assertNull(dataProvider.getDistributedColumnList()); + assertNull(dataProvider.getDatabse()); + } + + @Test + public void test_commit_error_flow() + { + assertNotNull(dataProvider.getDatabse()); + CommitStatus commit = null; + try + { + commit = dataProvider.commit(null, + true, helper.getRowEffectedConfirm(false), CommonLLTUtils.getDBConnection()); + } + catch (NullPointerException e) + { + assertTrue(true); + } + catch (MPPDBIDEException e) + { + fail("fail"); + } + assertNotNull(commit); + try + { + dataProvider.cancelCommit(); + } + catch (DatabaseCriticalException | DatabaseOperationException e) + { + fail("fail"); + } + assertNotNull(dataProvider.getLastCommitStatus()); + dataProvider.setCancel(true); + assertEquals(0, dataProvider.getLastCommitStatus().getListOfFailureRows().size()); + assertEquals(0, dataProvider.getLastCommitStatus().getListOfSuccessRows().size()); + assertEquals(0, dataProvider.getLastCommitStatus().getUpdatedRecords()); + assertNotNull(dataProvider.getTableName()); + dataProvider.preDestroy(); + assertFalse(dataProvider.isUniqueKeyPresent()); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/EditTableExecuteQueryTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/EditTableExecuteQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..94561f52a4ab279276a7b2395822f16e0628640e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/EditTableExecuteQueryTest.java @@ -0,0 +1,176 @@ +package org.opengauss.mppdbide.test.presentation.table; + +import static org.junit.Assert.*; + +import java.util.Iterator; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.presentation.EditTableDataCore; +import org.opengauss.mppdbide.presentation.edittabledata.DSEditTableDataGridDataProvider; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableExecuteQueryFactory; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableExecuteQueryUtility; +import org.opengauss.mppdbide.presentation.edittabledata.IDSGridEditDataRow; +import org.opengauss.mppdbide.presentation.grid.IDSEditGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.utils.JSQLParserUtils; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; + +public class EditTableExecuteQueryTest extends BasicJDBCTestCaseAdapter { + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + EditTableDataHelper helper; + IDSEditGridDataProvider dataProvider; + EditTableDataCore coreObject; + + @Before + public void setUp() throws Exception { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + connection = new MockConnection(); + MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + preparedstatementHandler = connection.getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + connProfCache = DBConnProfCache.getInstance(); + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + MockPresentationBLPreferenceImpl.setFileEncoding("UTF-8"); + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + initializeHelper(); + } + + @After + public void tearDown() throws Exception { + super.tearDown(); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().close(); + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) { + connProfCache.removeServer(itr.next().getId()); + itr = connProfCache.getServers().iterator(); + } + + connProfCache.closeAllNodes(); + + } + + public void initializeHelper() { + helper = new EditTableDataHelper(connProfCache.getDbForProfileId(profileId)); + try { + dataProvider = helper.getDataProvider(preparedstatementHandler); + coreObject = helper.getCoreObject(); + + } catch (DatabaseCriticalException e) { + e.printStackTrace(); + } catch (DatabaseOperationException e) { + e.printStackTrace(); + } catch (MPPDBIDEException e) { + e.printStackTrace(); + } + } + + @Test + public void testExecuteInsertRowCommandWhenTableIsNull() { + CommonLLTUtils.prepareDistibutionColumnListResultSetWithHashDistribution(preparedstatementHandler); + + try { + dataProvider.init(); + List consolidatedRows = dataProvider.getConsolidatedRows(); + dataProvider.deleteRecord((IDSGridEditDataRow) consolidatedRows.get(0), false); + String[] fullTableName = JSQLParserUtils.getSplitQualifiedName(coreObject.getTable().getName(), false); + EditTableExecuteQueryUtility editTableExcutequery = + EditTableExecuteQueryFactory.getEditTableExecuteQuery(dataProvider.getDatabse().getDBType()); + boolean flag = editTableExcutequery.executeInsertRowCommand((IDSGridEditDataRow) consolidatedRows.get(0), + (IDSGridEditDataRow) consolidatedRows.get(0), (DSEditTableDataGridDataProvider) dataProvider, null, + coreObject.getTermConnection().getConnection(), fullTableName, true, true); + assertTrue(flag); + } catch (DatabaseOperationException e) { + fail("not expected"); + } catch (DatabaseCriticalException e) { + fail("not expected"); + } catch (MPPDBIDEException e) { + fail("not expected"); + } + } + + @Test + public void testExecuteInsertRowCommandWhenTableNotNull() { + CommonLLTUtils.prepareDistibutionColumnListResultSetWithHashDistribution(preparedstatementHandler); + + try { + dataProvider.init(); + List consolidatedRows = dataProvider.getConsolidatedRows(); + dataProvider.deleteRecord((IDSGridEditDataRow) consolidatedRows.get(0), false); + EditTableExecuteQueryUtility editTableExcutequery = + EditTableExecuteQueryFactory.getEditTableExecuteQuery(dataProvider.getDatabse().getDBType()); + boolean flag = editTableExcutequery.executeInsertRowCommand((IDSGridEditDataRow) consolidatedRows.get(6), + (IDSGridEditDataRow) consolidatedRows.get(0), (DSEditTableDataGridDataProvider) dataProvider, + coreObject.getTable(), coreObject.getTermConnection().getConnection(), null, true, true); + assertTrue(flag); + } catch (DatabaseOperationException e) { + fail("not expected"); + } catch (DatabaseCriticalException e) { + fail("not expected"); + } catch (MPPDBIDEException e) { + fail("not expected"); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/EditTableExecuteQueryUtilityTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/EditTableExecuteQueryUtilityTest.java new file mode 100644 index 0000000000000000000000000000000000000000..6c029617300fcb6b79a28e59fb59ddd6b74bca15 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/EditTableExecuteQueryUtilityTest.java @@ -0,0 +1,287 @@ +package org.opengauss.mppdbide.test.presentation.table; + +import java.util.Iterator; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.*; + +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils.EXCEPTIONENUM; +import org.opengauss.mppdbide.mock.presentation.ExceptionConnection; +import org.opengauss.mppdbide.presentation.EditTableDataCore; +import org.opengauss.mppdbide.presentation.edittabledata.DSEditTableDataGridDataProvider; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableExecuteQueryFactory; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableExecuteQueryUtility; +import org.opengauss.mppdbide.presentation.edittabledata.IDSGridEditDataRow; +import org.opengauss.mppdbide.presentation.grid.IDSEditGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.utils.JSQLParserUtils; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; + +public class EditTableExecuteQueryUtilityTest extends BasicJDBCTestCaseAdapter +{ + + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + EditTableDataHelper helper; + IDSEditGridDataProvider dataProvider; + EditTableDataCore coreObject; + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#setUp() + */ + @Before + public void setUp() throws Exception + { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + connection = new MockConnection(); + MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + connProfCache = DBConnProfCache.getInstance(); + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + MockPresentationBLPreferenceImpl.setFileEncoding("UTF-8"); + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + // serverInfo.setSslPassword("12345"); + // serverInfo.setServerType(DATABASETYPE.GAUSS); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + initializeHelper(); + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception + { + super.tearDown(); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().close(); + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) + { + connProfCache.removeServer(itr.next().getId()); + itr = connProfCache.getServers().iterator(); + } + + connProfCache.closeAllNodes(); + + } + + public void initializeHelper() + { + helper = new EditTableDataHelper( + connProfCache.getDbForProfileId(profileId)); + try + { + dataProvider = helper.getDataProvider(preparedstatementHandler); + coreObject = helper.getCoreObject(); + + } + catch (DatabaseCriticalException e) + { + e.printStackTrace(); + } + catch (DatabaseOperationException e) + { + e.printStackTrace(); + } + catch (MPPDBIDEException e) + { + e.printStackTrace(); + } + } + + @Test + public void test_EditTableExecuteQuery_executeDeleteRowCommand() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + + try + { + dataProvider.init(); + List consolidatedRows = dataProvider + .getConsolidatedRows(); + dataProvider.deleteRecord( + (IDSGridEditDataRow) consolidatedRows.get(0), false); + TableMetaData table = coreObject.getTable(); + EditTableExecuteQueryUtility editTableExcutequery = + EditTableExecuteQueryFactory.getEditTableExecuteQuery(dataProvider.getDatabse().getDBType()); + boolean flag = editTableExcutequery.executeDeleteRowCommand( + (IDSGridEditDataRow) consolidatedRows.get(0), + JSQLParserUtils.getSplitQualifiedName(table.getDisplayName(), false), + (DSEditTableDataGridDataProvider) dataProvider, + coreObject.getTermConnection().getConnection(), + helper.getUniqueKeys(), + dataProvider.getColumnDataProvider(), + helper.getRowEffectedConfirm(false), true); + assertTrue(flag); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (MPPDBIDEException e) + { + fail("not expected"); + } + + } + + @Test + public void test_executeDeleteRowCommand_SQLException() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + + + try + { + dataProvider.init(); + List consolidatedRows = dataProvider + .getConsolidatedRows(); + ExceptionConnection exceptionConnection = new ExceptionConnection(); + exceptionConnection.setNeedExceptioStatement(true); + exceptionConnection.setNeedExceptionResultset(true); + exceptionConnection.setThrowExceptionNext(true); + exceptionConnection.setThrownResultSetNext(EXCEPTIONENUM.EXCEPTION); + getJDBCMockObjectFactory().getMockDriver() + .setupConnection(exceptionConnection); + dataProvider.deleteRecord( + (IDSGridEditDataRow) consolidatedRows.get(0), false); + TableMetaData table = coreObject.getTable(); + EditTableExecuteQueryUtility editTableExcutequery = + EditTableExecuteQueryFactory.getEditTableExecuteQuery(dataProvider.getDatabse().getDBType()); + editTableExcutequery.executeDeleteRowCommand( + (IDSGridEditDataRow) consolidatedRows.get(0), + JSQLParserUtils.getSplitQualifiedName(table.getDisplayName(), false), + (DSEditTableDataGridDataProvider) dataProvider, + coreObject.getTermConnection().getConnection(), + helper.getUniqueKeys(), + dataProvider.getColumnDataProvider(), + helper.getRowEffectedConfirm(false), true); + + } + catch (DatabaseOperationException e) + { + assertTrue(true); + } + catch (MPPDBIDEException e) + { + fail("not expected"); + + } + } + + + @Test + public void test_EditTableExecuteQuery_executeInsertRowCommand() + { + CommonLLTUtils + .prepareDistibutionColumnListResultSetWithHashDistribution( + preparedstatementHandler); + + try + { + dataProvider.init(); + List consolidatedRows = dataProvider + .getConsolidatedRows(); + dataProvider.deleteRecord( + (IDSGridEditDataRow) consolidatedRows.get(0), false); + EditTableExecuteQueryUtility editTableExcutequery = + EditTableExecuteQueryFactory.getEditTableExecuteQuery(dataProvider.getDatabse().getDBType()); + boolean flag = editTableExcutequery.executeInsertRowCommand( + (IDSGridEditDataRow) consolidatedRows.get(0), + (IDSGridEditDataRow) consolidatedRows.get(0), + (DSEditTableDataGridDataProvider) dataProvider, null, + coreObject.getTermConnection().getConnection(), + null, true, true); + assertTrue(flag); + } + catch (DatabaseOperationException e) + { + fail("not expected"); + } + catch (DatabaseCriticalException e) + { + fail("not expected"); + } + catch (MPPDBIDEException e) + { + fail("not expected"); + } + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/GenerateSQLDataCoreTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/GenerateSQLDataCoreTest.java new file mode 100644 index 0000000000000000000000000000000000000000..6e384799c2dd6d4fda152dd82066ec80f8c6de3c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/GenerateSQLDataCoreTest.java @@ -0,0 +1,789 @@ +package org.opengauss.mppdbide.test.presentation.table; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Properties; + +import org.hamcrest.CoreMatchers; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.postgresql.util.HostSpec; +import static org.junit.Assert.*; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.importexportdata.ImportExportDataExecuter; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ImportExportOption; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.SystemNamespace; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TypeMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.mock.presentation.BaseConnectionHelper; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.mock.presentation.ResultSetMetaDataImplementation; +import org.opengauss.mppdbide.presentation.exportdata.ExportCursorQueryExecuter; +import org.opengauss.mppdbide.presentation.exportdata.GenerateCursorExecuteVisitor; +import org.opengauss.mppdbide.presentation.exportdata.GenerateSQLDataCore; +import org.opengauss.mppdbide.presentation.exportdata.ImportExportDataCore; +import org.opengauss.mppdbide.utils.ConvertValueToInsertSqlFormat; +import org.opengauss.mppdbide.utils.CustomStringUtility; +import org.opengauss.mppdbide.utils.JSQLParserUtils; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; +import com.mockrunner.mock.jdbc.MockResultSet; + +public class GenerateSQLDataCoreTest extends BasicJDBCTestCaseAdapter +{ + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + + private DBConnection dbconn; + + @Before + public void setUp() throws Exception + { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + connection = new MockConnection(); + MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + this.dbconn = CommonLLTUtils.getDBConnection(); + preparedstatementHandler = connection.getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + + connProfCache = DBConnProfCache.getInstance(); + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + MockPresentationBLPreferenceImpl.setFileEncoding("UTF-8"); + + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + // serverInfo.setSslPassword("12345"); + // serverInfo.setServerType(DATABASETYPE.GAUSS); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception + { + super.tearDown(); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().close(); + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) + { + connProfCache.removeServer(itr.next().getId()); + } + + connProfCache.closeAllNodes(); + + } + + @Test + public void test_Generate_Insert_Sql_001() + { + try + { + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + Server server = new Server(serverInfo); + Database database = new Database(server, 2, "Gauss"); + Properties properties = new Properties(); + + properties.setProperty("user", serverInfo.getDsUsername()); + properties.setProperty("password", new String(serverInfo.getPrd())); + properties.setProperty("allowEncodingChanges", "true"); + String encoding = System.getProperty("file.encoding"); + properties.setProperty("characterEncoding", encoding); + properties.setProperty("ApplicationName", "Data Studio"); + + BaseConnectionHelper connectionHelper = + new BaseConnectionHelper("", properties, new HostSpec[] {new HostSpec("127.0.0.1", 5432)}, + serverInfo.getDatabaseName(), serverInfo.getDsUsername(), false); + + getJDBCMockObjectFactory().getMockDriver().setupConnection(connectionHelper); + CommonLLTUtils.mockServerEncoding(connectionHelper.getPreparedStatementResultSetHandler()); + + database.connectToServer(); + Namespace namespace = new SystemNamespace(1, "pg_catalog", database); + database.getSystemNamespaceGroup().addToGroup((SystemNamespace) namespace); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + String queryTerminal = "select * from pg_catalog.\"MyTable\" ;"; + Path path = Paths.get("121.sql"); + GenerateSQLDataCore core = + new GenerateSQLDataCore(database, queryTerminal, encoding, serverInfo.getDsUsername()); + core.initializeCore(); + // core.setImportExportoptions(new ImportExportOption()); + String query = core.composeSQLQuery(); + assertEquals(queryTerminal, query); + MockResultSet getselectrs = statementHandler.createResultSet(); + getselectrs.addColumn("Col1"); + getselectrs.addRow(new Object[] {2}); + statementHandler.prepareResultSet(query, getselectrs); + core.executeExportData(database.getConnectionManager().getFreeConnection(), path); + assertTrue(core != null); + } + catch (DatabaseOperationException e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + catch (Exception e) + { + assertTrue(true); + } + } + + @Test + public void test_Generate_Insert_Sql_002() + { + try + { + + Database database = connProfCache.getDbForProfileId(profileId); + Namespace namespace = new SystemNamespace(1, "pg_catalog", database); + database.getSystemNamespaceGroup().addToGroup((SystemNamespace) namespace); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn1 = new ColumnMetaData(tablemetaData, 2, "Col2", + new TypeMetaData(1, "number", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn2 = new ColumnMetaData(tablemetaData, 3, "Col3", + new TypeMetaData(1, "float8", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn3 = new ColumnMetaData(tablemetaData, 4, "Col4", + new TypeMetaData(1, "date", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn4 = new ColumnMetaData(tablemetaData, 5, "Col5", + new TypeMetaData(1, "timestamp", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn5 = new ColumnMetaData(tablemetaData, 6, "Col6", + new TypeMetaData(1, "timestamptz", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn6 = new ColumnMetaData(tablemetaData, 7, "Col7", + new TypeMetaData(1, "bool", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + tablemetaData.getColumns().addItem(newTempColumn1); + tablemetaData.getColumns().addItem(newTempColumn2); + tablemetaData.getColumns().addItem(newTempColumn3); + tablemetaData.getColumns().addItem(newTempColumn4); + tablemetaData.getColumns().addItem(newTempColumn5); + tablemetaData.getColumns().addItem(newTempColumn6); + String queryTerminal = "select * from pg_catalog.\"MyTable\" ;"; + Path path = Paths.get("121.sql"); + String encoding = "UTF-8"; + String username = database.getDatabase().getServer().getServerConnectionInfo().getDsUsername(); + GenerateSQLDataCore core = new GenerateSQLDataCore(database, queryTerminal, encoding, username); + core.initializeCore(); + ExportCursorQueryExecuter exportCursorExecuter = + new ExportCursorQueryExecuter(queryTerminal, database.getConnectionManager().getFreeConnection()); + String uniqCursorName = exportCursorExecuter.getUniqCursorName(); + MockResultSet getselectrs = statementHandler.createResultSet(); + getselectrs.setResultSetMetaData(new ResultSetMetaDataImplementation()); + getselectrs.addColumn("Col1"); + getselectrs.addColumn("Col2"); + getselectrs.addColumn("Col3"); + getselectrs.addColumn("Col4"); + getselectrs.addColumn("Col5"); + getselectrs.addColumn("Col6"); + getselectrs.addColumn("Col7"); + getselectrs.addRow(new Object[] {2, 2.04, 1.004, "2018-09-18 16:37:06", "2018-09-18 16:37:06", + "2018-09-18 16:37:06", true}); + statementHandler.prepareResultSet(uniqCursorName, getselectrs); + GenerateCursorExecuteVisitor visitor = new GenerateCursorExecuteVisitor(path, encoding, true, + JSQLParserUtils.getSelectQueryMainTableName(queryTerminal)); + long exportedRowCount = exportCursorExecuter.exportSQLData(visitor); + assertEquals(1, exportedRowCount); + } + catch (DatabaseOperationException e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_Generate_Insert_Sql_colunmCount() + { + try + { + + Database database = connProfCache.getDbForProfileId(profileId); + Namespace namespace = new SystemNamespace(1, "pg_catalog", database); + database.getSystemNamespaceGroup().addToGroup((SystemNamespace) namespace); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn1 = new ColumnMetaData(tablemetaData, 2, "Col2", + new TypeMetaData(1, "double", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn2 = new ColumnMetaData(tablemetaData, 3, "Col3", + new TypeMetaData(1, "float8", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn3 = new ColumnMetaData(tablemetaData, 4, "Col4", + new TypeMetaData(1, "date", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn4 = new ColumnMetaData(tablemetaData, 5, "Col5", + new TypeMetaData(1, "timestamp", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn5 = new ColumnMetaData(tablemetaData, 6, "Col6", + new TypeMetaData(1, "timestamptz", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn6 = new ColumnMetaData(tablemetaData, 7, "Col7", + new TypeMetaData(1, "bool", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + tablemetaData.getColumns().addItem(newTempColumn1); + tablemetaData.getColumns().addItem(newTempColumn2); + tablemetaData.getColumns().addItem(newTempColumn3); + tablemetaData.getColumns().addItem(newTempColumn4); + tablemetaData.getColumns().addItem(newTempColumn5); + tablemetaData.getColumns().addItem(newTempColumn6); + String queryTerminal = "select * from pg_catalog.\"MyTable\" ;"; + Path path = Paths.get("121.sql"); + String encoding = "UTF-8"; + String username = database.getDatabase().getServer().getServerConnectionInfo().getDsUsername(); + GenerateSQLDataCore core = new GenerateSQLDataCore(database, queryTerminal, encoding, username); + core.initializeCore(); + core.cancelExportOperation(); + ExportCursorQueryExecuter exportCursorExecuter = + new ExportCursorQueryExecuter(queryTerminal, database.getConnectionManager().getFreeConnection()); + String uniqCursorName = exportCursorExecuter.getUniqCursorName(); + MockResultSet getselectrs = statementHandler.createResultSet(); + getselectrs.setResultSetMetaData(new ResultSetMetaDataImplementation()); + getselectrs.addColumn("Col1"); + getselectrs.addColumn("Col2"); + getselectrs.addColumn("Col3"); + getselectrs.addColumn("Col4"); + getselectrs.addColumn("Col5"); + getselectrs.addColumn("Col6"); + getselectrs.addColumn("Col7"); + getselectrs.addRow(new Object[] {2, 2.04, 1.004, "2018-09-18 16:37:06", "2018-09-18 16:37:06", + "2018-09-18 16:37:06", true}); + statementHandler.prepareResultSet(uniqCursorName, getselectrs); + int columnCount = getselectrs.getMetaData().getColumnCount(); + assertEquals(7, columnCount); + } + catch (DatabaseOperationException e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_Generate_Insert_getTableName_001() + { + String queryTerminal = "select * from pg_catalog.\"MyTable\" ;"; + String tableName = JSQLParserUtils.getSelectQueryMainTableName(queryTerminal); + assertEquals("pg_catalog.\"MyTable\"", tableName); + + } + + @Test + public void test_Generate_Insert_getTableName_002() + { + String queryTerminal = "SELECT p.product_id, p.product_name" + " FROM products p" + " WHERE p.category_id IN" + + " (SELECT c.category_id" + " FROM categories c" + " WHERE c.category_id > 25" + + " AND c.category_name like 'S%');"; + String tableName = JSQLParserUtils.getSelectQueryMainTableName(queryTerminal); + assertEquals("products", tableName); + + } + + @Test + public void test_Generate_Insert_Sql_003() + { + try + { + Database database = connProfCache.getDbForProfileId(profileId); + Namespace namespace = new SystemNamespace(1, "pg_catalog", database); + database.getSystemNamespaceGroup().addToGroup((SystemNamespace) namespace); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn1 = new ColumnMetaData(tablemetaData, 2, "Col2", + new TypeMetaData(1, "double", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn2 = new ColumnMetaData(tablemetaData, 3, "Col3", + new TypeMetaData(1, "float8", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn3 = new ColumnMetaData(tablemetaData, 4, "Col4", + new TypeMetaData(1, "date", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn4 = new ColumnMetaData(tablemetaData, 5, "Col5", + new TypeMetaData(1, "timestamp", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn5 = new ColumnMetaData(tablemetaData, 6, "Col6", + new TypeMetaData(1, "timestamptz", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn6 = new ColumnMetaData(tablemetaData, 7, "Col7", + new TypeMetaData(1, "bool", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + tablemetaData.getColumns().addItem(newTempColumn1); + tablemetaData.getColumns().addItem(newTempColumn2); + tablemetaData.getColumns().addItem(newTempColumn3); + tablemetaData.getColumns().addItem(newTempColumn4); + tablemetaData.getColumns().addItem(newTempColumn5); + tablemetaData.getColumns().addItem(newTempColumn6); + String queryTerminal = "select * from pg_catalog.\"MyTable\" ;"; + Path path = Paths.get("121.sql"); + String encoding = "UTF-8"; + String username = database.getDatabase().getServer().getServerConnectionInfo().getDsUsername(); + GenerateSQLDataCore core = new GenerateSQLDataCore(database, queryTerminal, encoding, username); + core.initializeCore(); + Database db = core.getDatabase(); + ExportCursorQueryExecuter exportCursorExecuter = + new ExportCursorQueryExecuter(queryTerminal, database.getConnectionManager().getFreeConnection()); + // core.setImportExportoptions(new ImportExportOption()); + + assertTrue(core != null); + String query = core.composeSQLQuery(); + assertTrue(core.isOLAPDB()); + core.setExportIsInProgress(true); + MockResultSet getselectrs = statementHandler.createResultSet(); + getselectrs.addColumn("col1"); + getselectrs.addRow(new Object[] {2}); + statementHandler.prepareResultSet(query, getselectrs); + core.executeExportData(database.getConnectionManager().getFreeConnection(), path); + assertTrue(core!=null); + core.importExportCleanUp(); + core.cleanUpDataCore(); + } + catch (DatabaseOperationException e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + catch (Exception e) + { + assertTrue(true); + } + + } + @Test + public void test_Generate_Insert_Sql_004() + { + try + { + Database database = connProfCache.getDbForProfileId(profileId); + Namespace namespace = new SystemNamespace(1, "pg_catalog", database); + database.getSystemNamespaceGroup().addToGroup((SystemNamespace) namespace); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("\"MyTa.ble\""); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn1 = new ColumnMetaData(tablemetaData, 2, "col2", + new TypeMetaData(1, "double", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn2 = new ColumnMetaData(tablemetaData, 3, "col3", + new TypeMetaData(1, "float8", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn3 = new ColumnMetaData(tablemetaData, 4, "col4", + new TypeMetaData(1, "date", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn4 = new ColumnMetaData(tablemetaData, 5, "col5", + new TypeMetaData(1, "timestamp", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn5 = new ColumnMetaData(tablemetaData, 6, "col6", + new TypeMetaData(1, "timestamptz", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn6 = new ColumnMetaData(tablemetaData, 7, "col7", + new TypeMetaData(1, "bool", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + tablemetaData.getColumns().addItem(newTempColumn1); + tablemetaData.getColumns().addItem(newTempColumn2); + tablemetaData.getColumns().addItem(newTempColumn3); + tablemetaData.getColumns().addItem(newTempColumn4); + tablemetaData.getColumns().addItem(newTempColumn5); + tablemetaData.getColumns().addItem(newTempColumn6); + String queryTerminal = "select * from \"MyTa.ble\" ;"; + Path path = Paths.get("121.sql"); + String encoding = "UTF-8"; + String username = database.getDatabase().getServer().getServerConnectionInfo().getDsUsername(); + GenerateSQLDataCore core = new GenerateSQLDataCore(database, queryTerminal, encoding, username); + core.initializeCore(); + ExportCursorQueryExecuter exportCursorExecuter = + new ExportCursorQueryExecuter(queryTerminal, database.getConnectionManager().getFreeConnection()); + String uniqCursorName = exportCursorExecuter.getUniqCursorName(); + MockResultSet getselectrs = statementHandler.createResultSet(); + getselectrs.setResultSetMetaData(new ResultSetMetaDataImplementation()); + getselectrs.addColumn("Col1"); + getselectrs.addColumn("Col2"); + getselectrs.addColumn("Col3"); + getselectrs.addColumn("Col4"); + getselectrs.addColumn("Col5"); + getselectrs.addColumn("Col6"); + getselectrs.addColumn("Col7"); + getselectrs.addRow(new Object[] {2, 2.04, 1.004, "2018-09-18 16:37:06", "2018-09-18 16:37:06", + "2018-09-18 16:37:06", true}); + statementHandler.prepareResultSet(uniqCursorName, getselectrs); + String tableName=JSQLParserUtils.getSelectQueryMainTableName(queryTerminal); + GenerateCursorExecuteVisitor visitor = new GenerateCursorExecuteVisitor(path, encoding, true, + tableName); + assertEquals("\"MyTa.ble\"", tableName); + + } + catch (DatabaseOperationException e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + @Test + public void test_Generate_Insert_Sql_005() + { + try + { + Database database = connProfCache.getDbForProfileId(profileId); + Namespace namespace = new SystemNamespace(1, "pg_catalog", database); + database.getSystemNamespaceGroup().addToGroup((SystemNamespace) namespace); + TableMetaData tablemetaData = new TableMetaData(1, "Table005", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("\"MyT.able\""); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn1 = new ColumnMetaData(tablemetaData, 2, "Col2", + new TypeMetaData(1, "double", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn2 = new ColumnMetaData(tablemetaData, 3, "Col3", + new TypeMetaData(1, "float8", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn3 = new ColumnMetaData(tablemetaData, 4, "Col4", + new TypeMetaData(1, "date", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn4 = new ColumnMetaData(tablemetaData, 5, "Col5", + new TypeMetaData(1, "timestamp", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn5 = new ColumnMetaData(tablemetaData, 6, "Col6", + new TypeMetaData(1, "timestamptz", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn6 = new ColumnMetaData(tablemetaData, 7, "Col7", + new TypeMetaData(1, "bool", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + tablemetaData.getColumns().addItem(newTempColumn1); + tablemetaData.getColumns().addItem(newTempColumn2); + tablemetaData.getColumns().addItem(newTempColumn3); + tablemetaData.getColumns().addItem(newTempColumn4); + tablemetaData.getColumns().addItem(newTempColumn5); + tablemetaData.getColumns().addItem(newTempColumn6); + String queryTerminal = "select * from public.\"MyT.able\" ;"; + Path path = Paths.get("234.sql"); + String encoding = "UTF-8"; + String username = database.getDatabase().getServer().getServerConnectionInfo().getDsUsername(); + GenerateSQLDataCore core = new GenerateSQLDataCore(database, queryTerminal, encoding, username); + core.initializeCore(); + ExportCursorQueryExecuter exportCursorExecuter = + new ExportCursorQueryExecuter(queryTerminal, database.getConnectionManager().getFreeConnection()); + String uniqCursorName = exportCursorExecuter.getUniqCursorName(); + MockResultSet getselectrs = statementHandler.createResultSet(); + getselectrs.setResultSetMetaData(new ResultSetMetaDataImplementation()); + getselectrs.addColumn("Col1"); + getselectrs.addColumn("Col2"); + getselectrs.addColumn("Col3"); + getselectrs.addColumn("Col4"); + getselectrs.addColumn("Col5"); + getselectrs.addColumn("Col6"); + getselectrs.addColumn("Col7"); + getselectrs.addRow(new Object[] {2, 2.04, 1.004, "2018-09-18 16:37:06", "2018-09-18 16:37:06", + "2018-09-18 16:37:06", true}); + getselectrs.addRow(new Object[] {2}); + statementHandler.prepareResultSet(uniqCursorName, getselectrs); + String tableName=JSQLParserUtils.getSelectQueryMainTableName(queryTerminal); + GenerateCursorExecuteVisitor visitor = new GenerateCursorExecuteVisitor(path, encoding, true, + tableName); + assertEquals("public.\"MyT.able\"", tableName); + + + } + catch (DatabaseOperationException e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + @Test + public void test_Generate_Insert_Sql_006() + { + try + { + Database database = connProfCache.getDbForProfileId(profileId); + Namespace namespace = new SystemNamespace(1, "pg_catalog", database); + database.getSystemNamespaceGroup().addToGroup((SystemNamespace) namespace); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn1 = new ColumnMetaData(tablemetaData, 2, "Col2", + new TypeMetaData(1, "double", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn2 = new ColumnMetaData(tablemetaData, 3, "Col3", + new TypeMetaData(1, "float8", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn3 = new ColumnMetaData(tablemetaData, 4, "Col4", + new TypeMetaData(1, "date", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn4 = new ColumnMetaData(tablemetaData, 5, "Col5", + new TypeMetaData(1, "timestamp", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn5 = new ColumnMetaData(tablemetaData, 6, "Col6", + new TypeMetaData(1, "timestamptz", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn6 = new ColumnMetaData(tablemetaData, 7, "Col7", + new TypeMetaData(1, "bool", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + tablemetaData.getColumns().addItem(newTempColumn1); + tablemetaData.getColumns().addItem(newTempColumn2); + tablemetaData.getColumns().addItem(newTempColumn3); + tablemetaData.getColumns().addItem(newTempColumn4); + tablemetaData.getColumns().addItem(newTempColumn5); + tablemetaData.getColumns().addItem(newTempColumn6); + String queryTerminal = "select * from pg_catalog.\"MyTable\",pg_catalog.\"MyTable001\" ;"; + Path path = Paths.get("121.sql"); + String encoding = "UTF-8"; + String username = database.getDatabase().getServer().getServerConnectionInfo().getDsUsername(); + GenerateSQLDataCore core = new GenerateSQLDataCore(database, queryTerminal, encoding, username); + core.initializeCore(); + ExportCursorQueryExecuter exportCursorExecuter = + new ExportCursorQueryExecuter(queryTerminal, database.getConnectionManager().getFreeConnection()); + String uniqCursorName = exportCursorExecuter.getUniqCursorName(); + MockResultSet getselectrs = statementHandler.createResultSet(); + getselectrs.setResultSetMetaData(new ResultSetMetaDataImplementation()); + getselectrs.addColumn("col1"); + getselectrs.addColumn("col2"); + getselectrs.addColumn("col3"); + getselectrs.addColumn("col4"); + getselectrs.addColumn("col5"); + getselectrs.addColumn("col6"); + getselectrs.addColumn("col7"); + getselectrs.addRow(new Object[] {2, 2.04, 1.004, "2018-09-18 16:37:06", "2018-09-18 16:37:06", + "2018-09-18 16:37:06", true}); + statementHandler.prepareResultSet(uniqCursorName, getselectrs); + GenerateCursorExecuteVisitor visitor = new GenerateCursorExecuteVisitor(path, encoding, true, + JSQLParserUtils.getSelectQueryMainTableName(queryTerminal)); + long exportedRowCount = exportCursorExecuter.exportSQLData(visitor); + assertEquals(1, exportedRowCount); + } + catch (DatabaseOperationException e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + @Test + public void test_Generate_Insert_Sql_007() + { + try + { + Database database = connProfCache.getDbForProfileId(profileId); + Namespace namespace = new SystemNamespace(1, "pg_catalog", database); + database.getSystemNamespaceGroup().addToGroup((SystemNamespace) namespace); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn1 = new ColumnMetaData(tablemetaData, 2, "col2", + new TypeMetaData(1, "double", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn2 = new ColumnMetaData(tablemetaData, 3, "col3", + new TypeMetaData(1, "float8", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn3 = new ColumnMetaData(tablemetaData, 4, "col4", + new TypeMetaData(1, "date", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn4 = new ColumnMetaData(tablemetaData, 5, "col5", + new TypeMetaData(1, "timestamp", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn5 = new ColumnMetaData(tablemetaData, 6, "col6", + new TypeMetaData(1, "timestamptz", database.getNameSpaceById(1))); + ColumnMetaData newTempColumn6 = new ColumnMetaData(tablemetaData, 7, "col7", + new TypeMetaData(1, "bool", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + tablemetaData.getColumns().addItem(newTempColumn1); + tablemetaData.getColumns().addItem(newTempColumn2); + tablemetaData.getColumns().addItem(newTempColumn3); + tablemetaData.getColumns().addItem(newTempColumn4); + tablemetaData.getColumns().addItem(newTempColumn5); + tablemetaData.getColumns().addItem(newTempColumn6); + String queryTerminal = "select * from pg_catalog.\"MyTable\";"; + Path path = Paths.get("121.sql"); + String encoding = "UTF-8"; + String username = database.getDatabase().getServer().getServerConnectionInfo().getDsUsername(); + GenerateSQLDataCore core = new GenerateSQLDataCore(database, queryTerminal, encoding, username); + core.initializeCore(); + ExportCursorQueryExecuter exportCursorExecuter = + new ExportCursorQueryExecuter(queryTerminal, database.getConnectionManager().getFreeConnection()); + String uniqCursorName = exportCursorExecuter.getUniqCursorName(); + MockResultSet getselectrs = statementHandler.createResultSet(); + getselectrs.setResultSetMetaData(new ResultSetMetaDataImplementation()); + getselectrs.addColumn("col1"); + getselectrs.addColumn("col2"); + getselectrs.addColumn("col3"); + getselectrs.addColumn("col4"); + getselectrs.addColumn("col5"); + getselectrs.addColumn("col6"); + getselectrs.addColumn("col7"); + getselectrs.addRow(new Object[] {2, 2.04, 1.004, "2018-09-18 16:37:06", "2018-09-18 16:37:06", + "2018-09-18 16:37:06", true}); + statementHandler.prepareResultSet(uniqCursorName, getselectrs); + String tableName=JSQLParserUtils.getSelectQueryMainTableName(queryTerminal); + GenerateCursorExecuteVisitor visitor = new GenerateCursorExecuteVisitor(path, encoding, true, + tableName); + assertEquals("pg_catalog.\"MyTable\"", tableName); + } + catch (DatabaseOperationException e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + @Test + public void test_Generate_Insert_getTableName_003() + { + String queryTerminal = "select * from pg_catalog.\"MyTable\" " + + " union all " + + "select * from pg_catalog.\"MyTable\";"; + String tableName = JSQLParserUtils.getSelectQueryMainTableName(queryTerminal); + assertEquals("pg_catalog.\"MyTable\"", tableName); + + } + + @Test + public void test_copyQuery_01() + { + String queryTerminal = "select * into pg_catalog.\"MyTable\" ;"; + String queryTerminal2 = "insert into pg_catalog.\"MyTable\" values(0)"; + String queryTerminal3 = null; + String queryTerminal4 = "select * from pg_catalog.\"MyTable\" ;"; + boolean iscopyQuery1 = JSQLParserUtils.isCopyQuery(queryTerminal); + assertEquals(true, iscopyQuery1); + boolean iscopyQuery2 = JSQLParserUtils.isCopyQuery(queryTerminal2); + assertEquals(false, iscopyQuery2); + boolean iscopyQuery3 = JSQLParserUtils.isCopyQuery(queryTerminal3); + assertEquals(false, iscopyQuery3); + boolean iscopyQuery4 = JSQLParserUtils.isCopyQuery(queryTerminal4); + assertEquals(false, iscopyQuery4); + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/GrantRevokeCoreTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/GrantRevokeCoreTest.java new file mode 100644 index 0000000000000000000000000000000000000000..84811e8a1f181be09084d40c01c4dc9ffc7943cc --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/GrantRevokeCoreTest.java @@ -0,0 +1,661 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.test.presentation.table; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.*; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DebugObjects; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.PartitionTable; +import org.opengauss.mppdbide.bl.serverdatacache.SequenceMetadata; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.UserNamespace; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.groups.TableObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.presentation.userrole.GrantRevokeCore; +import org.opengauss.mppdbide.presentation.userrole.GrantRevokeParameters; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.MessageQueue; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; + +/** + * + * @ClassName: GrantRevokeCoreTest + * @Description: junit test for GrantRevokeCore + * + * @since 3.0.0 + */ +public class GrantRevokeCoreTest extends BasicJDBCTestCaseAdapter +{ + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + + Database database; + DBConnection dbconn; + GrantRevokeCore grantRevokeCore; + + @Before + public void setUp() throws Exception + { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + connection = new MockConnection(); + MPPDBIDELoggerUtility.setArgs(new String[] {"-logfolder=.", "-detailLogging=true"}); + + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + preparedstatementHandler = connection.getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + + connProfCache = DBConnProfCache.getInstance(); + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + database = connProfCache.getDbForProfileId(profileId); + getAllDatabaseObjects(); + dbconn = CommonLLTUtils.getDBConnection(); + + grantRevokeCore = new GrantRevokeCore(true, + Arrays.asList(database.getAllNameSpaces().get(0).getTablesGroup().getChildren())); + } + + @After + public void tearDown() throws Exception + { + super.tearDown(); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().close(); + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) + { + connProfCache.removeServer(itr.next().getId()); + } + + connProfCache.closeAllNodes(); + + } + + private void getAllDatabaseObjects() + { + try + { + + database.getServer().refresh(); + Namespace ns1 = new UserNamespace(6, "ns1", database); + Namespace ns2 = new UserNamespace(2, "NS1", database); + Namespace ns3 = new UserNamespace(3, "NS2", database); + Namespace ns4 = new UserNamespace(4, "yns2", database); + Namespace ns6 = new UserNamespace(5, "\"NS1\"", database); + Namespace ns7 = new UserNamespace(7, "Namespc", database); + + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns1); + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns2); + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns3); + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns4); + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns6); + database.getUserNamespaceGroup().addToGroup((UserNamespace) ns7); + + TableMetaData ptab1 = new PartitionTable(ns7); + ns7.addTableToSearchPool(ptab1); + + TableMetaData tbl1 = new TableMetaData(1, "tbl1", ns1, ""); + ColumnMetaData clm = new ColumnMetaData(tbl1, 1, "Col1", null); + tbl1.addColumn(clm); + TableMetaData tbl2 = new TableMetaData(2, "tbl2", ns1, ""); + ColumnMetaData clm1 = new ColumnMetaData(tbl2, 1, "Col2", null); + tbl2.addColumn(clm1); + TableMetaData tbl3 = new TableMetaData(3, "TBL1", ns1, ""); + ColumnMetaData clm2 = new ColumnMetaData(tbl3, 1, "Col3", null); + tbl3.addColumn(clm2); + + ns1.addTableToSearchPool(tbl1); + ns1.addTableToSearchPool(tbl2); + ns1.addTableToSearchPool(tbl3); + + TableMetaData tbl4 = new TableMetaData(4, "tbl1", ns2, ""); + ColumnMetaData clm3 = new ColumnMetaData(tbl4, 1, "Col4", null); + tbl4.addColumn(clm3); + TableMetaData tbl5 = new TableMetaData(5, "tbl2", ns2, ""); + ColumnMetaData clm4 = new ColumnMetaData(tbl5, 1, "Col5", null); + tbl5.addColumn(clm4); + TableMetaData tbl6 = new TableMetaData(6, "TBL1", ns2, ""); + ColumnMetaData clm5 = new ColumnMetaData(tbl6, 1, "Col6", null); + tbl6.addColumn(clm5); + TableMetaData tbl7 = new TableMetaData(7, "TBL2", ns2, ""); + ColumnMetaData clm6 = new ColumnMetaData(tbl7, 1, "Col7", null); + tbl7.addColumn(clm6); + TableMetaData tbl110 = new TableMetaData(110, "T}BL1", ns2, ""); + ColumnMetaData clm110 = new ColumnMetaData(tbl110, 1, "Col7", null); + tbl7.addColumn(clm110); + + ViewMetaData view = new ViewMetaData(1, "Yiew1", ns2,ns2.getDatabase()); + SequenceMetadata seq = new SequenceMetadata(ns2); + + ns2.addTableToSearchPool(tbl5); + ns2.addTableToSearchPool(tbl6); + ns2.addTableToSearchPool(tbl7); + ns2.addTableToSearchPool(tbl4); + ns2.addTableToSearchPool(tbl110); + ns2.addView(view); + ns2.addSequence(seq); + + TableMetaData tbl8 = new TableMetaData(8, "tbl1", ns3, ""); + ColumnMetaData clm8 = new ColumnMetaData(tbl8, 1, "Col8", null); + tbl8.addColumn(clm8); + TableMetaData tbl9 = new TableMetaData(9, "tbl2", ns3, ""); + ColumnMetaData clm9 = new ColumnMetaData(tbl9, 1, "Col9", null); + tbl9.addColumn(clm9); + + ns3.addTableToSearchPool(tbl8); + ns3.addTableToSearchPool(tbl9); + + TableMetaData tbl10 = new TableMetaData(10, "Tbl11", ns4, ""); + ColumnMetaData clm10 = new ColumnMetaData(tbl10, 1, "Col10", null); + tbl10.addColumn(clm10); + TableMetaData tbl11 = new TableMetaData(11, "xtbl2", ns4, ""); + ColumnMetaData clm11 = new ColumnMetaData(tbl11, 1, "Col11", null); + tbl11.addColumn(clm11); + TableMetaData tbl12 = new TableMetaData(12, "NS1", ns4, ""); + ColumnMetaData clm12 = new ColumnMetaData(tbl12, 1, "Col12", null); + tbl12.addColumn(clm12); + + ns4.addTableToSearchPool(tbl10); + ns4.addTableToSearchPool(tbl11); + ns4.addTableToSearchPool(tbl12); + + TableMetaData tbl14 = new TableMetaData(13, "ybl1", ns6, ""); + ColumnMetaData clm14 = new ColumnMetaData(tbl14, 1, "Col14", null); + tbl14.addColumn(clm14); + + ns6.addTableToSearchPool(tbl14); + } + catch (DatabaseOperationException e) + { + e.printStackTrace(); + } + catch (DatabaseCriticalException e) + { + e.printStackTrace(); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + @Test + public void test_GrantRevokeCore_001() + { + try + { + TableObjectGroup tablesGroup = database.getAllNameSpaces().get(0).getTablesGroup(); + GrantRevokeCore tempGrantRevokeCore = new GrantRevokeCore(false, tablesGroup); + assertEquals(true, tempGrantRevokeCore != null); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_GrantRevokeCore_002() + { + try + { + List tableList = Arrays.asList(database.getAllNameSpaces().get(0).getTablesGroup().getChildren()); + GrantRevokeCore tempGrantRevokeCore = new GrantRevokeCore(true, tableList); + assertEquals(true, tempGrantRevokeCore != null); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_getUserRoleOption_001() + { + try + { + grantRevokeCore.getUserRoleOption(); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_getDatabase_001() + { + try + { + grantRevokeCore.getDatabase(); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_getObjectOption_001() + { + try + { + grantRevokeCore.getObjectOption(); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_modifyObjectPrivilege_001() + { + try + { + List sqls = new ArrayList<>(); + sqls.add("grant select on table t_test to chris;"); + MessageQueue messageQueue = new MessageQueue(); + + grantRevokeCore.modifyObjectPrivilege(dbconn, sqls, messageQueue); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + + public GrantRevokeParameters setGrantRevokeParameters(List selectedObjects, String userRolesStr, + List withGrantOptionPrivileges, List withoutGrantOptionPrivileges, boolean allPrivilege, + boolean allWithGrantOption, List revokePrivileges, List revokeGrantPrivileges, + boolean revokeAllPrivilege, boolean revokeAllGrantPrivilege, boolean isGrant) + { + GrantRevokeParameters params = new GrantRevokeParameters(); + params.setSelectedObjects(selectedObjects); + params.setUserRolesStr(userRolesStr); + params.setWithGrantOptionPrivileges(withGrantOptionPrivileges); + params.setWithoutGrantOptionPrivileges(withoutGrantOptionPrivileges); + params.setAllPrivilege(allPrivilege); + params.setAllWithGrantOption(allWithGrantOption); + params.setRevokePrivileges(revokePrivileges); + params.setRevokeGrantPrivileges(revokeGrantPrivileges); + params.setRevokeAllPrivilege(revokeAllPrivilege); + params.setRevokeAllGrantPrivilege(revokeAllGrantPrivilege); + params.setGrant(isGrant); + return params; + } + + @Test + public void test_generateSql_001() + { + try + { + List selectedObjects = + Arrays.asList(database.getAllNameSpaces().get(0).getTablesGroup().getChildren()); + String userRolesStr = "chris, alex"; + List withGrantOptionPrivileges = Arrays.asList(new String[] {"select", "update"}); + List withoutGrantOptionPrivileges = Arrays.asList(new String[] {"delete"}); + boolean allPrivilege = false; + boolean allWithGrantOption = false; + List revokePrivileges = Arrays.asList(new String[] {"insert"}); + List revokeGrantPrivileges = Arrays.asList(new String[] {"truncate"}); + boolean revokeAllPrivilege = false; + boolean revokeAllGrantPrivilege = false; + boolean isGrant = true; + + grantRevokeCore.generateSql(setGrantRevokeParameters(selectedObjects, userRolesStr, + withGrantOptionPrivileges, withoutGrantOptionPrivileges, allPrivilege, allWithGrantOption, + revokePrivileges, revokeGrantPrivileges, revokeAllPrivilege, revokeAllGrantPrivilege, isGrant)); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_generateSql_002() + { + try + { + List selectedObjects = + Arrays.asList(database.getAllNameSpaces().get(0).getTablesGroup().getChildren()); + String userRolesStr = "chris, alex"; + List withGrantOptionPrivileges = Arrays.asList(new String[] {"select", "update"}); + List withoutGrantOptionPrivileges = Arrays.asList(new String[] {"delete"}); + boolean allPrivilege = true; + boolean allWithGrantOption = false; + List revokePrivileges = Arrays.asList(new String[] {"insert"}); + List revokeGrantPrivileges = Arrays.asList(new String[] {"truncate"}); + boolean revokeAllPrivilege = true; + boolean revokeAllGrantPrivilege = false; + boolean isGrant = false; + + grantRevokeCore.generateSql(setGrantRevokeParameters(selectedObjects, userRolesStr, + withGrantOptionPrivileges, withoutGrantOptionPrivileges, allPrivilege, allWithGrantOption, + revokePrivileges, revokeGrantPrivileges, revokeAllPrivilege, revokeAllGrantPrivilege, isGrant)); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_generateSql_003() + { + try + { + List selectedObjects = + Arrays.asList(database.getAllNameSpaces().get(0).getTablesGroup().getChildren()); + String userRolesStr = "chris, alex"; + List withGrantOptionPrivileges = Arrays.asList(new String[] {"select", "update"}); + List withoutGrantOptionPrivileges = Arrays.asList(new String[] {"delete"}); + boolean allPrivilege = true; + boolean allWithGrantOption = false; + List revokePrivileges = Arrays.asList(new String[] {"insert"}); + List revokeGrantPrivileges = Arrays.asList(new String[] {"truncate"}); + boolean revokeAllPrivilege = true; + boolean revokeAllGrantPrivilege = false; + boolean isGrant = true; + + grantRevokeCore.generateSql(setGrantRevokeParameters(selectedObjects, userRolesStr, + withGrantOptionPrivileges, withoutGrantOptionPrivileges, allPrivilege, allWithGrantOption, + revokePrivileges, revokeGrantPrivileges, revokeAllPrivilege, revokeAllGrantPrivilege, isGrant)); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_generateSql_004() + { + try + { + List selectedObjects = + Arrays.asList(database.getAllNameSpaces().get(0).getTablesGroup().getChildren()); + String userRolesStr = "chris, alex"; + List withGrantOptionPrivileges = Arrays.asList(new String[] {"select", "update"}); + List withoutGrantOptionPrivileges = Arrays.asList(new String[] {"delete"}); + boolean allPrivilege = true; + boolean allWithGrantOption = false; + List revokePrivileges = Arrays.asList(new String[] {"insert"}); + List revokeGrantPrivileges = Arrays.asList(new String[] {"truncate"}); + boolean revokeAllPrivilege = false; + boolean revokeAllGrantPrivilege = true; + boolean isGrant = false; + + grantRevokeCore.generateSql(setGrantRevokeParameters(selectedObjects, userRolesStr, + withGrantOptionPrivileges, withoutGrantOptionPrivileges, allPrivilege, allWithGrantOption, + revokePrivileges, revokeGrantPrivileges, revokeAllPrivilege, revokeAllGrantPrivilege, isGrant)); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_generateSql_005() + { + try + { + List selectedObjects = + Arrays.asList(database.getAllNameSpaces().get(0).getTablesGroup().getChildren()); + String userRolesStr = "chris, alex"; + List withGrantOptionPrivileges = Arrays.asList(new String[] {"select", "update"}); + List withoutGrantOptionPrivileges = Arrays.asList(new String[] {"delete"}); + boolean allPrivilege = true; + boolean allWithGrantOption = false; + List revokePrivileges = Arrays.asList(new String[] {"insert"}); + List revokeGrantPrivileges = Arrays.asList(new String[] {"truncate"}); + boolean revokeAllPrivilege = false; + boolean revokeAllGrantPrivilege = false; + boolean isGrant = false; + + grantRevokeCore.generateSql(setGrantRevokeParameters(selectedObjects, userRolesStr, + withGrantOptionPrivileges, withoutGrantOptionPrivileges, allPrivilege, allWithGrantOption, + revokePrivileges, revokeGrantPrivileges, revokeAllPrivilege, revokeAllGrantPrivilege, isGrant)); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_generateSql_006() + { + try + { + List selectedObjects = Arrays.asList(database.getAllNameSpaces().get(0)); + String userRolesStr = "chris, alex"; + List withGrantOptionPrivileges = Arrays.asList(new String[] {"select", "update"}); + List withoutGrantOptionPrivileges = Arrays.asList(new String[] {"delete"}); + boolean allPrivilege = true; + boolean allWithGrantOption = false; + List revokePrivileges = Arrays.asList(new String[] {"insert"}); + List revokeGrantPrivileges = Arrays.asList(new String[] {"truncate"}); + boolean revokeAllPrivilege = false; + boolean revokeAllGrantPrivilege = false; + boolean isGrant = false; + + grantRevokeCore.generateSql(setGrantRevokeParameters(selectedObjects, userRolesStr, + withGrantOptionPrivileges, withoutGrantOptionPrivileges, allPrivilege, allWithGrantOption, + revokePrivileges, revokeGrantPrivileges, revokeAllPrivilege, revokeAllGrantPrivilege, isGrant)); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_generateSql_007() + { + try + { + List selectedObjects = + Arrays.asList(new DebugObjects(1L, "debug_object", OBJECTTYPE.PLSQLFUNCTION, database)); + String userRolesStr = "chris, alex"; + List withGrantOptionPrivileges = Arrays.asList(new String[] {"select", "update"}); + List withoutGrantOptionPrivileges = Arrays.asList(new String[] {"delete"}); + boolean allPrivilege = true; + boolean allWithGrantOption = false; + List revokePrivileges = Arrays.asList(new String[] {"insert"}); + List revokeGrantPrivileges = Arrays.asList(new String[] {"truncate"}); + boolean revokeAllPrivilege = false; + boolean revokeAllGrantPrivilege = false; + boolean isGrant = false; + + grantRevokeCore.generateSql(setGrantRevokeParameters(selectedObjects, userRolesStr, + withGrantOptionPrivileges, withoutGrantOptionPrivileges, allPrivilege, allWithGrantOption, + revokePrivileges, revokeGrantPrivileges, revokeAllPrivilege, revokeAllGrantPrivilege, isGrant)); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_generateSql_008() + { + try + { + List selectedObjects = Arrays.asList(database.getAllNameSpaces().get(0)); + String userRolesStr = "chris, alex"; + List withGrantOptionPrivileges = Arrays.asList(new String[] {"select", "update"}); + List withoutGrantOptionPrivileges = Arrays.asList(new String[] {"delete"}); + boolean allPrivilege = true; + boolean allWithGrantOption = false; + List revokePrivileges = Arrays.asList(new String[] {"insert"}); + List revokeGrantPrivileges = Arrays.asList(new String[] {"truncate"}); + boolean revokeAllPrivilege = false; + boolean revokeAllGrantPrivilege = false; + boolean isGrant = true; + + grantRevokeCore.generateSql(setGrantRevokeParameters(selectedObjects, userRolesStr, + withGrantOptionPrivileges, withoutGrantOptionPrivileges, allPrivilege, allWithGrantOption, + revokePrivileges, revokeGrantPrivileges, revokeAllPrivilege, revokeAllGrantPrivilege, isGrant)); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_generateSql_009() + { + try + { + List selectedObjects = + Arrays.asList(new DebugObjects(1L, "debug_object", OBJECTTYPE.PLSQLFUNCTION, database)); + String userRolesStr = "chris, alex"; + List withGrantOptionPrivileges = Arrays.asList(new String[] {"select", "update"}); + List withoutGrantOptionPrivileges = Arrays.asList(new String[] {"delete"}); + boolean allPrivilege = true; + boolean allWithGrantOption = false; + List revokePrivileges = Arrays.asList(new String[] {"insert"}); + List revokeGrantPrivileges = Arrays.asList(new String[] {"truncate"}); + boolean revokeAllPrivilege = false; + boolean revokeAllGrantPrivilege = false; + boolean isGrant = true; + + grantRevokeCore.generateSql(setGrantRevokeParameters(selectedObjects, userRolesStr, + withGrantOptionPrivileges, withoutGrantOptionPrivileges, allPrivilege, allWithGrantOption, + revokePrivileges, revokeGrantPrivileges, revokeAllPrivilege, revokeAllGrantPrivilege, isGrant)); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_generateSql_010() + { + try + { + List selectedObjects = + Arrays.asList(database.getAllNameSpaces().get(0).getTablesGroup().getChildren()); + String userRolesStr = "chris, alex"; + List withGrantOptionPrivileges = Arrays.asList(new String[] {"select", "update"}); + List withoutGrantOptionPrivileges = Arrays.asList(new String[] {"delete"}); + boolean allPrivilege = true; + boolean allWithGrantOption = true; + List revokePrivileges = Arrays.asList(new String[] {"insert"}); + List revokeGrantPrivileges = Arrays.asList(new String[] {"truncate"}); + boolean revokeAllPrivilege = true; + boolean revokeAllGrantPrivilege = false; + boolean isGrant = true; + + grantRevokeCore.generateSql(setGrantRevokeParameters(selectedObjects, userRolesStr, + withGrantOptionPrivileges, withoutGrantOptionPrivileges, allPrivilege, allWithGrantOption, + revokePrivileges, revokeGrantPrivileges, revokeAllPrivilege, revokeAllGrantPrivilege, isGrant)); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ImportExcelApachePOITest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ImportExcelApachePOITest.java new file mode 100644 index 0000000000000000000000000000000000000000..370554c61eb59c5382cab870581e433cc2614998 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ImportExcelApachePOITest.java @@ -0,0 +1,406 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +package org.opengauss.mppdbide.test.presentation.table; + +import static org.junit.Assert.*; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.Iterator; +import java.util.List; + +import org.apache.poi.xssf.streaming.SXSSFCell; +import org.apache.poi.xssf.streaming.SXSSFRow; +import org.apache.poi.xssf.streaming.SXSSFSheet; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.opengauss.mppdbide.adapter.driver.Gauss200V1R7Driver; +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintType; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ImportExportOption; +import org.opengauss.mppdbide.bl.serverdatacache.IndexMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TypeMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.UserNamespace; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.presentation.exportdata.ImportExcelApachePOI; +import org.opengauss.mppdbide.presentation.exportdata.ImportExportDataCore; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.exceptions.PasswordExpiryException; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; + +/** + * + * Title: ImportExcelApachePOITest + * + * @since 3.0.0 + */ +public class ImportExcelApachePOITest extends BasicJDBCTestCaseAdapter { + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + private DBConnection dbconn; + Gauss200V1R7Driver mockDriver =null; + ServerConnectionInfo serverInfo = null; + + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#setUp() + */ + @Before + public void setUp() throws Exception { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + connection = new MockConnection(); + MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + mockDriver = CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + this.dbconn = CommonLLTUtils.getDBConnection(); + preparedstatementHandler = connection.getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + + connProfCache = DBConnProfCache.getInstance(); + + serverInfo = new ServerConnectionInfo(); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + MockPresentationBLPreferenceImpl.setFileEncoding("UTF-8"); + + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + // serverInfo.setSslPassword("12345"); + // serverInfo.setServerType(DATABASETYPE.GAUSS); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception { + super.tearDown(); + + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) { + connProfCache.removeServer(itr.next().getId()); + } + + connProfCache.closeAllNodes(); + + } + + + private TableMetaData getTableMetaData() { + TableMetaData tableMetaData = null; + try { + + Server server = new Server(serverInfo); + Database database = new Database(server, 2, "Gauss"); + try { + CommonLLTUtils.setConnectionManagerConnectionDriver(mockDriver,database); + } catch (Exception e) { + System.out.println("not expected to come here"); + } + Namespace namespace = new UserNamespace(1, "namespace1", database); + database.getUserNamespaceGroup().addToGroup((UserNamespace) namespace); + tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "col01", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + ColumnMetaData newTempColumn1 = new ColumnMetaData(tableMetaData, 1, "col02", + new TypeMetaData(1, "varchar", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn1); + + ColumnMetaData newTempColumn2 = new ColumnMetaData(tableMetaData, 1, "col03", + new TypeMetaData(1, "integer", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn2); + + ColumnMetaData newTempColumn3 = new ColumnMetaData(tableMetaData, 1, "col04", + new TypeMetaData(1, "double", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn3); + + ColumnMetaData newTempColumn4 = new ColumnMetaData(tableMetaData, 1, "col05", + new TypeMetaData(1, "boolean", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn4); + + ColumnMetaData newTempColumn5 = new ColumnMetaData(tableMetaData, 1, "col06", + new TypeMetaData(1, "date", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn5); + IndexMetaData indexMetaData = new IndexMetaData("Idx1"); + + indexMetaData.setTable(tableMetaData); + indexMetaData.setNamespace(tableMetaData.getNamespace()); + tableMetaData.addIndex(indexMetaData); + + } catch (OutOfMemoryError outofMemoryError) { + outofMemoryError.printStackTrace(); + } catch (MPPDBIDEException mppdbideException) { + mppdbideException.printStackTrace(); + } + return tableMetaData; + } + + private void createExcel(String fileName) { + FileOutputStream fos = null; + try { + // Create Workbook instance holding reference to .xlsx file + SXSSFWorkbook workbook = new SXSSFWorkbook(); + // Get first/desired sheet from the workbook + SXSSFSheet sheet = createSheet(workbook, "Sheet 1", false); + // Write some information in the cells or do what you want + SXSSFRow row1 = sheet.createRow(0); + SXSSFCell r1c2 = row1.createCell(0); + r1c2.setCellValue("col01"); + SXSSFCell r1c3 = row1.createCell(1); + r1c3.setCellValue("col02"); + SXSSFCell r1c4 = row1.createCell(2); + r1c4.setCellValue("col03"); + SXSSFCell r1c5 = row1.createCell(3); + r1c5.setCellValue("col04"); + SXSSFCell r1c6 = row1.createCell(4); + r1c6.setCellValue("col05"); + SXSSFCell r1c7 = row1.createCell(5); + r1c7.setCellValue("col06"); + SXSSFRow row2 = sheet.createRow(1); + SXSSFCell r2c2 = row2.createCell(0); + r2c2.setCellValue("1"); + SXSSFCell r2cc3 = row2.createCell(1); + r2cc3.setCellValue("item1"); + SXSSFCell r2cc4 = row2.createCell(2); + r2cc4.setCellValue("25"); + SXSSFCell r2cc5 = row2.createCell(3); + r2cc5.setCellValue(Double.parseDouble("25.5")); + SXSSFCell r2cc6 = row2.createCell(4); + r2cc6.setCellValue(Boolean.getBoolean("TRUE")); + SXSSFCell r2cc7 = row2.createCell(5); + DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date date = format.parse("2019-10-16 11:01:00"); + r2cc7.setCellValue(date); + + // Save excel to HDD Drive + File pathToFile = new File(fileName); + if (!pathToFile.exists()) { + pathToFile.createNewFile(); + } + + // Save excel to HDD Drive + fos = new FileOutputStream(pathToFile); + workbook.write(fos); + } catch (Exception exception) { + exception.printStackTrace(); + } finally { + try { + if (fos != null) { + fos.flush(); + fos.close(); + } + } catch (IOException exception) { + exception.printStackTrace(); + } + } + } + + private static SXSSFSheet createSheet(SXSSFWorkbook wb, String prefix, boolean isHidden) { + SXSSFSheet sheet = null; + int count = 0; + for (int i = 0; i < wb.getNumberOfSheets(); i++) { + String sName = wb.getSheetName(i); + if (sName.startsWith(prefix)) count++; + } + if (count > 0) { + sheet = wb.createSheet(prefix + count); + } else { + sheet = wb.createSheet(prefix); + } + return sheet; + } + + + @Test + public void testGetCellValues3() { + try { + if (CommonLLTUtils.isLinux()) + { + return; + } + + ImportExportOption option = new ImportExportOption(); + option.setExport(false); + option.setFileFormat("EXCEL(xls)"); + option.setAllColunms(true); + option.setHeader(true); + option.setEncoding("UTF-8"); + option.setDateSelector("yyyy-MM-dd HH:mm:ss"); + option.setZip(false); + option.setTablecolumns( + new ArrayList(Arrays.asList("col01", "coll02", "col03", "col04", "col05", "col06"))); + option.setFileName("./firstExcel.xls"); + TableMetaData tableMetaData = getTableMetaData(); + + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col01", "coll02", "col03", "col04", "col05", "col06")), null, + null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + ImportExcelApachePOI importExcelPOI = new ImportExcelApachePOI(option); + List> list = importExcelPOI.getCellValues(); + assertEquals(1, list.size()); + + } catch (MPPDBIDEException | IOException exception) { + fail("Not excepted to come here"); + } + } + + @Test + public void testGetCellValues4() { + try { + ImportExportOption option = new ImportExportOption(); + option.setExport(false); + option.setFileFormat("EXCEL(xlsx)"); + option.setAllColunms(true); + option.setHeader(true); + option.setEncoding("UTF-8"); + option.setDateSelector("yyyy-MM-dd HH:mm:ss"); + option.setZip(false); + option.setTablecolumns( + new ArrayList(Arrays.asList("col01", "coll02", "col03", "col04", "col05", "col06"))); + String filePath = "./testGetCellValues4.xlsx"; + createExcel(filePath); + option.setFileName(filePath); + TableMetaData tableMetaData = getTableMetaData(); + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col01", "coll02", "col03", "col04", "col05", "col06")), null, + null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + ImportExcelApachePOI importExcelPOI = new ImportExcelApachePOI(option); + List> list = importExcelPOI.getCellValues(); + assertEquals(1, list.size()); + + } catch (MPPDBIDEException | IOException exception) { + fail("Not excepted to come here"); + } + } + + @Test + public void testGetCellValues_Failure() { + try { + ImportExportOption option = new ImportExportOption(); + option.setExport(false); + option.setFileFormat("EXCEL(xlsx)"); + option.setAllColunms(true); + option.setHeader(true); + option.setEncoding("UTF-8"); + option.setDateSelector("yyyy-MM-dd HH:mm:ss"); + option.setZip(false); + option.setTablecolumns( + new ArrayList(Arrays.asList("col01", "coll02", "col03", "col04", "col05", "col06"))); + String filePath = "./testGetCellValues.xlsx"; + createExcel(filePath); + option.setFileName(filePath); + TableMetaData tableMetaData = getTableMetaData(); + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col01", "coll02", "col03", "col04", "col05", "col06")), null, + null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + ImportExcelApachePOI importExcelPOI = new ImportExcelApachePOI(option); + importExcelPOI.getCellValues(); + } catch (MPPDBIDEException e) { + assertTrue(true); + } + catch (IOException exception) { + fail("Not excepted to come here"); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ImportExcelExecuterTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ImportExcelExecuterTest.java new file mode 100644 index 0000000000000000000000000000000000000000..366a39643e0fa5f49705743b06aceeb891f86a62 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ImportExcelExecuterTest.java @@ -0,0 +1,417 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +package org.opengauss.mppdbide.test.presentation.table; + +import static org.junit.Assert.*; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import org.apache.poi.ss.usermodel.CellCopyPolicy; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.xssf.streaming.SXSSFCell; +import org.apache.poi.xssf.streaming.SXSSFRow; +import org.apache.poi.xssf.streaming.SXSSFSheet; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.opengauss.mppdbide.adapter.driver.Gauss200V1R7Driver; +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintType; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ImportExportOption; +import org.opengauss.mppdbide.bl.serverdatacache.IndexMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TypeMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.UserNamespace; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.presentation.exportdata.ImportExportDataCore; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.exceptions.PasswordExpiryException; +import org.opengauss.mppdbide.utils.exceptions.TableImporExportException; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; + +/** + * + * Title: ImportExcelExecuterTest + * + * Description: ImportExcelExecuterTest + * + * @since 3.0.0 + */ +public class ImportExcelExecuterTest extends BasicJDBCTestCaseAdapter { + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + ServerConnectionInfo serverInfo = null; + JobCancelStatus status = null; + private DBConnection dbconn; + Gauss200V1R7Driver mockDriver =null; + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#setUp() + */ + @Before + public void setUp() throws Exception { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + connection = new MockConnection(); + MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + mockDriver=CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + this.dbconn = CommonLLTUtils.getDBConnection(); + preparedstatementHandler = connection.getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + + connProfCache = DBConnProfCache.getInstance(); + + serverInfo = new ServerConnectionInfo(); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + MockPresentationBLPreferenceImpl.setFileEncoding("UTF-8"); + + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + // serverInfo.setSslPassword("12345"); + // serverInfo.setServerType(DATABASETYPE.GAUSS); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception { + super.tearDown(); + + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) { + connProfCache.removeServer(itr.next().getId()); + } + + connProfCache.closeAllNodes(); + + } + + private TableMetaData getTableMetaData() { + TableMetaData tableMetaData = null; + try { + + Server server = new Server(serverInfo); + + Database database = new Database(server, 2, "Gauss"); + try { + CommonLLTUtils.setConnectionManagerConnectionDriver(mockDriver,database); + } catch (Exception e) { + System.out.println("not expected to come here"); + } + Namespace namespace = new UserNamespace(1, "namespace1", database); + database.getUserNamespaceGroup().addToGroup((UserNamespace) namespace); + tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "col01", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + ColumnMetaData newTempColumn1 = new ColumnMetaData(tableMetaData, 2, "col02", + new TypeMetaData(2, "text", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn1); + + ColumnMetaData newTempColumn2 = new ColumnMetaData(tableMetaData, 3, "col03", + new TypeMetaData(3, "integer", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn2); + + ColumnMetaData newTempColumn3 = new ColumnMetaData(tableMetaData, 4, "col04", + new TypeMetaData(4, "double", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn3); + + ColumnMetaData newTempColumn4 = new ColumnMetaData(tableMetaData, 5, "col05", + new TypeMetaData(5, "bool", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn4); + + ColumnMetaData newTempColumn5 = new ColumnMetaData(tableMetaData, 6, "col06", + new TypeMetaData(6, "date", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn5); + + ColumnMetaData newTempColumn6 = new ColumnMetaData(tableMetaData, 7, "col07", + new TypeMetaData(7, "timestamptz", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn6); + + IndexMetaData indexMetaData = new IndexMetaData("Idx1"); + indexMetaData.setTable(tableMetaData); + indexMetaData.setNamespace(tableMetaData.getNamespace()); + tableMetaData.addIndex(indexMetaData); + + } catch (OutOfMemoryError outofMemoryError) { + outofMemoryError.printStackTrace(); + } catch (MPPDBIDEException mppdbideException) { + mppdbideException.printStackTrace(); + } + return tableMetaData; + } + + private void createExcel(String fileName) { + FileOutputStream fos = null; + try { + // Create Workbook instance holding reference to .xlsx file + SXSSFWorkbook workbook = new SXSSFWorkbook(); + // Get first/desired sheet from the workbook + SXSSFSheet sheet = createSheet(workbook, "Sheet 1", false); + // Write some information in the cells or do what you want + SXSSFRow row1 = sheet.createRow(0); + SXSSFCell r1c2 = row1.createCell(0); + r1c2.setCellValue("col01"); + SXSSFCell r1c3 = row1.createCell(1); + r1c3.setCellValue("col02"); + SXSSFCell r1c4 = row1.createCell(2); + r1c4.setCellValue("col03"); + SXSSFCell r1c5 = row1.createCell(3); + r1c5.setCellValue("col04"); + SXSSFCell r1c6 = row1.createCell(4); + r1c6.setCellValue("col05"); + SXSSFCell r1c7 = row1.createCell(5); + r1c7.setCellValue("col06"); + SXSSFCell r1c8 = row1.createCell(6); + r1c8.setCellValue("col07"); + + SXSSFRow row2 = sheet.createRow(1); + SXSSFCell r2c2 = row2.createCell(0); + r2c2.setCellValue("1"); + SXSSFCell r2cc3 = row2.createCell(1); + r2cc3.setCellValue("item1"); + SXSSFCell r2cc4 = row2.createCell(2); + r2cc4.setCellValue("25"); + SXSSFCell r2cc5 = row2.createCell(3); + r2cc5.setCellValue(Double.parseDouble("25.5")); + SXSSFCell r2cc6 = row2.createCell(4); + r2cc6.setCellValue(Boolean.getBoolean("TRUE")); + SXSSFCell r2cc7 = row2.createCell(5); + r2cc7.setCellValue("2019-10-16 11:01:00"); + SXSSFCell r2cc8 = row2.createCell(6); + r2cc8.setCellValue("2019-10-16 11:01:00"); + + SXSSFRow row3 = sheet.createRow(2); + SXSSFCell r3c2 = row3.createCell(0); + r3c2.setCellValue("2"); + SXSSFCell r3cc3 = row3.createCell(1); + r3cc3.setCellValue(""); + SXSSFCell r3cc4 = row3.createCell(2); + r3cc4.setCellValue("24"); + SXSSFCell r3cc5 = row3.createCell(3); + r3cc5.setCellValue("25"); + SXSSFCell r3cc6 = row3.createCell(4); + r3cc6.setCellValue(""); + SXSSFCell r3cc7 = row3.createCell(5); + r3cc7.setCellValue(""); + SXSSFCell r3cc8 = row3.createCell(6); + r3cc8.setCellValue(""); + List list = new ArrayList<>(); + list.add(r3c2.getStringCellValue()); + list.add(r3cc3.getStringCellValue()); + list.add(r3cc4.getStringCellValue()); + list.add(r3cc5.getStringCellValue()); + list.add(r3cc6.getStringCellValue()); + list.add(r3cc7.getStringCellValue()); + list.add(r3cc8.getStringCellValue()); + for (int row = 3; row < 3000; row++) { + SXSSFRow newrow = new SXSSFRow(sheet); + newrow = sheet.createRow(row); + for (int i = 0; i < list.size(); i++) { + SXSSFCell cell = newrow.createCell(i); + cell.setCellValue(list.get(i)); + } + } + + // Save excel to HDD Drive + File pathToFile = new File(fileName); + if (!pathToFile.exists()) { + pathToFile.createNewFile(); + } + fos = new FileOutputStream(pathToFile); + workbook.write(fos); + } catch (Exception exception) { + exception.printStackTrace(); + } finally { + try { + if (fos != null) { + fos.flush(); + fos.close(); + } + } catch (IOException exception) { + exception.printStackTrace(); + } + } + } + + private static SXSSFSheet createSheet(SXSSFWorkbook wb, String prefix, boolean isHidden) { + SXSSFSheet sheet = null; + int count = 0; + for (int i = 0; i < wb.getNumberOfSheets(); i++) { + String sName = wb.getSheetName(i); + if (sName.startsWith(prefix)) count++; + } + if (count > 0) { + sheet = wb.createSheet(prefix + count); + } else { + sheet = wb.createSheet(prefix); + } + return sheet; + } + + @Test + public void testExecuteImportExcelData_2() { + try { + ImportExportOption option = new ImportExportOption(); + option.setExport(false); + option.setFileFormat("EXCEL(xlsx)"); + option.setAllColunms(true); + option.setHeader(true); + option.setEncoding("UTF-8"); + option.setDateSelector("yyyy-MM-dd HH:mm:ss"); + option.setZip(false); + option.setTablecolumns(new ArrayList( + Arrays.asList("col01", "coll02", "col03", "col04", "col05", "col06", "col07"))); + String filePath = "./testExecuteImportExcelData_2.xlsx"; + createExcel(filePath); + option.setFileName(filePath); + TableMetaData tableMetaData = getTableMetaData(); + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList( + Arrays.asList("col01", "coll02", "col03", "col04", "col05", "col06", "col07")), + null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + long totalRows = core.executeImportData(); + core.cancelImportExportOperation(); + assertEquals(2999, totalRows); + + } catch (MPPDBIDEException exception) { + fail("Not excepted to come here"); + } + } + + @Test + public void testExecuteImportData_Failure() { + try { + ImportExportOption option = new ImportExportOption(); + option.setExport(false); + option.setFileFormat("EXCEL(xlsx)"); + option.setAllColunms(true); + option.setHeader(true); + option.setEncoding("UTF-8"); + option.setDateSelector("yyyy/MM/dd HH:mm:ss"); + option.setZip(false); + option.setTablecolumns(new ArrayList( + Arrays.asList("col01", "coll02", "col03", "col04", "col05", "col06", "col07"))); + String filePath = "./testExecuteImportData_Failure.xlsx"; + createExcel(filePath); + option.setFileName(filePath); + TableMetaData tableMetaData = getTableMetaData(); + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList( + Arrays.asList("col01", "coll02", "col03", "col04", "col05", "col06", "col07")), + null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + core.executeImportData(); + core.cancelImportExportOperation(); + String s = core.getDisplayTableName(); + assertEquals(s, core.getDisplayName()); + core.cleanUp(); + } catch (TableImporExportException tableImporExportException) { + fail("Not excepted to come here"); + } catch (DatabaseOperationException exception) { + assertTrue(true); + } catch (DatabaseCriticalException exception) { + fail("Not excepted to come here"); + } catch (MPPDBIDEException mPPDBIDEException) { + fail("Not excepted to come here"); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ImportExportDataTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ImportExportDataTest.java new file mode 100644 index 0000000000000000000000000000000000000000..91a1e6c073ebeff2c43cf953224531ad5cc338c2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ImportExportDataTest.java @@ -0,0 +1,3206 @@ +package org.opengauss.mppdbide.test.presentation.table; + +import java.io.FileNotFoundException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.Properties; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.postgresql.util.HostSpec; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintType; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ExportOption; +import org.opengauss.mppdbide.bl.serverdatacache.ImportExportOption; +import org.opengauss.mppdbide.bl.serverdatacache.IndexMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.bl.serverdatacache.SystemNamespace; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TypeMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.UserNamespace; +import org.opengauss.mppdbide.mock.presentation.BaseConnectionHelper; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.presentation.exportdata.ImportExportDataCore; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.exceptions.TableImporExportException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; +import static org.junit.Assert.*; + +public class ImportExportDataTest extends BasicJDBCTestCaseAdapter +{ + + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + private DBConnection dbconn; + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#setUp() + */ + @Before + public void setUp() throws Exception + { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + connection = new MockConnection(); + MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + this.dbconn = CommonLLTUtils.getDBConnection(); + preparedstatementHandler = connection.getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + + connProfCache = DBConnProfCache.getInstance(); + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + MockPresentationBLPreferenceImpl.setFileEncoding("UTF-8"); + + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + // serverInfo.setSslPassword("12345"); + // serverInfo.setServerType(DATABASETYPE.GAUSS); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception + { + super.tearDown(); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().close(); + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) + { + connProfCache.removeServer(itr.next().getId()); + } + + connProfCache.closeAllNodes(); + + } + + @Test + public void testTTA_EXPORT_TABLE_001_01() + { + try + { + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + Server server = new Server(serverInfo); + Database database = new Database(server, 2, "Gauss"); + Properties properties = new Properties(); + + properties.setProperty("user", serverInfo.getDsUsername()); + properties.setProperty("password", new String(serverInfo.getPrd())); + properties.setProperty("allowEncodingChanges", "true"); + String encoding = System.getProperty("file.encoding"); + properties.setProperty("characterEncoding", encoding); + properties.setProperty("ApplicationName", "Data Studio"); + + BaseConnectionHelper connectionHelper = new BaseConnectionHelper("", properties, + new HostSpec[] {new HostSpec("127.0.0.1", 1111)}, "db", "user", false); + + getJDBCMockObjectFactory().getMockDriver().setupConnection(connectionHelper); + CommonLLTUtils.mockServerEncoding(connectionHelper.getPreparedStatementResultSetHandler()); + CommonLLTUtils.mockCheckDebugSupport(connectionHelper.getPreparedStatementResultSetHandler()); + CommonLLTUtils.mockCheckExplainPlanSupport(connectionHelper.getPreparedStatementResultSetHandler()); + database.connectToServer(); + Namespace namespace = new SystemNamespace(1, "pg_catalog", database); + database.getSystemNamespaceGroup().addToGroup((SystemNamespace) namespace); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(true); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.validateImportExportOptParameters(); + core.initializeCore(); + core.setFilePath(Paths.get("myfile.csv")); + core.executeExportData(CommonLLTUtils.getDBConnection(), true); + ExportOption exportOption = new ExportOption("csv", true, "Test", "TestName"); + exportOption.getFilePath(); + assertNotNull(exportOption.getFilePathWithSuffixFormat()); + assertTrue(exportOption.isZip()); + exportOption.setFileName("Test123"); + exportOption.setZip(false); + assertNotNull( exportOption.getFilePathWithSuffixFormat()); + + exportOption.setFolderName("Check"); + exportOption.setFormat(".sql"); + assertNotNull(exportOption.getFilePathWithSuffixFormat()); + + exportOption.setFormat("Excel(xlsx)"); + assertNotNull(exportOption.getFilePathWithSuffixFormat()); + exportOption.setFormat("Excel(xls)"); + assertNotNull(exportOption.getFilePathWithSuffixFormat()); + assertEquals("Test123",exportOption.getFileName()); + assertEquals("Check",exportOption.getFolderName()); + assertEquals("Excel(xls)",exportOption.getFormat()); + + } + catch (DatabaseOperationException e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void testTTA_EXPORT_TABLE_001_001() + { + try + { + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + Server server = new Server(serverInfo); + Database database = new Database(server, 2, "Gauss"); + Properties properties = new Properties(); + + properties.setProperty("user", serverInfo.getDsUsername()); + properties.setProperty("password", new String(serverInfo.getPrd())); + properties.setProperty("allowEncodingChanges", "true"); + String encoding = System.getProperty("file.encoding"); + properties.setProperty("characterEncoding", encoding); + properties.setProperty("ApplicationName", "Data Studio"); + + BaseConnectionHelper connectionHelper = new BaseConnectionHelper("", properties, + new HostSpec[] {new HostSpec("127.0.0.1", 1111)}, "db", "user", false); + + getJDBCMockObjectFactory().getMockDriver().setupConnection(connectionHelper); + CommonLLTUtils.mockServerEncoding(connectionHelper.getPreparedStatementResultSetHandler()); + CommonLLTUtils.mockCheckDebugSupport(connectionHelper.getPreparedStatementResultSetHandler()); + CommonLLTUtils.mockCheckExplainPlanSupport(connectionHelper.getPreparedStatementResultSetHandler()); + database.connectToServer(); + Namespace namespace = new SystemNamespace(1, "pg_catalog", database); + database.getSystemNamespaceGroup().addToGroup((SystemNamespace) namespace); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Binary"); + option.setHeader(true); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.validateImportExportOptParameters(); + core.initializeCore(); + core.setFilePath(Paths.get("myfile.bin")); + core.executeExportData(CommonLLTUtils.getDBConnection(), true); + } + catch (DatabaseOperationException e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void testTTA_EXPORT_TABLE_001_02() + { + try + { + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + Server server = new Server(serverInfo); + Database database = new Database(server, 2, "Gauss"); + Properties properties = new Properties(); + + properties.setProperty("user", serverInfo.getDsUsername()); + properties.setProperty("password", new String(serverInfo.getPrd())); + properties.setProperty("allowEncodingChanges", "true"); + String encoding = System.getProperty("file.encoding"); + properties.setProperty("characterEncoding", encoding); + properties.setProperty("ApplicationName", "Data Studio"); + + BaseConnectionHelper connectionHelper = new BaseConnectionHelper("", properties, + new HostSpec[] {new HostSpec("127.0.0.1", 1111)}, "db", "user", false); + + getJDBCMockObjectFactory().getMockDriver().setupConnection(connectionHelper); + CommonLLTUtils.mockServerEncoding(connectionHelper.getPreparedStatementResultSetHandler()); + CommonLLTUtils.mockCheckDebugSupport(connectionHelper.getPreparedStatementResultSetHandler()); + CommonLLTUtils.mockCheckExplainPlanSupport(connectionHelper.getPreparedStatementResultSetHandler()); + database.connectToServer(); + Namespace namespace = new SystemNamespace(1, "pg_catalog", database); + database.getSystemNamespaceGroup().addToGroup((SystemNamespace) namespace); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(true); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + core.setFilePath(Paths.get("")); + core.executeExportData(this.dbconn, true); + + } + catch (DatabaseOperationException e) + { + if (!(e.getCause() instanceof FileNotFoundException)) + { + fail(e.getMessage()); + } + } + catch (Exception e) + { + fail(e.getMessage()); + } + } + + @Test + public void testTTA_EXPORT_TABLE_001_03() + { + try + { + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + Server server = new Server(serverInfo); + Database database = new Database(server, 2, "Gauss"); + Properties properties = new Properties(); + + properties.setProperty("user", serverInfo.getDsUsername()); + properties.setProperty("password", new String(serverInfo.getPrd())); + properties.setProperty("allowEncodingChanges", "true"); + String encoding = System.getProperty("file.encoding"); + properties.setProperty("characterEncoding", encoding); + properties.setProperty("ApplicationName", "Data Studio"); + + BaseConnectionHelper connectionHelper = new BaseConnectionHelper("", properties, + new HostSpec[] {new HostSpec("127.0.0.1", 1111)}, "db", "user", true); + + getJDBCMockObjectFactory().getMockDriver().setupConnection(connectionHelper); + CommonLLTUtils.mockServerEncoding(connectionHelper.getPreparedStatementResultSetHandler()); + CommonLLTUtils.mockCheckDebugSupport(connectionHelper.getPreparedStatementResultSetHandler()); + CommonLLTUtils.mockCheckExplainPlanSupport(connectionHelper.getPreparedStatementResultSetHandler()); + database.connectToServer(); + Namespace namespace = new SystemNamespace(1, "pg_catalog", database); + database.getSystemNamespaceGroup().addToGroup((SystemNamespace) namespace); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(true); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull("*"); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.initializeCore(); + core.setImportExportoptions(option); + core.validateImportExportOptParameters(); + core.setFilePath(Paths.get("somefile.csv")); + DBConnection dbConnection = CommonLLTUtils.getDBConnection(); + core.executeExportData(CommonLLTUtils.getDBConnection(), true); + } + catch (DatabaseOperationException e) + { + if (!(e.getCause() instanceof SQLException)) + { + fail(e.getMessage()); + } + } + catch (Exception e) + { + fail(e.getMessage()); + } + } + + + @Test + public void testTTA_IMPORT_TABLE_FUNC_001() + { + try + { + CommonLLTUtils.createTableRS(preparedstatementHandler); + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + Server server = new Server(serverInfo); + Database database = new Database(server, 2, "Gauss"); + Properties properties = new Properties(); + + properties.setProperty("user", serverInfo.getDsUsername()); + properties.setProperty("password", new String(serverInfo.getPrd())); + properties.setProperty("allowEncodingChanges", "true"); + String encoding = System.getProperty("file.encoding"); + properties.setProperty("characterEncoding", encoding); + properties.setProperty("ApplicationName", "Data Studio"); + + BaseConnectionHelper connectionHelper = new BaseConnectionHelper("", properties, + new HostSpec[] {new HostSpec("127.0.0.1", 1111)}, "db", "user", false); + + getJDBCMockObjectFactory().getMockDriver().setupConnection(connectionHelper); + CommonLLTUtils.mockServerEncoding(connectionHelper.getPreparedStatementResultSetHandler()); + CommonLLTUtils.mockCheckDebugSupport(connectionHelper.getPreparedStatementResultSetHandler()); + CommonLLTUtils.mockCheckExplainPlanSupport(connectionHelper.getPreparedStatementResultSetHandler()); + + database.connectToServer(); + + Namespace namespace = new UserNamespace(1, "namespace1", database); + database.getUserNamespaceGroup().addToGroup((UserNamespace) namespace); + + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + ColumnMetaData newTempColumn1 = new ColumnMetaData(tablemetaData, 1, "Col2", + new TypeMetaData(1, "text", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn1); + + IndexMetaData indexMetaData = new IndexMetaData("Idx1"); + + indexMetaData.setTable(tablemetaData); + indexMetaData.setNamespace(tablemetaData.getNamespace()); + tablemetaData.addIndex(indexMetaData); + + CommonLLTUtils.fetchColMetadataForTableRS(preparedstatementHandler); + CommonLLTUtils.getConstaraintForTableRS(preparedstatementHandler); + CommonLLTUtils.getIndexForTableRS(preparedstatementHandler); + + Files.deleteIfExists(Paths.get("samplecsv.csv")); + + Files.createFile(Paths.get("samplecsv.csv")); + + ImportExportOption option = new ImportExportOption(); + option.setFileFormat("other"); + option.setFileName("samplecsv.csv"); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.initializeCore(); + core.setImportExportoptions(option); + core.validateImportExportOptParameters(); + core.executeImportData(); + + } + catch (TableImporExportException e) + { + assertEquals("Please enter delimiter value.", e.getDBErrorMessage()); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void test_ExportTableData_composeQuery1() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(true); + option.setQuotes("\""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.setFilePath(Paths.get("myfile.xls")); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + String query1 = core.composeExcelQuery(); + assertEquals("SELECT * FROM pg_catalog.\"MyTable\"", query1); + assertEquals("COPY pg_catalog.\"MyTable\" TO STDOUT DELIMITERS ',' HEADER CSV QUOTE '\"' ;", query); + + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_ExportTableData_composeQuery2() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter("#"); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" TO STDOUT DELIMITERS '#' CSV ;", query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_ExportTableData_composeQuery3() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Binary"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" TO STDOUT BINARY ;", query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_ExportTableData_composeQuery4() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Binary"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(false); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" (col1) TO STDOUT BINARY ;", query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_ExportTableData_composeQuery5() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Binary"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding("UTF-8"); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" TO STDOUT BINARY ENCODING 'UTF-8' ;", query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_ExportTableData_composeQuery6() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(false); + option.setQuotes("\""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding("UTF-8"); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" TO STDOUT DELIMITERS ',' CSV QUOTE '\"' ENCODING 'UTF-8' ;", + query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_ExportTableData_composeQuery7() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" TO STDOUT DELIMITERS ',' CSV ;", query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_ExportTableData_composeQuery8() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape("\""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" TO STDOUT DELIMITERS ',' CSV ESCAPE '\"' ;", query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_ExportTableData_composeQuery9() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(true); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" TO STDOUT DELIMITERS ',' HEADER CSV ;", query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_ExportTableData_composeQuery10() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter("\t"); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" TO STDOUT DELIMITERS '\t' CSV ;", query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_ExportTableData_composeQuery11() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter("|"); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" TO STDOUT DELIMITERS '|' CSV ;", query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_ExportTableData_composeQuery12() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(";"); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" TO STDOUT DELIMITERS ';' CSV ;", query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_ExportTableData_composeQuery13() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding("UTF-8"); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" TO STDOUT DELIMITERS ',' CSV ENCODING 'UTF-8' ;", query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_ExportTableData_composeQuery14() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding("UTF-8"); + option.setDelimiter(","); + option.setAllColunms(false); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" (col1) TO STDOUT DELIMITERS ',' CSV ENCODING 'UTF-8' ;", + query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + public void test_ExportTableData_composeQuery15() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull("*"); + option.setEncoding("UTF-8"); + option.setDelimiter(","); + option.setAllColunms(false); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals( + "COPY pg_catalog.\"MyTable\" (col1) TO STDOUT DELIMITERS ',' NULL '*' CSV ENCODING 'UTF-8' ;", + query); + + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + public void test_ExportTableData_composeQuery16() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding("SQL_ASCII"); + option.setDelimiter("\t"); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" TO STDOUT DELIMITERS '\t' CSV ENCODING 'SQL_ASCII' ;", query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + public void test_ExportTableData_composeQuery17() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding("GBK"); + option.setDelimiter("\t"); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" TO STDOUT DELIMITERS '\t' CSV ENCODING 'GBK' ;", query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + public void test_ExportTableData_composeQuery18() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding("LATIN1"); + option.setDelimiter("\t"); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" TO STDOUT DELIMITERS '\t' CSV ENCODING 'LATIN1' ;", query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + public void test_ExportTableData_composeQuery19() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding("SQL_ASCII"); + option.setDelimiter("p"); + option.setAllColunms(false); + + option.setTablecolumns(new ArrayList(Arrays.asList("col1", "col2"))); + option.getTablecolumns(); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals( + "COPY pg_catalog.\"MyTable\" (col1,col2) TO STDOUT DELIMITERS 'p' CSV ENCODING 'SQL_ASCII' ;", + query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_ExportTableData_composeQuery20() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(true); + option.setQuotes("#"); + option.setEscape("*"); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" TO STDOUT DELIMITERS ',' HEADER CSV QUOTE '#' ESCAPE '*' ;", + query); + + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + public void test_ImportTableData_composeQuery1() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + ImportExportOption option = new ImportExportOption(); + option.setExport(false); + option.setFileFormat("Csv"); + + try + { + option.setHeader(true); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" FROM STDIN DELIMITERS ',' HEADER CSV ;", query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + try + { + option.setHeader(false); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding("SQL_ASCII"); + option.setDelimiter(";"); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" FROM STDIN DELIMITERS ';' CSV ENCODING 'SQL_ASCII' ;", query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + public void test_ImportTableData_composeQuery2() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + ImportExportOption option = new ImportExportOption(); + option.setExport(false); + option.setFileFormat("Csv"); + + try + { + + option.setHeader(true); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter(","); + option.setAllColunms(false); + + option.setTablecolumns(new ArrayList(Arrays.asList("col1", "col2"))); + option.getTablecolumns(); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" (col1,col2) FROM STDIN DELIMITERS ',' HEADER CSV ;", query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + try + { + option.setHeader(true); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding("UTF-8"); + option.setDelimiter("/t"); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" FROM STDIN DELIMITERS '/t' HEADER CSV ENCODING 'UTF-8' ;", + query); + } + + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + try + { + option.setHeader(true); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding("GBK"); + option.setDelimiter("|"); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals("COPY pg_catalog.\"MyTable\" FROM STDIN DELIMITERS '|' HEADER CSV ENCODING 'GBK' ;", + query); + } + + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + + } + + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + public void test_ImportTableData_composeQuery3() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + ImportExportOption option = new ImportExportOption(); + option.setExport(false); + option.setFileFormat("Csv"); + + try + { + option.setHeader(true); + option.setQuotes("p"); + option.setEscape("q"); + option.setReplaceNull("r"); + option.setEncoding(""); + option.setDelimiter(";"); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals( + "COPY pg_catalog.\"MyTable\" FROM STDIN DELIMITERS ';' NULL 'r' HEADER CSV QUOTE 'p' ESCAPE 'q' ;", + query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + public void test_ImportResultData_composeQuery1() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + + ImportExportOption option = new ImportExportOption(); + option.setExport(false); + option.setFileFormat("Csv"); + + try + { + option.setHeader(true); + option.setQuotes("p"); + option.setEscape("q"); + option.setReplaceNull("r"); + option.setEncoding(""); + option.setDelimiter(";"); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(database, + new ArrayList(Arrays.asList("col1")), "select * from pg_class", null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals( + "COPY (select * from pg_class) FROM STDIN DELIMITER ';' NULL 'r' HEADER CSV QUOTE 'p' ESCAPE 'q' ;", + query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + public void test_ImportResultData_composeQuery2() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + + ImportExportOption option = new ImportExportOption(); + option.setExport(false); + option.setFileFormat("Csv"); + + try + { + option.setHeader(true); + option.setQuotes("p"); + option.setEscape("q"); + option.setReplaceNull("r"); + option.setEncoding(""); + option.setDelimiter(";"); + option.setAllColunms(false); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(database, + new ArrayList(Arrays.asList("col1")), "select * from pg_class", null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + String query = core.composeQuery(); + assertEquals( + "COPY (SELECT col1 FROM (select * from pg_class)) FROM STDIN DELIMITER ';' NULL 'r' HEADER CSV QUOTE 'p' ESCAPE 'q' ;", + query); + } + catch (TableImporExportException e1) + { + fail("Not excepted to come here"); + } + + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_impotExport_validation1() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + ImportExportOption option1 = new ImportExportOption(); + option1.setFileFormat("csv"); + option1.setDelimiter(""); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option1); + core.initializeCore(); + core.validateImportExportOptParameters(); + } + catch (TableImporExportException e1) + { + assertEquals("Enter delimiter value.", e1.getDBErrorMessage()); + } + + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_impotExport_validation2() + { + Database database = connProfCache.getDbForProfileId(profileId); + ImportExportOption option = new ImportExportOption(); + try + { + TableMetaData tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + option.setFileFormat("Csv"); + option.setReplaceNull( + "datastudiodatastudiodatastudiodatastudiodatastudiodatastudiodatastudiodatastudiodatastudiodatastudiodatastudiodatastudiodtastudiodatastudio"); + option.getReplaceNull().length(); + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + // String query = core.composeQuery(); + } + + catch (TableImporExportException e1) + { + assertEquals("Maximum 100 characters allowed for null string.", e1.getDBErrorMessage()); + + } + catch (DatabaseOperationException e) + { + fail(e.getMessage()); + + } + catch (MPPDBIDEException e) + { + fail(e.getMessage()); + + } + } + + @Test + public void test_impotExport_validation3() + { + Database database = connProfCache.getDbForProfileId(profileId); + ImportExportOption option = new ImportExportOption(); + try + { + TableMetaData tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + option.setFileFormat("Csv"); + option.setReplaceNull("a"); + option.setQuotes("a"); + option.setDelimiter("a"); + + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + + } + + catch (TableImporExportException e1) + { + assertEquals("Null parameter can not be same as the delimiter and quote parameter.", + e1.getDBErrorMessage()); + + } + catch (DatabaseOperationException e) + { + fail(e.getMessage()); + + } + catch (MPPDBIDEException e) + { + fail(e.getMessage()); + + } + } + + @Test + public void test_impotExport_validation4() + { + Database database = connProfCache.getDbForProfileId(profileId); + + try + { + TableMetaData tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + ImportExportOption option = new ImportExportOption(); + option.setFileFormat("Csv"); + option.setQuotes("abc"); + option.setEscape(""); + option.getQuotes().length(); + option.getEscape().length(); + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + // String query = core.composeQuery(); + } + + catch (TableImporExportException e1) + { + assertEquals("Only single character is allowed for quote/escape.", e1.getDBErrorMessage()); + + } + catch (DatabaseOperationException e) + { + fail(e.getMessage()); + + } + catch (MPPDBIDEException e) + { + fail(e.getMessage()); + + } + } + + @Test + public void test_impotExport_validation5() + { + Database database = connProfCache.getDbForProfileId(profileId); + + try + { + TableMetaData tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + ImportExportOption option = new ImportExportOption(); + option.setFileFormat("Csv"); + option.setQuotes(""); + option.setEscape("abc"); + option.getQuotes().length(); + option.getEscape().length(); + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + // String query = core.composeQuery(); + } + + catch (TableImporExportException e1) + { + assertEquals("Only single character is allowed for quote/escape.", e1.getDBErrorMessage()); + + } + catch (DatabaseOperationException e) + { + fail(e.getMessage()); + + } + catch (MPPDBIDEException e) + { + fail(e.getMessage()); + + } + } + + @Test + public void test_impotExport_validation6() + { + Database database = connProfCache.getDbForProfileId(profileId); + + try + { + TableMetaData tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + ImportExportOption option = new ImportExportOption(); + option.setFileFormat("Csv"); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull("a"); + option.setDelimiter("a"); + option.getQuotes().length(); + option.getDelimiter().length(); + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + // String query = core.composeQuery(); + } + + catch (TableImporExportException e1) + { + assertEquals("Null parameter can not be same as the delimiter and quote parameter.", + e1.getDBErrorMessage()); + + } + catch (DatabaseOperationException e) + { + fail(e.getMessage()); + } + catch (MPPDBIDEException e) + { + fail(e.getMessage()); + } + } + + @Test + public void test_impotExport_validation7() + { + Database database = connProfCache.getDbForProfileId(profileId); + ImportExportOption option = new ImportExportOption(); + try + { + TableMetaData tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + option.setFileFormat("Csv"); + option.setQuotes("'"); + option.setEscape(""); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + // String query = core.composeQuery(); + assertEquals("'", option.getQuotes()); + + } + + catch (TableImporExportException e1) + { + + } + catch (DatabaseOperationException e) + { + fail(e.getMessage()); + } + catch (MPPDBIDEException e) + { + fail(e.getMessage()); + } + } + + @Test + public void test_impotExport_validation8() + { + Database database = connProfCache.getDbForProfileId(profileId); + ImportExportOption option = new ImportExportOption(); + try + { + TableMetaData tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + option.setFileFormat("Csv"); + + option.setEscape("'"); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + // String query = core.composeQuery(); + assertEquals("'", option.getEscape()); + + } + + catch (TableImporExportException e) + { + fail(e.getMessage()); + + } + catch (DatabaseOperationException e) + { + fail(e.getMessage()); + + } + catch (MPPDBIDEException e) + { + fail(e.getMessage()); + + } + } + + @Test + public void test_impotExport_validation9() + { + Database database = connProfCache.getDbForProfileId(profileId); + ImportExportOption option = new ImportExportOption(); + try + { + TableMetaData tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + option.setFileFormat("Csv"); + option.setDelimiter("'"); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + // String query = core.composeQuery(); + assertEquals("'", option.getDelimiter()); + + } + + catch (TableImporExportException e) + { + fail(e.getMessage()); + + } + catch (DatabaseOperationException e) + { + fail(e.getMessage()); + + } + catch (MPPDBIDEException e) + { + fail(e.getMessage()); + + } + } + + @Test + public void test_impotExport_validation10() + { + Database database = connProfCache.getDbForProfileId(profileId); + ImportExportOption option = new ImportExportOption(); + try + { + TableMetaData tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + option.setFileFormat("Csv"); + option.setReplaceNull("'"); + option.setQuotes(""); + option.setEscape(""); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + // String query = core.composeQuery(); + assertEquals("'", option.getReplaceNull()); + + } + + catch (TableImporExportException e) + { + fail(e.getMessage()); + + } + catch (DatabaseOperationException e) + { + fail(e.getMessage()); + + } + catch (MPPDBIDEException e) + { + fail(e.getMessage()); + + } + } + + @Test + public void test_impotExport_validation11() + { + Database database = connProfCache.getDbForProfileId(profileId); + ImportExportOption option = new ImportExportOption(); + try + { + TableMetaData tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + option.setFileFormat("Csv"); + option.setReplaceNull("\r\n"); + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + // String query = core.composeQuery(); + option.getReplaceNull(); + + } + + catch (TableImporExportException e1) + { + assertEquals("Null String should not contain newline or carriage return.", e1.getDBErrorMessage()); + } + catch (DatabaseOperationException e) + { + fail(e.getMessage()); + + } + catch (MPPDBIDEException e) + { + fail(e.getMessage()); + + } + } + + @Test + public void test_impotExport_validation12() + { + Database database = connProfCache.getDbForProfileId(profileId); + + try + { + TableMetaData tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + ImportExportOption option = new ImportExportOption(); + option.setFileFormat("Csv"); + option.setQuotes("a"); + option.setEscape("a"); + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + } + + catch (TableImporExportException e1) + { + assertEquals("Quote character should not be same as the Escape character.", e1.getDBErrorMessage()); + + } + catch (DatabaseOperationException e) + { + fail(e.getMessage()); + + } + catch (MPPDBIDEException e) + { + fail(e.getMessage()); + + } + } + + @Test + public void test_impotExport_validation13() + { + Database database = connProfCache.getDbForProfileId(profileId); + + try + { + TableMetaData tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + ImportExportOption option = new ImportExportOption(); + option.setFileFormat("Binary"); + option.setEncoding("UTF-8"); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(null); + option.setDelimiter(""); + ArrayList list = new ArrayList(4); + list.add("col1"); + list.add("col2"); + option.setTablecolumns(list); + + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + assertEquals("UTF-8", option.getEncoding()); + assertEquals("", option.getQuotes()); + assertEquals("", option.getEscape()); + assertEquals("", option.getDelimiter()); + assertEquals(null, option.getReplaceNull()); + + } + + catch (TableImporExportException e) + { + fail(e.getMessage()); + + } + catch (DatabaseOperationException e) + { + fail(e.getMessage()); + + } + catch (MPPDBIDEException e) + { + fail(e.getMessage()); + + } + } + + @Test + public void test_impotExport_validation14() + { + Database database = connProfCache.getDbForProfileId(profileId); + + try + { + TableMetaData tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + ImportExportOption option = new ImportExportOption(); + option.setFileFormat("CSv"); + option.setEncoding("UTF-8"); + option.setEscape(""); + option.setQuotes("a"); + option.setDelimiter("a"); + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + } + + catch (TableImporExportException e1) + { + assertEquals("Quote character should not be same as the delimiter.", e1.getDBErrorMessage()); + } + catch (DatabaseOperationException e) + { + fail(e.getMessage()); + + } + catch (MPPDBIDEException e) + { + fail(e.getMessage()); + + } + } + + @Test + public void test_impotExport_validation15() + { + Database database = connProfCache.getDbForProfileId(profileId); + ImportExportOption option = new ImportExportOption(); + try + { + TableMetaData tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + + option.setFileFormat("Csv"); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull("\""); + option.setDelimiter("|"); + + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + } + + catch (TableImporExportException e1) + { + assertEquals("Null parameter can not be same as the default quote parameter.", e1.getDBErrorMessage()); + + } + catch (DatabaseOperationException e) + { + fail(e.getMessage()); + + } + catch (MPPDBIDEException e) + { + fail(e.getMessage()); + + } + } + + @Test + public void test_impotExport_validation16() + { + Database database = connProfCache.getDbForProfileId(profileId); + ImportExportOption option = new ImportExportOption(); + ArrayList selectedColsList = new ArrayList(4); + try + { + TableMetaData tableMetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tableMetaData.setTempTable(true); + tableMetaData.setIfExists(true); + tableMetaData.setName("MyTable"); + tableMetaData.setHasOid(true); + tableMetaData.setDistributeOptions("HASH"); + tableMetaData.setNodeOptions("Node1"); + tableMetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tableMetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tableMetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tableMetaData.getColumns().addItem(newTempColumn); + option.setExport(true); + option.setFileFormat("Csv"); + option.setQuotes("a"); + option.setEscape("b"); + option.setReplaceNull("\""); + option.setDelimiter(","); + + option.setTablecolumns(selectedColsList); + option.getTablecolumns().clear(); + + ImportExportDataCore core = new ImportExportDataCore(tableMetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + } + + catch (TableImporExportException e1) + { + assertEquals("Select at least one column to Export.", e1.getDBErrorMessage()); + } + catch (DatabaseOperationException e) + { + fail(e.getMessage()); + + } + catch (MPPDBIDEException e) + { + fail(e.getMessage()); + } + } + + @Test + public void test_ExportTableData_validate17() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter("hasfgjshdafgjshdafhadfh"); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + fail(); + } + catch (TableImporExportException e1) + { + assertEquals("Delimiter must be maximum of 10 bytes.", e1.getDBErrorMessage()); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_ExportTableData_validate18() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(false); + option.setQuotes("dfgdfgdgh"); + option.setEscape(""); + option.setReplaceNull(""); + option.setEncoding(""); + option.setDelimiter("hasfgjshdafgjshdafhadfh"); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + fail(); + } + catch (TableImporExportException e1) + { + assertEquals("Only single character is allowed for quote/escape.", e1.getDBErrorMessage()); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + + @Test + public void test_ExportTableData_validate19() + { + + try + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData = new TableMetaData(1, "Table1", database.getNameSpaceById(1), "tablespace"); + tablemetaData.setTempTable(true); + tablemetaData.setIfExists(true); + tablemetaData.setName("MyTable"); + tablemetaData.setHasOid(true); + tablemetaData.setDistributeOptions("HASH"); + tablemetaData.setNodeOptions("Node1"); + tablemetaData.setDescription("Table description"); + + ConstraintMetaData constraintMetaData = + new ConstraintMetaData(1, "MyConstarint", ConstraintType.UNIQUE_KEY_CONSTRSINT); + + tablemetaData.addConstraint(constraintMetaData); + + ColumnMetaData newTempColumn = new ColumnMetaData(tablemetaData, 1, "Col1", + new TypeMetaData(1, "bigint", database.getNameSpaceById(1))); + tablemetaData.getColumns().addItem(newTempColumn); + + try + { + + ImportExportOption option = new ImportExportOption(); + option.setExport(true); + option.setFileFormat("Csv"); + option.setHeader(false); + option.setQuotes(""); + option.setEscape("3456546"); + option.setReplaceNull(""); + option.setEncoding("UTF-8"); + option.setDelimiter(","); + option.setAllColunms(true); + option.setTablecolumns(new ArrayList(Arrays.asList("col1"))); + ImportExportDataCore core = new ImportExportDataCore(tablemetaData, + new ArrayList(Arrays.asList("col1")), null, null, null); + core.setImportExportoptions(option); + core.initializeCore(); + core.validateImportExportOptParameters(); + fail(); + } + catch (TableImporExportException e1) + { + assertEquals("Only single character is allowed for quote/escape.", e1.getDBErrorMessage()); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/MockPresentationBLPreferenceImpl.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/MockPresentationBLPreferenceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..d4edea69f30089cb121e6664db4ddd4d2de54ae7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/MockPresentationBLPreferenceImpl.java @@ -0,0 +1,91 @@ +package org.opengauss.mppdbide.test.presentation.table; + +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import static org.junit.Assert.*; + +public class MockPresentationBLPreferenceImpl implements IBLPreference +{ + public MockPresentationBLPreferenceImpl() + { + + + } + + private static String DsEncoding; + private static String fileEncoding; + private static String dateFormat; + private static String timeFormat; + @Override + public int getSQLHistorySize() + { + + return 0; + } + + @Override + public int getSQLQueryLength() + { + + return 0; + } + + @Override + public String getDSEncoding() + { + return DsEncoding; + } + + @Override + public String getFileEncoding() + { + + return fileEncoding; + } + + public static void setDsEncoding(String DsEncoding) + { + MockPresentationBLPreferenceImpl.DsEncoding = DsEncoding; + + } + + public static void setFileEncoding(String fileEncoding) + { + MockPresentationBLPreferenceImpl.fileEncoding = fileEncoding; + + } + + public static void setDateFormat(String dateFormat) + { + MockPresentationBLPreferenceImpl.dateFormat = dateFormat; + + } + + public static void setTimeFormat(String timeFormat) + { + MockPresentationBLPreferenceImpl.timeFormat = timeFormat; + + } + + @Override + public boolean isIncludeEncoding() + { + + return false; + } + + @Override + public String getDateFormat() { + return dateFormat; + } + + @Override + public String getTimeFormat() { + return timeFormat; + } + + + + + + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/OptimizerStatisticsCoreTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/OptimizerStatisticsCoreTest.java new file mode 100644 index 0000000000000000000000000000000000000000..b733e90bfb9d808473aeb3c4161fcbabc8e02569 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/OptimizerStatisticsCoreTest.java @@ -0,0 +1,145 @@ +package org.opengauss.mppdbide.test.presentation.table; + +import java.util.Iterator; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.presentation.OptimizerStatisticsCore; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; +import static org.junit.Assert.*; + +public class OptimizerStatisticsCoreTest extends BasicJDBCTestCaseAdapter +{ + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + OptimizerStatisticsCore stCore = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + Database database = null; + @Before + public void setUp() throws Exception + { + + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + connection = new MockConnection(); + // test for logging + MPPDBIDELoggerUtility + .setArgs(new String[] {"-logfolder=.", "-detailLogging=true"}); + + // MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + + connProfCache = DBConnProfCache.getInstance(); + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + // serverInfo.setSslPassword("12345"); + // serverInfo.setServerType(DATABASETYPE.GAUSS); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + database = connProfCache.getDbForProfileId(profileId); + + stCore = new OptimizerStatisticsCore(database); + + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception + { + database.getServer().close(); + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) + { + connProfCache.removeServer(itr.next().getId()); + } + + connProfCache.closeAllNodes(); + } + + @Test + public void test_OptimizerStatisticsCore() + { + if (stCore != null) + { + stCore.getTermConnection(); + assertTrue(true); + }else{ + assertTrue(false); + } + } + + @Test + public void test_OptimizerStatisticsCore_getWindowDetails() + { + if (stCore != null) + { + stCore.getWindowDetails(); + stCore.getWindowDetails().getIcon(); + stCore.getWindowDetails().getShortTitle(); + stCore.getWindowDetails().getTitle(); + stCore.getWindowDetails().getUniqueID(); + stCore.getWindowDetails().isCloseable(); + assertTrue(true); + }else{ + assertTrue(false); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/QueryResultMaterializerTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/QueryResultMaterializerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..56c16d213a67fef09b296d6f157eec4ca944fee5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/QueryResultMaterializerTest.java @@ -0,0 +1,228 @@ +package org.opengauss.mppdbide.test.presentation.table; + +import java.util.Iterator; +import java.util.Properties; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.StmtExecutor; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.IQueryMaterializer; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.QueryResult; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.bl.sqlhistory.IQueryExecutionSummary; +import org.opengauss.mppdbide.bl.sqlhistory.SQLHistoryFactory; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtilsHelper; +import org.opengauss.mppdbide.presentation.EditTableDataCore; +import org.opengauss.mppdbide.presentation.edittabledata.QueryResultMaterializer; +import org.opengauss.mppdbide.presentation.resultset.ConsoleDataWrapper; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; +import static org.junit.Assert.*; + +public class QueryResultMaterializerTest extends BasicJDBCTestCaseAdapter +{ + + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + EditTableDataHelper helper; + Object dataProvider; + EditTableDataCore coreObject; + private Database database; + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#setUp() + */ + @Before + public void setUp() throws Exception + { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + connection = new MockConnection(); + MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + MockPresentationBLPreferenceImpl.setFileEncoding("UTF-8"); + + preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + connProfCache = DBConnProfCache.getInstance(); + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + initializeHelper(); + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception + { + super.tearDown(); + + database = connProfCache.getDbForProfileId(profileId); + database.getServer().close(); + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) + { + connProfCache.removeServer(itr.next().getId()); + itr = connProfCache.getServers().iterator(); + } + + connProfCache.closeAllNodes(); + + } + + public void initializeHelper() + { + helper = new EditTableDataHelper( + connProfCache.getDbForProfileId(profileId)); + try + { + dataProvider = helper.getDataProvider(preparedstatementHandler); + coreObject = helper.getCoreObject(); + + } + catch (DatabaseCriticalException e) + { + e.printStackTrace(); + } + catch (DatabaseOperationException e) + { + e.printStackTrace(); + } + catch (MPPDBIDEException e) + { + e.printStackTrace(); + } + } + + @Test + public void test_query_materializer() + { + String selectedQry = CommonLLTUtils.FETCH_ALL_NAMESPACE_LOAD_ALL; + + IQueryExecutionSummary summary = SQLHistoryFactory.getNewExlainQueryExecutionSummary("DataBase","Server", + "conn", selectedQry); + + ConsoleDataWrapper consoleData = new ConsoleDataWrapper(); + + IQueryMaterializer materializer = new QueryResultMaterializer(null, + summary, consoleData, null, false, false); + + String url = null; + Properties props = new Properties(); + + DBConnection dbConnection = new DBConnection(); + try + { + CommonLLTUtils.initDriver("org.postgresql.Driver"); + } + catch (DatabaseOperationException e1) + { + + e1.printStackTrace(); + } + + props.setProperty("user", "test"); + props.setProperty("password", "test"); + props.setProperty("allowEncodingChanges", "true"); + String encoding = System.getProperty("file.encoding"); + props.setProperty("characterEncoding", encoding); + props.setProperty("ApplicationName", "MPP IDE"); + props.setProperty("protocolVersion", "3.5"); + url = "jdbc:postgresql:127.0.0.1:1234/testDB"; + + try + { + dbConnection.dbConnect(props, url); + } + catch (DatabaseOperationException e1) + { + + e1.printStackTrace(); + } + catch (DatabaseCriticalException e1) + { + + e1.printStackTrace(); + } + try + { + StmtExecutor stmt = new StmtExecutor(selectedQry, dbConnection); + stmt.execute(); + QueryResult queryResult = new QueryResult(stmt); + if (null != materializer) + { + materializer.materializeQueryResult(queryResult); + } + } + + catch (Exception e) + { + assertTrue(true); + } + + + } + + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ServerVersionTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ServerVersionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..3ee936d9be2f5d6f7c4eea929c1f9a540f90b22e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ServerVersionTest.java @@ -0,0 +1,203 @@ +package org.opengauss.mppdbide.test.presentation.table; + +import java.util.Iterator; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.exceptions.PasswordExpiryException; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; +import com.mockrunner.mock.jdbc.MockResultSet; +import static org.junit.Assert.*; + +public class ServerVersionTest extends BasicJDBCTestCaseAdapter +{ + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + ServerConnectionInfo serverInfo; + public static final String version1 = + "PostgreSQL 9.2.4 (openGauss 1.0 build e2c0f862) compiled at 2020-04-29 10:27:47 commit 2144 last mr 131 debug on aarch64-unknown-linux-gnu, compiled by g++ (GCC) 8.2.0, 64-bit"; + public static final String version2 = + "Gauss200 OLAP V100R006C10 build 8496 compiled at 2017-03-18 01:17:38 on x86_64-unknown-linux-gnu, compiled by g++ (GCC) 5.4.0, 64-bit"; + public static final String version3 = + "PostgreSQL 9.2.4 (Gauss200 OLAP V100R007C10 build 3f29067a) compiled at 2018-03-02 12:28:00 commit 1072 last mr 1378 on x86_64-unknown-linux-gnu, compiled by g++ (GCC) 5.4.0, 64-bit"; + public static final String version4 = + "Gauss200 OLAP V100R006C10 build 8496 compiled at 2017-03-18 01:17:38 on x86_64-unknown-linux-gnu, compiled by g++ (GCC) 5.4.0, 64-bit"; + + public static final String version5 = + "GaussDBV100R003C20SPC107B110 (2017-08-31 08:46:25) on x86_64-unknown-linux-gnu, compiled by gcc (SUSE Linux) 4.3.4 [gcc-4_3-branch revision 152973], 64-bit"; + + public static final String version6 = + "PostgreSQL 9.2.4 (openGauss 1.0 build e2c0f862) compiled at 2020-04-29 10:27:47 commit 2144 last mr 131 debug on aarch64-unknown-linux-gnu, compiled by g++ (GCC) 8.2.0, 64-bit"; + public static final String versionOLAPV1r7c10 = + "Gauss200 OLAP V100R006C10 build 12125 compiled at 2018-04-25 22:00:40 on x86_64-unknown-linux-gnu, compiled by g++ (GCC) 5.4.0, 64-bit"; + public static final String version7="Gauss200 OLAP V100R006C10SPC007B008 compiled at 2016-11-11 16:18:35 on x86_64-unknown-linux-gnu, compiled by g++ (SUSE Linux) 4.3.4 [gcc-4_3-branch revision 152973], 64-bit"; + private String parsedVersion; + private String parsedVersiontooltip; + JobCancelStatus status; + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#setUp() + */ + @Before + public void setUp() throws Exception + { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + connection = new MockConnection(); + MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + preparedstatementHandler = connection.getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + CommonLLTUtils.columnComments(preparedstatementHandler); + CommonLLTUtils.getPartitionData(preparedstatementHandler); + CommonLLTUtils.getConstaraintForTableRS(preparedstatementHandler); + CommonLLTUtils.getPropertiesConstraint(preparedstatementHandler); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + connProfCache = DBConnProfCache.getInstance(); + + serverInfo = new ServerConnectionInfo(); + status = new JobCancelStatus(); + status.setCancel(false); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + MockPresentationBLPreferenceImpl.setFileEncoding("UTF-8"); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + // serverInfo.setSslPassword("12345"); + // serverInfo.setServerType(DATABASETYPE.GAUSS); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception + { + super.tearDown(); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().close(); + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) + { + connProfCache.removeServer(itr.next().getId()); + itr = connProfCache.getServers().iterator(); + } + + connProfCache.closeAllNodes(); + + } + + @Test + public void test_server_serverversion_1() + { + + MockResultSet getServerVersionResult = preparedstatementHandler + .createResultSet(); + getServerVersionResult.addColumn("VERSION"); + + getServerVersionResult.addRow(new Object[] { + version1}); + preparedstatementHandler.prepareResultSet("SELECT * from version();", + getServerVersionResult); + try + { + profileId = connProfCache.initConnectionProfile(serverInfo, status); + } + catch (OutOfMemoryError | MPPDBIDEException | PasswordExpiryException e) + { + + e.printStackTrace(); + } + Database database = connProfCache.getDbForProfileId(profileId); + Server server = database.getServer(); + server.setServerVersion(version1); + String serverVersion = server.getServerVersion(true); + ((ServerConnectionInfo) server.getServerConnectionInfo()).setDBVersion(serverVersion); + assertEquals("openGauss 1.0 build e2c0f862", serverVersion); + parsedVersion = testParseVersionforConnectionDialog( + ((ServerConnectionInfo) server.getServerConnectionInfo()).getDBVersion()); + assertEquals("openGauss 1.0", parsedVersion); + parsedVersiontooltip = + testParseVersionfortoolTip(((ServerConnectionInfo) server.getServerConnectionInfo()).getDBVersion()); + assertEquals("openGauss 1.0", parsedVersiontooltip); + } + + // method to test the connection dialog database version parsing + public String testParseVersionforConnectionDialog(String dbVersion) { + Matcher matchOpenGauss = Pattern.compile("(?i)(openGauss)\\s+([^\\s]+)").matcher(dbVersion); + + if (matchOpenGauss.find()) { + return matchOpenGauss.group(); + } + + return dbVersion; + } + + // method to test the object browser connection tooltip database version + public String testParseVersionfortoolTip(String version) + { + + Matcher matchOpenGauss = Pattern.compile("(?i)(openGauss)\\s+([^\\s]+)").matcher(version); + + if (matchOpenGauss.find()) + { + return matchOpenGauss.group(); + } + + return version; + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/TerminalExecutionSQLConnectionInfraTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/TerminalExecutionSQLConnectionInfraTest.java new file mode 100644 index 0000000000000000000000000000000000000000..65e02199b38862b045809387f5fa87ce6b2c37a8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/TerminalExecutionSQLConnectionInfraTest.java @@ -0,0 +1,405 @@ +package org.opengauss.mppdbide.test.presentation.table; + +import java.util.Iterator; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.contentassist.ContentAssistProcesserData; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.presentation.IUIWorkerJobNotifier; +import org.opengauss.mppdbide.presentation.TerminalExecutionSQLConnectionInfra; +import org.opengauss.mppdbide.presentation.contentassistprocesser.ContentAssistProcesserCore; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; +import static org.junit.Assert.*; + +public class TerminalExecutionSQLConnectionInfraTest extends BasicJDBCTestCaseAdapter +{ + + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + Database database; + TerminalExecutionSQLConnectionInfra connInfra = null; + private boolean notifyCancel; + private boolean notifiedFlag; + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#setUp() + */ + @Before + public void setUp() throws Exception + { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + connection = new MockConnection(); + // test for logging + MPPDBIDELoggerUtility + .setArgs(new String[] {"-logfolder=.", "-detailLogging=true"}); + + // MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + + connProfCache = DBConnProfCache.getInstance(); + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setServerPort(5432); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + // serverInfo.setSslPassword("12345"); + // serverInfo.setServerType(DATABASETYPE.GAUSS); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + profileId = connProfCache.initConnectionProfile(serverInfo, status); + database = connProfCache.getDbForProfileId(profileId); + connInfra = new TerminalExecutionSQLConnectionInfra(); + connInfra.setDatabase(database); + notifyCancel = false; + notifiedFlag = false; + + } + + @After + public void tearDown() throws Exception + { + super.tearDown(); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().close(); + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) + { + connProfCache.removeServer(itr.next().getId()); + } + + connProfCache.closeAllNodes(); + + } + + @Test + public void testTTA_getAndRelease_001() + { + try + { + connInfra.setConnection(database.getConnectionManager().getFreeConnection()); + } + catch (MPPDBIDEException e) + { + fail("fail"); + } + DBConnection conn1 = connInfra.getSecureConnection(null); + assertNotNull(conn1); + assertTrue(connInfra.isConnectionBusy()); + connInfra.releaseSecureConnection(conn1); + assertFalse(connInfra.isConnectionBusy()); + } + + @Test + public void testTTA_getAndRelease_002() + { + connInfra.setConnection(null); + assertFalse(notifyCancel); + DBConnection conn1 = connInfra.getSecureConnection(new IUIWorkerJobNotifier() + { + + @Override + public void setNotified(boolean notify) + { + + + } + + @Override + public void setCancelled(boolean cancel) + { + notifyCancel = true; + } + + @Override + public int compareTo(Object o) { + return 0; + } + }); + assertTrue(notifyCancel); + assertNull(conn1); + } + + @Test + public void testTTA_getAndRelease_003() + { + connInfra.setReuseConnectionFlag(false); + DBConnection conn1 = connInfra.getSecureConnection(null); + assertNotNull(conn1); + assertFalse(connInfra.isConnectionBusy()); + connInfra.releaseSecureConnection(conn1); + assertFalse(connInfra.isConnectionBusy()); + } + + @Test + public void testTTA_getAndRelease_004() + { + try + { + connInfra.setConnection(database.getConnectionManager().getFreeConnection()); + } + catch (MPPDBIDEException e) + { + fail("fail"); + } + connInfra.setReuseConnectionFlag(true); + DBConnection conn1 = connInfra.getSecureConnection(new IUIWorkerJobNotifier() + { + + @Override + public void setNotified(boolean notify) + { + + + } + + @Override + public void setCancelled(boolean cancel) + { + + } + + @Override + public int compareTo(Object o) { + return 0; + } + }); + + DBConnection conn2 = connInfra.getSecureConnection(new IUIWorkerJobNotifier() + { + + @Override + public void setNotified(boolean notify) + { + notifiedFlag = true; + + } + + @Override + public void setCancelled(boolean cancel) + { + + } + + @Override + public int compareTo(Object o) { + return 0; + } + }); + assertNotNull(conn1); + assertNull(conn2); + assertTrue(connInfra.isConnectionBusy()); + assertFalse(notifiedFlag); + connInfra.releaseSecureConnection(conn1); + assertTrue(notifiedFlag); + } + + @Test + public void testTTA_notifyWaitingJobs_tests() + { + try + { + connInfra.setConnection(database.getConnectionManager().getFreeConnection()); + } + catch (MPPDBIDEException e) + { + fail("fail"); + } + connInfra.setReuseConnectionFlag(true); + notifiedFlag = false; + DBConnection conn1 = connInfra.getSecureConnection(new IUIWorkerJobNotifier() + { + + @Override + public void setNotified(boolean notify) + { + + + } + + @Override + public void setCancelled(boolean cancel) + { + + } + + @Override + public int compareTo(Object o) { + return 0; + } + }); + + DBConnection conn2 = connInfra.getSecureConnection(new IUIWorkerJobNotifier() + { + + @Override + public void setNotified(boolean notify) + { + notifiedFlag = true; + + } + + @Override + public void setCancelled(boolean cancel) + { + + } + + @Override + public int compareTo(Object o) { + return 0; + } + }); + assertNotNull(conn1); + assertNull(conn2); + connInfra.notifyAllWaitingJobs(); + assertTrue(notifiedFlag); + + } + + @Test + public void testTTA_cancelWaitingJobs_tests() + { + try + { + connInfra.setConnection(database.getConnectionManager().getFreeConnection()); + } + catch (MPPDBIDEException e) + { + fail("fail"); + } + connInfra.setReuseConnectionFlag(true); + notifyCancel = false; + + DBConnection conn1 = connInfra.getSecureConnection(new IUIWorkerJobNotifier() + { + + @Override + public void setNotified(boolean notify) + { + + + } + + @Override + public void setCancelled(boolean cancel) + { + + } + + @Override + public int compareTo(Object o) { + return 0; + } + }); + + DBConnection conn2 = connInfra.getSecureConnection(new IUIWorkerJobNotifier() + { + + @Override + public void setNotified(boolean notify) + { + + + } + + @Override + public void setCancelled(boolean cancel) + { + notifyCancel = true; + } + + @Override + public int compareTo(Object o) { + return 0; + } + }); + assertNotNull(conn1); + assertNull(conn2); + connInfra.cancelAllWaitingJobs(); + assertTrue(notifyCancel); + + } + + @Test + public void testTTA_database_sanity_test() + { + assertTrue(connInfra.isDatabaseValid()); + String name = null; + try + { + name = connInfra.getDatabaseName(); + } + catch (MPPDBIDEException e) + { + fail("fail"); + } + assertNotNull(name); + connInfra.setDatabase(null); + try + { + name = connInfra.getDatabaseName(); + } + catch (MPPDBIDEException e) + { + assertTrue(true); + } + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ViewSequenceDataTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ViewSequenceDataTest.java new file mode 100644 index 0000000000000000000000000000000000000000..39ead36234e67c0f8247bf1a5acc436289c7c691 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ViewSequenceDataTest.java @@ -0,0 +1,402 @@ +package org.opengauss.mppdbide.test.presentation.table; + +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.SequenceMetadata; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.util.ExecTimer; +import org.opengauss.mppdbide.bl.util.IExecTimer; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.presentation.IViewTableDataCore; +import org.opengauss.mppdbide.presentation.IWindowDetail; +import org.opengauss.mppdbide.presentation.ViewSequenceCore; +import org.opengauss.mppdbide.presentation.ViewTableData; +import org.opengauss.mppdbide.presentation.ViewTableDataCore; +import org.opengauss.mppdbide.presentation.ViewTableSequenceDataCore; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; +import com.mockrunner.mock.jdbc.MockDriver; +import com.mockrunner.mock.jdbc.MockPreparedStatement; +import com.mockrunner.mock.jdbc.MockResultSet; + +import static org.junit.Assert.*; + +public class ViewSequenceDataTest extends BasicJDBCTestCaseAdapter +{ + + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#setUp() + */ + @Before + public void setUp() throws Exception + { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + connection = new MockConnection(); + MPPDBIDELoggerUtility.setArgs(null); + MockDriver mockDriver = getJDBCMockObjectFactory().getMockDriver(); + mockDriver.setupConnection(connection); + CommonLLTUtils.mockConnection(mockDriver); + preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + CommonLLTUtils.addViewTableData(preparedstatementHandler); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + + connProfCache = DBConnProfCache.getInstance(); + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + MockPresentationBLPreferenceImpl.setFileEncoding("UTF-8"); + // serverInfo.setSslPassword("12345"); + // serverInfo.setServerType(DATABASETYPE.GAUSS); + + profileId = connProfCache.initConnectionProfile(serverInfo,status); + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception + { + super.tearDown(); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().close(); + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) + { + connProfCache.removeServer(itr.next().getId()); + itr = connProfCache.getServers().iterator(); + } + + connProfCache.closeAllNodes(); + + } + + @Test + public void test_initializeCore() + { + Database database = connProfCache.getDbForProfileId(profileId); + CommonLLTUtils.addViewTableData(preparedstatementHandler); + + try + { + SequenceMetadata seqData = new SequenceMetadata(1, "seq001", + database.getNameSpaceById(1)); + IViewTableDataCore core = new ViewSequenceCore(); + core.init(seqData); + + } + catch (DatabaseOperationException e) + { + + fail("not expected"); + } + } + + + + + + + public void test_getWindowDetails() + { + Database database = connProfCache.getDbForProfileId(profileId); + SequenceMetadata seqData; + try + { + seqData = new SequenceMetadata(1, "seq001", + database.getNameSpaceById(1)); + IViewTableDataCore core = new ViewSequenceCore(); + core.init(seqData); + if (core.getWindowDetails() instanceof IWindowDetail) + { + assertTrue(true); + } + else + fail("not expected"); + + } + catch (DatabaseOperationException e) + { + fail("not expected to come here"); + } + } + + + public void test_getTitle() + { + Database database = connProfCache.getDbForProfileId(profileId); + SequenceMetadata seqData; + try + { + seqData = new SequenceMetadata(1, "seq001", + database.getNameSpaceById(1)); + IViewTableDataCore core = new ViewSequenceCore(); + core.init(seqData); + assertEquals(core.getWindowDetails().getTitle(), "pg_catalog.seq001-Gauss@TestConnectionName"); + + } + catch (DatabaseOperationException e) + { + fail("not expected to come here"); + } + + } + + public void test_getUniqueID() + { + + Database database = connProfCache.getDbForProfileId(profileId); + SequenceMetadata seqData; + try + { + seqData = new SequenceMetadata(1, "seq001", + database.getNameSpaceById(1)); + IViewTableDataCore core = new ViewSequenceCore(); + core.init(seqData); + assertEquals(core.getWindowDetails().getUniqueID(), + "VIEW_TABLE_DATA_pg_catalog.seq001-Gauss@TestConnectionName"); + + } + catch (DatabaseOperationException e) + { + + e.printStackTrace(); + } + + } + + public void test_getShortTitle() + { + + Database database = connProfCache.getDbForProfileId(profileId); + SequenceMetadata seqData; + try + { + seqData = new SequenceMetadata(1, "seq001", + database.getNameSpaceById(1)); + IViewTableDataCore core = new ViewSequenceCore(); + core.init(seqData); + core.getWindowDetails().getShortTitle(); + core.getTermConnection(); + core.getServerObject(); + core.getWindowDetails().isCloseable(); + assertEquals("pg_catalog.seq001", + core.getWindowDetails().getShortTitle()); + + } + catch (DatabaseOperationException e) + { + fail("not expected to come here"); + } + + } + + + + public void test_cancelQuery() + { + Database database = connProfCache.getDbForProfileId(profileId); + SequenceMetadata seqData; + try + { + seqData = new SequenceMetadata(1, "seq001", + database.getNameSpaceById(1)); + IViewTableDataCore core = new ViewSequenceCore(); + core.init(seqData); + assertTrue(true); + } + catch (DatabaseOperationException e) + { + fail("not expected to come here"); + } + } + + @Test + public void test_getElapsedTime() + { + IExecTimer timer=new ExecTimer("test"); + timer.start(); + ViewTableData data= new ViewTableData(); + + try + { + timer.stop(); + data.setElapsedTime(timer.getElapsedTime()); + assertNotNull(data.getElapsedTime()); + } + catch (DatabaseOperationException e) + { + fail("not expeted"); + } + } + + @Test + public void test_queryRelated001() { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData; + try { + tablemetaData = new TableMetaData(1, "MyTable", database.getNameSpaceById(1), "tablespace"); + IViewTableDataCore core = new ViewTableSequenceDataCore(); + core.init(tablemetaData); + core.getWindowDetails().getShortTitle(); + core.getServerObject(); + core.getWindowDetails().isCloseable(); + assertNotNull(core.getQuery()); + } catch (DatabaseOperationException e) { + fail("not expeted"); + } + + } + + @Test + public void test_viewcore_01() { + Database database = connProfCache.getDbForProfileId(profileId); + CommonLLTUtils.addViewTableData(preparedstatementHandler); + try { + SequenceMetadata seqData = null; + seqData = new SequenceMetadata(1, "seq001", database.getNameSpaceById(1)); + ViewSequenceCore viewSeqCore = new ViewSequenceCore(); + viewSeqCore.init(seqData); + assertNotNull(viewSeqCore.getServerObject()); + assertNotNull(viewSeqCore.getProgressBarLabel()); + assertNotNull(viewSeqCore.getWindowDetails()); + assertNotNull(viewSeqCore.getQuery()); + assertNotNull(viewSeqCore.getWindowTitle()); + assertNotNull(viewSeqCore.getWindowDetails().getShortTitle()); + assertNotNull(viewSeqCore.getWindowDetails().getTitle()); + assertNotNull(viewSeqCore.getWindowDetails().getUniqueID()); + } catch (DatabaseOperationException e) { + e.printStackTrace(); + } + } + + @Test + public void test_viewcore_02() { + Database database = connProfCache.getDbForProfileId(profileId); + try { + SequenceMetadata seqData = null; + seqData = new SequenceMetadata(1, "seq001", database.getNameSpaceById(1)); + seqData.setTableName("MyTable"); + seqData.setSequenceName("seq001"); + seqData.setSchemaName("pubilc"); + seqData.setMinValue("1"); + seqData.setMaxValue("9223372036854775807"); + seqData.setIncrementBy("1"); + seqData.setColumnName("id"); + + MockResultSet sequenceset = preparedstatementHandler.createResultSet(); + sequenceset.addColumn("sequenceName"); + sequenceset.addColumn("sequenceuser"); + sequenceset.addColumn("minValue"); + sequenceset.addColumn("maxValue"); + sequenceset.addColumn("increment"); + sequenceset.addColumn("columnName"); + sequenceset.addColumn("tableuser"); + sequenceset.addColumn("tableName"); + sequenceset.addRow(new Object[] {"seq001", "public", 1, "9223372036854775807", 1, "id", "tpcc", "MyTable"}); + String tableBySequenceSql = " SELECT seq.sequence_name as sequenceName, seq.sequence_schema as sequenceuser," + + " seq.minimum_value as minValue,seq.maximum_value as maxValue , seq.increment as increment, tc.attname as columnName, tu.rolname as tableuser" + + " , tb.relname as tableName FROM information_schema.sequences seq, pg_namespace sch, pg_class scl, pg_depend sdp" + + " , pg_attrdef sc, pg_attribute tc, pg_class tb, pg_roles tu" + + " WHERE seq.sequence_schema = ? AND seq.sequence_name = ? AND sch.nspname = seq.sequence_schema" + + " AND scl.relnamespace = sch.oid AND scl.relname = seq.sequence_name AND scl.relkind = 'S' AND sdp.refobjid = scl.oid " + + " AND sc.oid = sdp.objid AND tc.attrelid = sc.adrelid AND tc.attnum = sc.adnum AND tb.oid = tc.attrelid" + + " AND tu.oid = tb.relowner;"; + preparedstatementHandler.prepareResultSet(tableBySequenceSql, sequenceset); + + ViewSequenceCore viewSeqCore = new ViewSequenceCore(); + viewSeqCore.init(seqData); + assertNotNull(viewSeqCore.getServerObject()); + assertNotNull(viewSeqCore.getProgressBarLabel()); + assertNotNull(viewSeqCore.getWindowDetails()); + String result = viewSeqCore.getQuery(); + if (!result.contains("com.mockrunner.mock.jdbc.MockPreparedStatement")) { + assertEquals(result, tableBySequenceSql); + } else { + assertEquals(tableBySequenceSql, ViewSequenceCore.getTableBySequenceSql()); + } + String query = tableBySequenceSql; + try { + DBConnection conn = database.getConnectionManager().getFreeConnection(); + ResultSet rs = conn.execSelectAndReturnRs(query); + while (rs.next()) { + for (int i = 0 ; i < 8; i++) { + System.out.print(String.format(Locale.ENGLISH, "col%d: %10s ", i, rs.getString(i + 1))); + } + System.out.println(""); + } + } catch (Exception e) { + fail("some error occur"); + } + } catch (DatabaseOperationException e) { + e.printStackTrace(); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ViewTableDataTest.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ViewTableDataTest.java new file mode 100644 index 0000000000000000000000000000000000000000..1f4f0ace7c33df1d090f0bd41d5596ad08b686ce --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ViewTableDataTest.java @@ -0,0 +1,455 @@ +package org.opengauss.mppdbide.test.presentation.table; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.preferences.IBLPreference; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.UserNamespace; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ViewUtils; +import org.opengauss.mppdbide.bl.util.ExecTimer; +import org.opengauss.mppdbide.bl.util.IExecTimer; +import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; +import org.opengauss.mppdbide.presentation.IViewTableDataCore; +import org.opengauss.mppdbide.presentation.IWindowDetail; +import org.opengauss.mppdbide.presentation.ViewTableData; +import org.opengauss.mppdbide.presentation.ViewTableDataCore; +import org.opengauss.mppdbide.presentation.ViewTableSequenceDataCore; +import org.opengauss.mppdbide.presentation.autorefresh.AutoRefreshQueryFormation; +import org.opengauss.mppdbide.presentation.autorefresh.RefreshObjectDetails; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.files.DSFilesWrapper; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; +import com.mockrunner.jdbc.PreparedStatementResultSetHandler; +import com.mockrunner.jdbc.StatementResultSetHandler; +import com.mockrunner.mock.jdbc.MockConnection; +import com.mockrunner.mock.jdbc.MockResultSet; + +import static org.junit.Assert.*; + +public class ViewTableDataTest extends BasicJDBCTestCaseAdapter +{ + + MockConnection connection = null; + PreparedStatementResultSetHandler preparedstatementHandler = null; + StatementResultSetHandler statementHandler = null; + + PreparedStatementResultSetHandler epreparedstatementHandler = null; + StatementResultSetHandler estatementHandler = null; + DBConnProfCache connProfCache = null; + ConnectionProfileId profileId = null; + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#setUp() + */ + @Before + public void setUp() throws Exception + { + super.setUp(); + CommonLLTUtils.runLinuxFilePermissionInstance(); + connection = new MockConnection(); + MPPDBIDELoggerUtility.setArgs(null); + getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); + CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); + preparedstatementHandler = connection + .getPreparedStatementResultSetHandler(); + statementHandler = connection.getStatementResultSetHandler(); + + CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); + CommonLLTUtils.addViewTableData(preparedstatementHandler); + CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); + + connProfCache = DBConnProfCache.getInstance(); + JobCancelStatus status = new JobCancelStatus(); + status.setCancel(false); + + ServerConnectionInfo serverInfo = new ServerConnectionInfo(); + serverInfo.setConectionName("TestConnectionName"); + serverInfo.setServerIp(""); + serverInfo.setDriverName("FusionInsight LibrA"); + serverInfo.setServerPort(5432); + serverInfo.setDatabaseName("Gauss"); + serverInfo.setUsername("myusername"); + serverInfo.setPrd("mypassword".toCharArray()); + serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); + serverInfo.setPrivilegeBasedObAccess(true); + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); + ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); + IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); + BLPreferenceManager.getInstance().setBLPreference(sysPref); + MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); + MockPresentationBLPreferenceImpl.setFileEncoding("UTF-8"); + // serverInfo.setSslPassword("12345"); + // serverInfo.setServerType(DATABASETYPE.GAUSS); + + profileId = connProfCache.initConnectionProfile(serverInfo,status); + } + + /* + * (non-Javadoc) + * + * @see com.mockrunner.jdbc.BasicJDBCTestCaseAdapter#tearDown() + */ + @After + public void tearDown() throws Exception + { + super.tearDown(); + + Database database = connProfCache.getDbForProfileId(profileId); + database.getServer().close(); + + preparedstatementHandler.clearPreparedStatements(); + preparedstatementHandler.clearResultSets(); + statementHandler.clearStatements(); + connProfCache.closeAllNodes(); + + Iterator itr = connProfCache.getServers().iterator(); + + while (itr.hasNext()) + { + connProfCache.removeServer(itr.next().getId()); + itr = connProfCache.getServers().iterator(); + } + + connProfCache.closeAllNodes(); + + } + + @Test + public void test_initializeCore() + { + Database database = connProfCache.getDbForProfileId(profileId); + CommonLLTUtils.addViewTableData(preparedstatementHandler); + + try + { + + TableMetaData tablemetaData = new TableMetaData(1, "MyTable", + database.getNameSpaceById(1), "tablespace"); + IViewTableDataCore core = new ViewTableDataCore(); + core.init(tablemetaData); + + } + catch (DatabaseOperationException e) + { + + fail("not expected"); + } + } + + + public void test_getWindowDetails() + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData; + try + { + tablemetaData = new TableMetaData(1, "MyTable", + database.getNameSpaceById(1), "tablespace"); + IViewTableDataCore core = new ViewTableDataCore(); + core.init(tablemetaData); + if (core.getWindowDetails() instanceof IWindowDetail) + { + assertTrue(true); + } + else + fail("not expected"); + + } + catch (DatabaseOperationException e) + { + fail("not expected to come here"); + } + } + + + public void test_getTitle() + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData; + try + { + tablemetaData = new TableMetaData(1, "MyTable", database.getNameSpaceById(1), "tablespace"); + IViewTableDataCore core = new ViewTableDataCore(); + core.init(tablemetaData); + assertEquals(core.getWindowDetails().getTitle(), "pg_catalog.MyTable-Gauss@TestConnectionName"); + + } + catch (DatabaseOperationException e) + { + fail("not expected to come here"); + } + + } + + public void test_getUniqueID() + { + + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData; + + try + { + tablemetaData = new TableMetaData(1, "MyTable", + database.getNameSpaceById(1), "tablespace"); + + IViewTableDataCore core = new ViewTableDataCore(); + core.init(tablemetaData); + assertEquals(core.getWindowDetails().getUniqueID(), + "VIEW_TABLE_DATA_pg_catalog.MyTable-Gauss@TestConnectionName"); + + } + catch (DatabaseOperationException e) + { + + e.printStackTrace(); + } + + } + + public void test_getShortTitle() + { + + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData; + try + { + tablemetaData = new TableMetaData(1, "MyTable", + database.getNameSpaceById(1), "tablespace"); + IViewTableDataCore core = new ViewTableDataCore(); + core.init(tablemetaData); + core.getWindowDetails().getShortTitle(); + core.getTermConnection(); + core.getServerObject(); + core.getWindowDetails().isCloseable(); + assertEquals("select * from pg_catalog.\"MyTable\"", + core.getQuery()); + assertEquals("pg_catalog.\"MyTable\"", + core.getWindowDetails().getShortTitle()); + + } + catch (DatabaseOperationException e) + { + fail("not expected to come here"); + } + + } + + + + public void test_cancelQuery() + { + Database database = connProfCache.getDbForProfileId(profileId); + TableMetaData tablemetaData; + try + { + tablemetaData = new TableMetaData(1, "MyTable", + database.getNameSpaceById(1), "tablespace"); + IViewTableDataCore core = new ViewTableSequenceDataCore(); + core.init(tablemetaData); + String proglabel = core.getProgressBarLabel(); + assertEquals(proglabel, core.getProgressBarLabel()); + String windTitle = core.getWindowTitle(); + assertEquals(windTitle, core.getWindowTitle()); + String getrelQuery = core.getQuery(); + assertEquals(getrelQuery, core.getQuery()); + boolean isTabdropped = core.isTableDropped(); + assertEquals(isTabdropped, core.isTableDropped()); + assertTrue(true); + } + catch (DatabaseOperationException e) + { + fail("not expected to come here"); + } + } + + @Test + public void test_setColumnNames() + { + try + { + String columnNames[] = {"ename", "eid", "age"}; + ViewTableData data = new ViewTableData(); + data.setColumnNames(columnNames); + assertEquals(3, data.getColumnNames().length); + } + catch (Exception e) + { + fail("not expected "); + + } + } + + @Test + public void test_setColumnValues() + { + try + { + + List columnValues = new ArrayList<>(); + String columnValuesRow[] = {"abc", "001", "25"}; + String columnValuesRow1[] = {"def", "002", "42"}; + + columnValues.add(columnValuesRow); + columnValues.add(columnValuesRow1); + ViewTableData data = new ViewTableData(); + data.setColumnValues(columnValues); + + assertEquals(2, data.getColumnValues().size()); + + } + catch (Exception e) + { + fail("not expected "); + + } + + } + + @Test + public void test_getElapsedTime() + { + IExecTimer timer=new ExecTimer("test"); + timer.start(); + ViewTableData data= new ViewTableData(); + + try + { + timer.stop(); + data.setElapsedTime(timer.getElapsedTime()); + assertNotNull(data.getElapsedTime()); + } + catch (DatabaseOperationException e) + { + fail("not expeted"); + } + } + + @Test + public void test_isEnabled() + { + ViewTableData data=new ViewTableData(); + data.setEndOfTableReached(true); + assertTrue(data.isEndOfTableReached()); + } + + @Test + public void test_viewViewData_02() { + try { + Database database = connProfCache.getDbForProfileId(profileId); + Namespace ns = database.getNameSpaceById(1); + ViewMetaData vmd = new ViewMetaData(2, "anything", ns,ns.getDatabase()); + vmd.setNamespace(ns); + assertEquals("v", vmd.getRelKind()); + assertEquals("", vmd.getMaterViewString()); + assertEquals("OR REPLACE ", vmd.getOrReplaceString()); + vmd.setRelKind(null); + assertEquals("v", vmd.getRelKind()); + assertEquals("", vmd.getMaterViewString()); + assertEquals("OR REPLACE ", vmd.getOrReplaceString()); + vmd.setRelKind("m"); + assertEquals("m", vmd.getRelKind()); + assertEquals("MATERIALIZED ", vmd.getMaterViewString()); + assertEquals("", vmd.getOrReplaceString()); + } catch (Exception e) { + // TODO: handle exception + fail("not execept!"); + } + } + + @Test + public void test_viewViewData_03() { + try { + Database database = connProfCache.getDbForProfileId(profileId); + Namespace ns = database.getNameSpaceById(1); + ViewMetaData vmd = new ViewMetaData(2, "anything", ns,ns.getDatabase()); + vmd.setNamespace(ns); + assertEquals("v", vmd.getRelKind()); + assertEquals("DROP VIEW IF EXISTS pg_catalog.anything", vmd.getDropQuery(false)); + assertEquals("DROP VIEW pg_catalog.anything ", vmd.getDropQueryForOB(false)); + vmd.setRelKind(null); + assertEquals("v", vmd.getRelKind()); + assertEquals("DROP VIEW IF EXISTS pg_catalog.anything", vmd.getDropQuery(false)); + assertEquals("DROP VIEW pg_catalog.anything ", vmd.getDropQueryForOB(false)); + vmd.setRelKind("m"); + assertEquals("DROP MATERIALIZED VIEW IF EXISTS pg_catalog.anything", vmd.getDropQuery(false)); + assertEquals("DROP MATERIALIZED VIEW pg_catalog.anything ", vmd.getDropQueryForOB(false)); + } catch (Exception e) { + // TODO: handle exception + fail("not execept!"); + } + } + + @Test + public void test_viewViewData_04() { + try { + Database database = connProfCache.getDbForProfileId(profileId); + Namespace ns = database.getNameSpaceById(1); + ViewMetaData vmd = new ViewMetaData(2, "anything", ns,ns.getDatabase()); + vmd.setNamespace(ns); + String query = ViewUtils.getViewQuery(vmd.getOid(), false); + String compareQuery = "SELECT c.oid, n.oid as nspoid, n.nspname AS schemaname, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner FROM (pg_class c LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace))) WHERE (c.relkind = 'v'::\"char\" or c.relkind = 'm'::\"char\") and c.oid=2;"; + assertEquals(compareQuery, query); + } catch (Exception e) { + // TODO: handle exception + fail("not execept!"); + } + } + + @Test + public void test_viewViewData_05() { + try { + Database database = connProfCache.getDbForProfileId(profileId); + Namespace ns = database.getNameSpaceById(1); + ViewMetaData vmd = new ViewMetaData(2, "anything", ns,ns.getDatabase()); + vmd.setNamespace(ns); + String query = ViewUtils.getViewQueryByNamespaceId(ns.getOid(), false); + String compareQuery = "SELECT c.oid, c.relname AS viewname, pg_get_userbyid(c.relowner) AS viewowner , c.relkind as relkind FROM pg_class c WHERE (c.relkind = 'v'::char or c.relkind = 'm'::char) and c.relnamespace = 1;"; + assertEquals(compareQuery, query); + } catch (Exception e) { + // TODO: handle exception + fail("not execept!"); + } + } + /* + * public void test_DatabaseCriticalException() { + * + * Database database = connProfCache.getDbForProfileId(profileId); + * TableMetaData tablemetaData; try { tablemetaData = new TableMetaData(1, + * "MyTable", database.getNameSpaceById(1), "tablespace"); ViewTableDataCore + * core = new ViewTableDataCore(tablemetaData); core.initializeCore(); + * ViewTableDataExecutor executor=new ViewTableDataExecutor(tablemetaData, + * -1); executor.getResultsetData(2, database.getFreeConnection()); // + * assertEquals((executor.getColumnNames(database.getFreeConnection())),5); + * } catch (DatabaseOperationException e) { + * System.out.println("inside of the dboprs"); + * fail("not expected to come here"); } catch (MPPDBIDEException e) { + * System.out.println("insde of the mpdb"); + * fail("not expected to come here"); + * + * } catch (Exception e) { e.printStackTrace(); } } + */ + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/AbstractEditTableDataCore.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/AbstractEditTableDataCore.java new file mode 100644 index 0000000000000000000000000000000000000000..a907e2e1b45ade423dae4516a1c041db69a5f841 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/AbstractEditTableDataCore.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +/** + * + * Title: class + * + * Description: The Class AbstractEditTableDataCore. + * + * @since 3.0.0 + */ +public abstract class AbstractEditTableDataCore implements IEditTableDataCore { + private static final String EDIT_TABLE_DATA = "EDIT_TABLE_DATA"; + + /** + * + * Title: class + * + * Description: The Class EditTableDataWindowDetails. + */ + protected class EditTableDataWindowDetails implements IWindowDetail { + + @Override + public String getTitle() { + + return getWindowTitle(); + } + + @Override + public String getShortTitle() { + + return getTable().getDisplayName(); + } + + @Override + public String getUniqueID() { + + return EDIT_TABLE_DATA + getTitle(); + } + + @Override + public String getIcon() { + + return null; + } + + @Override + public boolean isCloseable() { + return true; + } + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/AbstractViewTableDataCore.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/AbstractViewTableDataCore.java new file mode 100644 index 0000000000000000000000000000000000000000..985b9487e7c7736661c91859d2ac1924ef53f60a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/AbstractViewTableDataCore.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: class + * + * Description: The Class AbstractViewTableDataCore. + * + * @since 3.0.0 + */ +public abstract class AbstractViewTableDataCore implements IViewTableDataCore { + + private TerminalExecutionConnectionInfra termConnection = null; + + /** + * init. + * + * @param obj the obj + */ + @Override + public abstract void init(ServerObject obj); + + /** + * getServerObject. + * + * @return the server object + */ + @Override + public abstract ServerObject getServerObject(); + + /** + * getWindowDetails. + * + * @return the window details + */ + @Override + public abstract IWindowDetail getWindowDetails(); + + /** + * getWindowTitle. + * + * @return the window title + */ + @Override + public abstract String getWindowTitle(); + + /** + * get Progress Bar Label. + * + * @return the progress bar label + */ + @Override + public abstract String getProgressBarLabel(); + + /** + * getQuery + * + * @return getQuery + * @throws DatabaseOperationException + */ + @Override + public abstract String getQuery() throws DatabaseOperationException; + + /** + * Gets the term connection. + * + * @return the term connection + */ + public TerminalExecutionConnectionInfra getTermConnection() { + if (null == this.termConnection) { + this.termConnection = new TerminalExecutionConnectionInfra(); + this.termConnection.setDatabase(getServerObject().getDatabase()); + } + return this.termConnection; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/CanContextContinueExecuteRule.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/CanContextContinueExecuteRule.java new file mode 100644 index 0000000000000000000000000000000000000000..0a1f730babd5f586ffb014d8c1e74436c868e6a8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/CanContextContinueExecuteRule.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +/** + * + * Title: enum + * + * Description: The Enum CanContextContinueExecuteRule. + * + * @since 3.0.0 + */ +public enum CanContextContinueExecuteRule { + CONTEXT_EXECUTION_PROCEED, CONTEXT_EXECUTION_STOP, CONTEXT_EXECUTION_UNKNOWN +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/ContextExecutionOperationType.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/ContextExecutionOperationType.java new file mode 100644 index 0000000000000000000000000000000000000000..43bfcdd92a7bee4112948ae4f5b5ec76075a5207 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/ContextExecutionOperationType.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +/** + * + * Title: enum + * + * Description: The Enum ContextExecutionOperationType. + * + * @since 3.0.0 + */ +public enum ContextExecutionOperationType { + CONTEXT_OPERATION_TYPE_NEW_PL_SQL_CREATION, CONTEXT_OPERATION_TYPE_PL_SQL_COMPILATION, + CONTEXT_OPERATION_TYPE_SQL_TERMINAL_EXECUTION, CONTEXT_OPERATION_TYPE_VIEW_OBJECT_DATA, + CONTEXT_OPERATION_TYPE_VIEW_OBJECT_PROPERTY, +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/DummyTerminalExecutionConnectionInfra.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/DummyTerminalExecutionConnectionInfra.java new file mode 100644 index 0000000000000000000000000000000000000000..1fa77bf0f6cbccff23da81f20cce7c025f08493b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/DummyTerminalExecutionConnectionInfra.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +/** + * + * Title: class + * + * Description: The Class DummyTerminalExecutionConnectionInfra. + * + * @since 3.0.0 + */ +public class DummyTerminalExecutionConnectionInfra extends TerminalExecutionConnectionInfra { + @Override + public boolean isConnected() { + return true; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/EditTableDataCore.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/EditTableDataCore.java new file mode 100644 index 0000000000000000000000000000000000000000..073466f425d8fd893a25802b47a85ef714d31200 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/EditTableDataCore.java @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.messaging.ProgressBarLabelFormatter; + +/** + * + * Title: class + * + * Description: The Class EditTableDataCore. + * + * @since 3.0.0 + */ +public class EditTableDataCore extends AbstractEditTableDataCore { + + private TableMetaData serverObj; + private IWindowDetail details; + private TerminalExecutionConnectionInfra termConnection; + private static final String SELECT_QUERY = "select * from "; + + /** + * Gets the query. + * + * @return the query + */ + public String getQuery() { + return SELECT_QUERY + getTable().getDisplayName(); + } + + /** + * Gets the window details. + * + * @return the window details + */ + public IWindowDetail getWindowDetails() { + return details; + } + + /** + * Gets the window title. + * + * @return the window title + */ + public String getWindowTitle() { + TableMetaData table = (TableMetaData) getTable(); + return table.getNameSpaceName() + '.' + table.getName() + '-' + table.getDatabaseName() + '@' + + table.getServerName(); + } + + /** + * Gets the progress bar label. + * + * @return the progress bar label + */ + public String getProgressBarLabel() { + TableMetaData table = (TableMetaData) getTable(); + return ProgressBarLabelFormatter.getProgressLabelForTableWithMsg(table.getName(), + table.getNamespace().getName(), table.getDatabaseName(), table.getServerName(), + IMessagesConstants.EDIT_TABLE_PROGRESS_NAME); + } + + /** + * Gets the term connection. + * + * @return the term connection + */ + public TerminalExecutionConnectionInfra getTermConnection() { + if (null == this.termConnection) { + this.termConnection = new TerminalExecutionConnectionInfra(); + this.termConnection.setDatabase(getTable().getDatabase()); + } + return this.termConnection; + } + + /** + * Gets the table. + * + * @return the table + */ + public TableMetaData getTable() { + return serverObj; + } + + @Override + public void init(ServerObject serverObject) { + this.serverObj = (TableMetaData) serverObject; + details = new EditTableDataWindowDetails(); + + } + + @Override + public void refreshTable(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + getTable().getNamespace().refreshTable(getTable(), conn, false); + } + + @Override + public boolean isTableDropped() { + return serverObj.isTableDropped(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/ExecutionFailureActionOptions.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/ExecutionFailureActionOptions.java new file mode 100644 index 0000000000000000000000000000000000000000..40384c809ce86ec0b41e7d6a6fedd09b3a86b8ee --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/ExecutionFailureActionOptions.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +/** + * + * Title: enum + * + * Description: The Enum ExecutionFailureActionOptions. + * + * @since 17 May, 2019 + */ +public enum ExecutionFailureActionOptions { + EXECUTION_FAILURE_ACTION_CONTINUE, EXECUTION_FAILURE_ACTION_ABORT +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/IEditTableDataCore.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/IEditTableDataCore.java new file mode 100644 index 0000000000000000000000000000000000000000..600dc53178fe13d19fddfa3b61cc8002b3d84696 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/IEditTableDataCore.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: interface + * + * Description: The Interface IEditTableDataCore. + * + * @since 3.0.0 + */ +public interface IEditTableDataCore { + + /** + * Inits the. + * + * @param serverObj the server obj + */ + void init(ServerObject serverObj); + + /** + * Gets the query. + * + * @return the query + */ + String getQuery(); + + /** + * Gets the window details. + * + * @return the window details + */ + IWindowDetail getWindowDetails(); + + /** + * Gets the window title. + * + * @return the window title + */ + String getWindowTitle(); + + /** + * Gets the progress bar label. + * + * @return the progress bar label + */ + String getProgressBarLabel(); + + /** + * Gets the term connection. + * + * @return the term connection + */ + TerminalExecutionConnectionInfra getTermConnection(); + + /** + * Gets the table. + * + * @return the table + */ + ServerObject getTable(); + + /** + * Refresh table. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + void refreshTable(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException; + + /** + * Checks if is table dropped. + * + * @return true, if is table dropped + */ + boolean isTableDropped(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/IExecutionContext.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/IExecutionContext.java new file mode 100644 index 0000000000000000000000000000000000000000..a285e53062ff6fe080fbb377d300854d2e54afbe --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/IExecutionContext.java @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +import java.util.ArrayList; + +import org.opengauss.mppdbide.bl.serverdatacache.DefaultParameter; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.presentation.resultsetif.IResultConfig; +import org.opengauss.mppdbide.utils.messaging.MessageQueue; + +/** + * + * Title: interface + * + * Description: The Interface IExecutionContext. + * + * @since 3.0.0 + */ +public interface IExecutionContext { + + /** + * Can free connection after use. + * + * @return true, if successful + */ + boolean canFreeConnectionAfterUse(); + + /** + * Need query parse and split. + * + * @return true, if successful + */ + boolean needQueryParseAndSplit(); + + /** + * Gets the action on query failure. + * + * @return the action on query failure + */ + ExecutionFailureActionOptions getActionOnQueryFailure(); + + /** + * Gets the context name. + * + * @return the context name + */ + String getContextName(); + + /** + * Sets the critical error thrown. + * + * @param b the new critical error thrown + */ + void setCriticalErrorThrown(boolean b); + + /** + * Gets the query. + * + * @return the query + */ + String getQuery(); + + /** + * Gets the working job context. + * + * @return the working job context + */ + Object getWorkingJobContext(); + + /** + * Sets the working job context. + * + * @param jobContext the new working job context + */ + void setWorkingJobContext(Object jobContext); + + /** + * Gets the notice message queue. + * + * @return the notice message queue + */ + MessageQueue getNoticeMessageQueue(); + + /** + * Gets the connection profile ID.Get the profile in which the query will be + * executed. + * + * @return the connection profile ID + */ + String getConnectionProfileID(); + + /** + * Gets the result config.User preferences of the result management from the + * preference store + * + * @return the result config + */ + IResultConfig getResultConfig(); + + /** + * Gets the result display UI manager.when the execution of the query is ok, + * UI worker will call this and hand over the results + * + * @return the result display UI manager + */ + IResultDisplayUIManager getResultDisplayUIManager(); + + /** + * Handle execution exception. + * + * @param e the e + */ + void handleExecutionException(Exception e); + + /** + * Handle successfull completion. + */ + void handleSuccessfullCompletion(); + + /** + * Sets the job done. + */ + void setJobDone(); + + /** + * Gets the term connection. + * + * @return the term connection + */ + TerminalExecutionConnectionInfra getTermConnection(); + + /** + * Job type. + * + * @return the string + */ + String jobType(); + + /** + * Gets the current execution. + * + * @return the current execution + */ + ContextExecutionOperationType getCurrentExecution(); + + /** + * Sets the current execution. + * + * @param contextOperationTypeNewPlSqlCreation the new current execution + */ + void setCurrentExecution(ContextExecutionOperationType contextOperationTypeNewPlSqlCreation); + + /** + * Gets the current server object. + * + * @return the current server object + */ + ServerObject getCurrentServerObject(); + + /** + * Hide exec progres bar. + */ + default void hideExecProgresBar() { + return; + }; + + /** + * Show exec progres bar. + */ + default void showExecProgresBar() { + return; + }; + + /** + * gets the input values + * + * @return the list of input values + */ + ArrayList getInputValues(); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/IExplainPlanExecutionContext.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/IExplainPlanExecutionContext.java new file mode 100644 index 0000000000000000000000000000000000000000..f11c8e0bcfadebb1c61a4b1c14e8e44cc6ef26f8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/IExplainPlanExecutionContext.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +import java.util.Observer; + +import org.opengauss.mppdbide.bl.sqlhistory.IQueryExecutionSummary; +import org.opengauss.mppdbide.presentation.resultsetif.IConsoleResult; + +/** + * + * Title: interface + * + * Description: The Interface IExplainPlanExecutionContext. + * + * @since 3.0.0 + */ +public interface IExplainPlanExecutionContext extends IExecutionContext { + + /** + * Handle result display. + * + * @param result the result + * @param consoleData the console data + * @param queryExecSummary the query exec summary + * @param totalRuntime the total runtime + */ + void handleResultDisplay(Object result, IConsoleResult consoleData, IQueryExecutionSummary queryExecSummary, + double totalRuntime); + + /** + * Checks if is analyze. + * + * @return true, if is analyze + */ + boolean isAnalyze(); + + /** + * Gets the observer. + * + * @return the observer + */ + Observer getObserver(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/IResultDisplayUIManager.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/IResultDisplayUIManager.java new file mode 100644 index 0000000000000000000000000000000000000000..fd395aad789a89fcd7bea7896df64c83d93c22c6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/IResultDisplayUIManager.java @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +import java.util.ArrayList; + +import org.eclipse.e4.core.services.events.IEventBroker; + +import org.opengauss.mppdbide.bl.sqlhistory.IQueryExecutionSummary; +import org.opengauss.mppdbide.presentation.resultsetif.IConsoleResult; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; + +/** + * + * Title: interface + * + * Description: The Interface IResultDisplayUIManager. + * + * @since 3.0.0 + */ +public interface IResultDisplayUIManager { + + /** + * Handle pre execution UI display setup. + * + * @param terminalExecutionConnectionInfra the terminal execution connection + * infra + * @param isActivateStatusBar the is activate status bar + * @throws MPPDBIDEException the MPPDBIDE exception + */ + void handlePreExecutionUIDisplaySetup(TerminalExecutionConnectionInfra terminalExecutionConnectionInfra, + boolean isActivateStatusBar) throws MPPDBIDEException; + + /** + * Handle result display. + * + * @param result the result + * @param consoleData the console data + * @param queryExecSummary the query exec summary + */ + void handleResultDisplay(Object result, IConsoleResult consoleData, IQueryExecutionSummary queryExecSummary); + + /** + * Handle result display. + * + * @param result the result + */ + void handleResultDisplay(Object result); + + /** + * Handle console display. + * + * @param consoleData the console data + */ + void handleConsoleDisplay(IConsoleResult consoleData); + + /** + * Handle exception display. + * + * @param e the e + */ + void handleExceptionDisplay(Object e); + + /** + * Handle step completion. + */ + void handleStepCompletion(); + + /** + * Handle successfull completion. + */ + void handleSuccessfullCompletion(); + + /** + * Handle final cleanup. + */ + void handleFinalCleanup(); + + /** + * Gets the event broker. + * + * @return the event broker + */ + IEventBroker getEventBroker(); + + /** + * Gets the term connection. + * + * @return the term connection + */ + TerminalExecutionConnectionInfra getTermConnection(); + + /** + * Can context execution continue. + * + * @return the can context continue execute rule + */ + CanContextContinueExecuteRule canContextExecutionContinue(); + + /** + * Reset display UI manager. + */ + void resetDisplayUIManager(); + + /** + * Inits the display manager. + * + * @param execType the exec type + */ + void initDisplayManager(ContextExecutionOperationType execType); + + /** + * Handle cancel request. + */ + void handleCancelRequest(); + + /** + * Gets the single query array. + * + * @param queryArray the query array + * @param query the query + * @return the single query array + */ + void getSingleQueryArray(ArrayList queryArray, String query); + + /** + * Sets the cursor offset. + * + * @param offset the new cursor offset + */ + void setCursorOffset(int offset); + + /** + * Handle pre execution UI display setup critical. + * + * @param termConn the term conn + * @param isCriticalErr the is critical err + */ + void handlePreExecutionUIDisplaySetupCritical(TerminalExecutionConnectionInfra termConn, boolean isCriticalErr); + + /** + * Handle grid component on dialog cancel. + */ + void handleGridComponentOnDialogCancel(); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/IUIWorkerJobNotifier.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/IUIWorkerJobNotifier.java new file mode 100644 index 0000000000000000000000000000000000000000..800b8536c9570dddbdde78b85d9737be74a26451 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/IUIWorkerJobNotifier.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +/** + * + * Title: interface + * + * Description: The Interface IUIWorkerJobNotifier. + * + * @since 3.0.0 + */ +public interface IUIWorkerJobNotifier extends Comparable { + + /** + * This method will be called to notify a worker, which is waiting to obtain + * SQL terminal connection + * + * @param notify the new notified + */ + public void setNotified(boolean notify); + + /** + * This method will be called to cancel a worker, which is waiting to obtain + * SQL terminal connection + * + * @param cancel the new cancelled + */ + public void setCancelled(boolean cancel); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/IViewTableDataCore.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/IViewTableDataCore.java new file mode 100644 index 0000000000000000000000000000000000000000..f2c8e98e6644490569d6dafd884d37d0ffbfc7e3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/IViewTableDataCore.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: interface + * + * Description: The Interface IViewTableDataCore. + * + * @since 3.0.0 + */ +public interface IViewTableDataCore { + + /** + * Inits the. + * + * @param obj the obj + */ + void init(ServerObject obj); + + /** + * Gets the server object. + * + * @return the server object + */ + ServerObject getServerObject(); + + /** + * Gets the window details. + * + * @return the window details + */ + IWindowDetail getWindowDetails(); + + /** + * Gets the window title. + * + * @return the window title + */ + String getWindowTitle(); + + /** + * Gets the progress bar label. + * + * @return the progress bar label + */ + String getProgressBarLabel(); + + /** + * Gets the query. + * + * @return the query + * @throws DatabaseOperationException + */ + String getQuery() throws DatabaseOperationException; + + /** + * Gets the term connection. + * + * @return the term connection + */ + TerminalExecutionConnectionInfra getTermConnection(); + + /** + * Checks if is table dropped. + * + * @return true, if is table dropped + */ + default boolean isTableDropped() { + return true; + } + + /** + * Refresh table/view. + * + * @param conn the conn + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + default void refreshTable(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/IWindowDetail.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/IWindowDetail.java new file mode 100644 index 0000000000000000000000000000000000000000..6faf4d400656bbb00164d3467ec175643d7500fa --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/IWindowDetail.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +/** + * + * Title: interface + * + * Description: The Interface IWindowDetail. + * + * @since 3.0.0 + */ +public interface IWindowDetail { + + /** + * Gets the title. + * + * @return the title + */ + String getTitle(); + + /** + * Gets the short title. + * + * @return the short title + */ + String getShortTitle(); + + /** + * Gets the unique ID. + * + * @return the unique ID + */ + String getUniqueID(); + + /** + * Gets the icon. + * + * @return the icon + */ + default String getIcon() { + return null; + } + + /** + * Checks if is closeable. + * + * @return true, if is closeable + */ + default boolean isCloseable() { + return true; + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/OptimizerStatisticsCore.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/OptimizerStatisticsCore.java new file mode 100644 index 0000000000000000000000000000000000000000..b7f1c8dff97ccf9ad3efbad5264270fbaf82cf91 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/OptimizerStatisticsCore.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; + +/** + * + * Title: class + * + * Description: The Class OptimizerStatisticsCore. + * + * @since 3.0.0 + */ +public class OptimizerStatisticsCore { + private Database connectedDatabase; + private TerminalExecutionConnectionInfra termConnection; + private ViewOptimizerStatsWindowDetails window; + + /** + * Instantiates a new optimizer statistics core. + * + * @param db the db + */ + public OptimizerStatisticsCore(Database db) { + this.connectedDatabase = db; + } + + /** + * Gets the term connection. + * + * @return the term connection + */ + public TerminalExecutionConnectionInfra getTermConnection() { + if (null == this.termConnection) { + this.termConnection = new TerminalExecutionConnectionInfra(); + this.termConnection.setDatabase(connectedDatabase); + } + return this.termConnection; + } + + /** + * Gets the window details. + * + * @return the window details + */ + public IWindowDetail getWindowDetails() { + if (null == this.window) { + this.window = new ViewOptimizerStatsWindowDetails(); + } + return this.window; + } + + /** + * + * Title: class + * + * Description: The Class ViewOptimizerStatsWindowDetails. + */ + private static class ViewOptimizerStatsWindowDetails implements IWindowDetail { + + @Override + public String getTitle() { + return "Optimizer Stats"; + } + + @Override + public String getUniqueID() { + return "Optimizer_stats"; + } + + @Override + public String getIcon() { + return null; + } + + @Override + public String getShortTitle() { + return "Optimizer Stats"; + } + + @Override + public boolean isCloseable() { + return true; + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/PropertyOperationType.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/PropertyOperationType.java new file mode 100644 index 0000000000000000000000000000000000000000..ea4a6b89cc5bf3f59d60f873c875f146ec032c98 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/PropertyOperationType.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +/** + * + * Title: enum + * + * Description: The Enum PropertyOperationType. + * + * @since 3.0.0 + */ +public enum PropertyOperationType { + PROPERTY_OPERATION_VIEW, /* View properties of the object */ + PROPERTY_OPERATION_EDIT, /* Edit properties of the object */ + PROPERTY_OPERATION_CREATE /* create the object */ +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/SequenceDataCore.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/SequenceDataCore.java new file mode 100644 index 0000000000000000000000000000000000000000..8630ca3b96cba21a9c5ba4a6de4bd2bab60240ef --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/SequenceDataCore.java @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionManager; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.SequenceMetadata; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; + +/** + * + * Title: class + * + * Description: The Class SequenceDataCore. + * + * @since 3.0.0 + */ +public class SequenceDataCore { + + private Namespace namespace; + + private SequenceMetadata sequenceMetadata; + private DBConnection dbCon; + + /** + * Instantiates a new sequence data core. + * + * @param ns the ns + */ + public SequenceDataCore(Namespace ns) { + this.namespace = ns; + sequenceMetadata = new SequenceMetadata(ns); + dbCon = null; + + } + + /** + * Creates the connection. + * + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public void createConnection() throws MPPDBIDEException { + ConnectionManager connectionManager = sequenceMetadata.getConnectionManager(); + if (dbCon == null && connectionManager != null) { + dbCon = connectionManager.getFreeConnection(); + } + } + + /** + * Release connection. + */ + public void releaseConnection() { + if (dbCon != null) { + sequenceMetadata.getDatabase().getConnectionManager().releaseAndDisconnection(dbCon); + dbCon = null; + } + + } + + /** + * Gets the sequence metadata. + * + * @return the sequence metadata + */ + public SequenceMetadata getSequenceMetadata() { + return sequenceMetadata; + } + + /** + * Compose query. + * + * @return the string + */ + public String composeQuery() { + return sequenceMetadata.composeQuery(String.format(Locale.ENGLISH, "%s.%s", + ServerObject.getQualifiedObjectName(sequenceMetadata.getNamespace().getName()), + ServerObject.getQualifiedObjectName(sequenceMetadata.getSequenceName()))); + } + + /** + * Execute create sequence. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public void executeCreateSequence() + throws DatabaseCriticalException, DatabaseOperationException, MPPDBIDEException { + String queryForSequence = composeQuery(); + dbCon.execNonSelect(queryForSequence); + if (!(this.namespace.getServer().isServerInProgress() + || this.namespace.getDatabase().isLoadingNamespaceInProgress())) { + this.namespace.refreshSequences(dbCon); + } + + } + + /** + * Cancel query. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void cancelQuery() throws DatabaseCriticalException, DatabaseOperationException { + dbCon.cancelQuery(); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/TerminalExecutionConnectionInfra.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/TerminalExecutionConnectionInfra.java new file mode 100644 index 0000000000000000000000000000000000000000..1e18c68a676a749d330ce93479339455e186af02 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/TerminalExecutionConnectionInfra.java @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: class + * + * Description: The Class TerminalExecutionConnectionInfra. + * + * @since 3.0.0 + */ +public class TerminalExecutionConnectionInfra { + + /** + * The connection. + */ + protected DBConnection connection; + + /** + * The database. + */ + protected Database database; + + /** + * The auto commit flag. + */ + protected boolean autoCommitFlag; + private boolean isReconnect; + + /** + * Instantiates a new terminal execution connection infra. + */ + public TerminalExecutionConnectionInfra() { + // By default DS supports Auto commit ON. + this.autoCommitFlag = true; + } + + /** + * Gets the connection. + * + * @return the connection + */ + public DBConnection getConnection() { + return connection; + } + + /** + * Sets the connection. + * + * @param connection the new connection + */ + public void setConnection(DBConnection connection) { + this.connection = connection; + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + return database; + } + + /** + * Sets the database. + * + * @param database the new database + */ + public void setDatabase(Database database) { + this.database = database; + } + + /** + * Gets the auto commit flag. + * + * @return the auto commit flag + */ + public boolean getAutoCommitFlag() { + return autoCommitFlag; + } + + /** + * Sets the auto commit flag. + * + * @param autoCommitFlag the new auto commit flag + */ + public void setAutoCommitFlag(boolean autoCommitFlag) { + this.autoCommitFlag = autoCommitFlag; + } + + /** + * Reset information. + */ + public void resetInformation() { + releaseConnection(); + + /* + * We will not set the database to null for reset. Setting to NULL will + * lead to force NULL checks (by static tools) and unexpected + * NullPointerException where it is not done. + */ + } + + /** + * Release connection. + */ + public void releaseConnection() { + if (null != this.getConnection()) { + try { + if (!this.getConnection().isClosed()) { + database.getConnectionManager().releaseAndDisconnection(this.getConnection()); + } else { + database.getConnectionManager().removeConnectionFromPool(this.getConnection()); + } + } catch (DatabaseOperationException e) { + // cant do anything. Just ignore and proceed! + this.setConnection(null); + } + this.setConnection(null); + } + } + + private boolean isClosed(DBConnection conn) { + try { + return this.getConnection().isClosed(); + } catch (DatabaseOperationException e) { + return false; + } + } + + /** + * Checks if is connected. + * + * @return true, if is connected + */ + public boolean isConnected() { + if (null != this.getConnection() && !isClosed(this.getConnection())) { + return true; + } + return false; + } + + /** + * Checks if is reconnect on terminal. + * + * @return true, if is reconnect on terminal + */ + public boolean isReconnectOnTerminal() { + return isReconnect; + } + + /** + * Sets the reconnect on terminal. + * + * @param reconnect the new reconnect on terminal + */ + public void setReconnectOnTerminal(boolean reconnect) { + this.isReconnect = reconnect; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/TerminalExecutionSQLConnectionInfra.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/TerminalExecutionSQLConnectionInfra.java new file mode 100644 index 0000000000000000000000000000000000000000..6fbb9859a0e88ddd0cd0a84c39ea1eec2e6bcfaf --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/TerminalExecutionSQLConnectionInfra.java @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +import java.util.PriorityQueue; +import java.util.concurrent.atomic.AtomicInteger; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class TerminalExecutionSQLConnectionInfra. + * + * @since 3.0.0 + */ +public class TerminalExecutionSQLConnectionInfra extends TerminalExecutionConnectionInfra { + private AtomicInteger waitingThreadCount; + private boolean isReuseConnection; + private PriorityQueue waitingJobQueue; + + /** + * Instantiates a new terminal execution SQL connection infra. + */ + public TerminalExecutionSQLConnectionInfra() { + // By default DS supports Auto commit ON. + super(); + this.isReuseConnection = true; + this.waitingJobQueue = new PriorityQueue(1); + this.waitingThreadCount = new AtomicInteger(0); + } + + /** + * Gets the secure connection. + * + * @param callerThread the caller thread + * @return the secure connection + */ + public DBConnection getSecureConnection(IUIWorkerJobNotifier callerThread) { + if (getReuseConnectionFlag()) { + if (null == getConnection()) { + callerThread.setCancelled(true); + return null; + } + + if (testAndSet()) { + return getConnection(); + } else { + if (!waitingJobQueue.contains(callerThread)) { + waitingJobQueue.add(callerThread); + } + return null; + } + } else { + try { + return this.database.getConnectionManager().getFreeConnection(); + } catch (MPPDBIDEException exception) { + MPPDBIDELoggerUtility.error( + "TerminalExecutionSQLConnectionInfra: getting free connection from Database failed.", + exception); + } + } + return null; + } + + private boolean testAndSet() { + return waitingThreadCount.compareAndSet(0, 1); + } + + /** + * Release secure connection. + * + * @param conn the conn + */ + public void releaseSecureConnection(DBConnection conn) { + if (null != getConnection() && getConnection().equals(conn)) { + waitingThreadCount.compareAndSet(1, 0); + if (!waitingJobQueue.isEmpty()) { + IUIWorkerJobNotifier topWorker = waitingJobQueue.remove(); + topWorker.setNotified(true); + } + } else { + if (null == getConnection()) { + waitingThreadCount.compareAndSet(1, 0); + this.cancelAllWaitingJobs(); + } + releaseGivenConnection(conn); + } + } + + /** + * Notify all waiting jobs. + */ + public void notifyAllWaitingJobs() { + while (!waitingJobQueue.isEmpty()) { + IUIWorkerJobNotifier topWorker = waitingJobQueue.remove(); + topWorker.setNotified(true); + } + } + + /** + * Cancel all waiting jobs. + */ + public void cancelAllWaitingJobs() { + while (!waitingJobQueue.isEmpty()) { + IUIWorkerJobNotifier topWorker = waitingJobQueue.remove(); + topWorker.setCancelled(true); + } + } + + /** + * Checks if is connection busy. + * + * @return true, if is connection busy + */ + public boolean isConnectionBusy() { + return waitingThreadCount.intValue() == 1; + } + + private void releaseGivenConnection(DBConnection conParam) { + DBConnection conn = conParam; + if (null != conn) { + try { + if (!conn.isClosed()) { + this.getDatabase().getConnectionManager().releaseAndDisconnection(conn); + } + } catch (DatabaseOperationException e) { + conn = null; + } + conn = null; + } + } + + /** + * Gets the reuse connection flag. + * + * @return the reuse connection flag + */ + public boolean getReuseConnectionFlag() { + return isReuseConnection; + } + + /** + * Sets the reuse connection flag. + * + * @param isReuseConn the new reuse connection flag + */ + public void setReuseConnectionFlag(boolean isReuseConn) { + this.isReuseConnection = isReuseConn; + } + + /** + * Checks if is database valid. + * + * @return true, if is database valid + */ + public boolean isDatabaseValid() { + return this.database != null; + } + + /** + * Gets the database name. + * + * @return the database name + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public String getDatabaseName() throws MPPDBIDEException { + if (this.database != null) { + return this.getDatabase().getName(); + } + throw new MPPDBIDEException("Database is not valid"); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/ViewSequenceCore.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/ViewSequenceCore.java new file mode 100644 index 0000000000000000000000000000000000000000..d0e9a39bc1a06bdbf281716fe8be3de1ab9a062d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/ViewSequenceCore.java @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +import java.sql.PreparedStatement; +import java.sql.SQLException; + +import org.opengauss.mppdbide.bl.serverdatacache.SequenceMetadata; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.ProgressBarLabelFormatter; + +/** + * Title: ViewSequenceCore + * + * @since 3.0.0 + */ +public class ViewSequenceCore extends AbstractViewTableDataCore { + private static final String VIEW_TABLE_DATA = "VIEW_TABLE_DATA_"; + private SequenceMetadata serverObject; + private ViewSequnceWindowDetails details; + + private static final String tableBySequenceSql = " SELECT seq.sequence_name as sequenceName, seq.sequence_schema as sequenceuser," + + " seq.minimum_value as minValue,seq.maximum_value as maxValue , seq.increment as increment, tc.attname as columnName, tu.rolname as tableuser" + + " , tb.relname as tableName FROM information_schema.sequences seq, pg_namespace sch, pg_class scl, pg_depend sdp" + + " , pg_attrdef sc, pg_attribute tc, pg_class tb, pg_roles tu" + + " WHERE seq.sequence_schema = ? AND seq.sequence_name = ? AND sch.nspname = seq.sequence_schema" + + " AND scl.relnamespace = sch.oid AND scl.relname = seq.sequence_name AND scl.relkind = 'S' AND sdp.refobjid = scl.oid " + + " AND sc.oid = sdp.objid AND tc.attrelid = sc.adrelid AND tc.attnum = sc.adnum AND tb.oid = tc.attrelid" + + " AND tu.oid = tb.relowner;"; + public static String getTableBySequenceSql() + { + return tableBySequenceSql; + } + + @Override + public ServerObject getServerObject() { + return serverObject; + } + + @Override + public IWindowDetail getWindowDetails() { + return details; + } + + @Override + public String getWindowTitle() { + SequenceMetadata seqData = null; + String windowTitle = null; + if (serverObject != null) { + seqData = (SequenceMetadata) serverObject; + windowTitle = seqData.getNamespace().getName() + '.' + seqData.getName() + '-' + + seqData.getDatabase().getDbName() + '@' + seqData.getDatabase().getServerName(); + ; + } + return windowTitle; + } + + @Override + public String getProgressBarLabel() { + SequenceMetadata seqData = null; + String progressLabelForTableWithMsg = null; + if (serverObject != null) { + seqData = (SequenceMetadata) serverObject; + progressLabelForTableWithMsg = ProgressBarLabelFormatter.getProgressLabelForTableWithMsg(seqData.getName(), + seqData.getNamespace().getName(), seqData.getDatabase().getDbName(), + seqData.getDatabase().getServerName(), IMessagesConstants.VIEW_TABLE_PROGRESS_NAME); + } + return progressLabelForTableWithMsg; + } + + @Override + public String getQuery() throws DatabaseOperationException { + SequenceMetadata seqData = null; + String result = null; + if (serverObject != null) { + + seqData = (SequenceMetadata) serverObject; + final String tableBySequenceSql = " SELECT seq.sequence_name as sequenceName, seq.sequence_schema as sequenceuser," + + " seq.minimum_value as minValue,seq.maximum_value as maxValue , seq.increment as increment, tc.attname as columnName, tu.rolname as tableuser" + + " , tb.relname as tableName FROM information_schema.sequences seq, pg_namespace sch, pg_class scl, pg_depend sdp" + + " , pg_attrdef sc, pg_attribute tc, pg_class tb, pg_roles tu" + + " WHERE seq.sequence_schema = ? AND seq.sequence_name = ? AND sch.nspname = seq.sequence_schema" + + " AND scl.relnamespace = sch.oid AND scl.relname = seq.sequence_name AND scl.relkind = 'S' AND sdp.refobjid = scl.oid " + + " AND sc.oid = sdp.objid AND tc.attrelid = sc.adrelid AND tc.attnum = sc.adnum AND tb.oid = tc.attrelid" + + " AND tu.oid = tb.relowner;"; + + try (PreparedStatement statement = seqData.getConnectionManager().getObjBrowserConn() + .getPrepareStmt(tableBySequenceSql)) { + statement.setString(1, seqData.getNamespace().getName()); + statement.setString(2, seqData.getName()); + result = statement.toString(); + } catch (DatabaseCriticalException | DatabaseOperationException | SQLException exception) { + MPPDBIDELoggerUtility.error("Preparing to query related table sql failed", exception); + throw new DatabaseOperationException(IMessagesConstants.PREPARED_QUERY_RELATED_TABLE_FAILED); + } + } + + return result; + } + + private class ViewSequnceWindowDetails implements IWindowDetail { + + @Override + public String getTitle() { + return getWindowTitle(); + } + + @Override + public String getUniqueID() { + return VIEW_TABLE_DATA + getTitle(); + } + + @Override + public String getShortTitle() { + SequenceMetadata seqData = null; + String sequenceName = null; + if (serverObject != null) { + seqData = (SequenceMetadata) serverObject; + sequenceName = seqData.getDisplayName(); + } + return sequenceName; + } + } + + /** + * the init + * + * @param obj the obj + */ + public void init(ServerObject obj) { + if (obj instanceof SequenceMetadata) { + this.serverObject = (SequenceMetadata) obj; + details = new ViewSequnceWindowDetails(); + } + + } + + /** + * Checks if is table dropped. + * + * @return true, if is table dropped + */ + @Override + public boolean isTableDropped() { + return this.serverObject.isTableDropped(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/ViewTableData.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/ViewTableData.java new file mode 100644 index 0000000000000000000000000000000000000000..a275b1c0f52a7f481e5f4d01221e83b0e9c32a39 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/ViewTableData.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +import java.util.ArrayList; +import java.util.List; + +/** + * + * Title: class + * + * Description: The Class ViewTableData. + * + * @since 3.0.0 + */ +public class ViewTableData { + + private String[] columnNames; + private List columnValue; + private boolean isEndOfTableReached; + private String elapsedTime; + + /** + * Instantiates a new view table data. + */ + public ViewTableData() { + columnNames = new String[0]; + columnValue = new ArrayList(0); + isEndOfTableReached = true; + elapsedTime = "0 ms"; + } + + /** + * Gets the column names. + * + * @return the column names + */ + public String[] getColumnNames() { + return columnNames.clone(); + } + + /** + * Sets the column names. + * + * @param columnNames the new column names + */ + public void setColumnNames(String[] columnNames) { + this.columnNames = columnNames.clone(); + } + + /** + * Sets the column values. + * + * @param columnValues the new column values + */ + public void setColumnValues(List columnValues) { + this.columnValue = columnValues; + } + + /** + * Gets the column values. + * + * @return the column values + */ + public List getColumnValues() { + return columnValue; + } + + /** + * Checks if is end of table reached. + * + * @return true, if is end of table reached + */ + public boolean isEndOfTableReached() { + return isEndOfTableReached; + } + + /** + * Sets the end of table reached. + * + * @param isEndOfTableReachd the new end of table reached + */ + public void setEndOfTableReached(boolean isEndOfTableReachd) { + this.isEndOfTableReached = isEndOfTableReachd; + } + + /** + * Gets the elapsed time. + * + * @return the elapsed time + */ + public String getElapsedTime() { + return elapsedTime; + } + + /** + * Sets the elapsed time. + * + * @param elapsedTime the new elapsed time + */ + public void setElapsedTime(String elapsedTime) { + this.elapsedTime = elapsedTime; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/ViewTableDataCore.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/ViewTableDataCore.java new file mode 100644 index 0000000000000000000000000000000000000000..314a9148488092a5d3fc0f96070e1b93b0ab0bcd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/ViewTableDataCore.java @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.ProgressBarLabelFormatter; + +/** + * + * Title: class + * + * Description: The Class ViewTableDataCore. + * + * @since 3.0.0 + */ +public class ViewTableDataCore extends AbstractViewTableDataCore { + private static final String VIEW_TABLE_DATA = "VIEW_TABLE_DATA_"; + private static final String SELECT_ALL_QUERY = "select * from %s%s"; + /** + * server object + */ + protected TableMetaData serverObject; + private ViewTableWindowDetails details; + private String handlerParameter = null; + + /** + * Gets the handler parameter. + * + * @return the handler parameter + */ + public String getHandlerParameter() { + return handlerParameter; + } + + /** + * Sets the handler parameter. + * + * @param handlerParameter the new handler parameter + */ + public void setHandlerParameter(String handlerParameter) { + this.handlerParameter = handlerParameter; + } + + /** + * Gets the server object. + * + * @return the server object + */ + public TableMetaData getServerObject() { + return serverObject; + } + + /** + * Gets the window details. + * + * @return the window details + */ + public IWindowDetail getWindowDetails() { + return details; + } + + /** + * Gets the window title. + * + * @return the window title + */ + public String getWindowTitle() { + TableMetaData table = null; + String windowTitle = null; + if (serverObject != null) { + table = (TableMetaData) serverObject; + windowTitle = table.getNameSpaceName() + '.' + table.getName() + + ((!getHandlerParameter().isEmpty()) ? "." + getHandlerParameter() : "") + '-' + + table.getDatabaseName() + '@' + table.getServerName(); + } + return windowTitle; + + } + + /** + * Gets the progress bar label. + * + * @return the progress bar label + */ + public String getProgressBarLabel() { + String progressLabelForTableWithMsg = null; + + if (serverObject != null) { + TableMetaData table = (TableMetaData) serverObject; + + progressLabelForTableWithMsg = ProgressBarLabelFormatter.getProgressLabelForTableWithMsg(table.getName(), + table.getNamespace().getName(), table.getDatabaseName(), table.getServerName(), + IMessagesConstants.VIEW_TABLE_PROGRESS_NAME); + } + return progressLabelForTableWithMsg; + } + + /** + * + * Title: class + * + * Description: The Class ViewTableWindowDetails. + */ + private class ViewTableWindowDetails implements IWindowDetail { + + @Override + public String getTitle() { + return getWindowTitle(); + } + + @Override + public String getUniqueID() { + return VIEW_TABLE_DATA + getTitle(); + } + + @Override + public String getShortTitle() { + TableMetaData table = (TableMetaData) serverObject; + return table.getDisplayName(); + } + } + + /** + * Gets the query. + * + * @return the query + * @throws DatabaseOperationException + */ + public String getQuery() throws DatabaseOperationException { + return String.format(Locale.ENGLISH, SELECT_ALL_QUERY, + serverObject.getDisplayName(), + " " + handlerParameter).trim(); + } + + + /** + * the init + * + * @param obj the obj + */ + public void init(ServerObject obj) { + if (obj instanceof TableMetaData) { + this.serverObject = (TableMetaData) obj; + details = new ViewTableWindowDetails(); + } + } + + @Override + public boolean isTableDropped() { + return serverObject.isTableDropped(); + } + + @Override + public void refreshTable(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + serverObject.getNamespace().refreshTable(serverObject, conn, false); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/ViewTableSequenceDataCore.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/ViewTableSequenceDataCore.java new file mode 100644 index 0000000000000000000000000000000000000000..1e5a4db2c85c317c6942844fbeeacd7bda15efae --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/ViewTableSequenceDataCore.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation; + +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Locale; + +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: ViewTableSequenceDataCore + * + * @since 3.0.0 + */ +public class ViewTableSequenceDataCore extends ViewTableDataCore { + /** + * Gets the query. + * + * @return the query + * @throws DatabaseOperationException + */ + @Override + public String getQuery() throws DatabaseOperationException { + TableMetaData table = null; + String result = null; + + if (serverObject != null) { + table = (TableMetaData) serverObject; + final String sequenceByTableSql = "WITH temp_sql as (SELECT tu.rolname as tableuser" + + ",tb.relname as tableName,tc.attname as columnName,scl.relname,sch.nspname FROM " + + "pg_class scl,pg_depend sdp,pg_attrdef sc,pg_attribute tc,pg_class tb,pg_roles tu" + + ",pg_namespace sch WHERE sch.nspname = ? and tb.relname = ? AND scl.relnamespace = sch.oid " + + "AND scl.relkind = 'S' AND sdp.refobjid = scl.oid AND sc.oid = sdp.objid " + + "AND tc.attrelid = sc.adrelid " + + "AND tc.attnum = sc.adnum AND tb.oid = tc.attrelid AND tu.oid = tb.relowner)" + + "select t.tableuser,t.tableName,t.columnName,decode(seq.sequence_name,t.relname," + + "seq.sequence_name,'[No_Privilege]') as sequenceName" + + " ,decode(seq.sequence_name,t.relname,seq.sequence_schema,'[No_Privilege]') " + + "as sequenceuser " + + " ,decode(seq.sequence_name,t.relname,seq.minimum_value,'[No_Privilege]') as minValue " + + " ,decode(seq.sequence_name,t.relname,seq.maximum_value,'[No_Privilege]') as maxValue " + + " ,decode(seq.sequence_name,t.relname,seq.increment,'[No_Privilege]') as increment " + + "from temp_sql t LEFT OUTER join information_schema.sequences seq on " + + "(t.nspname = seq.sequence_schema " + "AND t.relname = seq.sequence_name )"; + try (PreparedStatement statement = table.getConnectionManager().getObjBrowserConn() + .getPrepareStmt(sequenceByTableSql)) { + statement.setString(1, table.getNamespace().getName()); + statement.setString(2, table.getName()); + result = statement.toString(); + } catch (DatabaseCriticalException | DatabaseOperationException | SQLException exception) { + MPPDBIDELoggerUtility.error("Preparing to query related sequence sql failed", exception); + throw new DatabaseOperationException(IMessagesConstants.PREPARED_QUERY_RELATED_SEQUENCE_FAILED); + } + } + return result; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/autorefresh/AutoRefreshQueryFormation.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/autorefresh/AutoRefreshQueryFormation.java new file mode 100644 index 0000000000000000000000000000000000000000..424bc45e4714b2f47490bf8755377c53192daf09 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/autorefresh/AutoRefreshQueryFormation.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.autorefresh; + +import java.util.HashSet; + +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * Title: AutoRefreshQueryFormation + * + * @since 3.0.0 + */ +public class AutoRefreshQueryFormation { + /** + * Gets the object to be refreshed. + * + * @param objectDetail the object detail + * @param listOfObjects the list of objects + * @return the object to be refreshed + */ + public static void getObjectToBeRefreshed(RefreshObjectDetails objectDetail, HashSet listOfObjects) { + String operationType = objectDetail.getOperationType(); + ServerObject serverObj = null; + switch (operationType) { + case MPPDBIDEConstants.CREATE_TABLE: { + serverObj = objectDetail.getNamespace().getNewlyCreatedTable(objectDetail.getObjectName()); + break; + } + case MPPDBIDEConstants.ALTER_TABLE: { + serverObj = objectDetail.getNamespace().getNewlyUpdatedTable(objectDetail.getObjectName()); + break; + } + case MPPDBIDEConstants.DROP_TABLE: { + serverObj = dropTable(objectDetail); + break; + } + case MPPDBIDEConstants.CREATE_VIEW: { + serverObj = objectDetail.getNamespace().getNewlyCreatedView(objectDetail.getObjectName()); + break; + } + case MPPDBIDEConstants.ALTER_VIEW: { + serverObj = objectDetail.getNamespace().getNewlyUpdatedView(objectDetail.getObjectName()); + break; + } + case MPPDBIDEConstants.DROP_VIEW: { + serverObj = dropView(objectDetail); + break; + } + case MPPDBIDEConstants.SET_SCHEMA_VIEW: { + serverObj = setSchemaForView(objectDetail, listOfObjects); + break; + } + case MPPDBIDEConstants.SET_SCHEMA_TABLE: { + serverObj = setSchemaForTable(objectDetail, listOfObjects); + break; + } + case MPPDBIDEConstants.CREATE_TRIGGER: { + serverObj = objectDetail.getNamespace().getNewlyCreateTrigger(objectDetail.getObjectName()); + break; + } + default: { + break; + } + } + objectDetail.setObjToBeRefreshed(serverObj); + listOfObjects.add(objectDetail); + } + + private static ServerObject setSchemaForTable(RefreshObjectDetails objectDetail, HashSet listOfObjects) { + ServerObject serverObj = null; + RefreshObjectDetails objectDetailCreateView = objectDetail.getClone(); + objectDetailCreateView.setOperationType(MPPDBIDEConstants.CREATE_TABLE); + if (objectDetailCreateView.getDesctNamespace() != null) { + serverObj = objectDetailCreateView.getDesctNamespace() + .getNewlyCreatedTable(objectDetailCreateView.getObjectName()); + } + objectDetailCreateView.setObjToBeRefreshed(serverObj); + objectDetailCreateView.setNamespace(objectDetailCreateView.getDesctNamespace()); + listOfObjects.add(objectDetailCreateView); + objectDetail.setOperationType(MPPDBIDEConstants.DROP_TABLE); + serverObj = dropTable(objectDetail); + return serverObj; + } + + private static ServerObject setSchemaForView(RefreshObjectDetails objectDetail, HashSet listOfObjects) { + ServerObject serverObj; + RefreshObjectDetails objectDetailCreate = objectDetail.getClone(); + objectDetailCreate.setOperationType(MPPDBIDEConstants.CREATE_VIEW); + serverObj = objectDetailCreate.getDesctNamespace().getNewlyCreatedView(objectDetailCreate.getObjectName()); + objectDetailCreate.setObjToBeRefreshed(serverObj); + objectDetailCreate.setNamespace(objectDetailCreate.getDesctNamespace()); + listOfObjects.add(objectDetailCreate); + objectDetail.setOperationType(MPPDBIDEConstants.DROP_VIEW); + serverObj = dropView(objectDetail); + return serverObj; + } + + private static ServerObject dropView(RefreshObjectDetails objectDetail) { + ServerObject serverObj = null; + if (objectDetail.getNamespace() instanceof Namespace) { + Namespace ns = (Namespace) objectDetail.getNamespace(); + serverObj = ns.getViewGroup().get(objectDetail.getObjectName()); + ns.getViewGroup().remove((ViewMetaData) serverObj); + } + return serverObj; + } + + private static ServerObject dropTable(RefreshObjectDetails objectDetail) { + ServerObject serverObj = null; + if (objectDetail.getNamespace() instanceof Namespace) { + Namespace ns = (Namespace) objectDetail.getNamespace(); + serverObj = ns.getTables().get(objectDetail.getObjectName()); + if (null != serverObj) { + ns.getTables().remove((TableMetaData) serverObj); + TableMetaData tableMetaData = (TableMetaData) serverObj; + objectDetail.getNamespace().getDatabase().getSearchPoolManager().getTableTrie() + .remove(tableMetaData.getSearchName()); + } + } + return serverObj; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/autorefresh/RefreshObjectDetails.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/autorefresh/RefreshObjectDetails.java new file mode 100644 index 0000000000000000000000000000000000000000..1ad782f89e0a269f70d2d9e2070b2f3ed21c0c63 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/autorefresh/RefreshObjectDetails.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.autorefresh; + +import org.opengauss.mppdbide.bl.serverdatacache.INamespace; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; + +/** + * Title: RefreshObjectDetails + * + * @since 3.0.0 + */ +public class RefreshObjectDetails { + private String operationType; + private Object parent; + private String objectName; + private INamespace namespace; + private ServerObject objToBeRefreshed; + private INamespace desctNamespace; + + public INamespace getDesctNamespace() { + return desctNamespace; + } + + public void setDesctNamespace(INamespace desctNamespace) { + this.desctNamespace = desctNamespace; + } + + public ServerObject getObjToBeRefreshed() { + return objToBeRefreshed; + } + + public void setObjToBeRefreshed(ServerObject objToBeRefreshed) { + this.objToBeRefreshed = objToBeRefreshed; + } + + public String getOperationType() { + return operationType; + } + + public void setOperationType(String operationType) { + this.operationType = operationType; + } + + public Object getParent() { + return parent; + } + + public INamespace getNamespace() { + return namespace; + } + + public void setNamespace(INamespace namespace) { + this.namespace = namespace; + } + + public void setParent(Object parent) { + this.parent = parent; + } + + public String getObjectName() { + return objectName; + } + + public void setObjectName(String objectName) { + this.objectName = objectName; + } + + /** + * Clone. + * + * @return the refresh object details + */ + public RefreshObjectDetails getClone() { + RefreshObjectDetails refreshObj = new RefreshObjectDetails(); + refreshObj.setOperationType(this.operationType); + refreshObj.setParent(this.parent); + refreshObj.setObjectName(this.objectName); + refreshObj.setNamespace(this.namespace); + refreshObj.setObjToBeRefreshed(this.objToBeRefreshed); + refreshObj.setDesctNamespace(this.desctNamespace); + return refreshObj; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/contentassistprocesser/ContentAssistProcesserCore.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/contentassistprocesser/ContentAssistProcesserCore.java new file mode 100644 index 0000000000000000000000000000000000000000..089a08a0c89f23e571df0a756f96518ff4849791 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/contentassistprocesser/ContentAssistProcesserCore.java @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.contentassistprocesser; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.SortedMap; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.contentassist.ContentAssistProcesserData; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.utils.CustomStringUtility; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; + +/** + * + * Title: class + * + * Description: The Class ContentAssistProcesserCore. + * + * @since 3.0.0 + */ +public class ContentAssistProcesserCore { + private LinkedHashMap autoMap = null; + private String[] currentPrefix = new String[0]; + private int replaceLength = 0; + private ContentAssistProcesserData contentData; + + /** + * Instantiates a new content assist processer core. + * + * @param database the database + */ + public ContentAssistProcesserCore(Database database) { + this.contentData = new ContentAssistProcesserData(database); + } + + /** + * Gets the context proposals. + * + * @param prefix the prefix + * @param fullPretext the full pretext + * @return the context proposals + */ + public LinkedHashMap getContextProposals(String prefix, String fullPretext) { + // Handle empty String + if (null == prefix) { + autoSuggectForNullPrefix(); + } else { + String[] prefixes = contentData.getSplitPrefixByDots(prefix); + String[] unQuotedPrefix = unquotePrefixes(prefixes); + boolean isEndsWithDot = CustomStringUtility.isEndsWithDot(prefix); + int prefixLen = prefix.length(); + + // Mark the object items for lazy loading of schema. + setCurrentPrefix(unQuotedPrefix); + if ((prefixLen != 0 && isEndsWithDot) || (prefixLen != 0 && contentData.isInsert() + && (fullPretext.endsWith("(") || fullPretext.endsWith(",")))) { + autoMap = contentData.findExactMatchingObjects(unQuotedPrefix); + } else { + autoMap = contentData.findPrefixMatchingObjects(unQuotedPrefix); + String lastWord = prefixes.length > 0 ? prefixes[prefixes.length - 1] : ""; + setReplaceLength(lastWord.length()); + } + } + + return autoMap; + } + + /** + * Find string. + * + * @param pretext the pretext + * @param workBreakCharList the work break char list + * @return the string + */ + public String findString(String pretext, List workBreakCharList) { + return contentData.getFindString(pretext, workBreakCharList); + } + + private String[] unquotePrefixes(String[] prefixes) { + String[] unquotedPrefixes = new String[prefixes.length]; + + for (int i = 0; i < prefixes.length; i++) { + unquotedPrefixes[i] = contentData.getRemovdLiteralEscapesAndQuotes(prefixes[i]); + } + + return unquotedPrefixes; + } + + /** + * Auto suggect for null prefix. + */ + public void autoSuggectForNullPrefix() { + autoMap = contentData.findPrefixMatchingObjects(new String[] {""}); + } + + /** + * Gets the current prefix. + * + * @return the current prefix + */ + public String[] getCurrentPrefix() { + return currentPrefix.clone(); + } + + /** + * Sets the current prefix. + * + * @param currentPrefix the new current prefix + */ + public void setCurrentPrefix(String[] currentPrefix) { + this.currentPrefix = currentPrefix.clone(); + } + + /** + * Gets the replace length. + * + * @return the replace length + */ + public int getReplaceLength() { + return replaceLength; + } + + /** + * Sets the replace length. + * + * @param replaceLength the new replace length + */ + public void setReplaceLength(int replaceLength) { + this.replaceLength = replaceLength; + } + + /** + * Checks if is any non loaded object. + * + * @return true, if is any non loaded object + */ + public boolean isAnyNonLoadedObject() { + return contentData.getNonLoaded().size() > 0; + + } + + /** + * Find non loaded database objects on demand. + * + * @param connection the connection + * @return the sorted map + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public LinkedHashMap findNonLoadedDatabaseObjectsOnDemand(DBConnection connection) + throws MPPDBIDEException { + return contentData.findNonLoadedObjects(connection, currentPrefix); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/CommitStatus.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/CommitStatus.java new file mode 100644 index 0000000000000000000000000000000000000000..a63aef28efd71e8ccdcf042762c4c684b792f778 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/CommitStatus.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.edittabledata; + +import java.util.List; + +/** + * + * Title: class + * + * Description: The Class CommitStatus. + * + * @since 3.0.0 + */ +public class CommitStatus { + + private List listOfSuccessRows; + private List listOfFailureRows; + private int updatedRecords; + private List listOfNonExecutedRows; + + /** + * Instantiates a new commit status. + * + * @param success the success + * @param failure the failure + * @param updatedRecords the updated records + * @param nonExecutedRowsList the non executed rows list + */ + public CommitStatus(List success, List failure, int updatedRecords, + List nonExecutedRowsList) { + listOfSuccessRows = success; + listOfFailureRows = failure; + listOfNonExecutedRows = nonExecutedRowsList; + this.updatedRecords = updatedRecords; + } + + /** + * Gets the list of failure rows. + * + * @return the list of failure rows + */ + public List getListOfFailureRows() { + return listOfFailureRows; + } + + /** + * Sets the list of failure rows. + * + * @param listOfFailureRows the new list of failure rows + */ + public void setListOfFailureRows(List listOfFailureRows) { + this.listOfFailureRows = listOfFailureRows; + } + + /** + * Gets the list of success rows. + * + * @return the list of success rows + */ + public List getListOfSuccessRows() { + return listOfSuccessRows; + } + + /** + * Sets the list of success rows. + * + * @param listOfSuccessRows the new list of success rows + */ + public void setListOfSuccessRows(List listOfSuccessRows) { + this.listOfSuccessRows = listOfSuccessRows; + } + + /** + * Gets the updated records. + * + * @return the updated records + */ + public int getUpdatedRecords() { + return updatedRecords; + } + + /** + * Sets the updated records. + * + * @param updatedRecords the new updated records + */ + public void setUpdatedRecords(int updatedRecords) { + this.updatedRecords = updatedRecords; + } + + /** + * Gets the list of not executed rows. + * + * @return the list of not executed rows + */ + public List getListOfNotExecutedRows() { + return listOfNonExecutedRows; + } + + /** + * Sets the list of not executed rows. + * + * @param listOfNotExecutedRows the new list of not executed rows + */ + public void setListOfNotExecutedRows(List listOfNotExecutedRows) { + this.listOfNonExecutedRows = listOfNotExecutedRows; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/CursorQueryExecutor.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/CursorQueryExecutor.java new file mode 100644 index 0000000000000000000000000000000000000000..5180e03f9a52e08d6c4c2a391ec60f5cdcfd3a1e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/CursorQueryExecutor.java @@ -0,0 +1,468 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.edittabledata; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.serverdatacache.DefaultParameter; +import org.opengauss.mppdbide.bl.serverdatacache.IQueryResult; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.sqlhistory.IQueryExecutionSummary; +import org.opengauss.mppdbide.bl.util.ExecTimer; +import org.opengauss.mppdbide.bl.util.IExecTimer; +import org.opengauss.mppdbide.presentation.IExecutionContext; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSResultRowVisitor; +import org.opengauss.mppdbide.presentation.grid.resultset.CursorQueryResult; +import org.opengauss.mppdbide.presentation.resultsetif.IResultConfig; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.ResultSetDatatypeMapping; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class CursorQueryExecutor. + * + * @since 3.0.0 + */ +public class CursorQueryExecutor { + private String query; + private int fetchSize; + private String cursorName = null; + private IDSResultRowVisitor visitor = null; + private Statement stmt; + private boolean needAutoCommitReset; + private boolean isEditTable; + private boolean isQueryResultEdit; + private IResultConfig resultConfig; + private IQueryExecutionSummary execSummary; + private IExecutionContext execContext; + private IDSGridDataProvider dataProvider = null; + private DBConnection connection; + + private static final int CURSOR_FETCH_BATCH_SIZE = 1000; + private static final String CURSOR_QUERY_PREPEND = "CURSOR %s NO SCROLL FOR %s"; + private static final String FETCH_QUERY = "FETCH FORWARD %d FROM %s"; + private static final String CLOSE_QUERY = "CLOSE %s"; + private static ArrayList inputDailogValueList; + + /** + * Instantiates a new cursor query executor. + * + * @param query the query + * @param execContext the exec context + * @param execSummary the exec summary + * @param editTableData the edit table data + * @param queryResultEditing the query result editing + * @param connection the connection + */ + public CursorQueryExecutor(String query, IExecutionContext execContext, IQueryExecutionSummary execSummary, + boolean editTableData, boolean queryResultEditing, DBConnection connection) { + this.query = query; + this.execContext = execContext; + this.execSummary = execSummary; + this.isEditTable = editTableData; + this.isQueryResultEdit = queryResultEditing; + this.resultConfig = this.execContext.getResultConfig(); + this.fetchSize = this.execContext.getResultConfig().getFetchCount(); + this.connection = connection; + } + + /** + * Execute. + * + * @param execSummary2 the exec summary 2 + * @return the IDS grid data provider + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public IDSGridDataProvider execute(IQueryExecutionSummary execSummary2) + throws DatabaseCriticalException, DatabaseOperationException { + if (getDBConnection().isClosed()) { + return null; + } + + return executeSelect(); + } + + /** + * Gets the DB connection. + * + * @return the DB connection + */ + private DBConnection getDBConnection() { + return connection; + } + + /** + * Gets the sql connection. + * + * @return the sql connection + */ + private Connection getSqlConnection() { + return getDBConnection().getConnection(); + } + + /** + * sets the input dailog value list + * + * @param getInputDailogValueList the getInputDailogValueList + */ + public static void setInputDailogValueList(ArrayList getInputDailogValueList) { + inputDailogValueList = getInputDailogValueList; + } + + /** + * gets the input dailog value list + * + * @return inputDailogValueList the inputDailogValueList + */ + public static ArrayList getInputDailogValueList() { + return inputDailogValueList; + } + + /** + * Execute select. + * + * @return the IDS grid data provider + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private IDSGridDataProvider executeSelect() throws DatabaseCriticalException, DatabaseOperationException { + getDistributionColumns(); + startTxn(); + try { + executeCursor(); + try { + fetchRecords(); + } finally { + closeCursor(); + } + } finally { + stopTxn(); + } + + return this.dataProvider; + } + + /** + * Gets the distribution columns. + * + * @return the distribution columns + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void getDistributionColumns() throws DatabaseCriticalException, DatabaseOperationException { + + if (isEditTable) { + ServerObject currentServerObject = execContext.getCurrentServerObject(); + if (currentServerObject != null && currentServerObject instanceof TableMetaData) { + ((TableMetaData) currentServerObject).fetchDistributionColumnList(getDBConnection()); + } + } + } + + /** + * Gets the visitor. + * + * @param sqlStmt the sql stmt + * @return the visitor + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + private IDSResultRowVisitor getVisitor(Statement sqlStmt, boolean isfuncProcResultFlow) + throws DatabaseOperationException, DatabaseCriticalException { + if (null == this.visitor) { + IQueryResult queryResult = new CursorQueryResult(sqlStmt, getDBConnection(), true); + if (this.isEditTable || this.isQueryResultEdit) { + DSEditTableDataGridDataProvider editTableDataProvider = null; + editTableDataProvider = new DSEditTableDataGridDataProvider(queryResult, this.resultConfig, + this.execSummary, this.execContext, this.isQueryResultEdit); + editTableDataProvider.setDatabase(execContext.getTermConnection().getDatabase()); + editTableDataProvider + .setIncludeEncoding(BLPreferenceManager.getInstance().getBLPreference().isIncludeEncoding()); + this.dataProvider = editTableDataProvider; + this.visitor = editTableDataProvider.initByVisitor(isfuncProcResultFlow); + } else { + DSResultSetGridDataProvider rsdp = new DSResultSetGridDataProvider(queryResult, this.resultConfig, + this.execSummary); + rsdp.setIncludeEncoding(BLPreferenceManager.getInstance().getBLPreference().isIncludeEncoding()); + this.visitor = rsdp.initByVisitor(isfuncProcResultFlow); + this.dataProvider = rsdp; + } + } + + return this.visitor; + } + + /** + * Stop txn. + */ + private void stopTxn() { + if (!needAutoCommitReset) { + return; + } + IExecTimer timer = new ExecTimer("Stop transaction"); + timer.start(); + + try { + Connection sqlConnection = getSqlConnection(); + // Set auto commit would issue a commit before changing the flag. + // Its a cautious call that "select fns()", might do an DML + // operation and need commit. + sqlConnection.setAutoCommit(true); + } catch (SQLException ex) { + // Ignore. Not mechanism to recover from this failure. + MPPDBIDELoggerUtility.error( + "Stop transaction after query execution failed. " + "No way to recover, and skiping this error", + ex); + } + timer.stopAndLogNoException(); + } + + /** + * Start txn. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void startTxn() throws DatabaseCriticalException, DatabaseOperationException { + try { + if (getSqlConnection().getAutoCommit()) { + // if already inside a transaction, no need to reset. + getSqlConnection().setAutoCommit(false); + this.needAutoCommitReset = true; + } + } catch (SQLException ex) { + GaussUtils.handleCriticalException(ex); + throw new DatabaseOperationException(IMessagesConstants.ERR_DATABASE_OPERATION_FAILURE, ex); + } + } + + /** + * Close cursor. + */ + private void closeCursor() { + IExecTimer timer = new ExecTimer("close cursor"); + timer.start(); + try { + this.stmt.execute(getCloseCursorQuery()); + } catch (SQLException ex) { + // Ignore. No way to recover from close failure. + MPPDBIDELoggerUtility.error("Error closing a cursor.", ex); + } finally { + getDBConnection().closeStatement(stmt); + timer.stopAndLogNoException(); + } + } + + /** + * Fetch records. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void fetchRecords() throws DatabaseCriticalException, DatabaseOperationException { + IExecTimer timer = new ExecTimer("fetch records"); + timer.start(); + int fetchedBatchSize = 0; + int currentFetchSize = 0; + int toFetchRowCount = 0; + + for (int index = 0; index < this.fetchSize || this.fetchSize < 1;) { + if (this.fetchSize == -1) { + // Fetch All case. + currentFetchSize = CURSOR_FETCH_BATCH_SIZE; + } else { + toFetchRowCount = this.fetchSize - index; + currentFetchSize = toFetchRowCount > CURSOR_FETCH_BATCH_SIZE ? CURSOR_FETCH_BATCH_SIZE + : toFetchRowCount; + } + fetchedBatchSize = fetchRecordBatch(currentFetchSize); + index += fetchedBatchSize; + + if (fetchedBatchSize < currentFetchSize) { + this.visitor.setEndOfRecords(); + timer.stopAndLogNoException(); + return; + } + } + timer.stopAndLogNoException(); + } + + /** + * Fetch record batch. + * + * @param currentFetchSize the current fetch size + * @return the int + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private int fetchRecordBatch(int currentFetchSize) throws DatabaseCriticalException, DatabaseOperationException { + ResultSet rs = null; + int recordFetchCounter = 0; + boolean isfuncProcResultFlow = false; + ArrayList inputDailogValueListLocal; + try { + rs = stmt.executeQuery(getFetchQuery(currentFetchSize)); + inputDailogValueListLocal = this.execContext.getInputValues(); + setInputDailogValueList(inputDailogValueListLocal); + IQueryResult queryResult = new CursorQueryResult(stmt, getDBConnection(), true); + + if (inputDailogValueListLocal != null && queryResult.getColumnCount() == 1) { + isfuncProcResultFlow = true; + } + IDSResultRowVisitor rowVisitor = getVisitor(stmt, isfuncProcResultFlow); + + if (isfuncProcResultFlow) { + int listSize = 0; + if (inputDailogValueListLocal != null) { + listSize = inputDailogValueListLocal.size(); + } + for (int i = 0; i < listSize; i++) { + rowVisitor.visitInputValues(inputDailogValueListLocal.get(i), i + 1); + } + + this.dataProvider.setFuncProcExport(true); + } + while (rs.next()) { + if (isfuncProcResultFlow) { + rowVisitor.visit(rs, isfuncProcResultFlow, false, null); + } else if (ResultSetDatatypeMapping.isReturnTypeCursor(rs)) { + rowVisitor.visitUnNameCursor(rs); + } else { + rowVisitor.visit(rs); + } + recordFetchCounter++; + if (recordFetchCounter == currentFetchSize) { + break; + } + } + return recordFetchCounter; + } catch (SQLException ex) { + GaussUtils.handleCriticalException(ex); + throw new DatabaseOperationException(IMessagesConstants.ERR_DATABASE_OPERATION_FAILURE, ex); + } finally { + closeResultSet(rs); + } + } + + /** + * Close result set. + * + * @param rs the rs + */ + private void closeResultSet(ResultSet rs) { + try { + if (null != rs) { + rs.close(); + } + } catch (SQLException ex) { + // Ignore. Nothing can be done to recover. + MPPDBIDELoggerUtility.debug("Resultset close failed while materializing the records"); + } + } + + /** + * Execute cursor. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private void executeCursor() throws DatabaseCriticalException, DatabaseOperationException { + IExecTimer timer = new ExecTimer("Start Cursor"); + DBConnection dbConnection = getDBConnection(); + timer.start(); + try { + this.stmt = getSqlConnection().createStatement(); + dbConnection.registerNoticeListner(this.stmt, this.execContext.getNoticeMessageQueue()); + stmt.execute(getCursorQuery()); + } catch (SQLException ex) { + GaussUtils.handleCriticalException(ex); + throw new DatabaseOperationException(IMessagesConstants.ERR_DATABASE_OPERATION_FAILURE, + dbConnection.extractErrorCodeAndErrorMsgFromServerError(ex), ex); + } finally { + timer.stopAndLogNoException(); + } + } + + /** + * Gets the cursor query. + * + * @return the cursor query + */ + private String getCursorQuery() { + return String.format(Locale.ENGLISH, CURSOR_QUERY_PREPEND, getUniqCursorName(), query); + } + + /** + * gets the statement + * + * @return the statement + */ + public Statement getStatement() { + return this.stmt; + } + + /** + * To be changed to a uniq name. __DS_QRY_CRSR___ Unique name + * generator + * + * @return the uniq cursor name + */ + public String getUniqCursorName() { + if (null == cursorName) { + String timeStamp = new SimpleDateFormat("HHmmssSSS").format(new Date()); + cursorName = "__DS_QRY_CRSR_" + timeStamp + "__"; + } + + return cursorName; + } + + /** + * Gets the fetch query. + * + * @param currentFetchSize the current fetch size + * @return the fetch query + */ + private String getFetchQuery(int currentFetchSize) { + return String.format(Locale.ENGLISH, FETCH_QUERY, currentFetchSize, getUniqCursorName()); + } + + /** + * Gets the close cursor query. + * + * @return the close cursor query + */ + private String getCloseCursorQuery() { + return String.format(Locale.ENGLISH, CLOSE_QUERY, getUniqCursorName()); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSCursorDataGridRow.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSCursorDataGridRow.java new file mode 100644 index 0000000000000000000000000000000000000000..d8404e0c5c83aa3de7c79a0447fc6ebefdf0b703 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSCursorDataGridRow.java @@ -0,0 +1,282 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.edittabledata; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.utils.observer.DSEventTable; +import org.opengauss.mppdbide.utils.observer.IDSGridUIListenable; + +/** + * + * Title: class + * + * Description: The Class DSCursorDataGridRow. + * + * @since 3.0.0 + */ +public class DSCursorDataGridRow extends DSResultSetGridDataRow implements IDSGridEditDataRow { + private Map modifiedData = null; + private EditTableRecordStates state; + private EditTableRecordExecutionStatus execState = EditTableRecordExecutionStatus.NOT_EXECUTED; + private String commitStatusMessage = ""; + private int rowIndex = 0; + private DSEventTable eventTable; + private int updatedRecords; + private DSCursorTableDataGridDataProvider dataProvider; + private Map cellStateMap; + + /** + * Instantiates a new DS edit table data grid row. + * + * @param isNewRow the is new row + * @param index the index + * @param eventTable the event table + * @param dataProvider the data provider + */ + public DSCursorDataGridRow(boolean isNewRow, int index, DSEventTable eventTable, + DSCursorTableDataGridDataProvider dataProvider) { + super(dataProvider); + this.eventTable = eventTable; + state = isNewRow ? EditTableRecordStates.INSERT : EditTableRecordStates.NOT_EDITED; + this.rowIndex = index; + updatedRecords = 0; + this.dataProvider = dataProvider; + } + + /** + * Instantiates a new DS cursor table data grid row. + * + * @param eventTable the event table + * @param dsCursorTableDataGridDataProvider the data provider + */ + public DSCursorDataGridRow(DSEventTable eventTable, + DSCursorTableDataGridDataProvider dsCursorTableDataGridDataProvider) { + super(dsCursorTableDataGridDataProvider); + this.eventTable = eventTable; + state = EditTableRecordStates.NOT_EDITED; + updatedRecords = 0; + this.dataProvider = dsCursorTableDataGridDataProvider; + } + + /** + * Gets the cell state map. + * + * @return the cell state map + */ + private Map getCellStateMap() { + if (this.cellStateMap == null) { + cellStateMap = new HashMap(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + } + return cellStateMap; + } + + /** + * Gets the modified data map. + * + * @return the modified data map + */ + private Map getModifiedDataMap() { + if (this.modifiedData == null) { + modifiedData = new HashMap(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + } + return modifiedData; + } + + @Override + public void setValue(int columnIndex, Object newValue) { + getModifiedDataMap().put(columnIndex, newValue); + + if (state == EditTableRecordStates.NOT_EDITED) { + state = EditTableRecordStates.UPDATE; + this.dataProvider.incrementUpdatedRowCount(); + } + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_EDITED, null)); + + } + + @Override + public void undo(int columnIndex) { + if (getModifiedDataMap().containsKey(columnIndex)) { + getModifiedDataMap().remove(columnIndex); + + // Enum comparison doesn't need equals check as suggested by + if (getModifiedDataMap().isEmpty() && state == EditTableRecordStates.UPDATE) { + this.dataProvider.decrementUpdatedRowCount(); + setState(EditTableRecordStates.NOT_EDITED); + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_EDITED, null)); + } + + } + } + + @Override + public EditTableRecordStates getUpdatedState() { + return this.state; + } + + @Override + public EditTableRecordStates getUpdatedState(int columnIndex) { + if (this.state == EditTableRecordStates.UPDATE && null != modifiedData + && !modifiedData.containsKey(columnIndex)) { + return EditTableRecordStates.NOT_EDITED; + } + + return this.state; + } + + @Override + public void createNewRow(Object[] value) { + values = value.clone(); + setState(EditTableRecordStates.INSERT); + } + + /** + * Sets the state. + * + * @param insertState the new state + */ + private void setState(EditTableRecordStates insertState) { + this.state = insertState; + + } + + @Override + public Object getValue(int columnIndex) { + if (null != modifiedData && modifiedData.containsKey(columnIndex)) { + if (isIncludeEncoding() && !isUnstructuredDatatype(columnIndex)) { + return getEncodedValue(modifiedData.get(columnIndex)); + } + return modifiedData.get(columnIndex); + } + return super.getValue(columnIndex); + } + + @Override + public Object[] getValues() { + Object[] values = super.getValues(); + for (Map.Entry modifiedEntry : getModifiedDataMap().entrySet()) { + if (isIncludeEncoding() && !isUnstructuredDatatype(modifiedEntry.getKey())) { + values[modifiedEntry.getKey()] = getEncodedValue(modifiedEntry.getValue()); + } else { + values[modifiedEntry.getKey()] = modifiedEntry.getValue(); + } + } + + return values; + } + + @Override + public void clearAllRowUpdates() { + getModifiedDataMap().clear(); + setState(EditTableRecordStates.NOT_EDITED); + setExecutionStatus(EditTableRecordExecutionStatus.NOT_EXECUTED); + commitStatusMessage = ""; + } + + @Override + public Object getOriginalValue(int columnIndex) { + + if (getUpdatedState() == EditTableRecordStates.INSERT) { + getValue(columnIndex); + } + + return super.getOriginalValue(columnIndex); + } + + @Override + public void setExecutionStatus(EditTableRecordExecutionStatus status) { + execState = status; + } + + @Override + public EditTableRecordExecutionStatus getExecutionStatus() { + return execState; + } + + @Override + public List getModifiedColumns() { + return new ArrayList(getModifiedDataMap().keySet()); + } + + @Override + public void setStateDelete() { + this.state = EditTableRecordStates.DELETE; + } + + @Override + public String getCommitStatusMessage() { + return commitStatusMessage; + } + + @Override + public void setCommitStatusMessage(String commitStatusMessage) { + this.commitStatusMessage = commitStatusMessage; + } + + @Override + public int getRowIndex() { + return rowIndex; + } + + @Override + public void setRowIndex(int rowIndex) { + this.rowIndex = rowIndex; + } + + @Override + public Object[] getClonedValues() { + // Cannot use Super.getClonedValues() as it would call this.getValues() + // So, the original value will be changed. + Object[] values = super.getValues().clone(); + + for (Map.Entry modifiedEntry : getModifiedDataMap().entrySet()) { + values[modifiedEntry.getKey()] = modifiedEntry.getValue(); + } + + return values; + } + + @Override + public int getUpdatedRecords() { + + return updatedRecords; + } + + @Override + public void setUpdatedRecords(int updatedRecords) { + this.updatedRecords = updatedRecords; + } + + @Override + public EditTableCellState getCellStatus(int colIndex) { + EditTableCellState editTableCellState = EditTableCellState.MODIFIED_FAILED; + if (getCellStateMap().containsKey(colIndex)) { + editTableCellState = getCellStateMap().get(colIndex); + } + return editTableCellState; + } + + @Override + public void setCellSatus(EditTableCellState cellState, int colIndex) { + getCellStateMap().put(colIndex, cellState); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSCursorTableDataGridDataProvider.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSCursorTableDataGridDataProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..b93ff2de7590fef6521f98bc5679a98eb2f39ce4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSCursorTableDataGridDataProvider.java @@ -0,0 +1,258 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.edittabledata; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.presentation.grid.IDSEditGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.presentation.grid.IDSResultRowVisitor; +import org.opengauss.mppdbide.presentation.grid.IRowEffectedConfirmation; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.observer.DSEvent; + +/** + * + * Title: class + * + * Description: The Class DSCursorTableDataGridDataProvider. + * + * @since 3.0.0 + */ +public class DSCursorTableDataGridDataProvider extends DSResultSetGridDataProvider implements IDSEditGridDataProvider { + + /** + * The column count.- + */ + protected int columnCount; + + /** + * The column names. + */ + protected List columnNames; + + /** + * The column data provider. + */ + private IDSGridColumnProvider columnDataProvider; + + /** + * The grid data row. + */ + private List rows; + + /** + * The inserted list. + */ + protected List insertedList; + + /** + * The isEndOfRecordsReached flag. + */ + private boolean isEndOfRecordsReached; + + public DSCursorTableDataGridDataProvider(Object[] valueList) { + super(null, null, null); + insertedList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + this.rows = new ArrayList(5); + this.columnCount = valueList.length; + this.columnNames = new ArrayList(this.columnCount); + for (int index = 0; index < this.columnCount; index++) { + this.columnNames.add((String) valueList[index]); + } + } + + /** + * Gets the consolidated rows. + * + * @return the consolidated rows + */ + public List getConsolidatedRows() { + + List allFetchedRows = getAllFetchedRows(); + IDSGridEditDataRow insertedRow; + List consolidatedRows = new ArrayList(); + consolidatedRows.addAll(allFetchedRows); + Iterator iterator = insertedList.iterator(); + while (iterator.hasNext()) { + insertedRow = (IDSGridEditDataRow) iterator.next(); + consolidatedRows.add(insertedRow.getRowIndex(), insertedRow); + } + + return consolidatedRows; + } + + /** + * Gets the all fetched rows. + * + * @return the all fetched rows + */ + @Override + public List getAllFetchedRows() { + return rows; + } + + @Override + protected IDSGridDataRow createRowFromValues(Object[] rowValues) { + DSCursorDataGridRow row = new DSCursorDataGridRow(eventTable, this); + row.setValues(rowValues); + row.setIncludeEncoding(isIncludeEncoding()); + + return row; + } + + /** + * Inits the. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + @Override + public void init() throws DatabaseOperationException, DatabaseCriticalException { + + super.init(); + } + + /** + * Checks if is edits the supported. + * + * @return true, if is edits the supported + */ + @Override + public boolean isEditSupported() { + return false; + } + + /** + * Inits the by visitor. + * + * @return the IDS result row visitor + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public IDSResultRowVisitor initByVisitor(Object[] colValueList) + throws DatabaseOperationException, DatabaseCriticalException { + DSResultSetGridColumnDataProvider colData = new DSResultSetGridColumnDataProvider(); + colData.initByVisitorPopUpHeaderName(colValueList); + this.columnDataProvider = colData; + + return this; + } + + @Override + public void visit(DSResultSetGridDataRow gridDataRow) + throws DatabaseOperationException, DatabaseCriticalException, SQLException { + if (null == this.columnDataProvider) { + DSResultSetGridColumnDataProvider colData = new DSResultSetGridColumnDataProvider(); + colData.init(queryResult); + this.columnDataProvider = colData; + } + + Object[] rowValues = gridDataRow.getValues(); + IDSGridDataRow row = createRowFromValues(rowValues); + this.rows.add(row); + } + + /** + * Gets the column data provider. + * + * @return the column data provider + */ + @Override + public IDSGridColumnProvider getColumnDataProvider() { + return this.columnDataProvider; + } + + /** + * Sets the end of records. + */ + @Override + public void setEndOfRecords() { + this.isEndOfRecordsReached = true; + } + + /** + * Checks if is end of records. + * + * @return true, if is end of records + */ + @Override + public boolean isEndOfRecords() { + return this.isEndOfRecordsReached; + } + + @Override + public CommitStatus commit(List uniqueKeys, boolean isAtomic, IRowEffectedConfirmation rowEffectedConfirm, + DBConnection termConnection) throws MPPDBIDEException { + return null; + } + + @Override + public void rollBackProvider() { + + } + + @Override + public void deleteRecord(IDSGridEditDataRow row, boolean isInserted) { + + } + + @Override + public boolean isGridDataEdited() { + return false; + } + + @Override + public int getUpdatedRowCount() { + return 0; + } + + @Override + public int getInsertedRowCount() { + return 0; + } + + @Override + public int getDeletedRowCount() { + return 0; + } + + @Override + public void cancelCommit() throws DatabaseCriticalException, DatabaseOperationException { + + } + + @Override + public IDSGridEditDataRow getEmptyRowForInsert(int index) { + return null; + } + + public void decrementUpdatedRowCount() { + + } + + public void incrementUpdatedRowCount() { + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSEditTableDataGridDataProvider.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSEditTableDataGridDataProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..9d99bc07108a53bb31a00b1c28ef9ac50572ab0f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSEditTableDataGridDataProvider.java @@ -0,0 +1,1250 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.edittabledata; + +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintType; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.IQueryResult; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.sqlhistory.IQueryExecutionSummary; +import org.opengauss.mppdbide.presentation.IExecutionContext; +import org.opengauss.mppdbide.presentation.grid.IDSEditGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.presentation.grid.IDSResultRowVisitor; +import org.opengauss.mppdbide.presentation.grid.IRowEffectedConfirmation; +import org.opengauss.mppdbide.presentation.resultsetif.IResultConfig; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.JSQLParserUtils; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.utils.observer.IDSGridUIListenable; + +/** + * + * Title: class + * + * Description: The Class DSEditTableDataGridDataProvider. + * + * @since 3.0.0 + */ +public class DSEditTableDataGridDataProvider extends DSResultSetGridDataProvider implements IDSEditGridDataProvider { + + /** + * The inserted list. + */ + protected List insertedList; + + /** + * The insert returning list. + */ + protected List insertReturningList; + + /** + * The delete list. + */ + protected List deleteList; + private TableMetaData table; + + /** + * The context. + */ + protected IExecutionContext context; + + /** + * The last commit status. + */ + protected CommitStatus lastCommitStatus; + + /** + * The conn. + */ + protected DBConnection conn; + private boolean cancelled; + + /** + * The column count. + */ + protected int columnCount; + + /** + * The column names. + */ + protected List columnNames; + + /** + * The data type names. + */ + protected List dataTypeNames; + + /** + * The table name. + */ + protected String tableName = null; + + /** + * The full table name. + */ + protected String[] fullTableName; + + /** + * The is query result edit. + */ + protected boolean isQueryResultEdit; + + /** + * The updated row count. + */ + protected int updatedRowCount; + + /** + * The savepoint name. + */ + protected String savepointName = ""; + + /** + * Instantiates a new DS edit table data grid data provider. + * + * @param result the result + * @param rsConfig the rs config + * @param summary the summary + * @param context the context + * @param isQueryResultEditSupported the is query result edit supported + */ + public DSEditTableDataGridDataProvider(IQueryResult result, IResultConfig rsConfig, IQueryExecutionSummary summary, + IExecutionContext context, boolean isQueryResultEditSupported) { + super(result, rsConfig, summary); + this.context = context; + deleteList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + insertedList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + insertReturningList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + this.isQueryResultEdit = isQueryResultEditSupported; + fullTableName = new String[] {""}; + if (isQueryResultEdit) { + this.table = null; + try { + ResultSet rs = result.getResultsSet(); + if (rs != null) { + ResultSetMetaData rsmd = rs.getMetaData(); + this.tableName = JSQLParserUtils.getQualifiedTableName(summary.getQuery()); + + if (null != rsmd && rsmd.getColumnCount() > 0) { + if (this.tableName == null || "".equals(this.tableName)) { + this.tableName = rsmd.getTableName(1); + } + this.columnCount = rsmd.getColumnCount(); + this.columnNames = new ArrayList(this.columnCount); + this.dataTypeNames = new ArrayList(this.columnCount); + for (int index = 1; index <= this.columnCount; index++) { + this.columnNames.add(rsmd.getColumnName(index)); + this.dataTypeNames.add(rsmd.getColumnTypeName(index)); + } + } + fullTableName = JSQLParserUtils.getSplitQualifiedName(this.tableName, false); + } + } catch (SQLException ex) { + MPPDBIDELoggerUtility.error("DSEditTableDataGridDataProvider: edit table grid data provider failed.", + ex); + } + } else { + if (context.getCurrentServerObject() instanceof TableMetaData) { + this.table = (TableMetaData) context.getCurrentServerObject(); + this.tableName = this.table.getDisplayName(); + fullTableName = JSQLParserUtils.getSplitQualifiedName(this.tableName, false); + } + } + + } + + /** + * Inits the. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + @Override + public void init() throws DatabaseOperationException, DatabaseCriticalException { + + super.init(); + } + + /** + * Checks if is edits the supported. + * + * @return true, if is edits the supported + */ + @Override + public boolean isEditSupported() { + return true; + } + + /** + * Inits the by visitor. + * + * @return the IDS result row visitor + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + @Override + public IDSResultRowVisitor initByVisitor(boolean isfuncProcResultFlow) + throws DatabaseOperationException, DatabaseCriticalException { + super.initByVisitor(isfuncProcResultFlow); + return this; + } + + /** + * Update insert row grid. + */ + protected void updateInsertRowGrid() { + + int idx = 0; + + for (IDSGridEditDataRow insertReturnedRow : insertReturningList) { + /* + * If the buffer is null, that means the insert operation is failed. + * Else, update the insert row with the returned row values. + */ + if (insertReturnedRow != null) { + IDSGridEditDataRow originalRow = insertedList.get(idx); + Object[] values = originalRow.getValues(); + if (values != null && values.length > 0) { + for (int colIndex = 0; colIndex < values.length; colIndex++) { + originalRow.setValue(colIndex, insertReturnedRow.getValue(colIndex)); + } + } + } + + idx++; + } + + insertReturningList.clear(); + + } + + /** + * Commit. + * + * @param uniqueKeysParam the unique keys param + * @param isAtomic the is atomic + * @param rowEffectedConfirm the row effected confirm + * @param connection the connection + * @return the commit status + * @throws MPPDBIDEException the MPPDBIDE exception + */ + @Override + public CommitStatus commit(List uniqueKeysParam, boolean isAtomic, + IRowEffectedConfirmation rowEffectedConfirm, DBConnection connection) throws MPPDBIDEException { + List uniqueKeys = uniqueKeysParam; + getConnectionForExecution(connection); + boolean success = false; + boolean autoCommitState = false; + boolean commitStatus = true; + try { + + if (uniqueKeys == null || uniqueKeys.isEmpty()) { + uniqueKeys = getUniqueKeys(); + + } + + // All or nothing + if (isAtomic) { + autoCommitState = executeStatementsOnAtomic(); + } + + success = updateSuccessstatus(uniqueKeys, isAtomic, rowEffectedConfirm); + } finally { + commitStatus = doPostOperationTasks(isAtomic, success, autoCommitState); + + if (this.lastCommitStatus.getListOfFailureRows().isEmpty()) { + this.updatedRowCount = 0; + } + } + // Only when commit fails, fail the transaction, so user would be + // notified. + if (!commitStatus) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_TO_BEGIN_TRANSACTION)); + throw new DatabaseOperationException(IMessagesConstants.ERR_TO_BEGIN_TRANSACTION); + } + return lastCommitStatus; + } + + /** + * Gets the connection for execution. + * + * @param connection the connection + * @return the connection for execution + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + protected void getConnectionForExecution(DBConnection connection) + throws DatabaseCriticalException, DatabaseOperationException { + if (table != null) { + conn = getConnection(); + } else { + conn = connection; + } + } + + /** + * Update successstatus. + * + * @param uniqueKeys the unique keys + * @param isAtomic the is atomic + * @param rowEffectedConfirm the row effected confirm + * @return true, if successful + * @throws MPPDBIDEException the MPPDBIDE exception + */ + protected boolean updateSuccessstatus(List uniqueKeys, boolean isAtomic, + IRowEffectedConfirmation rowEffectedConfirm) throws MPPDBIDEException { + boolean success; + success = insertRows(conn, isAtomic); + if (success || !isAtomic) { + // to detect failure in update + success = false; + success = updateRows(conn, isAtomic, uniqueKeys, rowEffectedConfirm); + } + if (success || !isAtomic) { + // to detect failure in delete + success = false; + success = deleteRows(conn, isAtomic, uniqueKeys, rowEffectedConfirm); + } + return success; + } + + /** + * Execute statements on atomic. + * + * @return true, if successful + * @throws DatabaseOperationException the database operation exception + */ + protected boolean executeStatementsOnAtomic() throws DatabaseOperationException { + boolean autoCommitState = false; + Statement stmt = null; + try { + autoCommitState = conn.getConnection().getAutoCommit(); + conn.getConnection().setAutoCommit(false); + stmt = conn.getConnection().createStatement(); + savepointName = "SP" + System.currentTimeMillis(); + stmt.execute("SAVEPOINT " + savepointName); + + } catch (SQLException ex) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_TO_BEGIN_TRANSACTION), + ex); + throw new DatabaseOperationException(IMessagesConstants.ERR_TO_BEGIN_TRANSACTION, ex); + } finally { + try { + if (null != stmt) { + stmt.close(); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Error while closing statement while create savepoint.", exception); + } + } + return autoCommitState; + } + + /** + * Do post operation tasks. + * + * @param isAtomic the is atomic + * @param success the success + * @param resetAutoCommit the reset auto commit + * @return true, if successful + */ + protected boolean doPostOperationTasks(boolean isAtomic, boolean success, boolean resetAutoCommit) { + if (isAtomic) { + Statement stmt = null; + try { + // Perform rollback or commit + if (!success) { + stmt = conn.getConnection().createStatement(); + stmt.execute("rollback to savepoint " + savepointName); + // As the mode is Atomic, none of the records are + // commited. + setFailedStatus(); + } else { + if (resetAutoCommit) { + conn.getConnection().commit(); + } + updateInsertRowGrid(); + } + // Reset the AutoCommit + conn.getConnection().setAutoCommit(resetAutoCommit); + } catch (SQLException ex) { + MPPDBIDELoggerUtility.none("Unable to close transaction"); + return false; + } finally { + try { + if (null != stmt) { + stmt.close(); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Error while closing statement while rollback to savepoint.", + exception); + } + if (null != table) { + releaseConnection(conn); + } + this.lastCommitStatus = commitStatus(); + } + } else { + updateInsertRowGrid(); + if (null != table) { + releaseConnection(conn); + } + this.lastCommitStatus = commitStatus(); + } + + return true; + } + + /** + * Sets the failed status. + */ + protected void setFailedStatus() { + + List rows = getUpdatedRows(); + + for (Iterator iterator = rows.iterator(); iterator.hasNext();) { + IDSGridEditDataRow idsGridEditDataRow = (IDSGridEditDataRow) iterator.next(); + if (idsGridEditDataRow.getExecutionStatus() == EditTableRecordExecutionStatus.SUCCESS) { + + idsGridEditDataRow.setExecutionStatus(EditTableRecordExecutionStatus.NOT_EXECUTED); + } else { + + idsGridEditDataRow.setExecutionStatus(EditTableRecordExecutionStatus.FAILED); + } + } + + rows = deleteList; + for (Iterator iterator = rows.iterator(); iterator.hasNext();) { + IDSGridEditDataRow idsGridEditDataRow = (IDSGridEditDataRow) iterator.next(); + if (idsGridEditDataRow.getExecutionStatus() == EditTableRecordExecutionStatus.SUCCESS) { + idsGridEditDataRow.setExecutionStatus(EditTableRecordExecutionStatus.NOT_EXECUTED); + } else { + idsGridEditDataRow.setExecutionStatus(EditTableRecordExecutionStatus.FAILED); + } + } + + rows = insertedList; + for (Iterator iterator = rows.iterator(); iterator.hasNext();) { + IDSGridEditDataRow idsGridEditDataRow = (IDSGridEditDataRow) iterator.next(); + idsGridEditDataRow.setExecutionStatus(EditTableRecordExecutionStatus.FAILED); + } + + } + + /** + * Gets the consolidated rows. + * + * @return the consolidated rows + */ + public List getConsolidatedRows() { + + List rows = super.getAllFetchedRows(); + IDSGridEditDataRow insertedRow; + List consolidatedRows = new ArrayList(); + consolidatedRows.addAll(rows); + Iterator iterator = insertedList.iterator(); + while (iterator.hasNext()) { + insertedRow = (IDSGridEditDataRow) iterator.next(); + consolidatedRows.add(insertedRow.getRowIndex(), insertedRow); + } + + return consolidatedRows; + } + + /** + * Commit status. + * + * @return the commit status + */ + protected CommitStatus commitStatus() { + List success = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + List failure = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + int updatedRecords = 0; + + // Insert + updatedRecords = updateCommitStatusForInsertedRows(success, failure); + + // Update + updatedRecords += updateCommitStatusForUpdatedRows(success, failure); + + // Delete + updatedRecords += updatedCommitStatusForDeletedRows(success, failure); + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_EDITED, null)); + return new CommitStatus(success, failure, updatedRecords, new ArrayList()); + } + + /** + * Updated commit status for deleted rows. + * + * @param success the success + * @param failure the failure + * @param updatedRecords the updated records + * @return the int + */ + private int updatedCommitStatusForDeletedRows(List success, List failure) { + int updatedRecords = 0; + List successCommits = new ArrayList( + MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + for (Iterator iterator = deleteList.iterator(); iterator.hasNext();) { + IDSGridEditDataRow idsGridDataRow = (IDSGridEditDataRow) iterator.next(); + if (idsGridDataRow.getExecutionStatus() == EditTableRecordExecutionStatus.SUCCESS) { + success.add(idsGridDataRow); + updatedRecords = updatedRecords + idsGridDataRow.getUpdatedRecords(); + successCommits.add(idsGridDataRow); + getAllFetchedRows().remove(idsGridDataRow); + idsGridDataRow.clearAllRowUpdates(); + } else { + failure.add(idsGridDataRow); + } + } + deleteList.removeAll(successCommits); + successCommits.clear(); + return updatedRecords; + } + + /** + * Update commit status for updated rows. + * + * @param success the success + * @param failure the failure + * @param updatedRecords the updated records + * @return the int + */ + private int updateCommitStatusForUpdatedRows(List success, List failure) { + int updatedRecords = 0; + List parentRows = getAllFetchedRows(); + + for (Iterator iterator = parentRows.iterator(); iterator.hasNext();) { + IDSGridEditDataRow idsGridDataRow = (IDSGridEditDataRow) iterator.next(); + if (idsGridDataRow.getUpdatedState() == EditTableRecordStates.UPDATE) { + if (idsGridDataRow.getExecutionStatus() == EditTableRecordExecutionStatus.SUCCESS) { + List modifiedColumns = idsGridDataRow.getModifiedColumns(); + int modifiedColumnsSize = modifiedColumns.size(); + for (int indx = 0; indx < modifiedColumnsSize; indx++) { + int colIndex = modifiedColumns.get(indx); + Object value = idsGridDataRow.getValue(colIndex); + Object[] values = idsGridDataRow.getValues(); + if (values != null) { + values[colIndex] = value; + } + } + success.add(idsGridDataRow); + updatedRecords = updatedRecords + idsGridDataRow.getUpdatedRecords(); + idsGridDataRow.clearAllRowUpdates(); + } else { + failure.add(idsGridDataRow); + } + } + + } + return updatedRecords; + } + + /** + * Update commit status for inserted rows. + * + * @param success the success + * @param failure the failure + * @param updatedRecords the updated records + * @return the int + */ + private int updateCommitStatusForInsertedRows(List success, List failure) { + int updatedRecords = 0; + List successCommits = new ArrayList( + MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + + for (Iterator iterator = insertedList.iterator(); iterator.hasNext();) { + IDSGridEditDataRow idsGridDataRow = (IDSGridEditDataRow) iterator.next(); + if (idsGridDataRow.getExecutionStatus() == EditTableRecordExecutionStatus.SUCCESS) { + success.add(idsGridDataRow); + updatedRecords = updatedRecords + 1; + successCommits.add(idsGridDataRow); + Object[] values = idsGridDataRow.getValues(); + if (values != null && values.length > 0) { + for (int indx = 0; indx < values.length; indx++) { + values[indx] = idsGridDataRow.getValue(indx); + } + } + getAllFetchedRows().add(idsGridDataRow.getRowIndex(), idsGridDataRow); + idsGridDataRow.clearAllRowUpdates(); + } else { + failure.add(idsGridDataRow); + } + } + + insertedList.removeAll(successCommits); + successCommits.clear(); + return updatedRecords; + } + + /** + * Release connection. + * + * @param dbConn the db conn + */ + protected void releaseConnection(DBConnection dbConn) { + context.getTermConnection().getDatabase().getConnectionManager().releaseConnection(dbConn); + } + + /** + * Checks if is insert returning record supported. + * + * @return true, if is insert returning record supported + */ + protected boolean isInsertReturningRecordSupported() { + return context.getTermConnection().getDatabase().isSupportInsertReturing(); + } + + /** + * Delete rows. + * + * @param dbConn the db conn + * @param isAtomic the is atomic + * @param uniqueKeys the unique keys + * @param rowEffectedConfirm the row effected confirm + * @return true, if successful + * @throws MPPDBIDEException the MPPDBIDE exception + */ + protected boolean deleteRows(DBConnection dbConn, boolean isAtomic, List uniqueKeys, + IRowEffectedConfirmation rowEffectedConfirm) throws MPPDBIDEException { + List deletedRows = deleteList; + + boolean status = true; + + for (Iterator iterator = deletedRows.iterator(); iterator.hasNext();) { + IDSGridEditDataRow idsGridEditDataRow = (IDSGridEditDataRow) iterator.next(); + if (!isCancelled()) { + EditTableExecuteQueryUtility editTableExcutequery = EditTableExecuteQueryFactory + .getEditTableExecuteQuery(this.getDatabse().getDBType()); + status = editTableExcutequery.executeDeleteRowCommand(idsGridEditDataRow, fullTableName, this, dbConn, + uniqueKeys, getColumnDataProvider(), rowEffectedConfirm, isAtomic); + } else { + break; + } + if (!status && isAtomic) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_QUERY_EXECUTION_FAILED)); + throw new DatabaseOperationException(IMessagesConstants.ERR_QUERY_EXECUTION_FAILED); + } + } + + return status; + } + + /** + * Update rows. + * + * @param dbConn the db conn + * @param isAtomic the is atomic + * @param uniqueKeys the unique keys + * @param rowEffectedConfirm the row effected confirm + * @return true, if successful + * @throws MPPDBIDEException the MPPDBIDE exception + */ + protected boolean updateRows(DBConnection dbConn, boolean isAtomic, List uniqueKeys, + IRowEffectedConfirmation rowEffectedConfirm) throws MPPDBIDEException { + List updatedRows = getUpdatedRows(); + + boolean status = true; + + for (Iterator iterator = updatedRows.iterator(); iterator.hasNext();) { + IDSGridEditDataRow idsGridEditDataRow = (IDSGridEditDataRow) iterator.next(); + + if (!isCancelled()) { + EditTableExecuteQueryUtility editTableExcutequery = EditTableExecuteQueryFactory + .getEditTableExecuteQuery(this.getDatabse().getDBType()); + status = editTableExcutequery.executeUpdateRowCommand(idsGridEditDataRow, fullTableName, this, dbConn, + uniqueKeys, getColumnDataProvider(), rowEffectedConfirm, isAtomic); + } else { + break; + } + if (!status && isAtomic) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_QUERY_EXECUTION_FAILED)); + throw new DatabaseOperationException(IMessagesConstants.ERR_QUERY_EXECUTION_FAILED); + } else if (status && !isAtomic) { + List modifiedColumns = idsGridEditDataRow.getModifiedColumns(); + for (int i = 0; i < modifiedColumns.size(); i++) { + int index = modifiedColumns.get(i); + Object value = idsGridEditDataRow.getValue(index); + Object[] originalValues = ((DSEditTableDataGridRow)idsGridEditDataRow).getAllOriginal(); + originalValues[index] = value; + } + decrementUpdatedRowCount(); + } + } + + return status; + } + + /** + * Gets the updated rows. + * + * @return the updated rows + */ + private List getUpdatedRows() { + List allRows = getAllFetchedRows(); + List updatedRows = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + + for (Iterator iterator = allRows.iterator(); iterator.hasNext();) { + IDSGridEditDataRow idsGridDataRow = (IDSGridEditDataRow) iterator.next(); + if (idsGridDataRow.getUpdatedState() == EditTableRecordStates.UPDATE) { + updatedRows.add(idsGridDataRow); + } + } + + return updatedRows; + } + + /** + * Checks if is distribution columns required. + * + * @return true, if is distribution columns required + */ + public boolean isDistributionColumnsRequired() { + + if (!deleteList.isEmpty()) { + return true; + } + + for (Iterator iterator = getAllFetchedRows().iterator(); iterator.hasNext();) { + IDSGridEditDataRow idsGridDataRow = (IDSGridEditDataRow) iterator.next(); + if (idsGridDataRow.getUpdatedState() == EditTableRecordStates.UPDATE) { + return true; + } + } + + return false; + } + + /** + * Insert rows. + * + * @param dbConn the db conn + * @param isAtomic the is atomic + * @return true, if successful + * @throws MPPDBIDEException the MPPDBIDE exception + */ + private boolean insertRows(DBConnection dbConn, boolean isAtomic) throws MPPDBIDEException { + List insertedRows = insertedList; + boolean status = true; + + boolean insertReturningRecordSupported = isInsertReturningRecordSupported(); + for (Iterator iterator = insertedRows.iterator(); iterator.hasNext();) { + IDSGridEditDataRow idsGridEditDataRow = (IDSGridEditDataRow) iterator.next(); + DSEditTableDataGridRow emptyRow = new DSEditTableDataGridRow(eventTable, this); + if (idsGridEditDataRow instanceof DSEditTableDataGridRow) { + DSEditTableDataGridRow newRow = (DSEditTableDataGridRow) idsGridEditDataRow; + emptyRow.setEncoding(getEncoding()); + emptyRow.setIncludeEncoding(newRow.isIncludeEncoding()); + } + if (!isCancelled()) { + EditTableExecuteQueryUtility editTableExcutequery = EditTableExecuteQueryFactory + .getEditTableExecuteQuery(this.getDatabse().getDBType()); + status = editTableExcutequery.executeInsertRowCommand(idsGridEditDataRow, emptyRow, this, table, dbConn, + fullTableName, insertReturningRecordSupported, isAtomic); + + if (status) { + /* + * save the post insert returning row in the list. + */ + insertReturningList.add(emptyRow); + } else { + /* + * if there is failure, insert null in the returning list. + * the method to show to the editor, must check for null and + * assume the failure and act properly. + */ + insertReturningList.add(null); + } + } else { + break; + } + if (!status && isAtomic) { + /* + * if during the insert operations, one of them fails and user + * has chosen the operation set to be atomic then, we need to + * stop the operation any further and return immediately. + */ + insertReturningList.clear(); + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_QUERY_EXECUTION_FAILED)); + throw new DatabaseOperationException(IMessagesConstants.ERR_QUERY_EXECUTION_FAILED); + } + } + + return status; + } + + /** + * Gets the connection. + * + * @return the connection + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + protected DBConnection getConnection() throws DatabaseCriticalException, DatabaseOperationException { + + try { + if (!context.getTermConnection().getDatabase().isConnected()) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.EDIT_TABLE_DATA_CONNECTION_LOST_ERR_MSG)); + throw new DatabaseCriticalException(IMessagesConstants.EDIT_TABLE_DATA_CONNECTION_LOST_ERR_MSG); + + } + return context.getTermConnection().getDatabase().getConnectionManager().getFreeConnection(); + } catch (MPPDBIDEException exception) { + if (exception instanceof DatabaseCriticalException) { + throw (DatabaseCriticalException) exception; + } else { + throw (DatabaseOperationException) exception; + } + } + } + + /** + * Roll back provider. + */ + @Override + public void rollBackProvider() { + insertedList.clear(); + deleteList.clear(); + updatedRowCount = 0; + List allRows = getAllFetchedRows(); + + for (Iterator iterator = allRows.iterator(); iterator.hasNext();) { + IDSGridEditDataRow idsGridDataRow = (IDSGridEditDataRow) iterator.next(); + idsGridDataRow.clearAllRowUpdates(); + } + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_EDITED, null)); + + } + + /** + * Gets the empty row for insert. + * + * @param index the index + * @return the empty row for insert + */ + @Override + public IDSGridEditDataRow getEmptyRowForInsert(int index) { + // check the use of index and remove index + DSEditTableDataGridRow emptyRow = new DSEditTableDataGridRow(true, index, eventTable, this); + int colCount = getColumnDataProvider().getColumnCount(); + Object[] value = new Object[colCount]; + emptyRow.createNewRow(value); + emptyRow.setOriginalValues(value.clone()); + emptyRow.setIncludeEncoding(BLPreferenceManager.getInstance().getBLPreference().isIncludeEncoding()); + emptyRow.setEncoding(super.getEncoding()); + addToInsertList(emptyRow); + + return emptyRow; + } + + /** + * Creates the row from values. + * + * @param rowValues the row values + * @return the IDS grid data row + */ + @Override + protected IDSGridDataRow createRowFromValues(Object[] rowValues) { + DSEditTableDataGridRow row = new DSEditTableDataGridRow(eventTable, this); + row.setValues(rowValues); + row.setOriginalValues(rowValues.clone()); + row.setIncludeEncoding(isIncludeEncoding()); + + return row; + } + + /** + * Update data to rows. + * + * @param values the values + */ + @Override + protected void updateDataToRows(Object[][] values) { + for (int rowIndex = 0; rowIndex < values.length; rowIndex++) { + getAllFetchedRows().add(createRowFromValues(values[rowIndex])); + } + + summary.setNumRecordsFetched(getAllFetchedRows().size()); + } + + /** + * Adds the to insert list. + * + * @param emptyRow the empty row + */ + private void addToInsertList(IDSGridEditDataRow emptyRow) { + /* + * 1. Create Empty table, insert 1 row, fill data, again insert 1 row + * fill data, again insert 1 row fill data. + */ + + this.insertedList.add(emptyRow); + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_EDITED, null)); + } + + /** + * Delete record. + * + * @param row the row + * @param insertedRecord the inserted record + */ + @Override + public void deleteRecord(IDSGridEditDataRow row, boolean insertedRecord) { + + // check if the record is just inserted and being deleted + // check if the record is modified and being deleted(add to delete list + // and remove from the modified list) + // check if the record is marked as deleted and user try update it(add + // only to delete list and remove from parent + + if (insertedRecord) { + this.insertedList.remove(row); + // move the row index to one above for all rows + // below the currently deleted row. + rearrangeInsertedRowIndex(row.getRowIndex()); + } else if (!deleteList.contains(row)) { + this.deleteList.add(row); + row.setStateDelete(); + } + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_EDITED, null)); + } + + /** + * Call this method to rearrange the row index by reducing by 1 as one + * element is removed. + * + * @param rowIndex the row index + */ + private void rearrangeInsertedRowIndex(int rowIndex) { + + List insList = insertedList; + Iterator it = insList.iterator(); + while (it.hasNext()) { + IDSGridEditDataRow row = it.next(); + int index = row.getRowIndex(); + if (index > rowIndex) { + row.setRowIndex(index - 1); + } + } + + } + + /** + * Gets the unique keys. + * + * @return the unique keys + */ + public List getUniqueKeys() { + List uniqueKeys = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + if (table != null) { + List columnMetaDataList = table.getColumnMetaDataList(); + + for (Iterator iterator = columnMetaDataList.iterator(); iterator.hasNext();) { + ColumnMetaData columnMetaData = (ColumnMetaData) iterator.next(); + uniqueKeys.add(columnMetaData.getName()); + } + + } + return uniqueKeys; + } + + /** + * Checks if is unique key present. + * + * @return true, if is unique key present + */ + @Override + public boolean isUniqueKeyPresent() { + if (table != null) { + List constraintMetaDataList = table.getConstraintMetaDataList(); + + for (Iterator iterator = constraintMetaDataList.iterator(); iterator.hasNext();) { + ConstraintMetaData constraintMetaData = (ConstraintMetaData) iterator.next(); + if (constraintMetaData.getConstraintType() == ConstraintType.UNIQUE_KEY_CONSTRSINT + || constraintMetaData.getConstraintType() == ConstraintType.PRIMARY_KEY_CONSTRSINT) { + return true; + } + } + } + return false; + } + + /** + * Gets the table. + * + * @return the table + */ + @Override + public ServerObject getTable() { + if (table != null) { + return this.table; + } else { + return null; + } + } + + /** + * Gets the table name. + * + * @return the table name + */ + @Override + public String getTableName() { + return this.tableName; + } + + /** + * Gets the databse. + * + * @return the databse + */ + @Override + public Database getDatabse() { + if (null != super.getDatabse()) { + return super.getDatabse(); + } else if (null != context && null != context.getTermConnection()) { + return context.getTermConnection().getDatabase(); + } + + return null; + } + + /** + * Gets the distributed column list. + * + * @return the distributed column list + */ + public List getDistributedColumnList() { + if (this.table == null) { + return null; + } + return this.table.getDistributionColumnList(); + } + + /** + * Checks if is distribution column. + * + * @param columnIndex the column index + * @return true, if is distribution column + */ + public boolean isDistributionColumn(int columnIndex) { + if (this.table == null) { + return false; + } else if (columnIndex < this.table.getColumns().getSize()) { + return this.table.isDistributionColumn(columnIndex); + } + return false; + } + + /** + * Sets the cancel. + * + * @param cancel the new cancel + */ + @Override + public void setCancel(boolean cancel) { + this.cancelled = cancel; + + } + + /** + * Checks if is cancelled. + * + * @return true, if is cancelled + */ + @Override + public boolean isCancelled() { + return this.cancelled; + } + + /** + * Checks if is grid data edited. + * + * @return true, if is grid data edited + */ + @Override + public boolean isGridDataEdited() { + return getUpdatedRowCount() > 0 || insertedList.size() > 0 || deleteList.size() > 0; + } + + /** + * Gets the updated row count. + * + * @return the updated row count + */ + @Override + public int getUpdatedRowCount() { + return this.updatedRowCount; + } + + /** + * Gets the inserted row count. + * + * @return the inserted row count + */ + @Override + public int getInsertedRowCount() { + return insertedList.size(); + } + + /** + * Gets the deleted row count. + * + * @return the deleted row count + */ + @Override + public int getDeletedRowCount() { + return deleteList.size(); + } + + /** + * Gets the last commit status. + * + * @return the last commit status + */ + @Override + public CommitStatus getLastCommitStatus() { + + return this.lastCommitStatus; + } + + /** + * Cancel commit. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + @Override + public void cancelCommit() throws DatabaseCriticalException, DatabaseOperationException { + + if (null != conn) { + conn.cancelQuery(); + } + + } + + /** + * Increment updated row count. + */ + public void incrementUpdatedRowCount() { + this.updatedRowCount++; + } + + /** + * Decrement updated row count. + */ + public void decrementUpdatedRowCount() { + this.updatedRowCount--; + + } + + /** + * Gets the column count. + * + * @return the column count + */ + @Override + public int getColumnCount() { + return this.columnCount; + } + + /** + * Gets the column names. + * + * @return the column names + */ + @Override + public List getColumnNames() { + return this.columnNames; + } + + /** + * Gets the column data type names. + * + * @return the column data type names + */ + @Override + public List getColumnDataTypeNames() { + return this.dataTypeNames; + } + + /** + * Change encoding. + * + * @param newEncoding the new encoding + */ + @Override + public void changeEncoding(String newEncoding) { + super.changeEncoding(newEncoding); + setEncodingForEditRow(insertedList, newEncoding); + setEncodingForEditRow(insertReturningList, newEncoding); + } + + /** + * Sets the encoding for edit row. + * + * @param rows2 the rows 2 + * @param newEncoding the new encoding + */ + private void setEncodingForEditRow(List rows2, String newEncoding) { + for (IDSGridDataRow row : rows2) { + if (row instanceof DSResultSetGridDataRow) { + // Checking instance for one record is sufficient, but static + // tools may not think so. + DSResultSetGridDataRow rsRow = (DSResultSetGridDataRow) row; + rsRow.setIncludeEncoding(isIncludeEncoding()); + rsRow.setEncoding(newEncoding); + } + } + } + + /** + * Pre destroy. + */ + @Override + public void preDestroy() { + super.preDestroy(); + this.context = null; + this.table = null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSEditTableDataGridRow.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSEditTableDataGridRow.java new file mode 100644 index 0000000000000000000000000000000000000000..80b5612a5246ebc2f9a20113d3f041c252964667 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSEditTableDataGridRow.java @@ -0,0 +1,281 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.edittabledata; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.utils.observer.DSEventTable; +import org.opengauss.mppdbide.utils.observer.IDSGridUIListenable; + +/** + * + * Title: class + * + * Description: The Class DSEditTableDataGridRow. + * + * @since 3.0.0 + */ +public class DSEditTableDataGridRow extends DSResultSetGridDataRow implements IDSGridEditDataRow { + private Map modifiedData = null; + private EditTableRecordStates state; + private EditTableRecordExecutionStatus execState = EditTableRecordExecutionStatus.NOT_EXECUTED; + private String commitStatusMessage = ""; + private int rowIndex = 0; + private DSEventTable eventTable; + private int updatedRecords; + private DSEditTableDataGridDataProvider dataProvider; + private Map cellStateMap; + + /** + * Instantiates a new DS edit table data grid row. + * + * @param isNewRow the is new row + * @param index the index + * @param eventTable the event table + * @param dataProvider the data provider + */ + public DSEditTableDataGridRow(boolean isNewRow, int index, DSEventTable eventTable, + DSEditTableDataGridDataProvider dataProvider) { + super(dataProvider); + this.eventTable = eventTable; + state = isNewRow ? EditTableRecordStates.INSERT : EditTableRecordStates.NOT_EDITED; + this.rowIndex = index; + updatedRecords = 0; + this.dataProvider = dataProvider; + } + + /** + * Instantiates a new DS edit table data grid row. + * + * @param eventTable the event table + * @param dataProvider the data provider + */ + public DSEditTableDataGridRow(DSEventTable eventTable, DSEditTableDataGridDataProvider dataProvider) { + super(dataProvider); + this.eventTable = eventTable; + state = EditTableRecordStates.NOT_EDITED; + updatedRecords = 0; + this.dataProvider = dataProvider; + } + + /** + * Gets the cell state map. + * + * @return the cell state map + */ + private Map getCellStateMap() { + if (this.cellStateMap == null) { + cellStateMap = new HashMap(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + } + return cellStateMap; + } + + /** + * Gets the modified data map. + * + * @return the modified data map + */ + private Map getModifiedDataMap() { + if (this.modifiedData == null) { + modifiedData = new HashMap(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + } + return modifiedData; + } + + @Override + public void setValue(int columnIndex, Object newValue) { + getModifiedDataMap().put(columnIndex, newValue); + + if (state == EditTableRecordStates.NOT_EDITED) { + state = EditTableRecordStates.UPDATE; + this.dataProvider.incrementUpdatedRowCount(); + } + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_EDITED, null)); + + } + + @Override + public void undo(int columnIndex) { + if (getModifiedDataMap().containsKey(columnIndex)) { + getModifiedDataMap().remove(columnIndex); + + // Enum comparison doesn't need equals check as suggested by + if (getModifiedDataMap().isEmpty() && state == EditTableRecordStates.UPDATE) { + this.dataProvider.decrementUpdatedRowCount(); + setState(EditTableRecordStates.NOT_EDITED); + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_EDITED, null)); + } + + } + } + + @Override + public EditTableRecordStates getUpdatedState() { + return this.state; + } + + @Override + public EditTableRecordStates getUpdatedState(int columnIndex) { + if (this.state == EditTableRecordStates.UPDATE && null != modifiedData + && !modifiedData.containsKey(columnIndex)) { + return EditTableRecordStates.NOT_EDITED; + } + + return this.state; + } + + @Override + public void createNewRow(Object[] value) { + values = value.clone(); + setState(EditTableRecordStates.INSERT); + } + + /** + * Sets the state. + * + * @param insertState the new state + */ + private void setState(EditTableRecordStates insertState) { + this.state = insertState; + + } + + @Override + public Object getValue(int columnIndex) { + if (null != modifiedData && modifiedData.containsKey(columnIndex)) { + if (isIncludeEncoding() && !isUnstructuredDatatype(columnIndex)) { + return getEncodedValue(modifiedData.get(columnIndex)); + } + return modifiedData.get(columnIndex); + } + return super.getValue(columnIndex); + } + + @Override + public Object[] getValues() { + Object[] values = super.getValues(); + for (Map.Entry modifiedEntry : getModifiedDataMap().entrySet()) { + if (isIncludeEncoding() && !isUnstructuredDatatype(modifiedEntry.getKey())) { + values[modifiedEntry.getKey()] = getEncodedValue(modifiedEntry.getValue()); + } else { + values[modifiedEntry.getKey()] = modifiedEntry.getValue(); + } + } + + return values; + } + + @Override + public void clearAllRowUpdates() { + getModifiedDataMap().clear(); + setState(EditTableRecordStates.NOT_EDITED); + setExecutionStatus(EditTableRecordExecutionStatus.NOT_EXECUTED); + commitStatusMessage = ""; + } + + @Override + public Object getOriginalValue(int columnIndex) { + + if (getUpdatedState() == EditTableRecordStates.INSERT) { + getValue(columnIndex); + } + + return super.getOriginalValue(columnIndex); + } + + @Override + public void setExecutionStatus(EditTableRecordExecutionStatus status) { + execState = status; + } + + @Override + public EditTableRecordExecutionStatus getExecutionStatus() { + return execState; + } + + @Override + public List getModifiedColumns() { + return new ArrayList(getModifiedDataMap().keySet()); + } + + @Override + public void setStateDelete() { + this.state = EditTableRecordStates.DELETE; + } + + @Override + public String getCommitStatusMessage() { + return commitStatusMessage; + } + + @Override + public void setCommitStatusMessage(String commitStatusMessage) { + this.commitStatusMessage = commitStatusMessage; + } + + @Override + public int getRowIndex() { + return rowIndex; + } + + @Override + public void setRowIndex(int rowIndex) { + this.rowIndex = rowIndex; + } + + @Override + public Object[] getClonedValues() { + // Cannot use Super.getClonedValues() as it would call this.getValues() + // So, the original value will be changed. + Object[] values = super.getValues().clone(); + + for (Map.Entry modifiedEntry : getModifiedDataMap().entrySet()) { + values[modifiedEntry.getKey()] = modifiedEntry.getValue(); + } + + return values; + } + + @Override + public int getUpdatedRecords() { + + return updatedRecords; + } + + @Override + public void setUpdatedRecords(int updatedRecords) { + this.updatedRecords = updatedRecords; + } + + @Override + public EditTableCellState getCellStatus(int colIndex) { + EditTableCellState editTableCellState = EditTableCellState.MODIFIED_FAILED; + if (getCellStateMap().containsKey(colIndex)) { + editTableCellState = getCellStateMap().get(colIndex); + } + return editTableCellState; + } + + @Override + public void setCellSatus(EditTableCellState cellState, int colIndex) { + getCellStateMap().put(colIndex, cellState); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSGridEditDataRow.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSGridEditDataRow.java new file mode 100644 index 0000000000000000000000000000000000000000..4e14b9bd5081492696bcc7afec96989be32dac59 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSGridEditDataRow.java @@ -0,0 +1,338 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.edittabledata; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.opengauss.mppdbide.utils.observer.DSEventTable; + +/** + * + * Title: class + * + * Description: The Class DSGridEditDataRow. + * + * @since 3.0.0 + */ +public class DSGridEditDataRow implements IDSGridEditDataRow { + + /** + * The rows. + */ + protected Object[] rows; + + /** + * The modified data. + */ + protected Map modifiedData = new HashMap(); + + /** + * The rowstate. + */ + protected EditTableRecordStates rowstate; + + /** + * The event table. + */ + protected DSEventTable eventTable; + + /** + * The row index. + */ + protected int rowIndex; + + /** + * The execution status. + */ + protected EditTableRecordExecutionStatus executionStatus; + + /** + * The commit message. + */ + protected String commitMessage; + + /** + * Gets the values. + * + * @return the values + */ + @Override + public Object[] getValues() { + return rows.clone(); + } + + /** + * Gets the value. + * + * @param columnIndex the column index + * @return the value + */ + @Override + public Object getValue(int columnIndex) { + + if (modifiedData.containsKey(columnIndex)) { + return modifiedData.get(columnIndex); + } + return rows[columnIndex]; + } + + /** + * Gets the cloned values. + * + * @return the cloned values + */ + @Override + public Object[] getClonedValues() { + return getValues().clone(); + } + + /** + * Sets the value. + * + * @param columnIndex the column index + * @param newValue the new value + */ + @Override + public void setValue(int columnIndex, Object newValue) { + + } + + /** + * Sets the state. + * + * @param state the new state + */ + protected void setState(EditTableRecordStates state) { + this.rowstate = state; + + } + + /** + * Creates the new row. + * + * @param value the value + */ + @Override + public void createNewRow(Object[] value) { + rows = value.clone(); + setState(EditTableRecordStates.INSERT); + } + + /** + * Undo. + * + * @param columnIndex the column index + */ + @Override + public void undo(int columnIndex) { + + } + + /** + * Gets the updated state. + * + * @return the updated state + */ + @Override + public EditTableRecordStates getUpdatedState() { + return this.rowstate; + } + + /** + * Gets the updated state. + * + * @param columnIndex the column index + * @return the updated state + */ + @Override + public EditTableRecordStates getUpdatedState(int columnIndex) { + if (this.rowstate == EditTableRecordStates.UPDATE && !modifiedData.containsKey(columnIndex)) { + return EditTableRecordStates.NOT_EDITED; + } + + return this.rowstate; + } + + /** + * Clear all row updates. + */ + @Override + public void clearAllRowUpdates() { + modifiedData.clear(); + setState(EditTableRecordStates.NOT_EDITED); + setExecutionStatus(EditTableRecordExecutionStatus.NOT_EXECUTED); + + } + + /** + * Sets the execution status. + * + * @param status the new execution status + */ + @Override + public void setExecutionStatus(EditTableRecordExecutionStatus status) { + this.executionStatus = status; + } + + /** + * Gets the execution status. + * + * @return the execution status + */ + @Override + public EditTableRecordExecutionStatus getExecutionStatus() { + return this.executionStatus; + } + + /** + * Gets the original value. + * + * @param columnIndex the column index + * @return the original value + */ + @Override + public Object getOriginalValue(int columnIndex) { + if (getUpdatedState() == EditTableRecordStates.INSERT) { + return getValue(columnIndex); + } + return rows[columnIndex]; + } + + /** + * Gets the modified columns. + * + * @return the modified columns + */ + @Override + public List getModifiedColumns() { + return new ArrayList<>(modifiedData.keySet()); + } + + /** + * Sets the state delete. + */ + @Override + public void setStateDelete() { + this.rowstate = EditTableRecordStates.DELETE; + } + + /** + * Gets the commit status message. + * + * @return the commit status message + */ + @Override + public String getCommitStatusMessage() { + + return this.commitMessage; + } + + /** + * Sets the commit status message. + * + * @param commitStatusMessage the new commit status message + */ + @Override + public void setCommitStatusMessage(String commitStatusMessage) { + this.commitMessage = commitStatusMessage; + } + + /** + * Gets the row index. + * + * @return the row index + */ + @Override + public int getRowIndex() { + return this.rowIndex; + } + + /** + * Sets the row index. + * + * @param rowIndex the new row index + */ + @Override + public void setRowIndex(int rowIndex) { + this.rowIndex = rowIndex; + } + + /** + * Gets the updated records. + * + * @return the updated records + */ + @Override + public int getUpdatedRecords() { + + return 0; + } + + /** + * Sets the updated records. + * + * @param updatedRecords the new updated records + */ + @Override + public void setUpdatedRecords(int updatedRecords) { + + } + + /** + * Sets the cell satus. + * + * @param cellState the cell state + * @param columnIndex the column index + */ + @Override + public void setCellSatus(EditTableCellState cellState, int columnIndex) { + + } + + /** + * Gets the cell status. + * + * @param columnIndex the column index + * @return the cell status + */ + @Override + public EditTableCellState getCellStatus(int columnIndex) { + + return null; + } + + /** + * Gets the event table. + * + * @return the event table + */ + public DSEventTable getEventTable() { + return eventTable; + } + + /** + * Sets the event table. + * + * @param eventTable the new event table + */ + public void setEventTable(DSEventTable eventTable) { + this.eventTable = eventTable; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSResultSetGridColumnDataProvider.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSResultSetGridColumnDataProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..4e25958e9d9ee6319a26e93f9683c7bae131017c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSResultSetGridColumnDataProvider.java @@ -0,0 +1,307 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.edittabledata; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; + +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.bl.serverdatacache.IQueryResult; +import org.opengauss.mppdbide.bl.serverdatacache.QueryResult; +import org.opengauss.mppdbide.bl.serverdatacache.ResultSetColumn; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.presentation.grid.resultset.ColumnValueSqlTypeComparator; +import org.opengauss.mppdbide.presentation.grid.resultset.CursorQueryResult; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class DSResultSetGridColumnDataProvider. + * + * @since 3.0.0 + */ +public class DSResultSetGridColumnDataProvider implements IDSGridColumnProvider { + private ResultSetColumn[] cols; + private int columnCount; + + /** + * Inits the. + * + * @param queryResult the query result + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void init(IQueryResult queryResult) throws DatabaseOperationException, DatabaseCriticalException { + this.columnCount = queryResult.getColumnCount(); + this.cols = queryResult.getColumnMetaData(); + } + + /** + * initialize column header name + * + * @param colValueList the colValueList + * @param isCallableStmt the isCallableStmt + * @param iQueryResult the iQueryResult + * @throws DatabaseCriticalException the DatabaseCriticalException + * @throws DatabaseOperationException the DatabaseOperationException + */ + public void initColHeaderName(Object[] colValueList, boolean isCallableStmt, IQueryResult iQueryResult) + throws DatabaseCriticalException, DatabaseOperationException { + List columnHeaderName = new ArrayList(columnCount); + boolean isCursorType = initColumnHeader(colValueList, columnHeaderName); + if (colValueList != null) { + this.columnCount = colValueList.length; + } else { + this.columnCount = 4; + } + if (iQueryResult instanceof CursorQueryResult) { + this.cols = ((CursorQueryResult) iQueryResult).getColumnHeaderName(this.columnCount, columnHeaderName, + isCallableStmt, isCursorType); + } + if (iQueryResult instanceof QueryResult) { + this.cols = ((QueryResult) iQueryResult).getColumnHeaderName(this.columnCount, columnHeaderName, + isCallableStmt, isCursorType); + } + } + + /** + * initialize column header name by visitor + * + * @param colValueList the colValueList + * @param isCallableStmt the isCallableStmt + * @throws DatabaseCriticalException the DatabaseCriticalException + * @throws DatabaseOperationException the DatabaseOperationException + */ + public void initByVisitorColHeaderName(Object[] colValueList, boolean isCallableStmt, IQueryResult iQryResult) + throws DatabaseCriticalException, DatabaseOperationException { + List columnHeaderName = new ArrayList(columnCount); + boolean isCursorType = initColumnHeader(colValueList, columnHeaderName); + if (colValueList != null) { + this.columnCount = colValueList.length; + } else { + this.columnCount = 4; + } + if (iQryResult != null && iQryResult instanceof CursorQueryResult) { + this.cols = ((CursorQueryResult) iQryResult).getColumnHeaderName(this.columnCount, columnHeaderName, + isCallableStmt, isCursorType); + } + } + + /** + * initialize By Visitor PopUp Header Name + * + * @param colValueList the colValueList + */ + public void initByVisitorPopUpHeaderName(Object[] colValueList) { + List columnHeaderName = new ArrayList(); + initColumnHeader(colValueList, columnHeaderName); + if (colValueList != null) { + this.columnCount = colValueList.length; + } + this.cols = getCursorPopupColheaderName(this.columnCount, columnHeaderName); + + } + + /** + * gets the cursor popup column header name + * + * @param columnCount the column count + * @param columnHeaderName the column header name + * @param cursorPopUpdataType the cursor popup datatype + * @return metaData the resultset column object + */ + private ResultSetColumn[] getCursorPopupColheaderName(int columnCount, List columnHeaderName) { + ResultSetColumn[] metaData = new ResultSetColumn[columnCount]; + for (int i = 0; i < columnCount; i++) { + metaData[i] = new ResultSetColumn(i + 1); + metaData[i].setPopUpColumnHeaderName(columnHeaderName.get(i), i + 1); + } + return metaData; + } + + /** + * init column header + * + * @param colValueList the colValueList + * @param columnHeaderName the columnHeaderName + * @return return true, if is cursor type + */ + private boolean initColumnHeader(Object[] colValueList, List columnHeaderName) { + boolean isCursorType = false; + if (colValueList != null) { + for (int i = 0; i < colValueList.length; i++) { + columnHeaderName.add((String) colValueList[i]); + } + isCursorType = true; + } else { + columnHeaderName.add(MessageConfigLoader.getProperty(IMessagesConstants.RESULT_TAB_COL_NAME)); + columnHeaderName.add(MessageConfigLoader.getProperty(IMessagesConstants.RESULT_TAB_COL_DATA_TYPE)); + columnHeaderName.add(MessageConfigLoader.getProperty(IMessagesConstants.RESULT_TAB_COL_PARAMETER_TYPE)); + columnHeaderName.add(MessageConfigLoader.getProperty(IMessagesConstants.RESULT_TAB_COL_VALUE)); + } + return isCursorType; + } + + /** + * Inits the. + * + * @param colCount the col count + * @param rcols the rcols + */ + public void init(int colCount, ResultSetColumn[] rcols) { + this.columnCount = colCount; + this.cols = rcols.clone(); + } + + @Override + public int getColumnCount() { + return this.columnCount; + } + + @Override + public String[] getColumnNames() { + String[] names = new String[this.columnCount]; + for (int index = 0; index < this.columnCount; index++) { + names[index] = this.cols[index].getColumnName(); + } + + return names; + } + + @Override + public String getColumnName(int columnIndex) { + return this.cols[columnIndex].getColumnName(); + } + + @Override + public String getColumnDesc(int columnIndex) { + return getColumnName(columnIndex) + " - " + getDataTypeName(columnIndex); + } + + /** + * Gets the data type name. + * + * @param columnIndex the column index + * @return the data type name + */ + public String getDataTypeName(int columnIndex) { + return this.cols[columnIndex].getDataTypeName(); + } + + /** + * Gets the data type names. + * + * @return the data type names + */ + public String[] getDataTypeNames() { + String[] typeNames = new String[this.columnCount]; + for (int index = 0; index < this.columnCount; index++) { + typeNames[index] = this.cols[index].getDataTypeName(); + } + + return typeNames; + } + + @Override + public int getColumnIndex(String columnLabel) { + // No idea, who and when this code will be used. + for (int index = 0; index < this.columnCount; index++) { + if (columnLabel.equals(this.cols[index].getColumnName())) { + return index; + } + } + + return -1; + } + + @Override + public Comparator getComparator(int columnIndex) { + return new ColumnValueSqlTypeComparator(this.cols[columnIndex].getDataType()); + } + + @Override + public int getColumnDatatype(int columnIndex) { + return this.cols[columnIndex].getDataType(); + } + + /** + * Gets the column data type name. + * + * @param columnIndex the column index + * @return the column data type name + */ + public String getColumnDataTypeName(int columnIndex) { + return getDataTypeName(columnIndex); + } + + /** + * Gets the precision. + * + * @param columnIndex the column index + * @return the precision + */ + public int getPrecision(int columnIndex) { + return this.cols[columnIndex].getPrecision(); + } + + /** + * Gets the scale. + * + * @param columnIndex the column index + * @return the scale + */ + public int getScale(int columnIndex) { + return this.cols[columnIndex].getScale(); + } + + @Override + public int getMaxLength(int columnIndex) { + return this.cols[columnIndex].getMaxLength(); + } + + @Override + public String getColumnComment(int columnIndex) { + return (0 <= columnIndex && columnIndex < this.cols.length) ? this.cols[columnIndex].getComment() : ""; + } + + /** + * Adds the default values. + * + * @param defaultValueMap the default value map + */ + public void addDefaultValues(Map defaultValueMap) { + String colName = null; + for (int i = 0; i < this.cols.length; i++) { + colName = this.cols[i].getColumnName(); + String defaultVal = defaultValueMap.get(colName); + this.cols[i].setDefaultValue(defaultVal); + } + } + + @Override + public String getDefaultValue(int columnIndex) { + return this.cols[columnIndex].getDefaultValue(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSResultSetGridDataProvider.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSResultSetGridDataProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..249cb7a23667416f31499bfbeee220bbeaf7157a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSResultSetGridDataProvider.java @@ -0,0 +1,995 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.edittabledata; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.adapter.gauss.StmtExecutor; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DefaultParameter; +import org.opengauss.mppdbide.bl.serverdatacache.IQueryResult; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.sqlhistory.IQueryExecutionSummary; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnGroupProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataAccessListenable; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.presentation.grid.IDSResultRowVisitor; +import org.opengauss.mppdbide.presentation.resultsetif.IResultConfig; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.ResultSetDatatypeMapping; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.utils.observer.DSEventTable; +import org.opengauss.mppdbide.utils.observer.IDSListener; +import org.opengauss.mppdbide.utils.stringparse.IServerMessageParseUtils; + +/** + * + * Title: class + * + * Description: The Class DSResultSetGridDataProvider. + * + * @since 3.0.0 + */ +public class DSResultSetGridDataProvider + implements IDSGridDataProvider, IDSGridDataAccessListenable, IDSResultRowVisitor { + + /** + * The query result. + */ + protected IQueryResult queryResult; + + private IResultConfig config; + + /** + * The summary. + */ + protected IQueryExecutionSummary summary; + + private IDSGridColumnProvider columnDataProvider; + + private List rows; + + private boolean isEndOfRecordsReached; + + /** + * The event table. + */ + protected DSEventTable eventTable; + + private boolean isResultTabDirty = false; + + private Database db; + + private String encoding = null; + + private boolean isIncludeEncoding = false; + + private boolean isEncodingChanged = false; + + private boolean editSupported = true; + + private boolean olapCursorExec = false; + + private boolean isFuncProcExport = false; + + /** + * Instantiates a new DS result set grid data provider. + * + * @param result the result + * @param rsConfig the rs config + * @param summary the summary + */ + public DSResultSetGridDataProvider(IQueryResult result, IResultConfig rsConfig, IQueryExecutionSummary summary) { + this.queryResult = result; + this.config = rsConfig; + this.summary = summary; + this.rows = new ArrayList(5); + this.eventTable = new DSEventTable(); + } + + /** + * Inits the. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + @Override + public void init() throws DatabaseOperationException, DatabaseCriticalException { + DSResultSetGridColumnDataProvider colData = new DSResultSetGridColumnDataProvider(); + colData.init(queryResult); + this.columnDataProvider = colData; + getNextBatch(); + } + + /** + * Inits the. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws SQLException + */ + @Override + public void init(IQueryResult iQueryResult, ArrayList debugInputValueList, boolean isCallableStmt) + throws DatabaseOperationException, DatabaseCriticalException, SQLException { + DSResultSetGridColumnDataProvider colData = new DSResultSetGridColumnDataProvider(); + boolean isSingleFuncProcExecution = getSingleFuncProcExecution(iQueryResult); + if (debugInputValueList != null || isSingleFuncProcExecution) { + colData.initColHeaderName(null, isCallableStmt, iQueryResult); + } else { + colData.init(queryResult); + } + this.columnDataProvider = colData; + if (isSingleFuncProcExecution || debugInputValueList != null) { + getNextBatch(debugInputValueList); + if (debugInputValueList != null) { + setFuncProcExport(true); + } + + } else { + getNextBatch(); + } + + } + + /** + * gets boolean isFuncProcExport + * + * @return isFuncProcExport the isFuncProcExport flag + */ + public boolean isFuncProcExport() { + return isFuncProcExport; + } + + /** + * sets boolean isFuncProcExport + * + * @param isFuncProcExport the isFuncProcExport + */ + public void setFuncProcExport(boolean isFuncProcExport) { + this.isFuncProcExport = isFuncProcExport; + } + + private boolean getSingleFuncProcExecution(IQueryResult iQueryResult) throws DatabaseOperationException { + StmtExecutor stmtExecutor = iQueryResult.getStmtExecutor(); + String queryWithoutCommnent = null; + if (stmtExecutor != null) { + queryWithoutCommnent = IServerMessageParseUtils.extractQueryWithoutComments(stmtExecutor.getQuery()); + if (queryWithoutCommnent.startsWith("EXEC") || queryWithoutCommnent.startsWith("exec") + || queryWithoutCommnent.startsWith("CALL") || queryWithoutCommnent.startsWith("call")) { + return true; + } + } + return false; + } + + /** + * Inits the by visitor. + * + * @return the IDS result row visitor + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public IDSResultRowVisitor initByVisitor(boolean isfuncProcResultFlow) + throws DatabaseOperationException, DatabaseCriticalException { + DSResultSetGridColumnDataProvider colData = new DSResultSetGridColumnDataProvider(); + if (isfuncProcResultFlow) { + colData.initByVisitorColHeaderName(null, false, queryResult); + } else { + colData.init(queryResult); + } + + this.columnDataProvider = colData; + + return this; + } + + /** + * Update data to rows. + * + * @param values the values + */ + protected void updateDataToRows(Object[][] values) { + for (int rowIndex = 0; rowIndex < values.length; rowIndex++) { + this.rows.add(createRowFromValues(values[rowIndex])); + } + + summary.setNumRecordsFetched(this.rows.size()); + } + + /** + * Close. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + @Override + public void close() throws DatabaseOperationException, DatabaseCriticalException { + this.queryResult.closeStament(); + } + + /** + * Pre destroy. + */ + @Override + public void preDestroy() { + if (eventTable != null) { + this.eventTable.unhookall(); + } + if (queryResult != null) { + this.queryResult.closeStament(); + this.queryResult = null; + } + this.rows = new ArrayList(5); + this.config = null; + this.columnDataProvider = null; + this.summary = null; + this.eventTable = null; + } + + /** + * Gets the next batch. + * + * @return the next batch + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + @Override + public List getNextBatch() throws DatabaseOperationException, DatabaseCriticalException { + /* refetch cleanup? */ + ResultSetDatatypeMapping.setIncludeEncoding(isIncludeEncoding); + Object[][] values = this.queryResult.getNextObjectRecordBatch(this.config.getFetchCount()); + updateDataToRows(values); + actionAfterNextBatch(); + return rows; + } + + /** + * Gets the next batch. + * + * @return the next batch + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws SQLException + */ + @Override + public List getNextBatch(ArrayList debugInputValueList) + throws DatabaseOperationException, DatabaseCriticalException, SQLException { + /* refetch cleanup? */ + ResultSetDatatypeMapping.setIncludeEncoding(isIncludeEncoding); + Object[][] inputValues = null; + int regOutParaIndex = 0; + int size = 0; + ArrayList rowsList = new ArrayList<>(); + if (debugInputValueList != null) { + size = debugInputValueList.size(); + } + for (int i = 0; i < size; i++) { + if (MPPDBIDEConstants.OUT.equals(debugInputValueList.get(i).getDefaultParameterMode().name())) { + regOutParaIndex++; + rowsList.add(getInputRowValues(debugInputValueList.get(i), regOutParaIndex, i + 1)); + } else { + rowsList.add(getInputRowValues(debugInputValueList.get(i), 0, i + 1)); + } + } + + inputValues = rowsList.toArray(new Object[rowsList.size()][this.columnDataProvider.getColumnCount()]); + updateDataToRows(inputValues); + + int columnCount = this.columnDataProvider.getColumnCount(); + if (queryResult.getResultsSet() != null) { + Object[][] values = this.queryResult.getNextObjectRecordBatch(this.config.getFetchCount(), columnCount, + debugInputValueList != null, true); + updateDataToRows(values); + } + actionAfterNextBatch(); + return rows; + } + + private void actionAfterNextBatch() throws DatabaseOperationException, DatabaseCriticalException { + eventTable.sendEvent(new DSEvent(LISTEN_TYPE_POST_FETCH, summary)); + + this.isEndOfRecordsReached = this.queryResult.isEndOfRecordsReached(); + + if (this.isEndOfRecordsReached) { + eventTable.sendEvent(new DSEvent(LISTEN_TYPE_ENDOF_RS, summary)); + } + + /* Commit & close not possible? */ + switch (this.config.getActionAfterFetch()) { + case ISSUE_ROLLBACK_CONNECTION_AFTER_FETCH: { + this.queryResult.rollback(); + break; + } + case ISSUE_COMMIT_CONNECTION_AFTER_FETCH: { + this.queryResult.commitConnection(); + break; + } + case CLOSE_CONNECTION_AFTER_FETCH: { + this.close(); + break; + } + default: { + break; + } + } + } + + /** + * Gets the all fetched rows. + * + * @return the all fetched rows + */ + @Override + public List getAllFetchedRows() { + return rows; + } + + /** + * Checks if is end of records. + * + * @return true, if is end of records + */ + @Override + public boolean isEndOfRecords() { + return this.isEndOfRecordsReached; + } + + /** + * Gets the record count. + * + * @return the record count + */ + @Override + public int getRecordCount() { + return rows.size(); + } + + /** + * Adds the listener. + * + * @param type the type + * @param listener the listener + */ + @Override + public void addListener(int type, IDSListener listener) { + eventTable.hook(type, listener); + } + + /** + * Removes the listener. + * + * @param type the type + * @param listener the listener + */ + @Override + public void removeListener(int type, IDSListener listener) { + if (eventTable != null) { + eventTable.unhook(type, listener); + } + } + + /** + * Gets the column data provider. + * + * @return the column data provider + */ + @Override + public IDSGridColumnProvider getColumnDataProvider() { + return this.columnDataProvider; + } + + /** + * Gets the summary. + * + * @return the summary + */ + public IQueryExecutionSummary getSummary() { + return summary; + } + + /** + * Gets the data provider config. + * + * @return the data provider config + */ + public IResultConfig getDataProviderConfig() { + return config; + } + + /** + * Gets the query results. + * + * @return the query results + */ + public IQueryResult getQueryResults() { + return this.queryResult; + } + + /** + * Gets the column group provider. + * + * @return the column group provider + */ + @Override + public IDSGridColumnGroupProvider getColumnGroupProvider() { + return null; + } + + /** + * Gets the table. + * + * @return the table + */ + @Override + public ServerObject getTable() { + return null; + } + + /** + * Gets the result tab dirty flag. + * + * @return the result tab dirty flag + */ + @Override + public boolean getResultTabDirtyFlag() { + return this.isResultTabDirty; + } + + /** + * Sets the result tab dirty flag. + * + * @param flag the new result tab dirty flag + */ + @Override + public void setResultTabDirtyFlag(boolean flag) { + this.isResultTabDirty = flag; + } + + /** + * Gets the databse. + * + * @return the databse + */ + @Override + public Database getDatabse() { + + return this.db; + } + + /** + * Sets the database. + * + * @param database the new database + */ + public void setDatabase(Database database) { + this.db = database; + } + + /** + * Gets the encoding. + * + * @return the encoding + */ + public String getEncoding() { + return this.encoding; + } + + /** + * Change encoding. + * + * @param newEncoding the new encoding + */ + public void changeEncoding(String newEncoding) { + this.encoding = newEncoding.trim(); + if (!this.encoding.trim().equals(BLPreferenceManager.getInstance().getBLPreference().getDSEncoding().trim())) { + setEncodingChanged(true); + } else { + setEncodingChanged(false); + } + + setEncodingForRow(rows, newEncoding.trim()); + } + + /** + * Sets the encoding for row. + * + * @param rows2 the rows 2 + * @param newEncoding the new encoding + */ + protected void setEncodingForRow(List rows2, String newEncoding) { + for (IDSGridDataRow row : rows2) { + if (row instanceof DSResultSetGridDataRow) { + // Checking instance for one record is sufficient, but static + // tools may not think so. + DSResultSetGridDataRow rsRow = (DSResultSetGridDataRow) row; + rsRow.setEncoding(newEncoding); + } + } + } + + /** + * Checks if is include encoding. + * + * @return true, if is include encoding + */ + public boolean isIncludeEncoding() { + return isIncludeEncoding; + } + + /** + * Sets the include encoding. + * + * @param isEncodingIncluded the new include encoding + */ + public void setIncludeEncoding(boolean isEncodingIncluded) { + this.isIncludeEncoding = isEncodingIncluded; + ResultSetDatatypeMapping.setIncludeEncoding(isEncodingIncluded); + setIncludeEncodingForRow(rows); + } + + /** + * Sets the include encoding for row. + * + * @param rows2 the new include encoding for row + */ + protected void setIncludeEncodingForRow(List rows2) { + for (IDSGridDataRow row : rows2) { + if (row instanceof DSResultSetGridDataRow) { + // Checking instance for one record is sufficient, but static + // tools may not think so. + DSResultSetGridDataRow rsRow = (DSResultSetGridDataRow) row; + rsRow.setIncludeEncoding(isIncludeEncoding()); + } + } + } + + /** + * Checks if is encoding changed. + * + * @return true, if is encoding changed + */ + public boolean isEncodingChanged() { + return isEncodingChanged; + } + + /** + * Sets the encoding changed. + * + * @param isDSEncodingChanged the new encoding changed + */ + public void setEncodingChanged(boolean isDSEncodingChanged) { + this.isEncodingChanged = isDSEncodingChanged; + } + + /** + * Visit. + * + * @param rs the rs + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws SQLException + */ + @Override + public void visit(ResultSet rs) throws DatabaseOperationException, DatabaseCriticalException, SQLException { + if (null == this.columnDataProvider) { + DSResultSetGridColumnDataProvider colData = new DSResultSetGridColumnDataProvider(); + colData.init(queryResult); + this.columnDataProvider = colData; + } + + Object[] rowValues = null; + rowValues = getRowValues(rs); + IDSGridDataRow row = createRowFromValues(rowValues); + this.rows.add(row); + summary.setNumRecordsFetched(this.rows.size()); + } + + /** + * Visit. + * + * @param rs the rs + * @param isfuncProcResultFlow the function proc flow + * @param isPopupCursorType the popup cursor type + * @param valueList the list of input values + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws SQLException + */ + @Override + public void visit(ResultSet rs, boolean isfuncProcResultFlow, boolean isPopupCursorType, Object[] valueList) + throws DatabaseOperationException, DatabaseCriticalException, SQLException { + if (null == this.columnDataProvider) { + DSResultSetGridColumnDataProvider colData = new DSResultSetGridColumnDataProvider(); + colData.init(queryResult); + this.columnDataProvider = colData; + } + + Object[] rowValues = null; + rowValues = getFuncProcRowValues(rs); + IDSGridDataRow row = createRowFromValues(rowValues); + this.rows.add(row); + if (!isPopupCursorType) { + summary.setNumRecordsFetched(this.rows.size()); + + } + } + + private Object[] getFuncProcRowValues(ResultSet rs) + throws SQLException, NumberFormatException, DatabaseOperationException { + boolean isShowCursorPopup = getShowCursorPopup(rs); + int columnCount = this.columnDataProvider.getColumnCount(); + Object[] row = new Object[columnCount]; + int colIndex; + for (colIndex = 1; colIndex < columnCount; colIndex++) { + row[colIndex - 1] = ResultSetDatatypeMapping.getFuncProcColObjectExceptValue(rs, colIndex, false); + } + if (isShowCursorPopup) { + row[colIndex - 1] = ResultSetDatatypeMapping.getReadColumnValueObject(rs, + rs.getMetaData().getColumnCount()); + List cursorGridrow = new ArrayList(); + List> cursorRowValues = (List>) row[colIndex - 1]; + Object[] rowValues = null; + IDSGridDataRow cursorRow = null; + int size = 0; + if (cursorRowValues != null) { + size = cursorRowValues.size(); + } + for (int i = 0; i < size; i++) { + rowValues = convertCursorValueToObject(cursorRowValues.get(i)); + cursorRow = createRowFromValues(rowValues); + cursorGridrow.add(cursorRow); + } + row[columnCount - 1] = cursorGridrow; + this.olapCursorExec = true; + + } else { + row[colIndex - 1] = ResultSetDatatypeMapping.getReadColumnValueObject(rs, + rs.getMetaData().getColumnCount()); + } + return row; + } + + /** + * Visit the input values + * + * @param dp the default parameter + * @param index the index + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws SQLException + */ + public void visitInputValues(DefaultParameter dp, int index) + throws DatabaseOperationException, DatabaseCriticalException { + + Object[] rowValues = null; + try { + rowValues = getInputRowValues(dp, 0, index); + } catch (SQLException exe) { + GaussUtils.handleCriticalException(exe); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exe); + } + IDSGridDataRow row = createRowFromValues(rowValues); + this.rows.add(row); + summary.setNumRecordsFetched(this.rows.size()); + } + + /** + * Visit the unNamed cursor values + * + * @param rs the result set + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + @Override + public void visitUnNameCursor(ResultSet rs) + throws DatabaseOperationException, DatabaseCriticalException, SQLException { + if (null == this.columnDataProvider) { + DSResultSetGridColumnDataProvider colData = new DSResultSetGridColumnDataProvider(); + colData.init(queryResult); + this.columnDataProvider = colData; + } + + Object[] rowValues = null; + rowValues = getUnnamedCursorRowValues(rs); + IDSGridDataRow row = createRowFromValues(rowValues); + this.rows.add(row); + } + + private Object[] getUnnamedCursorRowValues(ResultSet rs) throws SQLException, DatabaseCriticalException { + try { + int columnCount = this.columnDataProvider.getColumnCount(); + Object[] row = new Object[columnCount]; + for (int i = 1; i <= columnCount; i++) { + row[i - 1] = ResultSetDatatypeMapping.resultSetDataTypeMapDefaultAction(rs, i); + } + return row; + } catch (OutOfMemoryError exe) { + throw new DatabaseCriticalException(IMessagesConstants.ERR_MSG_OUT_OF_MEMORY_ERROR_OCCURRED, exe); + } + } + + /** + * Creates the row from values. + * + * @param rowValues the row values + * @return the IDS grid data row + */ + protected IDSGridDataRow createRowFromValues(Object[] rowValues) { + DSResultSetGridDataRow row = new DSResultSetGridDataRow(this); + createCursorRowFromValues(rowValues); + row.setValues(rowValues); + row.setIncludeEncoding(isIncludeEncoding()); + return row; + } + + private void createCursorRowFromValues(Object[] rowValues) { + List> cursorRowValues = null; + if (!this.olapCursorExec && rowValues.length >= 4 && rowValues[3] instanceof List) { + List cursorGridrow = new ArrayList(); + cursorRowValues = (List>) rowValues[3]; + IDSGridDataRow cursorRow = null; + Object[] cursorRowObject = null; + for (int i = 0; i < cursorRowValues.size(); i++) { + cursorRowObject = convertCursorValueToObject(cursorRowValues.get(i)); + cursorRow = handleCursorRowFromValues(cursorRowObject); + cursorGridrow.add(cursorRow); + } + rowValues[3] = cursorGridrow; + } + } + + private IDSGridDataRow handleCursorRowFromValues(Object[] rowValues) { + DSResultSetGridDataRow row = new DSResultSetGridDataRow(this); + row.setValues(rowValues); + row.setIncludeEncoding(isIncludeEncoding()); + return row; + } + + /** + * Gets the row values. + * + * @param rs the rs + * @return the row values + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + protected Object[] getRowValues(ResultSet rs) + throws DatabaseOperationException, DatabaseCriticalException, SQLException { + // Shouldn't be a static variable. Need to revisit this. + ResultSetDatatypeMapping.setIncludeEncoding(isIncludeEncoding); + try { + int columnCount = this.columnDataProvider.getColumnCount(); + Object[] row = new Object[columnCount]; + for (int i = 1; i <= columnCount; i++) { + row[i - 1] = ResultSetDatatypeMapping.getReadColumnValueObject(rs, i); + } + return row; + } catch (OutOfMemoryError exe) { + throw new DatabaseCriticalException(IMessagesConstants.ERR_MSG_OUT_OF_MEMORY_ERROR_OCCURRED, exe); + } + } + + private Object[] convertCursorValueToObject(List cursorRowValue) { + int columnCount = cursorRowValue.size(); + Object[] row = new Object[columnCount]; + for (int i = 0; i < columnCount; i++) { + row[i] = cursorRowValue.get(i); + } + return row; + } + + private boolean getShowCursorPopup(ResultSet rs) throws SQLException { + if (MPPDBIDEConstants.REF_CURSOR.equals(rs.getMetaData().getColumnTypeName(rs.getMetaData().getColumnCount())) + || MPPDBIDEConstants.RECORD + .equals(rs.getMetaData().getColumnTypeName(rs.getMetaData().getColumnCount()))) { + return true; + } + return false; + } + + /** + * gets the input row values + * + * @param dp the dp + * @param regOutParaIndex the regOutParaIndex + * @param index the index + * @return the input row values + * @throws DatabaseOperationException the DatabaseOperationException + * @throws DatabaseCriticalException the DatabaseCriticalException + * @throws SQLException the SQLException + */ + protected Object[] getInputRowValues(DefaultParameter dp, int regOutParaIndex, int index) + throws DatabaseOperationException, DatabaseCriticalException, SQLException { + // Shouldn't be a static variable. Need to revisit this. + ResultSetDatatypeMapping.setIncludeEncoding(isIncludeEncoding); + try { + int columnCount = this.columnDataProvider.getColumnCount(); + Object[] row = new Object[columnCount]; + for (int i = 1; i <= columnCount; i++) { + row[i - 1] = getReadInputColumnValueObject(dp, i, regOutParaIndex, index); + } + + return row; + } catch (OutOfMemoryError e) { + throw new DatabaseCriticalException(IMessagesConstants.ERR_MSG_OUT_OF_MEMORY_ERROR_OCCURRED, e); + } + } + + /** + * gets the input column value object + * + * @param dp the dp + * @param columnIndex the columnIndex + * @param regOutParaIndex the regOutParaIndex + * @param inParamIndex the inParamIndex + * @return the column value object + * @throws SQLException the SQLException + * @throws DatabaseOperationException the DatabaseOperationException + * @throws DatabaseCriticalException the DatabaseCriticalException + */ + public Object getReadInputColumnValueObject(DefaultParameter dp, int columnIndex, int regOutParaIndex, + int inParamIndex) throws DatabaseCriticalException, DatabaseOperationException, SQLException { + Object colValue = ""; + switch (columnIndex) { + case 1: { + colValue = getParameterName(dp, inParamIndex); + break; + } + case 2: { + colValue = dp.getDefaultParameterType(); + break; + } + case 3: { + colValue = dp.getDefaultParameterMode().name(); + break; + } + case 4: { + if (MPPDBIDEConstants.OUT.equals(dp.getDefaultParameterMode().name())) { + colValue = getOutParameterValue(dp, regOutParaIndex); + } else { + colValue = dp.getDefaultParameterValue(); + } + break; + } + default: { + break; + } + } + return colValue; + } + + /** + * gets the parameter name + * + * @param dp the dp + * @param inParamIndex the inParamIndex + * @return the parameter name + */ + private Object getParameterName(DefaultParameter dp, int inParamIndex) { + Object colValue = ""; + colValue = dp.getDefaultParameterName(); + if (colValue == null) { + return MPPDBIDEConstants.PARAM + inParamIndex; + } + return colValue; + } + + /** + * gets the value of Out parameter value + * + * @param dp the default parameter + * @param regOutParaIndex the index of registered out parameter + * @return the out parameter value + * @throws SQLException the SQLException + * @throws DatabaseOperationException the DatabaseOperationException + * @throws DatabaseCriticalException the DatabaseCriticalException + */ + private Object getOutParameterValue(DefaultParameter dp, int regOutParaIndex) + throws SQLException, DatabaseCriticalException, DatabaseOperationException { + String query = summary.getQuery(); + ArrayList outResultList = StmtExecutor.getOutResultList(); + boolean isCallableStmt = StmtExecutor.isCallableStmtExecuted(); + DBConnection conn = queryResult.getConnection(); + StmtExecutor stmt = null; + try { + if (conn != null) { + stmt = new StmtExecutor(query, conn); + stmt.execute(); + + ResultSet rs = stmt.getResultSet(); + if (rs != null && MPPDBIDEConstants.CURSOR.equals(dp.getDefaultParameterType())) { + return ResultSetDatatypeMapping.convertResultSetToObject(rs, rs.getMetaData().getColumnCount(), + true, true); + } else { + if (regOutParaIndex > 0) { + return stmt.getCalStmt().getObject(regOutParaIndex); + } + + } + } else if (isCallableStmt) { + Object resObject = (Object) outResultList.get(regOutParaIndex - 1); + if (resObject instanceof ResultSet) { + return ResultSetDatatypeMapping.convertResultSetToObject((ResultSet) resObject, + ((ResultSet) resObject).getMetaData().getColumnCount(), true, true); + } else { + return outResultList.get(regOutParaIndex - 1); + } + } + } finally { + if (null != stmt) { + stmt.closeResultSet(); + stmt.closeStatement(); + } + } + + return ""; + } + + /** + * Sets the end of records. + */ + @Override + public void setEndOfRecords() { + eventTable.sendEvent(new DSEvent(LISTEN_TYPE_POST_FETCH, summary)); + this.isEndOfRecordsReached = true; + eventTable.sendEvent(new DSEvent(LISTEN_TYPE_ENDOF_RS, summary)); + } + + /** + * Checks if is edits the supported. + * + * @return true, if is edits the supported + */ + public boolean isEditSupported() { + return editSupported; + } + + /** + * Sets the edits the supported. + * + * @param isEditSupported the new edits the supported + */ + public void setEditSupported(boolean isEditSupported) { + this.editSupported = isEditSupported; + } + + /** + * Adds the default to col data provider. + * + * @param rows the rows + */ + public void addDefaultToColDataProvider(Map rows) { + ((DSResultSetGridColumnDataProvider) this.columnDataProvider).addDefaultValues(rows); + } + + @Override + public void visit(DSResultSetGridDataRow gridDataRow) + throws DatabaseOperationException, DatabaseCriticalException, SQLException { + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSResultSetGridDataRow.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSResultSetGridDataRow.java new file mode 100644 index 0000000000000000000000000000000000000000..a4d912af5809f3f5d6edfe6cec40f12aba6387aa --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/DSResultSetGridDataRow.java @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.edittabledata; + +import java.io.UnsupportedEncodingException; +import java.nio.charset.Charset; + +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class DSResultSetGridDataRow. + * + * @since 3.0.0 + */ +public class DSResultSetGridDataRow implements IDSGridDataRow { + + /** The values. */ + protected Object[] values; + protected Object[] originalValues; + private String encoding; + private boolean isIncludeEncoding; + private DSResultSetGridDataProvider dsResultSetGridDataProvider; + + /** + * Instantiates a new DS result set grid data row. + */ + public DSResultSetGridDataRow(DSResultSetGridDataProvider dsResultSetGridDataProvider) { + this.encoding = null; + this.dsResultSetGridDataProvider = dsResultSetGridDataProvider; + } + + /** + * Sets the originalValues. + * + * @param rowValues the new values + */ + public void setOriginalValues(Object[] rowValues) { + this.originalValues = rowValues; + } + + /** + * Sets the values. + * + * @param rowValues the new values + */ + public void setValues(Object[] rowValues) { + this.values = rowValues; + } + + @Override + public Object[] getValues() { + return values; + } + + @Override + public Object getValue(int columnIndex) { + if (values != null && columnIndex >= 0 && columnIndex < values.length) { + if (isIncludeEncoding() && !isUnstructuredDatatype(columnIndex)) { + return getEncodedValue(values[columnIndex]); + } + return values[columnIndex]; + } else { + return ""; + } + + } + + public Object[] getOriginalValues() { + return originalValues; + } + + public Object getOriginalValue(int columnIndex) { + if (originalValues != null && columnIndex >= 0 && columnIndex < originalValues.length) { + if (isIncludeEncoding() && !isUnstructuredDatatype(columnIndex)) { + return getEncodedValue(originalValues[columnIndex]); + } + return originalValues[columnIndex]; + } else { + return ""; + } + } + + /** + * Gets all original values. + * + * @return the original array. + */ + public Object[] getAllOriginal() { + return originalValues; + } + + /** + * Gets the encoded value. + * + * @param value the value + * @return the encoded value + */ + protected Object getEncodedValue(Object value) { + if (value instanceof byte[]) { + byte[] byteVal = (byte[]) value; + + try { + if (null != getEncoding() && !getEncoding().isEmpty()) { + + return new String(byteVal, getEncoding()); + + } + + return new String(byteVal, Charset.defaultCharset().name()); + } catch (UnsupportedEncodingException e) { + // Ignore. nothing can be done here. + MPPDBIDELoggerUtility.debug("Encoding failed"); + } + } + + return value; + } + + @Override + public Object[] getClonedValues() { + return getValues().clone(); + } + + /** + * Gets the encoding. + * + * @return the encoding + */ + public String getEncoding() { + return encoding; + } + + /** + * Sets the encoding. + * + * @param encoding the new encoding + */ + public void setEncoding(String encoding) { + this.encoding = encoding; + } + + /** + * Checks if is include encoding. + * + * @return true, if is include encoding + */ + public boolean isIncludeEncoding() { + return isIncludeEncoding; + } + + /** + * Checks if is blob. + * + * @param columnIndex the column index + * @return true, if is blob + */ + public boolean isBlob(int columnIndex) { + return MPPDBIDEConstants.BLOB + .equals(dsResultSetGridDataProvider.getColumnDataProvider().getColumnDataTypeName(columnIndex)); + } + + /** + * Checks if is byte A. + * + * @param columnIndex the column index + * @return true, if is byte A + */ + public boolean isByteA(int columnIndex) { + return MPPDBIDEConstants.BYTEA + .equals(dsResultSetGridDataProvider.getColumnDataProvider().getColumnDataTypeName(columnIndex)); + } + + /** + * Checks if is unstructured datatype. + * + * @param columnIndex the column index + * @return true, if is unstructured datatype + */ + public boolean isUnstructuredDatatype(int columnIndex) { + return isBlob(columnIndex) || isByteA(columnIndex); + } + + /** + * Sets the include encoding. + * + * @param isIncludeDSEncoding the new include encoding + */ + public void setIncludeEncoding(boolean isIncludeDSEncoding) { + this.isIncludeEncoding = isIncludeDSEncoding; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/EditTableCellState.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/EditTableCellState.java new file mode 100644 index 0000000000000000000000000000000000000000..b172daf2eccb95679bdd812f007ac40d085fa73f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/EditTableCellState.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.edittabledata; + +/** + * + * Title: enum + * + * Description: The Enum EditTableCellState. + * + * @since 3.0.0 + */ +public enum EditTableCellState { + // modified state is set for a cell when it has been modified commit it is + // failed MODIFIED_FAILED is set for a cell after the commit is performed. + // label accumulator MODIFIED State to make the cell green and + // MODIFIED_FAILED is used for the make it red + MODIFIED, MODIFIED_FAILED +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/EditTableExecuteQuery.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/EditTableExecuteQuery.java new file mode 100644 index 0000000000000000000000000000000000000000..f0b9de3aa956a24da3e385fcee4f4aadee4f8ed0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/EditTableExecuteQuery.java @@ -0,0 +1,310 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.edittabledata; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ITableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class EditTableExecuteQuery. + * + * @since 3.0.0 + */ +public class EditTableExecuteQuery implements EditTableExecuteQueryUtility { + + /** + * Execute insert row command. + * + * @param insertedRow the inserted row + * @param insertedRowBuffer the inserted row buffer + * @param dsEditTableDataGridDataProvider the ds edit table data grid data + * provider + * @param table the table + * @param conn the conn + * @param tableName the table name + * @param isSupportReturning the is support returning + * @param isAtomic the is atomic + * @return true, if successful + * @throws MPPDBIDEException the MPPDBIDE exception + */ + @Override + public boolean executeInsertRowCommand(IDSGridEditDataRow insertedRow, IDSGridEditDataRow insertedRowBuffer, + DSEditTableDataGridDataProvider dsEditTableDataGridDataProvider, ITableMetaData table, DBConnection conn, + String[] tableName, boolean isSupportReturning, boolean isAtomic) throws MPPDBIDEException { + boolean executeStatus = true; + int noOfColumns = insertedRow.getValues().length; + List values = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + for (int colIndex = 0; colIndex < noOfColumns; ++colIndex) { + values.add(insertedRow.getValue(colIndex)); + } + List editValues = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + + String query = null; + if (table == null) { + query = IEditTableExecuteQuery.generateInsertQueryForEditQueryResults(dsEditTableDataGridDataProvider, + values, tableName, editValues, conn, isSupportReturning); + } else if (table instanceof TableMetaData) { + query = generateInsertQuery(dsEditTableDataGridDataProvider, values, (TableMetaData) table, editValues, + conn, isSupportReturning); + } + + PreparedStatement stmt = null; + int editValueCount = editValues.size(); + try { + Object value = null; + stmt = conn.getConnection().prepareStatement(query); + + for (int index = 0; index < editValueCount; index++) { + value = editValues.get(index); + if (!IEditTableExecuteQuery.isNonPlaceholderType(value)) { + stmt.setObject(index + 1, value); + } + } + + boolean result = stmt.execute(); + if (result || stmt.getUpdateCount() > 0) { + insertedRow.setExecutionStatus(EditTableRecordExecutionStatus.SUCCESS); + getResultValuesFromResultSet(insertedRowBuffer, dsEditTableDataGridDataProvider, noOfColumns, stmt); + } else { + insertedRow.setExecutionStatus(EditTableRecordExecutionStatus.FAILED); + + insertedRow.setCommitStatusMessage( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_QUERY_EXECUTION_FAILED)); + } + } catch (SQLException exception) { + insertedRow.setExecutionStatus(EditTableRecordExecutionStatus.FAILED); + insertedRow.setCommitStatusMessage(IEditTableExecuteQuery.generateCommitFailureMessage(conn, exception)); + executeStatus = false; + IEditTableExecuteQuery.handleSQLException(conn, exception, insertedRow); + } finally { + IEditTableExecuteQuery.closeStatement(stmt); + } + + return executeStatus; + } + + /** + * Generate insert query. + * + * @param dsEditTableDataGridDataProvider the ds edit table data grid data + * provider + * @param values the values + * @param table the table + * @param editValues the edit values + * @param conn the conn + * @param isSupportReturning the is support returning + * @return the string + * @throws MPPDBIDEException the MPPDBIDE exception + */ + private static String generateInsertQuery(DSEditTableDataGridDataProvider dsEditTableDataGridDataProvider, + List values, TableMetaData table, List editValues, DBConnection conn, + boolean isSupportReturning) throws MPPDBIDEException { + + boolean useDefaultVal = false; + boolean defaultValUsed = false; + StringBuilder query = new StringBuilder("INSERT into "); + StringBuilder queryPlaceHolder = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + int valueCount = values.size(); + Object value = null; + Object col = null; + List distributedCols = table.getDistributionColumnList(); + List colMetData = table.getColumnMetaDataList(); + query.append(table.getDisplayName()); + query.append(" ("); + for (int index = 0; index < valueCount; index++) { + value = values.get(index); + col = colMetData.get(index); + useDefaultVal = false; + + if (null == value) { + useDefaultVal = colMetData.get(index).getHasDefVal(); + if (useDefaultVal) { + value = colMetData.get(index).getDefaultValue(); + defaultValUsed = true; + } + } + if (null == value) { + editValues.add(null); + query.append(table.getQualifiedObjectName(((ColumnMetaData) col).getName())); + query.append(", "); + IEditTableExecuteQuery.filterPlaceHolderQuery(values.get(index), queryPlaceHolder); + queryPlaceHolder.append(", "); + } else { + generateQuerywhenValueisNotNull(dsEditTableDataGridDataProvider, values, table, editValues, + useDefaultVal, query, queryPlaceHolder, value, col, index, conn); + } + } + + IEditTableExecuteQuery.removeExtraCommas(editValues, distributedCols, defaultValUsed, query, queryPlaceHolder); + + query.append(") "); + query.append(" values ("); + query.append(queryPlaceHolder.toString()).append(")"); + + /* Generate query for getting values from server */ + if (isSupportReturning) { + query.append(" RETURNING *"); + } + return query.toString(); + } + + /** + * Gets the result values from result set. + * + * @param insertedRowBuffer the inserted row buffer + * @param dsEditTableDataGridDataProvider the ds edit table data grid data + * provider + * @param noOfColumns the no of columns + * @param stmt the stmt + * @return the result values from result set + * @throws SQLException the SQL exception + */ + private static void getResultValuesFromResultSet(IDSGridEditDataRow insertedRowBuffer, + DSEditTableDataGridDataProvider dsEditTableDataGridDataProvider, int noOfColumns, PreparedStatement stmt) + throws SQLException { + try (ResultSet rs = stmt.getResultSet()) { + int colIndex = 0; + IDSGridColumnProvider columnDataProvider = dsEditTableDataGridDataProvider.getColumnDataProvider(); + while (rs.next()) { + while (colIndex < noOfColumns) { + // if rs.getString() is used for the boolean/bit it + // will store it as 't' + insertedRowBuffer.setValue(colIndex, getDatatypeFromString(columnDataProvider, rs, colIndex)); + + colIndex++; + } + dsEditTableDataGridDataProvider.decrementUpdatedRowCount(); + } + } + } + + /** + * Generate querywhen valueis not null. + * + * @param dsEditTableDataGridDataProvider the ds edit table data grid data + * provider + * @param values the values + * @param table the table + * @param editValues the edit values + * @param useDefaultVal the use default val + * @param query the query + * @param queryPlaceHolder the query place holder + * @param value the value + * @param col the col + * @param idx the idx + */ + protected static void generateQuerywhenValueisNotNull( + DSEditTableDataGridDataProvider dsEditTableDataGridDataProvider, List values, TableMetaData table, + List editValues, boolean useDefaultVal, StringBuilder query, StringBuilder queryPlaceHolder, + Object value, Object col, int idx, DBConnection conn) { + if (null != value) { + + if (!useDefaultVal) { + value = IEditTableExecuteQuery.transformToSqlDatatypes( + dsEditTableDataGridDataProvider.getColumnDataProvider(), idx, value, conn.getConnection()); + if (!IEditTableExecuteQuery.isNonPlaceholderType(value)) { + editValues.add(value); + } + } + query.append(table.getQualifiedObjectName(((ColumnMetaData) col).getName())); + + query.append(", "); + + if (!useDefaultVal) { + IEditTableExecuteQuery.filterPlaceHolderQuery(values.get(idx), queryPlaceHolder); + } else { + queryPlaceHolder.append("default"); + } + queryPlaceHolder.append(", "); + + } + } + + /** + * Gets the datatype from string. + * + * @param columnDataProvider the column data provider + * @param rs the rs + * @param colIndex the col index + * @return the datatype from string + * @throws SQLException the SQL exception + */ + private static Object getDatatypeFromString(IDSGridColumnProvider columnDataProvider, ResultSet rs, int colIndex) + throws SQLException { + switch (columnDataProvider.getColumnDatatype(colIndex)) { + case Types.TINYINT: + case Types.SMALLINT: + case Types.INTEGER: + case Types.BIGINT: + case Types.FLOAT: + case Types.REAL: + case Types.DOUBLE: { + if (IEditTableExecuteQuery.isMoneyDataType(columnDataProvider.getColumnDataTypeName(colIndex))) { + return rs.getString(colIndex + 1); + } else { + return rs.getObject(colIndex + 1); + } + } + case Types.BOOLEAN: + case Types.BIT: { + if (columnDataProvider.getPrecision(colIndex) <= 1) { + return rs.getObject(colIndex + 1); + } else { + return rs.getString(colIndex + 1); + } + } + case Types.NUMERIC: { + return rs.getBigDecimal(colIndex + 1); + } + case Types.DATE: { + return rs.getDate(colIndex + 1); + } + case Types.TIME: + case Types.TIME_WITH_TIMEZONE: + case Types.TIMESTAMP: + case Types.TIMESTAMP_WITH_TIMEZONE: { + return rs.getTimestamp(colIndex + 1); + } + case Types.BINARY: { + if (MPPDBIDEConstants.BYTEA.equals(columnDataProvider.getColumnDataTypeName(colIndex))) { + return rs.getBytes(colIndex + 1); + } else { + return rs.getString(colIndex + 1); + } + } + default: { + return rs.getString(colIndex + 1); + } + } + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/EditTableExecuteQueryFactory.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/EditTableExecuteQueryFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..bdbfb7464c2758229d195d3ed82ddc2f70ba1b34 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/EditTableExecuteQueryFactory.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.edittabledata; + +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.DBTYPE; + +/** + * Title: EditTableExecuteQueryFactory + * + * Description:A factory for Edit Table Execute Query. + * + * @since 3.0.0 + */ + +public final class EditTableExecuteQueryFactory { + + private EditTableExecuteQueryFactory() { + + } + + /** + * Gets the edits the table data core. + * + * @param serverObject the server object + * @return the edits the table data core + */ + public static EditTableExecuteQueryUtility getEditTableExecuteQuery(DBTYPE dbType) { + switch (dbType) { + case OPENGAUSS: + default: { + return new EditTableExecuteQuery(); + } + + } + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/EditTableExecuteQueryUtility.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/EditTableExecuteQueryUtility.java new file mode 100644 index 0000000000000000000000000000000000000000..0236b7ea078cc3e7b24bdfd9b3dca56a3610bd47 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/EditTableExecuteQueryUtility.java @@ -0,0 +1,244 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.edittabledata; + +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.List; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.ITableMetaData; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.presentation.grid.IRowEffectedConfirmation; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class EditTableExecuteQueryUtility. + * + * @since 3.0.0 + */ +public interface EditTableExecuteQueryUtility { + + /** + * Execute insert row command. + * + * @param insertedRow the inserted row + * @param insertedRowBuffer the inserted row buffer + * @param dsEditTableDataGridDataProvider the ds edit table data grid data + * provider + * @param table the table + * @param conn the conn + * @param tableName the table name + * @param isSupportReturning the is support returning + * @param isAtomic the is atomic + * @return true, if successful + * @throws MPPDBIDEException the MPPDBIDE exception + */ + boolean executeInsertRowCommand(IDSGridEditDataRow insertedRow, IDSGridEditDataRow insertedRowBuffer, + DSEditTableDataGridDataProvider dsEditTableDataGridDataProvider, ITableMetaData table, DBConnection conn, + String[] tableName, boolean isSupportReturning, boolean isAtomic) throws MPPDBIDEException; + + /** + * Execute update row command. + * + * @param updatedRow the updated row + * @param tableName the table name + * @param dsEditTableDataGridDataProvider the ds edit table data grid data + * provider + * @param conn the conn + * @param uniqueKeys the unique keys + * @param columnProvider the column provider + * @param rowEffectedConfirm the row effected confirm + * @param isAtomic the is atomic + * @return true, if successful + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public default boolean executeUpdateRowCommand(IDSGridEditDataRow updatedRow, String[] tableName, + DSEditTableDataGridDataProvider dsEditTableDataGridDataProvider, DBConnection conn, List uniqueKeys, + IDSGridColumnProvider columnProvider, IRowEffectedConfirmation rowEffectedConfirm, boolean isAtomic) + throws MPPDBIDEException { + boolean executeStatus = true; + Object value = null; + int placeholderIdx = 0; + updatedRow.setUpdatedRecords(0); + final String query = IEditTableExecuteQuery.generateUpdateQuery(updatedRow, tableName, + dsEditTableDataGridDataProvider, uniqueKeys, columnProvider); + PreparedStatement stmt = null; + try { + stmt = conn.getConnection().prepareStatement(query); + placeholderIdx = addPlaceHolderForUpdatedColumns(updatedRow, columnProvider, placeholderIdx, stmt); + + int uniqueKeysSize = uniqueKeys.size(); + for (int index = 0; index < uniqueKeysSize; index++) { + String colName = uniqueKeys.get(index); + int columnIndex = columnProvider.getColumnIndex(colName); + value = updatedRow.getOriginalValue(columnIndex); + if (value != null && !IEditTableExecuteQuery.isNonPlaceholderType(value) + && IEditTableExecuteQuery.isDatatypeSupported(columnProvider.getColumnDataTypeName(columnIndex), + columnProvider.getPrecision(columnIndex))) { + placeholderIdx++; + IEditTableExecuteQuery.preparePlaceHolderStmt(columnProvider, value, placeholderIdx, stmt, index); + } + } + int result = stmt.executeUpdate(); + executeStatus = IEditTableExecuteQuery.updateStatusAndRecordsinRow(updatedRow, rowEffectedConfirm, + executeStatus, result); + } catch (SQLException exception) { + updatedRow.setExecutionStatus(EditTableRecordExecutionStatus.FAILED); + updatedRow.setCommitStatusMessage(IEditTableExecuteQuery.generateCommitFailureMessage(conn, exception)); + executeStatus = false; + IEditTableExecuteQuery.handleSQLException(conn, exception, updatedRow); + } finally { + IEditTableExecuteQuery.closeStatement(stmt); + } + return executeStatus; + } + + /** + * Gets the place holder for updated columns. + * + * @param updatedRow the updated row + * @param columnProvider the column provider + * @param placeholderIdx the placeholder idx + * @param stmt the stmt + * @return the place holder for updated columns + * @throws SQLException the SQL exception + */ + public default int addPlaceHolderForUpdatedColumns(IDSGridEditDataRow updatedRow, + IDSGridColumnProvider columnProvider, int placeholderIdx, PreparedStatement stmt) throws SQLException { + List modifiedColumns = updatedRow.getModifiedColumns(); + int clmnCount = 0; + int modifiedColumnsSize = (modifiedColumns != null) ? modifiedColumns.size() : 0; + + for (clmnCount = 0; clmnCount < modifiedColumnsSize; clmnCount++) { + int index = modifiedColumns.get(clmnCount); + Object value1 = updatedRow.getValue(index); + + if (!IEditTableExecuteQuery.isNonPlaceholderType(value1)) { + if (!IEditTableExecuteQuery.isMoneyDataType(columnProvider.getColumnDataTypeName(index))) { + placeholderIdx++; + IEditTableExecuteQuery.preparePlaceHolderStmt(columnProvider, value1, placeholderIdx, stmt, index); + } + } + } + return placeholderIdx; + } + + /** + * Execute delete row command. + * + * @param deletedRow the deleted row + * @param tableName the table name + * @param dsEditTableDataGridDataProvider the ds edit table data grid data + * provider + * @param conn the conn + * @param uniqueKeys the unique keys + * @param columnProvider the column provider + * @param rowEffectedConfirm the row effected confirm + * @param isAtomic the is atomic + * @return true, if successful + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public default boolean executeDeleteRowCommand(IDSGridEditDataRow deletedRow, String[] tableName, + DSEditTableDataGridDataProvider dsEditTableDataGridDataProvider, DBConnection conn, List uniqueKeys, + IDSGridColumnProvider columnProvider, IRowEffectedConfirmation rowEffectedConfirm, boolean isAtomic) + throws MPPDBIDEException { + boolean executeStatus = true; + deletedRow.setUpdatedRecords(0); + final String query = IEditTableExecuteQuery.generateDeleteQuery(deletedRow, tableName, + dsEditTableDataGridDataProvider, uniqueKeys, columnProvider); + PreparedStatement stmt = null; + try { + stmt = conn.getConnection().prepareStatement(query); + addPlaceHolderForDeletedClms(deletedRow, uniqueKeys, columnProvider, stmt, conn); + + int result = stmt.executeUpdate(); + if (result == 0) { + deletedRow.setExecutionStatus(EditTableRecordExecutionStatus.FAILED); + deletedRow.setUpdatedRecords(result); + deletedRow.setCommitStatusMessage( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_QUERY_EXECUTION_FAILED)); + + } else if (result > 1) { + IEditTableExecuteQuery.getUserConfirmationOnMultiRowOprt(rowEffectedConfirm); + deletedRow.setExecutionStatus(EditTableRecordExecutionStatus.SUCCESS); + deletedRow.setUpdatedRecords(result); + } else { + deletedRow.setUpdatedRecords(result); + deletedRow.setExecutionStatus(EditTableRecordExecutionStatus.SUCCESS); + } + } catch (SQLException exception) { + deletedRow.setExecutionStatus(EditTableRecordExecutionStatus.FAILED); + deletedRow.setCommitStatusMessage(generateCommitFailureMessage(conn, exception)); + executeStatus = false; + IEditTableExecuteQuery.handleSQLException(conn, exception, deletedRow); + } finally { + IEditTableExecuteQuery.closeStatement(stmt); + } + return executeStatus; + } + + /** + * Gets the place holder for deleted clms. + * + * @param deletedRow the deleted row + * @param uniqueKeys the unique keys + * @param columnProvider the column provider + * @param stmt the stmt + * @param conn the conn + * @return the place holder for deleted clms + * @throws SQLException the SQL exception + */ + public default void addPlaceHolderForDeletedClms(IDSGridEditDataRow deletedRow, List uniqueKeys, + IDSGridColumnProvider columnProvider, PreparedStatement stmt, DBConnection conn) throws SQLException { + Object value; + String colName; + int columnIndex; + int placeHolder = 0; + int uniqueKeysSize = uniqueKeys.size(); + for (int index = 0; index < uniqueKeysSize; index++) { + colName = uniqueKeys.get(index); + columnIndex = columnProvider.getColumnIndex(colName); + value = deletedRow.getOriginalValue(columnIndex); + if (null != value && !IEditTableExecuteQuery.isNonPlaceholderType(value) + && IEditTableExecuteQuery.isDatatypeSupported(columnProvider.getColumnDataTypeName(columnIndex), + columnProvider.getPrecision(columnIndex))) { + placeHolder++; + value = IEditTableExecuteQuery.transformToSqlDatatypes(columnProvider, index, value, + conn.getConnection()); + stmt.setObject(placeHolder, value); + } + } + } + + /** + * Generate commit failure message. + * + * @param conn the conn + * @param exception the e + * @return the string + */ + static String generateCommitFailureMessage(DBConnection conn, SQLException exception) { + String erromsgSplit = conn.extractErrorCodeAndErrorMsgFromServerError(exception); + + return erromsgSplit.trim(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/EditTableRecordExecutionStatus.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/EditTableRecordExecutionStatus.java new file mode 100644 index 0000000000000000000000000000000000000000..a023ffe032e78efe34ea8fbe453bda3387749365 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/EditTableRecordExecutionStatus.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.edittabledata; + +/** + * + * Title: enum + * + * Description: The Enum EditTableRecordExecutionStatus. + * + * @since 3.0.0 + */ +public enum EditTableRecordExecutionStatus { + // NOT_EXECUTED is set for a row when commit operation is not performed + // SUCCESS is set when a row is successfully commited + // FAILED is set when a commit for a row is failed + // FAILED_AND_MODIFIED is used is set for a row when the row was failed and + // again modified + + NOT_EXECUTED, SUCCESS, FAILED, FAILED_AND_MODIFIED, CONSUMED +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/EditTableRecordStates.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/EditTableRecordStates.java new file mode 100644 index 0000000000000000000000000000000000000000..7ba38822da6de2e42c1bcfd27823f2154186a0ed --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/EditTableRecordStates.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.edittabledata; + +/** + * + * Title: enum + * + * Description: The Enum EditTableRecordStates. + * + * @since 3.0.0 + */ +public enum EditTableRecordStates { + NOT_EDITED, INSERT, UPDATE, DELETE +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/IDSGridEditDataRow.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/IDSGridEditDataRow.java new file mode 100644 index 0000000000000000000000000000000000000000..d77dd637592d80dd66028e1027bd116bba3f97cf --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/IDSGridEditDataRow.java @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.edittabledata; + +import java.util.List; + +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; + +/** + * + * Title: interface + * + * Description: The Interface IDSGridEditDataRow. + * + * @since 3.0.0 + */ +public interface IDSGridEditDataRow extends IDSGridDataRow { + + /** + * Sets the value.for persisiting the record + * + * @param columnIndex the column index + * @param newValue the new value + */ + void setValue(int columnIndex, Object newValue); + + /** + * Creates the new row. + * + * @param value the value + */ + void createNewRow(Object[] value); + + /** + * Undo. + * + * @param columnIndex the column index + */ + void undo(int columnIndex); + + /** + * Gets the updated state. + * + * @return the updated state + */ + EditTableRecordStates getUpdatedState(); + + /** + * Gets the updated state. + * + * @param columnIndex the column index + * @return the updated state + */ + EditTableRecordStates getUpdatedState(int columnIndex); + + /** + * Clear all row updates. + */ + void clearAllRowUpdates(); + + /** + * Sets the execution status. + * + * @param status the new execution status + */ + void setExecutionStatus(EditTableRecordExecutionStatus status); + + /** + * Gets the execution status. + * + * @return the execution status + */ + EditTableRecordExecutionStatus getExecutionStatus(); + + /** + * Gets the original value. + * + * @param columnIndex the column index + * @return the original value + */ + Object getOriginalValue(int columnIndex); + + /** + * Gets the modified columns. + * + * @return the modified columns + */ + List getModifiedColumns(); + + /** + * Sets the state delete. + */ + void setStateDelete(); + + /** + * Gets the commit status message. + * + * @return the commit status message + */ + String getCommitStatusMessage(); + + /** + * Sets the commit status message. + * + * @param commitStatusMessage the new commit status message + */ + void setCommitStatusMessage(String commitStatusMessage); + + /** + * Gets the row index. + * + * @return the row index + */ + int getRowIndex(); + + /** + * Sets the row index. + * + * @param rowIndex the new row index + */ + void setRowIndex(int rowIndex); + + /** + * Gets the updated records. + * + * @return the updated records + */ + int getUpdatedRecords(); + + /** + * Sets the updated records. + * + * @param updatedRecords the new updated records + */ + void setUpdatedRecords(int updatedRecords); + + /** + * Sets the cell satus. + * + * @param cellState the cell state + * @param columnIndex the column index + */ + void setCellSatus(EditTableCellState cellState, int columnIndex); + + /** + * Gets the cell status. + * + * @param columnIndex the column index + * @return the cell status + */ + EditTableCellState getCellStatus(int columnIndex); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/IDSGridRowChangeHistory.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/IDSGridRowChangeHistory.java new file mode 100644 index 0000000000000000000000000000000000000000..60ec06c72a677277fad7d3fbd5621d0acb1d0117 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/IDSGridRowChangeHistory.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.edittabledata; + +/** + * + * Title: interface + * + * Description: The Interface IDSGridRowChangeHistory. + * + * @since 3.0.0 + */ +public interface IDSGridRowChangeHistory { + + /** + * Push. + * + * @param columnIndex the column index + * @param oldValue the old value + * @param newValue the new value + */ + void push(int columnIndex, Object oldValue, Object newValue); + + /** + * Pop. + * + * @param columnIndex the column index + * @param oldValue the old value + * @param newValue the new value + * @return the object + */ + Object pop(int columnIndex, Object oldValue, Object newValue); + + /** + * Clear. + */ + void clear(); + + /** + * Clear. + * + * @param columnIndex the column index + */ + void clear(int columnIndex); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/IEditTableExecuteQuery.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/IEditTableExecuteQuery.java new file mode 100644 index 0000000000000000000000000000000000000000..24d2d5afa58e73a1b6cdbeec6f42da4f0bb962d0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/IEditTableExecuteQuery.java @@ -0,0 +1,611 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.edittabledata; + +import java.sql.Blob; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.sql.Types; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.presentation.grid.IRowEffectedConfirmation; +import org.opengauss.mppdbide.presentation.util.DataTypeUtility; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: class Description: The Class EditTableExecuteQueryUtil. + * + * @since 3.0.0 + */ +public interface IEditTableExecuteQuery { + + /** + * Removes the extra commas. + * + * @param editValues the edit values + * @param distributedCols the distributed cols + * @param defaultValUsed the default val used + * @param query the query + * @param queryPlaceHolder the query place holder + */ + public static void removeExtraCommas(List editValues, List distributedCols, boolean defaultValUsed, + StringBuilder query, StringBuilder queryPlaceHolder) { + if (editValues.size() == 0 && !defaultValUsed && distributedCols.size() > 0) { + query.append(ServerObject.getQualifiedObjectName(distributedCols.get(0))); + editValues.add(null); + filterPlaceHolderQuery(null, queryPlaceHolder); + } else { + // Delete the last extra comma added to the query with space + query.delete(query.length() - 2, query.length()); + // Delete the last extra comma added to the query with space + queryPlaceHolder.delete(queryPlaceHolder.length() - 2, queryPlaceHolder.length()); + } + } + + /** + * Generate insert query for edit query results. + * + * @param dsEditTableDataGridDataProvider the ds edit table data grid data + * provider + * @param values the values + * @param tableName the table name + * @param editValues the edit values + * @param conn the conn + * @param isInsertReturningSupported the is insert returning supported + * @return the string + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public static String generateInsertQueryForEditQueryResults( + DSEditTableDataGridDataProvider dsEditTableDataGridDataProvider, List values, String[] tableName, + List editValues, DBConnection conn, boolean isInsertReturningSupported) throws MPPDBIDEException { + boolean isNoEdit = false; + StringBuilder query = new StringBuilder("INSERT into "); + StringBuilder queryPlaceHolder = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + if (dsEditTableDataGridDataProvider.getDatabse() == null) { + return ""; + } + query.append(dsEditTableDataGridDataProvider.getDatabse().getQualifiedObjectNameSplit(tableName)); + String[] columnList = dsEditTableDataGridDataProvider.getColumnDataProvider().getColumnNames(); + if (columnList == null) { + return null; + } + getInsertQueryValues(dsEditTableDataGridDataProvider, values, editValues, conn, query, queryPlaceHolder, + columnList); + + if (editValues.size() == 0) { + // Delete ( in the query with space + query.delete(query.length() - 2, query.length()); + isNoEdit = true; + queryPlaceHolder.append("default"); + } else { + // Delete the last extra comma added to the query with space + query.delete(query.length() - 2, query.length()); + // Delete the last extra comma added to the query with space + queryPlaceHolder.delete(queryPlaceHolder.length() - 2, queryPlaceHolder.length()); + } + + appendValues(isInsertReturningSupported, isNoEdit, query, queryPlaceHolder); + + return query.toString(); + } + + /** + * Append values. + * + * @param isInsertReturningSupported the is insert returning supported + * @param isNoEdit the is no edit + * @param query the query + * @param queryPlaceHolder the query place holder + */ + static void appendValues(boolean isInsertReturningSupported, boolean isNoEdit, StringBuilder query, + StringBuilder queryPlaceHolder) { + if (!isNoEdit) { + query.append(") "); + } + query.append(" values ("); + query.append(queryPlaceHolder.toString()).append(")"); + + if (isInsertReturningSupported) { + /* Generate query for getting values from server */ + query.append(" RETURNING *"); + } + } + + /** + * Gets the insert query values. + * + * @param dsEditTableDataGridDataProvider the ds edit table data grid data + * provider + * @param values the values + * @param editValues the edit values + * @param conn the conn + * @param query the query + * @param queryPlaceHolder the query place holder + * @param columnList the column list + * @return the insert query values + */ + static void getInsertQueryValues(DSEditTableDataGridDataProvider dsEditTableDataGridDataProvider, + List values, List editValues, DBConnection conn, StringBuilder query, + StringBuilder queryPlaceHolder, String[] columnList) { + query.append(" ("); + int valueCount = values.size(); + Object value = null; + String col = null; + for (int index = 0; index < valueCount; index++) { + value = values.get(index); + col = columnList[index]; + + if (null != value) { + value = transformToSqlDatatypes(dsEditTableDataGridDataProvider.getColumnDataProvider(), index, value, + conn.getConnection()); + if (!isNonPlaceholderType(value)) { + editValues.add(value); + } + query.append(dsEditTableDataGridDataProvider.getDatabse().getValidObjectName(col)); + query.append(", "); + + filterPlaceHolderQuery(values.get(index), queryPlaceHolder); + queryPlaceHolder.append(", "); + + } + } + } + + /** + * Append non place holder type. + * + * @param query the query + * @param value the value + */ + static void appendNonPlaceHolderType(StringBuilder query, Object value) { + if (value instanceof Boolean) { + Boolean boolVal = (Boolean) value; + query.append(boolVal ? "'1'" : "'0'"); + } + } + + /** + * Checks if is non placeholder type. + * + * @param value the value + * @return true, if is non placeholder type + */ + public static boolean isNonPlaceholderType(Object value) { + return value instanceof Boolean; + } + + /** + * Update status and recordsin row. + * + * @param updatedRow the updated row + * @param rowEffectedConfirm the row effected confirm + * @param executeStatus the execute status + * @param result the result + * @return true, if successful + * @throws SQLException the SQL exception + */ + public static boolean updateStatusAndRecordsinRow(IDSGridEditDataRow updatedRow, + IRowEffectedConfirmation rowEffectedConfirm, boolean executeStatus, int result) throws SQLException { + if (result == 0) { + updatedRow.setExecutionStatus(EditTableRecordExecutionStatus.FAILED); + updatedRow.setUpdatedRecords(result); + updatedRow.setCommitStatusMessage( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_QUERY_EXECUTION_FAILED)); + executeStatus = false; + } else if (result > 1) { + getUserConfirmationOnMultiRowOprt(rowEffectedConfirm); + updatedRow.setExecutionStatus(EditTableRecordExecutionStatus.SUCCESS); + updatedRow.setUpdatedRecords(result); + } else { + updatedRow.setExecutionStatus(EditTableRecordExecutionStatus.SUCCESS); + updatedRow.setUpdatedRecords(result); + } + return executeStatus; + } + + /** + * Prepare place holder stmt. + * + * @param columnProvider the column provider + * @param valueParam the value param + * @param placeholderIdx the placeholder idx + * @param stmt the stmt + * @param index the index + * @throws SQLException the SQL exception + */ + public static void preparePlaceHolderStmt(IDSGridColumnProvider columnProvider, Object valueParam, + int placeholderIdx, PreparedStatement stmt, int index) throws SQLException { + Object value = valueParam; + value = transformToSqlDatatypes(columnProvider, index, value, stmt.getConnection()); + stmt.setObject(placeholderIdx, value); + } + + /** + * Transform to sql datatypes. + * + * @param columnProvider the column provider + * @param index the index + * @param value the value + * @param con the con + * @return the object + */ + public static Object transformToSqlDatatypes(IDSGridColumnProvider columnProvider, int index, Object value, + Connection con) { + switch (columnProvider.getColumnDatatype(index)) { + case Types.TIMESTAMP: + case Types.TIMESTAMP_WITH_TIMEZONE: + case Types.TIME: + case Types.TIME_WITH_TIMEZONE: + return convertToTimestamp(value); + case Types.DOUBLE: + return convertToDouble(value); + case Types.BLOB: + return convertToBlob(con, value); + default: + return value; + } + } + + /** + * Convert to double. + * + * @param value the value + * @return the double + */ + static Double convertToDouble(Object value) { + if (value instanceof Double) { + return (Double) value; + } else if (value instanceof String) { + return Double.valueOf((String) value); + } + + return null; + } + + /** + * Convert to blob. + * + * @param con the con + * @param value the value + * @return the blob + */ + static Blob convertToBlob(Connection con, Object value) { + + if (null == value || !(value instanceof byte[])) { + return null; + } + + Blob createBlob = null; + try { + createBlob = con.createBlob(); + createBlob.setBytes(1, (byte[]) value); + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Failed to convert bytes to blob object", exception); + } + + return createBlob; + } + + /** + * Convert to timestamp. + * + * @param value the value + * @return the timestamp + */ + static Timestamp convertToTimestamp(Object value) { + if (value instanceof Timestamp) { + return (Timestamp) value; + } else if (value instanceof java.util.Date) { + return new Timestamp(((java.util.Date) value).getTime()); + } + + return null; + } + + /** + * Generate commit failure message. + * + * @param conn the conn + * @param exception the e + * @return the string + */ + public static String generateCommitFailureMessage(DBConnection conn, SQLException exception) { + String erromsgSplit = conn.extractErrorCodeAndErrorMsgFromServerError(exception); + + return erromsgSplit.trim(); + } + + /** + * Generate update query. + * + * @param updatedRow the updated row + * @param tableName the table name + * @param dsEditTableDataGridDataProvider the ds edit table data grid data + * provider + * @param uniqueKeys the unique keys + * @param columnProvider the column provider + * @return the string + */ + public static String generateUpdateQuery(IDSGridEditDataRow updatedRow, String[] tableName, + DSEditTableDataGridDataProvider dsEditTableDataGridDataProvider, List uniqueKeys, + IDSGridColumnProvider columnProvider) { + Object value = null; + StringBuilder strBldr = new StringBuilder("UPDATE "); + Database dataBase = dsEditTableDataGridDataProvider.getDatabse(); + if (dataBase == null) { + return ""; + } + strBldr.append(dataBase.getQualifiedObjectNameSplit(tableName)); + + strBldr.append(" SET "); + List modifiedColumns = updatedRow.getModifiedColumns(); + + for (Iterator iterator = modifiedColumns.iterator(); iterator.hasNext();) { + Integer colIndex = (Integer) iterator.next(); + String colName = columnProvider.getColumnName(colIndex); + if (colName != null) { + strBldr.append(dataBase.getValidObjectName(colName)); + strBldr.append("= "); + } + + filterPlaceHolderQuery(updatedRow.getValue(colIndex), strBldr); + + if (iterator.hasNext()) { + strBldr.append(", "); + } + } + + strBldr.append(" WHERE"); + + for (Iterator iterator = uniqueKeys.iterator(); iterator.hasNext();) { + String column = (String) iterator.next(); + int columnIndex = columnProvider.getColumnIndex(column); + value = updatedRow.getOriginalValue(columnIndex); + String columnDatatype = columnProvider.getColumnDataTypeName(columnIndex); + if (isComplexDataType(columnDatatype)) { + strBldr.append(' ' + dataBase.getValidObjectName(column) + "::text"); + } else { + strBldr.append(' ' + dataBase.getValidObjectName(column)); + } + if (null == value) { + strBldr.append(" is null"); + } else { + strBldr.append(" = "); + handleNonEditableDatatypeQuery(columnProvider, value, columnIndex, strBldr); + } + + if (iterator.hasNext()) { + strBldr.append(" AND"); + } + } + + return strBldr.toString(); + } + + /** + * Gets the user confirmation on multi row oprt. + * + * @param rowEffectedConfirm the row effected confirm + * @return the user confirmation on multi row oprt + * @throws SQLException the SQL exception + */ + public static void getUserConfirmationOnMultiRowOprt(IRowEffectedConfirmation rowEffectedConfirm) + throws SQLException { + rowEffectedConfirm.promptUerConfirmation(); + + } + + /** + * Generate delete query. + * + * @param deletedRow the deleted row + * @param tableName the table name + * @param dsEditTableDataGridDataProvider the ds edit table data grid data + * provider + * @param uniqueKeys the unique keys + * @param columnProvider the column provider + * @return the string + */ + public static String generateDeleteQuery(IDSGridEditDataRow deletedRow, String[] tableName, + DSEditTableDataGridDataProvider dsEditTableDataGridDataProvider, List uniqueKeys, + IDSGridColumnProvider columnProvider) { + Object value = null; + String column = null; + int columnIndex = 0; + StringBuilder queryBuilder = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + if (dsEditTableDataGridDataProvider.getDatabse() == null) { + return ""; + } + queryBuilder.append("DELETE FROM " + + dsEditTableDataGridDataProvider.getDatabse().getQualifiedObjectNameSplit(tableName) + " WHERE"); + + for (Iterator iterator = uniqueKeys.iterator(); iterator.hasNext();) { + column = (String) iterator.next(); + columnIndex = columnProvider.getColumnIndex(column); + value = deletedRow.getOriginalValue(columnIndex); + String columnDatatype = columnProvider.getColumnDataTypeName(columnIndex); + if (isComplexDataType(columnDatatype)) { + queryBuilder.append( + ' ' + dsEditTableDataGridDataProvider.getDatabse().getValidObjectName(column) + "::text"); + } else { + queryBuilder.append(' ' + dsEditTableDataGridDataProvider.getDatabse().getValidObjectName(column)); + } + + if (null == value) { + queryBuilder.append(" is null"); + } else { + queryBuilder.append(" = "); + handleNonEditableDatatypeQuery(columnProvider, value, columnIndex, queryBuilder); + } + + if (iterator.hasNext()) { + queryBuilder.append(" AND"); + } + } + + return queryBuilder.toString(); + + } + + /** + * Handle non editable datatype query. + * + * @param columnProvider the column provider + * @param value the value + * @param columnIndex the column index + * @param query the query + */ + static void handleNonEditableDatatypeQuery(IDSGridColumnProvider columnProvider, Object value, int columnIndex, + StringBuilder query) { + if (!isDatatypeSupported(columnProvider.getColumnDataTypeName(columnIndex), + columnProvider.getPrecision(columnIndex))) { + query.append(ServerObject.getLiteralName(value.toString())); + } else { + filterPlaceHolderQuery(value, query); + } + } + + /** + * Filter place holder query. + * + * @param value the value + * @param query the query + */ + public static void filterPlaceHolderQuery(Object value, StringBuilder query) { + if (isNonPlaceholderType(value)) { + appendNonPlaceHolderType(query, value); + } else { + query.append("?"); + } + } + + /** + * Close statement. + * + * @param stmt the stmt + */ + public static void closeStatement(PreparedStatement stmt) { + try { + if (stmt != null) { + stmt.close(); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("Statement close failed. ", exception); + } + } + + /** + * Checks if is datatype supported. + * + * @param sqlType the sql type + * @param precision the precision + * @return true, if is datatype supported + */ + public static boolean isDatatypeSupported(String sqlType, int precision) { + switch (sqlType.toLowerCase(Locale.ENGLISH)) { + case "bpchar": + case "char": + case "varchar": + case "text": + case "int4": + case "int2": + case "int8": + case "date": + case "numeric": + case "decimal": + case "float8": + case "time": + case "timetz": + case "timestamp": + case "timestamptz": + case "bool": + case "serial": + return true; + case "bit": + if (precision > 1) { + return false; + } + return true; + default: + return false; + } + } + + /** + * Handle SQL exception. + * + * @param con the con + * @param exception the exception + * @param row the row + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public static void handleSQLException(DBConnection con, SQLException exception, IDSGridEditDataRow row) + throws MPPDBIDEException { + GaussUtils.handleCriticalException(exception); + row.setCommitStatusMessage(generateCommitFailureMessage(con, exception)); + + /* + * Should not throw exception. To be analyzed. throw new + * DatabaseOperationException + */ + } + + /** + * Checks if is money data type. + * + * @param colDataType the col data type + * @return true, if is money data type + */ + public static boolean isMoneyDataType(String colDataType) { + return "money".equals(DataTypeUtility.convertToDisplayDatatype(colDataType)); + } + + /** + * Checks if is complex data type. + * + * @param colDataType the col data type + * @return true, if is complex data type + */ + static boolean isComplexDataType(String colDataType) { + switch (colDataType.toLowerCase(Locale.ENGLISH)) { + case "point": + case "polygon": + case "json": + case "circle": + case "path": + case "box": + case "lseg": + return true; + default: + return false; + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/QueryResultMaterializer.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/QueryResultMaterializer.java new file mode 100644 index 0000000000000000000000000000000000000000..593c7f75bfc09519eda6733f25e95ed433561788 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/QueryResultMaterializer.java @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.edittabledata; + +import java.sql.SQLException; +import java.util.ArrayList; + +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.serverdatacache.DefaultParameter; +import org.opengauss.mppdbide.bl.serverdatacache.IQueryMaterializer; +import org.opengauss.mppdbide.bl.serverdatacache.IQueryResult; +import org.opengauss.mppdbide.bl.sqlhistory.IQueryExecutionSummary; +import org.opengauss.mppdbide.presentation.IExecutionContext; +import org.opengauss.mppdbide.presentation.resultsetif.IConsoleResult; +import org.opengauss.mppdbide.presentation.resultsetif.IResultConfig; +import org.opengauss.mppdbide.utils.QueryResultType; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: class + * + * Description: The Class QueryResultMaterializer. + * + * @since 3.0.0 + */ +public class QueryResultMaterializer implements IQueryMaterializer { + private IResultConfig iResultConfig; + private IQueryExecutionSummary qes; + private IConsoleResult consoleWrapper; + private IExecutionContext context; + private boolean isEditSupported; + private boolean isQueryResultEditSupported; + private Object materializedQueryResult = null; + + private static ArrayList inputDailogValueList; + + /** + * Instantiates a new query result materializer. + * + * @param iResultConfig the i result config + * @param qes the qes + * @param consoleWrapper the console wrapper + * @param context the context + * @param isEditSupported the is edit supported + * @param isQueryResultEditSupported the is query result edit supported + */ + public QueryResultMaterializer(IResultConfig iResultConfig, IQueryExecutionSummary qes, + IConsoleResult consoleWrapper, IExecutionContext context, boolean isEditSupported, + boolean isQueryResultEditSupported) { + this.iResultConfig = iResultConfig; + this.qes = qes; + this.consoleWrapper = consoleWrapper; + this.context = context; + this.isEditSupported = isEditSupported; + this.isQueryResultEditSupported = isQueryResultEditSupported; + } + + /** + * sets the input dailog value list + * + * @param inDailogValueList the inDailogValueList + */ + public static void setInputDailogValueList(ArrayList inDailogValueList) { + inputDailogValueList = inDailogValueList; + } + + /** + * gets the input dailog value list + * + * @return inputDailogValueList the inputDailogValueList + */ + public static ArrayList getInputDailogValueList() { + return inputDailogValueList; + } + + /** + * Materialize query result. + * + * @param irq the irq + * @param iResultConfig the i result config + * @param qes the qes + * @param consoleWrapper the console wrapper + * @param context the context + * @param isEditSupported the is edit supported + * @param isQueryResultEditSupported the is query result edit supported + * @return the object + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws SQLException + */ + public static Object materializeQueryResult(IQueryResult irq, IResultConfig iResultConfig, + IQueryExecutionSummary qes, IConsoleResult consoleWrapper, IExecutionContext context, + boolean isEditSupported, boolean isQueryResultEditSupported, + ArrayList debugInputValueList, boolean isCallableStmt) + throws DatabaseCriticalException, DatabaseOperationException, SQLException { + setInputDailogValueList(debugInputValueList); + if (!isEditSupported && !isQueryResultEditSupported + && QueryResultType.RESULTTYPE_RESULTSET == irq.getReturnType()) { + DSResultSetGridDataProvider rsdw = new DSResultSetGridDataProvider(irq, iResultConfig, qes); + rsdw.setIncludeEncoding(BLPreferenceManager.getInstance().getBLPreference().isIncludeEncoding()); + rsdw.init(irq, debugInputValueList, isCallableStmt); + + return rsdw; + } else if (isEditSupported || isQueryResultEditSupported) { + DSEditTableDataGridDataProvider editTableDataProvider; + editTableDataProvider = new DSEditTableDataGridDataProvider(irq, iResultConfig, qes, context, + isQueryResultEditSupported); + editTableDataProvider + .setIncludeEncoding(BLPreferenceManager.getInstance().getBLPreference().isIncludeEncoding()); + editTableDataProvider.init(); + editTableDataProvider.setDatabase(context.getTermConnection().getDatabase()); + return editTableDataProvider; + } + + else { + qes.setNumRecordsFetched(irq.getRowsAffected()); + return consoleWrapper; + } + + } + + /** + * Materialize query result. + * + * @param irq the irq + * @return the object + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws SQLException + */ + @Override + public Object materializeQueryResult(IQueryResult irq, boolean isCallableStmt) + throws DatabaseCriticalException, DatabaseOperationException, SQLException { + + ArrayList inputDailogValueListLocal = this.context.getInputValues(); + materializedQueryResult = materializeQueryResult(irq, iResultConfig, qes, consoleWrapper, context, + isEditSupported, isQueryResultEditSupported, inputDailogValueListLocal, isCallableStmt); + return materializedQueryResult; + } + + /** + * Gets the materialized query result. + * + * @return the materialized query result + */ + public Object getMaterializedQueryResult() { + return materializedQueryResult; + } + + /** + * Materialize query result. + * + * @param irq the irq + * @return the object + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + @Override + public Object materializeQueryResult(IQueryResult irq) + throws DatabaseCriticalException, DatabaseOperationException { + return null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/RowIndexIdentifier.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/RowIndexIdentifier.java new file mode 100644 index 0000000000000000000000000000000000000000..77b565dba0a6521d04c0fffcfe5ea13e25c5db79 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/edittabledata/RowIndexIdentifier.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.edittabledata; + +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; + +/** + * + * Title: interface + * + * Description: The Interface RowIndexIdentifier. + * + * @since 3.0.0 + */ +public interface RowIndexIdentifier { + + /** + * Gets the row index. + * + * @param row the row + * @return the row index + */ + int getRowIndex(IDSGridDataRow row); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/erd/AbstractERPresentation.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/erd/AbstractERPresentation.java new file mode 100644 index 0000000000000000000000000000000000000000..ef739f710b9079785ad931789a471a8f96e0d146 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/erd/AbstractERPresentation.java @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.erd; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.erd.model.AbstractERAssociation; +import org.opengauss.mppdbide.bl.erd.model.AbstractERConstraint; +import org.opengauss.mppdbide.bl.erd.model.AbstractEREntity; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * The Class IERPresentation. + * + * @param the element type + * @ClassName: IERPresentation + * @Description: The Class IERPresentation. + * + * @since 3.0.0 + */ +public abstract class AbstractERPresentation { + /** + * The dbcon. + */ + protected DBConnection dbcon; + + /** + * The server object. + */ + protected E serverObject; + + /** + * The entities. + */ + protected List entities; + + /** + * The foreign constraints. + */ + protected List foreignConstraints; + + /** + * The associations. + */ + protected List associations; + + /** + * Instantiates a new abstract ER presentation. + * + * @param serverObject the server object + * @param dbcon the dbcon + */ + public AbstractERPresentation(E serverObject, DBConnection dbcon) { + this.entities = new ArrayList<>(); + this.associations = new ArrayList<>(); + this.foreignConstraints = new ArrayList<>(); + this.dbcon = dbcon; + this.serverObject = serverObject; + } + + /** + * Inits the ER presentation. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws SQLException the SQL exception + */ + public abstract void initERPresentation() + throws DatabaseCriticalException, DatabaseOperationException, SQLException; + + /** + * Gets the dbcon. + * + * @return the dbcon + */ + public DBConnection getDbcon() { + return this.dbcon; + } + + /** + * Adds the entity. + * + * @param entity the entity + */ + public void addEntity(AbstractEREntity entity) { + entities.add(entity); + } + + /** + * Gets the entities. + * + * @return the entities + */ + public List getEntities() { + return entities; + } + + /** + * Adds the association. + * + * @param association the association + */ + public void addAssociation(AbstractERAssociation association) { + associations.add(association); + } + + /** + * Gets the associations. + * + * @return the associations + */ + public List getAssociations() { + return associations; + } + + /** + * Adds the foreign constraint. + * + * @param keyData the key data + */ + public void addForeignConstraint(AbstractERConstraint keyData) { + if (foreignConstraints == null) { + foreignConstraints = new ArrayList<>(); + } + if (foreignConstraints.contains(keyData)) { + throw new IllegalArgumentException("Constraint already present"); + } + foreignConstraints.add(keyData); + } + + /** + * Gets the foreign constraints. + * + * @return the foreign constraints + */ + public List getForeignConstraints() { + return foreignConstraints; + } + + /** + * Gets the window title. + * + * @return the window title + */ + public abstract String getWindowTitle(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/erd/ERDiagramPresentation.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/erd/ERDiagramPresentation.java new file mode 100644 index 0000000000000000000000000000000000000000..cd97cf506a11217bf4b848d5b34c15339ac20ec0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/erd/ERDiagramPresentation.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.erd; + +import java.sql.SQLException; +import java.util.ArrayList; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.erd.model.EREntity; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.groups.TableObjectGroup; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * The Class ERDiagramPresentation. + * + * @ClassName: ERDiagramPresentation + * @Description: The Class ERDiagramPresentation. + * + * @since 3.0.0 + */ +public class ERDiagramPresentation extends AbstractERPresentation { + + public ERDiagramPresentation(TableObjectGroup obj, DBConnection dbcon) { + super(obj, dbcon); + } + + @Override + public void initERPresentation() throws DatabaseCriticalException, DatabaseOperationException, SQLException { + ArrayList tables = serverObject.getSortedServerObjectList(); + for (TableMetaData table : tables) { + if (!table.isLoaded()) { + table.setLevel3Loaded(false); + serverObject.getNamespace().fetchTableColumnMetaData(table.getOid(), serverObject, dbcon); + } + EREntity entity = new EREntity(table, false, dbcon); + entity.initEREntity(); + addEntity(entity); + } + } + + @Override + public String getWindowTitle() { + Namespace namespace = serverObject.getNamespace(); + return namespace.getName() + "-" + namespace.getDatabaseName() + '@' + namespace.getServerName(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/erd/EREntityPresentation.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/erd/EREntityPresentation.java new file mode 100644 index 0000000000000000000000000000000000000000..e2b491e2fdb3f8de43b54623e7c9b5445bc14870 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/erd/EREntityPresentation.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.erd; + +import java.sql.SQLException; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.erd.model.EREntity; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * The Class EREntityPresentation. + * + * @ClassName: EREntityPresentation + * @Description: The Class EREntityPresentation. + * + * @since 3.0.0 + */ +public class EREntityPresentation extends AbstractERPresentation { + + /** + * The entity model. + */ + private EREntity entityModel; + + /** + * Instantiates a new ER entity presentation. + * + * @param serverObject the server object + * @param dbcon the dbcon + */ + public EREntityPresentation(TableMetaData serverObject, DBConnection dbcon) { + super(serverObject, dbcon); + this.entityModel = null; + } + + /** + * Inits the ER presentation. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws SQLException the SQL exception + */ + @Override + public void initERPresentation() throws DatabaseCriticalException, DatabaseOperationException, SQLException { + if (!serverObject.isLoaded()) { + serverObject.setLevel3Loaded(false); + serverObject.getNamespace().fetchTableColumnMetaData(serverObject.getOid(), + serverObject.getNamespace().getTables(), dbcon); + } + EREntity entity = new EREntity(serverObject, true, dbcon); + entity.initEREntity(); + entityModel = entity; + addEntity(entityModel); + } + + /** + * Gets the entity. + * + * @return the entity + */ + public EREntity getEntity() { + return this.entityModel; + } + + /** + * Gets the window title. + * + * @return the window title + */ + @Override + public String getWindowTitle() { + return getEntity().getFullyQualifiedName() + "-" + serverObject.getDatabaseName() + '@' + + serverObject.getServerName(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/AbstractImportExportData.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/AbstractImportExportData.java new file mode 100644 index 0000000000000000000000000000000000000000..65b613dcecd24052b5c4ddead8cea4b5826eaa51 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/AbstractImportExportData.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.exportdata; + +import java.util.ArrayList; +import java.util.Observable; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ImportExportOption; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class ImportExportDataFactory. + * + * @since 3.0.0 + */ +public abstract class AbstractImportExportData extends Observable { + + /** + * The import export server obj. + */ + protected ServerObject importExportServerObj; + + /** + * Instantiates a new abstract import export data. + * + * @param obj the obj + */ + public AbstractImportExportData(ServerObject obj) { + this.importExportServerObj = obj; + } + + /** + * Compose excel query. + * + * @param queryBuff the query buff + * @param importExportoptions the import exportoptions + * @return the string + */ + protected String composeExcelQuery(StringBuffer queryBuff, ImportExportOption importExportoptions) { + queryBuff.append("SELECT"); + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + if (!importExportoptions.isAllColunms()) { + queryBuff.append(getSelectedColumn(importExportoptions.getTablecolumns())); + } else { + queryBuff.append("*"); + } + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + queryBuff.append("FROM"); + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + queryBuff.append(this.importExportServerObj.getDisplayName()); + return queryBuff.toString(); + } + + /** + * Append query format for csv format. + * + * @param queryBuff the query buff + * @return the string + */ + protected String appendQueryFormatForCsvFormat(StringBuffer queryBuff) { + queryBuff.append("DELIMITERS"); + return queryBuff.toString(); + } + + /** + * Appaend tbl name or executed query. + * + * @param queryBuff the query buff + * @param importExportoptions the import exportoptions + */ + protected void appaendTblNameOrExecutedQuery(StringBuffer queryBuff, ImportExportOption importExportoptions) { + queryBuff.append(this.importExportServerObj.getDisplayName()); + + if (!importExportoptions.isAllColunms()) { + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR).append('(') + .append(getSelectedColumn(importExportoptions.getTablecolumns())).append(')'); + } + } + + private String getSelectedColumn(ArrayList selectedColsList) { + StringBuilder strBuild = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + for (String clm : selectedColsList) { + strBuild.append(ServerObject.getQualifiedObjectName(clm)); + strBuild.append(","); + } + if (selectedColsList.size() > 0) { + strBuild.deleteCharAt(strBuild.length() - 1); + } + return strBuild.toString(); + + } + + /** + * Gets the file name. + * + * @return the file name + */ + protected String getFileName() { + return importExportServerObj.getName(); + } + + /** + * Gets the display table name. + * + * @return the display table name + */ + public abstract String getDisplayTableName(); + + /** + * Gets the display name. + * + * @return the display name + */ + public abstract String getDisplayName(); + + /** + * Gets the progress label name. + * + * @return the progress label name + */ + public abstract String getProgressLabelName(); + + /** + * Gets the database. + * + * @return the database + */ + public abstract Database getDatabase(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/AbstractImportExportDataCore.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/AbstractImportExportDataCore.java new file mode 100644 index 0000000000000000000000000000000000000000..f452e92a9f1517ac20eefc80f258a26219b97868 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/AbstractImportExportDataCore.java @@ -0,0 +1,895 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.exportdata; + +import java.nio.file.Path; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; +import java.util.Observable; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.importexportdata.ImportExportDataExecuter; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ImportExportOption; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.presentation.exportdata.ExportCursorExecuteVisitor.ColumnDataType; +import org.opengauss.mppdbide.utils.CustomStringUtility; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.exceptions.TableImporExportException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class AbstractImportExportDataCore. + * + * @since 3.0.0 + */ +public abstract class AbstractImportExportDataCore extends Observable { + + /** + * The import export server obj. + */ + protected ServerObject importExportServerObj; + + /** + * The import exportoptions. + */ + protected ImportExportOption importExportoptions; + + /** + * The import export executer. + */ + protected ImportExportDataExecuter importExportExecuter; + + /** + * The db con. + */ + protected DBConnection dbCon; + + /** + * The executed query. + */ + protected String executedQuery; + + /** + * The path. + */ + protected Path path; + + /** + * The display table name. + */ + protected String displayTableName; + + /** + * The visitor. + */ + protected ExportCursorExecuteVisitor visitor; + + /** + * The is OLAP. + */ + protected boolean isOLAP; + + /** + * The import excel executer. + */ + protected ImportExcelExecuter importExcelExecuter; + + /** + * The temp file path. + */ + protected Path tempFilePath; + + /** + * The query time. + */ + protected String queryTime; + private ArrayList columns; + private ArrayList originalColumns; + private String terminalName; + private boolean isExportIsInProgress; + private String fileLocation; + + /** + * Instantiates a new abstract import export data core. + * + * @param obj the obj + * @param clmList the clm list + * @param executedQuery the executed query + * @param terminalID the terminal ID + * @param querySubmitTime the query submit time + */ + public AbstractImportExportDataCore(ServerObject obj, ArrayList clmList, String executedQuery, + String terminalID, String querySubmitTime) { + this.importExportServerObj = obj; + importExportExecuter = new ImportExportDataExecuter(); + importExportoptions = new ImportExportOption(); + this.columns = clmList; + this.originalColumns = clmList; + this.executedQuery = executedQuery; + this.terminalName = terminalID; + this.queryTime = querySubmitTime; + setDatabaseType(obj); + } + + private void setDatabaseType(ServerObject obj) { + Database database = obj.getDatabase(); + if (database != null) { + switch (database.getDBType()) { + case OPENGAUSS: { + this.isOLAP = true; + break; + } + default: { + // fall through + break; + } + } + } + } + + /** + * Checks if is olapdb. + * + * @return true, if is olapdb + */ + public boolean isOLAPDB() { + return isOLAP; + } + + /** + * Initialize core. + * + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public void initializeCore() throws MPPDBIDEException { + createConnection(); + } + + private void createConnection() throws MPPDBIDEException { + if (dbCon == null && importExportServerObj.getConnectionManager() != null) { + dbCon = importExportServerObj.getConnectionManager().getFreeConnection(); + } + } + + /** + * Compose excel query. + * + * @param queryBuff the query buff + * @return the string + */ + protected String composeExcelQuery(StringBuffer queryBuff) { + if (importExportServerObj instanceof Database) { + if (!importExportoptions.isAllColunms()) { + queryBuff.append("SELECT ").append(getSelectedColumn(importExportoptions.getTablecolumns())) + .append(" FROM (").append(executedQuery).append(")"); + } else { + queryBuff.append(executedQuery); + } + } + return queryBuff.toString(); + } + + /** + * Compose excel query. + * + * @return the string + */ + protected abstract String composeExcelQuery(); + + /** + * Compose query. + * + * @return the string + */ + public String composeQuery() { + checkForSingleQoutes(importExportoptions); + StringBuffer queryBuff = new StringBuffer("COPY"); + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + appendTblNameOrExecutedQuery(queryBuff); + + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + appendQueryForImportOrExport(queryBuff); + + appendFileFormat(queryBuff); + appendEncoding(queryBuff); + queryBuff.append(";"); + return queryBuff.toString(); + } + + private void appendEncoding(StringBuffer queryBuff) { + if (null != importExportoptions.getEncoding() && !importExportoptions.getEncoding().isEmpty()) { + queryBuff.append("ENCODING"); + stringSpacer(importExportoptions.getEncoding(), queryBuff); + } + } + + private void appendFileFormat(StringBuffer queryBuff) { + if (null != importExportoptions.getFileFormat()) { + if ("Binary".equalsIgnoreCase(importExportoptions.getFileFormat())) { + queryBuff.append("BINARY"); + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + } else if ("Excel(xlsx)".equalsIgnoreCase(importExportoptions.getFileFormat())) { + queryBuff.append("Excel(xlsx)"); + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + } else if ("Excel(xls)".equalsIgnoreCase(importExportoptions.getFileFormat())) { + queryBuff.append("Excel(xls)"); + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + } else { + appendQueryFormatForCsvFormat(queryBuff); + } + + } + } + + /** + * Append delimiter option. + * + * @param queryBuff the query buff + */ + protected void appendDelimiterOption(StringBuffer queryBuff) { + if (importExportServerObj instanceof Database) { + queryBuff.append("DELIMITER"); + } + } + + private void appendQueryFormatForCsvFormat(StringBuffer queryBuff) { + if (null != importExportoptions.getDelimiter() && !importExportoptions.getDelimiter().isEmpty()) { + appendDelimiterOption(queryBuff); + stringSpacer(importExportoptions.getDelimiter(), queryBuff); + } + if (null != importExportoptions.getReplaceNull() && !importExportoptions.getReplaceNull().isEmpty()) { + queryBuff.append("NULL"); + stringSpacer(importExportoptions.getReplaceNull(), queryBuff); + } + if (importExportoptions.isHeader()) { + queryBuff.append("HEADER"); + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + } + queryBuff.append("CSV"); + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + + if (null != importExportoptions.getQuotes() && !importExportoptions.getQuotes().isEmpty()) { + queryBuff.append("QUOTE"); + stringSpacer(importExportoptions.getQuotes(), queryBuff); + } + if (null != importExportoptions.getEscape() && !importExportoptions.getEscape().isEmpty()) { + queryBuff.append("ESCAPE"); + stringSpacer(importExportoptions.getEscape(), queryBuff); + } + } + + private void appendQueryForImportOrExport(StringBuffer queryBuff) { + if (importExportoptions.isExport()) { + queryBuff.append("TO"); + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + queryBuff.append("STDOUT"); + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + } else { + queryBuff.append("FROM"); + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + queryBuff.append("STDIN"); + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + + } + } + + /** + * Append tbl name or executed query. + * + * @param queryBuff the query buff + */ + protected void appendTblNameOrExecutedQuery(StringBuffer queryBuff) { + if (importExportServerObj instanceof Database) { + queryBuff.append('('); + + if (!importExportoptions.isAllColunms()) { + queryBuff.append("SELECT ").append(getSelectedColumn(importExportoptions.getTablecolumns())) + .append(" FROM (").append(executedQuery).append(")"); + } else { + queryBuff.append(executedQuery); + } + + queryBuff.append(')'); + } + } + + private void checkForSingleQoutes(ImportExportOption importExportOptions) { + // check to form query if ' is used as input from UI by adding one more + // ' to the query + if (null != importExportOptions.getEscape() && importExportOptions.getEscape().equals("'")) { + importExportOptions.setEscape(MPPDBIDEConstants.ADD_QUOTE); + } + if (null != importExportOptions.getReplaceNull() && importExportOptions.getReplaceNull().equals("'")) { + importExportOptions.setReplaceNull(MPPDBIDEConstants.ADD_QUOTE); + } + if (null != importExportOptions.getQuotes() && importExportOptions.getQuotes().equals("'")) { + importExportOptions.setQuotes(MPPDBIDEConstants.ADD_QUOTE); + } + if (null != importExportOptions.getDelimiter() && importExportOptions.getDelimiter().equals("'")) { + importExportOptions.setDelimiter(MPPDBIDEConstants.ADD_QUOTE); + } + } + + /** + * Gets the selected column. + * + * @param selectedColsList the selected cols list + * @return the selected column + */ + public static String getSelectedColumn(ArrayList selectedColsList) { + StringBuilder strBuild = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + for (String clm : selectedColsList) { + strBuild.append(ServerObject.getQualifiedObjectName(clm)); + strBuild.append(","); + } + if (selectedColsList.size() > 0) { + strBuild.deleteCharAt(strBuild.length() - 1); + } + return strBuild.toString(); + + } + + private void stringSpacer(String string, StringBuffer queryBuff) { + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + queryBuff.append(ServerObject.getLiteralName(string)); + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + } + + /** + * Execute export data. + * + * @param conn the conn + * @return the long + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws MPPDBIDEException the MPPDBIDE exception + * @throws ParseException the parse exception + */ + public long executeExportData(DBConnection conn, boolean isFuncProcExport) + throws DatabaseCriticalException, DatabaseOperationException, MPPDBIDEException, ParseException { + long totalRows = 0; + try { + DBConnection currentConnection = getCurrentConnection(conn); + + if (!"Excel(xlsx)".equalsIgnoreCase(importExportoptions.getFileFormat()) + && !"Excel(xls)".equalsIgnoreCase(importExportoptions.getFileFormat())) { + totalRows = excuteExportDataExceptExcel(currentConnection); + } else { + + totalRows = excuteExportExcelData(currentConnection, isFuncProcExport); + } + } finally { + releaseConnection(); + } + return totalRows; + + } + + /** + * get current connection + * + * @param conn the DBConnection + * @return the current connection + * @throws MPPDBIDEException + */ + private DBConnection getCurrentConnection(DBConnection conn) throws MPPDBIDEException { + boolean isExportTable = null == conn; + DBConnection currentConnection = null; + if (isExportTable) { + if (dbCon == null) { + initializeCore(); + } + currentConnection = dbCon; + } else { + currentConnection = conn; + } + return currentConnection; + } + + /** + * excute export data except Excel files. + * + * @param currentConnection the current connection + * @param totalRows total rows + * @return the total rows + * @throws MPPDBIDEException the MppDBIDEException + */ + private long excuteExportDataExceptExcel(DBConnection currentConnection) throws MPPDBIDEException { + String queryForExport = composeQuery(); + long totalRows = 0; + if (currentConnection != null) { + totalRows = importExportExecuter.exportData(importExportoptions.getZip() ? tempFilePath : path, + queryForExport, currentConnection, importExportoptions.getEncoding(), + importExportoptions.getFileFormat()); + } else { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_RESULT_INVALID_CONNECTION)); + throw new DatabaseOperationException(IMessagesConstants.EXPORT_RESULT_INVALID_CONNECTION); + } + return totalRows; + } + + /** + * excute export excel data. + * + * @param currentConnection the current connection + * @return the total rows + * @throws ParseException the ParseException + * @throws MPPDBIDEException the MPPDBIDEException + */ + private long excuteExportExcelData(DBConnection currentConnection, boolean isFuncProcExport) + throws ParseException, MPPDBIDEException { + long totalRows = 0; + if (currentConnection != null) { + visitor = new ExportCursorExecuteVisitor(importExportoptions.getZip() ? tempFilePath : path, + importExportoptions.getEncoding(), importExportoptions.getFileFormat(), getSafeSheetName(), isOLAP); + totalRows = getExportExcelTotalRows(currentConnection, isFuncProcExport); + } else { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_RESULT_INVALID_CONNECTION)); + throw new DatabaseOperationException(IMessagesConstants.EXPORT_RESULT_INVALID_CONNECTION); + } + + return totalRows; + } + + /** + * gets the ExportExcelTotalRows + * + * @param currentConnection the currentConnection + * @param isFuncProcExport the isFuncProcExport + * @return the count of exported rows + * @throws ParseException the ParseException + * @throws MPPDBIDEException the MPPDBIDEException + */ + protected abstract long getExportExcelTotalRows(DBConnection currentConnection, boolean isFuncProcExport) + throws ParseException, MPPDBIDEException; + + /** + * Validate import export opt parameters. + * + * @throws TableImporExportException the table impor export exception + */ + public void validateImportExportOptParameters() throws TableImporExportException { + if (!"Excel(xlsx)".equalsIgnoreCase(importExportoptions.getFileFormat()) + && !"Excel(xls)".equalsIgnoreCase(importExportoptions.getFileFormat()) + && !MPPDBIDEConstants.BINARY.equalsIgnoreCase(importExportoptions.getFileFormat())) { + validateBasicChecks(); + validateNullAndQuotes(); + validateNullAndDelimiter(); + validateDelimiterAndQuotes(); + validateEscapeAndQuotes(); + } + validateColumns(); + } + + private void validateColumns() throws TableImporExportException { + + if (null != importExportoptions.getTablecolumns() && importExportoptions.getTablecolumns().isEmpty() + && !importExportoptions.isExport()) { + MPPDBIDELoggerUtility.error("IMPORT_VALIDATION_QUOTE_NO_COLS_SELECTED"); + throw new TableImporExportException("IMPORT_VALIDATION_QUOTE_NO_COLS_SELECTED"); + } + if (null != importExportoptions.getTablecolumns() && importExportoptions.getTablecolumns().isEmpty() + && importExportoptions.isExport()) { + MPPDBIDELoggerUtility.error("EXPORT_VALIDATION_QUOTE_NO_COLS_SELECTED"); + throw new TableImporExportException("EXPORT_VALIDATION_QUOTE_NO_COLS_SELECTED"); + } + } + + private void validateBasicChecks() throws TableImporExportException { + // To check if delimiter is empty + if (null != importExportoptions.getDelimiter() && importExportoptions.getDelimiter().isEmpty()) { + MPPDBIDELoggerUtility.error("IMPORTEXPORT_VALIDATION_OTHER"); + throw new TableImporExportException("IMPORTEXPORT_VALIDATION_OTHER"); + } + // To check if replace null contains new line or carriage + // check + if (null != importExportoptions.getReplaceNull() + && (importExportoptions.getReplaceNull().matches(System.lineSeparator()))) { + MPPDBIDELoggerUtility.error("IMPORTEXPORT_VALIDATION_NULL_STRING"); + throw new TableImporExportException("IMPORTEXPORT_VALIDATION_NULL_STRING"); + } + // To check if replace null is more than 100 character + if (null != importExportoptions.getReplaceNull() && (importExportoptions.getReplaceNull().length() > 100)) { + MPPDBIDELoggerUtility.error("IMPORTEXPORT_VALIDATION_NULL_LENGTH"); + throw new TableImporExportException("IMPORTEXPORT_VALIDATION_NULL_LENGTH"); + } + } + + private void validateNullAndQuotes() throws TableImporExportException { + // To check if replace null and quotes are same + if (null != importExportoptions.getReplaceNull() && null != importExportoptions.getQuotes()) { + if (isValidInput(importExportoptions.getReplaceNull(), importExportoptions.getQuotes())) { + MPPDBIDELoggerUtility.error("IMPORTEXPORT_VALIDATION_NULL_AS_DELIMITOR"); + throw new TableImporExportException("IMPORTEXPORT_VALIDATION_NULL_AS_DELIMITOR"); + } + } + } + + private void validateNullAndDelimiter() throws TableImporExportException { + // To check if replace null and delimiter are same + if (null != importExportoptions.getReplaceNull() && null != importExportoptions.getDelimiter()) { + if (isValidInput(importExportoptions.getReplaceNull(), importExportoptions.getDelimiter())) { + MPPDBIDELoggerUtility.error("IMPORTEXPORT_VALIDATION_NULL_AS_DELIMITOR"); + throw new TableImporExportException("IMPORTEXPORT_VALIDATION_NULL_AS_DELIMITOR"); + } + } + if (null != importExportoptions.getQuotes() + && (importExportoptions.getQuotes().length() > 1 || importExportoptions.getEscape().length() > 1)) { + MPPDBIDELoggerUtility.error("IMPORTEXPORT_VALIDATION_QUOTE_SINGLE_CHAR"); + throw new TableImporExportException("IMPORTEXPORT_VALIDATION_QUOTE_SINGLE_CHAR"); + } + } + + private void validateDelimiterAndQuotes() throws TableImporExportException { + // To check if replace delimiter and quotes are same + if (null != importExportoptions.getQuotes() && null != importExportoptions.getDelimiter()) { + if (isValidInput(importExportoptions.getQuotes(), importExportoptions.getDelimiter())) { + MPPDBIDELoggerUtility.error("IMPORTEXPORT_VALIDATION_QUOTE_AS_DELI"); + throw new TableImporExportException("IMPORTEXPORT_VALIDATION_QUOTE_AS_DELI"); + } + } + if (null != importExportoptions.getDelimiter() && (importExportoptions.getDelimiter().length() > 10)) { + MPPDBIDELoggerUtility.error("IMPORTEXPORT_VALIDATION_DELIMITER_LENGTH"); + throw new TableImporExportException("IMPORTEXPORT_VALIDATION_DELIMITER_LENGTH"); + } + if (null != importExportoptions.getReplaceNull() && null != importExportoptions.getQuotes()) { + if (importExportoptions.getQuotes().isEmpty() + && ("\"".equalsIgnoreCase(importExportoptions.getReplaceNull()))) { + MPPDBIDELoggerUtility.error("IMPORTEXPORT_VALIDATION_NULL_AS_QUOTE"); + throw new TableImporExportException("IMPORTEXPORT_VALIDATION_NULL_AS_QUOTE"); + } + } + } + + private void validateEscapeAndQuotes() throws TableImporExportException { + // To check if replace Escape and quotes are same + if (null != importExportoptions.getQuotes() && null != importExportoptions.getEscape()) { + if (isValidInput(importExportoptions.getQuotes(), importExportoptions.getEscape())) { + throw new TableImporExportException("IMPORTEXPORT_VALIDATION_QUOTE_AS_ESCAPE"); + } + } + } + + private boolean isValidInput(String strfirst, String strsecond) { + if (!strfirst.isEmpty() && !strsecond.isEmpty()) { + if (strfirst.equals(strsecond)) { + return true; + } + } + return false; + } + + /** + * Cancel import export operation. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void cancelImportExportOperation() throws DatabaseCriticalException, DatabaseOperationException { + if (dbCon != null) { + dbCon.cancelQuery(); + } + if (importExcelExecuter != null) { + importExcelExecuter.setCancelFlag(true); + } + + } + + /** + * Release connection. + */ + protected void releaseConnection() { + if (dbCon != null && importExportServerObj.getConnectionManager() != null) { + importExportServerObj.getConnectionManager().releaseAndDisconnection(dbCon); + } + dbCon = null; + } + + /** + * Execute import data. + * + * @return the long + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public long executeImportData() throws MPPDBIDEException { + long totalRows = 0; + try { + if (dbCon == null) { + initializeCore(); + } + + if (!"Excel(xlsx)".equalsIgnoreCase(importExportoptions.getFileFormat()) + && !"Excel(xls)".equalsIgnoreCase(importExportoptions.getFileFormat())) { + String query = composeQuery(); + + if (null != dbCon) { + totalRows = importExportExecuter.importTabledata(query, importExportoptions.getFileName(), dbCon); + } else { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.IMPORT_RESULT_INVALID_CONNECTION)); + throw new DatabaseOperationException(IMessagesConstants.IMPORT_RESULT_INVALID_CONNECTION); + } + } else { + // Import excel data execution method + if (dbCon != null) { + importExcelExecuter = new ImportExcelExecuter(dbCon, importExportoptions, importExportServerObj); + totalRows = importExcelExecuter.executeExcImp(); + } else { + throw new DatabaseOperationException(IMessagesConstants.IMPORT_RESULT_INVALID_CONNECTION); + } + } + + } finally { + releaseConnection(); + } + return totalRows; + } + + /** + * Gets the import exportoptions. + * + * @return the import exportoptions + */ + public ImportExportOption getImportExportoptions() { + return importExportoptions; + } + + /** + * Sets the import exportoptions. + * + * @param importExportoptions the new import exportoptions + */ + public void setImportExportoptions(ImportExportOption importExportoptions) { + this.importExportoptions = importExportoptions; + } + + /** + * Gets the file format. + * + * @return the file format + */ + public String getFileFormat() { + return importExportoptions.getFileFormat(); + + } + + /** + * Gets the file name. + * + * @return the file name + */ + public String getFileName() { + String fileName = null; + if (importExportServerObj instanceof Database) { + fileName = getTerminalId() + '_' + + CustomStringUtility.convertStringDateFormat(queryTime, MPPDBIDEConstants.DATE_COLLAPSE_FORMAT); + } + return fileName; + } + + /** + * Gets the safe sheet name. + * + * @return the safe sheet name + */ + public String getSafeSheetName() { + String fileName = null; + if (importExportServerObj instanceof Database) { + fileName = getTerminalId(); + } + return fileName; + } + + /** + * Gets the file path. + * + * @return the file path + */ + public Path getFilePath() { + return path; + } + + /** + * Sets the file path. + * + * @param filePath the new file path + */ + public void setFilePath(Path filePath) { + this.path = filePath; + } + + /** + * Gets the display table name. + * + * @return the display table name + */ + public String getDisplayTableName() { + if (importExportServerObj instanceof Database) { + displayTableName = MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_QUERY, getDisplayName()); + + } + return displayTableName; + } + + /** + * Gets the display name. + * + * @return the display name + */ + public String getDisplayName() { + if (importExportServerObj instanceof Database) { + String query = executedQuery; + if (query.length() > 50) { + query = query.substring(0, 50) + " .."; + } + displayTableName = query + " - " + ((Database) importExportServerObj).getServer().getName(); + + } + return displayTableName; + } + + /** + * Gets the progress label name. + * + * @return the progress label name + */ + public String getProgressLabelName() { + if (importExportServerObj instanceof Database) { + String query = executedQuery; + if (query.length() > 50) { + query = query.substring(0, 50) + " .."; + } + displayTableName = query + " @ " + ((Database) importExportServerObj).getServer().getName(); + + } + return displayTableName; + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + if (importExportServerObj instanceof Database) { + return (Database) importExportServerObj; + } + return null; + } + + /** + * Gets the columns. + * + * @return the columns + */ + public ArrayList getColumns() { + return columns; + } + + /** + * Sets the export. + * + * @param isExport the new export + */ + public void setExport(boolean isExport) { + importExportoptions.setExport(isExport); + } + + /** + * Gets the import export server obj. + * + * @return the import export server obj + */ + public ServerObject getImportExportServerObj() { + return importExportServerObj; + } + + /** + * Gets the terminal id. + * + * @return the terminal id + */ + public String getTerminalId() { + return terminalName; + } + + /** + * Import export clean up. + */ + public void importExportCleanUp() { + setExportIsInProgress(false); + } + + /** + * Sets the export is in progress. + * + * @param isExportIsInProgres the new export is in progress + */ + public void setExportIsInProgress(boolean isExportIsInProgres) { + this.isExportIsInProgress = isExportIsInProgres; + setChanged(); + notifyObservers(this.isExportIsInProgress); + } + + /** + * Gets the original columns. + * + * @return the original columns + */ + public ArrayList getOriginalColumns() { + return originalColumns; + } + + /** + * Gets the file location. + * + * @return the file location + */ + public String getFileLocation() { + return fileLocation; + } + + /** + * Sets the file location. + * + * @param fileLocation the new file location + */ + public void setFileLocation(String fileLocation) { + this.fileLocation = fileLocation; + } + + /** + * Clean up. + * + * @throws DatabaseOperationException the database operation exception + */ + public void cleanUp() throws DatabaseOperationException { + if (visitor != null) { + visitor.cleanUpworkbook(); + } + } + + /** + * Gets the temp file path. + * + * @return the temp file path + */ + public Path getTempFilePath() { + return tempFilePath; + } + + /** + * Sets the temp file path. + * + * @param tempFilePath the new temp file path + */ + public void setTempFilePath(Path tempFilePath) { + this.tempFilePath = tempFilePath; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ExportCursorExecuteVisitor.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ExportCursorExecuteVisitor.java new file mode 100644 index 0000000000000000000000000000000000000000..0dcc34d6b33951d90c4b8385a919203ac6d06c2d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ExportCursorExecuteVisitor.java @@ -0,0 +1,771 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.exportdata; + +import java.io.File; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.nio.file.Path; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.sql.Types; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Locale; + +import org.apache.poi.util.DefaultTempFileCreationStrategy; +import org.apache.poi.util.TempFile; +import org.apache.poi.util.TempFileCreationStrategy; + +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.serverdatacache.DefaultParameter; +import org.opengauss.mppdbide.presentation.edittabledata.CursorQueryExecutor; +import org.opengauss.mppdbide.presentation.edittabledata.QueryResultMaterializer; +import org.opengauss.mppdbide.utils.ConvertTimeStampValues; +import org.opengauss.mppdbide.utils.ConvertTimeValues; +import org.opengauss.mppdbide.utils.DateTimeFormatValidator; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.ResultSetDatatypeMapping; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.files.FileValidationUtils; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: class Description: The Class ExportCursorExecuteVisitor. + * + * @since 3.0.0 + */ +public class ExportCursorExecuteVisitor implements ICursorExecuteRecordVisitor { + + private Path path; + + private String encoding; + + private String safeSheetName; + + private String fileFormat; + + private ExportExcelApachePOI exportExcel; + + private int rowNo = 1; + + private List columnDatatype; + + private int columnCount; + + private long totalRows; + + private boolean isOLAP; + + private int outParaIndex = 0; + + /** + * Instantiates a new export cursor execute visitor. + * + * @param path the path + * @param encoding the encoding + * @param fileFormat the file format + * @param safeSheetName the safe sheet name + * @param isOLAP the is OLAP + */ + public ExportCursorExecuteVisitor(Path path, String encoding, String fileFormat, String safeSheetName, + boolean isOLAP) { + this.path = path; + this.encoding = encoding; + this.safeSheetName = safeSheetName; + this.fileFormat = fileFormat; + this.isOLAP = isOLAP; + } + + /** + * Visit record. + * + * @param rs the rs + * @param isFirstBatch the is first batch + * @param isFirstBatchFirstRecord the is first batch first record + * @return the long + * @throws ParseException the parse exception + * @throws MPPDBIDEException the MPPDBIDE exception + */ + @Override + public long visitRecord(ResultSet rs, boolean isFirstBatch, boolean isFirstBatchFirstRecord, + boolean isFuncProcExport) throws ParseException, MPPDBIDEException { + try { + // Only for the firstbatch and firstrecord, exportexcel object will + // be created and it will be reused further. + long rowsCount = writeToExcel(rs, columnCount, columnDatatype, isFirstBatch, null, null, false, + isFuncProcExport); + totalRows += rowsCount; + } catch (SQLException ex) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERROR_EXPORT_EXCEL_RESULTSET), ex); + throw new DatabaseOperationException(IMessagesConstants.ERROR_EXPORT_EXCEL_RESULTSET); + } + return totalRows; + } + + /** + * Visit record. + * + * @param rs the rs + * @param isFirstBatch the is first batch + * @param isFirstBatchFirstRecord the is first batch first record + * @return the long + * @throws ParseException the parse exception + * @throws MPPDBIDEException the MPPDBIDE exception + */ + @Override + public long visitRecord(ResultSet rs, boolean isFirstBatch, boolean isFirstBatchFirstRecord, + ArrayList inputDailogValueList, ArrayList outResultList, + boolean isCursorResultSet, boolean isFuncProcExport) throws ParseException, MPPDBIDEException { + try { + // Only for the firstbatch and firstrecord, exportexcel object will + // be created and it will be reused further. + + int size = 0; + if (inputDailogValueList != null) { + size = inputDailogValueList.size(); + } + long rowsCount = 0; + if (isFuncProcExport) { + for (int i = 0; i < size; i++) { + rowsCount = writeToExcel(rs, columnCount, columnDatatype, isFirstBatch, inputDailogValueList.get(i), + outResultList, isCursorResultSet, isFuncProcExport); + totalRows += rowsCount; + } + } + rowsCount = writeToExcel(rs, columnCount, columnDatatype, isFirstBatch, null, outResultList, + isCursorResultSet, isFuncProcExport); + totalRows += rowsCount; + } catch (SQLException ex) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERROR_EXPORT_EXCEL_RESULTSET), ex); + throw new DatabaseOperationException(IMessagesConstants.ERROR_EXPORT_EXCEL_RESULTSET); + } + return totalRows; + + } + + /** + * Gets the header of record. + * + * @param rs the rs + * @param isFirstBatch the is first batch + * @return the header of record + * @throws DatabaseOperationException the database operation exception + */ + @Override + public void getHeaderOfRecord(ResultSet rs, boolean isFirstBatch, boolean isFuncProcExport) + throws DatabaseOperationException { + try { + // Only for the firstbatch and firstrecord, exportexcel object will + // be created and it will be reused further. + ArrayList inputDailogValueList = getInputDailogValue(); + if (isFirstBatch && rs != null && rs.getMetaData() != null) { + if (isFuncProcExport) { + columnCount = MPPDBIDEConstants.FUNC_PROC_COLUMN_COUNT; + columnDatatype = getColumnDatatype(columnCount, rs, inputDailogValueList); + } else { + columnCount = rs.getMetaData().getColumnCount(); + columnDatatype = getColumnDatatype(columnCount, rs, null); + } + + TempFile.setTempFileCreationStrategy(new DefaultTempFileCreationStrategy()); + + ThreadLocal threadLocal = new ThreadLocal() { + @Override + protected TempFileCreationStrategy initialValue() { + // to do create thread folder + return createTempFileCreationStrategy(); + } + }; + initColumnHeaderList(rs, isFuncProcExport, threadLocal); + + } else if (inputDailogValueList != null) { + columnCount = MPPDBIDEConstants.FUNC_PROC_COLUMN_COUNT; + columnDatatype = getColumnDatatype(columnCount, rs, inputDailogValueList); + ThreadLocal threadLocal = new ThreadLocal() { + @Override + protected TempFileCreationStrategy initialValue() { + // to do create thread folder + return createTempFileCreationStrategy(); + } + }; + initColumnHeaderList(rs, isFuncProcExport, threadLocal); + } + } catch (SQLException ex) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERROR_EXPORT_EXCEL_RESULTSET)); + throw new DatabaseOperationException(IMessagesConstants.ERROR_EXPORT_EXCEL_RESULTSET); + } + } + + private void initColumnHeaderList(ResultSet rs, boolean isFuncProcExport, + ThreadLocal threadLocal) throws DatabaseOperationException, SQLException { + exportExcel = new ExportExcelApachePOI(fileFormat, true); + List columnHeaderName = new ArrayList(columnCount); + columnHeaderName.add(MessageConfigLoader.getProperty(IMessagesConstants.RESULT_TAB_COL_NAME)); + columnHeaderName.add(MessageConfigLoader.getProperty(IMessagesConstants.RESULT_TAB_COL_DATA_TYPE)); + columnHeaderName.add(MessageConfigLoader.getProperty(IMessagesConstants.RESULT_TAB_COL_PARAMETER_TYPE)); + columnHeaderName.add(MessageConfigLoader.getProperty(IMessagesConstants.RESULT_TAB_COL_VALUE)); + try { + if (MPPDBIDEConstants.STR_EXCEL_XLSX.equalsIgnoreCase(fileFormat)) { + TempFileCreationStrategy tempFileCreationStrategy = threadLocal.get(); + if (tempFileCreationStrategy != null) { + tempFileCreationStrategy.createTempFile("", ""); + } + } + if (exportExcel.checkColLength(columnCount)) { + exportExcel.createSheet(safeSheetName); + List headerList = new ArrayList(); + for (int i = 1; i <= columnCount; i++) { + if (isFuncProcExport) { + headerList.add(columnHeaderName.get(i - 1)); + } else if (null != rs) { + headerList.add(rs.getMetaData().getColumnName(i)); + } + } + exportExcel.createHeaderRow(headerList); + } else { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERROR_EXCEL_ROW_COLUMN_LIMIT)); + throw new DatabaseOperationException(IMessagesConstants.ERROR_EXCEL_ROW_COLUMN_LIMIT); + } + } catch (IOException ex) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERROR_EXCEL_ROW_COLUMN_LIMIT), ex); + throw new DatabaseOperationException(IMessagesConstants.ERROR_EXPORT_EXCEL_RESULTSET, ex); + } + } + + /** + * gets the list of input dailog values + * + * @return the list of InputDailogValue + */ + public ArrayList getInputDailogValue() { + ArrayList olapInputValueList = CursorQueryExecutor.getInputDailogValueList(); + ArrayList oltpInputValueList = QueryResultMaterializer.getInputDailogValueList(); + if (olapInputValueList != null && !olapInputValueList.isEmpty()) { + return olapInputValueList; + } + if (oltpInputValueList != null && !oltpInputValueList.isEmpty()) { + return oltpInputValueList; + } + return null; + } + + /** + * Creates the temp file creation strategy. + * + * @return the temp file creation strategy + */ + private TempFileCreationStrategy createTempFileCreationStrategy() { + return new TempFileCreationStrategy() { + + @Override + public File createTempFile(String arg0, String arg1) throws IOException { + Path pathParent = path.getParent(); + File dir = null; + if (pathParent != null) { + System.setProperty("java.io.tmpdir", pathParent.normalize().toString()); + String stdizedPath = null; + try { + stdizedPath = new File(pathParent.toString()).getCanonicalPath(); + } catch (IOException ex) { + MPPDBIDELoggerUtility.error("Invalid File Path", ex); + } + if (stdizedPath != null) { + System.setProperty("java.io.tmpdir", stdizedPath); + + if (dir == null && FileValidationUtils.validateFilePathName(MPPDBIDEConstants.TEMP_FILE_PATH)) { + dir = new File(MPPDBIDEConstants.TEMP_FILE_PATH, stdizedPath); + } + } + return dir; + } else { + return path.toFile(); + } + } + + @Override + public File createTempDirectory(String arg0) throws IOException { + return null; + } + }; + } + + /** + * Title: enum Description: The Enum ColumnDataType. + * + * @since 17 May, 2019 + */ + public enum ColumnDataType { + + /** + * The double. + */ + DOUBLE, + + /** + * The date. + */ + DATE, + + /** + * The calendar. + */ + CALENDAR, + + /** + * The boolean. + */ + BOOLEAN, + + /** + * The string. + */ + STRING, + + /** + * The TIME + */ + TIME, + + /** + * The timestamp. + */ + TIMESTAMP, + + /** + * The blob. + */ + BLOB, + + /** + * The cursor. + */ + CURSOR, + + /** + * The bytea. + */ + BYTEA, + + /** + * the SMALLINT + */ + SMALLINT, + + /** + * The money + */ + MONEY, + + /** + * The bit + */ + BIT + } + + /** + * Gets the column datatype. + * + * @param colCount the col count + * @param rs the rs + * @return the column datatype + * @throws SQLException ColumnDatatype will be stored in a list so that + * while setCellValue we can check for the datatype for the particular + * rowValue + */ + private List getColumnDatatype(int colCount, ResultSet rs, + ArrayList inputDailogValueList) throws SQLException { + List columnList = new ArrayList(); + String columnType = null; + for (int index = 1; index <= colCount; index++) { + + if (inputDailogValueList != null && !inputDailogValueList.isEmpty()) { + if (index <= 3) { + columnType = inputDailogValueList.get(0).getDefaultParameterType(); + } else if (rs != null) { + columnType = rs.getMetaData().getColumnTypeName(rs.getMetaData().getColumnCount()) + .toLowerCase(Locale.ENGLISH); + } + } else if (rs != null) { + columnType = rs.getMetaData().getColumnTypeName(index).toLowerCase(Locale.ENGLISH); + } + prepareColumnList(columnList, columnType); + } + return columnList; + } + + private void prepareColumnList(List columnList, String columnType) { + switch (columnType) { + case "float8": { + columnList.add(ColumnDataType.DOUBLE); + break; + } + case "float4": { + columnList.add(ColumnDataType.DOUBLE); + break; + } + case "date": { + columnList.add(ColumnDataType.DATE); + break; + } + case "timestamp": { + columnList.add(ColumnDataType.DATE); + break; + } + case "timestamptz": { + columnList.add(ColumnDataType.DATE); + break; + } + case "bool": { + columnList.add(ColumnDataType.BOOLEAN); + break; + } + case "boolean": { + columnList.add(ColumnDataType.BOOLEAN); + break; + } + case "blob": { + columnList.add(ColumnDataType.BLOB); + break; + } + case "refcursor": + columnList.add(ColumnDataType.CURSOR); + + // fall through + case MPPDBIDEConstants.BYTEA: { + columnList.add(ColumnDataType.BYTEA); + break; + } + default: { + columnList.add(ColumnDataType.STRING); + break; + } + } + } + + /** + * Write to excel. + * + * @param rs the rs + * @param colCount the col count + * @param colDatatype the col datatype + * @param isFirstBatch the is first batch + * @return the long + * @throws ParseException the parse exception + * @throws DatabaseOperationException the database operation exception + * @throws SQLException the SQL exception + * @throws MPPDBIDEException the MPPDBIDE exception + */ + private long writeToExcel(ResultSet rs, int colCount, List colDatatype, boolean isFirstBatch, + DefaultParameter inputDailogValueList, ArrayList outResultList, boolean isCursorResultSet, + boolean isFuncProcExport) + throws ParseException, DatabaseOperationException, SQLException, MPPDBIDEException { + long rowsCount = 0; + if (null != exportExcel && exportExcel.checkRowLength(rowNo) && exportExcel.checkColLength(colCount)) { + // From resultset, list will be made for a single row and then + // setCellValue is done for that particular row + boolean needEncode = null != encoding && !encoding.isEmpty(); + + List rows = new ArrayList(); + String content = null; + int index = 0; + try { + for (index = 1; index <= colCount; ++index) { + content = addValuesToRows(rs, colDatatype, inputDailogValueList, outResultList, isCursorResultSet, + needEncode, rows, content, index, isFuncProcExport); + } + exportExcel.setCellValue(rows, rowNo); + } catch (ParseException exception) { + throw new ParseException(IMessagesConstants.ERROR_EXPORT_EXCEL_PARSER, rowNo); + } catch (Exception exception) { + if (exception.getMessage().contains(MPPDBIDEConstants.DISK_FULL_ERR_MSG)) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_ALL_DATA_NOT_ENOUGH_SPACE), + exception); + throw new DatabaseOperationException(IMessagesConstants.EXPORT_ALL_DATA_NOT_ENOUGH_SPACE); + } else { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_EXPORT_TABLE), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_EXPORT_TABLE); + } + } + rowNo++; + rows.clear(); + rowsCount++; + return rowsCount; + } else { + writeToFile(); + throw new DatabaseOperationException(IMessagesConstants.MAXIMUM_EXCEL_ROW_REACHED); + } + } + + private String addValuesToRows(ResultSet rs, List colDatatype, + DefaultParameter inputDailogValueList, ArrayList outResultList, boolean isCursorResultSet, + boolean needEncode, List rows, String content, int index, boolean isFuncProcExport) + throws SQLException, UnsupportedEncodingException { + // If the datatype is Blob, [BLOB] watermark is added + // instead of the content since it can be huge + + if ((colDatatype.size() > index - 1) && colDatatype.get(index - 1) == ColumnDataType.BYTEA && null != rs + && rs.getBytes(index) != null) { + rows.add(MPPDBIDEConstants.BYTEA_WATERMARK); + return content; + } + if (inputDailogValueList != null) { + content = readInputParaContent(inputDailogValueList, index, outResultList); + } else { + content = readContent(rs, needEncode, index, isCursorResultSet, isFuncProcExport); + } + rows.add(content); + return content; + } + + /** + * Read content. + * + * @param rs the rs + * @param needEncode the need encode + * @param index the index + * @return the string + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws SQLException the SQL exception + */ + private String readContent(ResultSet rs, boolean needEncode, int index, boolean isCursorResultSet, + boolean isFuncProcExport) throws UnsupportedEncodingException, SQLException { + if (isFuncProcExport) { + return readResultTabContent(rs, isCursorResultSet, needEncode, index); + } else { + return readTableContent(rs, needEncode, index); + } + + } + + /** + * gets the result tab content + * + * @param rs the rs + * @param isCursorResultSet the isCursorResultSet + * @param needEncode the needEncode + * @param index the index + * @return the result tab content + * @throws SQLException the SQLException + * @throws UnsupportedEncodingException + */ + private String readResultTabContent(ResultSet rs, boolean isCursorResultSet, boolean needEncode, int index) + throws SQLException, UnsupportedEncodingException { + if (null == rs) { + return ""; + } + switch (index) { + + case 1: { + return rs.getMetaData().getColumnLabel(rs.getMetaData().getColumnCount()); + } + case 2: { + return (String) ResultSetDatatypeMapping.getColumnDataTypeName(rs); + } + case 3: { + return MPPDBIDEConstants.OUT; + } + case 4: { + String typeName = rs.getMetaData().getColumnTypeName(rs.getMetaData().getColumnCount()); + if (isCursorResultSet || MPPDBIDEConstants.REF_CURSOR.equals(typeName) + || MPPDBIDEConstants.RECORD.equals(typeName)) { + return MPPDBIDEConstants.CURSOR_WATERMARK; + } else { + return rs.getString(rs.getMetaData().getColumnCount()); + } + } + default: { + break; + } + } + return ""; + } + + /** + * gets the table content + * + * @param rs the rs + * @param needEncode the needEncode + * @param index the index + * @return the table content + * @throws SQLException the SQLException + * @throws UnsupportedEncodingException the UnsupportedEncodingException + */ + private String readTableContent(ResultSet rs, boolean needEncode, int index) + throws SQLException, UnsupportedEncodingException { + if (null == rs) { + return ""; + } + if (rs.getMetaData().getColumnType(index) == Types.TIMESTAMP + || rs.getMetaData().getColumnType(index) == Types.TIMESTAMP_WITH_TIMEZONE) { + return readTimeStampValue(rs, index); + } + if (rs.getMetaData().getColumnType(index) == Types.TIME + || rs.getMetaData().getColumnType(index) == Types.TIME_WITH_TIMEZONE) { + return readTimeValue(rs, index); + } + if (rs.getMetaData().getColumnType(index) == Types.DATE) { + return readDateValue(rs, index); + } + if (isOLAP && needEncode) { + byte[] content = rs.getBytes(index); + if (null == content) { + return null; + } + return new String(content, encoding); + } else { + return rs.getString(index); + } + } + + private String readDateValue(ResultSet rs, int index) throws SQLException { + Date date = rs.getDate(index); + String value = ""; + if (null != date) { + value = new ConvertTimeStampValues(date.getTime(), + BLPreferenceManager.getInstance().getBLPreference().getDateFormat()).toString(); + } + return value; + } + + private String readTimeValue(ResultSet rs, int index) throws SQLException { + Timestamp timestamp = rs.getTimestamp(index); + String value = ""; + if (null != timestamp) { + value = new ConvertTimeValues(timestamp.getTime(), + BLPreferenceManager.getInstance().getBLPreference().getTimeFormat()).toString(); + } + return value; + } + + private String readTimeStampValue(ResultSet rs, int index) throws SQLException { + Timestamp timestamp = rs.getTimestamp(index); + String value = ""; + if (null != timestamp) { + value = new ConvertTimeStampValues(timestamp.getTime(), + DateTimeFormatValidator.getDatePlusTimeFormat( + BLPreferenceManager.getInstance().getBLPreference().getDateFormat(), + BLPreferenceManager.getInstance().getBLPreference().getTimeFormat())).toString(); + } + return value; + } + + /** + * gets the input parameter values + * + * @param inputDailogValue the inputDailogValue + * @param inputIndex the inputIndex + * @param outResultList the outResultList + * @return input parameter content + */ + private String readInputParaContent(DefaultParameter inputDailogValue, int inputIndex, + ArrayList outResultList) { + switch (inputIndex) { + case 1: { + return getParameterName(inputDailogValue, inputIndex); + } + case 2: { + return inputDailogValue.getDefaultParameterType(); + } + case 3: { + return inputDailogValue.getDefaultParameterMode().name(); + } + case 4: { + if (MPPDBIDEConstants.OUT.equals(inputDailogValue.getDefaultParameterMode().name())) { + if (outResultList != null) { + return convertObjectValueToString(outResultList.get(outParaIndex++)); + } + } + return inputDailogValue.getDefaultParameterValue(); + } + default: { + break; + } + } + return ""; + + } + + /** + * convert object values into string + * + * @param object the object + * @return the object + */ + private String convertObjectValueToString(Object object) { + String value = ""; + if (object instanceof Integer) { + value = Integer.toString((int) object); + } + + if (object instanceof ResultSet) { + value = MPPDBIDEConstants.CURSOR_WATERMARK; + } + return value; + } + + /** + * gets the parameter name + * + * @param inputDailogValue the inputDailogValue + * @param inputIndex the inputIndex + * @return the parameter name + */ + private String getParameterName(DefaultParameter inputDailogValue, int inputIndex) { + if (inputDailogValue.getDefaultParameterName() == null + || inputDailogValue.getDefaultParameterName().isEmpty()) { + return MPPDBIDEConstants.PARAM + inputIndex; + } + return inputDailogValue.getDefaultParameterName(); + } + + /** + * Clean upworkbook. + * + * @throws DatabaseOperationException the database operation exception + */ + public void cleanUpworkbook() throws DatabaseOperationException { + if (exportExcel != null && path != null) { + exportExcel.cleanUpWorkbookPOIFiles(path.toString()); + } + exportExcel = null; + } + + /** + * Write to file. + * + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public void writeToFile() throws MPPDBIDEException { + if (exportExcel != null) { + exportExcel.writeToWorkbook(path.toString(), encoding); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ExportCursorQueryExecuter.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ExportCursorQueryExecuter.java new file mode 100644 index 0000000000000000000000000000000000000000..c055ff7203a76089d2f3592eb8a191e2e375be90 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ExportCursorQueryExecuter.java @@ -0,0 +1,409 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.exportdata; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.bl.serverdatacache.DefaultParameter; +import org.opengauss.mppdbide.bl.util.ExecTimer; +import org.opengauss.mppdbide.bl.util.IExecTimer; +import org.opengauss.mppdbide.presentation.edittabledata.CursorQueryExecutor; +import org.opengauss.mppdbide.presentation.edittabledata.QueryResultMaterializer; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class ExportCursorQueryExecuter. + * + * @since 3.0.0 + */ +public class ExportCursorQueryExecuter { + + private boolean needAutoCommitReset; + private Statement stmt; + private String cursorName; + private int fetchSize; + private static final String CURSOR_QUERY_PREPEND = "CURSOR %s NO SCROLL FOR %s"; + private static final int CURSOR_FETCH_BATCH_SIZE = 1000; + private static final String FETCH_QUERY = "FETCH FORWARD %d FROM %s"; + private static final String CLOSE_QUERY = "CLOSE %s"; + private long totalRows; + private boolean cancelled = false; + private String queryForExport; + private DBConnection currentConnection; + + /** + * Instantiates a new export cursor query executer. + * + * @param queryForExport the query for export + * @param currentConnection the current connection + */ + public ExportCursorQueryExecuter(String queryForExport, DBConnection currentConnection) { + this.queryForExport = queryForExport; + this.currentConnection = currentConnection; + } + + /** + * Export excel data. + * + * @param visitor the visitor + * @return the long + * @throws ParseException the parse exception + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public long exportExcelData(ExportCursorExecuteVisitor visitor, boolean isFuncProcExport) + throws ParseException, MPPDBIDEException { + this.fetchSize = -1; + startTxn(); + try { + executeCursor(); + try { + fetchRecords(visitor, isFuncProcExport); + } finally { + closeCursor(); + } + } finally { + stopTxn(); + } + + return totalRows; + } + + /** + * Export SQL data. + * + * @param visitor the visitor + * @return the long + * @throws ParseException the parse exception + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public long exportSQLData(GenerateCursorExecuteVisitor visitor) throws ParseException, MPPDBIDEException { + this.fetchSize = -1; + startTxn(); + try { + executeCursor(); + try { + fetchFileRecords(visitor); + } finally { + closeCursor(); + } + } finally { + stopTxn(); + } + + return totalRows; + } + + private DBConnection getDBConnection() { + return currentConnection; + } + + private Connection getSqlConnection() { + return getDBConnection().getConnection(); + } + + private void startTxn() throws DatabaseCriticalException, DatabaseOperationException { + try { + if (getSqlConnection().getAutoCommit()) { + // if already inside a transaction, no need to reset. + getSqlConnection().setAutoCommit(false); + this.needAutoCommitReset = true; + } + } catch (SQLException ex) { + GaussUtils.handleCriticalException(ex); + throw new DatabaseOperationException(IMessagesConstants.ERR_DATABASE_OPERATION_FAILURE, ex); + } + } + + private void executeCursor() throws DatabaseCriticalException, DatabaseOperationException { + IExecTimer timer = new ExecTimer("Start Cursor"); + timer.start(); + try { + this.stmt = getSqlConnection().createStatement(); + stmt.execute(getCursorQuery()); + } catch (SQLException ex) { + GaussUtils.handleCriticalException(ex); + throw new DatabaseOperationException(IMessagesConstants.ERR_DATABASE_OPERATION_FAILURE, ex); + } finally { + timer.stopAndLogNoException(); + } + } + + private String getCursorQuery() { + return String.format(Locale.ENGLISH, CURSOR_QUERY_PREPEND, getUniqCursorName(), queryForExport); + } + + /** + * To be changed to a uniq name. __DS_QRY_CRSR___ + * + * @return the uniq cursor name + */ + public String getUniqCursorName() { + if (null == cursorName) { + String timeStamp = new SimpleDateFormat("HHmmssSSS").format(new Date()); + cursorName = "__DS_QRY_CRSR_" + timeStamp + "__"; + } + + return cursorName; + } + + private void fetchRecords(ICursorExecuteRecordVisitor visitor, boolean isFuncProcExport) + throws MPPDBIDEException, ParseException { + IExecTimer timer = new ExecTimer("fetch records"); + timer.start(); + int fetchedBatchSize = 0; + int currentFetchSize = 0; + int toFetchRowCount = 0; + + for (int index = 0; index < this.fetchSize || this.fetchSize < 1;) { + if (this.fetchSize == -1) { + // Fetch All case. + currentFetchSize = CURSOR_FETCH_BATCH_SIZE; + } else { + toFetchRowCount = this.fetchSize - index; + currentFetchSize = toFetchRowCount > CURSOR_FETCH_BATCH_SIZE ? CURSOR_FETCH_BATCH_SIZE + : toFetchRowCount; + } + boolean isFirstBatch = false; + if (fetchedBatchSize == 0) { + isFirstBatch = true; + } + fetchedBatchSize = fetchRecordBatch(currentFetchSize, visitor, isFirstBatch, isFuncProcExport); + index += fetchedBatchSize; + if (fetchedBatchSize < currentFetchSize) { + ((ExportCursorExecuteVisitor) visitor).writeToFile(); + timer.stop(); + return; + } + } + timer.stopAndLogNoException(); + } + + private void fetchFileRecords(ICursorExecuteRecordVisitor visitor) throws MPPDBIDEException, ParseException { + IExecTimer timer = new ExecTimer("fetch records"); + timer.start(); + int fetchedBatchSize = 0; + int currentFetchSize = 0; + int toFetchRowCount = 0; + + for (int index = 0; index < this.fetchSize || this.fetchSize < 1;) { + if (this.fetchSize == -1) { + // Fetch All case. + currentFetchSize = CURSOR_FETCH_BATCH_SIZE; + } else { + toFetchRowCount = this.fetchSize - index; + currentFetchSize = toFetchRowCount > CURSOR_FETCH_BATCH_SIZE ? CURSOR_FETCH_BATCH_SIZE + : toFetchRowCount; + } + boolean isFirstBatch = false; + if (fetchedBatchSize == 0) { + isFirstBatch = true; + } + fetchedBatchSize = fetchSQLFileRecordBatch(currentFetchSize, visitor, isFirstBatch); + index += fetchedBatchSize; + if (fetchedBatchSize < currentFetchSize) { + ((GenerateCursorExecuteVisitor) visitor).writeToSqlFile(); + timer.stop(); + return; + } + } + timer.stopAndLogNoException(); + } + + /** + * Sets the cancel flag. + * + * @param iscancel the new cancel flag + */ + public void setCancelFlag(boolean iscancel) { + this.cancelled = iscancel; + } + + private int fetchSQLFileRecordBatch(int currentFetchSize, ICursorExecuteRecordVisitor visitor, boolean isFirstBatch) + throws MPPDBIDEException, ParseException { + ResultSet rs = null; + int recordFetchCounter = 0; + try { + rs = stmt.executeQuery(getFetchQuery(currentFetchSize)); + visitor.getHeaderOfRecord(rs, isFirstBatch, false); + // header + while (rs.next()) { + boolean isFirstBatchFirstRecord = false; + recordFetchCounter++; + if (recordFetchCounter == 1) { + isFirstBatchFirstRecord = true; + } + // data + if (!cancelled) { + + this.totalRows = visitor.visitRecord(rs, isFirstBatch, isFirstBatchFirstRecord, false); + if (recordFetchCounter == currentFetchSize) { + break; + } + + } else { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.USER_CANCEL_MSG)); + throw new DatabaseOperationException(IMessagesConstants.USER_CANCEL_MSG); + } + } + + return recordFetchCounter; + } catch (SQLException ex) { + GaussUtils.handleCriticalException(ex); + throw new DatabaseOperationException(IMessagesConstants.ERR_DATABASE_OPERATION_FAILURE, ex); + } finally { + closeResultSet(rs); + } + + } + + private int fetchRecordBatch(int currentFetchSize, ICursorExecuteRecordVisitor visitor, boolean isFirstBatch, + boolean isFuncProcExport) throws MPPDBIDEException, ParseException { + ResultSet rs = null; + int recordFetchCounter = 0; + try { + rs = stmt.executeQuery(getFetchQuery(currentFetchSize)); + visitor.getHeaderOfRecord(rs, isFirstBatch, isFuncProcExport); + + ArrayList inputDailogValueList = getInputDailogValue(); + boolean isRecordType = false; + while (rs.next() && !isRecordType) { + boolean isFirstBatchFirstRecord = false; + recordFetchCounter++; + if (recordFetchCounter == 1) { + isFirstBatchFirstRecord = true; + } + + if (MPPDBIDEConstants.RECORD + .equals(rs.getMetaData().getColumnTypeName(rs.getMetaData().getColumnCount()))) { + isRecordType = true; + } + // data + if (!cancelled) { + this.totalRows = visitor.visitRecord(rs, isFirstBatch, isFirstBatchFirstRecord, + inputDailogValueList, null, false, isFuncProcExport); + if (recordFetchCounter == currentFetchSize) { + break; + } + + } else { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.USER_CANCEL_MSG)); + throw new DatabaseOperationException(IMessagesConstants.USER_CANCEL_MSG); + } + } + + return recordFetchCounter; + } catch (SQLException ex) { + GaussUtils.handleCriticalException(ex); + throw new DatabaseOperationException(IMessagesConstants.ERR_DATABASE_OPERATION_FAILURE, ex); + } finally { + closeResultSet(rs); + } + + } + + /** + * gets the list of input dailog values + * + * @return the list of getInputDailogValue + */ + public ArrayList getInputDailogValue() { + ArrayList olapInputValueList = null; + if (currentConnection.isOLAPConnection()) { + olapInputValueList = CursorQueryExecutor.getInputDailogValueList(); + } + + if (olapInputValueList != null && !olapInputValueList.isEmpty()) { + return olapInputValueList; + } + + return null; + } + + private void closeResultSet(ResultSet rs) { + try { + if (null != rs) { + rs.close(); + } + } catch (SQLException ex) { + // Ignore. Nothing can be done to recover. + MPPDBIDELoggerUtility.debug("Resultset close failed while materializing the records"); + } + } + + private String getFetchQuery(int currentFetchSize) { + return String.format(Locale.ENGLISH, FETCH_QUERY, currentFetchSize, getUniqCursorName()); + } + + private void closeCursor() { + IExecTimer timer = new ExecTimer("close cursor"); + timer.start(); + try { + this.stmt.execute(getCloseCursorQuery()); + } catch (SQLException ex) { + // Ignore. No way to recover from close failure. + MPPDBIDELoggerUtility.error("Error closing a cursor.", ex); + } finally { + getDBConnection().closeStatement(stmt); + timer.stopAndLogNoException(); + } + } + + private String getCloseCursorQuery() { + return String.format(Locale.ENGLISH, CLOSE_QUERY, getUniqCursorName()); + } + + private void stopTxn() { + if (!needAutoCommitReset) { + return; + } + IExecTimer timer = new ExecTimer("Stop transaction"); + timer.start(); + + try { + Connection sqlConnection = getSqlConnection(); + // Set auto commit would issue a commit before changing the flag. + // Its a cautious call that "select fns()", might do an DML + // operation and need commit. + sqlConnection.setAutoCommit(true); + } catch (SQLException exception) { + // Ignore. Not mechanism to recover from this failure. + MPPDBIDELoggerUtility.error( + "Stop transaction after query execution failed. " + "No way to recover, and skiping this error", + exception); + } + timer.stopAndLogNoException(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ExportExcelApachePOI.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ExportExcelApachePOI.java new file mode 100644 index 0000000000000000000000000000000000000000..80b71b03dc2ac201e5314a90a2efdc1bc35534b4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ExportExcelApachePOI.java @@ -0,0 +1,382 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.exportdata; + +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.apache.poi.hpsf.SummaryInformation; +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFCellStyle; +import org.apache.poi.hssf.usermodel.HSSFDataFormat; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ooxml.POIXMLProperties; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.DataFormat; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.streaming.SXSSFCell; +import org.apache.poi.xssf.streaming.SXSSFRow; +import org.apache.poi.xssf.streaming.SXSSFSheet; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; +import org.apache.poi.xssf.usermodel.XSSFCellStyle; +import org.apache.poi.xssf.usermodel.XSSFDataFormat; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.files.DSFolderDeleteUtility; +import org.opengauss.mppdbide.utils.files.FilePermissionFactory; +import org.opengauss.mppdbide.utils.files.ISetFilePermission; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class ExportExcelApachePOI. + * + * @since 3.0.0 + */ +public class ExportExcelApachePOI { + private static final String POIFILES_NAME = "\\poifiles"; + private static final int MAX_COL_COUNT_XLS = 256; + private static final int MAX_COL_COUNT_XLSX = 16384; + private static final int MAX_ROW_COUNT_XLS = 64000; + private static final int MAX_ROW_COUNT_XLSX = 1000000; + private static final String EXCEL_XLSX = "Excel(xlsx)"; + private static final String EXCEL_XLS = "Excel(xls)"; + private String fileFormat; + private SXSSFWorkbook xssfWorkBook; + private HSSFWorkbook hssfWorkBook; + private SXSSFSheet xssfsheet; + private HSSFSheet hssfSheet; + private FileOutputStream fileOutStream; + private HSSFCellStyle hssfDateCellStyl; + private XSSFCellStyle xssfDateCellStyl; + + // true mains column cell style is common + private boolean dbDataExport; + // if dbDataExport is true, then common column index use this common index cell style + // this will init when createHeaderRow + private List dbDataCellStyles = new ArrayList<>(); + + /** + * Instantiates a new export excel apache POI. + * + * @param fileFormat the file format + */ + public ExportExcelApachePOI(String fileFormat) { + this(fileFormat, false); + } + + /** + * Instantiates a new export excel apache POI. + * + * @param fileFormat the file format + * @param dbDataExport is database data export + */ + public ExportExcelApachePOI(String fileFormat, boolean dbDataExport) { + this.fileFormat = fileFormat; + this.dbDataExport = dbDataExport; + } + + /** + * Sets the cell value. + * + * @param oneRow the one row + * @param rowNo the row no + * @throws ParseException the parse exception + */ + public void setCellValue(List oneRow, int rowNo) throws ParseException { + Sheet sheet = null; + if (EXCEL_XLSX.equals(fileFormat)) { + sheet = xssfsheet; + } else if (EXCEL_XLS.equals(fileFormat)) { + sheet = hssfSheet; + } else { + return; + } + + Row row = sheet.createRow(rowNo); + for (int i = 0; i < oneRow.size(); i ++) { + String cellValue = oneRow.get(i); + Cell cell = row.createCell(i); + if (cellValue == null || "".equals(cellValue)) { + cell.setCellValue(""); + } else { + cellValue = truncateCellSize(cellValue); + cell.setCellStyle(getCellStyleByColumn(i)); + cell.setCellValue(cellValue); + } + } + } + + /** + * Truncate cell size. + * + * @param cellValue - CellValue to set in the workbook. If number of + * characters in the cell is greater than 32767 then it would truncate the + * cell characters to 32767 + * @return the string + */ + private String truncateCellSize(String cellValue) { + String truncatedCellValue = cellValue; + if (cellValue.length() > 32767) { + truncatedCellValue = cellValue.substring(0, 32767 - 3) + "..."; + } + return truncatedCellValue; + } + + /** + * Creates the sheet. + * + * @param sheetName the sheet name + * @throws DatabaseOperationException the database operation exception + */ + public void createSheet(String sheetName) throws DatabaseOperationException { + try { + if ("Excel(xlsx)".equals(fileFormat)) { + xssfWorkBook = new SXSSFWorkbook(); + POIXMLProperties properties = xssfWorkBook.getXSSFWorkbook().getProperties(); + properties.getCoreProperties().setCreator("Data Studio"); + xssfsheet = xssfWorkBook.createSheet(sheetName); + createXSSFCellStyleFormat(); + } else if ("Excel(xls)".equals(fileFormat)) { + hssfWorkBook = new HSSFWorkbook(); + hssfWorkBook.createInformationProperties(); + SummaryInformation summaryInfo = hssfWorkBook.getSummaryInformation(); + if (null != summaryInfo) { + summaryInfo.setAuthor("Data Studio"); + } + hssfSheet = (HSSFSheet) hssfWorkBook.createSheet(sheetName); + createHSSFCellStyleFormat(); + } + } catch (Exception exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_EXPORT_TABLE), exe); + throw new DatabaseOperationException(IMessagesConstants.ERR_EXPORT_TABLE); + } + } + + /** + * Cell Style and Format will be created globally once for date format so + * that it can be used for the cells with date format + */ + private void createHSSFCellStyleFormat() { + hssfDateCellStyl = (HSSFCellStyle) hssfWorkBook.createCellStyle(); + HSSFDataFormat format = (HSSFDataFormat) hssfWorkBook.createDataFormat(); + short dateFormatCode = format.getFormat("yyyy-MM-dd hh:mm:ss"); + hssfDateCellStyl.setDataFormat(dateFormatCode); + } + + private void createXSSFCellStyleFormat() { + xssfDateCellStyl = (XSSFCellStyle) xssfWorkBook.createCellStyle(); + XSSFDataFormat xssfDataFormat = (XSSFDataFormat) xssfWorkBook.createDataFormat(); + int dateFormatCode = xssfDataFormat.getFormat("yyyy-MM-dd hh:mm:ss"); + xssfDateCellStyl.setDataFormat(dateFormatCode); + } + + /** + * Write to workbook. + * + * @param fileName the file name + * @param encoding the encoding + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public void writeToWorkbook(String fileName, String encoding) throws MPPDBIDEException { + try { + ISetFilePermission withPermission = FilePermissionFactory.getFilePermissionInstance(); + Path path = withPermission.createFileWithPermission(fileName, false, null, false); + fileOutStream = new FileOutputStream(path.toString(), true); + if ("Excel(xlsx)".equals(fileFormat)) { + xssfWorkBook.write(fileOutStream); + } else if ("Excel(xls)".equals(fileFormat)) { + hssfWorkBook.write(fileOutStream); + } + fileOutStream.flush(); + + } catch (FileNotFoundException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_EXPORT_TABLE), exe); + throw new DatabaseOperationException(IMessagesConstants.ERR_EXPORT_TABLE, exe); + } catch (IOException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.IO_EXCEPTION_WHILE_EXPORT), + exe); + String msg = (exe.getMessage().contains(MPPDBIDEConstants.DISK_FULL_ERR_MSG)) + ? IMessagesConstants.EXPORT_ALL_DATA_NOT_ENOUGH_SPACE + : IMessagesConstants.IO_EXCEPTION_WHILE_EXPORT; + throw new DatabaseOperationException(msg, exe); + } catch (Exception exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.IO_EXCEPTION_WHILE_EXPORT), + exe); + throw new DatabaseOperationException(IMessagesConstants.FAILED_TO_WRITE_TO_EXCEL); + } finally { + if (fileOutStream != null) { + try { + fileOutStream.close(); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("Error while closing file output stream.", exception); + } + } + } + } + + /** + * Creates the header row. + * + * @param headerList the header list + */ + public void createHeaderRow(List headerList) { + Sheet sheet = null; + if ("Excel(xlsx)".equals(fileFormat)) { + sheet = xssfsheet; + } else if ("Excel(xls)".equals(fileFormat)) { + sheet = hssfSheet; + } else { + return; + } + + Row row = sheet.createRow(0); + for (int i = 0; i < headerList.size(); i ++) { + Cell cell = row.createCell(i); + cell.setCellValue(headerList.get(i)); + if (dbDataExport) { + dbDataCellStyles.add(getCellStyle().get()); + } + } + } + + /** + * Check row length. + * + * @param rowCount the row count + * @return true, if successful + */ + + public boolean checkRowLength(int rowCount) { + if ("Excel(xlsx)".equals(fileFormat)) { + if (rowCount > MAX_ROW_COUNT_XLSX) { + return false; + } + } else if ("Excel(xls)".equals(fileFormat)) { + if (rowCount > MAX_ROW_COUNT_XLS) { + return false; + } + } + return true; + } + + /** + * Check col length. + * + * @param colCount the col count + * @return true, if successful + */ + public boolean checkColLength(int colCount) { + if ("Excel(xlsx)".equals(fileFormat)) { + if (colCount > MAX_COL_COUNT_XLSX) { + return false; + } + } else if ("Excel(xls)".equals(fileFormat)) { + if (colCount > MAX_COL_COUNT_XLS) { + return false; + } + } + return true; + } + + private void handleWorkbookCleanupActivity(String fileName) throws DatabaseOperationException { + if ("Excel(xlsx)".equals(fileFormat)) { + if (xssfWorkBook != null) { + try { + xssfWorkBook.close(); + } catch (IOException exp) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.IO_EXCEPTION_WHILE_EXPORT), exp); + throw new DatabaseOperationException(IMessagesConstants.IO_EXCEPTION_WHILE_EXPORT, exp); + } + xssfWorkBook.dispose(); + Path path = Paths.get(fileName); + Path parent = path.getParent(); + Path newpath; + if (parent != null) { + newpath = Paths.get(parent.toString() + POIFILES_NAME); + } else { + newpath = Paths.get(path.toString() + POIFILES_NAME); + } + try { + Files.walkFileTree(newpath, new DSFolderDeleteUtility()); + } catch (IOException exception) { + + if (exception.getMessage().contains( + "The process cannot access the file because it is being used by another process.")) { + MPPDBIDELoggerUtility.error( + "The process cannot access the file because it is being used by another process", + exception); + return; + } + throw new DatabaseOperationException(IMessagesConstants.IO_EXCEPTION_WHILE_EXPORT, exception); + } + } + } + } + + /** + * Clean up workbook POI files. + * + * @param fileName the file name + * @throws DatabaseOperationException the database operation exception + */ + public void cleanUpWorkbookPOIFiles(String fileName) throws DatabaseOperationException { + handleWorkbookCleanupActivity(fileName); + } + + private CellStyle getCellStyleByColumn(int column) { + if (dbDataExport) { + return dbDataCellStyles.get(column); + } + return getCellStyle().get(); + } + + private Optional getCellStyle() { + Workbook workBook = null; + if (EXCEL_XLSX.equals(fileFormat)) { + workBook = xssfWorkBook; + } else if (EXCEL_XLS.equals(fileFormat)) { + workBook = hssfWorkBook; + } else { + return Optional.empty(); + } + DataFormat fmt = workBook.createDataFormat(); + CellStyle cellStyle = workBook.createCellStyle(); + cellStyle.setDataFormat(fmt.getFormat("@")); + return Optional.of(cellStyle); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ExportZipData.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ExportZipData.java new file mode 100644 index 0000000000000000000000000000000000000000..cb8c5da7507bf4b764a15e266c109f76a8c1f716 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ExportZipData.java @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.exportdata; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import org.opengauss.mppdbide.utils.EnvirnmentVariableValidator; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.FileCompressException; +import org.opengauss.mppdbide.utils.files.FilePermissionFactory; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: ExportZipData + * + * @since 3.0.0 + */ +public class ExportZipData { + private ZipOutputStream out; + private BufferedInputStream bis; + private FileInputStream fis; + private FileOutputStream fos; + + /** + * Do compress. + * + * @param srcFilePath the src file path + * @param zipFilePath the zip file path + * @throws FileCompressException the file compress exception + * @Title: doCompress + * @Description: the entrance for performing compression + */ + public void doCompress(String srcFilePath, String zipFilePath) throws FileCompressException { + try { + compressCore(srcFilePath, zipFilePath); + } catch (IOException | DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.COMPRESS_FAILED), exception); + throw new FileCompressException(IMessagesConstants.COMPRESS_FAILED, exception.getMessage(), exception); + } + } + + private void compressCore(String srcFilePath, String zipFilePath) + throws IOException, DatabaseOperationException { + File srcFile = new File(srcFilePath); + File zipFile = null; + try { + fis = new FileInputStream(srcFile); + zipFile = new File(zipFilePath); + if (!zipFile.exists()) { + FilePermissionFactory.getFilePermissionInstance().createFileWithPermission(zipFilePath, false, null, + false); + } + fos = new FileOutputStream(zipFile); + out = new ZipOutputStream(fos); + writeData(fis, out, srcFile); + } finally { + closeIO(); + deleteFile(srcFile); + } + } + + private void writeData(FileInputStream fis, ZipOutputStream out, File srcFile) throws IOException { + String entryName = null; + bis = new BufferedInputStream(fis); + entryName = srcFile.getName(); + ZipEntry entry = new ZipEntry(entryName); + out.putNextEntry(entry); + int len = 0; + byte[] buffer = new byte[1024]; + while ((len = bis.read(buffer)) > 0) { + out.write(buffer, 0, len); + out.flush(); + } + } + + private void closeIO() { + if (out != null) { + try { + out.closeEntry(); + } catch (IOException ioException) { + MPPDBIDELoggerUtility.error("ExportZipData: Error while closing Entry", ioException); + } + + try { + out.close(); + } catch (IOException ioException) { + MPPDBIDELoggerUtility.error("ExportZipData: Error while closing ZipOutputStream", ioException); + } + } + + if (fos != null) { + try { + fos.close(); + } catch (IOException ioException) { + MPPDBIDELoggerUtility.error("ExportZipData: Error while closing FileOutputStream", ioException); + } + } + + if (bis != null) { + try { + bis.close(); + } catch (IOException ioException) { + MPPDBIDELoggerUtility.error("ExportZipData: Error while closing BufferedInputStream", ioException); + } + } + + if (fis != null) { + try { + fis.close(); + } catch (IOException ioException) { + MPPDBIDELoggerUtility.error("ExportZipData: Error while closing FileInputStream", ioException); + } + } + } + + private void deleteFile(File file) { + if (file.exists() && file.isFile()) { + if (file.delete() == false) { + MPPDBIDELoggerUtility.error("ExportZipData: failed to delete the file in temp path"); + } + + } + } + + /** + * Gets the temp path str. + * + * @param zipFilePath the zip file path + * @param fileSuffix the file suffix + * @return the temp path str + * @Title: getTempPathStr + */ + public static String getTempPathStr(String zipFilePath, String fileSuffix, String tempPath) { + return tempPath + EnvirnmentVariableValidator.validateAndGetFileSeperator() + + zipFilePath.substring( + zipFilePath.lastIndexOf(EnvirnmentVariableValidator.validateAndGetFileSeperator()) + 1, + zipFilePath.lastIndexOf(MPPDBIDEConstants.DOT)) + + fileSuffix; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/GenerateCursorExecuteVisitor.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/GenerateCursorExecuteVisitor.java new file mode 100644 index 0000000000000000000000000000000000000000..9ced614639cf081abad6e41dbf604d43563bfb44 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/GenerateCursorExecuteVisitor.java @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.exportdata; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; +import org.opengauss.mppdbide.bl.export.GenerateCursorExecuteUtil; +import org.opengauss.mppdbide.bl.serverdatacache.DefaultParameter; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class GenerateCursorExecuteVisitor. + * + * @since 3.0.0 + */ +public class GenerateCursorExecuteVisitor implements ICursorExecuteRecordVisitor { + + private Path path; + private String encoding; + private long totalRows; + private FileOutputStream fileOutPutStream = null; + private OutputStreamWriter filewriter; + private GenerateCursorExecuteUtil cursorExecuteUtil; + + /** + * Instantiates a new generate cursor execute visitor. + * + * @param path the path + * @param encoding the encoding + * @param isOLAP the is OLAP + * @param tableNames the table names + */ + public GenerateCursorExecuteVisitor(Path path, String encoding, boolean isOLAP, String tableNames) { + this.path = path; + this.encoding = encoding; + cursorExecuteUtil = new GenerateCursorExecuteUtil(tableNames, encoding, isOLAP); + } + + @Override + public long visitRecord(ResultSet rs, boolean isFirstBatch, boolean isFirstBatchFirstRecord, + boolean isFuncProcExport) throws ParseException, MPPDBIDEException { + try { + // Only for the firstbatch and firstrecord, exportexcel object will + // be created and it will be reused further. + long rowsCount = cursorExecuteUtil.getAllRowsCount(rs, isFirstBatch); + totalRows += rowsCount; + } catch (SQLException ex) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERROR_EXPORT_EXCEL_RESULTSET), ex); + throw new DatabaseOperationException(IMessagesConstants.ERROR_EXPORT_EXCEL_RESULTSET); + } + return totalRows; + + } + + /** + * Gets the column datatype. + * + * @param colCount the col count + * @param rs the rs + * @return the column datatype + * @throws SQLException the SQL exception + */ + public List getColumnDatatype(int colCount, ResultSet rs) throws SQLException { + List columnList = new ArrayList(); + if (rs.getMetaData() != null) { + for (int i = 1; i <= colCount; i++) { + columnList.add(rs.getMetaData().getColumnType(i)); + + } + } + return columnList; + } + + /** + * Write to sql file. + * + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public void writeToSqlFile() throws MPPDBIDEException { + boolean isExceptionThrown = false; + try { + fileOutPutStream = new FileOutputStream(path.toFile()); + filewriter = new OutputStreamWriter(fileOutPutStream, encoding); + + filewriter.write(cursorExecuteUtil.getOutPutInsertSql().toString()); + + } catch (Exception exception) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.DIRTY_GENERATE_INSERT_DIALOG_SAVE_FILE_ERROR), + exception); + isExceptionThrown = true; + throw new MPPDBIDEException( + MessageConfigLoader.getProperty(IMessagesConstants.DIRTY_GENERATE_INSERT_DIALOG_SAVE_FILE_ERROR), + exception); + + } finally { + closeStream(isExceptionThrown); + } + } + + private void closeStream(Boolean isExceptionThrown) { + try { + if (filewriter != null) { + filewriter.close(); + } + if (fileOutPutStream != null) { + fileOutPutStream.close(); + } + + } catch (IOException error) { + MPPDBIDELoggerUtility.error("Error while generating file in exception.", error); + + } + if (isExceptionThrown) { + try { + Files.deleteIfExists(path); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("Error while deleting file in exception.", exception); + } + } + + } + + /** + * Clean up file content. + */ + public void cleanUpFileContent() { + cursorExecuteUtil.cleanOutputInsertSql(); + } + + /** + * visit records + */ + @Override + public long visitRecord(ResultSet rs, boolean isFirstBatch, boolean isFirstBatchFirstRecord, + ArrayList inputDailogValueList, ArrayList outResultList, + boolean isCursorResultSet, boolean isFuncProcExport) throws ParseException, MPPDBIDEException { + return 0; + } + + /** + * getPath path + * + * @return path sql file + */ + public Path getPath() { + return path; + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/GenerateSQLDataCore.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/GenerateSQLDataCore.java new file mode 100644 index 0000000000000000000000000000000000000000..24c75d8728e5c152611e948b65ac9ded2db5a5c6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/GenerateSQLDataCore.java @@ -0,0 +1,254 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.exportdata; + +import java.nio.file.Path; +import java.text.ParseException; +import java.util.Observable; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.JSQLParserUtils; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class GenerateSQLDataCore. + * + * @since 3.0.0 + */ +public class GenerateSQLDataCore extends Observable { + + private ServerObject importExportServerObj; + private DBConnection dbCon; + private String executedQuery; + private boolean isExportIsInProgress; + private ExportCursorQueryExecuter exportCursorExecuter; + private GenerateCursorExecuteVisitor visitor; + private boolean isOLAP; + private String encode; + private String tableNames; + + /** + * Instantiates a new generate SQL data core. + * + * @param obj the obj + * @param executedQuery the executed query + * @param encode the encode + * @param userName the user name + */ + public GenerateSQLDataCore(ServerObject obj, String executedQuery, String encode, String userName) { + this.importExportServerObj = obj; + this.executedQuery = executedQuery; + this.encode = encode; + setDatabaseType(obj); + } + + private void setDatabaseType(ServerObject obj) { + Database database = obj.getDatabase(); + if (database != null) { + switch (database.getDBType()) { + case OPENGAUSS: { + this.isOLAP = true; + break; + } + default: { + // fall through + break; + } + } + } + } + + /** + * Checks if is olapdb. + * + * @return true, if is olapdb + */ + public boolean isOLAPDB() { + return isOLAP; + } + + /** + * Initialize core. + * + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public void initializeCore() throws MPPDBIDEException { + createConnection(); + } + + private void createConnection() throws MPPDBIDEException { + if (dbCon == null && importExportServerObj.getConnectionManager() != null) { + dbCon = importExportServerObj.getConnectionManager().getFreeConnection(); + } + } + + /** + * Compose SQL query. + * + * @return the string + */ + public String composeSQLQuery() { + StringBuffer queryBuff = new StringBuffer(); + if (importExportServerObj instanceof TableMetaData) { + queryBuff.append("SELECT"); + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + + queryBuff.append("*"); + + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + queryBuff.append("FROM"); + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + queryBuff.append(this.importExportServerObj.getDisplayName()); + } else { + queryBuff.append(executedQuery); + + } + return queryBuff.toString(); + } + + /** + * Execute export data. + * + * @param conn the conn + * @param newPath the new path + * @return the long + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws MPPDBIDEException the MPPDBIDE exception + * @throws ParseException the parse exception + */ + public long executeExportData(DBConnection conn, Path newPath) + throws DatabaseCriticalException, DatabaseOperationException, MPPDBIDEException, ParseException { + long totalRows = 0; + boolean isExportTable = null == conn; + DBConnection currentConnection = null; + try { + if (isExportTable) { + if (dbCon == null) { + try { + initializeCore(); + } catch (MPPDBIDEException exe) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_RESULT_INVALID_CONNECTION), + exe); + throw new DatabaseOperationException(IMessagesConstants.EXPORT_RESULT_INVALID_CONNECTION); + } + } + currentConnection = dbCon; + } else { + currentConnection = conn; + } + + String querySql = composeSQLQuery(); + tableNames = JSQLParserUtils.getSelectQueryMainTableName(querySql); + visitor = new GenerateCursorExecuteVisitor(newPath, encode, isOLAP, tableNames); + exportCursorExecuter = new ExportCursorQueryExecuter(querySql, currentConnection); + totalRows = exportCursorExecuter.exportSQLData(visitor); + } finally { + releaseConnection(); + } + + return totalRows; + } + + private void releaseConnection() { + if (dbCon != null && importExportServerObj.getConnectionManager() != null) { + importExportServerObj.getConnectionManager().releaseAndDisconnection(dbCon); + } + dbCon = null; + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + if (importExportServerObj instanceof TableMetaData) { + return ((TableMetaData) importExportServerObj).getDatabase(); + } + if (importExportServerObj instanceof Database) { + return (Database) importExportServerObj; + } + return null; + } + + /** + * Import export clean up. + */ + public void importExportCleanUp() { + setExportIsInProgress(false); + } + + + /** + * Sets the export is in progress. + * + * @param isExportIsInProgres the new export is in progress + */ + public void setExportIsInProgress(boolean isExportIsInProgres) { + this.isExportIsInProgress = isExportIsInProgres; + setChanged(); + notifyObservers(this.isExportIsInProgress); + } + + /** + * Clean up. + */ + public void cleanUpDataCore() { + if (visitor != null) { + visitor.cleanUpFileContent(); + } + } + + /** + * Gets the path. + * + * @return the path + */ + public Path getPath() { + return visitor.getPath(); + } + + /** + * Cancel export operation. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void cancelExportOperation() throws DatabaseCriticalException, DatabaseOperationException { + if (dbCon != null) { + dbCon.cancelQuery(); + } + if (isOLAPDB() && exportCursorExecuter != null) { + exportCursorExecuter.setCancelFlag(true); + } + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ICursorExecuteRecordVisitor.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ICursorExecuteRecordVisitor.java new file mode 100644 index 0000000000000000000000000000000000000000..7dcb586e1813dd1244dcf1f4d097b9abca7c578a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ICursorExecuteRecordVisitor.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.exportdata; + +import java.sql.ResultSet; +import java.text.ParseException; +import java.util.ArrayList; + +import org.opengauss.mppdbide.bl.serverdatacache.DefaultParameter; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; + +/** + * + * Title: interface + * + * Description: The Interface ICursorExecuteRecordVisitor. + * + * @since 3.0.0 + */ +public interface ICursorExecuteRecordVisitor { + + /** + * visits the Record + * + * @param rs the rs + * @param isFirstBatch the isFirstBatch + * @param isFirstBatchFirstRecord the isFirstBatchFirstRecord + * @param isFuncProcExport the isFuncProcExport + * @return the effected rows + * @throws ParseException the ParseException + * @throws MPPDBIDEException the MPPDBIDEException + */ + long visitRecord(ResultSet rs, boolean isFirstBatch, boolean isFirstBatchFirstRecord, boolean isFuncProcExport) + throws ParseException, MPPDBIDEException; + + /** + * gets the HeaderOfRecord + * + * @param rs the rs + * @param isFirstBatch the isFirstBatch + * @param isFuncProcExport the isFuncProcExport + * @throws ParseException the ParseException + * @throws MPPDBIDEException the MPPDBIDEException + */ + default void getHeaderOfRecord(ResultSet rs, boolean isFirstBatch, boolean isFuncProcExport) + throws ParseException, MPPDBIDEException { + return; + } + + /** + * visits the Record + * + * @param rs the rs + * @param isFirstBatch the isFirstBatch + * @param isFirstBatchFirstRecord the isFirstBatchFirstRecord + * @param inputDailogValueList the inputDailogValueList + * @param outResultList the outResultList + * @param isCursorResultSet the isCursorResultSet + * @param isFuncProcExport the isFuncProcExport + * @return the number of visited records + * @throws ParseException the ParseException + * @throws MPPDBIDEException the MPPDBIDEException + */ + long visitRecord(ResultSet rs, boolean isFirstBatch, boolean isFirstBatchFirstRecord, + ArrayList inputDailogValueList, ArrayList outResultList, + boolean isCursorResultSet, boolean isFuncProcExport) throws ParseException, MPPDBIDEException; + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ImportExcelApachePOI.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ImportExcelApachePOI.java new file mode 100644 index 0000000000000000000000000000000000000000..e573a3558050881cf7fc4311c9281f0fe2fb7620 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ImportExcelApachePOI.java @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.exportdata; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.List; + +import org.apache.poi.hssf.usermodel.HSSFDateUtil; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +import org.opengauss.mppdbide.bl.serverdatacache.ImportExportOption; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: ImportExcelApachePOI + * + * Description: The Class ImportExcelApachePOI. + * + * @since 3.0.0 + */ +public class ImportExcelApachePOI { + private ImportExportOption importExportoptions; + private HSSFSheet hssfSheet; + private XSSFSheet xssfSheet; + private String dateFormat; + private static final String EXCEL_XLSX = "EXCEL(xlsx)"; + + /** + * Instantiates a new import excel apache POI. + * + * @param importExportoptions the import exportoptions + */ + public ImportExcelApachePOI(ImportExportOption importExportoptions) { + this.importExportoptions = importExportoptions; + } + + /** + * Gets the cell values. + * + * @return the cell values + * @throws DatabaseOperationException the database operation exception + * @throws IOException Signals that an I/O exception has occurred. + * @Title: getCellValues + * @Description: Get excel cell values + */ + public List> getCellValues() throws DatabaseOperationException, IOException { + List> countList; + countList = new ArrayList>(); + dateFormat = importExportoptions.getDateSelector(); + int firstRow = 0; + if (importExportoptions.isHeader()) { + firstRow = 1; + } + + boolean isXLSX = false; + if (EXCEL_XLSX.equals(importExportoptions.getFileFormat())) { + isXLSX = true; + } + getExcelCellValues(firstRow, countList, isXLSX); + return countList; + } + + private void getExcelCellValues(int firstRow, List> countList, boolean isXLSX) + throws IOException, DatabaseOperationException { + Workbook workbook = null; + FileInputStream excelFile = null; + try { + excelFile = new FileInputStream(importExportoptions.getFileName()); + if (isXLSX) { + workbook = new XSSFWorkbook(excelFile); + xssfSheet = (XSSFSheet) workbook.getSheetAt(0); + if (null != xssfSheet && xssfSheet.getLastRowNum() > 0) { + for (int i = firstRow; i <= xssfSheet.getLastRowNum(); i++) { + XSSFRow xssfRow = xssfSheet.getRow(i); + if (xssfRow == null) { + continue; + } + countList.add(getCellList(xssfRow)); + } + } + } else { + workbook = new HSSFWorkbook(excelFile); + hssfSheet = (HSSFSheet) workbook.getSheetAt(0); + if (null != hssfSheet && hssfSheet.getLastRowNum() > 0) { + for (int i = firstRow; i <= hssfSheet.getLastRowNum(); i++) { + HSSFRow hssfRow = hssfSheet.getRow(i); + if (hssfRow == null) { + continue; + } + countList.add(getCellList(hssfRow)); + } + } + } + } catch (FileNotFoundException exception) { + MPPDBIDELoggerUtility.error("Import File not found", exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_IMPORT_TABLE_TO_EXCEL); + } finally { + try { + if (excelFile != null) { + excelFile.close(); + } + if (workbook != null) { + workbook.close(); + } + } catch (IOException ioException) { + MPPDBIDELoggerUtility.error("Import while get cell values", ioException); + excelFile = null; + } + } + } + + private ArrayList getCellList(HSSFRow hssfRow) { + ArrayList cellList = new ArrayList(); + for (int i = 0; i < importExportoptions.getTablecolumns().size(); i++) { + Cell cellObj = hssfRow.getCell(i); + cellList.add(getCellValue(cellObj)); + } + return cellList; + } + + private ArrayList getCellList(XSSFRow xssfRow) { + ArrayList cellList = new ArrayList(); + for (int j = 0; j < importExportoptions.getTablecolumns().size(); j++) { + Cell cellObj = xssfRow.getCell(j); + cellList.add(getCellValue(cellObj)); + } + return cellList; + } + + private String getCellValue(Cell cellObj) { + String cellValue = null; + if (cellObj == null) { + cellValue = ""; + } else if (cellObj.getCellType() == CellType.BOOLEAN) { + cellValue = String.valueOf(cellObj.getBooleanCellValue()); + } else if (cellObj.getCellType() == CellType.NUMERIC) { + if (HSSFDateUtil.isCellDateFormatted(cellObj)) { + SimpleDateFormat formatter = new SimpleDateFormat(dateFormat); + if (cellObj.getDateCellValue() != null) { + cellValue = formatter.format(cellObj.getDateCellValue()); + } + } else { + cellValue = String.valueOf(cellObj.getNumericCellValue()); + } + } else { + cellValue = cellObj.getStringCellValue(); + } + return cellValue; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ImportExcelExecuter.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ImportExcelExecuter.java new file mode 100644 index 0000000000000000000000000000000000000000..c38f5ce94bbdf079cd257997ec8bd8b51c596e12 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ImportExcelExecuter.java @@ -0,0 +1,542 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.exportdata; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.sql.Blob; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import org.apache.commons.lang3.BooleanUtils; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ImportExportOption; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.presentation.exportdata.ExportCursorExecuteVisitor.ColumnDataType; +import org.opengauss.mppdbide.utils.ConvertTimeValues; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: ImportExcelExecuter + * + * @since 3.0.0 + */ +public class ImportExcelExecuter { + private DBConnection dbCon; + private ImportExportOption importExportoptions; + private ServerObject importExportServerObj; + private ImportExcelApachePOI importExcelPOI; + private boolean cancelled = false; + private static final String DEFAULT_BOOL_VALUE = "FALSE"; + private static final int EXCEL_PARAM_MAXIMUM = 10000; + + /** + * Instantiates a new import excel executer. + * + * @param queryForImport the query for import + * @param dbCon the db con + * @param importExportoptions the import exportoptions + * @param importExportServerObj the import export server obj + */ + public ImportExcelExecuter(DBConnection dbCon, ImportExportOption importExportoptions, + ServerObject importExportServerObj) { + this.dbCon = dbCon; + this.importExportoptions = importExportoptions; + this.importExportServerObj = importExportServerObj; + this.importExcelPOI = new ImportExcelApachePOI(importExportoptions); + } + + /** + * Execute exc imp. + * + * @return the int + * @throws DatabaseOperationException the database operation exception + * @Title: executeExcImp + * @Description: Import data execution method + */ + public int executeExcImp() throws DatabaseOperationException { + int talCount = 0; + boolean failFlag = false; + try { + List> countList = importExcelPOI.getCellValues(); + talCount = countList.size(); + int excelCountMaximum = getPeriodExcuteMaxCount(countList); + if (!countList.isEmpty()) { + dbCon.getConnection().setAutoCommit(false); + if (excelCountMaximum == 0) { + periodExecuteExc(countList); + } else { + do { + List> subList = countList.subList(0, excelCountMaximum); + periodExecuteExc(subList); + countList.subList(0, excelCountMaximum).clear(); + } while (countList.size() > excelCountMaximum); + periodExecuteExc(countList); + } + dbCon.getConnection().commit(); + } + } catch (SQLException | DateTimeParseException exception) { + failFlag = true; + handleException(exception); + } catch (IOException ioException) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_DATABASE_OPERATION_FAILURE), ioException); + throw new DatabaseOperationException(IMessagesConstants.ERR_DATABASE_OPERATION_FAILURE, ioException); + } finally { + try { + if (failFlag) { + dbCon.getConnection().rollback(); + } + } catch (SQLException sqlException) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_DATABASE_OPERATION_FAILURE), + sqlException); + } + } + return talCount; + } + + /** + * Gets the period excute max count. + * + * @param countList the count list + * @return the period excute max count + * @Title: getPeriodExcuteMaxCount + * @Description: Get the maximum number of rows executed by the segment + */ + private int getPeriodExcuteMaxCount(List> countList) { + long allParam = countList.size() * (long) importExportoptions.getTablecolumns().size(); + if (allParam > EXCEL_PARAM_MAXIMUM) { + double periodCount = Math + .floor(EXCEL_PARAM_MAXIMUM / (double) (importExportoptions.getTablecolumns().size())); + return (int) periodCount; + } + return 0; + } + + /** + * Period execute exc. + * + * @param subList the sub list + * @throws DatabaseOperationException the database operation exception + * @Title: periodExecuteExc + * @Description: Period execute excel data + */ + + private void periodExecuteExc(List> subList) throws DatabaseOperationException { + List columnDataType = getColumnDatatype(); + String newQuery = composeBatchFormatSql(columnDataType.size(), subList, columnDataType); + try { + setValuesPeriodExecuteExc(subList, columnDataType, newQuery); + } catch (RuntimeException runex) { + throw runex; + } catch (Exception exception) { + handleException(exception); + } + } + + private void setValuesPeriodExecuteExc(List> subList, List columnDataType, + String newQuery) + throws DatabaseCriticalException, DatabaseOperationException, + UnsupportedEncodingException, SQLException, ParseException { + PreparedStatement preState = dbCon.getPrepareStmt(newQuery); + int kcount = 1; + try { + for (int index = 0; index < subList.size(); index++) { + kcount = setValuesPeriodExecuteExcInner(subList, columnDataType, preState, kcount, index); + } + String preparedStatementString = preState.toString(); + dbCon.closeStatement(preState); + preState = dbCon.getPrepareStmt(preparedStatementString); + validateForCancel(preState); + } finally { + dbCon.closeStatement(preState); + } + } + + private int setValuesPeriodExecuteExcInner(List> subList, List columnDataType, + PreparedStatement preState, int kcount, int index) + throws UnsupportedEncodingException, SQLException, ParseException { + int retCount = kcount; + for (int j = 0; j < columnDataType.size(); j++) { + String cellValue = getCellValue(subList, index, j); + switch (columnDataType.get(j)) { + case SMALLINT: { + preState.setObject(retCount++, Short.parseShort(cellValue)); + break; + } + case BOOLEAN: { + retCount = setBooleanValue(preState, retCount, cellValue); + break; + } + case MONEY: { + retCount = setMoneyTypeValue(preState, retCount, cellValue); + break; + } + case TIME: { + retCount = setTimeValue(preState, retCount, cellValue); + break; + } + case DATE: { + retCount = setDateValue(preState, retCount, cellValue); + break; + } + case TIMESTAMP: { + retCount = setTimeStampValue(preState, retCount, cellValue); + break; + } + case BLOB: { + Blob blob = null; + preState.setBlob(retCount++, blob); + break; + } + case BYTEA: { + preState.setBytes(retCount++, null); + break; + } + default: { + retCount = setDefaultValue(preState, retCount, cellValue); + break; + } + } + } + return retCount; + } + + private int setDefaultValue(PreparedStatement preState, int kcount, String cellValue) throws SQLException { + int retCount = kcount; + if (null == cellValue || cellValue.isEmpty()) { + preState.setObject(retCount++, null); + } else { + preState.setString(retCount++, cellValue); + } + return retCount; + } + + private int setMoneyTypeValue(PreparedStatement preState, int kcount, String cellValue) throws SQLException { + int retCount = kcount; + String value = cellValue; + if (null == value || value.isEmpty()) { + preState.setObject(retCount++, null); + } else { + if (value.charAt(0) == '$') { + value = value.substring(1, value.length()); + } + preState.setObject(retCount++, value, java.sql.Types.NUMERIC, 2); + } + return retCount; + } + + private int setTimeStampValue(PreparedStatement preState, int kcount, String cellValue) throws SQLException { + int retCount = kcount; + if (null == cellValue || cellValue.isEmpty()) { + preState.setTimestamp(retCount++, null); + } else { + DateTimeFormatter fommatter = getDateTimeFormatter(); + LocalDateTime dateTime; + dateTime = LocalDateTime.parse(cellValue, fommatter); + if (dateTime != null) { + Timestamp ts = Timestamp.valueOf(dateTime); + preState.setTimestamp(retCount++, ts); + } + } + return retCount; + } + + private int setDateValue(PreparedStatement preState, int kcount, String cellValue) + throws SQLException, ParseException { + int retCount = kcount; + if (null == cellValue || cellValue.isEmpty()) { + preState.setDate(retCount++, null); + } else { + String timeFormat = getDateFormatValue(importExportoptions.getDateSelector()); + SimpleDateFormat sdf = new SimpleDateFormat(timeFormat); + java.sql.Date date = new java.sql.Date(sdf.parse(cellValue).getTime()); + preState.setDate(retCount++, date); + } + return retCount; + } + + private int setTimeValue(PreparedStatement preState, int kcount, String cellValue) + throws SQLException, ParseException { + int retCount = kcount; + String timeFormat = getTimeFormatValue(importExportoptions.getDateSelector()); + SimpleDateFormat sdf = new SimpleDateFormat(timeFormat); + if (null == cellValue || cellValue.isEmpty()) { + preState.setTimestamp(retCount++, null); + } else { + Timestamp timestamp = new Timestamp(sdf.parse(cellValue).getTime()); + ConvertTimeValues value = new ConvertTimeValues(timestamp.getTime(), timeFormat); + preState.setTime(retCount++, value); + } + return retCount; + } + + private String getDateFormatValue(String dateSelector) { + String[] formatValues = dateSelector.split(" "); + return formatValues[0]; + } + + private String getTimeFormatValue(String dateSelector) { + String[] formatValues = dateSelector.split(" "); + return formatValues[formatValues.length - 1]; + } + + private void handleException(Exception exception) throws DatabaseOperationException { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DATABASE_OPERATION_FAILURE), + exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_DATABASE_OPERATION_FAILURE, exception); + } + + private String getCellValue(List> subList, int index, int j) throws UnsupportedEncodingException { + String cellValue = String.valueOf(subList.get(index).get(j)); + cellValue = getCelEncode(cellValue); + return cellValue; + } + + private DateTimeFormatter getDateTimeFormatter() { + DateTimeFormatter fommatter = DateTimeFormatter.ofPattern(importExportoptions.getDateSelector(), + Locale.ENGLISH); + return fommatter; + } + + private void validateForCancel(PreparedStatement preState) throws SQLException, DatabaseOperationException { + if (!cancelled) { + preState.execute(); + } else { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.USER_CANCEL_MSG)); + throw new DatabaseOperationException(IMessagesConstants.USER_CANCEL_MSG); + } + } + + private int setBooleanValue(PreparedStatement preState, int kcount, String cellValue) throws SQLException { + if (cellValue.equalsIgnoreCase("")) { + cellValue = DEFAULT_BOOL_VALUE; + } + preState.setBoolean(kcount++, BooleanUtils.toBooleanObject(cellValue)); + return kcount; + } + + /** + * Compose batch format sql. + * + * @param colCount the col count + * @param subList the sub list + * @return the string + * @Title: composeBatchFormatSql + * @Description: Compose batch import excel format SQL + */ + private String composeBatchFormatSql(int colCount, List> subList, + List columnDataType) { + StringBuffer queryBuff = new StringBuffer(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + if (colCount > 0) { + String query = composeImportExcelQuery(columnDataType, subList.get(0)); + queryBuff.append(query); + // insert into tab_name values(?,?,?) + for (int index = 1; index < subList.size(); index++) { + queryBuff.append(MPPDBIDEConstants.COMMA_SEPARATE); + queryBuff.append(MPPDBIDEConstants.LEFT_PARENTHESIS); + for (int j = 0; j < colCount; j++) { + if (ColumnDataType.BIT.equals(columnDataType.get(j))) { + String bitColValue = subList.get(index).get(j); + if (bitColValue.length() > 1) { + queryBuff.append("?::bit(" + bitColValue.length() + ")"); + } else { + queryBuff.append("?::bit"); + } + + } else { + queryBuff.append("?"); + } + queryBuff.append(MPPDBIDEConstants.COMMA_SEPARATE); + } + queryBuff.deleteCharAt(queryBuff.length() - 1); + queryBuff.append(MPPDBIDEConstants.RIGHT_PARENTHESIS); + } + } + return queryBuff.toString(); + } + + private String composeImportExcelQuery(List columnDataType, ArrayList colValueList) { + StringBuffer queryBuff = new StringBuffer(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + queryBuff.append("INSERT"); + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + queryBuff.append("INTO"); + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + queryBuff.append(this.importExportServerObj.getDisplayName()); + queryBuff.append(MPPDBIDEConstants.SPACE_CHAR); + if (!importExportoptions.isAllColunms()) { + queryBuff.append(MPPDBIDEConstants.LEFT_PARENTHESIS); + queryBuff.append(AbstractImportExportDataCore.getSelectedColumn(importExportoptions.getTablecolumns())); + queryBuff.append(MPPDBIDEConstants.RIGHT_PARENTHESIS); + } + queryBuff.append("VALUES"); + queryBuff.append(MPPDBIDEConstants.LEFT_PARENTHESIS); + queryBuff.append(formatSelectedColumn(importExportoptions.getTablecolumns(), columnDataType, colValueList)); + queryBuff.append(MPPDBIDEConstants.RIGHT_PARENTHESIS); + return queryBuff.toString(); + } + + /** + * Format selected column. + * + * @param tablecolumns the tablecolumns + * @return the object + * @Title: formatSelectedColumn + * @Description: Format table column value + */ + private String formatSelectedColumn(ArrayList tablecolumns, List columnDataType, + ListcolValueList) { + StringBuilder strBuild = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + for (int i = 0; i < tablecolumns.size(); i++) { + if (ColumnDataType.BIT.equals(columnDataType.get(i))) { + String bitColValue = colValueList.get(i); + if (bitColValue.length() > 1) { + strBuild.append("?::bit(" + bitColValue.length() + ")"); + } else { + strBuild.append("?::bit"); + } + } else { + strBuild.append("?"); + } + strBuild.append(MPPDBIDEConstants.COMMA_SEPARATE); + } + if (tablecolumns.size() > 0) { + strBuild.deleteCharAt(strBuild.length() - 1); + } + return strBuild.toString(); + } + + /** + * Gets the cel encode. + * + * @param cell the cell + * @return the cel encode + * @throws UnsupportedEncodingException the unsupported encoding exception + * @Title: getCelEncode + * @Description: Get the transcode string + */ + private String getCelEncode(String cell) throws UnsupportedEncodingException { + if (null != importExportoptions.getEncoding() && !importExportoptions.getEncoding().isEmpty()) { + byte[] content = cell.getBytes(importExportoptions.getEncoding()); + return new String(content, importExportoptions.getEncoding()); + } + return cell; + } + + /** + * Gets the column datatype. + * + * @return the column datatype + * @Title: getColumnDatatype + * @Description: Get the data type of the data table column + */ + private List getColumnDatatype() { + ArrayList columnDataTypeList = new ArrayList(); + ArrayList columnTypeList = new ArrayList(); + List columns = importExportoptions.getTablecolumns(); + if (importExportServerObj instanceof TableMetaData) { + for (int cnt = 0; cnt < columns.size(); cnt++) { + ColumnMetaData columnMetaData = ((TableMetaData) importExportServerObj).getColumns() + .get(columns.get(cnt)); + if (columnMetaData != null) { + columnTypeList.add(columnMetaData.getDataTypeName()); + } + } + } + handleColumnDataType(columnDataTypeList, columnTypeList); + return columnDataTypeList; + } + + private void handleColumnDataType(ArrayList columnDataTypeList, ArrayList columnTypeList) { + for (int indx = 0; indx < columnTypeList.size(); indx++) { + String columnType = columnTypeList.get(indx); + switch (columnType) { + case "int2": { + columnDataTypeList.add(ColumnDataType.SMALLINT); + break; + } + case "bool": { + columnDataTypeList.add(ColumnDataType.BOOLEAN); + break; + } + case "money": { + columnDataTypeList.add(ColumnDataType.MONEY); + break; + } + case "bit": { + columnDataTypeList.add(ColumnDataType.BIT); + break; + } + case "time": + case "timetz": { + columnDataTypeList.add(ColumnDataType.TIME); + break; + } + case "date": { + columnDataTypeList.add(ColumnDataType.DATE); + break; + } + case "timestamp": + case "timestamptz": + case "TIMESTAMP": { + columnDataTypeList.add(ColumnDataType.TIMESTAMP); + break; + } + case "BLOB": { + columnDataTypeList.add(ColumnDataType.BLOB); + break; + } + case MPPDBIDEConstants.BYTEA: { + columnDataTypeList.add(ColumnDataType.BYTEA); + break; + } + default: { + columnDataTypeList.add(ColumnDataType.STRING); + break; + } + } + } + } + + /** + * Sets the cancel flag. + * + * @param iscancel the new cancel flag + * @Title: setCancelFlag + * @Description: Set cancel query flag + */ + public void setCancelFlag(boolean iscancel) { + this.cancelled = iscancel; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ImportExportData.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ImportExportData.java new file mode 100644 index 0000000000000000000000000000000000000000..13fe57e7e54da985aa4f96c4628d2c27121acf99 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ImportExportData.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.exportdata; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.messaging.ProgressBarLabelFormatter; + +/** + * + * Title: class + * + * Description: The Class ImportExportDataCore. + * + * @since 3.0.0 + */ +public class ImportExportData extends AbstractImportExportData { + + private String displayTableName; + + /** + * Instantiates a new import export data core. + * + * @param obj the obj + */ + public ImportExportData(ServerObject obj) { + super(obj); + } + + /** + * Gets the display name. + * + * @return the display name + */ + @Override + public String getDisplayName() { + displayTableName = MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_TABLE_SUCESS, + ((TableMetaData) importExportServerObj).getDisplayName()); + return displayTableName; + } + + /** + * Gets the display table name. + * + * @return the display table name + */ + public String getDisplayTableName() { + displayTableName = MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_TABLE_SUCESS, + ((TableMetaData) importExportServerObj).getDisplayName()); + return displayTableName; + } + + /** + * Gets the progress label name. + * + * @return the progress label name + */ + public String getProgressLabelName() { + TableMetaData table = (TableMetaData) importExportServerObj; + displayTableName = ProgressBarLabelFormatter.getProgressLabelForTableWithoutMsg(table.getName(), + table.getNamespace().getName(), table.getDatabase().getDbName(), + table.getDatabase().getServer().getName()); + return displayTableName; + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + return ((TableMetaData) importExportServerObj).getDatabase(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ImportExportDataCore.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ImportExportDataCore.java new file mode 100644 index 0000000000000000000000000000000000000000..44adf8bcabf9e11e950ff7c5ba073728918deacd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportdata/ImportExportDataCore.java @@ -0,0 +1,197 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.exportdata; + +import java.text.ParseException; +import java.util.ArrayList; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.utils.CustomStringUtility; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; + +/** + * + * Title: class + * + * Description: The Class ImportExportDataCore. + * + * @since 3.0.0 + */ +public class ImportExportDataCore extends AbstractImportExportDataCore { + + private ImportExportData importExportData; + private ExportCursorQueryExecuter exportCursorExecuter; + + /** + * Instantiates a new import export data core. + * + * @param obj the obj + * @param clmList the clm list + * @param executedQuery the executed query + * @param terminalID the terminal ID + * @param querySubmitTime the query submit time + */ + public ImportExportDataCore(ServerObject obj, ArrayList clmList, String executedQuery, String terminalID, + String querySubmitTime) { + super(obj, clmList, executedQuery, terminalID, querySubmitTime); + importExportData = new ImportExportData(obj); + } + + /** + * Compose excel query. + * + * @return the string + */ + public String composeExcelQuery() { + StringBuffer queryBuff = new StringBuffer(); + if (importExportServerObj instanceof TableMetaData) { + importExportData.composeExcelQuery(queryBuff, importExportoptions); + } else { + composeExcelQuery(queryBuff); + } + return queryBuff.toString(); + } + + /** + * Append delimiter option. + * + * @param queryBuff the query buff + */ + protected void appendDelimiterOption(StringBuffer queryBuff) { + super.appendDelimiterOption(queryBuff); + if (importExportServerObj instanceof TableMetaData) { + importExportData.appendQueryFormatForCsvFormat(queryBuff); + } + } + + /** + * Append tbl name or executed query. + * + * @param queryBuff the query buff + */ + protected void appendTblNameOrExecutedQuery(StringBuffer queryBuff) { + super.appendTblNameOrExecutedQuery(queryBuff); + if (importExportServerObj instanceof TableMetaData) { + importExportData.appaendTblNameOrExecutedQuery(queryBuff, importExportoptions); + } + } + + /** + * Cancel import export operation. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void cancelImportExportOperation() throws DatabaseCriticalException, DatabaseOperationException { + super.cancelImportExportOperation(); + if (isOLAPDB() && exportCursorExecuter != null) { + exportCursorExecuter.setCancelFlag(true); + } + } + + /** + * Gets the file name. + * + * @return the file name + */ + public String getFileName() { + String fileName = super.getFileName(); + if (importExportServerObj instanceof TableMetaData) { + fileName = importExportData.getFileName(); + } + return CustomStringUtility.sanitizeExportFileName(fileName); + } + + /** + * Gets the safe sheet name. + * + * @return the safe sheet name + */ + public String getSafeSheetName() { + String fileName = super.getSafeSheetName(); + if (importExportServerObj instanceof TableMetaData) { + fileName = importExportData.getFileName(); + } + return CustomStringUtility.sanitizeExcelSheetName(fileName); + } + + /** + * Gets the display table name. + * + * @return the display table name + */ + public String getDisplayTableName() { + super.getDisplayTableName(); + if (importExportServerObj instanceof TableMetaData) { + displayTableName = importExportData.getDisplayTableName(); + } + return displayTableName; + } + + /** + * Gets the display name. + * + * @return the display name + */ + public String getDisplayName() { + displayTableName = super.getDisplayName(); + if (importExportServerObj instanceof TableMetaData) { + displayTableName = importExportData.getDisplayName(); + } + return displayTableName; + } + + /** + * Gets the progress label name. + * + * @return the progress label name + */ + public String getProgressLabelName() { + displayTableName = super.getProgressLabelName(); + if (importExportServerObj instanceof TableMetaData) { + displayTableName = importExportData.getProgressLabelName(); + } + return displayTableName; + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + Database database = super.getDatabase(); + if (importExportServerObj instanceof TableMetaData) { + database = importExportData.getDatabase(); + } + return database; + } + + @Override + protected long getExportExcelTotalRows(DBConnection currentConnection, boolean isFuncProcExport) + throws ParseException, MPPDBIDEException { + String queryForExport = composeExcelQuery(); + exportCursorExecuter = new ExportCursorQueryExecuter(queryForExport, currentConnection); + long totalRows = exportCursorExecuter.exportExcelData(visitor, isFuncProcExport); + return totalRows; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportimportdsconnectionprofiles/ExportConnectionCore.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportimportdsconnectionprofiles/ExportConnectionCore.java new file mode 100644 index 0000000000000000000000000000000000000000..66bd3e8e5d017abf888f84d65c32bd2f3a003652 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportimportdsconnectionprofiles/ExportConnectionCore.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.exportimportdsconnectionprofiles; + +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class ExportConnectionCore. + * + * @since 3.0.0 + */ +public class ExportConnectionCore { + + private String filePath; + private List loadedProfileList; + private List selectedProfilesIndexes; + + /** + * Sets the file output path. + * + * @param path the new file output path + */ + public void setFileOutputPath(String path) { + this.filePath = path; + + } + + /** + * Gets the file output path. + * + * @return the file output path + */ + public String getFileOutputPath() { + return this.filePath; + } + + /** + * Export files. + * + * @param serverConnInfoList the server conn info list + */ + public void setExportProfilesIndexList(List indexList) { + this.selectedProfilesIndexes = indexList; + } + + /** + * Gets the export file list. + * + * @return the export file list + */ + public List getExportFileList() { + List serverConnInfoList = new ArrayList( + MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + if (selectedProfilesIndexes != null && loadedProfileList != null) { + selectedProfilesIndexes.stream().forEach(item -> { + serverConnInfoList.add(loadedProfileList.get(item)); + }); + } + return serverConnInfoList; + } + + /** + * Gets the loaded profile list. + * + * @return the loaded profile list + */ + public List getLoadedProfileList() { + if (loadedProfileList != null) { + return loadedProfileList; + } + return new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + } + + /** + * Sets the loaded profile list. + * + * @param loadedProfileList the new loaded profile list + */ + public void setLoadedProfileList(List loadedProfileList) { + this.loadedProfileList = loadedProfileList; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportimportdsconnectionprofiles/ImportConnectionProfileCore.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportimportdsconnectionprofiles/ImportConnectionProfileCore.java new file mode 100644 index 0000000000000000000000000000000000000000..ede40d471e993ea662b011eb4425036079e8c60c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportimportdsconnectionprofiles/ImportConnectionProfileCore.java @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.exportimportdsconnectionprofiles; + +import java.io.IOException; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DataStudioSecurityException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class ImportConnectionProfileCore. + * + * @since 3.0.0 + */ +public class ImportConnectionProfileCore { + private String sourcePath; + private double fileSizeLimit; + private List uniqueList; + private List sourceList; + private List destinationList; + private List matchedList; + + /** + * Instantiates a new import connection profile core. + * + * @param sourceFilePath the source file path + * @param sourceFileSizeLimit the file data size limit + */ + public ImportConnectionProfileCore(String sourceFilePath, double sourceFileSizeLimit) { + sourcePath = sourceFilePath; + fileSizeLimit = sourceFileSizeLimit; + uniqueList = new LinkedList(); + matchedList = new LinkedList(); + } + + /** + * Import files. + * + * @throws DatabaseOperationException the database operation exception + */ + public void importFiles() throws DatabaseOperationException { + ConnectionProfileManagerImpl connectionManager = ConnectionProfileManagerImpl.getInstance(); + compareFiles(readSourceFiles(connectionManager), readDestinationFile(connectionManager)); + } + + private List readSourceFiles(ConnectionProfileManagerImpl connectionManager) + throws DatabaseOperationException { + sourceList = connectionManager.importConnectionProfiles(sourcePath, fileSizeLimit); + + return sourceList; + } + + private List readDestinationFile(ConnectionProfileManagerImpl connectionManager) + throws DatabaseOperationException { + try { + destinationList = connectionManager.getAllProfiles(); + } catch (DataStudioSecurityException | IOException exe) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.ERROR_IMPORTING_CONNECTION_PROFILES), exe); + throw new DatabaseOperationException( + MessageConfigLoader.getProperty(IMessagesConstants.ERROR_IMPORTING_CONNECTION_PROFILES), exe); + } + + return destinationList; + } + + private void compareFiles(List sourceList, List destinationList) { + Map destinationProfileMap = new HashMap<>(); + for (IServerConnectionInfo info : destinationList) { + destinationProfileMap.put(info.getConectionName(), info); + } + for (IServerConnectionInfo info : sourceList) { + if (destinationProfileMap.containsKey(info.getConectionName())) { + MatchedConnectionProfiles matchingProfiles = new MatchedConnectionProfiles(); + matchingProfiles.setDestProfile(destinationProfileMap.get(info.getConectionName())); + matchingProfiles.setSourceProfile(info); + matchedList.add(matchingProfiles); + + } else { + uniqueList.add(info); + } + } + + } + + /** + * Gets the original destination list. + * + * @return the original destination list + */ + public List getOriginalDestinationList() { + return this.destinationList; + } + + /** + * Gets the unique list. + * + * @return the unique list + */ + public List getUniqueList() { + return this.uniqueList; + } + + /** + * Gets the matched profiles list. + * + * @return the matched profiles list + */ + public List getMatchedProfilesList() { + return this.matchedList; + } + + /** + * + * Title: class + * + * Description: The Class MatchedConnectionProfiles. + */ + public static class MatchedConnectionProfiles { + private IServerConnectionInfo sourceProfile; + private IServerConnectionInfo destProfile; + + /** + * Gets the source profile. + * + * @return the source profile + */ + public IServerConnectionInfo getSourceProfile() { + return sourceProfile; + } + + /** + * Sets the source profile. + * + * @param sourceProfile the new source profile + */ + public void setSourceProfile(IServerConnectionInfo sourceProfile) { + this.sourceProfile = sourceProfile; + } + + /** + * Gets the dest profile. + * + * @return the dest profile + */ + public IServerConnectionInfo getDestProfile() { + return destProfile; + } + + /** + * Sets the dest profile. + * + * @param destProfile the new dest profile + */ + public void setDestProfile(IServerConnectionInfo destProfile) { + this.destProfile = destProfile; + } + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportimportdsconnectionprofiles/ImportConnectionProfileManager.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportimportdsconnectionprofiles/ImportConnectionProfileManager.java new file mode 100644 index 0000000000000000000000000000000000000000..4b2ce47092635838d293623322e47705d07e9e0a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportimportdsconnectionprofiles/ImportConnectionProfileManager.java @@ -0,0 +1,240 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.exportimportdsconnectionprofiles; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; +import org.opengauss.mppdbide.presentation.exportimportdsconnectionprofiles.ImportConnectionProfileCore.MatchedConnectionProfiles; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DataStudioSecurityException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class ImportConnectionProfileManager. + * + * @since 3.0.0 + */ +public class ImportConnectionProfileManager { + + List copyList; + Map replaceMap; + private ImportConnectionProfileCore core; + + /** + * Instantiates a new import connection profile manager. + * + * @param core the core + */ + public ImportConnectionProfileManager(ImportConnectionProfileCore core) { + this.core = core; + copyList = new LinkedList<>(); + replaceMap = new HashMap(); + } + + /** + * Merge all profiles. + * + * @throws DatabaseOperationException the database operation exception + */ + public void mergeAllProfiles() throws DatabaseOperationException { + + List allProfiles = core.getOriginalDestinationList(); + List importedProfilesList = core.getUniqueList(); + List finalListOfProfiles = new LinkedList(); + try { + int maxProfileId = Integer.parseInt(calculateMaxProfileValue(allProfiles)); + int maxID = maxProfileId; + for (IServerConnectionInfo info : importedProfilesList) { + ++maxID; + info.setProfileId("" + maxID); + finalListOfProfiles.add(info); + + } + + ConnectionProfileManagerImpl instance = ConnectionProfileManagerImpl.getInstance(); + if (!finalListOfProfiles.isEmpty()) { + instance.mergeImportedProfiles(finalListOfProfiles, allProfiles); + } + if (!copyList.isEmpty()) { + updateCopyList(allProfiles); + instance.mergeImportedProfiles(copyList, allProfiles); + } + + if (!replaceMap.isEmpty()) { + Iterator> iterator = replaceMap.entrySet().iterator(); + while (iterator.hasNext()) { + Entry next = iterator.next(); + updateReplaceProfilesList(allProfiles, next); + instance.replaceWithImportedProfiles(next.getValue().getDestProfile(), + next.getValue().getSourceProfile(), allProfiles); + } + } + } catch (NumberFormatException exp) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.ERROR_IMPORTING_CONNECTION_PROFILES), exp); + throw new DatabaseOperationException( + MessageConfigLoader.getProperty(IMessagesConstants.ERROR_IMPORTING_CONNECTION_PROFILES)); + } catch (DataStudioSecurityException exp) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.ERROR_IMPORTING_CONNECTION_PROFILES), exp); + throw new DatabaseOperationException( + MessageConfigLoader.getProperty(IMessagesConstants.ERROR_IMPORTING_CONNECTION_PROFILES)); + } + + } + + private void updateReplaceProfilesList(List allProfiles, + Entry entry) { + MatchedConnectionProfiles value = entry.getValue(); + String profileId = value.getDestProfile().getProfileId(); + String profileId2 = value.getSourceProfile().getProfileId(); + if (!profileId.equals(profileId2)) { + IServerConnectionInfo serverConnectionInfo = value.getSourceProfile(); + int updateProfileID = findLeastAvailableProFileID(allProfiles); + serverConnectionInfo.setProfileId("" + updateProfileID); + } + } + + private int findLeastAvailableProFileID(List allProfiles) { + List originalPorfileIDList = allProfiles.stream().map(entry -> Integer.parseInt(entry.getProfileId())) + .collect(Collectors.toList()); + + return evaluateMinValue(originalPorfileIDList); + } + + private int evaluateMinValue(List profiles) { + int minValue = 0; + Collections.sort(profiles); + for (Integer val : profiles) { + ++minValue; + if (val != minValue) { + break; + } + + } + + if (minValue == 0 || minValue == profiles.get(minValue - 1)) { + ++minValue; + } + + return minValue; + } + + private void updateCopyList(List allProfiles) { + int maxProfileID = Integer.parseInt(calculateMaxProfileValue(allProfiles)); + for (IServerConnectionInfo info : copyList) { + ++maxProfileID; + info.setProfileId("" + maxProfileID); + + handleConnectionName(allProfiles, info); + allProfiles.add(info); + } + } + + private void handleConnectionName(List allProfiles, IServerConnectionInfo info) { + String copyString = info.getConectionName(); + copyString = copyString.replaceAll("\\((\\d+)\\)", ""); + Pattern pattern = Pattern.compile(Pattern.quote(copyString) + "\\((\\d+)\\)"); + Matcher matcher = null; + List collect = new ArrayList<>(); + for (IServerConnectionInfo prof : allProfiles) { + matcher = pattern.matcher(prof.getConectionName()); + if (matcher.matches() && !matcher.group(1).isEmpty()) { + collect.add(Integer.parseInt(matcher.group(1))); + } + } + int minValue = evaluateMinValue(collect); + + info.setConectionName(copyString + "(" + minValue + ")"); + } + + private String calculateMaxProfileValue(List profilesList) { + if (profilesList.isEmpty()) { + return "" + 0; + } + List collect = profilesList.stream().map(entry -> Integer.parseInt(entry.getProfileId())) + .collect(Collectors.toList()); + Integer integer = collect.stream().max(Integer::compare).get(); + return "" + integer; + } + + /** + * Adds the profiles to be overriden. + * + * @param matchedProfiles the matched profiles + * @param option the option + */ + public void addProfilesToBeOverriden(MatchedConnectionProfiles matchedProfiles, OverridingOptions option) { + if (option == OverridingOptions.COPYANDKEEPBOTH) { + copyList.add(matchedProfiles.getSourceProfile()); + } else if (option == OverridingOptions.REPLACE) { + String sourceProfconectionName = matchedProfiles.getSourceProfile().getConectionName(); + if (!replaceMap.containsKey(sourceProfconectionName)) { + replaceMap.put(sourceProfconectionName, matchedProfiles); + } + + } else { + return; + } + + } + + /** + * Handle all profiles with conflicts. + * + * @param option the option + */ + public void handleAllProfilesWithConflicts(OverridingOptions option) { + if (OverridingOptions.COPYANDKEEPBOTH == option) { + List matchedList = core.getMatchedProfilesList(); + for (MatchedConnectionProfiles matchedProfile : matchedList) { + if (!copyList.contains(matchedProfile.getSourceProfile()) + && !replaceMap.containsKey(matchedProfile.getSourceProfile().getConectionName())) { + copyList.add(matchedProfile.getSourceProfile()); + } + } + } else if (OverridingOptions.REPLACE == option) { + List matchedProfilesList = core.getMatchedProfilesList(); + for (MatchedConnectionProfiles matchedProfiles : matchedProfilesList) { + + String conectionName = matchedProfiles.getSourceProfile().getConectionName(); + if (!copyList.contains(matchedProfiles.getSourceProfile()) && !replaceMap.containsKey(conectionName)) { + replaceMap.put(conectionName, matchedProfiles); + } + } + } else { + return; + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportimportdsconnectionprofiles/OverridingOptions.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportimportdsconnectionprofiles/OverridingOptions.java new file mode 100644 index 0000000000000000000000000000000000000000..78185e9a97afb43fa36b4e0835121bbc2e4b0e94 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/exportimportdsconnectionprofiles/OverridingOptions.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.exportimportdsconnectionprofiles; + +/** + * + * Title: enum + * + * Description: The Enum OverridingOptions. + * + * @since 3.0.0 + */ +public enum OverridingOptions { + + REPLACE, COPYANDKEEPBOTH, DONTCOPY; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IDSEditGridDataProvider.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IDSEditGridDataProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..1389eafbbdaf60789afac05801a68f3cb0c5bbd2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IDSEditGridDataProvider.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.grid; + +import java.util.List; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.presentation.edittabledata.CommitStatus; +import org.opengauss.mppdbide.presentation.edittabledata.IDSGridEditDataRow; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; + +/** + * + * Title: interface + * + * Description: The Interface IDSEditGridDataProvider. + * + * @since 3.0.0 + */ +public interface IDSEditGridDataProvider extends IDSGridDataProvider { + + /** + * Checks if is edits the supported. + * + * @return true, if is edits the supported + */ + boolean isEditSupported(); + + /** + * Commit. + * + * @param uniqueKeys the unique keys + * @param isAtomic the is atomic + * @param rowEffectedConfirm the row effected confirm + * @param termConnection the term connection + * @return the commit status + * @throws MPPDBIDEException the MPPDBIDE exception + */ + CommitStatus commit(List uniqueKeys, boolean isAtomic, IRowEffectedConfirmation rowEffectedConfirm, + DBConnection termConnection) throws MPPDBIDEException; + + /** + * Roll back. + */ + void rollBackProvider(); + + /** + * Checks if is unique key present. + * + * @return true, if is unique key present + */ + default boolean isUniqueKeyPresent() { + return false; + } + + /** + * Gets the empty row for insert. + * + * @param index the index + * @return the empty row for insert + */ + IDSGridEditDataRow getEmptyRowForInsert(int index); + + /** + * Delete record. + * + * @param row the row + * @param isInserted the is inserted + */ + void deleteRecord(IDSGridEditDataRow row, boolean isInserted); + + /** + * Gets the last commit status. + * + * @return the last commit status + */ + default CommitStatus getLastCommitStatus() { + return null; + } + + /** + * Checks if is distribution columns required. + * + * @return true, if is distribution columns required + */ + default boolean isDistributionColumnsRequired() { + return false; + } + + /** + * Checks if is grid data edited. + * + * @return true, if is grid data edited + */ + boolean isGridDataEdited(); + + /** + * Gets the distributed column list. + * + * @return the distributed column list + */ + default List getDistributedColumnList() { + return null; + } + + /** + * Gets the consolidated rows. + * + * @return the consolidated rows + */ + List getConsolidatedRows(); + + /** + * Gets the updated row count. + * + * @return the updated row count + */ + int getUpdatedRowCount(); + + /** + * Gets the inserted row count. + * + * @return the inserted row count + */ + int getInsertedRowCount(); + + /** + * Gets the deleted row count. + * + * @return the deleted row count + */ + int getDeletedRowCount(); + + /** + * Cancel commit. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + void cancelCommit() throws DatabaseCriticalException, DatabaseOperationException; + + /** + * Checks if is cancelled. + * + * @return true, if is cancelled + */ + default boolean isCancelled() { + return false; + } + + /** + * Sets the cancel. + * + * @param cancel the new cancel + */ + default void setCancel(boolean cancel) { + + } + + /** + * Checks if is distribution column. + * + * @param columnIndex the column index + * @return true, if is distribution column + */ + default boolean isDistributionColumn(int columnIndex) { + return false; + } + + /** + * Gets the table name. + * + * @return the table name + */ + default String getTableName() { + return ""; + } + + /** + * Gets the column count. + * + * @return the column count + */ + default int getColumnCount() { + return 0; + } + + /** + * Gets the column names. + * + * @return the column names + */ + default List getColumnNames() { + return null; + } + + /** + * Gets the column data type names. + * + * @return the column data type names + */ + default List getColumnDataTypeNames() { + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IDSGridColumnGroupProvider.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IDSGridColumnGroupProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..d2213523f5185f91a9b4d36b53032c5aa4f5e849 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IDSGridColumnGroupProvider.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.grid; + +/** + * + * Title: interface + * + * Description: The Interface IDSGridColumnGroupProvider. + * + * @since 3.0.0 + */ +public interface IDSGridColumnGroupProvider { + + /** + * Gets the group count. + * + * @return the group count + */ + int getGroupCount(); + + /** + * Gets the column group name. + * + * @param idx the idx + * @return the column group name + */ + String getColumnGroupName(int idx); + + /** + * Gets the column index in group. + * + * @param idx the idx + * @return the column index in group + */ + int[] getColumnIndexInGroup(int idx); + + /** + * Gets the column group index. + * + * @param columnIndex the column index + * @return the column group index + */ + int getColumnGroupIndex(int columnIndex); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IDSGridColumnProvider.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IDSGridColumnProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..25e40138baec983c4892628dc06b197455393634 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IDSGridColumnProvider.java @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.grid; + +import java.util.Comparator; + +/** + * + * Title: interface + * + * Description: The Interface IDSGridColumnProvider. + * + * @since 3.0.0 + */ +public interface IDSGridColumnProvider { + + /** + * Gets the column count. + * + * @return the column count + */ + int getColumnCount(); + + /** + * Gets the column names. + * + * @return the column names + */ + String[] getColumnNames(); + + /** + * Gets the column name. + * + * @param columnIndex the column index + * @return the column name + */ + String getColumnName(int columnIndex); + + /** + * Gets the column desc. + * + * @param columnIndex the column index + * @return the column desc + */ + String getColumnDesc(int columnIndex); + + /** + * Gets the column index. + * + * @param columnLabel the column label + * @return the column index + */ + int getColumnIndex(String columnLabel); + + /** + * Gets the comparator. + * + * @param columnIndex the column index + * @return the comparator + */ + Comparator getComparator(int columnIndex); + + /** + * Gets the column datatype. + * + * @param columnIndex the column index + * @return the column datatype + */ + int getColumnDatatype(int columnIndex); + + /** + * Gets the column data type name. + * + * @param columnIndex the column index + * @return the column data type name + */ + String getColumnDataTypeName(int columnIndex); + + /** + * Gets the precision. + * + * @param columnIndex the column index + * @return the precision + */ + int getPrecision(int columnIndex); + + /** + * Gets the scale. + * + * @param columnIndex the column index + * @return the scale + */ + int getScale(int columnIndex); + + /** + * Gets the max length. + * + * @param columnIndex the column index + * @return the max length + */ + int getMaxLength(int columnIndex); + + /** + * Gets the column comment. + * + * @param columnIndex the column index + * @return the column comment + */ + default String getColumnComment(int columnIndex) { + return null; + } + + /** + * Gets the column default value. + * + * @param i the i + * @return the column default value + */ + String getDefaultValue(int i); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IDSGridDataAccessListenable.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IDSGridDataAccessListenable.java new file mode 100644 index 0000000000000000000000000000000000000000..ac2df46ed543b9ca8882b60c32d895ce53c9327f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IDSGridDataAccessListenable.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.grid; + +import org.opengauss.mppdbide.bl.serverdatacache.DefaultParameter; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.observer.IDSListenable; + +/** + * + * Title: interface + * + * Description: The Interface IDSGridDataAccessListenable. + * + * @since 3.0.0 + */ +public interface IDSGridDataAccessListenable extends IDSListenable { + int LISTEN_TYPE_POST_FETCH = 1; + int LISTEN_TYPE_ENDOF_RS = 2; + int LISTEN_TYPE_ABOUTTO_REEXECUTE_QUERY = 3; + + /** + * visits the InputValues + * + * @param dp the dp + * @param index the index + * @throws DatabaseOperationException the DatabaseOperationException + * @throws DatabaseCriticalException the DatabaseCriticalException + */ + void visitInputValues(DefaultParameter dp, int index) throws DatabaseOperationException, DatabaseCriticalException; + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IDSGridDataProvider.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IDSGridDataProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..7fe412fd21de2cfc111dbe31203df8b71455beae --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IDSGridDataProvider.java @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.grid; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DefaultParameter; +import org.opengauss.mppdbide.bl.serverdatacache.IQueryResult; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.observer.IDSListenable; + +/** + * + * Title: interface + * + * Description: The Interface IDSGridDataProvider. + * + * @since 3.0.0 + */ +public interface IDSGridDataProvider extends IDSListenable { + + /** + * Inits the. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + void init() throws DatabaseOperationException, DatabaseCriticalException; + + /** + * Close. + * + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + default void close() throws DatabaseOperationException, DatabaseCriticalException { + + } + + /** + * Gets the next batch. + * + * @return the next batch + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + default List getNextBatch() throws DatabaseOperationException, DatabaseCriticalException { + return null; + } + + /** + * Gets the all fetched rows. + * + * @return the all fetched rows + */ + List getAllFetchedRows(); + + /** + * Checks if is end of records. + * + * @return true, if is end of records + */ + boolean isEndOfRecords(); + + /** + * Gets the record count. + * + * @return the record count + */ + int getRecordCount(); + + /** + * Gets the column data provider. + * + * @return the column data provider + */ + IDSGridColumnProvider getColumnDataProvider(); + + /** + * Pre destroy. + */ + default void preDestroy() { + + } + + /** + * Gets the column group provider. + * + * @return the column group provider + */ + default IDSGridColumnGroupProvider getColumnGroupProvider() { + return null; + } + + /** + * Gets the table. + * + * @return the table + */ + ServerObject getTable(); + + /** + * Gets the data base. + * + * @return the data base + */ + Database getDatabse(); + + /** + * Gets the result tab dirty flag. + * + * @return the result tab dirty flag + */ + boolean getResultTabDirtyFlag(); + + /** + * Sets the result tab dirty flag. + * + * @param flag the new result tab dirty flag + */ + void setResultTabDirtyFlag(boolean flag); + + /** + * init + * + * @param irq the irq + * @param debugInputValueList the debugInputValueList + * @param isCallableStmt the isCallableStmt + * @throws DatabaseOperationException the DatabaseOperationException + * @throws DatabaseCriticalException the DatabaseCriticalException + * @throws SQLException the SQLException + */ + void init(IQueryResult irq, ArrayList debugInputValueList, boolean isCallableStmt) + throws DatabaseOperationException, DatabaseCriticalException, SQLException; + + /** + * get next batch + * + * @param debugInputValueList the debugInputValueList + * @return next batch object + * @throws DatabaseOperationException the DatabaseOperationException + * @throws DatabaseCriticalException the DatabaseCriticalException + * @throws SQLException the SQLException + */ + List getNextBatch(ArrayList debugInputValueList) + throws DatabaseOperationException, DatabaseCriticalException, SQLException; + + /** + * sets the setFuncProcExport flag + * + * @param isFuncProcExport the isFuncProcExport flag + */ + void setFuncProcExport(boolean isFuncProcExport); + + /** + * gets the setFuncProcExport flag + * + * @return isFuncProcExport the isFuncProcExport flag + */ + boolean isFuncProcExport(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IDSGridDataRow.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IDSGridDataRow.java new file mode 100644 index 0000000000000000000000000000000000000000..d53eb4947392db351cde03f3c2ebe17d2be51198 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IDSGridDataRow.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.grid; + +/** + * + * Title: interface + * + * Description: The Interface IDSGridDataRow. + * + * @since 3.0.0 + */ +public interface IDSGridDataRow { + + /** + * Gets the values. + * + * @return the values + */ + Object[] getValues(); + + /** + * Gets the value. + * + * @param columnIndex the column index + * @return the value + */ + Object getValue(int columnIndex); + + /** + * Gets the cloned values. + * + * @return the cloned values + */ + Object[] getClonedValues(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IDSResultRowVisitor.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IDSResultRowVisitor.java new file mode 100644 index 0000000000000000000000000000000000000000..931928e09e3b5192f02598a4c550ea3b5ac3fa1d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IDSResultRowVisitor.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.grid; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.bl.serverdatacache.DefaultParameter; +import org.opengauss.mppdbide.presentation.edittabledata.DSResultSetGridDataRow; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: interface + * + * Description: The Interface IDSResultRowVisitor. + * + * @since 3.0.0 + */ +public interface IDSResultRowVisitor { + + /** + * the visit + * + * @param rs the rs + * @param isfuncProcResultFlow the isfuncProcResultFlow + * @param isCursorType the isCursorType + * @param arrayList the arrayList + * @throws DatabaseOperationException the DatabaseOperationException + * @throws DatabaseCriticalException the DatabaseCriticalException + * @throws SQLException the SQLException + */ + void visit(ResultSet rs, boolean isfuncProcResultFlow, boolean isCursorType, Object[] arrayList) + throws DatabaseOperationException, DatabaseCriticalException, SQLException; + + /** + * the visit + * + * @param rs the rs + * @throws DatabaseOperationException the DatabaseOperationException + * @throws DatabaseCriticalException the DatabaseCriticalException + * @throws SQLException the SQLException + */ + void visit(ResultSet rs) throws DatabaseOperationException, DatabaseCriticalException, SQLException; + + /** + * the visit + * + * @param gridDataRow the gridDataRow + * @throws DatabaseOperationException the DatabaseOperationException + * @throws DatabaseCriticalException the DatabaseCriticalException + * @throws SQLException the SQLException + */ + void visit(DSResultSetGridDataRow gridDataRow) + throws DatabaseOperationException, DatabaseCriticalException, SQLException; + + /** + * Sets the end of records. + */ + void setEndOfRecords(); + + /** + * Checks if is end of records. + * + * @return true, if is end of records + */ + boolean isEndOfRecords(); + + /** + * visit input values + * + * @param dp the dp + * @param index the + * @throws DatabaseOperationException the DatabaseOperationException + * @throws DatabaseCriticalException the DatabaseCriticalException + */ + void visitInputValues(DefaultParameter dp, int index) throws DatabaseOperationException, DatabaseCriticalException; + + /** + * visits the UnNameCursor + * + * @param rs the rs + * @throws DatabaseOperationException the DatabaseOperationException + * @throws DatabaseCriticalException the DatabaseCriticalException + * @throws SQLException the SQLException + */ + void visitUnNameCursor(ResultSet rs) throws DatabaseOperationException, DatabaseCriticalException, SQLException; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IRowEffectedConfirmation.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IRowEffectedConfirmation.java new file mode 100644 index 0000000000000000000000000000000000000000..ff2dfa6bb3ec306fea034dab797aa2084536e09a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/IRowEffectedConfirmation.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.grid; + +/** + * + * Title: interface + * + * Description: The Interface IRowEffectedConfirmation. + * + * @since 3.0.0 + */ +public interface IRowEffectedConfirmation { + + /** + * Prompt uer confirmation. + */ + void promptUerConfirmation(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/batchdrop/BatchDropColumnProvider.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/batchdrop/BatchDropColumnProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..fcd891e36da08398d671a4fe10c7d917da35e1fe --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/batchdrop/BatchDropColumnProvider.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.grid.batchdrop; + +import java.sql.Types; +import java.util.Comparator; + +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.presentation.grid.resultset.ColumnValueSqlTypeComparator; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class BatchDropColumnProvider. + * + * @since 3.0.0 + */ +public class BatchDropColumnProvider implements IDSGridColumnProvider { + private int columnCount = 5; + private String[] columnNames; + + /** + * Instantiates a new batch drop column provider. + */ + public BatchDropColumnProvider() { + this.columnNames = new String[] { + MessageConfigLoader.getProperty(IMessagesConstants.DROP_OBJECTS_NATTABLE_COLUMN_TYPE), + MessageConfigLoader.getProperty(IMessagesConstants.DROP_OBJECTS_NATTABLE_COLUMN_NAME), + MessageConfigLoader.getProperty(IMessagesConstants.DROP_OBJECTS_NATTABLE_COLUMN_QUERY), + MessageConfigLoader.getProperty(IMessagesConstants.DROP_OBJECTS_NATTABLE_COLUMN_STATUS), + MessageConfigLoader.getProperty(IMessagesConstants.DROP_OBJECTS_NATTABLE_COLUMN_ERR_MSG)}; + } + + @Override + public int getColumnCount() { + return columnCount; + } + + @Override + public String[] getColumnNames() { + return this.columnNames.clone(); + } + + @Override + public String getColumnName(int columnIndex) { + return this.columnNames[columnIndex]; + } + + @Override + public String getColumnDesc(int columnIndex) { + return getColumnName(columnIndex); + } + + @Override + public int getColumnIndex(String columnLabel) { + return 0; + } + + @Override + public Comparator getComparator(int columnIndex) { + return new ColumnValueSqlTypeComparator(Types.VARCHAR); + } + + @Override + public int getColumnDatatype(int columnIndex) { + return Types.VARCHAR; + } + + @Override + public String getColumnDataTypeName(int columnIndex) { + return "varchar"; + } + + @Override + public int getPrecision(int columnIndex) { + return 0; + } + + @Override + public int getScale(int columnIndex) { + return 0; + } + + @Override + public int getMaxLength(int columnIndex) { + return 0; + } + + @Override + public String getDefaultValue(int i) { + return null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/batchdrop/BatchDropDataProvider.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/batchdrop/BatchDropDataProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..37dcd0670ce92136ec851a61560446f64459d512 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/batchdrop/BatchDropDataProvider.java @@ -0,0 +1,468 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.grid.batchdrop; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.bl.IServerObjectBatchOperations; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DefaultParameter; +import org.opengauss.mppdbide.bl.serverdatacache.IQueryResult; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnGroupProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.Message; +import org.opengauss.mppdbide.utils.messaging.MessageQueue; +import org.opengauss.mppdbide.utils.messaging.MessageType; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.utils.observer.DSEventTable; +import org.opengauss.mppdbide.utils.observer.IDSGridUIListenable; + +/** + * + * Title: class + * + * Description: The Class BatchDropDataProvider. + * + * @since 3.0.0 + */ +public class BatchDropDataProvider implements IDSGridDataProvider { + private List rows; + private boolean isAtomic; + private boolean isCascade; + private List serverObjects = null; + private DSEventTable eventTable = null; + private int objectsProcessedCnt; + private boolean pauseStopOperation; + private boolean cancelOperation; + private int objectTotalCount; + private final Object lock = new Object(); + private boolean editSupported = true; + private Database db; + + private static final String TRIM_FOR_OBJECT_NOT_FOUND = "ERROR:"; + private static final String APPEND_FOR_OBJECT_NOT_FOUND = ", skipping"; + + /** + * Instantiates a new batch drop data provider. + * + * @param objectsToDrop the objects to drop + */ + public BatchDropDataProvider(List objectsToDrop) { + this.isAtomic = false; + this.isCascade = false; + this.pauseStopOperation = false; + rows = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + this.serverObjects = objectsToDrop; + objectsProcessedCnt = 0; + this.cancelOperation = false; + this.objectTotalCount = serverObjects.size(); + ServerObject serverObj = (ServerObject) (this.serverObjects.get(0)); + this.db = serverObj.getDatabase(); + } + + @Override + public void init() throws DatabaseOperationException, DatabaseCriticalException { + for (int i = 0; i < objectTotalCount; i++) { + Object obj = serverObjects.get(i); + if (obj instanceof ServerObject && obj instanceof IServerObjectBatchOperations) { + rows.add(new BatchDropDataRow((IServerObjectBatchOperations) serverObjects.get(i), isCascade, + this.getColumnDataProvider().getColumnCount())); + } + } + + serverObjects = null; + } + + /** + * Sets the cascade. + * + * @param isCascade1 the new cascade + */ + public void setCascade(boolean isCascade1) { + this.isCascade = isCascade1; + for (int i = 0; i < objectTotalCount; i++) { + ((BatchDropDataRow) rows.get(i)).updateQuery(isCascade1); + } + + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_BATCHDROP_GRID_INPUT_CHANGED, null)); + } + + private void handleSQLException(SQLException e) throws DatabaseCriticalException, DatabaseOperationException { + GaussUtils.handleCriticalException(e); + throw new DatabaseOperationException(IMessagesConstants.ERR_QUERY_EXECUTION_FAILED, e); + } + + private void handleObjectNotFound(DatabaseOperationException e, MessageQueue queue) + throws DatabaseOperationException { + if (e.getCause() instanceof SQLException && GaussUtils.isObjectNotFoundErr((SQLException) e.getCause())) { + String str = e.getServerMessage(); + if (str != null) { + str = str.replace(TRIM_FOR_OBJECT_NOT_FOUND, "").trim(); + } + queue.push(new Message(MessageType.NOTICE, str + APPEND_FOR_OBJECT_NOT_FOUND)); + } else { + throw e; + } + } + + private void execute(DBConnection conn, BatchDropDataRow row) + throws DatabaseCriticalException, DatabaseOperationException { + MessageQueue queue = new MessageQueue(); + Message msg = null; + try { + row.execute(conn, queue, this.isCascade); + } catch (DatabaseOperationException e) { + handleObjectNotFound(e, queue); + } + + if (!queue.isEmpty()) { + msg = queue.pop(); + if (msg != null) { + row.updateError(msg.getMessage()); + } + } else { + row.updateError(""); + } + } + + /** + * Start execute. + * + * @param conn the conn + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public void startExecute(DBConnection conn) throws MPPDBIDEException { + setAutoCommit(conn, !isAtomic); + objectsProcessedCnt = 0; + + while (objectsProcessedCnt < objectTotalCount) { + if (conn.isClosed()) { + break; + } + executeBatchDrop(conn); + + objectsProcessedCnt++; + while (isPauseStopOperation()) { + if (isCancelOperation()) { + // Job will be cancelled by UI thread itself + return; + } + + try { + Thread.sleep(500); + } catch (InterruptedException exception) { + MPPDBIDELoggerUtility.error("BatchDropDataProvider: start execute for batch drop failed.", + exception); + } + } + } + + commitDataOnAtomic(conn); + + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_BATCHDROP_OP_COMPLETE, null)); + + setAutoCommit(conn, true); + } + + private void commitDataOnAtomic(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + if (isAtomic) { + try { + synchronized (lock) { + conn.getConnection().commit(); + objectsProcessedCnt = 0; + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("BatchDropDataProvider: commit for batch drop failed.", exception); + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_BATCHDROP_OP_ROLLBACK, null)); + handleSQLException(exception); + } + } + } + + private void setAutoCommit(DBConnection conn, boolean isCommit) + throws DatabaseCriticalException, DatabaseOperationException { + try { + conn.getConnection().setAutoCommit(isCommit); + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("BatchDropDataProvider: Auto commit for batch drop failed.", exception); + handleSQLException(exception); + } + } + + private BatchDropDataRow executeBatchDrop(DBConnection conn) throws MPPDBIDEException { + BatchDropDataRow row = null; + try { + row = (BatchDropDataRow) rows.get(objectsProcessedCnt); + row.updateStatus(BatchDropStatusEnum.IN_PROGRESS, false); + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_BATCHDROP_GRID_INPUT_CHANGED, null)); + + execute(conn, row); + + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_BATCHDROP_DROP_SUCCESS, row)); + row.updateStatus(BatchDropStatusEnum.COMPLETED, true); + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_BATCHDROP_GRID_INPUT_CHANGED, null)); + } catch (DatabaseOperationException | DatabaseCriticalException e) { + + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_BATCHDROP_DROP_FAILED, row)); + if (row != null) { + row.updateStatus(BatchDropStatusEnum.ERROR, false); + row.updateError(e.getServerMessage()); + } + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_BATCHDROP_GRID_INPUT_CHANGED, null)); + + if (isAtomic) { + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_BATCHDROP_OP_ROLLBACK, null)); + throw e; + } + } + return row; + } + + /** + * Rollback and notify UI mgr. + * + * @param conn the conn + */ + public void rollbackAndNotifyUIMgr(DBConnection conn) { + if (isAtomic) { + int objectsAlreadyDropped = 0; + try { + synchronized (lock) { + objectsAlreadyDropped = objectsProcessedCnt; + objectsProcessedCnt = 0; + + conn.getConnection().rollback(); + conn.getConnection().setAutoCommit(true); + } + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("BatchDropDataProvider: rollback for batch drop failed.", exception); + } + + BatchDropDataRow row = null; + for (int i = 0; i < objectsAlreadyDropped; i++) { + row = (BatchDropDataRow) rows.get(i); + if (row.isDropped()) { + row.updateStatus(BatchDropStatusEnum.TO_START, false); + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_BATCHDROP_DROP_REVERTED, row)); + } else { + row.updateStatus(BatchDropStatusEnum.TO_START, false); + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_BATCHDROP_DROP_FAIL_REVERTED, row)); + } + } + + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_BATCHDROP_GRID_INPUT_CHANGED, null)); + } + } + + @Override + public void close() throws DatabaseOperationException, DatabaseCriticalException { + + } + + @Override + public List getNextBatch() throws DatabaseOperationException, DatabaseCriticalException { + return rows; + } + + @Override + public List getAllFetchedRows() { + return rows; + } + + @Override + public boolean isEndOfRecords() { + return true; + } + + @Override + public int getRecordCount() { + return rows.size(); + } + + @Override + public IDSGridColumnProvider getColumnDataProvider() { + return new BatchDropColumnProvider(); + } + + @Override + public void preDestroy() { + setCancelOperation(true); + if (null != this.eventTable) { + this.eventTable.unhookall(); + this.eventTable = null; + } + + if (null != this.rows) { + this.rows.clear(); + this.rows = null; + } + + if (null != this.serverObjects) { + this.serverObjects.clear(); + this.serverObjects = null; + } + } + + @Override + public IDSGridColumnGroupProvider getColumnGroupProvider() { + // No grouping expected here. + return null; + } + + @Override + public TableMetaData getTable() { + + return null; + } + + /** + * Sets the atomic. + * + * @param isAtomic1 the new atomic + */ + public void setAtomic(boolean isAtomic1) { + this.isAtomic = isAtomic1; + } + + /** + * Sets the event table. + * + * @param eventTable the new event table + */ + public void setEventTable(DSEventTable eventTable) { + this.eventTable = eventTable; + } + + /** + * Gets the total object cnt. + * + * @return the total object cnt + */ + public int getTotalObjectCnt() { + return objectTotalCount; + } + + /** + * Checks if is pause stop operation. + * + * @return true, if is pause stop operation + */ + public boolean isPauseStopOperation() { + return pauseStopOperation; + } + + /** + * Sets the pause stop operation. + * + * @param pauseStopOperation1 the new pause stop operation + */ + public void setPauseStopOperation(boolean pauseStopOperation1) { + this.pauseStopOperation = pauseStopOperation1; + } + + /** + * Checks if is cancel operation. + * + * @return true, if is cancel operation + */ + public boolean isCancelOperation() { + return cancelOperation; + } + + /** + * Sets the cancel operation. + * + * @param cancelOperation1 the new cancel operation + */ + public void setCancelOperation(boolean cancelOperation1) { + this.cancelOperation = cancelOperation1; + } + + /** + * Checks if is edits the supported. + * + * @return true, if is edits the supported + */ + public boolean isEditSupported() { + return editSupported; + } + + /** + * Sets the edits the supported. + * + * @param isEditSupported the new edits the supported + */ + public void setEditSupported(boolean isEditSupported) { + this.editSupported = isEditSupported; + } + + @Override + public boolean getResultTabDirtyFlag() { + + return false; + } + + @Override + public void setResultTabDirtyFlag(boolean flag) { + + } + + @Override + public Database getDatabse() { + return this.db; + } + + /** + * init + */ + @Override + public void init(IQueryResult irq, ArrayList debugInputValueList, boolean isCallableStmt) + throws DatabaseOperationException, DatabaseCriticalException { + } + + /** + * gets next batch + */ + @Override + public List getNextBatch(ArrayList debugInputValueList) + throws DatabaseOperationException, DatabaseCriticalException { + return null; + } + + @Override + public void setFuncProcExport(boolean isFuncProcExport) { + } + + @Override + public boolean isFuncProcExport() { + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/batchdrop/BatchDropDataRow.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/batchdrop/BatchDropDataRow.java new file mode 100644 index 0000000000000000000000000000000000000000..175b6bdd34db4922f99b88432f5b259fba3e5e70 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/batchdrop/BatchDropDataRow.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.grid.batchdrop; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.IServerObjectBatchOperations; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.messaging.MessageQueue; + +/** + * + * Title: class + * + * Description: The Class BatchDropDataRow. + * + * @since 3.0.0 + */ +public class BatchDropDataRow implements IDSGridDataRow { + private IServerObjectBatchOperations serverObject; + private Object[] values; + private boolean isDropped = false; + private static final int QUERY_IDX = 2; + private static final int STATUS_IDX = 3; + private static final int ERROR_IDX = 4; + + /** + * Instantiates a new batch drop data row. + * + * @param servObj the serv obj + * @param isCascade the is cascade + * @param columnCount the column count + */ + public BatchDropDataRow(IServerObjectBatchOperations servObj, boolean isCascade, int columnCount) { + this.serverObject = servObj; + init(isCascade, columnCount); + } + + private void init(boolean isCascade, int columnCount) { + this.values = new Object[columnCount]; + values[0] = serverObject.getObjectTypeName(); + values[1] = serverObject.getObjectFullName(); + values[QUERY_IDX] = serverObject.getDropQuery(isCascade); + + values[STATUS_IDX] = BatchDropStatusEnum.TO_START; + values[ERROR_IDX] = ""; + } + + @Override + public Object[] getValues() { + return new Object[0]; + } + + @Override + public Object getValue(int columnIndex) { + return values[columnIndex]; + } + + @Override + public Object[] getClonedValues() { + return values.clone(); + } + + /** + * Execute. + * + * @param connection the connection + * @param queue the queue + * @param isCascade the is cascade + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void execute(DBConnection connection, MessageQueue queue, boolean isCascade) + throws DatabaseOperationException, DatabaseCriticalException { + connection.execQueryWithMsgQueue(this.serverObject.getDropQuery(isCascade), queue); + } + + /** + * Update query. + * + * @param isCascade the is cascade + */ + public void updateQuery(boolean isCascade) { + values[QUERY_IDX] = ((IServerObjectBatchOperations) serverObject).getDropQuery(isCascade); + } + + /** + * Update status. + * + * @param status the status + * @param isDropped1 the is dropped 1 + */ + public void updateStatus(BatchDropStatusEnum status, boolean isDropped1) { + values[STATUS_IDX] = status; + this.isDropped = isDropped1; + } + + /** + * Update error. + * + * @param serverMessage the server message + */ + public void updateError(String serverMessage) { + if (!(serverMessage.contains(" Detail") && serverMessage.contains(" Hint"))) { + values[ERROR_IDX] = serverMessage; + return; + } + int index1 = serverMessage.indexOf(" Detail"); + int index2 = serverMessage.indexOf(" Hint"); + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append(serverMessage.substring(0, index1)); + sb.append(serverMessage.substring(index2)); + values[ERROR_IDX] = sb.toString(); + } + + /** + * Gets the server object. + * + * @return the server object + */ + public ServerObject getServerObject() { + return (ServerObject) serverObject; + } + + /** + * Checks if is dropped. + * + * @return true, if is dropped + */ + public boolean isDropped() { + return isDropped; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/batchdrop/BatchDropStatusEnum.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/batchdrop/BatchDropStatusEnum.java new file mode 100644 index 0000000000000000000000000000000000000000..c91966df849d0d1520414a2dc1401d6c21f34167 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/batchdrop/BatchDropStatusEnum.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.grid.batchdrop; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: enum + * + * Description: The Enum BatchDropStatusEnum. + * + * @since 3.0.0 + */ +public enum BatchDropStatusEnum { + TO_START(MessageConfigLoader.getProperty(IMessagesConstants.DROP_OBJECTS_OPER_STATUS_TOSTART)), + IN_PROGRESS(MessageConfigLoader.getProperty(IMessagesConstants.DROP_OBJECTS_OPER_STATUS_INPROGRESS)), + ERROR(MessageConfigLoader.getProperty(IMessagesConstants.DROP_OBJECTS_OPER_STATUS_ERROR)), + COMPLETED(MessageConfigLoader.getProperty(IMessagesConstants.DROP_OBJECTS_OPER_STATUS_COMPLETED)); + + String value; + + /** + * Instantiates a new batch drop status enum. + * + * @param value1 the value 1 + */ + BatchDropStatusEnum(String value1) { + this.value = value1; + } + + @Override + public String toString() { + return this.value; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/resultset/ColumnValueSqlTypeComparator.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/resultset/ColumnValueSqlTypeComparator.java new file mode 100644 index 0000000000000000000000000000000000000000..c608fb34288a611cdb5ae5d906a25002e7cb2461 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/resultset/ColumnValueSqlTypeComparator.java @@ -0,0 +1,359 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.grid.resultset; + +import java.math.BigDecimal; +import java.sql.Date; +import java.sql.Time; +import java.sql.Timestamp; +import java.sql.Types; +import java.util.Comparator; + +/** + * + * Title: class + * + * Description: The Class ColumnValueSqlTypeComparator. + * + * @param the generic type + * @since 3.0.0 + */ +public class ColumnValueSqlTypeComparator implements Comparator { + private static final String TRUE_VALUE = "true"; + private static final String FALSE_VALUE = "false"; + private static final String BIT_ONE = "1"; + private static final String BIT_ZERO = "0"; + private static final String NULL_VALUE = ""; + private int sqlType; + + /** + * Instantiates a new column value sql type comparator. + * + * @param type the type + */ + public ColumnValueSqlTypeComparator(int type) { + this.sqlType = type; + } + + @Override + public int compare(T o1, T o2) { + int result = 0; + + if (o1 == null) { + result = (null != o2) ? 1 : 0; + } else { + result = (null == o2) ? -1 : compareValues(o1, o2); + } + + return result; + } + + private int compareValues(T val1, T val2) { + switch (this.sqlType) { + case Types.TINYINT: + case Types.SMALLINT: + case Types.INTEGER: { + return compareInteger(val1, val2); + } + case Types.BIGINT: { + return compareLong(val1, val2); + } + case Types.FLOAT: + case Types.REAL: { + return compareFloat(val1, val2); + } + case Types.DOUBLE: { + return compareDouble(val1, val2); + } + case Types.NUMERIC: { + return compareBigDecimal(val1, val2); + } + case Types.BIT: + case Types.BOOLEAN: { + return compareBoolean(val1, val2); + } + case Types.DATE: { + return compareDate(val1, val2); + } + case Types.TIME: + case Types.TIME_WITH_TIMEZONE: { + return compareTime(val1, val2); + } + case Types.TIMESTAMP: + case Types.TIMESTAMP_WITH_TIMEZONE: { + return compareTimestamps(val1, val2); + } + default: { + return val1.toString().compareTo(val2.toString()); + } + } + } + + private int compareDate(Object val1, Object val2) { + Date dVal1 = convertToDate(val1); + Date dVal2 = convertToDate(val2); + + if (null == dVal1) { + return 1; + } + if (null == dVal2) { + return -1; + } + return dVal1.compareTo(dVal2); + } + + private Date convertToDate(Object value) { + if (value instanceof Date) { + return (Date) value; + } else if (value instanceof String) { + return Date.valueOf((String) value); + } + + return null; + } + + private int compareBigDecimal(Object val1, Object val2) { + BigDecimal dVal1 = convertToBigDecimal(val1); + BigDecimal dVal2 = convertToBigDecimal(val2); + + if (null == dVal1) { + return 1; + } else if (null == dVal2) { + return -1; + } + + return dVal1.compareTo(dVal2); + } + + private BigDecimal convertToBigDecimal(Object value) { + if (value instanceof BigDecimal) { + return (BigDecimal) value; + } else if (value instanceof String) { + return new BigDecimal((String) value); + } + + return null; + } + + private int compareBoolean(Object val1, Object val2) { + Boolean dVal1 = convertToBoolean(val1); + Boolean dVal2 = convertToBoolean(val2); + + return dVal1.compareTo(dVal2); + } + + private Boolean convertToBoolean(Object value) { + if (value instanceof Boolean) { + return (Boolean) value; + } else if (value instanceof String) { + return convertToBooleanInner((String) value); + } + + return false; + } + + private Boolean convertToBooleanInner(String value) { + if (NULL_VALUE.equals(value)) { + return false; + } + if (TRUE_VALUE.equalsIgnoreCase(value) || value.equals(BIT_ONE)) { + return true; + } + if (FALSE_VALUE.equalsIgnoreCase(value) || value.equals(BIT_ZERO)) { + return false; + } + throw new IllegalArgumentException(); + } + + private int compareDouble(Object val1, Object val2) { + Double dVal1 = convertToDouble(val1); + Double dVal2 = convertToDouble(val2); + + if (null == dVal1) { + return 1; + } else if (null == dVal2) { + return -1; + } + + return dVal1.compareTo(dVal2); + } + + private Double convertToDouble(Object value) { + if (value instanceof Double) { + return (Double) value; + } else if (value instanceof String) { + /* + * To handle money data type vlaues, which can be of following + * format $10.25, $-25.00, 56.89$, etc.. + */ + String strippedString = (String) value; + strippedString = stripCurrencyChar(strippedString); + return Double.valueOf(strippedString); + } + + return null; + } + + private String stripCurrencyChar(String strippedStringParam) { + String strippedString = strippedStringParam; + /* NOTE: This function manipulates the input parameter itself */ + boolean hasSign = strippedString.startsWith("+") || strippedString.startsWith("-"); + char signChar = 0; + if (hasSign && strippedString.length() > 1) { + signChar = strippedString.charAt(0); + strippedString = strippedString.substring(1, strippedString.length() - 1); + } + char startChar = strippedString.charAt(0); + char endChar = strippedString.charAt(strippedString.length() - 1); + boolean isStripFirstChar = !Character.isDigit(startChar); + boolean isStripLastChar = !Character.isDigit(endChar); + if (isStripFirstChar && strippedString.length() > 1) { + strippedString = strippedString.substring(1, strippedString.length() - 1); + } + + if (isStripLastChar && strippedString.length() > 1) { + strippedString = strippedString.substring(0, strippedString.length() - 2); + } + + if (hasSign && strippedString.length() > 1) { + strippedString = String.valueOf(signChar).concat(strippedString); + } + return strippedString; + } + + private int compareFloat(Object val1, Object val2) { + Float dVal1 = convertToFloat(val1); + Float dVal2 = convertToFloat(val2); + + if (null == dVal1) { + return 1; + } else if (null == dVal2) { + return -1; + } + + return dVal1.compareTo(dVal2); + } + + private Float convertToFloat(Object value) { + if (value instanceof Float) { + return (Float) value; + } else if (value instanceof String) { + return Float.valueOf((String) value); + } + + return null; + } + + private int compareLong(Object val1, Object val2) { + Long dVal1 = convertToLong(val1); + Long dVal2 = convertToLong(val2); + + if (null == dVal1) { + return 1; + } else if (null == dVal2) { + return -1; + } + + return dVal1.compareTo(dVal2); + } + + private Long convertToLong(Object value) { + if (value instanceof Long) { + return (Long) value; + } else if (value instanceof String) { + return Long.valueOf((String) value); + } + + return null; + } + + private int compareInteger(Object val1, Object val2) { + Integer dVal1 = convertToInteger(val1); + Integer dVal2 = convertToInteger(val2); + + if (null == dVal1) { + return 1; + } else if (null == dVal2) { + return -1; + } + + return dVal1.compareTo(dVal2); + } + + private Integer convertToInteger(Object value) { + if (value instanceof Integer) { + return (Integer) value; + } else if (value instanceof Short) { + return ((Short) value).intValue(); + } else if (value instanceof String && !((String) value).isEmpty()) { + return Integer.valueOf((String) value); + } + + return null; + } + + private int compareTime(T val1, T val2) { + Time time1 = convertToTime(val1); + Time time2 = convertToTime(val2); + + // Unsupported format. Assuming that this compare is for sorting + // return 1 to move down the order + if (null == time1) { + return 1; + } else if (null == time2) { + return -1; + } + + return time1.compareTo(time2); + + } + + private Time convertToTime(T value) { + if (value instanceof Time) { + return (Time) value; + } else if (value instanceof java.util.Date) { + return new Time(((java.util.Date) value).getTime()); + } + + return null; + } + + private int compareTimestamps(T val1, T val2) { + Timestamp time1 = convertToTimestamp(val1); + Timestamp time2 = convertToTimestamp(val2); + + // Unsupported format. Assuming that this compare is for sorting + // return 1 to move down the order + if (null == time1) { + return 1; + } else if (null == time2) { + return -1; + } + + return time1.compareTo(time2); + } + + private Timestamp convertToTimestamp(Object value) { + if (value instanceof Timestamp) { + return (Timestamp) value; + } else if (value instanceof java.util.Date) { + return new Timestamp(((java.util.Date) value).getTime()); + } + + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/resultset/CursorQueryResult.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/resultset/CursorQueryResult.java new file mode 100644 index 0000000000000000000000000000000000000000..df6fbe6acbca84ce1a6794f92ea0cf8f9d959530 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/grid/resultset/CursorQueryResult.java @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.grid.resultset; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.adapter.gauss.StmtExecutor; +import org.opengauss.mppdbide.bl.serverdatacache.IQueryResult; +import org.opengauss.mppdbide.bl.serverdatacache.ResultSetColumn; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.QueryResultType; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class CursorQueryResult. + * + * @since 3.0.0 + */ +public class CursorQueryResult implements IQueryResult { + private Statement stmt; + private DBConnection connection; + private boolean fetchCommentFlag = false; + + /** + * Instantiates a new cursor query result. + * + * @param stmt the stmt + */ + public CursorQueryResult(Statement stmt, DBConnection connection, boolean fetchCommentFlag) { + this.stmt = stmt; + this.connection = connection; + this.fetchCommentFlag = fetchCommentFlag; + } + + @Override + public void closeStament() { + // Not supported + } + + @Override + public void rollback() { + // Not supported + } + + @Override + public void commitConnection() { + // Not supported + } + + @Override + public int getRowsAffected() { + try { + return this.stmt.getUpdateCount(); + } catch (SQLException exception) { + // ignore + MPPDBIDELoggerUtility.error("Error fetching rows affected", exception); + return 0; + } + } + + @Override + public QueryResultType getReturnType() { + return QueryResultType.RESULTTYPE_RESULTSET; + } + + @Override + public ResultSetColumn[] getColumnMetaData() throws DatabaseOperationException, DatabaseCriticalException { + Map columnComment = new HashMap<>(); + if (this.fetchCommentFlag && connection.isOLAPConnection()) { + columnComment = getColumnCommentOfOLAP(connection, stmt); + } + + int count = getColumnCount(); + ResultSetColumn[] metaData = new ResultSetColumn[count]; + + for (int i = 0; i < count; i++) { + metaData[i] = new ResultSetColumn(i + 1); + metaData[i].collectColumnData(stmt, columnComment); + } + + return metaData; + } + + @Override + public String[][] getNextRecordBatch(int count) throws DatabaseOperationException, DatabaseCriticalException { + // Do nothing. Because cursor materializing will be based on visitor + return new String[0][0]; + } + + @Override + public Object[][] getNextObjectRecordBatch(int count) throws DatabaseOperationException, DatabaseCriticalException { + // Do nothing. Because cursor materializing will be based on visitor + return new Object[0][0]; + } + + @Override + public Object[][] getNextObjectRecordBatch(int count, int columnCount, boolean isInputParaVisited, + boolean isFuncProcResultFlow) throws DatabaseOperationException, DatabaseCriticalException { + // Do nothing. Because cursor materializing will be based on visitor + return new Object[0][0]; + } + + @Override + public ResultSet getResultsSet() { + try { + return stmt.getResultSet(); + } catch (SQLException e) { + // Ignore + return null; + } + + } + + @Override + public int getColumnCount() throws DatabaseOperationException { + try { + if (stmt.getResultSet().getMetaData() != null) { + return stmt.getResultSet().getMetaData().getColumnCount(); + } + return 0; + } catch (SQLException exp) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.UNKNOW_CLOB_TYPE), exp); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exp); + } + } + + @Override + public boolean isEndOfRecordsReached() { + + return false; + } + + /** + * gets the database connection + */ + @Override + public DBConnection getConnection() { + return this.connection; + } + + /** + * gets the ColumnHeaderName + * + * @param columnCount the columnCount + * @param columnHeaderName the columnHeaderName + * @param isCallableStmt the isCallableStmt + * @param isCursorType the isCursorType + * @return metaData the meta data + * @throws DatabaseOperationException the DatabaseOperationException + * @throws DatabaseCriticalException the DatabaseCriticalException + */ + public ResultSetColumn[] getColumnHeaderName(int columnCount, List columnHeaderName, boolean isCallableStmt, + boolean isCursorType) throws DatabaseOperationException, DatabaseCriticalException { + ResultSetColumn[] metaData = new ResultSetColumn[columnCount]; + ResultSet rs = null; + try { + if (isCallableStmt || (stmt != null && !stmt.isClosed())) { + rs = stmt.getResultSet(); + } + } catch (SQLException exe) { + GaussUtils.handleCriticalException(exe); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exe); + } + for (int i = 0; i < columnCount; i++) { + metaData[i] = new ResultSetColumn(i + 1); + metaData[i].setColumnHeaderName(rs, columnHeaderName.get(i), i + 1, isCursorType, isCallableStmt); + } + return metaData; + } + + @Override + public StmtExecutor getStmtExecutor() { + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectbrowser/ObjectBrowserObjectRefreshPresentation.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectbrowser/ObjectBrowserObjectRefreshPresentation.java new file mode 100644 index 0000000000000000000000000000000000000000..68848aa67f6c6a3056ed5e4feaf6df281b795924 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectbrowser/ObjectBrowserObjectRefreshPresentation.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectbrowser; + +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: class + * + * Description: The Class ObjectBrowserObjectRefreshPresentation. + * + * @since 3.0.0 + */ +public class ObjectBrowserObjectRefreshPresentation { + + /** + * Refresh sever object. + * + * @param obj the obj + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static void refreshSeverObject(ServerObject obj) + throws DatabaseCriticalException, DatabaseOperationException { + if (obj instanceof TableMetaData) { + TableMetaData tbl = (TableMetaData) obj; + Namespace ns = tbl.getNamespace(); + tbl.getDatabase().setLoadingNamespaceInProgress(true); + ns.refreshTable(tbl, tbl.getDatabase().getConnectionManager().getObjBrowserConn(), false); + tbl.getDatabase().setLoadingNamespaceInProgress(false); + } + if (obj instanceof ViewMetaData) { + ViewMetaData view = (ViewMetaData) obj; + Namespace ns = view.getNamespace(); + view.getDatabase().setLoadingNamespaceInProgress(true); + ns.refreshView(view, view.getDatabase().getConnectionManager().getObjBrowserConn(), false); + view.getDatabase().setLoadingNamespaceInProgress(false); + } + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/AbstractDSObjectPropertiesGridDataProvider.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/AbstractDSObjectPropertiesGridDataProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..0a6d8416a2523dd6d159263f3473c3d510604917 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/AbstractDSObjectPropertiesGridDataProvider.java @@ -0,0 +1,443 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; + +import org.opengauss.mppdbide.presentation.edittabledata.CommitStatus; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableRecordExecutionStatus; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableRecordStates; +import org.opengauss.mppdbide.presentation.edittabledata.IDSGridEditDataRow; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.utils.observer.DSEventTable; +import org.opengauss.mppdbide.utils.observer.IDSGridUIListenable; +import org.opengauss.mppdbide.utils.observer.IDSListener; + +/** + * + * Title: class + * + * Description: The Class AbstractDSObjectPropertiesGridDataProvider. + * + * @since 3.0.0 + */ +public abstract class AbstractDSObjectPropertiesGridDataProvider { + + /** + * The inserted list. + */ + protected List insertedList; + + /** + * The delete list. + */ + protected List deleteList; + + /** + * The altered list. + */ + protected List alteredList; + + /** + * The event table. + */ + protected DSEventTable eventTable; + + /** + * The updated rows count. + */ + protected int updatedRowsCount; + + /** + * The row provider list. + */ + protected List rowProviderList; + + /** + * Instantiates a new abstract DS object properties grid data provider. + */ + public AbstractDSObjectPropertiesGridDataProvider() { + insertedList = new ArrayList<>(); + deleteList = new ArrayList<>(); + alteredList = new ArrayList<>(); + this.eventTable = new DSEventTable(); + rowProviderList = new ArrayList(5); + } + + /** + * Commit status. + * + * @return the commit status + */ + public CommitStatus commitStatus() { + List successRowsList = new ArrayList<>(); + List failureRowsList = new ArrayList<>(); + List successCommits = new ArrayList<>(); + List nonExecutedRowsList = new ArrayList<>(); + updatedRowsCount = 0; + // maintain the list of failure rows and successful row and update the + // parent rows + for (IDSGridEditDataRow insertedRow : insertedList) { + if (insertedRow.getExecutionStatus() == EditTableRecordExecutionStatus.SUCCESS) { + insertedSuccessedRow(successRowsList, successCommits, insertedRow); + } else if (insertedRow.getExecutionStatus() == EditTableRecordExecutionStatus.NOT_EXECUTED) { + nonExecutedRowsList.add(insertedRow); + } else { + failureRowsList.add(insertedRow); + } + } + + insertedList.removeAll(successCommits); + successCommits.clear(); + List parentRows = rowProviderList; + for (IDSGridDataRow rows : parentRows) { + if (((IDSGridEditDataRow) rows).getUpdatedState() == EditTableRecordStates.UPDATE) { + if (((IDSGridEditDataRow) rows).getExecutionStatus() == EditTableRecordExecutionStatus.SUCCESS) { + updatedSuccessedRows(successRowsList, rows); + } else if (((IDSGridEditDataRow) rows) + .getExecutionStatus() == EditTableRecordExecutionStatus.NOT_EXECUTED) { + nonExecutedRowsList.add((IDSGridEditDataRow) rows); + } else { + failureRowsList.add((IDSGridEditDataRow) rows); + } + + } + } + + Iterator iterator = deleteList.iterator(); + while (iterator.hasNext()) { + IDSGridEditDataRow deletedRow = (IDSGridEditDataRow) iterator.next(); + if (deletedRow.getExecutionStatus() == EditTableRecordExecutionStatus.SUCCESS) { + successRowsList.add(deletedRow); + successCommits.add(deletedRow); + removeDeletedRowFromMetadata(deletedRow); + this.rowProviderList.remove(deletedRow); + deletedRow.clearAllRowUpdates(); + } else if (deletedRow.getExecutionStatus() == EditTableRecordExecutionStatus.NOT_EXECUTED) { + nonExecutedRowsList.add(deletedRow); + } else { + failureRowsList.add(deletedRow); + } + + } + deleteList.removeAll(successCommits); + successCommits.clear(); + removeSuccessFromAlterList(successRowsList); + return new CommitStatus(successRowsList, failureRowsList, updatedRowsCount, nonExecutedRowsList); + } + + /** + * Updated successed rows. + * + * @param successRowsList the success rows list + * @param rows the rows + */ + private void updatedSuccessedRows(List successRowsList, IDSGridDataRow rows) { + List modifiedColumns = ((IDSGridEditDataRow) rows).getModifiedColumns(); + int modifiedColumnsSize = modifiedColumns.size(); + for (int i = 0; i < modifiedColumnsSize; i++) { + int colIndex = modifiedColumns.get(i); + Object value = ((IDSGridEditDataRow) rows).getValue(colIndex); + Object[] values = ((IDSGridEditDataRow) rows).getValues(); + values[colIndex] = value == null ? null : value.toString(); + } + updatedRowsCount++; + successRowsList.add((IDSGridEditDataRow) rows); + ((IDSGridEditDataRow) rows).clearAllRowUpdates(); + } + + /** + * Inserted successed row. + * + * @param successRowsList the success rows list + * @param successCommits the success commits + * @param insertedRow the inserted row + */ + private void insertedSuccessedRow(List successRowsList, List successCommits, + IDSGridEditDataRow insertedRow) { + successCommits.add(insertedRow); + successRowsList.add(insertedRow); + Object[] values = insertedRow.getValues(); + if (values != null && values.length > 0) { + for (int i = 0; i < values.length; i++) { + values[i] = insertedRow.getValue(i); + } + } + rowProviderList.add(insertedRow.getRowIndex(), insertedRow); + insertedRow.clearAllRowUpdates(); + removeAlteredRowInList(insertedRow); + } + + /** + * Removes the deleted row from metadata. + * + * @param deletedRow the deleted row + */ + protected void removeDeletedRowFromMetadata(IDSGridEditDataRow deletedRow) { + // This method is added to remove meta data information for deleted + // row..Overridden in particular provider + + } + + /** + * Adds the altered row in list. + * + * @param row the row + */ + public void addAlteredRowInList(IDSGridEditDataRow row) { + if (!alteredList.contains(row)) { + alteredList.add(row); + } + + } + + /** + * Removes the altered row in list. + * + * @param row the row + */ + public void removeAlteredRowInList(IDSGridEditDataRow row) { + alteredList.remove(row); + } + + /** + * Gets the all fetched rows. + * + * @return the all fetched rows + */ + public List getAllFetchedRows() { + + return this.rowProviderList; + } + + /** + * Gets the record count. + * + * @return the record count + */ + public int getRecordCount() { + + return rowProviderList.size(); + } + + /** + * Delete record. + * + * @param row the row + * @param isInserted the is inserted + */ + public void deleteRecord(IDSGridEditDataRow row, boolean isInserted) { + // check if the record is just inserted and being deleted + // check if the record is modified and being deleted(add to delete list + // and remove from the modified list) + // check if the record is marked as deleted and user try update it(add + // only to delete list and remove from parent + + if (isInserted) { + insertedList.remove(row); + rearrangeInsertedRowIndex(row.getRowIndex(), false); + removeAlteredRowInList(row); + } else { + if (!deleteList.contains(row)) { + deleteList.add(row); + addAlteredRowInList(row); + row.setStateDelete(); + } + } + + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_ROW_DELETED, row)); + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_EDITED, null)); + } + + /** + * Rearrange inserted row index. + * + * @param rowIndex the row index + * @param isInsertOperation the is insert operation + */ + protected void rearrangeInsertedRowIndex(int rowIndex, boolean isInsertOperation) { + + List insList = insertedList; + Iterator it = insList.iterator(); + while (it.hasNext()) { + IDSGridEditDataRow row = it.next(); + int index = row.getRowIndex(); + if (index > rowIndex) { + if (isInsertOperation) { + row.setRowIndex(index + 1); + } else { + row.setRowIndex(index - 1); + } + } + } + + } + + /** + * Gets the consolidated rows. + * + * @return the consolidated rows + */ + public List getConsolidatedRows() { + List rows = getAllFetchedRows(); + IDSGridEditDataRow insertedRow; + List consolidatedRows = new ArrayList(); + consolidatedRows.addAll(rows); + Iterator iterator = insertedList.iterator(); + while (iterator.hasNext()) { + insertedRow = (IDSGridEditDataRow) iterator.next(); + consolidatedRows.add(insertedRow.getRowIndex(), insertedRow); + } + return consolidatedRows; + } + + /** + * Gets the inserted row count. + * + * @return the inserted row count + */ + public int getInsertedRowCount() { + + return insertedList.size(); + } + + /** + * Gets the deleted row count. + * + * @return the deleted row count + */ + public int getDeletedRowCount() { + + return deleteList.size(); + } + + /** + * Adds the listener. + * + * @param type the type + * @param listener the listener + */ + public void addListener(int type, IDSListener listener) { + eventTable.hook(type, listener); + } + + /** + * Removes the listener. + * + * @param type the type + * @param listener the listener + */ + public void removeListener(int type, IDSListener listener) { + eventTable.unhook(type, listener); + } + + + /** + * Removes the success from alter list. + * + * @param success the success + */ + public void removeSuccessFromAlterList(List success) { + for (IDSGridEditDataRow successUpdatedRows : success) { + alteredList.remove(successUpdatedRows); + } + } + + /** + * Roll back provider. + */ + public void rollBackProvider() { + insertedList.clear(); + deleteList.clear(); + alteredList.clear(); + List allRows = getAllFetchedRows(); + + for (Iterator iterator = allRows.iterator(); iterator.hasNext();) { + IDSGridEditDataRow idsGridDataRow = (IDSGridEditDataRow) iterator.next(); + idsGridDataRow.clearAllRowUpdates(); + } + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_EDITED, null)); + + } + + /** + * Checks if is grid data edited. + * + * @return true, if is grid data edited + */ + public boolean isGridDataEdited() { + return getUpdatedRowCount() > 0 || getInsertedRowCount() > 0 || getDeletedRowCount() > 0; + } + + /** + * Gets the updated row count. + * + * @return the updated row count + */ + public int getUpdatedRowCount() { + int updatedRows = 0; + for (IDSGridDataRow row : getAllFetchedRows()) { + if (((IDSGridEditDataRow) row).getUpdatedState() == EditTableRecordStates.UPDATE) { + updatedRows++; + } + } + + return updatedRows; + } + + /** + * Gets the all rows. + * + * @return the all rows + */ + public List getAllRows() { + List combinedRowproviderList = new ArrayList<>(rowProviderList); + List sortedInsertedList = new ArrayList<>(insertedList); + Collections.sort(sortedInsertedList, new RowIndexComparator()); + for (IDSGridEditDataRow row : sortedInsertedList) { + int rowIndex = row.getRowIndex(); + combinedRowproviderList.add(rowIndex, row); + } + + return combinedRowproviderList; + } + + /** + * + * Title: class + * + * Description: The Class RowIndexComparator. + */ + private static class RowIndexComparator implements Comparator { + @Override + public int compare(IDSGridEditDataRow o1, IDSGridEditDataRow o2) { + if (o1.getRowIndex() > o2.getRowIndex()) { + return 1; + } + if (o1.getRowIndex() < o2.getRowIndex()) { + return -1; + } + return 0; + } + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/ColumnValuePropertiesComparator.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/ColumnValuePropertiesComparator.java new file mode 100644 index 0000000000000000000000000000000000000000..5d5faba228a52580e0e55b825b1b551a6b53048f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/ColumnValuePropertiesComparator.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import org.opengauss.mppdbide.presentation.util.AbstractValueComparator; + +/** + * + * Title: class + * + * Description: The Class ColumnValuePropertiesComparator. + * + * @param the generic type + * @since 3.0.0 + */ +public class ColumnValuePropertiesComparator extends AbstractValueComparator { + + private static final long serialVersionUID = 1L; + + @Override + protected int compareValues(T o1, T o2) { + + if (o2 instanceof ObjectPropColumnTabInfo) { + + return o2.toString().compareTo(o1.toString()); + } + /* + * new value for the first time will be string but next time when the + * user will be select the checkbox it will be boolean.Hence o1 has been + * checked for instance of boolean + */ + if (o1 instanceof Boolean || o2 instanceof Boolean) { + + boolean parseBoolean = Boolean.parseBoolean(o1.toString()); + + return Boolean.compare(parseBoolean, Boolean.valueOf(o2.toString())); + } + if (o2 instanceof String && o1 instanceof String) { + String val1 = (String) o1; + String val2 = (String) o2; + return val1.compareTo(val2); + + } + + return 0; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/ConnectionPropertiesImpl.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/ConnectionPropertiesImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..e0f5997d88228968b7682ed9c1ac360f23099f1a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/ConnectionPropertiesImpl.java @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.utils.CustomStringUtility; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class ConnectionPropertiesImpl. + * + * @since 3.0.0 + */ +public class ConnectionPropertiesImpl implements IServerObjectProperties { + private Server server; + private String serverType; + private String serverVersion; + private ConvertToObjectPropertyData convertToObjectPropertyData; + + /** + * Instantiates a new connection properties impl. + * + * @param obj the obj + */ + public ConnectionPropertiesImpl(Object obj) { + // get the IADAPTABLE CALL + server = (Server) obj; + convertToObjectPropertyData = new OlapConvertToObjectPropertyData(); + } + + @Override + public String getObjectName() { + + return server.getDisplayName(); + } + + @Override + public String getHeader() { + + return server.getName(); + } + + @Override + public String getUniqueID() { + + return server.getId() + "properties"; + } + + @Override + public List getAllProperties(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException, MPPDBIDEException { + List tabNameList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + List> propertyList = new ArrayList>(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + tabNameList.add(PropertiesConstants.GENERAL); + propertyList.add(getGeneralproperty(conn)); + return convertToObjectPropertyData.getObjectPropertyData(tabNameList, propertyList, null, this); + } + + /** + * Gets the generalproperty. + * + * @param conn the conn + * @return the generalproperty + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws MPPDBIDEException the MPPDBIDE exception + */ + private List getGeneralproperty(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException, MPPDBIDEException { + List props = new ArrayList(); + String[] dbPropHeader = {MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_WID_PROPERTY), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_WID_VALUE)}; + parseVersionForProperty(server.getServerVersion(true)); + + props.add(dbPropHeader); + // only one record expected + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.CONNECTION_NAME), + server.getServerConnectionInfo().getConectionName()).getProp()); + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.CONN_PROP_HOST), + server.getServerConnectionInfo().getServerIp()).getProp()); + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.CONN_PROP_PORT), + server.getServerConnectionInfo().getServerPort()).getProp()); + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.CONN_PROP_USERNAME), + server.getServerConnectionInfo().getDsUsername()).getProp()); + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.CONN_PROP_SERVER_IP), + server.getServerIP2()).getProp()); + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.CONN_PROP_SERVER_TYPE), + this.serverType).getProp()); + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.CONN_PROP_DB_VERSION), + this.serverVersion).getProp()); + if (props.isEmpty()) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.CONNECTION_PROPERTIES_UNAVAILABLE)); + throw new DatabaseOperationException(IMessagesConstants.CONNECTION_PROPERTIES_UNAVAILABLE, + server.getName()); + } + return props; + } + + /** + * Parses the version for property. + * + * @param version the version + */ + private void parseVersionForProperty(String version) { + String[] serverTypeAndInfo = CustomStringUtility.getServerType(version); + this.serverType = (String) Array.get(serverTypeAndInfo, 0); + this.serverVersion = (String) Array.get(serverTypeAndInfo, 1); + } + + @Override + public Database getDatabase() { + return null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/ConstraintInfo.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/ConstraintInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..0ec37c84c23cc002be2fc4cf35abdc1e818fdb95 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/ConstraintInfo.java @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +/** + * + * Title: class + * + * Description: The Class ConstraintInfo. + * + * @since 3.0.0 + */ +public class ConstraintInfo { + private String constraintExpr; + private String columns; + + private String constraintType; + private String constraintName; + private String tablespace; + private String consSchema; + private boolean isdeferred; + + /** + * Gets the constraint type. + * + * @return the constraint type + */ + public String getConstraintType() { + return constraintType; + } + + /** + * Sets the constraint type. + * + * @param constraintType the new constraint type + */ + public void setConstraintType(String constraintType) { + this.constraintType = constraintType; + } + + /** + * Gets the constraint name. + * + * @return the constraint name + */ + public String getConstraintName() { + return constraintName; + } + + /** + * Sets the constraint name. + * + * @param constraintName the new constraint name + */ + public void setConstraintName(String constraintName) { + this.constraintName = constraintName; + } + + /** + * Gets the constraint expr. + * + * @return the constraint expr + */ + public String getConstraintExpr() { + return constraintExpr; + } + + /** + * Sets the constraint expr. + * + * @param constraintExpr the new constraint expr + */ + public void setConstraintExpr(String constraintExpr) { + this.constraintExpr = constraintExpr; + } + + /** + * Gets the columns. + * + * @return the columns + */ + public String getColumns() { + return columns; + } + + /** + * Sets the columns. + * + * @param columns the new columns + */ + public void setColumns(String columns) { + this.columns = columns; + } + + /** + * Gets the table space. + * + * @return the table space + */ + public String getTableSpace() { + return tablespace; + } + + /** + * Sets the tablespace. + * + * @param tablespace the new tablespace + */ + public void setTablespace(String tablespace) { + this.tablespace = tablespace; + } + + /** + * Gets the cons schema. + * + * @return the cons schema + */ + public String getConsSchema() { + return consSchema; + } + + /** + * Sets the cons schema. + * + * @param consSchema the new cons schema + */ + public void setConsSchema(String consSchema) { + this.consSchema = consSchema; + } + + /** + * Checks if is deferred. + * + * @return true, if is deferred + */ + public boolean isDeferred() { + return isdeferred; + } + + /** + * Sets the deferred. + * + * @param isDeferred the new deferred + */ + public void setDeferred(boolean isDeferred) { + this.isdeferred = isDeferred; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/ConvertToObjectPropertyData.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/ConvertToObjectPropertyData.java new file mode 100644 index 0000000000000000000000000000000000000000..4a964b2011ac870cd0294361ac0e1b83a70c406f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/ConvertToObjectPropertyData.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: class + * + * Description: The Class ConvertToObjectPropertyData. + * + * @since 3.0.0 + */ +public abstract class ConvertToObjectPropertyData { + + /** + * Gets the object property data. + * + * @param tabName the tab name + * @param properties the properties + * @param table the table + * @param objectPropertyObject the object property object + * @return the object property data + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public List getObjectPropertyData(List tabName, List> properties, + ServerObject table, IServerObjectProperties objectPropertyObject) + throws DatabaseOperationException, DatabaseCriticalException { + int size = tabName.size(); + List objectPropData = new ArrayList(); + for (int i = 0; i < size; i++) { + DSObjectPropertiesGridDataProvider prop = new DSObjectPropertiesGridDataProvider(properties.get(i), + tabName.get(i), table, objectPropertyObject); + prop.init(); + objectPropData.add(prop); + } + return objectPropData; + } + + /** + * Gets the object property data generic. + * + * @param tabName the tab name + * @param properties the properties + * @return the object property data generic + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public static List getObjectPropertyDataGeneric(List tabName, + List> properties) throws DatabaseOperationException, DatabaseCriticalException { + int size = tabName.size(); + List objectPropData = new ArrayList(); + for (int i = 0; i < size; i++) { + DSGeneraicGridDataProvider prop = new DSGeneraicGridDataProvider(properties.get(i), tabName.get(i)); + prop.init(); + objectPropData.add(prop); + } + return objectPropData; + } + + /** + * Gets the object property data generic grouped column. + * + * @param tabName the tab name + * @param data the data + * @param colgrp the colgrp + * @return the object property data generic grouped column + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public static List getObjectPropertyDataGenericGroupedColumn(List tabName, + Map> data, List colgrp) + throws DatabaseOperationException, DatabaseCriticalException { + List objectPropData = new ArrayList(); + ArrayList objects = new ArrayList(data.size()); + ArrayList colName = new ArrayList(5); + + for (DNIntraNodeDetailsColumn dncolumns : colgrp) { + colName.addAll(dncolumns.getColnames()); + } + + objects.add(colName.toArray()); + + for (Map.Entry> entry : data.entrySet()) { + String dnName = entry.getKey(); + List dnpropVals = entry.getValue(); + + Object[] allvals = new Object[dnpropVals.size() + 1]; + allvals[0] = dnName; + int index = 1; + for (Object obj : dnpropVals) { + allvals[index] = obj; + index++; + } + + objects.add(allvals); + } + + DSGeneraicGridDataProvider prop = new DSGeneraicGridDataProvider(objects, tabName.get(0), colgrp); + + prop.init(); + objectPropData.add(prop); + return objectPropData; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DNIntraNodeDetailsColumn.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DNIntraNodeDetailsColumn.java new file mode 100644 index 0000000000000000000000000000000000000000..d1b740ee064dab68c4e6aa9794239cf356657769 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DNIntraNodeDetailsColumn.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.util.List; + +/** + * + * Title: class + * + * Description: The Class DNIntraNodeDetailsColumn. + * + * @since 3.0.0 + */ +public class DNIntraNodeDetailsColumn { + private String groupColumnName; + private int colCount; + private List colnames; + + /** + * Gets the group column name. + * + * @return the group column name + */ + public String getGroupColumnName() { + return groupColumnName; + } + + /** + * Sets the group column name. + * + * @param groupColumnName the new group column name + */ + public void setGroupColumnName(String groupColumnName) { + this.groupColumnName = groupColumnName; + } + + /** + * Gets the col count. + * + * @return the col count + */ + public int getColCount() { + return colCount; + } + + /** + * Sets the col count. + * + * @param colCount the new col count + */ + public void setColCount(int colCount) { + this.colCount = colCount; + } + + /** + * Gets the colnames. + * + * @return the colnames + */ + public List getColnames() { + return colnames; + } + + /** + * Sets the colnames. + * + * @param colnames the new colnames + */ + public void setColnames(List colnames) { + this.colnames = colnames; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSColumnPropertiesGridDataProvider.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSColumnPropertiesGridDataProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..a5de310764f1cdd047393cd7495b265d6a3809dd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSColumnPropertiesGridDataProvider.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.util.List; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableRecordExecutionStatus; +import org.opengauss.mppdbide.presentation.edittabledata.IDSGridEditDataRow; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class DSColumnPropertiesGridDataProvider. + * + * @since 3.0.0 + */ +public class DSColumnPropertiesGridDataProvider { + + /** + * Perform column delete. + * + * @param columnMetaDataList the column meta data list + * @param freeConnection the free connection + * @param row the row + */ + public static void performColumnDelete(List columnMetaDataList, DBConnection freeConnection, + IDSGridEditDataRow row) { + boolean isColDropped = false; + for (ColumnMetaData col : columnMetaDataList) { + if (col.getName().equals(row.getValue(0))) { + // need to check the solution if column has been dropped + // from the OB and delete oprtn is performed. + isColDropped = false; + PropertiesInfoExecuteQueryUtility.deleteColumnQuery((ColumnMetaData) col, freeConnection, row); + break; + + } else { + isColDropped = true; + } + + } + if (isColDropped) { + row.setCommitStatusMessage(MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_ERROR_MESSAGE, + row.getOriginalValue(0))); + row.setExecutionStatus(EditTableRecordExecutionStatus.FAILED); + } + } + + /** + * Perform column update. + * + * @param columnMetaDataList the column meta data list + * @param freeConnection the free connection + * @param updatedRows the updated rows + */ + public static void performColumnUpdate(List columnMetaDataList, DBConnection freeConnection, + List updatedRows) { + boolean isColumnDropped = false; + for (IDSGridEditDataRow row : updatedRows) { + for (ColumnMetaData column : columnMetaDataList) { + if (row.getOriginalValue(0).equals(column.getName())) { + isColumnDropped = false; + PropertiesInfoExecuteQueryUtility.updateColumnInfoQuery(freeConnection, row, column); + break; + + } else { + isColumnDropped = true; + } + + } + if (isColumnDropped) { + row.setCommitStatusMessage(MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_ERROR_MESSAGE, + row.getOriginalValue(0))); + row.setExecutionStatus(EditTableRecordExecutionStatus.FAILED); + } + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSConstraintsPropertiesGridDataProvider.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSConstraintsPropertiesGridDataProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..78b57e90d2df56a86e4c5b2235cbc6479d5fbf53 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSConstraintsPropertiesGridDataProvider.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.util.List; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintMetaData; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableRecordExecutionStatus; +import org.opengauss.mppdbide.presentation.edittabledata.IDSGridEditDataRow; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class DSConstraintsPropertiesGridDataProvider. + * + * @since 3.0.0 + */ +public class DSConstraintsPropertiesGridDataProvider { + + /** + * Perform constraint delete. + * + * @param constraintList the constraint list + * @param freeConnection the free connection + * @param row the row + */ + public static void performConstraintDelete(List constraintList, DBConnection freeConnection, + IDSGridEditDataRow row) { + boolean isConsDropped = false; + for (ConstraintMetaData cons : constraintList) { + + if (cons.getName().equals(row.getValue(0))) { + isConsDropped = false; + PropertiesInfoExecuteQueryUtility.deleteConstraintQuery((ConstraintMetaData) cons, freeConnection, row); + break; + } else { + isConsDropped = true; + } + } + if (isConsDropped) { + + if (row.getOriginalValue(0) != null && !row.getOriginalValue(0).toString().isEmpty()) { + + row.setCommitStatusMessage(MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_ERROR_MESSAGE, + row.getOriginalValue(0))); + } else if (row.getOriginalValue(0) != null) { + row.setCommitStatusMessage(MessageConfigLoader.getProperty( + IMessagesConstants.PROPERTIES_ERROR_MESSAGE_FOR_CONSTRAINT, row.getOriginalValue(0))); + } + + row.setExecutionStatus(EditTableRecordExecutionStatus.FAILED); + } + } + + /** + * Perform constraint update. + * + * @param constraintList the constraint list + * @param freeConnection the free connection + * @param updatedRows the updated rows + */ + public static void performConstraintUpdate(List constraintList, DBConnection freeConnection, + List updatedRows) { + boolean isConsDropped = false; + for (IDSGridEditDataRow row : updatedRows) { + for (ConstraintMetaData cons : constraintList) { + if (row.getOriginalValue(0).equals(cons.getName())) { + isConsDropped = false; + PropertiesInfoExecuteQueryUtility.updateConstraintInfoQuery(freeConnection, row, cons); + break; + + } else { + isConsDropped = true; + } + + } + if (isConsDropped) { + if (row.getOriginalValue(0) != null && !row.getOriginalValue(0).toString().isEmpty()) { + + row.setCommitStatusMessage(MessageConfigLoader + .getProperty(IMessagesConstants.PROPERTIES_ERROR_MESSAGE, row.getOriginalValue(0))); + } else if (row.getOriginalValue(0) != null) { + row.setCommitStatusMessage(MessageConfigLoader.getProperty( + IMessagesConstants.PROPERTIES_ERROR_MESSAGE_FOR_CONSTRAINT, row.getOriginalValue(0))); + } + row.setExecutionStatus(EditTableRecordExecutionStatus.FAILED); + } + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSGeneraicGridDataProvider.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSGeneraicGridDataProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..5368a8e8d6e3a789487686207956fab53dac5f5a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSGeneraicGridDataProvider.java @@ -0,0 +1,196 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DefaultParameter; +import org.opengauss.mppdbide.bl.serverdatacache.IQueryResult; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnGroupProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: class + * + * Description: The Class DSGeneraicGridDataProvider. + * + * @since 3.0.0 + */ +public class DSGeneraicGridDataProvider implements IObjectPropertyData { + + private List serverObjectPropertiesList; + private IDSGridColumnProvider colProvider; + private IDSGridColumnGroupProvider colGroupProvider; + private List colgrpDetails; + private List rowProviderList; + private String propertyName; + + /** + * Instantiates a new DS generaic grid data provider. + * + * @param list the list + * @param propertyName the property name + */ + public DSGeneraicGridDataProvider(List list, String propertyName) { + this(list, propertyName, null); + } + + /** + * Instantiates a new DS generaic grid data provider. + * + * @param list the list + * @param propertyName the property name + * @param colgrp the colgrp + */ + public DSGeneraicGridDataProvider(List list, String propertyName, List colgrp) { + this.serverObjectPropertiesList = list; + this.propertyName = propertyName; + rowProviderList = new ArrayList(5); + colgrpDetails = colgrp; + } + + @Override + public void init() throws DatabaseOperationException, DatabaseCriticalException { + DSGenericGridColumnProvider provider = new DSGenericGridColumnProvider(); + provider.init(serverObjectPropertiesList); + this.colProvider = provider; + prepareGridRow(); + if (null != colgrpDetails) { + DSGenericGroupedGridColumnProvider grpprovider = new DSGenericGroupedGridColumnProvider(colgrpDetails); + colGroupProvider = grpprovider; + } + + } + + /** + * Prepare grid row. + */ + private void prepareGridRow() { + DSObjectPropertiesGridDataRow gridRowData = null; + Object[] col = null; + int size = serverObjectPropertiesList.size(); + for (int i = 1; i < size; i++) { + col = serverObjectPropertiesList.get(i); + + gridRowData = new DSObjectPropertiesGridDataRow(col); + rowProviderList.add(gridRowData); + } + + } + + @Override + public void close() throws DatabaseOperationException, DatabaseCriticalException { + + } + + @Override + public List getNextBatch() throws DatabaseOperationException, DatabaseCriticalException { + + return null; + } + + @Override + public List getAllFetchedRows() { + return rowProviderList; + } + + @Override + public boolean isEndOfRecords() { + return true; + } + + @Override + public int getRecordCount() { + return 0; + } + + @Override + public IDSGridColumnProvider getColumnDataProvider() { + return this.colProvider; + } + + @Override + public String getObjectPropertyName() { + return this.propertyName; + } + + @Override + public IDSGridColumnGroupProvider getColumnGroupProvider() { + return this.colGroupProvider; + } + + @Override + public void preDestroy() { + + } + + @Override + public TableMetaData getTable() { + + return null; + } + + @Override + public boolean getResultTabDirtyFlag() { + + return false; + } + + @Override + public void setResultTabDirtyFlag(boolean flag) { + + } + + @Override + public Database getDatabse() { + + return null; + } + + /** + * init + */ + @Override + public void init(IQueryResult irq, ArrayList debugInputValueList, boolean isCallableStmt) + throws DatabaseOperationException, DatabaseCriticalException { + } + + /** + * gets next batch + */ + @Override + public List getNextBatch(ArrayList debugInputValueList) + throws DatabaseOperationException, DatabaseCriticalException { + return null; + } + + @Override + public void setFuncProcExport(boolean isFuncProcExport) { + } + + @Override + public boolean isFuncProcExport() { + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSGenericGridColumnProvider.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSGenericGridColumnProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..366dd34e805929436563b93803b4a9c4414e4029 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSGenericGridColumnProvider.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.util.Comparator; +import java.util.List; + +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; + +/** + * + * Title: class + * + * Description: The Class DSGenericGridColumnProvider. + * + * @since 3.0.0 + */ +public class DSGenericGridColumnProvider implements IDSGridColumnProvider { + private List serverObjectProperty; + private int colCount; + + /** + * Inits the. + * + * @param serverObjectProprty the server object proprty + */ + public void init(List serverObjectProprty) { + this.serverObjectProperty = serverObjectProprty; + this.colCount = serverObjectProprty.get(0).length; + } + + @Override + public int getColumnCount() { + return colCount; + } + + @Override + public String[] getColumnNames() { + return (String[]) serverObjectProperty.get(0); + } + + @Override + public String getColumnName(int columnIndex) { + + return (String) serverObjectProperty.get(0)[columnIndex]; + } + + @Override + public String getColumnDesc(int columnIndex) { + + return (String) serverObjectProperty.get(0)[columnIndex]; + } + + @Override + public int getColumnIndex(String columnLabel) { + + return 0; + } + + @Override + public Comparator getComparator(int columnIndex) { + + return null; + } + + @Override + public int getColumnDatatype(int columnIndex) { + + return 0; + } + + @Override + public String getColumnDataTypeName(int columnIndex) { + + return ""; + } + + @Override + public int getPrecision(int columnIndex) { + + return 0; + } + + @Override + public int getScale(int columnIndex) { + + return 0; + } + + @Override + public int getMaxLength(int columnIndex) { + + return 0; + } + + @Override + public String getDefaultValue(int i) { + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSGenericGroupedGridColumnProvider.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSGenericGroupedGridColumnProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..e79661426e6acf0c597b5107fbcd94ac35ccad5e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSGenericGroupedGridColumnProvider.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.util.List; + +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnGroupProvider; + +/** + * + * Title: class + * + * Description: The Class DSGenericGroupedGridColumnProvider. + * + * @since 3.0.0 + */ +public class DSGenericGroupedGridColumnProvider implements IDSGridColumnGroupProvider { + private List colgrpDetails; + + /** + * Instantiates a new DS generic grouped grid column provider. + * + * @param colgrpDetails the colgrp details + */ + public DSGenericGroupedGridColumnProvider(List colgrpDetails) { + this.colgrpDetails = colgrpDetails; + } + + @Override + public int getGroupCount() { + return this.colgrpDetails.size(); + } + + @Override + public String getColumnGroupName(int idx) { + return this.colgrpDetails.get(idx).getGroupColumnName(); + } + + @Override + public int[] getColumnIndexInGroup(int idx) { + int[] colno = new int[this.colgrpDetails.get(idx).getColCount()]; + + int idxSofar = 0; + for (int index = 0; index < idx; index++) { + idxSofar += this.colgrpDetails.get(index).getColCount(); + } + + int colCount = this.colgrpDetails.get(idx).getColCount(); + for (int jindex = 0; jindex < colCount; jindex++) { + colno[jindex] = idxSofar++; + } + + return colno; + } + + @Override + public int getColumnGroupIndex(int columnIndex) { + int colgroupCount = this.getGroupCount(); + + int colSofar = 0; + for (int index = 0; index < colgroupCount; index++) { + colSofar += this.colgrpDetails.get(index).getColCount(); + if (colSofar > columnIndex) { + return index; + } + } + + return 0; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSIndexPropertiesGridDataProvider.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSIndexPropertiesGridDataProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..40c48549bd7c5f52d016d9b43eb77826ea38473b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSIndexPropertiesGridDataProvider.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.IndexMetaData; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableRecordExecutionStatus; +import org.opengauss.mppdbide.presentation.edittabledata.IDSGridEditDataRow; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class DSIndexPropertiesGridDataProvider. + * + * @since 3.0.0 + */ +public class DSIndexPropertiesGridDataProvider { + + /** + * Perform index delete. + * + * @param indexList the index list + * @param freeConnection the free connection + * @param row the row + */ + public static void performIndexDelete(List indexList, DBConnection freeConnection, + IDSGridEditDataRow row) { + List indexList2 = new ArrayList<>(indexList); + boolean isIndexDropped = false; + for (IndexMetaData index : indexList2) { + + if (index.getName().equals(row.getValue(0))) { + isIndexDropped = false; + PropertiesInfoExecuteQueryUtility.deleteIndexQuery((IndexMetaData) index, freeConnection, row); + break; + } else { + isIndexDropped = true; + } + } + + if (isIndexDropped || indexList2.size() == 0) { + row.setCommitStatusMessage(MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_ERROR_MESSAGE, + row.getOriginalValue(0))); + row.setExecutionStatus(EditTableRecordExecutionStatus.FAILED); + } + + } + + /** + * Perform index update. + * + * @param indexList the index list + * @param freeConnection the free connection + * @param updatedRows the updated rows + */ + public static void performIndexUpdate(List indexList, DBConnection freeConnection, + List updatedRows) { + boolean isIndexDropped = false; + for (IDSGridEditDataRow row : updatedRows) { + for (IndexMetaData index : indexList) { + if (row.getOriginalValue(0).equals(index.getName())) { + isIndexDropped = false; + PropertiesInfoExecuteQueryUtility.updateIndexInfoQuery(freeConnection, row, index); + break; + + } else { + isIndexDropped = true; + } + + } + + if (isIndexDropped || indexList.size() == 0) { + row.setCommitStatusMessage(MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_ERROR_MESSAGE, + row.getOriginalValue(0))); + row.setExecutionStatus(EditTableRecordExecutionStatus.FAILED); + } + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSObjectPropertiesGridColumnDataProvider.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSObjectPropertiesGridColumnDataProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..af438b9a545ce22e506f0093fca3352cfc7a4dcb --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSObjectPropertiesGridColumnDataProvider.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.util.Comparator; +import java.util.List; + +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; + +/** + * + * Title: class + * + * Description: The Class DSObjectPropertiesGridColumnDataProvider. + * + * @since 3.0.0 + */ +public class DSObjectPropertiesGridColumnDataProvider implements IDSGridColumnProvider { + private List serverObjectProperty; + private int colCount; + + /** + * Inits the. + * + * @param serverObjectProprty the server object proprty + */ + public void init(List serverObjectProprty) { + this.serverObjectProperty = serverObjectProprty; + this.colCount = serverObjectProprty.get(0).length; + } + + @Override + public int getColumnCount() { + return colCount; + } + + @Override + public String[] getColumnNames() { + + if (serverObjectProperty.size() > 0) { + + return serverObjectProperty.get(0); + } + return new String[0]; + } + + @Override + public String getColumnName(int columnIndex) { + if (serverObjectProperty.size() > 0) { + + return serverObjectProperty.get(0)[columnIndex]; + } + return null; + } + + @Override + public String getColumnDesc(int columnIndex) { + if (serverObjectProperty.size() > 0) { + + return serverObjectProperty.get(0)[columnIndex]; + } + return null; + } + + @Override + public int getColumnIndex(String columnLabel) { + return 0; + } + + @Override + public Comparator getComparator(int columnIndex) { + return new ColumnValuePropertiesComparator<>(); + } + + @Override + public int getColumnDatatype(int columnIndex) { + return -1; + } + + @Override + public String getColumnDataTypeName(int columnIndex) { + return ""; + } + + @Override + public int getPrecision(int columnIndex) { + return 0; + } + + @Override + public int getScale(int columnIndex) { + return 0; + } + + @Override + public int getMaxLength(int columnIndex) { + return 0; + } + + @Override + public String getDefaultValue(int i) { + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSObjectPropertiesGridDataProvider.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSObjectPropertiesGridDataProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..146862b87212e84761ea79fce607b60adc9cdd8d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSObjectPropertiesGridDataProvider.java @@ -0,0 +1,724 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.StringUtils; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionManager; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DefaultParameter; +import org.opengauss.mppdbide.bl.serverdatacache.IQueryResult; +import org.opengauss.mppdbide.bl.serverdatacache.IndexMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.PartitionTable; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.UserRole; +import org.opengauss.mppdbide.bl.serverdatacache.UserRoleManager; +import org.opengauss.mppdbide.presentation.edittabledata.CommitStatus; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableRecordExecutionStatus; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableRecordStates; +import org.opengauss.mppdbide.presentation.edittabledata.IDSGridEditDataRow; +import org.opengauss.mppdbide.presentation.grid.IDSEditGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnGroupProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.presentation.grid.IRowEffectedConfirmation; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.utils.observer.IDSGridUIListenable; +import org.opengauss.mppdbide.utils.observer.IDSListenable; + +/** + * + * Title: class + * + * Description: The Class DSObjectPropertiesGridDataProvider. + * + * @since 3.0.0 + */ +public class DSObjectPropertiesGridDataProvider extends AbstractDSObjectPropertiesGridDataProvider + implements IObjectPropertyData, IDSEditGridDataProvider, IDSListenable { + + private List serverObjectPropertiesList; + private IDSGridColumnProvider colProvider; + private String propertyName; + private TableMetaData table; + private static final String GENERAL_TAB = "General"; + private static final String COLUMNS_TAB = "Columns"; + private static final String CONSTRAINTS_TAB = "Constraints"; + private static final String INDEX_TAB = "Index"; + private IServerObjectProperties objectPropertyObject; + private DBConnection connection; + private boolean cancelled; + private CommitStatus lastCommitStat; + + /** + * Instantiates a new DS object properties grid data provider. + * + * @param serverObjectPropertiesList the server object properties list + * @param propertyName the property name + * @param table the table + * @param objectPropertyObject the object property object + */ + public DSObjectPropertiesGridDataProvider(List serverObjectPropertiesList, String propertyName, + ServerObject table, IServerObjectProperties objectPropertyObject) { + super(); + this.serverObjectPropertiesList = serverObjectPropertiesList; + this.propertyName = propertyName; + this.objectPropertyObject = objectPropertyObject; + this.table = (TableMetaData) table; + + } + + @Override + public void init() throws DatabaseOperationException, DatabaseCriticalException { + DSObjectPropertiesGridColumnDataProvider provider = new DSObjectPropertiesGridColumnDataProvider(); + provider.init(serverObjectPropertiesList); + this.colProvider = provider; + prepareGridRow(); + } + + /** + * Prepare grid row. + */ + private void prepareGridRow() { + + DSObjectPropertiesGridDataRow gridRowData = null; + for (int index = 1; index < serverObjectPropertiesList.size(); index++) { + String[] col = serverObjectPropertiesList.get(index); + + gridRowData = new DSObjectPropertiesGridDataRow(col); + gridRowData.setEventTable(eventTable); + rowProviderList.add(gridRowData); + } + } + + @Override + public void close() throws DatabaseOperationException, DatabaseCriticalException { + + } + + @Override + public List getNextBatch() throws DatabaseOperationException, DatabaseCriticalException { + + return null; + } + + /** + * Commit. + * + * @return the commit status + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public CommitStatus commit() throws MPPDBIDEException { + // first need inserted list to commit + // modified info will be committed + + List columnMetaDataList = this.table.getColumnMetaDataList(); + List constraintList = this.table.getConstraintMetaDataList(); + List indexList = this.table.getIndexMetaDataList(); + + if (this.table.getConnectionManager() == null) { + return null; + } + + connection = this.table.getConnectionManager().getFreeConnection(); + for (IDSGridEditDataRow row : insertedList) { + ServerObject serverObject = ((DSObjectPropertiesGridDataRow) row).getServerObject(); + + performAddQueries(row, serverObject); + } + + for (IDSGridEditDataRow row : deleteList) { + + performDeleteQueries(columnMetaDataList, constraintList, indexList, row); + + } + List updatedRows = getModifiedRows(); + + performUpdateQueries(columnMetaDataList, constraintList, indexList, updatedRows); + + this.table.refresh(connection); + + releaseConnection(); + this.lastCommitStat = commitStatus(); + return lastCommitStat; + + } + + /** + * Perform update queries. + * + * @param columnMetaDataList the column meta data list + * @param constraintList the constraint list + * @param indexList the index list + * @param updatedRows the updated rows + */ + private void performUpdateQueries(List columnMetaDataList, List constraintList, + List indexList, List updatedRows) { + switch (this.propertyName) { + case GENERAL_TAB: { + IDSGridEditDataRow idsGridEditDataRow = updatedRows.get(updatedRows.size() - 1); + PropertiesInfoExecuteQueryUtility.setTableDescriptionQuery(table, connection, idsGridEditDataRow); + break; + } + + case COLUMNS_TAB: { + DSColumnPropertiesGridDataProvider.performColumnUpdate(columnMetaDataList, connection, updatedRows); + break; + } + case CONSTRAINTS_TAB: { + DSConstraintsPropertiesGridDataProvider.performConstraintUpdate(constraintList, connection, + updatedRows); + break; + } + case INDEX_TAB: { + DSIndexPropertiesGridDataProvider.performIndexUpdate(indexList, connection, updatedRows); + } + } + } + + /** + * Perform delete queries. + * + * @param columnMetaDataList the column meta data list + * @param constraintList the constraint list + * @param indexList the index list + * @param row the row + */ + private void performDeleteQueries(List columnMetaDataList, List constraintList, + List indexList, IDSGridEditDataRow row) { + switch (this.propertyName) { + case COLUMNS_TAB: { + DSColumnPropertiesGridDataProvider.performColumnDelete(columnMetaDataList, connection, row); + break; + } + case CONSTRAINTS_TAB: { + DSConstraintsPropertiesGridDataProvider.performConstraintDelete(constraintList, connection, row); + break; + } + case INDEX_TAB: { + DSIndexPropertiesGridDataProvider.performIndexDelete(indexList, connection, row); + break; + } + default: { + break; + } + } + } + + /** + * Perform add queries. + * + * @param row the row + * @param serverObject the server object + */ + private void performAddQueries(IDSGridEditDataRow row, ServerObject serverObject) { + switch (this.propertyName) { + + case COLUMNS_TAB: { + PropertiesInfoExecuteQueryUtility.addColumnQuery((ColumnMetaData) serverObject, connection, row); + break; + } + case CONSTRAINTS_TAB: { + PropertiesInfoExecuteQueryUtility.addConstraintQuery((ConstraintMetaData) serverObject, connection, + row); + break; + } + case INDEX_TAB: { + PropertiesInfoExecuteQueryUtility.addIndexQuery((IndexMetaData) serverObject, connection, row, + this.table); + break; + } + default: { + break; + } + + } + } + + /** + * Generate user role property change preview sql. + * + * @param conn the conn + * @return the list + * @throws Exception the exception + */ + public List generateUserRolePropertyChangePreviewSql(DBConnection conn) throws Exception { + List updatedRows = getModifiedRows(); + try { + UserRole userRole = new UserRole(); + PropertiesUserRoleImpl propertiesUserRoleImpl = (PropertiesUserRoleImpl) this.objectPropertyObject; + userRole.setOid(propertiesUserRoleImpl.getUserRole().getOid()); + + String userRoleName = UserRoleManager.getUserRoleNameByOid(conn, userRole.getOid()); + boolean canLogin = UserRoleManager.getUserRoleLoginByOid(conn, userRole.getOid()); + userRole.setIsUser(canLogin); + if (userRoleName == null || userRoleName.isEmpty()) { + MPPDBIDELoggerUtility.error(MessageConfigLoader + .getProperty(IMessagesConstants.ERR_USER_ROLE_IS_NOT_EXIST, String.valueOf(userRole.getOid()))); + throw new MPPDBIDEException(IMessagesConstants.ERR_USER_ROLE_IS_NOT_EXIST, + String.valueOf(userRole.getOid())); + } + + switch (this.propertyName) { + case PropertiesConstants.USER_ROLE_PROPERTY_TAB_GENERAL: { + DSUserRolePropertiesGridDataProvider.generateUserRolePropertyGeneralTab(updatedRows, userRole); + break; + } + case PropertiesConstants.USER_ROLE_PROPERTY_TAB_PRIVILEGE: { + DSUserRolePropertiesGridDataProvider.generateUserRolePropertyTabPrivilege(updatedRows, userRole); + break; + } + case PropertiesConstants.USER_ROLE_PROPERTY_TAB_MEMBERSHIP: { + DSUserRolePropertiesGridDataProvider.generateUserRolePropertyTabMembership(updatedRows, userRole, + userRoleName); + break; + } + default: { + break; + } + } + return UserRoleManager.generatePropertyChangePreviewSQL(conn, userRole, userRoleName); + } catch (MPPDBIDEException exception) { + updatedRows.stream().forEach(row -> row.setExecutionStatus(EditTableRecordExecutionStatus.FAILED)); + throw exception; + } finally { + this.lastCommitStat = commitStatus(); + } + + } + + /** + * Commit user role property. + * + * @param conn the conn + * @param sqls the sqls + * @throws ParseException the parse exception + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public void commitUserRoleProperty(DBConnection conn, List sqls) throws ParseException, MPPDBIDEException { + List updatedRows = getModifiedRows(); + try { + conn.execNonSelect("START TRANSACTION;"); + UserRoleManager.alterUserRole(conn, sqls); + conn.execNonSelect("COMMIT;"); + updatedRows.stream().forEach(row -> row.setExecutionStatus(EditTableRecordExecutionStatus.SUCCESS)); + } catch (Exception exception) { + conn.execNonSelect("ROLLBACK;"); + updatedRows.stream().forEach(row -> { + row.setExecutionStatus(EditTableRecordExecutionStatus.FAILED); + if (exception instanceof MPPDBIDEException) { + row.setCommitStatusMessage(((MPPDBIDEException) exception).getServerMessage()); + } else { + row.setCommitStatusMessage(exception.getMessage()); + } + }); + throw exception; + } finally { + this.lastCommitStat = commitStatus(); + } + } + + /** + * Release connection. + */ + public void releaseConnection() { + this.table.getDatabase().getConnectionManager().releaseConnection(this.connection); + connection = null; + } + + /** + * Gets the modified rows. + * + * @return the modified rows + */ + private List getModifiedRows() { + List modifiedrows = new ArrayList<>(); + for (IDSGridDataRow row : rowProviderList) { + if (((IDSGridEditDataRow) row).getUpdatedState() == EditTableRecordStates.UPDATE) { + modifiedrows.add((IDSGridEditDataRow) row); + } + } + + return modifiedrows; + + } + + @Override + public boolean isEndOfRecords() { + + return true; + } + + @Override + public IDSGridColumnProvider getColumnDataProvider() { + + return this.colProvider; + } + + @Override + public String getObjectPropertyName() { + + return this.propertyName; + } + + @Override + public IDSGridColumnGroupProvider getColumnGroupProvider() { + + return null; + } + + @Override + public void preDestroy() { + // Nothing to do. Ignore + } + + /** + * Creates the new row. + * + * @param serverObject the server object + * @param index the index + * @return the IDS grid edit data row + */ + public IDSGridEditDataRow createNewRow(ServerObject serverObject, int index) { + + int columnCount = getColumnDataProvider().getColumnCount(); + Object[] tabFieldsInfoFromServerObject = FilterServerObjPropInfoUtility.fetchInfoForRow(serverObject, + columnCount); + DSObjectPropertiesGridDataRow row = new DSObjectPropertiesGridDataRow(tabFieldsInfoFromServerObject); + + for (int cnt = 0; cnt < columnCount; cnt++) { + row.setEventTable(eventTable); + row.setValue(cnt, tabFieldsInfoFromServerObject[cnt]); + } + row.setRowIndex(index); + row.createNewRow(tabFieldsInfoFromServerObject); + row.setServerObject(serverObject); + insertedList.add(row); + rearrangeInsertedRowIndex(row.getRowIndex(), true); + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_EDITED, null)); + return row; + + } + + @Override + public TableMetaData getTable() { + return this.table; + } + + @Override + public boolean isEditSupported() { + if (objectPropertyObject instanceof PropertiesUserRoleImpl) { + return true; + } + + if (table == null) { + return false; + } + if (table instanceof PartitionTable) { + return false; + } + + return objectPropertyObject instanceof PropertiesTableImpl; + } + + @Override + public boolean getResultTabDirtyFlag() { + + return false; + } + + @Override + public void setResultTabDirtyFlag(boolean flag) { + + } + + @Override + public boolean isUniqueKeyPresent() { + + return false; + } + + @Override + public IDSGridEditDataRow getEmptyRowForInsert(int index) { + + return null; + } + + @Override + public CommitStatus getLastCommitStatus() { + + return this.lastCommitStat; + } + + @Override + public boolean isDistributionColumnsRequired() { + + return false; + } + + @Override + public List getDistributedColumnList() { + + return new ArrayList(); + } + + @Override + public void cancelCommit() throws DatabaseCriticalException, DatabaseOperationException { + if (connection != null) { + connection.cancelQuery(); + } + + } + + @Override + public boolean isCancelled() { + return this.cancelled; + } + + @Override + public void setCancel(boolean cancel) { + this.cancelled = cancel; + + } + + @Override + public boolean isDistributionColumn(int columnIndex) { + + return false; + } + + /** + * Refresh. + * + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public void refresh() throws MPPDBIDEException { + ConnectionManager connectionManager = table.getConnectionManager(); + if (connectionManager != null) { + connection = connectionManager.getFreeConnection(); + List propertyListPostRefresh = PropertiesInfoExecuteQueryUtility.performRefresh(this.propertyName, + this.objectPropertyObject, connection); + if (propertyListPostRefresh != null) { + + serverObjectPropertiesList.clear(); + serverObjectPropertiesList = propertyListPostRefresh; + rowProviderList.clear(); + init(); + releaseConnection(); + } + } + + } + + /** + * Checks if is valid object name. + * + * @param columnIndex the column index + * @param newValue the new value + * @param rowObject the row object + * @return the string + */ + public String isValidObjectName(int columnIndex, Object newValue, IDSGridDataRow rowObject) { + + switch (this.propertyName) { + + case COLUMNS_TAB: + case CONSTRAINTS_TAB: + case INDEX_TAB: { + return isValidIndexTabObjName(columnIndex, newValue); + } + case GENERAL_TAB: { + return isValidGeneralTabObjName(columnIndex, newValue, rowObject); + } + case PropertiesConstants.USER_ROLE_PROPERTY_TAB_GENERAL: { + return isValidUserRolePropertyObjName(columnIndex, newValue, rowObject); + } + default: { + break; + } + } + + return null; + } + + /** + * Checks if is valid index tab obj name. + * + * @param columnIndex the column index + * @param newValue the new value + * @return the string + */ + private String isValidIndexTabObjName(int columnIndex, Object newValue) { + if (columnIndex == 0) { + if (newValue instanceof String && newValue.toString().length() > 63) { + return MessageConfigLoader.getProperty(IMessagesConstants.OBJECT_NAME_MORE_THAN_LIMIT_ERROR_MESSAGE); + } + } + return null; + } + + /** + * Checks if is valid general tab obj name. + * + * @param columnIndex the column index + * @param newValue the new value + * @param rowObject the row object + * @return the string + */ + private String isValidGeneralTabObjName(int columnIndex, Object newValue, IDSGridDataRow rowObject) { + if (columnIndex == 1) { + if (rowObject.getValue(0).equals(MessageConfigLoader.getProperty(IMessagesConstants.DESC_MSG))) { + if (newValue instanceof String && newValue.toString().length() > 5000) { + return MessageConfigLoader.getProperty(IMessagesConstants.MAX_CHARATCTERS_ALLOWED_FOR_TABLE_DESC); + } + } + } + return null; + } + + /** + * Checks if is valid user role property obj name. + * + * @param columnIndex the column index + * @param newValue the new value + * @param rowObject the row object + * @return the string + */ + private String isValidUserRolePropertyObjName(int columnIndex, Object newValue, IDSGridDataRow rowObject) { + if (columnIndex == 1) { + if (MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_NAME).equals(rowObject.getValue(0))) { + if (null == newValue) { + return MessageConfigLoader.getProperty(IMessagesConstants.ERR_USER_ROLE_NAME_EMPTY); + } + } + + if (MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_CONNECT_LIMIT) + .equals(rowObject.getValue(0))) { + Pattern pattern = Pattern.compile("^(((-)?[1-9]+[0-9]*)|0)$"); + Matcher matcher = pattern.matcher(newValue.toString()); + if (!matcher.find()) { + return MessageConfigLoader.getProperty(IMessagesConstants.ERR_USER_ROLE_CONNECT_LIMIT_INVALID); + } + } + + if (MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_VALID_BEGIN) + .equals(rowObject.getValue(0))) { + if (StringUtils.isEmpty(newValue.toString())) { + return MessageConfigLoader.getProperty(IMessagesConstants.ERR_USER_ROLE_BEGIN_DATE_NULL); + } + } + if (MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_VALID_UNTIL) + .equals(rowObject.getValue(0))) { + if (StringUtils.isEmpty(newValue.toString())) { + return MessageConfigLoader.getProperty(IMessagesConstants.ERR_USER_ROLE_VALID_UNTIL_DATE_NULL); + } + } + if (newValue instanceof String + && newValue.toString().length() > PropertiesConstants.USER_ROLE_COMMENT_MAXIMUM_CHARACTERS) { + return MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_COMMENT_ERROR_MESSAGE); + } + } + return null; + } + + @Override + public String getTableName() { + + return null; + } + + @Override + public int getColumnCount() { + + return 0; + } + + @Override + public List getColumnNames() { + + return null; + } + + @Override + public List getColumnDataTypeNames() { + + return new ArrayList<>(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + } + + @Override + public Database getDatabse() { + return this.objectPropertyObject.getDatabase(); + } + + @Override + public CommitStatus commit(List uniqueKeys, boolean isAtomic, IRowEffectedConfirmation rowEffectedConfirm, + DBConnection termConnection) throws MPPDBIDEException { + + return null; + } + + /** + * Gets the object property object. + * + * @return the object property object + */ + public IServerObjectProperties getObjectPropertyObject() { + return this.objectPropertyObject; + } + + /** + * init + */ + @Override + public void init(IQueryResult irq, ArrayList debugInputValueList, boolean isCallableStmt) + throws DatabaseOperationException, DatabaseCriticalException { + } + + /** + * gets next batch + */ + @Override + public List getNextBatch(ArrayList debugInputValueList) + throws DatabaseOperationException, DatabaseCriticalException { + return null; + } + + @Override + public void setFuncProcExport(boolean isFuncProcExport) { + } + + @Override + public boolean isFuncProcExport() { + return false; + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSObjectPropertiesGridDataRow.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSObjectPropertiesGridDataRow.java new file mode 100644 index 0000000000000000000000000000000000000000..5ba5eaa9e5b39e20a6f89e4cb7ab4d1f2f1855c1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSObjectPropertiesGridDataRow.java @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.util.Map; + +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.IndexMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.presentation.edittabledata.DSGridEditDataRow; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableRecordExecutionStatus; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableRecordStates; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.utils.observer.IDSGridUIListenable; + +/** + * + * Title: class + * + * Description: The Class DSObjectPropertiesGridDataRow. + * + * @since 3.0.0 + */ +public class DSObjectPropertiesGridDataRow extends DSGridEditDataRow { + + private ServerObject serverObject; + + /** + * Instantiates a new DS object properties grid data row. + * + * @param row the row + */ + public DSObjectPropertiesGridDataRow(Object[] row) { + this.rows = row.clone(); + this.rowstate = EditTableRecordStates.NOT_EDITED; + this.executionStatus = EditTableRecordExecutionStatus.NOT_EXECUTED; + } + + @Override + public Object[] getValues() { + Object[] values = rows; + prepareModifiedRow(values); + return values; + } + + /** + * Prepare modified row. + * + * @param values the values + */ + private void prepareModifiedRow(Object[] values) { + for (Map.Entry modifiedEntry : modifiedData.entrySet()) { + + values[modifiedEntry.getKey()] = modifiedEntry.getValue() != null ? modifiedEntry.getValue().toString() + : modifiedEntry.getValue(); + } + } + + @Override + public Object[] getClonedValues() { + Object[] values = rows.clone(); + prepareModifiedRow(values); + + return values; + } + + @Override + public void setValue(int columnIndex, Object newValue) { + modifiedData.put(columnIndex, newValue); + if (modifiedData.containsKey(columnIndex)) { + if (serverObject != null && newValue != null) { + updateServerObject(columnIndex, newValue); + } + } + if (this.rowstate == EditTableRecordStates.NOT_EDITED) { + rowstate = EditTableRecordStates.UPDATE; + } + getEventTable().sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_EDITED, null)); + } + + /** + * Update server object. + * + * @param columnIndex the column index + * @param newValue the new value + */ + private void updateServerObject(int columnIndex, Object newValue) { + switch (serverObject.getType()) { + case COLUMN_METADATA: { + performUpdateforColumn(columnIndex, newValue); + break; + } + case CONSTRAINT: { + ((ConstraintMetaData) serverObject).setName(newValue.toString()); + break; + } + case INDEX_METADATA: { + ((IndexMetaData) serverObject).setName(newValue.toString()); + break; + } + default: { + break; + } + } + } + + /** + * Perform updatefor column. + * + * @param columnIndex the column index + * @param value the value + */ + private void performUpdateforColumn(int columnIndex, Object value) { + switch (columnIndex) { + case 0: { + ((ColumnMetaData) serverObject).setName(value.toString()); + break; + } + case 1: { + ((ColumnMetaData) serverObject).setDataType(((ObjectPropColumnTabInfo) value).getColDatatype()); + ((ColumnMetaData) serverObject).setScale(((ObjectPropColumnTabInfo) value).getScale()); + ((ColumnMetaData) serverObject).setLenOrPrecision(((ObjectPropColumnTabInfo) value).getPrecision()); + break; + } + case 2: { + ((ColumnMetaData) serverObject).setNotNull((boolean) value); + break; + } + case 3: { + ((ColumnMetaData) serverObject).setColDescription(value.toString()); + break; + } + default: { + break; + } + } + } + + /** + * Sets the server object. + * + * @param serverObject the new server object + */ + public void setServerObject(ServerObject serverObject) { + this.serverObject = serverObject; + } + + /** + * Gets the server object. + * + * @return the server object + */ + public ServerObject getServerObject() { + return serverObject; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSUserRolePropertiesGridDataProvider.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSUserRolePropertiesGridDataProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..06549618c50c43a59612e87e19c5fb58935a816e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/DSUserRolePropertiesGridDataProvider.java @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.StringUtils; + +import org.opengauss.mppdbide.bl.serverdatacache.UserRole; +import org.opengauss.mppdbide.presentation.edittabledata.IDSGridEditDataRow; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class DSUserRolePropertiesGridDataProvider. + * + * @since 3.0.0 + */ +public class DSUserRolePropertiesGridDataProvider { + + /** + * Generate user role property general tab. + * + * @param updatedRows the updated rows + * @param userRole the user role + * @throws ParseException the parse exception + */ + public static void generateUserRolePropertyGeneralTab(List updatedRows, UserRole userRole) + throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat(MPPDBIDEConstants.USER_ROLE_DATE_DISPLAY_FORMAT); + for (IDSGridEditDataRow row : updatedRows) { + String displayName = (String) row.getValue(0); + if (MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_CONNECT_LIMIT).equals(displayName)) { + userRole.setRolConnLimit(Integer.valueOf((String) row.getValue(1))); + continue; + } + if (MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_VALID_BEGIN).equals(displayName)) { + userRole.setRolValidBegin(sdf.parse(String.valueOf(row.getValue(1)))); + continue; + } + if (MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_VALID_UNTIL).equals(displayName)) { + userRole.setRolValidUntil(sdf.parse(String.valueOf(row.getValue(1)))); + continue; + } + if (MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_RESOURCE_POOL).equals(displayName)) { + userRole.setRolResPool(String.valueOf(row.getValue(1))); + continue; + } + if (MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_COMMENT).equals(displayName)) { + userRole.setComment( + "null".equals(String.valueOf(row.getValue(1))) ? "" : String.valueOf(row.getValue(1))); + continue; + } + // for rename + if (MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_NAME).equals(displayName)) { + userRole.setName("null".equals(String.valueOf(row.getValue(1))) ? "" : String.valueOf(row.getValue(1))); + continue; + } + } + } + + /** + * Generate user role property tab privilege. + * + * @param updatedRows the updated rows + * @param userRole the user role + */ + public static void generateUserRolePropertyTabPrivilege(List updatedRows, UserRole userRole) { + for (IDSGridEditDataRow row : updatedRows) { + String displayName = (String) row.getValue(0); + if (MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_CAN_LOGIN).equals(displayName)) { + userRole.setRolCanLogin((Boolean) (row.getValue(1))); + continue; + } + if (MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_CREATE_ROLE).equals(displayName)) { + userRole.setRolCreateRole((Boolean) (row.getValue(1))); + continue; + } + if (MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_CREATE_DB).equals(displayName)) { + userRole.setRolCreateDb((Boolean) (row.getValue(1))); + continue; + } + if (MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_SYSTEM_ADMIN).equals(displayName)) { + userRole.setRolSystemAdmin((Boolean) (row.getValue(1))); + continue; + } + if (MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_AUDITOR).equals(displayName)) { + userRole.setRolAuditAdmin((Boolean) (row.getValue(1))); + continue; + } + if (MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLR_INHERIT).equals(displayName)) { + userRole.setRolInherit((Boolean) (row.getValue(1))); + continue; + } + if (MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_REPLICATION).equals(displayName)) { + userRole.setRolReplication((Boolean) (row.getValue(1))); + continue; + } + if (MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_IS_LOCK).equals(displayName)) { + userRole.setIsLock((Boolean) (row.getValue(1))); + continue; + } + } + } + + /** + * Generate user role property tab membership. + * + * @param updatedRows the updated rows + * @param userRole the user role + * @param userRoleName the user role name + */ + public static void generateUserRolePropertyTabMembership(List updatedRows, UserRole userRole, + String userRoleName) { + for (IDSGridEditDataRow row : updatedRows) { + String displayName = (String) row.getValue(0); + if (userRoleName != null && userRoleName.equals(displayName)) { + Object value = row.getValue(1); + if (value instanceof String && StringUtils.isNotEmpty(value.toString())) { + String parentNamesStr = value.toString().substring(1, value.toString().length() - 1); + if (StringUtils.isNotEmpty(parentNamesStr)) { + String[] parentNames = parentNamesStr.split(PropertiesConstants.SPLIT_STR); + List parents = Arrays.asList(parentNames).stream().map(parentName -> { + UserRole parent = new UserRole(); + parent.setName(parentName); + return parent; + }).collect(Collectors.toList()); + userRole.setParents(parents); + } else { + userRole.setParents(new ArrayList()); + } + } + if (value instanceof String && StringUtils.isEmpty(value.toString())) { + userRole.setParents(new ArrayList()); + } + } + continue; + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/FilterServerObjPropInfoUtility.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/FilterServerObjPropInfoUtility.java new file mode 100644 index 0000000000000000000000000000000000000000..88f73ecd3a50516a07aa6bebae4861a3feb9bf3e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/FilterServerObjPropInfoUtility.java @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.util.List; + +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintType; +import org.opengauss.mppdbide.bl.serverdatacache.IndexMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.IndexedColumnExpr; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.Tablespace; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class FilterServerObjPropInfoUtility. + * + * @since 3.0.0 + */ +public class FilterServerObjPropInfoUtility { + + /** + * Fetch info for row. + * + * @param serverObject the server object + * @param numOfColumns the num of columns + * @return the object[] + */ + public static Object[] fetchInfoForRow(ServerObject serverObject, int numOfColumns) { + + switch (serverObject.getType()) { + case COLUMN_METADATA: { + Object[] colInfo = new Object[numOfColumns]; + colInfo[0] = ((ColumnMetaData) serverObject).getName(); + colInfo[1] = formColumnDatatypeInfo(serverObject); + colInfo[2] = "" + !((ColumnMetaData) serverObject).isNotNull(); + colInfo[3] = ((ColumnMetaData) serverObject).getColDescription(); + return colInfo; + } + case CONSTRAINT: { + Object[] consInfo = new Object[numOfColumns]; + consInfo[0] = ((ConstraintMetaData) serverObject).getName(); + consInfo[1] = ""; + consInfo[2] = getConstraintTypeString(((ConstraintMetaData) serverObject).getConstraintType()); + consInfo[3] = ((ConstraintMetaData) serverObject).getCheckConstraintExpr(); + consInfo[4] = ((ConstraintMetaData) serverObject).isDeferable(); + consInfo[5] = ((ConstraintMetaData) serverObject).getParent().getNamespace().getName(); + consInfo[6] = ((ConstraintMetaData) serverObject).getTableSpace(); + return consInfo; + } + case INDEX_METADATA: { + Object[] indexInfo = new Object[numOfColumns]; + indexInfo[0] = ((IndexMetaData) serverObject).getName(); + indexInfo[1] = formIndexedColumns(serverObject); + indexInfo[2] = ((IndexMetaData) serverObject).isUnique(); + indexInfo[3] = ((IndexMetaData) serverObject).getWhereExpr(); + indexInfo[4] = getTablespace(((IndexMetaData) serverObject).getTablespace()); + return indexInfo; + } + default: { + break; + } + + } + + return new Object[12]; + } + + /** + * Form column datatype info. + * + * @param serverObject the server object + * @return the object + */ + private static Object formColumnDatatypeInfo(ServerObject serverObject) { + + String name = ((ColumnMetaData) serverObject).getDataType().getName(); + StringBuilder datatypeString = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + datatypeString.append(name); + ((ColumnMetaData) serverObject).formPrecisionAndArrayDimensionForQuery(datatypeString); + + return datatypeString.toString(); + } + + /** + * Gets the constraint type string. + * + * @param constraintType the constraint type + * @return the constraint type string + */ + private static Object getConstraintTypeString(ConstraintType constraintType) { + + if (constraintType == ConstraintType.CHECK_CONSTRSINT) { + return 'c'; + } else if (constraintType == ConstraintType.UNIQUE_KEY_CONSTRSINT) { + return 'u'; + } else { + return 'p'; + } + } + + /** + * Gets the tablespace. + * + * @param tablespace the tablespace + * @return the tablespace + */ + private static Object getTablespace(Tablespace tablespace) { + + if (tablespace == null) { + return ""; + } + return tablespace.getName(); + + } + + /** + * Form indexed columns. + * + * @param serverObject the server object + * @return the object + */ + private static Object formIndexedColumns(ServerObject serverObject) { + List columns = ((IndexMetaData) serverObject).getIndexedColumns(); + StringBuilder cols = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + for (IndexedColumnExpr indexCol : columns) { + if (indexCol.getCol() == null) { + cols.append(indexCol.getExpr()); + cols.append(','); + } else { + + cols.append(indexCol.getCol().getName()); + cols.append(','); + } + } + cols.deleteCharAt(cols.length() - 1); + return cols.toString(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/IObjectPropertyData.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/IObjectPropertyData.java new file mode 100644 index 0000000000000000000000000000000000000000..c10b68d73a47f751c2cd5f36d02a8ddb7fb67b55 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/IObjectPropertyData.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; + +/** + * + * Title: interface + * + * Description: The Interface IObjectPropertyData. + * + * @since 3.0.0 + */ +public interface IObjectPropertyData extends IDSGridDataProvider { + + /** + * Gets the object property name. + * + * @return the object property name + */ + String getObjectPropertyName(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/IServerObjectProperties.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/IServerObjectProperties.java new file mode 100644 index 0000000000000000000000000000000000000000..ea72366e1f148c449e7b537167a46d3344f300f1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/IServerObjectProperties.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.util.List; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; + +/** + * + * Title: interface + * + * Description: The Interface IServerObjectProperties. + * + * @since 3.0.0 + */ +public interface IServerObjectProperties { + + /** + * Gets the object name. + * + * @return the object name + */ + String getObjectName(); + + /** + * Gets the header. + * + * @return the header + */ + String getHeader(); + + /** + * Gets the unique ID. + * + * @return the unique ID + */ + String getUniqueID(); + + /** + * Gets the all properties. + * + * @param conn the conn + * @return the all properties + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws MPPDBIDEException the MPPDBIDE exception + */ + List getAllProperties(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException, MPPDBIDEException; + + /** + * Gets the parent properties. + * + * @param conn the conn + * @return the parent properties + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + * @throws MPPDBIDEException the MPPDBIDE exception + */ + default IObjectPropertyData getParentProperties(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException, MPPDBIDEException { + return null; + } + + /** + * Gets the database. + * + * @return the database + */ + Database getDatabase(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/ObjectPropColumnTabInfo.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/ObjectPropColumnTabInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..b4db6229cc6e1f8c9349fe74ee19075147df48f5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/ObjectPropColumnTabInfo.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import org.opengauss.mppdbide.bl.serverdatacache.TypeMetaData; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class ObjectPropColumnTabInfo. + * + * @since 3.0.0 + */ +public class ObjectPropColumnTabInfo { + + private TypeMetaData datatype; + private String datatypeSchema; + private int precision; + private int scale; + + /** + * Gets the datatype. + * + * @return the datatype + */ + public TypeMetaData getColDatatype() { + return datatype; + } + + /** + * Sets the datatype. + * + * @param typeMetaData the new datatype + */ + public void setColDataType(TypeMetaData typeMetaData) { + this.datatype = typeMetaData; + } + + /** + * Gets the datatype schema. + * + * @return the datatype schema + */ + public String getDataTypeSchema() { + return datatypeSchema; + } + + /** + * Sets the datatype schema. + * + * @param datatypeSchema the new datatype schema + */ + public void setDataTypeSchema(String datatypeSchema) { + this.datatypeSchema = datatypeSchema; + } + + /** + * Gets the precision. + * + * @return the precision + */ + public int getPrecision() { + return precision; + } + + /** + * Sets the precision. + * + * @param precision the new precision + */ + public void setPrecision(int precision) { + this.precision = precision; + } + + /** + * Gets the scale. + * + * @return the scale + */ + public int getScale() { + return scale; + } + + /** + * Sets the scale. + * + * @param scale the new scale + */ + public void setScale(int scale) { + this.scale = scale; + } + + @Override + public String toString() { + StringBuilder formattedString = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + formattedString.append(getColDatatype().getName()); + if (getPrecision() > 0) { + formattedString.append('('); + formattedString.append(getPrecision()); + if (getScale() > 0) { + formattedString.append(','); + formattedString.append(getScale()); + } + formattedString.append(')'); + } + + return formattedString.toString(); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/OlapConvertToObjectPropertyData.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/OlapConvertToObjectPropertyData.java new file mode 100644 index 0000000000000000000000000000000000000000..dae2129a47f333a0f775be633165e1e5f7a79360 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/OlapConvertToObjectPropertyData.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.util.List; + +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: class + * + * Description: The Class OlapConvertToObjectPropertyData. + * + * @since 3.0.0 + */ +public class OlapConvertToObjectPropertyData extends ConvertToObjectPropertyData { + + @Override + public List getObjectPropertyData(List tabName, List> properties, + ServerObject table, IServerObjectProperties objectPropertyObject) + throws DatabaseOperationException, DatabaseCriticalException { + + return super.getObjectPropertyData(tabName, properties, table, objectPropertyObject); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesConstants.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesConstants.java new file mode 100644 index 0000000000000000000000000000000000000000..d23fe636b735ff66d5c45e429924a6baaf7de330 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesConstants.java @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +/** + * + * Title: interface + * + * Description: The Interface PropertiesConstants. + * + * @since 3.0.0 + */ +public interface PropertiesConstants { + + /** + * The Constant INDEX. + */ + public static final String INDEX = "Index"; + + /** + * The Constant CONSTRAINTS. + */ + public static final String CONSTRAINTS = "Constraints"; + + /** + * The Constant COLUMNS. + */ + public static final String COLUMNS = "Columns"; + + /** + * The Constant GENERAL. + */ + public static final String GENERAL = "General"; + + /** + * The Constant PARTITION. + */ + public static final String PARTITION = "Partition"; + + /** + * The Constant KEYS. + */ + public static final String KEYS = "Keys"; + + /** + * The Constant CHECKS. + */ + public static final String CHECKS = "Checks"; + + /** + * The Constant DISTRIBUTION. + */ + public static final String DISTRIBUTION = "Distribution"; + + /** + * The Constant USER_ROLE_PROPERTY_TAB_GENERAL. + */ + public static final String USER_ROLE_PROPERTY_TAB_GENERAL = "userRolePropertyTabGeneral"; + + /** + * The Constant USER_ROLE_PROPERTY_TAB_PRIVILEGE. + */ + public static final String USER_ROLE_PROPERTY_TAB_PRIVILEGE = "userRolePropertyTabPrivilege"; + + /** + * The Constant USER_ROLE_PROPERTY_TAB_MEMBERSHIP. + */ + public static final String USER_ROLE_PROPERTY_TAB_MEMBERSHIP = "userRolePropertyTabMembership"; + + /** + * The Constant USER_ROLE_COMMENT_MAXIMUM_CHARACTERS. + */ + public static final int USER_ROLE_COMMENT_MAXIMUM_CHARACTERS = 4000; + + /** + * The Constant COMBO_BOX_MAX_VISIBLE_ITEM. + */ + public static final int COMBO_BOX_MAX_VISIBLE_ITEM = 18; + + /** + * The Constant SPLIT_STR. + */ + public static final String SPLIT_STR = ", "; + + /** + * The Constant RESOURCE_POOL_COMBO_BOX_DATA_PROVIDER. + */ + public static final String RESOURCE_POOL_COMBO_BOX_DATA_PROVIDER = "RESOURCE_POOL_COMBO_BOX_DATA_PROVIDER"; + + /** + * The Constant MEMBER_SHIP_COMBO_BOX_DATA_PROVIDER. + */ + public static final String MEMBER_SHIP_COMBO_BOX_DATA_PROVIDER = "MEMBER_SHIP_COMBO_BOX_DATA_PROVIDER"; + + /** + * The Constant EDIT_PROPERTIES_COMBO_BOX_TABLESPACE. + */ + public static final String EDIT_PROPERTIES_COMBO_BOX_TABLESPACE = "EDIT_PROPERTIES_COMBO_BOX_TABLESPACE"; + + /** + * The Constant EDIT_PROPERTIES_COMBO_BOX_CONSTRAINT_TYPE. + */ + public static final String EDIT_PROPERTIES_COMBO_BOX_CONSTRAINT_TYPE = "EDIT_PROPERTIES_COMBO_BOX_CONSTRAINT_TYPE"; + + /** + * The Constant EDIT_PROPERTIES_COMBO_BOX_COLUMNS_LIST. + */ + public static final String EDIT_PROPERTIES_COMBO_BOX_COLUMNS_LIST = "EDIT_PROPERTIES_COMBO_BOX_COLUMNS_LIST"; + + /** + * The Constant EDIT_PROPERTIES_COMBO_BOX_ON_DELETE. + */ + public static final String EDIT_PROPERTIES_COMBO_BOX_ON_DELETE = "EDIT_PROPERTIES_COMBO_BOX_ON_DELETE"; + + /** + * The Constant CREATE_PROPERTIES_COMBO_BOX_DISTRIBUTION_TYPE. + */ + public static final String CREATE_PROPERTIES_COMBO_BOX_DISTRIBUTION_TYPE = "CREATE_PROPERTIES_COMBO_BOX_DISTRIBUTION_TYPE"; + + /** + * The Constant CREATE_PROPERTIES_COMBO_BOX_PARTITION_TYPE. + */ + public static final String CREATE_PROPERTIES_COMBO_BOX_PARTITION_TYPE = "CREATE_PROPERTIES_COMBO_BOX_PARTITION_TYPE"; + + /** + * The create table compression type. + */ + String CREATE_TABLE_COMPRESSION_TYPE = "CREATE_TABLE_COMPRESSION_TYPE"; + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesDatabaseImpl.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesDatabaseImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..676942add3d32a63a5944725da7aed718f3e17fd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesDatabaseImpl.java @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DatabaseHelper; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class PropertiesDatabaseImpl. + * + * @since 3.0.0 + */ +public class PropertiesDatabaseImpl implements IServerObjectProperties { + private Database db; + private ConvertToObjectPropertyData convertToObjectPropertyData; + + /** + * Instantiates a new properties database impl. + * + * @param obj the obj + */ + public PropertiesDatabaseImpl(Object obj) { + // get the IADAPTABLE CALL + db = (Database) obj; + convertToObjectPropertyData = new OlapConvertToObjectPropertyData(); + } + + @Override + public String getObjectName() { + + return db.getQualifiedObjectName(); + } + + @Override + public List getAllProperties(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + + List tabNameList = new ArrayList(5); + List> propertyList = new ArrayList>(5); + tabNameList.add(PropertiesConstants.GENERAL); + propertyList.add(getGeneralproperty(conn)); + return convertToObjectPropertyData.getObjectPropertyData(tabNameList, propertyList, null, this); + } + + /** + * Gets the generalproperty. + * + * @param conn the conn + * @return the generalproperty + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private List getGeneralproperty(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + String qry = "SELECT oid as oid, datname AS name, pg_encoding_to_char(encoding) as encoding," + + " datallowconn as allow_conn, datconnlimit as max_conn_limit, " + + "(select spcname from pg_tablespace where oid=dattablespace) as default_tablespace, " + + "datcollate as collation, datctype as char_type " + "from pg_database where oid = " + + DatabaseHelper.fetchDBOid(db) + ';'; + + ResultSet rs = conn.execSelectAndReturnRs(qry); + boolean hasNext = false; + List props = new ArrayList(); + String[] dbPropHeader = {MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_WID_PROPERTY), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_WID_VALUE)}; + props.add(dbPropHeader); + + try { + hasNext = rs.next(); + + // only one record expected + if (hasNext) { + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.OID_MSG), + rs.getString("oid")).getProp()); + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.NAME_MSG), + rs.getString("name")).getProp()); + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.ENCODING_MSG), + rs.getString("encoding")).getProp()); + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.ALLOW_CON), + convertToBoolean(rs.getString("allow_conn"))).getProp()); + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.CONNECTION_LIMIT), + appendNoLimit(rs.getString("max_conn_limit"))).getProp()); + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.DFLT_TBSPACE), + rs.getString("default_tablespace")).getProp()); + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.COLLECTION_MSG), + rs.getString("Collation")).getProp()); + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.CHAR_TYPE), + rs.getString("char_type")).getProp()); + } + } catch (SQLException sqlExcept) { + GaussUtils.handleCriticalException(sqlExcept); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, sqlExcept); + } finally { + conn.closeResultSet(rs); + } + if (props.isEmpty()) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.CONNECTION_PROPERTIES_UNAVAILABLE)); + throw new DatabaseOperationException("PROPERT_TYABLE_UNAVAILABLE", db.getDisplayName()); + } + return props; + } + + /** + * Convert to boolean. + * + * @param value the value + * @return the string + */ + private String convertToBoolean(String value) { + + if ("t".equalsIgnoreCase(value)) { + return "" + true; + } else if ("f".equalsIgnoreCase(value)) { + return "" + false; + } + + return ""; + } + + /** + * Append no limit. + * + * @param value the value + * @return the string + */ + public String appendNoLimit(String value) { + if ("-1".equalsIgnoreCase(value)) { + return value + "(No Limit)"; + } + return value; + } + + @Override + public String getHeader() { + return db.getDbName() + '@' + db.getServerName(); + } + + @Override + public String getUniqueID() { + return db.getOid() + '@' + db.getServerName() + "properties"; + } + + @Override + public Database getDatabase() { + return db; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesInfoExecuteQueryUtility.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesInfoExecuteQueryUtility.java new file mode 100644 index 0000000000000000000000000000000000000000..c7ee67a49a9934c0451038ed1d4a13528af884c4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesInfoExecuteQueryUtility.java @@ -0,0 +1,406 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.util.List; +import java.util.Map; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.IndexMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableRecordExecutionStatus; +import org.opengauss.mppdbide.presentation.edittabledata.IDSGridEditDataRow; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class PropertiesInfoExecuteQueryUtility. + * + * @since 3.0.0 + */ +public class PropertiesInfoExecuteQueryUtility { + + /** + * Adds the column query. + * + * @param column the column + * @param conn the conn + * @param row the row + */ + public static void addColumnQuery(ColumnMetaData column, DBConnection conn, IDSGridEditDataRow row) { + if (column != null) { + try { + column.execAlterAddColumn(conn); + if (row.getValue(3) != null) { + + column.setDescription(column.getObjectFullName(), row.getValue(3).toString(), conn); + } + row.setExecutionStatus(EditTableRecordExecutionStatus.SUCCESS); + } catch (DatabaseOperationException e) { + + handleFailureOperations(e, row); + } catch (DatabaseCriticalException e) { + handleFailureOperations(e, row); + } + } + + } + + /** + * Adds the constraint query. + * + * @param constraint the constraint + * @param freeConnection the free connection + * @param row the row + */ + public static void addConstraintQuery(ConstraintMetaData constraint, DBConnection freeConnection, + IDSGridEditDataRow row) { + + if (constraint != null) { + try { + + constraint.execAlterAddConstraint(constraint.getParent(), freeConnection); + row.setExecutionStatus(EditTableRecordExecutionStatus.SUCCESS); + } catch (DatabaseOperationException e) { + + handleFailureOperations(e, row); + } catch (DatabaseCriticalException e) { + handleFailureOperations(e, row); + } + + } + + } + + /** + * Handle failure operations. + * + * @param exception the e + * @param row the row + */ + public static void handleFailureOperations(MPPDBIDEException exception, IDSGridEditDataRow row) { + row.setExecutionStatus(EditTableRecordExecutionStatus.FAILED); + row.setCommitStatusMessage(generateFailureMessages(exception)); + } + + /** + * Generate failure messages. + * + * @param exception the e + * @return the string + */ + private static String generateFailureMessages(MPPDBIDEException exception) { + StringBuilder strBlr = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + strBlr.append(MessageConfigLoader.getProperty(IMessagesConstants.ERR_EDIT_TABLE_COMMIT_FAIL)); + strBlr.append("[").append(exception.getServerMessage()).append("]").append(MPPDBIDEConstants.LINE_SEPARATOR); + strBlr.append("Cancel changes,refresh and try again"); + + return strBlr.toString(); + + } + + /** + * Delete column query. + * + * @param column the column + * @param dbConnection the db connection + * @param row the row + */ + public static void deleteColumnQuery(ColumnMetaData column, DBConnection dbConnection, IDSGridEditDataRow row) { + try { + column.execDrop(dbConnection); + row.setExecutionStatus(EditTableRecordExecutionStatus.SUCCESS); + } catch (DatabaseOperationException e) { + handleFailureOperations(e, row); + } catch (DatabaseCriticalException e) { + handleFailureOperations(e, row); + } + } + + /** + * Update column info query. + * + * @param dbConnection the db connection + * @param row the row + * @param column the column + */ + public static void updateColumnInfoQuery(DBConnection dbConnection, IDSGridEditDataRow row, ColumnMetaData column) { + List modifiedColumns = row.getModifiedColumns(); + int size = modifiedColumns.size(); + try { + for (int i = 0; i < size; i++) { + switch (modifiedColumns.get(i)) { + case 0: { + setFirstClmData(dbConnection, row, column); + break; + } + case 1: { + setSecondClmData(dbConnection, row, column); + break; + } + case 2: { + setThirdClmData(dbConnection, row, column); + break; + } + case 3: { + setFourthClmData(dbConnection, row, column); + break; + } + default: { + break; + } + + } + } + + } catch (DatabaseOperationException e) { + handleFailureOperations(e, row); + } catch (DatabaseCriticalException e) { + handleFailureOperations(e, row); + } + } + + private static void setFourthClmData(DBConnection dbConnection, IDSGridEditDataRow row, ColumnMetaData column) + throws DatabaseOperationException, DatabaseCriticalException { + Object obj = row.getValue(3); + String updatedcomment = ""; + if (obj != null) { + updatedcomment = row.getValue(3).toString(); + } + column.setDescription(column.getObjectFullName(), updatedcomment, dbConnection); + row.setExecutionStatus(EditTableRecordExecutionStatus.SUCCESS); + } + + private static void setThirdClmData(DBConnection dbConnection, IDSGridEditDataRow row, ColumnMetaData column) + throws DatabaseOperationException, DatabaseCriticalException { + /* + * modifiedIsNullValue is used to update the isNotNull value as the + * existing rows on update does not update the value on server object as + * the server object for existings rows is null. Same fix has been done + * in rename column + */ + Boolean modifiedIsNullValue = (Boolean) row.getValue(2); + if (modifiedIsNullValue != column.isNotNull()) { + column.setNotNull(modifiedIsNullValue); + } + column.execAlterToggleSetNull(dbConnection); + row.setExecutionStatus(EditTableRecordExecutionStatus.SUCCESS); + } + + private static void setSecondClmData(DBConnection dbConnection, IDSGridEditDataRow row, ColumnMetaData column) + throws DatabaseOperationException, DatabaseCriticalException { + Object value = row.getValue(1); + setModifiedValuesToColumn(column, value); + column.execChangeDataType(dbConnection); + row.setExecutionStatus(EditTableRecordExecutionStatus.SUCCESS); + } + + private static void setFirstClmData(DBConnection dbConnection, IDSGridEditDataRow row, ColumnMetaData column) + throws DatabaseCriticalException, DatabaseOperationException { + column.execRename((String) row.getValue(0), dbConnection); + row.setExecutionStatus(EditTableRecordExecutionStatus.SUCCESS); + column.setName((String) row.getValue(0)); + } + + /** + * Sets the modified values to column. + * + * @param column the column + * @param value the value + */ + private static void setModifiedValuesToColumn(ColumnMetaData column, Object value) { + + column.setLenOrPrecision(((ObjectPropColumnTabInfo) value).getPrecision()); + column.setScale(((ObjectPropColumnTabInfo) value).getScale()); + column.setDataType(((ObjectPropColumnTabInfo) value).getColDatatype()); + + String datatypeSchema = ((ObjectPropColumnTabInfo) value).getDataTypeSchema(); + if (datatypeSchema != null && !datatypeSchema.isEmpty()) { + column.setDataTypeScheam(datatypeSchema); + } + + } + + /** + * Perform refresh. + * + * @param propertyName the property name + * @param objectPropertyObject the object property object + * @param conn the conn + * @return the list + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public static List performRefresh(String propertyName, IServerObjectProperties objectPropertyObject, + DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + + switch (propertyName) { + case "General": { + Map commentsList = ((PropertiesTableImpl) objectPropertyObject).getComments(conn); + return ((PropertiesTableImpl) objectPropertyObject).getGeneralProperty(conn, commentsList); + } + + case "Columns": { + Map commentsList1 = ((PropertiesTableImpl) objectPropertyObject).getComments(conn); + return ((PropertiesTableImpl) objectPropertyObject).getColumnInfo(conn, commentsList1); + } + case "Constraints": { + return ((PropertiesTableImpl) objectPropertyObject).getConstraintInfo(conn); + } + case "Index": { + return ((PropertiesTableImpl) objectPropertyObject).getIndexInfo(conn); + } + default: { + break; + } + + } + return null; + } + + /** + * Delete constraint query. + * + * @param cons the cons + * @param freeConnection the free connection + * @param row the row + */ + public static void deleteConstraintQuery(ConstraintMetaData cons, DBConnection freeConnection, + IDSGridEditDataRow row) { + + try { + cons.execDrop(freeConnection); + row.setExecutionStatus(EditTableRecordExecutionStatus.SUCCESS); + } catch (DatabaseOperationException e) { + handleFailureOperations(e, row); + } catch (DatabaseCriticalException e) { + handleFailureOperations(e, row); + } + + } + + /** + * Update constraint info query. + * + * @param freeConnection the free connection + * @param row the row + * @param cons the cons + */ + public static void updateConstraintInfoQuery(DBConnection freeConnection, IDSGridEditDataRow row, + ConstraintMetaData cons) { + try { + cons.execRenameConstraint((String) row.getValue(0), freeConnection); + row.setExecutionStatus(EditTableRecordExecutionStatus.SUCCESS); + } catch (DatabaseOperationException e) { + handleFailureOperations(e, row); + } catch (DatabaseCriticalException e) { + handleFailureOperations(e, row); + } + + } + + /** + * Adds the index query. + * + * @param index the index + * @param freeConnection the free connection + * @param row the row + * @param table the table + */ + public static void addIndexQuery(IndexMetaData index, DBConnection freeConnection, IDSGridEditDataRow row, + TableMetaData table) { + + try { + table.execCreateIndex(index, freeConnection); + row.setExecutionStatus(EditTableRecordExecutionStatus.SUCCESS); + } catch (DatabaseOperationException e) { + handleFailureOperations(e, row); + } catch (DatabaseCriticalException e) { + handleFailureOperations(e, row); + + } + } + + /** + * Delete index query. + * + * @param index the index + * @param freeConnection the free connection + * @param row the row + */ + public static void deleteIndexQuery(IndexMetaData index, DBConnection freeConnection, IDSGridEditDataRow row) { + try { + index.drop(freeConnection); + row.setExecutionStatus(EditTableRecordExecutionStatus.SUCCESS); + } catch (DatabaseOperationException e) { + handleFailureOperations(e, row); + + } catch (DatabaseCriticalException e) { + handleFailureOperations(e, row); + + } + } + + /** + * Update index info query. + * + * @param freeConnection the free connection + * @param row the row + * @param index the index + */ + public static void updateIndexInfoQuery(DBConnection freeConnection, IDSGridEditDataRow row, IndexMetaData index) { + + try { + index.rename((String) row.getValue(0), freeConnection); + row.setExecutionStatus(EditTableRecordExecutionStatus.SUCCESS); + } catch (DatabaseOperationException e) { + handleFailureOperations(e, row); + } catch (DatabaseCriticalException e) { + handleFailureOperations(e, row); + } + } + + /** + * Sets the table description query. + * + * @param table the table + * @param freeConnection the free connection + * @param row the row + */ + public static void setTableDescriptionQuery(TableMetaData table, DBConnection freeConnection, + IDSGridEditDataRow row) { + try { + table.execSetTableDescription((String) row.getValue(1), freeConnection); + row.setExecutionStatus(EditTableRecordExecutionStatus.SUCCESS); + } catch (DatabaseCriticalException e) { + handleFailureOperations(e, row); + } catch (DatabaseOperationException e) { + handleFailureOperations(e, row); + + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesPartitionTableImpl.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesPartitionTableImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..b591b6fde824c313ddfbe7ca69970ea5377f0be6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesPartitionTableImpl.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.bl.serverdatacache.PartitionMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.PartitionTable; +import org.opengauss.mppdbide.bl.serverdatacache.PartitionTypeEnum; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class PropertiesPartitionTableImpl. + * + * @since 3.0.0 + */ +public class PropertiesPartitionTableImpl extends PropertiesTableImpl { + + private String partitionType; + private PartitionTable partitionTable; + private OlapConvertToObjectPropertyData convertToObjectPropertyData; + + /** + * Instantiates a new properties partition table impl. + * + * @param obj the obj + */ + public PropertiesPartitionTableImpl(Object obj) { + super(obj); + this.partitionTable = (PartitionTable) obj; + convertToObjectPropertyData = new OlapConvertToObjectPropertyData(); + } + + @Override + public List getAllProperties(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + + super.getAllProperties(conn); + if (!(this.partitionTable.getPartitions().getSize() == 0)) { + this.partitionType = partitionTable.getPartitions().getItem(0).getPartitionType(); + } else { + this.partitionType = PartitionTypeEnum.BY_RANGE.getTypeName(); + } + tabNameList.add(PropertiesConstants.PARTITION); + tableProperties.add(getPartitionInfo(conn)); + tableProperties.get(0) + .add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.PARTITION_TAB_TYPE), + partitionType).getProp()); + tableProperties.get(0) + .add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.PARTITION_COLUMN_ID), + partitionTable.getPartKey()).getProp()); + return convertToObjectPropertyData.getObjectPropertyData(tabNameList, tableProperties, this.partitionTable, + this); + + } + + /** + * Gets the partition info. + * + * @param conn the conn + * @return the partition info + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private List getPartitionInfo(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + ArrayList partitionMetadataList = PartitionTable.class.cast(table).getPartitions().getList(); + Map partInfo = getPartitionData(conn); + List partitionList = new ArrayList(5); + String partName = null; + String[] partitionHeader = {MessageConfigLoader.getProperty(IMessagesConstants.PROP_PARTITION_PARTITIONNAME), + MessageConfigLoader.getProperty(IMessagesConstants.PROP_PARTITION_PARTITIONBOUNDARIES), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_TABLESPACE)}; + + partitionList.add(partitionHeader); + for (PartitionMetaData part : partitionMetadataList) { + int jindex = 0; + partName = part.getName(); + String[] partitionsInfo = new String[partitionHeader.length]; + partitionsInfo[jindex] = partName; + + partitionsInfo[++jindex] = partInfo.get(partName)[0]; + partitionsInfo[++jindex] = partInfo.get(partName)[1]; + + partitionList.add(partitionsInfo); + } + return partitionList; + } + + /** + * Gets the partition data. + * + * @param conn the conn + * @return the partition data + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private Map getPartitionData(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + ResultSet rs = null; + Map partMap = new HashMap<>(); + String query = "select pr.relname ,array_to_string(pr.boundaries, ','::text, 'MAXVALUE'::text) as boundaries ," + + "t.spcname from pg_partition pr " + + "left join pg_tablespace t on (pr.reltablespace=t.oid) where parttype in('p,v') and pr.parentid =" + + partitionTable.getOid(); + rs = conn.execSelectAndReturnRs(query); + boolean hasNext; + try { + hasNext = rs.next(); + while (hasNext) { + String[] partInfo = new String[2]; + partInfo[0] = rs.getString("boundaries"); + partInfo[1] = rs.getString("spcname"); + partMap.put(rs.getString("relname"), partInfo); + hasNext = rs.next(); + } + } catch (SQLException ex) { + GaussUtils.handleCriticalException(ex); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, ex); + } finally { + conn.closeResultSet(rs); + } + return partMap; + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesSynonymImpl.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesSynonymImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..42ada2be016f349b262075a229c8bdac153cfe6e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesSynonymImpl.java @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.bl.serverdatacache.SynonymMetaData; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.SynonymConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: Class + * + * Description: The Class ZPropertiesSynonymImpl + * + * @since 3.0.0 + */ +public class PropertiesSynonymImpl implements IServerObjectProperties { + private SynonymMetaData synonymMetaData; + private OlapConvertToObjectPropertyData convertToObjectPropertyData; + + /** + * Instantiates a new properties synonym impl. + * + * @param obj the object + */ + public PropertiesSynonymImpl(Object obj) { + this.synonymMetaData = (SynonymMetaData) obj; + convertToObjectPropertyData = new OlapConvertToObjectPropertyData(); + } + + @Override + public String getObjectName() { + return this.synonymMetaData.getName(); + } + + @Override + public String getHeader() { + return this.synonymMetaData.getWindowTitleName(); + } + + @Override + public String getUniqueID() { + return this.synonymMetaData.getOid() + '@' + synonymMetaData.getParent().getDisplayName() + ".properties"; + } + + @Override + public List getAllProperties(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException, MPPDBIDEException { + List tabName = new ArrayList(5); + List> propertyList = new ArrayList>(5); + tabName.add(PropertiesConstants.GENERAL); + propertyList.add(getSynonymProperties(conn)); + + return convertToObjectPropertyData.getObjectPropertyData(tabName, propertyList, null, this); + } + + @Override + public Database getDatabase() { + return this.synonymMetaData.getDatabase(); + } + + /** + * @Title: getSynonymProperties + * @Description: get the synonym properties + * @param conn the db connection + * @return List the synonym properties + * @throws MPPDBIDEException the MPPDBIDE exception + * + */ + public List getSynonymProperties(DBConnection conn) throws MPPDBIDEException { + ResultSet rs = null; + PreparedStatement preparedStatement = null; + try { + preparedStatement = conn.getPrepareStmt(SynonymMetaData.REFRESH_SYNONYM_STATEMENT); + preparedStatement.setString(1, synonymMetaData.getParent().getQualifiedObjectName()); + preparedStatement.setString(2, synonymMetaData.getName()); + rs = preparedStatement.executeQuery(); + boolean hasNext = rs.next(); + while (hasNext) { + synonymMetaData.setName(rs.getString(SynonymConstants.SYN_NAME)); + synonymMetaData.setOwner(rs.getString(SynonymConstants.OWNER.toLowerCase(Locale.ENGLISH))); + synonymMetaData.setObjectOwner(rs.getString(SynonymConstants.SCHEMA_NAME)); + synonymMetaData.setObjectName(rs.getString(SynonymConstants.TAB_NAME)); + hasNext = rs.next(); + } + } catch (SQLException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID), + exe); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID); + } finally { + conn.closeResultSet(rs); + conn.closeStatement(preparedStatement); + } + + List str = new ArrayList(5); + String[] viewPropHeader = {MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_WID_PROPERTY), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_WID_VALUE)}; + str.add(viewPropHeader); + str.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_SYNONYM_NAME), + synonymMetaData.getName()).getProp()); + str.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_SYNONYM_OWNER), + synonymMetaData.getObjectOwner()).getProp()); + str.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_OBJECT_OWNER), + synonymMetaData.getOwner()).getProp()); + str.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_OBJECT_NAME), + synonymMetaData.getObjectName()).getProp()); + return str; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesTableImpl.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesTableImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..ef7aa63bc1eaeabeb75d398a2c67cd46b90a3432 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesTableImpl.java @@ -0,0 +1,664 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintMetaDataUtils; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.IndexMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.IndexedColumnExpr; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.presentation.objectbrowser.ObjectBrowserObjectRefreshPresentation; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class PropertiesTableImpl. + * + * @since 3.0.0 + */ +public class PropertiesTableImpl implements IServerObjectProperties { + private static final String TABLE_DESC = "tableDesc"; + + /** + * The table. + */ + protected TableMetaData table; + + /** + * The tab name list. + */ + protected List tabNameList; + + /** + * The table properties. + */ + protected List> tableProperties; + private String defaultTableSpaceName; + private ConvertToObjectPropertyData convertToObjectPropertyData; + + /** + * Instantiates a new properties table impl. + * + * @param obj the obj + */ + public PropertiesTableImpl(Object obj) { + this.table = (TableMetaData) obj; + tabNameList = null; + tableProperties = null; + convertToObjectPropertyData = new OlapConvertToObjectPropertyData(); + + } + + /** + * Gets the object name. + * + * @return the object name + */ + @Override + public String getObjectName() { + return table.getQualifiedObjectName(); + } + + /** + * Gets the all properties. + * + * @param conn the conn + * @return the all properties + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public List getAllProperties(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + if (!table.isLoaded()) { + ObjectBrowserObjectRefreshPresentation.refreshSeverObject(table); + } + tabNameList = new ArrayList(5); + tableProperties = new ArrayList>(5); + tabNameList.add(PropertiesConstants.GENERAL); + tabNameList.add(PropertiesConstants.COLUMNS); + tabNameList.add(PropertiesConstants.CONSTRAINTS); + tabNameList.add(PropertiesConstants.INDEX); + /* + * get the comments associated with the table. + */ + Map commentsList = getComments(conn); + defaultTableSpaceName = this.table.getDatabase().getDBDefaultTblSpc(); + tableProperties.add(getGeneralProperty(conn, commentsList)); + tableProperties.add(getColumnInfo(conn, commentsList)); + tableProperties.add(getConstraintInfo(conn)); + tableProperties.add(getIndexInfo(conn)); + return convertToObjectPropertyData.getObjectPropertyData(tabNameList, tableProperties, this.table, this); + + } + + /** + * Gets the general property. + * + * @param conn the conn + * @param commentsList the comments list + * @return the general property + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public List getGeneralProperty(DBConnection conn, Map commentsList) + throws DatabaseCriticalException, DatabaseOperationException { + + String qry = getQueryForFetchingGeneralProperties(); + + ResultSet rs = conn.execSelectAndReturnRs(qry); + boolean hasNext = false; + List props = new ArrayList(5); + String[] genPropHeader = {MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_WID_PROPERTY), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_WID_VALUE)}; + props.add(genPropHeader); + try { + hasNext = rs.next(); + + /* only one record expected */ + if (hasNext) { + addGeneralPropertiesInList(commentsList, rs, props); + + } else { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.TABLE_DOES_NOT_EXIST)); + throw new DatabaseOperationException(IMessagesConstants.TABLE_DOES_NOT_EXIST); + + } + } catch (SQLException exception) { + GaussUtils.handleCriticalException(exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + conn.closeResultSet(rs); + } + + return props; + } + + private void addGeneralPropertiesInList(Map commentsList, ResultSet rs, List props) + throws SQLException { + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.OID_MSG), + Long.toString(table.getOid())).getProp()); + + String tableName = table.getName(); + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.TABLE_PROPERTIES_TABLE_NAME), + tableName).getProp()); + + String tblSpcName = rs.getString("spcname"); + if ("DEFAULT".equals(tblSpcName)) { + tblSpcName = defaultTableSpaceName; + } + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.TABLESPACE_MSG), tblSpcName) + .getProp()); + + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.IS_TEMP), + table.isTempTable() ? "true" : "false").getProp()); + String tabletype = rs.getString("relpersistence"); + getTypeProperty(props, tabletype); + props.add( + new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.OWNER_MSG), rs.getString("Owner")) + .getProp()); + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.PAGES_MSG), + Integer.toString(rs.getInt("pages"))).getProp()); + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.ROW_COUNT), + Long.toString(rs.getLong("rows_count"))).getProp()); + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.HAS_INDEX), + rs.getBoolean("has_index") ? "true" : "false").getProp()); + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.IS_SHARED), + rs.getBoolean("is_shared") ? "true" : "false").getProp()); + + StringBuilder sbOpts = getTableOptionProperty(rs, props); + String hashOId = ""; + if (rs.getBoolean("hashoid")) { + hashOId = "yes"; + } else { + hashOId = "no"; + } + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.HAS_OID), hashOId).getProp()); + if (sbOpts.length() > 0) { + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.OPTION_MSG), + sbOpts.toString()).getProp()); + } + + String tableDescriptionPos = TABLE_DESC; + + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.DESC_MSG), + commentsList.get(tableDescriptionPos)).getProp()); + } + + private String getQueryForFetchingGeneralProperties() { + String qry = "SELECT tbl.relpersistence as relpersistence, case when tbl.reltablespace = 0 then" + + " 'DEFAULT' else tblsp.spcname end, auth.rolname as owner, tbl.relpages pages, " + + "tbl.reltuples as rows_count, tbl.relhasindex as has_index, tbl.relisshared as is_shared, " + + "tbl.relchecks as check_count, tbl.relhaspkey as has_pkey, tbl.relhasrules as has_rules, " + + "tbl.relhastriggers as has_triggers, array_to_string(tbl.reloptions, ',') as options," + + "tbl.relhasoids as hashoid, d.description as tbl_desc " + + "FROM pg_class tbl LEFT JOIN pg_roles auth on " + "(tbl.relowner = auth.oid) left join " + + "pg_description d on (tbl.oid = d.objoid) " + + "LEFT JOIN pg_tablespace tblsp ON (tbl.reltablespace = tblsp.oid) WHERE tbl.oid = " + table.getOid() + + ';'; + return qry; + } + + /** + * Gets the constraint info. + * + * @param conn the conn + * @return the constraint info + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public List getConstraintInfo(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + List uiConstraintList = new ArrayList(5); + List infoList = getConstrainColumnlist(conn); + + String[] consHeader = {MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_CONSTRAINT_CONSTRAINTNAME), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_CONSTRAINT_COLUMNS), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_CONSTRAINT_TYPE), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_EXPRESSION), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_CONSTRAINT_ISDEFFERED), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_CONSTRAINT_SCHEMA), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_TABLESPACE)}; + uiConstraintList.add(consHeader); + for (ConstraintInfo info : infoList) { + int jindex = 0; + String[] consInfo = new String[consHeader.length]; + consInfo[jindex] = info.getConstraintName(); + consInfo[++jindex] = formConsColToDisplay(info.getColumns()); + consInfo[++jindex] = info.getConstraintType(); + consInfo[++jindex] = info.getConstraintExpr(); + consInfo[++jindex] = "" + info.isDeferred(); + consInfo[++jindex] = info.getConsSchema(); + consInfo[++jindex] = info.getTableSpace() == null ? defaultTableSpaceName : info.getTableSpace(); + uiConstraintList.add(consInfo); + } + + return uiConstraintList; + } + + /** + * Gets the index info. + * + * @param conn the conn + * @return the index info + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public List getIndexInfo(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + // index expression need to be removed after the confirmation + List indexList = getIndexMetaData(conn); + List uiIndexList = new ArrayList(); + String[] indexHeader = {MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_INDEX_INDEXNAME), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_INDEX_INDEXCOLUMNS), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_INDEX_ISUNIQUE), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_EXPRESSION), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_TABLESPACE)}; + + uiIndexList.add(indexHeader); + for (IndexMetaData index : indexList) { + int jindex = 0; + String[] indexInfo = new String[indexHeader.length]; + indexInfo[jindex] = index.getName(); + indexInfo[++jindex] = splitIndexedColumns(index.getIndexedColumns()); + indexInfo[++jindex] = "" + index.isUnique(); + indexInfo[++jindex] = index.getWhereExpr() == null ? getWhereExpr(index, conn) : index.getWhereExpr(); + indexInfo[++jindex] = index.getTablespc(); + uiIndexList.add(indexInfo); + } + return uiIndexList; + } + + /** + * Gets the where expr. + * + * @param index the index + * @param conn the conn + * @return the where expr + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private String getWhereExpr(IndexMetaData index, DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + + return index.getwhereExpresionforProperty(conn); + } + + /** + * Split indexed columns. + * + * @param indexedColumns the indexed columns + * @return the string + */ + private String splitIndexedColumns(ArrayList indexedColumns) { + String indexes = indexedColumns.toString(); + return indexes.substring(1, indexes.length() - 1); + } + + /** + * Form cons col to display. + * + * @param colIndexes the col indexes + * @return the string + */ + private String formConsColToDisplay(String colIndexes) { + String colNames = colIndexes.substring(1, colIndexes.length() - 1); + List splittedColNames = Arrays.asList(colNames.split(",")); + StringBuilder str = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + List colMetadataList = table.getColumnMetaDataList(); + int index = 0; + for (ColumnMetaData colMetadata : colMetadataList) { + if (index == splittedColNames.size()) { + break; + } + if (colMetadata.getOid() == Integer.parseInt(splittedColNames.get(index))) { + str.append(colMetadata.getName()); + str.append(","); + index++; + } + } + str.deleteCharAt(str.length() - 1); + + return str.toString(); + } + + /** + * Gets the column info. + * + * @param dbcon the dbcon + * @param commentsList the comments list + * @return the column info + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public List getColumnInfo(DBConnection dbcon, Map commentsList) + throws DatabaseCriticalException, DatabaseOperationException { + List colMetaData = getColumnMetaData(dbcon); + List uiColumnList = new ArrayList(5); + String[] columnHeader = {MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_COLUMNS_COLUMNSNAME), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_COLUMNS_DATATYPE), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_COLUMNS_ISNULLABLE), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_COLUMNS_COMMENTS)}; + uiColumnList.add(columnHeader); + for (ColumnMetaData col : colMetaData) { + String[] colInfo = new String[columnHeader.length]; + int cnt = 0; + colInfo[cnt] = col.getName(); + if (null != col.getDataType()) { + colInfo[++cnt] = col.getDisplayDatatype(); + } else { + + colInfo[++cnt] = ""; + } + // retrieve the boolean value and change to string + colInfo[++cnt] = "" + !col.isNotNull(); + if (commentsList.containsKey(col.getName())) { + + colInfo[++cnt] = commentsList.get(col.getName()); + } + uiColumnList.add(colInfo); + + } + + return uiColumnList; + } + + /** + * Gets the comments. + * + * @param conn the conn + * @return the comments + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public Map getComments(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + + String comment = null; + String attributeName = ""; + Map commentInfo = new HashMap(); + ResultSet rs = null; + try { + + String query = "select a.attrelid,a.attname ,d.objsubid, d.description from pg_description d " + + "left join pg_attribute a on (d.objoid = a.attrelid and a.attnum = d.objsubid)" + + " where d.objoid = " + this.table.getOid() + ';'; + rs = conn.execSelectAndReturnRs(query); + + while (rs.next()) { + comment = rs.getString("description"); + attributeName = rs.getString("attname"); + + if (attributeName == null) { + attributeName = TABLE_DESC; + } + commentInfo.put(attributeName, comment); + + } + + } catch (SQLException exc) { + GaussUtils.handleCriticalException(exc); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exc); + + } finally { + conn.closeResultSet(rs); + } + return commentInfo; + } + + /** + * Gets the header. + * + * @return the header + */ + @Override + public String getHeader() { + return table.getNameSpaceName() + '.' + table.getName() + '-' + table.getDatabaseName() + '@' + + table.getServerName(); + } + + /** + * Gets the unique ID. + * + * @return the unique ID + */ + @Override + public String getUniqueID() { + return table.getOid() + '@' + table.getServerName() + "properties"; + } + + /** + * Gets the type property. + * + * @param props the props + * @param tabletype the tabletype + * @return the type property + */ + private void getTypeProperty(List props, String tabletype) { + switch (getEnumTableType(tabletype)) { + case UNLOGGED: { + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.TYEP_MSG), + MessageConfigLoader.getProperty(IMessagesConstants.CREATE_TABLE_UNLOGGED)).getProp()); + break; + } + case TEMPORARY: { + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.TYEP_MSG), + MessageConfigLoader.getProperty(IMessagesConstants.CREATE_TABLE_TEMPORARY)).getProp()); + break; + } + case PERMANENT: { + props.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.TYEP_MSG), + MessageConfigLoader.getProperty(IMessagesConstants.CREATE_TABLE_NORMAL)).getProp()); + break; + } + default: { + break; + } + } + } + + /** + * + * Title: enum + * + * Description: The Enum TableType. + */ + private enum TableType { + + UNLOGGED, TEMPORARY, PERMANENT; + + } + + /** + * Gets the enum table type. + * + * @param tbltype the tbltype + * @return the enum table type + */ + private TableType getEnumTableType(String tbltype) { + if ("u".equals(tbltype)) { + return TableType.UNLOGGED; + } else if ("t".equals(tbltype) || "g".equals(tbltype)) { + return TableType.TEMPORARY; + } else { + return TableType.PERMANENT; + } + + } + + /** + * Gets the table option property. + * + * @param rs the rs + * @param props the props + * @return the table option property + * @throws SQLException the SQL exception + */ + private StringBuilder getTableOptionProperty(ResultSet rs, List props) throws SQLException { + String optionsStr = rs.getString("options"); + String[] optionsArr = optionsStr != null ? optionsStr.split(",") : null; + StringBuilder sbOpts = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + if (null != optionsArr && optionsArr.length > 0) { + int index = 0; + int optLen = optionsArr.length; + String[] opts = null; + for (; index < optLen; index++) { + if (optionsArr[index] != null && optionsArr[index].contains("=")) { + opts = optionsArr[index].split("="); + String filterTableOptionProperty = splitTableOptionProperty(opts[0]); + if (null != filterTableOptionProperty) { + props.add(new ServerProperty(filterTableOptionProperty, opts[1]).getProp()); + } + + } else { + sbOpts.append(optionsArr[index]); + } + } + } + return sbOpts; + } + + /** + * Split table option property. + * + * @param options the options + * @return the string + */ + private String splitTableOptionProperty(String options) { + switch (options) { + case "orientation": { + return MessageConfigLoader.getProperty(IMessagesConstants.TABLEPROPERTIES_OPTIONS_ORIENTATION); + } + case "fillfactor": { + return MessageConfigLoader.getProperty(IMessagesConstants.TABLEPROPERTIES_OPTIONS_FILLFACTOR); + } + case "compression": { + return MessageConfigLoader.getProperty(IMessagesConstants.TABLEPROPERTIES_OPTIONS_COMPRESSION); + } + case "MAX_Batchrow": { + return MessageConfigLoader.getProperty(IMessagesConstants.TABLEPROPERTIES_OPTIONS_MAX_BATCHROW); + } + case "Partial_cluster_rows": { + return MessageConfigLoader.getProperty(IMessagesConstants.TABLEPROPERTIES_OPTIONS_PARTIAL_CLUSTER_ROWS); + } + case "version": { + return MessageConfigLoader.getProperty(IMessagesConstants.VERSION); + } + default: { + return null; + } + } + + } + + /** + * Gets the constrain columnlist. + * + * @param conn the conn + * @return the constrain columnlist + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + private List getConstrainColumnlist(DBConnection conn) + throws DatabaseCriticalException, DatabaseOperationException { + + String columnslist = ConstraintMetaDataUtils.getTableConstraintQry(this.table.getOid()); + + ConstraintInfo info = null; + List consInfoList = new ArrayList(5); + ResultSet rs = null; + try { + + rs = conn.execSelectAndReturnRs(columnslist); + boolean hasNext = rs.next(); + while (hasNext) { + info = new ConstraintInfo(); + info.setConstraintName(rs.getString("constraintname")); + info.setColumns(rs.getString("columnlist")); + info.setConstraintExpr(rs.getString("const_def")); + info.setConstraintType(rs.getString("constrainttype")); + info.setTablespace(rs.getString("tablespace")); + Namespace ns = this.table.getDatabase().getNameSpaceById(rs.getLong("namespaceid")); + info.setConsSchema(ns.getDisplayName()); + info.setDeferred(rs.getBoolean("deferred")); + consInfoList.add(info); + hasNext = rs.next(); + } + + } catch (SQLException ex) { + GaussUtils.handleCriticalException(ex); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, ex); + + } finally { + conn.closeResultSet(rs); + + } + return consInfoList; + } + + /** + * Gets the column meta data. + * + * @param dbcon the dbcon + * @return the column meta data + */ + private List getColumnMetaData(DBConnection dbcon) { + + List listCol = this.table.getColumnMetaDataList(); + + return listCol; + } + + /** + * Gets the index meta data. + * + * @param dbcon the dbcon + * @return the index meta data + */ + private List getIndexMetaData(DBConnection dbcon) { + List listIndex = this.table.getIndexMetaDataList(); + return listIndex; + } + + /** + * Gets the database. + * + * @return the database + */ + @Override + public Database getDatabase() { + return this.table.getDatabase(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesUserRoleImpl.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesUserRoleImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..14377edc037091a911657534b4538af9f176c913 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesUserRoleImpl.java @@ -0,0 +1,309 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.bl.serverdatacache.UserRole; +import org.opengauss.mppdbide.bl.serverdatacache.UserRoleFieldEnum; +import org.opengauss.mppdbide.bl.serverdatacache.UserRoleManager; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class PropertiesUserRoleImpl. + * + * @since 3.0.0 + */ +public class PropertiesUserRoleImpl implements IServerObjectProperties { + + private UserRole userRole; + private OlapConvertToObjectPropertyData convertToObjectPropertyData; + + /** + * Instantiates a new properties user role impl. + * + * @param obj the obj + */ + public PropertiesUserRoleImpl(Object obj) { + this.userRole = (UserRole) obj; + convertToObjectPropertyData = new OlapConvertToObjectPropertyData(); + } + + @Override + public String getObjectName() { + return this.userRole.getName(); + } + + @Override + public String getHeader() { + return this.userRole.getName() + '@' + this.userRole.getServer().getName(); + } + + @Override + public String getUniqueID() { + return this.userRole.getOid() + '@' + this.userRole.getServer().getName() + "properties"; + } + + @Override + public Database getDatabase() { + try { + return this.userRole.getServer().findOneActiveDb(); + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("Failed to get database: No active database present", exception); + return null; + } + } + + /** + * Gets the user role. + * + * @return the user role + */ + public UserRole getUserRole() { + return this.userRole; + } + + @Override + public List getAllProperties(DBConnection conn) throws MPPDBIDEException { + List tabNameList = new ArrayList(4); + List> propertyList = new ArrayList>(4); + Server server = this.userRole.getServer(); + boolean isSysAdmin = UserRoleManager.isSysAdmin(conn); + + UserRoleManager.copyProperties(UserRoleManager.fetchUserRoleDetailInfoByOid(server, conn, this.userRole), + this.userRole); + this.userRole.setParents(UserRoleManager.fetchAllParent(server, conn, this.userRole)); + this.userRole.setComment(UserRoleManager.fetchDescriptionOfUserRole(conn, userRole)); + if (isSysAdmin) { + this.userRole.setIsLock(UserRoleManager.fetchLockStatusOfUserRole(conn, userRole)); + } + + tabNameList.add(PropertiesConstants.USER_ROLE_PROPERTY_TAB_GENERAL); + tabNameList.add(PropertiesConstants.USER_ROLE_PROPERTY_TAB_PRIVILEGE); + tabNameList.add(PropertiesConstants.USER_ROLE_PROPERTY_TAB_MEMBERSHIP); + + propertyList.add(getPropertiesOfGeneralTab()); + propertyList.add(getPropertiesOfPrivilegeTab(isSysAdmin)); + propertyList.add(getPropertiesOfMemberShipTab()); + + return convertToObjectPropertyData.getObjectPropertyData(tabNameList, propertyList, null, this); + } + + /** + * Gets the properties of general tab. + * + * @return the properties of general tab + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public List getPropertiesOfGeneralTab() throws MPPDBIDEException { + List props = new ArrayList(); + + props.add(new String[] {MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_TAB_COLUMN_TITLE_PROPERTY), + MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_TAB_COLUMN_TITLE_VALUE)}); + + props.add( + new ServerProperty(getPropertyName(UserRoleFieldEnum.OID), Long.toString(userRole.getOid())).getProp()); + props.add(new ServerProperty(getPropertyName(UserRoleFieldEnum.NAME), userRole.getName()).getProp()); + props.add(new ServerProperty(getPropertyName(UserRoleFieldEnum.ROL_CONN_LIMIT), userRole.getRolConnLimit()) + .getProp()); + props.add(new ServerProperty(getPropertyName(UserRoleFieldEnum.ROL_VALID_BEGIN), + userRole.getRolValidBegin() == null ? "" : userRole.getRolValidBegin().toString()).getProp()); + props.add(new ServerProperty(getPropertyName(UserRoleFieldEnum.ROL_VALID_UNTIL), + userRole.getRolValidUntil() == null ? "" : userRole.getRolValidUntil().toString()).getProp()); + props.add(new ServerProperty(getPropertyName(UserRoleFieldEnum.ROL_RES_POOL), userRole.getRolResPool()) + .getProp()); + props.add(new ServerProperty(getPropertyName(UserRoleFieldEnum.COMMENT), + userRole.getComment() == null ? "" : userRole.getComment()).getProp()); + + return props; + } + + /** + * Gets the properties of privilege tab. + * + * @param isSysAdmin the is sys admin + * @return the properties of privilege tab + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public List getPropertiesOfPrivilegeTab(boolean isSysAdmin) throws MPPDBIDEException { + List props = new ArrayList(); + + props.add(new String[] {MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_TAB_COLUMN_TITLE_PROPERTY), + MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_TAB_COLUMN_TITLE_IS_ENABLE)}); + + props.add(new ServerProperty(getPropertyName(UserRoleFieldEnum.ROL_CAN_LOGIN), + userRole.getRolCanLogin().toString()).getProp()); + props.add(new ServerProperty(getPropertyName(UserRoleFieldEnum.ROL_CREATE_ROLE), + userRole.getRolCreateRole().toString()).getProp()); + props.add(new ServerProperty(getPropertyName(UserRoleFieldEnum.ROL_CREATE_DB), + userRole.getRolCreateDb().toString()).getProp()); + props.add(new ServerProperty(getPropertyName(UserRoleFieldEnum.ROL_SYSTEM_ADMIN), + userRole.getRolSystemAdmin().toString()).getProp()); + props.add(new ServerProperty(getPropertyName(UserRoleFieldEnum.ROL_AUDIT_ADMIN), + userRole.getRolAuditAdmin().toString()).getProp()); + props.add( + new ServerProperty(getPropertyName(UserRoleFieldEnum.ROL_INHERIT), userRole.getRolInherit().toString()) + .getProp()); + props.add(new ServerProperty(getPropertyName(UserRoleFieldEnum.ROL_REPLICATION), + userRole.getRolReplication().toString()).getProp()); + + if (isSysAdmin) { + props.add(new ServerProperty(getPropertyName(UserRoleFieldEnum.IS_LOCK), userRole.getIsLock().toString()) + .getProp()); + } + + return props; + } + + /** + * Gets the properties of member ship tab. + * + * @return the properties of member ship tab + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public List getPropertiesOfMemberShipTab() throws MPPDBIDEException { + List props = new ArrayList(); + + props.add( + new String[] {MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_TAB_COLUMN_TITLE_USER_ROLE), + MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_TAB_COLUMN_TITLE_BELONG_TO)}); + + StringBuilder parents = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + for (UserRole obj : userRole.getParents()) { + parents.append(obj.getName() + PropertiesConstants.SPLIT_STR); + } + if (parents.length() > 0) { + parents.delete(parents.length() - PropertiesConstants.SPLIT_STR.length(), parents.length()); + } + parents.insert(0, '['); + parents.insert(parents.length(), ']'); + + props.add(new ServerProperty(getPropertyName(UserRoleFieldEnum.PARENTS), parents.toString()).getProp()); + + return props; + } + + /** + * Gets the property name. + * + * @param field the field + * @return the property name + */ + private String getPropertyName(UserRoleFieldEnum field) { + String propertyName = null; + propertyName = getPropertyNameFirst(field); + switch (field) { + case ROL_REPLICATION: { + propertyName = MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_REPLICATION); + break; + } + case ROL_CAN_LOGIN: { + propertyName = MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_CAN_LOGIN); + break; + } + case ROL_SYSTEM_ADMIN: { + propertyName = MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_SYSTEM_ADMIN); + break; + } + case ROL_RES_POOL: { + propertyName = MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_RESOURCE_POOL); + break; + } + case COMMENT: { + propertyName = MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_COMMENT); + break; + } + case ROL_AUDIT_ADMIN: { + propertyName = MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_AUDITOR); + break; + } + case IS_LOCK: { + propertyName = MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_IS_LOCK); + break; + } + case PARENTS: { + propertyName = this.userRole.getName(); + break; + } + default: { + break; + } + } + return propertyName; + } + + /** + * Gets the property name first. + * + * @param field the field + * @return the property name first + */ + private String getPropertyNameFirst(UserRoleFieldEnum field) { + String propertyName = null; + switch (field) { + case OID: { + propertyName = MessageConfigLoader.getProperty(IMessagesConstants.OID_MSG); + break; + } + case NAME: { + propertyName = MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_NAME); + break; + } + case ROL_CONN_LIMIT: { + propertyName = MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_CONNECT_LIMIT); + break; + } + case ROL_VALID_BEGIN: { + propertyName = MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_VALID_BEGIN); + break; + } + case ROL_VALID_UNTIL: { + propertyName = MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_VALID_UNTIL); + break; + } + case ROL_CREATE_ROLE: { + propertyName = MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_CREATE_ROLE); + break; + } + case ROL_CREATE_DB: { + propertyName = MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_CREATE_DB); + break; + } + case ROL_INHERIT: { + propertyName = MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLR_INHERIT); + break; + } + default: { + break; + } + } + return propertyName; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesViewImpl.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesViewImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..64eaa3a50bfdf1cee3791abb1416cfa630997301 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/PropertiesViewImpl.java @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.adapter.gauss.GaussUtils; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ServerProperty; +import org.opengauss.mppdbide.bl.serverdatacache.ViewColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.presentation.objectbrowser.ObjectBrowserObjectRefreshPresentation; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class PropertiesViewImpl. + * + * @since 3.0.0 + */ +public class PropertiesViewImpl implements IServerObjectProperties { + + private ViewMetaData view; + private OlapConvertToObjectPropertyData convertToObjectPropertyData; + private static final String FETCH_SOURCE_CODE_QUERY = "SELECT * FROM pg_get_viewdef"; + + /** + * Instantiates a new properties view impl. + * + * @param obj the obj + */ + public PropertiesViewImpl(Object obj) { + + this.view = (ViewMetaData) obj; + convertToObjectPropertyData = new OlapConvertToObjectPropertyData(); + } + + @Override + public List getAllProperties(DBConnection conn) throws MPPDBIDEException { + if (!view.isLoaded()) { + ObjectBrowserObjectRefreshPresentation.refreshSeverObject(view); + } + List tabName = new ArrayList(5); + List> propertyList = new ArrayList>(5); + tabName.add(PropertiesConstants.GENERAL); + tabName.add(PropertiesConstants.COLUMNS); + + propertyList.add(getViewProperties(conn)); + propertyList.add(getViewColumnInfo(conn)); + + return convertToObjectPropertyData.getObjectPropertyData(tabName, propertyList, null, this); + + } + + /** + * Gets the view column info. + * + * @param conn the conn + * @return the view column info + */ + private List getViewColumnInfo(DBConnection conn) { + ArrayList viewMetaDataList = this.view.getColumns().getList(); + List viewColmnsList = new ArrayList(5); + String[] viewColsHeader = new String[] { + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_COLUMNS_COLUMNSNAME), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_COLUMNS_DATATYPE), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_COLUMNS_ISNULLABLE)}; + viewColmnsList.add(viewColsHeader); + for (ViewColumnMetaData col : viewMetaDataList) { + int jcnt = 0; + String[] viewCol = new String[viewColsHeader.length]; + viewCol[jcnt] = col.getName(); + if (null != col.getDataType()) { + viewCol[++jcnt] = col.getViewDisplayDatatype(); + } + // retrieve the boolean value invert it for UI purpose and change to + // string + viewCol[++jcnt] = "" + !col.isNotNull(); + viewColmnsList.add(viewCol); + } + + return viewColmnsList; + + } + + /** + * Gets the view properties. + * + * @param conn the conn + * @return the view properties + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public List getViewProperties(DBConnection conn) throws MPPDBIDEException { + List str = new ArrayList(5); + String viewName = view.getName(); + String ownerName = view.getOwner(); + String viewDefinition = getDDL(conn); + + String[] viewPropHeader = {MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_WID_PROPERTY), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_WID_VALUE)}; + str.add(viewPropHeader); + str.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_VIEW_NAME), viewName) + .getProp()); + str.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_VIEW_OWNER), ownerName) + .getProp()); + str.add(new ServerProperty(MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_VIEW_DEF), + viewDefinition).getProp()); + return str; + } + + /** + * Fetch DDL. + * + * @param conn the conn + * @throws MPPDBIDEException the MPPDBIDE exception + */ + private void fetchDDL(DBConnection conn) throws MPPDBIDEException { + + ResultSet rs = null; + try { + rs = conn.execSelectAndReturnRs(FETCH_SOURCE_CODE_QUERY + '(' + view.getOid() + ')'); + + boolean hasNext = rs.next(); + if (hasNext) { + if (!rs.getString(1).contains("Not a view")) { + view.setSource(rs.getString(1)); + view.setViewCodeLoaded(true); + } else { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.VIEW_DOES_NOT_EXIST)); + throw new DatabaseOperationException(IMessagesConstants.VIEW_DOES_NOT_EXIST); + } + } + } catch (SQLException exception) { + GaussUtils.handleCriticalException(exception); + throw new DatabaseOperationException(IMessagesConstants.ERR_GUI_RESULT_SET_INVALID, exception); + } finally { + conn.closeResultSet(rs); + } + } + + /** + * Gets the ddl. + * + * @param conn the conn + * @return the ddl + * @throws MPPDBIDEException the MPPDBIDE exception + */ + private String getDDL(DBConnection conn) throws MPPDBIDEException { + if (!view.isViewCodeLoaded()) { + fetchDDL(conn); + } + + StringBuilder strbldr = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + if (view.isViewCodeLoaded()) { + strbldr.append(String.format(Locale.ENGLISH, "CREATE %s%sVIEW ", + this.view.getOrReplaceString(), this.view.getMaterViewString())); + strbldr.append(view.getNamespace().getQualifiedObjectName()).append(".") + .append(view.getQualifiedObjectName()).append(System.lineSeparator()).append(" AS ") + .append(System.lineSeparator()).append(view.getSource()); + } + return strbldr.toString(); + } + + @Override + public Database getDatabase() { + return this.view.getDatabase(); + } + + @Override + public String getObjectName() { + + return view.getQualifiedObjectName(); + } + + @Override + public String getHeader() { + return view.getNameSpaceName() + '.' + view.getName() + '-' + view.getDatabase().getDbName() + '@' + + view.getDatabase().getServerName(); + } + + @Override + public String getUniqueID() { + return view.getOid() + '@' + view.getDatabase().getServerName() + "properties"; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/factory/ServerFactory.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/factory/ServerFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..93027e6c307996a3e4b48b467a70f4c7a4756cf8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/factory/ServerFactory.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties.factory; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.PartitionTable; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.SynonymMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.UserRole; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.presentation.PropertyOperationType; +import org.opengauss.mppdbide.presentation.objectproperties.ConnectionPropertiesImpl; +import org.opengauss.mppdbide.presentation.objectproperties.IServerObjectProperties; +import org.opengauss.mppdbide.presentation.objectproperties.PropertiesDatabaseImpl; +import org.opengauss.mppdbide.presentation.objectproperties.PropertiesPartitionTableImpl; +import org.opengauss.mppdbide.presentation.objectproperties.PropertiesSynonymImpl; +import org.opengauss.mppdbide.presentation.objectproperties.PropertiesTableImpl; +import org.opengauss.mppdbide.presentation.objectproperties.PropertiesUserRoleImpl; +import org.opengauss.mppdbide.presentation.objectproperties.PropertiesViewImpl; + +/** + * + * Title: ServerFactory + * + * Description: The Class ServerFactory. + * + * @since 3.0.0 + */ +public class ServerFactory { + + /** + * Gets the object. + * + * @param obj the obj + * @param propType the prop type + * @return the object + */ + public IServerObjectProperties getObject(Object obj, PropertyOperationType propType) { + if (obj == null) { + return null; + } + if (PropertyOperationType.PROPERTY_OPERATION_VIEW == propType) { + return handleViewObjectProperties(obj); + } + return null; + } + + /** + * Handle view object properties. + * + * @param obj the obj + * @return the i server object properties + */ + protected IServerObjectProperties handleViewObjectProperties(Object obj) { + if (obj instanceof Database) { + return new PropertiesDatabaseImpl(obj); + + } else if (obj instanceof PartitionTable) { + return new PropertiesPartitionTableImpl(obj); + } else if (obj instanceof TableMetaData) { + return new PropertiesTableImpl(obj); + } else if (obj instanceof ViewMetaData) { + return new PropertiesViewImpl(obj); + } else if (obj instanceof SynonymMetaData) { + return new PropertiesSynonymImpl(obj); + } else if (obj instanceof Server) { + return new ConnectionPropertiesImpl(obj); + } else if (obj instanceof UserRole) { + return new PropertiesUserRoleImpl(obj); + } + + return null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/handler/IPropertyDetail.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/handler/IPropertyDetail.java new file mode 100644 index 0000000000000000000000000000000000000000..6b296189863de2890cfac189ab33b2ed898c872d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/handler/IPropertyDetail.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties.handler; + +import java.util.List; + +import org.opengauss.mppdbide.presentation.objectproperties.IObjectPropertyData; + +/** + * + * Title: interface + * + * Description: The Interface IPropertyDetail. + * + * @since 3.0.0 + */ +public interface IPropertyDetail { + + /** + * Gets the property core. + * + * @return the property core + */ + PropertyHandlerCore getPropertyCore(); + + /** + * Gets the header.return the Property window Title + * + * @return the header + */ + String getHeader(); + + /** + * Objectproperties.return the object Properties detail + * + * @return the list + */ + List objectproperties(); + + /** + * Gets the unique ID.return the Property window UID + * + * @return the unique ID + */ + String getUniqueID(); + + /** + * Gets the parent property. + * + * @return the parent property + */ + default IObjectPropertyData getParentProperty() { + return null; + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/handler/PropertyHandlerCore.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/handler/PropertyHandlerCore.java new file mode 100644 index 0000000000000000000000000000000000000000..413515f06ebda2bb83f41f7036246be72169c7b1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/objectproperties/handler/PropertyHandlerCore.java @@ -0,0 +1,243 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.objectproperties.handler; + +import java.sql.SQLException; +import java.util.List; + +import org.opengauss.mppdbide.presentation.IWindowDetail; +import org.opengauss.mppdbide.presentation.PropertyOperationType; +import org.opengauss.mppdbide.presentation.TerminalExecutionConnectionInfra; +import org.opengauss.mppdbide.presentation.objectproperties.IObjectPropertyData; +import org.opengauss.mppdbide.presentation.objectproperties.IServerObjectProperties; +import org.opengauss.mppdbide.presentation.objectproperties.factory.ServerFactory; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; + +/** + * + * Title: class + * + * Description: The Class PropertyHandlerCore. + * + * @since 3.0.0 + */ +public class PropertyHandlerCore { + private IServerObjectProperties iServerObject; + private String objectName; + + /** + * The conn infra. + */ + protected TerminalExecutionConnectionInfra connInfra; + + /** + * The details. + */ + protected IWindowDetail details; + /** + * Instantiates a new property handler core. + */ + public PropertyHandlerCore() { + + } + + /** + * Instantiates a new property handler core. + * + * @param obj the obj + */ + public PropertyHandlerCore(Object obj) { + this(obj, PropertyOperationType.PROPERTY_OPERATION_VIEW); + } + + /** + * Instantiates a new property handler core. + * + * @param obj the obj + * @param propertyOperationEdit the property operation edit + */ + public PropertyHandlerCore(Object obj, PropertyOperationType propertyOperationEdit) { + // initialization of the object + ServerFactory factory = new ServerFactory(); + this.iServerObject = factory.getObject(obj, propertyOperationEdit); + if (null != iServerObject) { + this.setObjectName(iServerObject.getObjectName()); + } + + details = new ObjectPropertiesWindowDetails(); + } + + /** + * Sets the properties object. + * + * @param obj the new properties object + */ + protected void setPropertiesObject(IServerObjectProperties obj) { + this.iServerObject = obj; + } + + /** + * Checks if is executable. + * + * @return true, if is executable + */ + public boolean isExecutable() { + if (iServerObject != null) { + return true; + } + return false; + } + + /** + * Gets the property. + * + * @return the property + * @throws MPPDBIDEException the MPPDBIDE exception + * @throws SQLException the SQL exception + */ + public IPropertyDetail getproperty() throws MPPDBIDEException, SQLException { + + PropertyDetailImpl obj = null; + List propList = null; + IObjectPropertyData parentProperty = null; + propList = iServerObject.getAllProperties(connInfra.getConnection()); + parentProperty = iServerObject.getParentProperties(connInfra.getConnection()); + String uId = getUniqueID(); + String windowTitle = getWindowTitle(); + obj = new PropertyDetailImpl(uId, windowTitle, propList, this, parentProperty); + return obj; + } + + private String getWindowTitle() { + return iServerObject.getHeader(); + } + + private String getUniqueID() { + return iServerObject.getUniqueID(); + } + + private void setObjectName(String objectName) { + this.objectName = objectName; + } + + /** + * + * Title: class + * + * Description: The Class PropertyDetailImpl. + */ + private static class PropertyDetailImpl implements IPropertyDetail { + private String uid; + private String title; + private List prop; + private PropertyHandlerCore core; + private IObjectPropertyData parentObjectProperty; + + PropertyDetailImpl(String uID, String windowTitle, List propList, + PropertyHandlerCore propertyHandlerCore, IObjectPropertyData parentObjectProperty) { + this.uid = uID; + this.title = windowTitle; + this.prop = propList; + this.core = propertyHandlerCore; + this.parentObjectProperty = parentObjectProperty; + + } + + @Override + public String getHeader() { + return title; + } + + @Override + public String getUniqueID() { + return uid; + } + + @Override + public List objectproperties() { + return prop; + } + + @Override + public PropertyHandlerCore getPropertyCore() { + return this.core; + } + + @Override + public IObjectPropertyData getParentProperty() { + return this.parentObjectProperty; + } + + } + + /** + * Gets the term connection. + * + * @return the term connection + */ + public TerminalExecutionConnectionInfra getTermConnection() { + if (null == connInfra) { + this.connInfra = new TerminalExecutionConnectionInfra(); + this.connInfra.setDatabase(iServerObject.getDatabase()); + } + + return connInfra; + } + + /** + * Gets the window details. + * + * @return the window details + */ + public IWindowDetail getWindowDetails() { + return details; + } + + /** + * + * Title: class + * + * Description: The Class ObjectPropertiesWindowDetails. + */ + private class ObjectPropertiesWindowDetails implements IWindowDetail { + + @Override + public String getTitle() { + return iServerObject.getHeader(); + } + + @Override + public String getUniqueID() { + return iServerObject.getUniqueID(); + } + + @Override + public String getIcon() { + return null; + } + + @Override + public String getShortTitle() { + return objectName; + } + + @Override + public boolean isCloseable() { + return true; + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/resultset/ActionAfterResultFetch.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/resultset/ActionAfterResultFetch.java new file mode 100644 index 0000000000000000000000000000000000000000..06f3978678d822e1dca358c9c2df40dad984c828 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/resultset/ActionAfterResultFetch.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.resultset; + +/** + * + * Title: enum + * + * Description: The Enum ActionAfterResultFetch. + * + * @since 3.0.0 + */ +public enum ActionAfterResultFetch { + /* Action indicates the connection be closed after result is fetched */ + CLOSE_CONNECTION_AFTER_FETCH, + /* Indices to keep the connection open rather just commit */ + ISSUE_COMMIT_CONNECTION_AFTER_FETCH, + /* Indices to keep the connection open rather just rollback */ + ISSUE_ROLLBACK_CONNECTION_AFTER_FETCH, + /* Do nothing and continue with the next statement */ + ISSUE_NO_OP +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/resultset/ConsoleDataWrapper.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/resultset/ConsoleDataWrapper.java new file mode 100644 index 0000000000000000000000000000000000000000..7c866bf9d79f96fe6fc76646ebc8b3a50ded494d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/resultset/ConsoleDataWrapper.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.resultset; + +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.presentation.resultsetif.IConsoleResult; + +/** + * Title: class Description: The Class ConsoleDataWrapper. + * + * @since 3.0.0 + */ +public class ConsoleDataWrapper extends ArrayList implements IConsoleResult { + + private static final long serialVersionUID = 1L; + + private List hintMessage = new ArrayList<>(1); + + /** + * Instantiates a new console data wrapper. + */ + public ConsoleDataWrapper() { + super(); + } + + /** + * get the list of hint messages + * + * @return return the hint message list + */ + @Override + public List getHintMessages() { + return hintMessage; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/resultsetif/IConsoleResult.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/resultsetif/IConsoleResult.java new file mode 100644 index 0000000000000000000000000000000000000000..ff51c2eb0003972f7e6d3ebcc0c1ab66eb6a83cd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/resultsetif/IConsoleResult.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.resultsetif; + +import java.util.List; + +/** + * Title: interface Description: The Interface IConsoleResult. + * + * @since 3.0.0 + */ +public interface IConsoleResult extends List { + + /** + * get the list of hint messages + * + * @return return the hint message list + */ + List getHintMessages(); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/resultsetif/IResultConfig.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/resultsetif/IResultConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..a122337d0b734d8dade76506e35323ea6a999140 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/resultsetif/IResultConfig.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.resultsetif; + +import org.opengauss.mppdbide.presentation.resultset.ActionAfterResultFetch; + +/** + * + * Title: interface + * + * Description: The Interface IResultConfig. + * + * @since 3.0.0 + */ +public interface IResultConfig { + + /** + * Gets the fetch count. + * + * @return the fetch count + */ + int getFetchCount(); + + /** + * Gets the action after fetch. + * + * @return the action after fetch + */ + ActionAfterResultFetch getActionAfterFetch(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/search/AbstractSearchObjUtils.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/search/AbstractSearchObjUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..5fc39e28d654f552b18d53f9edb6c0c6cc00eb7f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/search/AbstractSearchObjUtils.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.search; + +import java.util.ArrayList; + +import org.opengauss.mppdbide.bl.search.SearchNameMatchEnum; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class AbstractSearchObjUtils. + * + * @since 3.0.0 + */ +public abstract class AbstractSearchObjUtils { + + /** + * Gets the index by value. + * + * @param array the array + * @param value the value + * @return the index by value + */ + public static int getIndexByValue(ArrayList array, String value) { + for (int index = 0; index < array.size(); index++) { + if (value.equals(array.get(index))) { + return index; + } + } + return 0; + } + + private static String getWildcardEscapedString(String str) { + String newStr = str; + newStr = newStr.replace("_", MPPDBIDEConstants.ESCAPE_STRING_UNDERSCORE); + newStr = newStr.replace("%", MPPDBIDEConstants.ESCAPE_STRING_PERCENTILE); + return newStr; + } + + /** + * Form queryby name match. + * + * @param matchIndex the match index + * @param searchText the search text + * @return the string + */ + public static String formQuerybyNameMatch(SearchNameMatchEnum matchIndex, String searchText) { + StringBuilder builder = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + switch (matchIndex) { + case CONTAINS: { + builder.append("%"); + builder.append(searchText); + builder.append("%"); + break; + } + case STARTS_WITH: { + builder.append(getWildcardEscapedString(searchText)); + builder.append("%"); + break; + } + case EXACT_WORD: { + builder.append(getWildcardEscapedString(searchText)); + break; + } + case REGULAR_EXPRESSION: { + builder.append(searchText); + break; + } + default: { + break; + } + } + return builder.toString(); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/search/SearchObjCore.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/search/SearchObjCore.java new file mode 100644 index 0000000000000000000000000000000000000000..0d17ab4f87faa815dbb817be714dfc56a7037f70 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/search/SearchObjCore.java @@ -0,0 +1,607 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.search; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Observable; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.search.SearchDatabase; +import org.opengauss.mppdbide.bl.search.SearchNameMatchEnum; +import org.opengauss.mppdbide.bl.search.SearchNamespace; +import org.opengauss.mppdbide.bl.search.SearchObjectEnum; +import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DebugObjects; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.NamespaceUtilsBase; +import org.opengauss.mppdbide.bl.serverdatacache.PartitionTable; +import org.opengauss.mppdbide.bl.serverdatacache.SequenceMetadata; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.SynonymMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TriggerMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class SearchObjCore. + * + * @since 3.0.0 + */ +public class SearchObjCore extends Observable { + private SearchCoreJob innerSearch = null; + private SearchObjInfo searchInfo; + private DBConnection conn; + private String executionTime; + private HashMap connectionMap; + private HashMap dBMap; + private HashMap nsMap; + private SearchDatabase searchedDatabase; + private Database selectedDb; + private Namespace selectedNs; + private ArrayList nameMatchList; + private SearchNamespace searchNamespace; + private Server server; + private ArrayList connectionDetails; + private ArrayList dataBases; + private ArrayList namespacesList; + + /** + * Instantiates a new search obj core. + */ + public SearchObjCore() { + dBMap = new HashMap(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + connectionMap = new HashMap(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + nameMatchList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + nsMap = new HashMap(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + innerSearch = new SearchCoreJob(); + } + + /** + * Gets the selected ns. + * + * @return the selected ns + */ + public Namespace getSelectedNs() { + this.selectedNs = nsMap.get(searchInfo.getSelectedNamespace()); + return this.selectedNs; + } + + /** + * Sets the search info. + * + * @param searchInfo the new search info + */ + public void setSearchInfo(SearchObjInfo searchInfo) { + this.searchInfo = searchInfo; + } + + /** + * Gets the selected db. + * + * @return the selected db + */ + public Database getSelectedDb() { + this.selectedDb = dBMap.get(searchInfo.getSelectedDB()); + return this.selectedDb; + } + + /** + * Gets the search namespace. + * + * @return the search namespace + */ + public SearchNamespace getSearchNamespace() { + return this.searchNamespace; + } + + /** + * Gets the connection. + * + * @return the connection + * @throws DatabaseOperationException the database operation exception + */ + public void getConnection() throws DatabaseOperationException { + + try { + setConn(selectedDb.getConnectionManager().getFreeConnection()); + } catch (MPPDBIDEException exception) { + MPPDBIDELoggerUtility.error("SearchObjCore: getting connection failed.", exception); + throw new DatabaseOperationException(IMessagesConstants.SEARCH_OBJ_ERROR, exception); + } + } + + /** + * Gets the searched database. + * + * @return the searched database + */ + public SearchDatabase getSearchedDatabase() { + return this.searchedDatabase; + } + + /** + * Gets the search info. + * + * @return the search info + */ + public SearchObjInfo getSearchInfo() { + return this.searchInfo; + } + + private String getSearchedText() { + String searchText = ""; + if (searchInfo != null) { + searchText = searchInfo.getSearchText(); + } + return searchText; + } + + private SearchNameMatchEnum getMatchIndex() { + SearchNameMatchEnum enumMatch = null; + if (searchInfo != null) { + enumMatch = searchInfo.getNameMatchIndex(); + } + return enumMatch; + } + + /** + * Gets the name match list. + * + * @return the name match list + */ + public ArrayList getNameMatchList() { + nameMatchList.clear(); + nameMatchList.add(MessageConfigLoader.getProperty(IMessagesConstants.SEARCH_NAME_MATCH_CONTAINS)); + nameMatchList.add(MessageConfigLoader.getProperty(IMessagesConstants.SEARCH_NAME_MATCH_STARTS_LBL)); + nameMatchList.add(MessageConfigLoader.getProperty(IMessagesConstants.SEARCH_NAME_MATCH_EXACT_LBL)); + nameMatchList.add(MessageConfigLoader.getProperty(IMessagesConstants.SEARCH_NAME_MATCH_REGU_EXPRESS_LBL)); + return nameMatchList; + } + + /** + * Gets the all profiles. + * + * @return the all profiles + */ + public ArrayList getAllProfiles() { + connectionMap.clear(); + connectionDetails = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + DBConnProfCache.getInstance().getAllProfilesForSearch(connectionDetails, connectionMap); + return connectionDetails; + + } + + /** + * Gets the selected server. + * + * @return the selected server + */ + public Server getSelectedServer() { + this.server = connectionMap.get(searchInfo.getSelectedserver()); + return this.server; + + } + + /** + * Gets the all databases. + * + * @return the all databases + */ + public ArrayList getAllDatabases() { + dataBases = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + dBMap.clear(); + Server servr = getSelectedServer(); + if (null != servr) { + servr.getAllDatabasesForSearch(dataBases, dBMap); + } + return dataBases; + + } + + /** + * Gets the namespace list. + * + * @return the namespace list + */ + public ArrayList getNamespaceList() { + namespacesList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + nsMap.clear(); + selectedDb = getSelectedDb(); + if (null != selectedDb) { + + namespacesList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + nsMap.clear(); + NamespaceUtilsBase.getNamespaceListForSearch(namespacesList, nsMap, selectedDb.getAllNameSpaces()); + } + return namespacesList; + } + + private void setConn(DBConnection conn) { + this.conn = conn; + } + + /** + * Search. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void search() throws DatabaseCriticalException, DatabaseOperationException { + innerSearch.search(); + } + + /** + * + * Title: class + * + * Description: The Class SearchCoreJob. + */ + private class SearchCoreJob { + /* + * creation of this class is for fixing UADP God class defect. + */ + + /** + * Search. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void search() throws DatabaseCriticalException, DatabaseOperationException { + selectedNs = getSelectedNs(); + searchedDatabase = new SearchDatabase(getSelectedServer(), selectedDb.getOid(), selectedDb); + searchNamespace = new SearchNamespace(selectedNs.getOid(), selectedNs.getName(), selectedDb); + searchedDatabase.addSearchNamespaces(searchNamespace); + try { + if (searchInfo.isTableSelected() || searchInfo.isViewsSelected() || searchInfo.isSequenceSelected()) { + searchTableData(selectedNs.getPrivilegeFlag()); + } + if (searchInfo.isFunProcSelected()) { + executeTogetSearchedFunctionProcedure(selectedNs.getPrivilegeFlag()); + + } + if (searchInfo.isSynonymSelected()) { + executeTogetSearchedSynonym(selectedNs.getPrivilegeFlag()); + } + if (searchInfo.isTriggerSelected()) { + searchTriggerData(selectedNs.getPrivilegeFlag()); + } + } catch (DatabaseCriticalException exception) { + MPPDBIDELoggerUtility.error("SearchObjCore: search operation failed.", exception); + throw new DatabaseCriticalException(IMessagesConstants.SEARCH_OBJ_ERROR, exception); + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("SearchObjCore: search operation failed.", exception); + throw new DatabaseOperationException(IMessagesConstants.SEARCH_OBJ_ERROR, exception); + } catch (SQLException exception) { + MPPDBIDELoggerUtility.error("SearchObjCore: search operation failed.", exception); + throw new DatabaseOperationException(IMessagesConstants.SEARCH_OBJ_ERROR, exception); + } + + searchNamespace.setLoaded(); + } + + private void executeTogetSearchedFunctionProcedure(boolean privilegeFlag) + throws DatabaseCriticalException, DatabaseOperationException, SQLException { + ResultSet rs = null; + DebugObjects debugObj = null; + try { + SearchNameMatchEnum matchIndex = getMatchIndex(); + if (null != matchIndex) { + rs = conn.execSelectForSearch( + searchInfo.formSearchQueryForFunProc(selectedNs.getOid(), matchIndex, privilegeFlag), + AbstractSearchObjUtils.formQuerybyNameMatch(matchIndex, getSearchedText())); + + boolean hasNext = rs.next(); + while (hasNext) { + debugObj = DebugObjects.DebugObjectsUtils.convertToObject(rs, selectedDb); + if (searchNamespace.getOid() != debugObj.getNameSpaceId()) { + searchNamespace = new SearchNamespace(debugObj.getNameSpaceId(), + debugObj.getDbgNameSpaceName(), selectedDb); + searchedDatabase.addSearchNamespaces(searchNamespace); + } + searchNamespace.addDebugObjectToSearchPool(debugObj); + hasNext = rs.next(); + } + } + } finally { + conn.closeResultSet(rs); + } + } + + private void executeTogetSearchedSynonym(boolean privilegeFlag) + throws DatabaseCriticalException, DatabaseOperationException, SQLException { + ResultSet rs = null; + try { + int namespaceId; + String nsName; + Namespace ns; + SearchNameMatchEnum matchIndex = getMatchIndex(); + if (null != matchIndex) { + rs = conn.execSelectForSearch( + searchInfo.formSearchQueryForSyn(selectedNs.getOid(), matchIndex, privilegeFlag), + AbstractSearchObjUtils.formQuerybyNameMatch(matchIndex, getSearchedText())); + + boolean hasNext = rs.next(); + while (hasNext) { + namespaceId = rs.getInt("synnamespace"); + ns = selectedDb.getNameSpaceById(namespaceId); + nsName = rs.getString("synobjschema"); + if (searchNamespace.getOid() != namespaceId) { + searchNamespace = new SearchNamespace(namespaceId, nsName, selectedDb); + searchedDatabase.addSearchNamespaces(searchNamespace); + } + getSearchedSynonym(rs, ns); + hasNext = rs.next(); + } + } + } finally { + conn.closeResultSet(rs); + } + } + + private void searchTableData(boolean privilegeFlag) + throws DatabaseCriticalException, DatabaseOperationException, SQLException { + ResultSet rs = null; + try { + int namespaceId; + String nsName; + Namespace ns; + SearchNameMatchEnum matchIndex = getMatchIndex(); + if (null != matchIndex) { + + rs = conn.execSelectForSearch( + searchInfo.formSearchQueryForTablesnViews(selectedNs.getOid(), matchIndex, privilegeFlag, + server.isServerCompatibleToNodeGroupPrivilege()), + AbstractSearchObjUtils.formQuerybyNameMatch(getMatchIndex(), getSearchedText())); + boolean hasNext = rs.next(); + while (hasNext) { + namespaceId = rs.getInt("relnamespace"); + ns = selectedDb.getNameSpaceById(namespaceId); + nsName = rs.getString("nsname"); + + if (searchNamespace.getOid() != namespaceId) { + searchNamespace = new SearchNamespace(namespaceId, nsName, selectedDb); + searchedDatabase.addSearchNamespaces(searchNamespace); + } + getSearchedObject(rs, ns); + hasNext = rs.next(); + } + } + } finally { + conn.closeResultSet(rs); + } + } + } + + private void searchTriggerData(boolean privilegeFlag) + throws DatabaseCriticalException, DatabaseOperationException, SQLException { + ResultSet rs = null; + try { + int namespaceId; + String nsName; + Namespace ns; + SearchNameMatchEnum matchIndex = getMatchIndex(); + if (null != matchIndex) { + rs = conn.execSelectForSearch( + searchInfo.formSearchQueryForTriggers(selectedNs.getOid(), matchIndex, privilegeFlag, + server.isServerCompatibleToNodeGroupPrivilege()), + AbstractSearchObjUtils.formQuerybyNameMatch(getMatchIndex(), getSearchedText())); + boolean hasNext = rs.next(); + while (hasNext) { + namespaceId = rs.getInt("relnamespace"); + ns = selectedDb.getNameSpaceById(namespaceId); + nsName = rs.getString("nsname"); + + if (searchNamespace.getOid() != namespaceId) { + searchNamespace = new SearchNamespace(namespaceId, nsName, selectedDb); + searchedDatabase.addSearchNamespaces(searchNamespace); + } + getSearchedTrigger(rs, ns); + hasNext = rs.next(); + } + } + } finally { + conn.closeResultSet(rs); + } + } + + private void getSearchedObject(ResultSet rs, Namespace ns) throws SQLException { + PartitionTable parTable; + ViewMetaData viewTable; + TableMetaData forTable; + String ftOptions; + TableMetaData tbl; + SequenceMetadata seq; + int childId; + String childName; + String relkind = null; + String parttype = null; + childId = rs.getInt("oid"); + childName = rs.getString("relname"); + relkind = rs.getString("relkind"); + parttype = rs.getString("parttype"); + switch (relkind) { + case "r": { + if ("n".equals(parttype)) { + tbl = ns.getSearchedTable(childId, childName); + searchNamespace.addTableToSearchPool(tbl); + } else { + parTable = ns.getSearchedPartitionTable(childId, childName); + searchNamespace.addTableToSearchPool(parTable); + } + break; + } + case "f": { + ftOptions = rs.getString("ftoptions"); + forTable = ns.getSearchedForeignTable(childId, ftOptions); + if (null != forTable) { + searchNamespace.addToForeignGroup(forTable); + } + break; + } + case "S": { + seq = ns.getSearchedSequence(childId, childName); + if (null != seq) { + searchNamespace.addToSequenceGroup(seq); + } + break; + } + default: { + viewTable = ns.getSearchedView(childId, childName); + searchNamespace.addViewToGroup(viewTable); + break; + } + } + } + + private void getSearchedSynonym(ResultSet rs, Namespace ns) throws SQLException { + SynonymMetaData syn; + int childId; + String childName = null; + childId = rs.getInt("oid"); + childName = rs.getString("synname"); + syn = ns.getSearchedSynonym(childId, childName); + searchNamespace.addToSynonymGroup(syn); + } + + private void getSearchedTrigger(ResultSet rs, Namespace ns) throws SQLException { + TriggerMetaData triggerMetaData; + int childId; + String childName = null; + childId = rs.getInt("oid"); + childName = rs.getString("tgname"); + triggerMetaData = ns.getSearchedTrigger(childId, childName); + searchNamespace.addToTrigerGroup(triggerMetaData); + } + + /** + * Gets the rows fetched. + * + * @return the rows fetched + */ + public int getRowsFetched() { + return searchNamespace.getSize(); + } + + /** + * Gets the execution time. + * + * @return the execution time + */ + public String getExecutionTime() { + return executionTime; + } + + /** + * Sets the execution time. + * + * @param executionTime the new execution time + */ + public void setExecutionTime(String executionTime) { + this.executionTime = executionTime; + } + + private void releaseConnection() { + if (conn != null) { + selectedDb.getConnectionManager().releaseAndDisconnection(conn); + } + + } + + /** + * Clear data. + */ + public void clearData() { + if (null != searchNamespace) { + searchNamespace.clearAllObjects(); + } + searchNamespace = null; + searchedDatabase = null; + } + + /** + * Cancel query. + * + * @throws DatabaseCriticalException the database critical exception + * @throws DatabaseOperationException the database operation exception + */ + public void cancelQuery() throws DatabaseCriticalException, DatabaseOperationException { + conn.cancelQuery(); + + } + + /** + * Clean up search. + */ + public void cleanUpSearch() { + releaseConnection(); + } + + /** + * Sets the search status. + * + * @param searchStatus the new search status + */ + public void setSearchStatus(SearchObjectEnum searchStatus) { + setChanged(); + notifyObservers(searchStatus); + } + + /** + * Gets the object browser selected server. + * + * @param serverName the server name + * @return the object browser selected server + */ + public int getObjectBrowserSelectedServer(String serverName) { + return AbstractSearchObjUtils.getIndexByValue(connectionDetails, serverName); + + } + + /** + * Gets the object browser selected database. + * + * @param dbName the db name + * @return the object browser selected database + */ + public int getObjectBrowserSelectedDatabase(String dbName) { + return AbstractSearchObjUtils.getIndexByValue(dataBases, dbName); + } + + /** + * Gets the object browser selected schema. + * + * @param schemaName the schema name + * @return the object browser selected schema + */ + public int getObjectBrowserSelectedSchema(String schemaName) { + return AbstractSearchObjUtils.getIndexByValue(namespacesList, schemaName); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/search/SearchObjInfo.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/search/SearchObjInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..fdaf13e492f1907b7d0f334d3c559a2ebc464659 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/search/SearchObjInfo.java @@ -0,0 +1,517 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.search; + +import org.opengauss.mppdbide.bl.search.SearchNameMatchEnum; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class SearchObjInfo. + * + * @since 3.0.0 + */ +public class SearchObjInfo { + + /** + * The Constant TABLES_VIEWS_FAST_LOAD. + */ + public static final String TABLES_VIEWS_FAST_LOAD = "select tbl.oid as oid, tbl.relname relname, tbl.relnamespace relnamespace, ns.nspname nsname," + + "tbl.relowner relowner,tbl.relkind relkind, tbl.parttype parttype, frgn.ftoptions "; + + /** + * The Constant TABLES_VIEWS_FAST_LOAD_WHERE. + */ + public static final String TABLES_VIEWS_FAST_LOAD_WHERE = "from pg_class tbl left join pg_namespace ns on tbl.relnamespace = ns.oid " + + "left join pg_foreign_table frgn on (tbl.oid = frgn.ftrelid) "; + + /** + * The Constant NO_PRIVILEGE. + */ + public static final String NO_PRIVILEGE = ")"; + + /** + * The Constant REL_TYPE_TABLES. + */ + public static final String REL_TYPE_TABLES = " (tbl.relkind='r' or tbl.relkind='f'"; + + /** + * The Constant NODEGROUP_PRIVILEGE. + */ + public static final String NODEGROUP_PRIVILEGE = " and tbl.oid in (with x as (select pcrelid from pgxc_class " + + "where has_nodegroup_privilege(pgroup, 'USAGE'))" + + " select * from x where has_table_privilege(x.pcrelid, 'SELECT')))"; + + /** + * The Constant TABLE_PRIVILEGE. + */ + public static final String TABLE_PRIVILEGE = " and has_table_privilege(tbl.oid, 'SELECT'))"; + + /** + * The Constant REL_TYPE_VIEWS. + */ + public static final String REL_TYPE_VIEWS = " (tbl.relkind='v'"; + + /** + * The Constant VIEWS_PRIVILEGE. + */ + public static final String VIEWS_PRIVILEGE = " and has_table_privilege(tbl.oid, 'SELECT'))"; + + /** + * The Constant REL_TYPE_SEQUENCE. + */ + public static final String REL_TYPE_SEQUENCE = " (tbl.relkind='S'"; + + /** + * The Constant SEQUENCE_PRIVILEGE. + */ + public static final String SEQUENCE_PRIVILEGE = " and has_sequence_privilege('\"'|| ns.nspname||'\"'||'.'||'\"'||tbl.relname||'\"', 'USAGE'))"; + + /** + * The Constant FUNCTION_PROCEDURE_FAST_LOAD. + */ + public static final String FUNCTION_PROCEDURE_FAST_LOAD = "SELECT pr.oid oid, pr.proname objname, pr.pronamespace namespace, pr.prorettype ret, " + + "pr.proallargtypes alltype, " + "pr.pronargs nargs, pr.proargtypes argtype, pr.proargnames argname, " + + "pr.proargmodes argmod, pr.proretset retset, lng.lanname lang,ns.nspname nsname "; + + /** + * The Constant FUNCTION_PROCEDURE_FAST_LOAD_WHERE. + */ + public static final String FUNCTION_PROCEDURE_FAST_LOAD_WHERE = "FROM pg_proc pr JOIN pg_language lng ON lng.oid=prolang " + + "left join pg_namespace ns ON ns.oid=pr.pronamespace " + "WHERE lng.lanname in ('plpgsql','sql','c') "; + + /** + * The Constant FUNCTION_PROCEDURE_FAST_LOAD_PRIVILEGE. + */ + public static final String FUNCTION_PROCEDURE_FAST_LOAD_PRIVILEGE = " and has_function_privilege(pr.oid, 'EXECUTE')"; + + /** + * The Constant SYNONYM_FAST_LOAD_PRIVILAGE + */ + public static final String SYNONYM_FAST_LOAD_PRIVILAGE = "select syn.synname,syn.oid,syn.synnamespace," + + "syn.synobjschema,syn.synowner "; + + /** + * The Constant TRIGGER_FAST_LOAD_PRIVILAGE + */ + public static final String TRIGGER_FAST_LOAD_PRIVILAGE = "select t.oid as oid, t.tgrelid as tableoid, t.tgname, ns.nspname as nsname, c.relnamespace " + + "as relnamespace, t.tgfoid as functionoid,t.tgtype as tgtype, t.tgenabled as tgenable, pg_get_triggerdef(t.oid) as ddlmsg "; + + /** + * TRIGGER_FAST_LOAD_PRIVILAGE_WHERE + */ + public static final String TRIGGER_FAST_LOAD_PRIVILAGE_WHERE = "from pg_trigger t left join pg_class c on t.tgrelid = c.oid inner join " + + "pg_namespace ns on c.relnamespace=ns.oid and c.relnamespace ="; + + /** + * The Constant SYNONYM_FROM_CLASS + */ + public static final String SYNONYM_FROM_CLASS = " from pg_synonym syn"; + + private int selectedserver; + private int selectedDB; + private int selectedNamespace; + private String searchText; + private SearchNameMatchEnum nameMatch; + private boolean matchCase; + private boolean tableSelected; + private boolean viewsSelected; + private boolean funProcSelected; + private boolean sequenceSelected; + private boolean synonymSelected; + private boolean triggerSelected; + + /** + * Gets the selectedserver. + * + * @return the selectedserver + */ + public int getSelectedserver() { + return selectedserver; + } + + /** + * Sets the selectedserver. + * + * @param selectedserver the new selectedserver + */ + public void setSelectedserver(int selectedserver) { + this.selectedserver = selectedserver; + } + + /** + * Gets the selected DB. + * + * @return the selected DB + */ + public int getSelectedDB() { + return selectedDB; + } + + /** + * Sets the selected DB. + * + * @param selectedDB the new selected DB + */ + public void setSelectedDB(int selectedDB) { + this.selectedDB = selectedDB; + } + + /** + * Gets the selected namespace. + * + * @return the selected namespace + */ + public int getSelectedNamespace() { + return selectedNamespace; + } + + /** + * Sets the selected namespace. + * + * @param selectedNamespace the new selected namespace + */ + public void setSelectedNamespace(int selectedNamespace) { + this.selectedNamespace = selectedNamespace; + } + + /** + * Gets the search text. + * + * @return the search text + */ + public String getSearchText() { + return searchText; + } + + /** + * Sets the search text. + * + * @param searchText the new search text + */ + public void setSearchText(String searchText) { + this.searchText = searchText; + } + + /** + * Gets the name match index. + * + * @return the name match index + */ + public SearchNameMatchEnum getNameMatchIndex() { + return this.nameMatch; + } + + /** + * Sets the name match. + * + * @param nameMatchIndex the new name match + */ + public void setNameMatch(int nameMatchIndex) { + switch (nameMatchIndex) { + case 0: { + this.nameMatch = SearchNameMatchEnum.CONTAINS; + break; + } + case 1: { + this.nameMatch = SearchNameMatchEnum.STARTS_WITH; + break; + } + case 2: { + this.nameMatch = SearchNameMatchEnum.EXACT_WORD; + break; + } + case 3: { + this.nameMatch = SearchNameMatchEnum.REGULAR_EXPRESSION; + break; + } + default: { + break; + } + } + } + + /** + * Checks if is match case. + * + * @return true, if is match case + */ + public boolean isMatchCase() { + return matchCase; + } + + /** + * Sets the match case. + * + * @param matchCase the new match case + */ + public void setMatchCase(boolean matchCase) { + this.matchCase = matchCase; + } + + /** + * Checks if is table selected. + * + * @return true, if is table selected + */ + public boolean isTableSelected() { + return tableSelected; + } + + /** + * Sets the table selected. + * + * @param tableSelected the new table selected + */ + public void setTableSelected(boolean tableSelected) { + this.tableSelected = tableSelected; + } + + /** + * Checks if is views selected. + * + * @return true, if is views selected + */ + public boolean isViewsSelected() { + return viewsSelected; + } + + /** + * Sets the views selected. + * + * @param viewsSelected the new views selected + */ + public void setViewsSelected(boolean viewsSelected) { + this.viewsSelected = viewsSelected; + } + + /** + * Checks if is fun proc selected. + * + * @return true, if is fun proc selected + */ + public boolean isFunProcSelected() { + return funProcSelected; + } + + /** + * Sets the fun proc selected. + * + * @param funProcSelected the new fun proc selected + */ + public void setFunProcSelected(boolean funProcSelected) { + this.funProcSelected = funProcSelected; + } + + /** + * Checks if is sequence selected. + * + * @return true, if is sequence selected + */ + public boolean isSequenceSelected() { + return sequenceSelected; + } + + /** + * Sets the sequence selected. + * + * @param sequenceSelected the new sequence selected + */ + public void setSequenceSelected(boolean sequenceSelected) { + this.sequenceSelected = sequenceSelected; + } + + /** + * Checks if is synonym selected. + * + * @return true, if is synonym selected + */ + public boolean isSynonymSelected() { + return synonymSelected; + } + + public boolean isTriggerSelected() { + return triggerSelected; + } + + /** + * Sets the synonym selected. + * + * @param synonymSelected the new synonym selected + */ + public void setSynonymSelected(boolean synonymSelected) { + this.synonymSelected = synonymSelected; + } + + public void setTriggerSelected(boolean triggerSelected) { + this.triggerSelected = triggerSelected; + } + + private String getRegularExpression() { + StringBuilder builder = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + if (!isMatchCase()) { + builder.append(",'i'"); + } + builder.append(") "); + return builder.toString(); + } + + /** + * Form search query for fun proc. + * + * @param nsoid the nsoid + * @param searchIndex the search index + * @param privilegeFlag the privilege flag + * @return the string + */ + public String formSearchQueryForFunProc(long nsoid, SearchNameMatchEnum searchIndex, boolean privilegeFlag) { + StringBuilder builder = new StringBuilder(FUNCTION_PROCEDURE_FAST_LOAD); + if (searchIndex == SearchNameMatchEnum.REGULAR_EXPRESSION) { + builder.append(", regexp_matches(objname, ?"); + builder.append(getRegularExpression()); + } + builder.append(FUNCTION_PROCEDURE_FAST_LOAD_WHERE); + builder.append(" and pr.pronamespace="); + builder.append(nsoid); + if (privilegeFlag) { + builder.append(FUNCTION_PROCEDURE_FAST_LOAD_PRIVILEGE); + } + if (searchIndex != SearchNameMatchEnum.REGULAR_EXPRESSION) { + builder.append(" and objname "); + builder.append(getExpressionForNameMatch(searchIndex)); + } + return builder.toString(); + } + + /** + * Form search query for syn. + * + * @param nsoid the nsoid + * @param searchIndex the search index + * @return the string + */ + public String formSearchQueryForSyn(long nsoid, SearchNameMatchEnum searchIndex, boolean privilegeFlag) { + StringBuilder builder = new StringBuilder(SYNONYM_FAST_LOAD_PRIVILAGE); + if (searchIndex == SearchNameMatchEnum.REGULAR_EXPRESSION) { + builder.append(", regexp_matches(synname, ?"); + builder.append(getRegularExpression()); + } + builder.append(SYNONYM_FROM_CLASS); + builder.append(" where syn.synnamespace="); + builder.append(nsoid); + if (searchIndex != SearchNameMatchEnum.REGULAR_EXPRESSION) { + builder.append(" and synname "); + builder.append(getExpressionForNameMatch(searchIndex)); + } + return builder.toString(); + + } + + /** + * Form search query for tablesn views. + * + * @param nsoid the nsoid + * @param searchIndex the search index + * @param privilegeFlag the privilege flag + * @param nodeGroupPrivilegeFlag the node group privilege flag + * @return the string + */ + public String formSearchQueryForTablesnViews(long nsoid, SearchNameMatchEnum searchIndex, boolean privilegeFlag, + boolean nodeGroupPrivilegeFlag) { + boolean orFlag = false; + StringBuilder builder = new StringBuilder(TABLES_VIEWS_FAST_LOAD); + if (searchIndex == SearchNameMatchEnum.REGULAR_EXPRESSION) { + builder.append(", regexp_matches(relname,?) "); + } + builder.append(TABLES_VIEWS_FAST_LOAD_WHERE); + + builder.append("where tbl.relnamespace ="); + builder.append(nsoid); + builder.append(" and ("); + if (isTableSelected()) { + orFlag = true; + builder.append(REL_TYPE_TABLES); + builder.append( + privilegeFlag ? (nodeGroupPrivilegeFlag ? NODEGROUP_PRIVILEGE : TABLE_PRIVILEGE) : NO_PRIVILEGE); + } + if (isViewsSelected()) { + if (orFlag) { + builder.append(" or"); + } else { + orFlag = true; + } + builder.append(REL_TYPE_VIEWS); + builder.append(privilegeFlag ? VIEWS_PRIVILEGE : NO_PRIVILEGE); + } + if (isSequenceSelected()) { + if (orFlag) { + builder.append(" or"); + } else { + orFlag = true; + } + builder.append(REL_TYPE_SEQUENCE); + builder.append(privilegeFlag ? SEQUENCE_PRIVILEGE : NO_PRIVILEGE); + } + builder.append(") and tbl.parttype in ('n', 'p', 'v') "); + + if (searchIndex != SearchNameMatchEnum.REGULAR_EXPRESSION) { + builder.append(" and relname "); + builder.append(getExpressionForNameMatch(searchIndex)); + } + return builder.toString(); + } + + /** + * Form search query for triggers. + * + * @param nsoid + * @param searchIndex + * @param privilegeFlag + * @param nodeGroupPrivilegeFlag + * @return + */ + public String formSearchQueryForTriggers(long nsoid, SearchNameMatchEnum searchIndex, boolean privilegeFlag, + boolean nodeGroupPrivilegeFlag) { + StringBuilder builder = new StringBuilder(TRIGGER_FAST_LOAD_PRIVILAGE); + if (searchIndex == SearchNameMatchEnum.REGULAR_EXPRESSION) { + builder.append(", regexp_matches(tgname, ?) "); + } + + builder.append(TRIGGER_FAST_LOAD_PRIVILAGE_WHERE); + builder.append(nsoid); + if (searchIndex != SearchNameMatchEnum.REGULAR_EXPRESSION) { + builder.append(" and tgname "); + builder.append(getExpressionForNameMatch(searchIndex)); + } + + return builder.toString(); + } + + private String getExpressionForNameMatch(SearchNameMatchEnum searchIndex) { + StringBuilder builder = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + if (isMatchCase()) { + builder.append(" LIKE "); + } else { + builder.append(" ILIKE "); + } + builder.append("? ;"); + + return builder.toString(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/synonym/olap/SynonymInfo.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/synonym/olap/SynonymInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..a939dbece9f6f45bb18245ab8d524de5620bc7c8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/synonym/olap/SynonymInfo.java @@ -0,0 +1,251 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.synonym.olap; + +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.groups.SynonymObjectGroup; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: Class + * + * Description: The Class SynonymInfo. + * + * @since 3.0.0 + */ +public class SynonymInfo { + + private String owner; + private String synonymName; + private String objectOwner; + private String objectName; + private boolean replaceIfExist; + private Namespace namespace; + private String objectType; + + /** + * Instantiates a new z sequence info. + * + * @param zSynonymObjectGroup the z synonym object group + */ + public SynonymInfo(SynonymObjectGroup synonymObjectGroup) { + this.namespace = (Namespace) synonymObjectGroup.getParent(); + } + + /** + * Gets the namespace. + * + * @return the namespace + * @Title: getNamespace + * @Description: get the namespace + */ + public Namespace getNamespace() { + return namespace; + } + + /** + * Gets the z namespace name. + * + * @return get the namespace name + * @Title: getSynonymName + * @Description: get synonym name + */ + public String getNameSpaceName() { + return namespace.getDisplayName(); + } + + /** + * Gets the owner. + * + * @return the owner + * @Title: getSynonymName + * @Description: get the owner + */ + public String getOwner() { + return owner; + } + + /** + * Sets the owner. + * + * @param owner the owner + * @Title: setSynonymName + * @Description: set the owner + */ + public void setOwner(String owner) { + this.owner = owner; + } + + /** + * Gets the synonym name. + * + * @return the synonym name + * @Title: getSynonymName + * @Description: get synonym name + */ + public String getSynonymName() { + return synonymName; + } + + /** + * Sets the synonym name. + * + * @param synonymName the synonym name + * @Title: setSynonymName + * @Description: set the synonym name + */ + public void setSynonymName(String synonymName) { + this.synonymName = synonymName; + } + + /** + * Gets the object owner. + * + * @return the object owner + * @Title: getObjectOwner + * @Description: get the object owner + */ + public String getObjectOwner() { + return objectOwner; + } + + /** + * Sets the object owner. + * + * @param objectOwner the object owner + * @Title: setObjectOwner + * @Description: set the object owner + */ + public void setObjectOwner(String objectOwner) { + this.objectOwner = objectOwner; + } + + /** + * Gets the object type. + * + * @return the object type + * @Title: getObjectType + * @Description: get the object type + */ + public String getObjectType() { + return objectType; + } + + /** + * Sets the object owner. + * + * @param objectOwner the object owner + * @Title: setObjectOwner + * @Description: set the object owner + */ + public void setObjectType(String objectType) { + this.objectType = objectType; + } + + /** + * Gets the object name. + * + * @return the object name + * @Title: getObjectName + * @Description: get the object name + */ + public String getObjectName() { + return objectName; + } + + /** + * Sets the object name. + * + * @param objectName the object name + * @Title: setObjectName + * @Description: set the object name + */ + public void setObjectName(String objectName) { + this.objectName = objectName; + } + + /** + * Checks if is replace if exist. + * + * @return true, if selected replace if exist button + * @Title: isReplaceIfExist + * @Description: check if select replace if exist button + */ + public boolean isReplaceIfExist() { + return replaceIfExist; + } + + /** + * Sets the replace if exist. + * + * @param replaceIfExist the new replace if exist + * @Title: setReplaceIfExist + * @Description: set replace if exist + */ + public void setReplaceIfExist(boolean replaceIfExist) { + this.replaceIfExist = replaceIfExist; + } + + /** + * Checks if is field empty. + * + * @param name the name + * @return true, if is field empty + */ + public boolean isFieldEmpty(String name) { + return name.isEmpty(); + } + + /** + * Generate create synonym sql. + * + * @return String generated sql + * @Title: generateCreateSynonymSql + * @Description: generate create synonym sql + */ + public String generateCreateSynonymSql() { + StringBuffer queryBuff = new StringBuffer(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + queryBuff.append("CREATE"); + if (isReplaceIfExist()) { + queryBuff.append(" OR REPLACE "); + } + queryBuff.append(MPPDBIDEConstants.LINE_SEPARATOR); + queryBuff.append(" SYNONYM "); + + if (!isFieldEmpty(getObjectOwner())) { + queryBuff.append(ServerObject.getQualifiedSimpleObjectName(getObjectOwner())).append("."); + } + if (!isFieldEmpty(getSynonymName())) { + queryBuff.append(ServerObject.getQualifiedSimpleObjectName(getSynonymName())); + } + + queryBuff.append(MPPDBIDEConstants.LINE_SEPARATOR); + queryBuff.append(" FOR "); + queryBuff.append(MPPDBIDEConstants.LINE_SEPARATOR); + if (!isFieldEmpty(getObjectOwner())) { + queryBuff.append(ServerObject.getQualifiedSimpleObjectName(getObjectOwner())).append("."); + } + + if (!isFieldEmpty(getObjectName())) { + queryBuff.append(ServerObject.getQualifiedSimpleObjectName(getObjectName())); + } + queryBuff.append(MPPDBIDEConstants.LINE_SEPARATOR); + return queryBuff.toString(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/synonym/olap/SynonymWrapper.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/synonym/olap/SynonymWrapper.java new file mode 100644 index 0000000000000000000000000000000000000000..4a6ccc84bd593db49bded7343ed49b5ce3e11856 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/synonym/olap/SynonymWrapper.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.synonym.olap; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.SynonymMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.SynonymUtil; +import org.opengauss.mppdbide.bl.serverdatacache.groups.SynonymObjectGroup; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; + +/** + * + * Title: Class + * + * Description: The Class SynonymWrapper. + * + * @since 3.0.0 + */ +public class SynonymWrapper { + private SynonymInfo synonymInfo; + private Database database; + private Namespace namespace; + private SynonymObjectGroup synonymObjectGroup; + private SynonymMetaData synonymMetaData; + + /** + * Instantiates a new synonym wrapper. + * + * @param SynonymGroup the synonym group + * @param info the info + */ + public SynonymWrapper(SynonymObjectGroup objectGroup, SynonymInfo info) { + this.synonymInfo = info; + this.synonymObjectGroup = objectGroup; + this.namespace = (Namespace) objectGroup.getParent(); + this.database = objectGroup.getDatabase(); + this.synonymMetaData = new SynonymMetaData(info.getSynonymName(), this.namespace); + } + + /** + * Gets the metadata. + * + * @return the metadata + */ + public SynonymMetaData getMetadata() { + return synonymMetaData; + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + return database; + } + + /** + * Gets the synonym group. + * + * @return the synonym group + */ + public SynonymObjectGroup getSynonymObjectGroup() { + return synonymObjectGroup; + } + + /** + * Execute compose query. + * + * @param connection the connection + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public void executeComposeQuery(DBConnection connection) throws MPPDBIDEException { + final String generateCreateSynonymSql = synonymInfo.generateCreateSynonymSql(); + connection.execNonSelect(generateCreateSynonymSql); + + } + + /** + * Refresh. + * + * @param connection the connection + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public void refresh(DBConnection connection) throws MPPDBIDEException { + SynonymUtil.fetchSynonyms(namespace, connection); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/userrole/GrantRevokeCore.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/userrole/GrantRevokeCore.java new file mode 100644 index 0000000000000000000000000000000000000000..d7841e39b0c5a6769143e8b91cabc6e7bd0b81dc --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/userrole/GrantRevokeCore.java @@ -0,0 +1,433 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.userrole; + +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DebugObjects; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ObjectGroup; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.MessageQueue; + +/** + * + * Title: class + * + * Description: The Class GrantRevokeCore. + * + * @since 3.0.0 + */ +public class GrantRevokeCore { + private Database database; + private Namespace namespace; + private Object[] objectOption; + + /** + * Instantiates a new grant revoke core. + * + * @param isBatch the is batch + * @param object the object + */ + public GrantRevokeCore(boolean isBatch, Object object) { + if (isBatch) { + initForBatch(object); + } else { + initForNotBatch(object); + } + } + + /** + * Inits the for batch. + * + * @param object the object + */ + private void initForBatch(Object object) { + List objects = (List) object; + + if (!((ServerObject) objects.get(0) instanceof Namespace)) { + this.namespace = (Namespace) (((ServerObject) objects.get(0)).getParent()); + } + + this.database = ((ServerObject) objects.get(0)).getDatabase(); + objectOption = objects.toArray(); + } + + /** + * Inits the for not batch. + * + * @param object the object + */ + private void initForNotBatch(Object object) { + ObjectGroup objectGroup = (ObjectGroup) object; + this.database = objectGroup.getDatabase(); + objectOption = objectGroup.getChildren(); + if (!(objectOption[0] instanceof Namespace)) { + this.namespace = (Namespace) objectGroup.getParent(); + } + } + + /** + * Generate sql. + * + * @param params the params + * @return the list + */ + public List generateSql(GrantRevokeParameters params) { + List previewSqls = new ArrayList<>(); + StringBuffer objectStrBuf = new StringBuffer(); + StringBuffer userRoleStrBuf = new StringBuffer(); + + List selectedObjects = params.getSelectedObjects(); + String userRolesStr = params.getUserRolesStr(); + List withGrantOptionPrivileges = params.getWithGrantOptionPrivileges(); + List withoutGrantOptionPrivileges = params.getWithoutGrantOptionPrivileges(); + boolean allPrivilege = params.isAllPrivilege(); + boolean allWithGrantOption = params.isAllWithGrantOption(); + List revokePrivileges = params.getRevokePrivileges(); + List revokeGrantPrivileges = params.getRevokeGrantPrivileges(); + boolean revokeAllPrivilege = params.isRevokeAllPrivilege(); + boolean revokeAllGrantPrivilege = params.isRevokeAllGrantPrivilege(); + boolean isGrant = params.isGrant(); + + userRoleStrBuf.append(userRolesStr); + appendNamespaceForSelectedObj(objectStrBuf, selectedObjects); + + if (isGrant) { + queryFormationOnSelectionOfGrant(previewSqls, objectStrBuf, userRoleStrBuf, selectedObjects, + withGrantOptionPrivileges, withoutGrantOptionPrivileges, allPrivilege, allWithGrantOption); + } else { + queryFormationOnSelectionOfRevoke(previewSqls, objectStrBuf, userRoleStrBuf, selectedObjects, + revokePrivileges, revokeGrantPrivileges, revokeAllPrivilege, revokeAllGrantPrivilege); + } + return previewSqls; + } + + /** + * Query formation on selection of revoke. + * + * @param previewSqls the preview sqls + * @param objectStrBuf the object str buf + * @param userRoleStrBuf the user role str buf + * @param selectedObjects the selected objects + * @param revokePrivileges the revoke privileges + * @param revokeGrantPrivileges the revoke grant privileges + * @param revokeAllPrivilege the revoke all privilege + * @param revokeAllGrantPrivilege the revoke all grant privilege + */ + private void queryFormationOnSelectionOfRevoke(List previewSqls, StringBuffer objectStrBuf, + StringBuffer userRoleStrBuf, List selectedObjects, List revokePrivileges, + List revokeGrantPrivileges, boolean revokeAllPrivilege, boolean revokeAllGrantPrivilege) { + StringBuffer revokePrivilegesStrBuf = new StringBuffer(); + StringBuffer revokeGrantPrivilegesStrBuf = new StringBuffer(); + + appendPriviledgeWithGrant(revokePrivileges, revokePrivilegesStrBuf); + appendPriviledgeWithGrant(revokeGrantPrivileges, revokeGrantPrivilegesStrBuf); + String revokeSqlFormat = null; + revokeSqlFormat = appendRevokeSyntaxForSelectedObj(selectedObjects); + + appendQueryForRevokAllPrivilege(previewSqls, objectStrBuf, userRoleStrBuf, revokeAllPrivilege, + revokeAllGrantPrivilege, revokePrivilegesStrBuf, revokeGrantPrivilegesStrBuf, revokeSqlFormat); + } + + /** + * Append query for revok all privilege. + * + * @param previewSqls the preview sqls + * @param objectStrBuf the object str buf + * @param userRoleStrBuf the user role str buf + * @param revokeAllPrivilege the revoke all privilege + * @param revokeAllGrantPrivilege the revoke all grant privilege + * @param revokePrivilegesStrBuf the revoke privileges str buf + * @param revokeGrantPrivilegesStrBuf the revoke grant privileges str buf + * @param revokeSqlFormat the revoke sql format + */ + private void appendQueryForRevokAllPrivilege(List previewSqls, StringBuffer objectStrBuf, + StringBuffer userRoleStrBuf, boolean revokeAllPrivilege, boolean revokeAllGrantPrivilege, + StringBuffer revokePrivilegesStrBuf, StringBuffer revokeGrantPrivilegesStrBuf, String revokeSqlFormat) { + if (revokeAllPrivilege) { + previewSqls.add(MessageFormat.format(revokeSqlFormat, "", "ALL", + objectStrBuf.substring(0, objectStrBuf.length() - 1), userRoleStrBuf)); + } else if (revokeAllGrantPrivilege) { + previewSqls.add(MessageFormat.format(revokeSqlFormat, "GRANT OPTION FOR", "ALL", + objectStrBuf.substring(0, objectStrBuf.length() - 1), userRoleStrBuf)); + } else { + if (revokePrivilegesStrBuf.length() > 0) { + previewSqls.add(MessageFormat.format(revokeSqlFormat, "", + revokePrivilegesStrBuf.substring(0, revokePrivilegesStrBuf.length() - 1), + objectStrBuf.substring(0, objectStrBuf.length() - 1), userRoleStrBuf)); + } + + if (revokeGrantPrivilegesStrBuf.length() > 0) { + previewSqls.add(MessageFormat.format(revokeSqlFormat, "GRANT OPTION FOR", + revokeGrantPrivilegesStrBuf.substring(0, revokeGrantPrivilegesStrBuf.length() - 1), + objectStrBuf.substring(0, objectStrBuf.length() - 1), userRoleStrBuf)); + } + } + } + + /** + * Append revoke syntax for selected obj. + * + * @param selectedObjects the selected objects + * @return the string + */ + private String appendRevokeSyntaxForSelectedObj(List selectedObjects) { + String revokeSqlFormat; + if (selectedObjects.get(0) instanceof Namespace) { + revokeSqlFormat = "REVOKE {0} {1} ON SCHEMA {2} FROM {3} CASCADE;"; + } else if (selectedObjects.get(0) instanceof DebugObjects) { + revokeSqlFormat = "REVOKE {0} {1} ON FUNCTION {2} FROM {3} CASCADE;"; + } else { + revokeSqlFormat = "REVOKE {0} {1} ON {2} FROM {3} CASCADE;"; + } + return revokeSqlFormat; + } + + /** + * Query formation on selection of grant. + * + * @param previewSqls the preview sqls + * @param objectStrBuf the object str buf + * @param userRoleStrBuf the user role str buf + * @param selectedObjects the selected objects + * @param withGrantOptionPrivileges the with grant option privileges + * @param withoutGrantOptionPrivileges the without grant option privileges + * @param allPrivilege the all privilege + * @param allWithGrantOption the all with grant option + */ + private void queryFormationOnSelectionOfGrant(List previewSqls, StringBuffer objectStrBuf, + StringBuffer userRoleStrBuf, List selectedObjects, List withGrantOptionPrivileges, + List withoutGrantOptionPrivileges, boolean allPrivilege, boolean allWithGrantOption) { + StringBuffer withGrantOptionPrivilegeStrBuf = new StringBuffer(); + StringBuffer withoutGrantOptionPrivilegeStrBuf = new StringBuffer(); + + appendPriviledgeWithGrant(withGrantOptionPrivileges, withGrantOptionPrivilegeStrBuf); + appendPriviledgeWithGrant(withoutGrantOptionPrivileges, withoutGrantOptionPrivilegeStrBuf); + + String grantSqlFormat = null; + grantSqlFormat = appendGrantSyntaxForSelectedObj(selectedObjects); + + appendQueryForAllPrivilegeWithGrantOption(previewSqls, objectStrBuf, userRoleStrBuf, allPrivilege, + allWithGrantOption, grantSqlFormat); + + appendQueryForAllPrivilegeWithoutGrant(previewSqls, objectStrBuf, userRoleStrBuf, allPrivilege, + allWithGrantOption, withGrantOptionPrivilegeStrBuf, grantSqlFormat); + + appendQueryForNotAllPrivilege(previewSqls, objectStrBuf, userRoleStrBuf, allPrivilege, + withGrantOptionPrivilegeStrBuf, withoutGrantOptionPrivilegeStrBuf, grantSqlFormat); + } + + /** + * Append query for not all privilege. + * + * @param previewSqls the preview sqls + * @param objectStrBuf the object str buf + * @param userRoleStrBuf the user role str buf + * @param allPrivilege the all privilege + * @param withGrantOptionPrivilegeStrBuf the with grant option privilege str + * buf + * @param withoutGrantOptionPrivilegeStrBuf the without grant option + * privilege str buf + * @param grantSqlFormat the grant sql format + */ + private void appendQueryForNotAllPrivilege(List previewSqls, StringBuffer objectStrBuf, + StringBuffer userRoleStrBuf, boolean allPrivilege, StringBuffer withGrantOptionPrivilegeStrBuf, + StringBuffer withoutGrantOptionPrivilegeStrBuf, String grantSqlFormat) { + if (!allPrivilege) { + if (withGrantOptionPrivilegeStrBuf.length() > 0) { + previewSqls.add(MessageFormat.format(grantSqlFormat, + withGrantOptionPrivilegeStrBuf.substring(0, withGrantOptionPrivilegeStrBuf.length() - 1), + objectStrBuf.substring(0, objectStrBuf.length() - 1), userRoleStrBuf, "WITH GRANT OPTION")); + } + + if (withoutGrantOptionPrivilegeStrBuf.length() > 0) { + previewSqls.add(MessageFormat.format(grantSqlFormat, + withoutGrantOptionPrivilegeStrBuf.substring(0, withoutGrantOptionPrivilegeStrBuf.length() - 1), + objectStrBuf.substring(0, objectStrBuf.length() - 1), userRoleStrBuf, "")); + } + } + } + + /** + * Append query for all privilege without grant. + * + * @param previewSqls the preview sqls + * @param objectStrBuf the object str buf + * @param userRoleStrBuf the user role str buf + * @param allPrivilege the all privilege + * @param allWithGrantOption the all with grant option + * @param withGrantOptionPrivilegeStrBuf the with grant option privilege str + * buf + * @param grantSqlFormat the grant sql format + */ + private void appendQueryForAllPrivilegeWithoutGrant(List previewSqls, StringBuffer objectStrBuf, + StringBuffer userRoleStrBuf, boolean allPrivilege, boolean allWithGrantOption, + StringBuffer withGrantOptionPrivilegeStrBuf, String grantSqlFormat) { + if (allPrivilege && !allWithGrantOption) { + previewSqls.add(MessageFormat.format(grantSqlFormat, "ALL", + objectStrBuf.substring(0, objectStrBuf.length() - 1), userRoleStrBuf, "")); + + if (withGrantOptionPrivilegeStrBuf.length() > 0) { + previewSqls.add(MessageFormat.format(grantSqlFormat, + withGrantOptionPrivilegeStrBuf.substring(0, withGrantOptionPrivilegeStrBuf.length() - 1), + objectStrBuf.substring(0, objectStrBuf.length() - 1), userRoleStrBuf, "WITH GRANT OPTION")); + } + } + } + + /** + * Append query for all privilege with grant option. + * + * @param previewSqls the preview sqls + * @param objectStrBuf the object str buf + * @param userRoleStrBuf the user role str buf + * @param allPrivilege the all privilege + * @param allWithGrantOption the all with grant option + * @param grantSqlFormat the grant sql format + */ + private void appendQueryForAllPrivilegeWithGrantOption(List previewSqls, StringBuffer objectStrBuf, + StringBuffer userRoleStrBuf, boolean allPrivilege, boolean allWithGrantOption, String grantSqlFormat) { + if (allPrivilege && allWithGrantOption) { + previewSqls.add(MessageFormat.format(grantSqlFormat, "ALL", + objectStrBuf.substring(0, objectStrBuf.length() - 1), userRoleStrBuf, "WITH GRANT OPTION")); + } + } + + /** + * Append grant syntax for selected obj. + * + * @param selectedObjects the selected objects + * @return the string + */ + private String appendGrantSyntaxForSelectedObj(List selectedObjects) { + String grantSqlFormat; + if (selectedObjects.get(0) instanceof Namespace) { + grantSqlFormat = "GRANT {0} ON SCHEMA {1} TO {2} {3};"; + } else if (selectedObjects.get(0) instanceof DebugObjects) { + grantSqlFormat = "GRANT {0} ON FUNCTION {1} TO {2} {3};"; + } else { + grantSqlFormat = "GRANT {0} ON {1} TO {2} {3};"; + } + return grantSqlFormat; + } + + /** + * Append priviledge with grant. + * + * @param withGrantOptionPrivileges the with grant option privileges + * @param withGrantOptionPrivilegeStrBuf the with grant option privilege str + * buf + */ + private void appendPriviledgeWithGrant(List withGrantOptionPrivileges, + StringBuffer withGrantOptionPrivilegeStrBuf) { + for (String privilegeName : withGrantOptionPrivileges) { + if (MPPDBIDEConstants.PRIVILEGE_ALL.equals(privilegeName)) { + continue; + } + withGrantOptionPrivilegeStrBuf.append(privilegeName).append(","); + } + } + + /** + * Append namespace for selected obj. + * + * @param objectStrBuf the object str buf + * @param selectedObjects the selected objects + */ + private void appendNamespaceForSelectedObj(StringBuffer objectStrBuf, List selectedObjects) { + for (Object object : selectedObjects) { + ServerObject serverObject = (ServerObject) object; + if (selectedObjects.get(0) instanceof Namespace) { + objectStrBuf.append(serverObject.getQualifiedObjectName()).append(","); + } else if (selectedObjects.get(0) instanceof DebugObjects) { + objectStrBuf.append(namespace.getQualifiedObjectName()).append(".") + .append(((DebugObjects) serverObject).getGrantRevokeName()).append(","); + } else { + objectStrBuf.append(namespace.getQualifiedObjectName()).append(".") + .append(serverObject.getQualifiedObjectName()).append(","); + } + } + } + + /** + * Modify object privilege. + * + * @param conn the conn + * @param sqls the sqls + * @param messageQueue the message queue + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void modifyObjectPrivilege(DBConnection conn, List sqls, MessageQueue messageQueue) + throws DatabaseOperationException, DatabaseCriticalException { + try { + conn.execNonSelect("START TRANSACTION;"); + for (String sql : sqls) { + conn.execQueryWithMsgQueue(sql, messageQueue); + } + conn.execNonSelect("COMMIT;"); + MPPDBIDELoggerUtility.debug("Commit object privilege modification"); + } catch (Exception e) { + conn.execNonSelect("ROLLBACK;"); + MPPDBIDELoggerUtility.debug("Rollback object privilege modification"); + throw e; + } + + } + + /** + * Gets the user role option. + * + * @return the user role option + */ + public List getUserRoleOption() { + return Arrays.asList(database.getServer().getUserRoleObjectGroup().getChildren()).stream() + .map(object -> ((ServerObject) object).getQualifiedObjectName() != null + ? ((ServerObject) object).getQualifiedObjectName() + : "") + .collect(Collectors.toList()); + } + + /** + * Gets the database. + * + * @return the database + */ + public Database getDatabase() { + return database; + } + + /** + * Gets the object option. + * + * @return the object option + */ + public Object[] getObjectOption() { + return objectOption != null ? Arrays.copyOf(objectOption, objectOption.length) : new Object[0]; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/userrole/GrantRevokeParameters.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/userrole/GrantRevokeParameters.java new file mode 100644 index 0000000000000000000000000000000000000000..fae6550becc307bad1c8b0533b1d625bf9294fa9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/userrole/GrantRevokeParameters.java @@ -0,0 +1,239 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.userrole; + +import java.util.List; + +/** + * + * Title: class + * + * Description: The Class GrantRevokeParameters. + * + * @since 3.0.0 + */ +public class GrantRevokeParameters { + private List selectedObjects; + private String userRolesStr; + private List withGrantOptionPrivileges; + private List withoutGrantOptionPrivileges; + private boolean allPrivilege; + private boolean allWithGrantOption; + private List revokePrivileges; + private List revokeGrantPrivileges; + private boolean revokeAllPrivilege; + private boolean revokeAllGrantPrivilege; + private boolean isGrant; + + /** + * Gets the selected objects. + * + * @return the selected objects + */ + public List getSelectedObjects() { + return selectedObjects; + } + + /** + * Sets the selected objects. + * + * @param selectedObjects the new selected objects + */ + public void setSelectedObjects(List selectedObjects) { + this.selectedObjects = selectedObjects; + } + + /** + * Gets the user roles str. + * + * @return the user roles str + */ + public String getUserRolesStr() { + return userRolesStr; + } + + /** + * Sets the user roles str. + * + * @param userRolesStr the new user roles str + */ + public void setUserRolesStr(String userRolesStr) { + this.userRolesStr = userRolesStr; + } + + /** + * Gets the with grant option privileges. + * + * @return the with grant option privileges + */ + public List getWithGrantOptionPrivileges() { + return withGrantOptionPrivileges; + } + + /** + * Sets the with grant option privileges. + * + * @param withGrantOptionPrivileges the new with grant option privileges + */ + public void setWithGrantOptionPrivileges(List withGrantOptionPrivileges) { + this.withGrantOptionPrivileges = withGrantOptionPrivileges; + } + + /** + * Gets the without grant option privileges. + * + * @return the without grant option privileges + */ + public List getWithoutGrantOptionPrivileges() { + return withoutGrantOptionPrivileges; + } + + /** + * Sets the without grant option privileges. + * + * @param withoutGrantOptionPrivileges the new without grant option + * privileges + */ + public void setWithoutGrantOptionPrivileges(List withoutGrantOptionPrivileges) { + this.withoutGrantOptionPrivileges = withoutGrantOptionPrivileges; + } + + /** + * Checks if is all privilege. + * + * @return true, if is all privilege + */ + public boolean isAllPrivilege() { + return allPrivilege; + } + + /** + * Sets the all privilege. + * + * @param allPrivilege the new all privilege + */ + public void setAllPrivilege(boolean allPrivilege) { + this.allPrivilege = allPrivilege; + } + + /** + * Checks if is all with grant option. + * + * @return true, if is all with grant option + */ + public boolean isAllWithGrantOption() { + return allWithGrantOption; + } + + /** + * Sets the all with grant option. + * + * @param allWithGrantOption the new all with grant option + */ + public void setAllWithGrantOption(boolean allWithGrantOption) { + this.allWithGrantOption = allWithGrantOption; + } + + /** + * Gets the revoke privileges. + * + * @return the revoke privileges + */ + public List getRevokePrivileges() { + return revokePrivileges; + } + + /** + * Sets the revoke privileges. + * + * @param revokePrivileges the new revoke privileges + */ + public void setRevokePrivileges(List revokePrivileges) { + this.revokePrivileges = revokePrivileges; + } + + /** + * Gets the revoke grant privileges. + * + * @return the revoke grant privileges + */ + public List getRevokeGrantPrivileges() { + return revokeGrantPrivileges; + } + + /** + * Sets the revoke grant privileges. + * + * @param revokeGrantPrivileges the new revoke grant privileges + */ + public void setRevokeGrantPrivileges(List revokeGrantPrivileges) { + this.revokeGrantPrivileges = revokeGrantPrivileges; + } + + /** + * Checks if is revoke all privilege. + * + * @return true, if is revoke all privilege + */ + public boolean isRevokeAllPrivilege() { + return revokeAllPrivilege; + } + + /** + * Sets the revoke all privilege. + * + * @param revokeAllPrivilege the new revoke all privilege + */ + public void setRevokeAllPrivilege(boolean revokeAllPrivilege) { + this.revokeAllPrivilege = revokeAllPrivilege; + } + + /** + * Checks if is revoke all grant privilege. + * + * @return true, if is revoke all grant privilege + */ + public boolean isRevokeAllGrantPrivilege() { + return revokeAllGrantPrivilege; + } + + /** + * Sets the revoke all grant privilege. + * + * @param revokeAllGrantPrivilege the new revoke all grant privilege + */ + public void setRevokeAllGrantPrivilege(boolean revokeAllGrantPrivilege) { + this.revokeAllGrantPrivilege = revokeAllGrantPrivilege; + } + + /** + * Checks if is grant. + * + * @return true, if is grant + */ + public boolean isGrant() { + return isGrant; + } + + /** + * Sets the grant. + * + * @param isGrnt the new grant + */ + public void setGrant(boolean isGrnt) { + this.isGrant = isGrnt; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/util/AbstractValueComparator.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/util/AbstractValueComparator.java new file mode 100644 index 0000000000000000000000000000000000000000..a46a6f18eff18a991e9b32ccdf003bd87d62569c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/util/AbstractValueComparator.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.util; + +import java.io.Serializable; +import java.util.Comparator; + +/** + * + * Title: class + * + * Description: The Class AbstractValueComparator. + * + * @param the generic type + * @since 3.0.0 + */ +public abstract class AbstractValueComparator implements Comparator, Serializable { + + private static final long serialVersionUID = 1L; + + /** + * Compare. + * + * @param o1 the o 1 + * @param o2 the o 2 + * @return the int + */ + @Override + public int compare(T o1, T o2) { + int res = 0; + if (o1 == null) { + res = (o2 != null) ? -1 : 0; + } else if (o2 == null) { + res = 1; + } else { + res = compareValues(o1, o2); + + } + + return res; + } + + /** + * Compare values. + * + * @param o1 the o 1 + * @param o2 the o 2 + * @return the int + */ + protected abstract int compareValues(T o1, T o2); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/util/DataTypeUtility.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/util/DataTypeUtility.java new file mode 100644 index 0000000000000000000000000000000000000000..d2a380f92b6c59c3da29b409448a5cbf40b34af7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/util/DataTypeUtility.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.util; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * + * Title: class + * + * Description: The Class DataTypeUtility. + * + * @since 3.0.0 + */ +public abstract class DataTypeUtility { + + /** + * Convert to date obj. + * + * @param value the value + * @param pattern the pattern + * @return the date + * @throws ParseException the parse exception + */ + public static Date convertToDateObj(Object value, String pattern) throws ParseException { + SimpleDateFormat datetimeFormatter1 = new SimpleDateFormat(pattern); + Date dateValue = datetimeFormatter1.parse((String) value); + return dateValue; + } + + /** + * Convert to time obj. + * + * @param value the value + * @param pattern the pattern + * @return the date + * @throws ParseException the parse exception + */ + public static Date convertToTimeObj(Object value, String pattern) throws ParseException { + SimpleDateFormat datetimeFormatter1 = new SimpleDateFormat(pattern); + Date dateValue = datetimeFormatter1.parse((String) value); + return dateValue; + } + + /** + * Convert to display datatype. + * + * @param datatypeName the datatype name + * @return the string + */ + public static String convertToDisplayDatatype(String datatypeName) { + switch (datatypeName) { + case "bpchar": { + return "char"; + } + case "bool": { + return "boolean"; + } + case "float": { + return "binary double"; + } + case "int2": { + return "smallint"; + } + case "int4": { + return "integer"; + } + case "int8": { + return "bigint"; + } + case "float8": { + return "double precision"; + } + case "float4": { + return "real"; + } + case "timetz": { + return "time with time zone"; + } + case "timestamptz": { + return "timestamp with time zone"; + } + case "time": { + return "time without time zone"; + } + case "timestamp": { + return "timestamp without time zone"; + } + default: { + return datatypeName; + } + + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/view/ViewViewDataCore.java b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/view/ViewViewDataCore.java new file mode 100644 index 0000000000000000000000000000000000000000..decb31e19393ee00543894cfeb1633b257daa815 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.presentation/src/org/opengauss/mppdbide/presentation/view/ViewViewDataCore.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.presentation.view; + +import java.util.Locale; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.presentation.AbstractViewTableDataCore; +import org.opengauss.mppdbide.presentation.IWindowDetail; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.messaging.ProgressBarLabelFormatter; + +/** + * + * Title: class + * + * Description: The Class ViewViewDataCore. + * + * @since 3.0.0 + */ +public class ViewViewDataCore extends AbstractViewTableDataCore { + private static final String VIEW_DATA = "VIEW_DATA_"; + private static final String SELECT_ALL_QUERY = "select * from %s"; + private ViewMetaData serverObject; + private ViewWindowDetails details; + + /** + * Gets the server object. + * + * @return the server object + */ + public ViewMetaData getServerObject() { + return serverObject; + } + + /** + * Gets the window details. + * + * @return the window details + */ + public IWindowDetail getWindowDetails() { + return details; + } + + /** + * Gets the window title. + * + * @return the window title + */ + public String getWindowTitle() { + String windowTitle = null; + if (serverObject != null) { + Database database = serverObject.getDatabase(); + windowTitle = serverObject.getNameSpaceName() + '.' + serverObject.getName() + '-' + database.getName() + + '@' + database.getServer().getName(); + } + return windowTitle; + } + + /** + * Gets the progress bar label. + * + * @return the progress bar label + */ + public String getProgressBarLabel() { + String progressLabel = null; + + if (serverObject != null) { + Database database = serverObject.getDatabase(); + progressLabel = ProgressBarLabelFormatter.getProgressLabelForTableWithMsg(serverObject.getName(), + serverObject.getNamespace().getName(), database.getName(), database.getServer().getName(), + IMessagesConstants.VIEW_PROGRESS_NAME); + } + return progressLabel; + } + + /** + * + * Title: class + * + * Description: The Class ViewWindowDetails. + */ + private class ViewWindowDetails implements IWindowDetail { + @Override + public String getTitle() { + return getWindowTitle(); + } + + @Override + public String getUniqueID() { + return VIEW_DATA + getTitle(); + } + + @Override + public String getShortTitle() { + return serverObject.getDisplayName(); + } + } + + /** + * Gets the query. + * + * @return the query + */ + public String getQuery() { + return String.format(Locale.ENGLISH, SELECT_ALL_QUERY, serverObject.getDisplayName()); + } + + + /** + * the init + * + * @param obj the obj + */ + public void init(ServerObject obj) { + if (obj instanceof ViewMetaData) { + this.serverObject = (ViewMetaData) obj; + details = new ViewWindowDetails(); + } + } + + @Override + public boolean isTableDropped() { + return serverObject.isViewDropped(); + } + + @Override + public void refreshTable(DBConnection conn) throws DatabaseCriticalException, DatabaseOperationException { + serverObject.getNamespace().refreshView(serverObject, conn, false); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.repository/.project b/code/datastudio/src/org.opengauss.mppdbide.repository/.project new file mode 100644 index 0000000000000000000000000000000000000000..5ee5d645f6314f4d325ca348c87e9700e7043516 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.repository/.project @@ -0,0 +1,23 @@ + + + org.opengauss.mppdbide.repository + + + + + + org.eclipse.pde.UpdateSiteBuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.pde.UpdateSiteNature + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.repository/category.xml b/code/datastudio/src/org.opengauss.mppdbide.repository/category.xml new file mode 100644 index 0000000000000000000000000000000000000000..0bbaf6eb6a97eaf3397a804051c2bae00755ad6e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.repository/category.xml @@ -0,0 +1,11 @@ + + + + + + + + Data Studio Repository + + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio-16x16x32.bmp b/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio-16x16x32.bmp new file mode 100644 index 0000000000000000000000000000000000000000..a3feb3bf968d38e434050c12266740ce6bf6cf14 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio-16x16x32.bmp differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio-16x16x8.bmp b/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio-16x16x8.bmp new file mode 100644 index 0000000000000000000000000000000000000000..9307c408032a04d0d3c3c15b54cbcdaf5cba66e2 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio-16x16x8.bmp differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio-256x256x32.bmp b/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio-256x256x32.bmp new file mode 100644 index 0000000000000000000000000000000000000000..dccf6c69afc5da7a423de7683bb24e65cd8508ae Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio-256x256x32.bmp differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio-32x32x32.bmp b/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio-32x32x32.bmp new file mode 100644 index 0000000000000000000000000000000000000000..5464b32fa74b75f304856f6871f577e8d9cc0f8c Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio-32x32x32.bmp differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio-32x32x8.bmp b/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio-32x32x8.bmp new file mode 100644 index 0000000000000000000000000000000000000000..635eb98c3b082b44d63c7c6903a2006404319542 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio-32x32x8.bmp differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio-48x48x32.bmp b/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio-48x48x32.bmp new file mode 100644 index 0000000000000000000000000000000000000000..1bc1829bbed42d63a939b95413bd62a93cc5071d Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio-48x48x32.bmp differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio-48x48x8.bmp b/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio-48x48x8.bmp new file mode 100644 index 0000000000000000000000000000000000000000..11e5be62a6e20630cfc1531ffe7e7face0418da1 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio-48x48x8.bmp differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio.png b/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio.png new file mode 100644 index 0000000000000000000000000000000000000000..973a86c9176f20ff31abbb9e3b2f4d6b49d22ea3 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.repository/icons/DataStudio ICO/datastudio.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.repository/mppdbide.p2.inf b/code/datastudio/src/org.opengauss.mppdbide.repository/mppdbide.p2.inf new file mode 100644 index 0000000000000000000000000000000000000000..29b06a3cb03a9d3005e0243bbb51a808fddc3a67 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.repository/mppdbide.p2.inf @@ -0,0 +1 @@ +instructions.configure=org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/eclipsec.exe); \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.repository/mppdbide.product b/code/datastudio/src/org.opengauss.mppdbide.repository/mppdbide.product new file mode 100644 index 0000000000000000000000000000000000000000..5d4a6f6a60330116e02b02b8cb869b3c5eff8307 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.repository/mppdbide.product @@ -0,0 +1,59 @@ + + + + + + + + + + -clearPersistedState -consoleLineCount=5000 -logfolder=. -loginTimeout=180 -enableSSL=true -data +@user.home/MyAppWorkspace -focusOnFirstResult=false + + --launcher.GTK_version 2 + + -Dosgi.requiredJavaVersion=1.11 -Xms40m -Xmx1200m -Dorg.osgi.framework.bundle.parent=ext -Dosgi.framework.extensions=org.eclipse.fx.osgi -Dorg.eclipse.swt.graphics.Resource.reportNonDisposed=false + + -XstartOnFirstThread -Dorg.eclipse.swt.internal.carbon.smallFonts + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.repository/pom.xml b/code/datastudio/src/org.opengauss.mppdbide.repository/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..08bfec7dbc3cb483b5537c9e7370036475c5b69d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.repository/pom.xml @@ -0,0 +1,545 @@ + + + 4.0.0 + + org.opengauss.plide.build + GAUSS_MPP_DB_IDE + 1.0.0-SNAPSHOT + + org.opengauss.mppdbide.repository + eclipse-repository + + + UTF-8 + + ${project.build.directory}/../../ + + ${project.build.directory}/products/mppdbide.product/win32/win32/x86 + + ${project.build.directory}/products/mppdbide.product/win32/win32/x86_64 + + ${project.build.directory}/products/mppdbide.product/linux/gtk/x86_64 + + ${project.build.directory}/products/mppdbide.product/org.opengauss.mppdbide.repository/icons/ + + yyyyMMdd_HHmm + + ${basedir}/../../build/ + Data Studio + + ${target-product-dir}/${tool-name}/docs/ + + ${target-product-dir_x86_64}/${tool-name}/docs/ + + ${target-product-dir_linux_x86_64}/${tool-name}/docs/ + + ${target-product-dir}/${tool-name}/db_assistant/ + + ${target-product-dir_x86_64}/${tool-name}/db_assistant/ + + ${target-product-dir_linux_x86_64}/${tool-name}/db_assistant/ + + ${target-product-dir}/${tool-name}/tools/ + + ${target-product-dir_x86_64}/${tool-name}/tools/ + + ${target-product-dir}/${tool-name}/tools/win/dbms1/ + + ${target-product-dir}/${tool-name}/tools/win/FileUtil/ + + ${target-product-dir}/${tool-name}/tools/win/dbms2/ + + ${target-product-dir}/${tool-name}/tools/win/dbms3/ + + ${target-product-dir_x86_64}/${tool-name}/tools/win/dbms1/ + + ${target-product-dir_x86_64}/${tool-name}/tools/win/FileUtil/ + + ${target-product-dir_x86_64}/${tool-name}/tools/win/dbms2/ + + ${target-product-dir_x86_64}/${tool-name}/tools/win/dbms3/ + + ${target-product-dir_linux_x86_64}/${tool-name}/tools/linux/dbms1/ + + ${target-product-dir_linux_x86_64}/${tool-name}/tools/linux/dbms2/ + + ${target-product-dirfor}/${tool-name}/docs/ + + ${target-product-dirfor}/${tool-name}/tools/ + + + + + org.eclipse.tycho + tycho-p2-director-plugin + ${tycho-version} + + + + materialize-products + + materialize-products + + + + + archive-products + + archive-products + + + + + mppdbide.product + + ${data.studio.binaryName} + + + + + + + + + mppdbide.product + ${tool-name} + + + + + + maven-antrun-plugin + 1.8 + + + copy-ds-final-package + clean + + + + + + + + + + + run + + + + copy-package + package + + + + + + + + + + + run + + + + + + maven-resources-plugin + 2.5 + + + copy-resources + generate-resources + + copy-resources + + + + ${project.build.directory}/products/mppdbide.product/org.opengauss.mppdbide.repository/icons/ + + + + icons + + + + + + ds-manual-pdf-copy-resources + generate-resources + + copy-resources + + + ${docs-output-dir} + + + ../../docs/ + + **/*.pdf + + + + + + + ds-manual-pdf-copy-resources_x86_64 + generate-resources + + copy-resources + + + + ${docs-output-dir_x86_64} + + + ../../docs/ + + **/*.pdf + + + + + + + ds-manual-pdf-copy-resources_linux_x86_64 + generate-resources + + copy-resources + + + + ${docs-output-dir_linux_x86_64} + + + ../../docs/ + + **/*.pdf + + + + + + + ds-readme-txt-copy-resources + generate-resources + + copy-resources + + + ${target-product-dir}/${tool-name} + + + ../../docs/ + + **/*.txt + + + + + + + ds-readme-txt-copy-resources_x86_64 + generate-resources + + copy-resources + + + + ${target-product-dir_x86_64}/${tool-name} + + + ../../docs/ + + **/*.txt + + + + + + + ds-readme-txt-copy-resources_linux_x86_64 + generate-resources + + copy-resources + + + + ${target-product-dir_linux_x86_64}/${tool-name} + + + ../../docs/ + + **/*.txt + + + + + + + ds-assit-copy-resources + generate-resources + + copy-resources + + + + ${assit-output-dir} + + + ../../db_assistant/ + + + + + + ds-assit-copy-resources_x86_64 + generate-resources + + copy-resources + + + + ${assit-output-dir_x86_64} + + + ../../db_assistant/ + + + + + + ds-assit-copy-resources_linux_x86_64 + generate-resources + + copy-resources + + + + ${assit-output-dir_linux_x86_64} + + + ../../db_assistant/ + + + + + + tools-output-dir-startstudiobat + generate-resources + + copy-resources + + + + ${tools-output-dir-startstudiobat} + + + tools/ + + + + + + tools-output-dir-startstudiobat_x86_64 + generate-resources + + copy-resources + + + + ${tools-output-dir-startstudiobat_x86_64} + + + tools/ + + + + + + ds-manual-tools-copy-resources_linux_x86_64-dbms1 + generate-resources + + copy-resources + + + + ${tools-output-dir-linux_x86_64-dbms1} + + + tools/linux/dbms1 + + + + + + ds-manual-tools-copy-resources_linux_x86_64-dbms2 + generate-resources + + copy-resources + + + + ${tools-output-dir-linux_x86_64-dbms2} + + + tools/linux/dbms2 + + + + + + ds-manual-tools-copy-resources-dbms1 + generate-resources + + copy-resources + + + + ${tools-output-dir-dbms1} + + + tools/win/dbms1/ + + + + + + ds-manual-tools-copy-resources-FileUtil + generate-resources + + copy-resources + + + + ${tools-output-dir-FileUtil} + + + tools/win/FileUtil/ + + + + + + ds-manual-tools-copy-resources_x86_64-dbms1 + generate-resources + + copy-resources + + + + ${tools-output-dir_x86_64-dbms1} + + + tools/win/dbms1/ + + + + + + ds-manual-tools-copy-resources_x86_64-FileUtil + generate-resources + + copy-resources + + + + ${tools-output-dir_x86_64-FileUtil} + + + tools/FileUtil/ + + + + + + ds-manual-tools-copy-resources-dbms3 + generate-resources + + copy-resources + + + + ${tools-output-dir-dbms3} + + + tools/win/dbms3/ + + + + + + ds-manual-tools-copy-resources_x86_64-dbms3 + generate-resources + + copy-resources + + + + ${tools-output-dir_x86_64-dbms3} + + + tools/win/dbms3/ + + + + + + ds-manual-tools-copy-resources-dbms2 + generate-resources + + copy-resources + + + + ${tools-output-dir-dbms2} + + + tools/win/dbms2 + + + + + + ds-manual-tools-copy-resources_x86_64-dbms2 + generate-resources + + copy-resources + + + + ${tools-output-dir_x86_64-dbms2} + + + tools/win/dbms2 + + + + + + + + org.codehaus.mojo + properties-maven-plugin + 1.0-alpha-2 + + + initialize + + read-project-properties + + + + ${basedir}/../version.properties + + + + + + + + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/.classpath b/code/datastudio/src/org.opengauss.mppdbide.utils/.classpath new file mode 100644 index 0000000000000000000000000000000000000000..14280364947f4424381b6013c9c3f366ebb07b73 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/.gitignore b/code/datastudio/src/org.opengauss.mppdbide.utils/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ddc25c7fcd00a3a38f67eabde7efb88c26a8c3a8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/.gitignore @@ -0,0 +1,3 @@ +/bin/ +/.settings/ +/target/ diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/.project b/code/datastudio/src/org.opengauss.mppdbide.utils/.project new file mode 100644 index 0000000000000000000000000000000000000000..0ea012ea681e1dffd1eeded0f960bf660550bb4d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/.project @@ -0,0 +1,40 @@ + + + org.opengauss.mppdbide.utils + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.pde.api.tools.apiAnalysisBuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + org.eclipse.pde.api.tools.apiAnalysisNature + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/META-INF/MANIFEST.MF b/code/datastudio/src/org.opengauss.mppdbide.utils/META-INF/MANIFEST.MF new file mode 100644 index 0000000000000000000000000000000000000000..34b3e4418c4ee2d14be19364f30e837ec31ad71a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/META-INF/MANIFEST.MF @@ -0,0 +1,31 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: MPPDBIDE_Util +Bundle-SymbolicName: org.opengauss.mppdbide.util +Bundle-Version: 1.0.0.qualifier +Bundle-Activator: org.opengauss.mppdbide.utils.Activator +Bundle-Vendor: Huawei Technologies +Require-Bundle: org.eclipse.core.runtime;bundle-version="3.15.300", + org.eclipse.jface;bundle-version="3.16.0", + org.eclipse.jface.text;bundle-version="3.15.200", + org.apache.commons.lang3;bundle-version="3.1.0", + org.apache.commons.codec;bundle-version="1.10.0", + org.apache.commons.io;bundle-version="2.6.0", + JSQLParser;bundle-version="1.0.0" +Bundle-RequiredExecutionEnvironment: JavaSE-11 +Bundle-ActivationPolicy: lazy +Export-Package: ., + org.opengauss.mppdbide.utils, + org.opengauss.mppdbide.utils.connectionprofileversion, + org.opengauss.mppdbide.utils.exceptions, + org.opengauss.mppdbide.utils.files, + org.opengauss.mppdbide.utils.loader, + org.opengauss.mppdbide.utils.logger, + org.opengauss.mppdbide.utils.messaging, + org.opengauss.mppdbide.utils.observer, + org.opengauss.mppdbide.utils.security, + org.opengauss.mppdbide.utils.stringparse +Import-Package: net.sf.jsqlparser.schema +Bundle-ClassPath: ., + log4j-api-2.17.1.jar, + log4j-core-2.17.1.jar diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/build.properties b/code/datastudio/src/org.opengauss.mppdbide.utils/build.properties new file mode 100644 index 0000000000000000000000000000000000000000..d771e624ee3569d2f7d6032c03104eaab07fde3a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/build.properties @@ -0,0 +1,6 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + log4j-api-2.17.1.jar,\ + log4j-core-2.17.1.jar diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/compile_plsqlide.utils.xml b/code/datastudio/src/org.opengauss.mppdbide.utils/compile_plsqlide.utils.xml new file mode 100644 index 0000000000000000000000000000000000000000..59be8deb82cd9dfed8bf0c859142668cbefb9b88 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/compile_plsqlide.utils.xml @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/pom.xml b/code/datastudio/src/org.opengauss.mppdbide.utils/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..e9e434440f438d742160256e0ce3e3edbaed74ae --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/pom.xml @@ -0,0 +1,19 @@ + + 4.0.0 + + org.opengauss.plide.build + GAUSS_MPP_DB_IDE + 1.0.0-SNAPSHOT + + org.opengauss.mppdbide.util + eclipse-plugin + + + \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/log4j2.xml b/code/datastudio/src/org.opengauss.mppdbide.utils/src/log4j2.xml new file mode 100644 index 0000000000000000000000000000000000000000..42a6ec4e273425ec6f71588e93d997a3df37d1e5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/log4j2.xml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/messages.properties b/code/datastudio/src/org.opengauss.mppdbide.utils/src/messages.properties new file mode 100644 index 0000000000000000000000000000000000000000..b80200b1119005ab79aaf415c85b090f97418c05 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/messages.properties @@ -0,0 +1,3181 @@ + +ENTRE_CLIENTSSLKEY = Client SSL Key +ENTER_CLIENT_SSLPVT_KEYFILE = Enter client SSL private key file: +BTN_CLIENT_PVTKEY = *.key +INVALID_SSL_KEY = Invalid SSL key file + +MULTISORT_POPUP_WINDOW_TITLE = Multi-Column Sort +COLUMN_PRIORITY = Priority +COLUMN_COLUMN_NAME = Column Name +COLUMN_DATATYPE = Data Type +COLUMN_SORT_ORDER = Sort Order +BUTTON_ADD_COLUMN = Add Column +BUTTON_DELETE_COLUMN = Delete Column +BUTTON_UP_COLUMN = Up +BUTTON_DOWN_COULMN = Down +BUTTON_APPLY_SORT = Apply +COMBO_TEXT_SORT_COLUMN = -- Sort Column -- +COMBO_TEXT_SORT_OREDER = -- Sort Order -- +COMBO_OPTION_ASCENDING = Ascending +COMBO_OPTION_DESCENDING = Descending +GRIDDATA_SORT = Multi-Column Sort +SORT_ERROR_WINDOW_TITLE = Multi-column Sort Error +SORT_ERROR_BLANK_COLUMN = All sort criteria must have a column name specified. \nSelect a valid column name for priority {0} and try again. +SORT_ERROR_DUPLICATE_COLUMN = Column {0} is being sorted more than once. \nDelete the duplicate sort criteria in priority {1} and try again. +CLEAR_SORT = Clear Sort + +COLUMN_HEADER_QUERY_PLAN = Query Plan +EXPLAIN_PLAN_MORE_THAN_ONE_QUERY_TITLE = Execution Plan +EXPLAIN_PLAN_MORE_THAN_ONE_QUERY_MSG = Multiple queries selected for execution plan. Execution plan will be provided only for the first query and remaining queries will be executed. Do you want to proceed? +EXPLAIN_ANALYZE_WINDOW_TITLE = Execution Analyze Plan +EXPLAIN_ANALYZE_WARNING_MSG = Selection of Include Analyze in the explain plan will execute the query. Table data will be affected if the query contains DML statements. Do you want to proceed? +TOOLBAR_TREE_VIEW = Tree Format +TOOLBAR_TEXT_VIEW = Text Format +EXECUTION_PLAN_JOB = Executing explain plan +EXECUTION_PLAN_SAVE = Saving explain plan +EXECUTION_PLAN_SAVE_POPUP_TITLE = Explain Plan Exported Successfully +EXECUTION_PLAN_SAVE_POPUP_MSG = Exported explain plan. +INCLUDE_ANALYZE_DROPDOWN = Include Analyze + +SET_GBK_FILE_ENCODE_PREF = Set GBK as File Encoding while working with Chinese tables. +CHECK_FILE_ENCODE_SET = \n\nHint: \ + \n1. Check the file encoding set in Preferences > Environment > Session Setting.\ + \n2. Refresh Object Browser to check if objects exist in the database. + +BATCH_EXPORT_DDL_ERROR_FAIL_OBJ = Export {0} Error +BATCH_EXPORT_WARNING_TEXT = You have selected more than 100 object to export {0}. This operation may take a while to complete.\n\nDo you want to continue with export {0} operation? +BATCH_EXPORT_JOB = Batch export in progress +BATCH_EXPORT_DDL_VALID_OBJ = Export {0} operation is allowed only on following objects: +BATCH_EXPORT_DDL_VALID_OBJ_LIST = \nSchema\nRegular Table\nPartition Table\nFunction/Procedure\nView\nSequence +BATCH_EXPORT_DDLDATA_VALID_OBJ_LIST = \nSchema\nRegular Table\nPartition Table\nSequence +BATCH_EXPORT_DDL_MULTIPLE_DB = Export {0} operation can be performed only within a database. +BATCH_EXPORT_DDL_NO_OBJ = Export {0} operation is not allowed from Object Groups. +EXPORT_FAIL_PROCESS_INTRUPTED_FOR_OBJ=Export process failed.\nReason: {0} + +BATCH_EXPORT_NO_USER_PREVILAGE = Current user is not a super or admin user. +BATCH_EXPORT_ERROR_SHORT_MSG = Export process failed. + +UPDATE_DBG_OBJ_TITLE = Source Code Change +UPDATE_DBG_OBJ_QUESTION = Debug object {0} is not in sync with server. Do you want to discard the changes and sync with server? +LBL_GRP_OB_ACESS = Object Browser +LBL_OBJS = Load Objects +OB_ACCESS_TYPE_ALL = All objects +OB_ACCESS_TYPE_PRIVILEGED = Objects allowed as per user privilege +ERR_GUI_SERVER_CONNECTION_FAILED = Connection Failed + +ERR_GUI_COMPILE_FUN_PROC_TRIG_QUERY_FAILED = Compiling of {0} failed. Check {1} code. + +ERR_GUI_EXECUTE_FUN_PROC_TRIG_QUERY_FAILED = Execution failed. Please Check code. + +ERR_GUI_LOADING_FUN_PROC_TRIG_FAILED = Error loading object: {0} + +ERR_GUI_INVALID_CONNECTION_DETAILS = Check whether the connection details are valid and the server is running. + +MSG_HINT_GUI_CONNECTION_FAIL = HINT (Try one of the below): \ + \n1. Verify the connection properties specified.\ + \n2. Check whether the Data Studio and Server are version compatible. \ + \n3. Check whether the configurations are set properly, refer the client and server manual for more information. + +MSG_HINT_GUI_CONNECTION_FAIL_FOR_SSL = HINT (Try one of the below): \ + \n1. Verify that SSL password is valid\ + \n2. Verify that valid certificate and key files are used + + +ERR_GUI_RESULT_SET_INVALID = Result set fetch invalid. +ERR_SYNONYM_NOT_SUPPORTED = Synonyms are not supported in this server, please uncheck Synonyms and search. +ERR_EXPORT_TABLE_TO_CSV=Error while exporting table data + + + +#BL Error messages + +ERR_BL_ATTACH_TARGET_FAILED = An error occurred while attaching to target session. + +ERR_BL_DETACH_TARGET_FAILED = An error occurred while detaching session. + +ERR_BL_CONNECT_FAILED = An error occurred while connecting. + +ERR_BL_EXECUTE_FAILED = An error occurred while executing. + +LOG_SOURCE = Source + +ERR_UI_EXPORT_FILE_OVERWRITE = File Overwrite Confirmation +ERR_UI_NAME_EXIT = Are you sure you want to overwrite the existing file with same name? + +ERR_UI_EXPORT_QUERY =Error while exporting query data. +IDE_INTERNAL_ERR = Data Studio Internal error. + +USER_GUIDE_NAME=docs/Data Studio User Manual.pdf + +EXE_BL_CLS = I/O Exception while closing properties file. + +ERR_BL_GET_SESSION_FAILED = An error occurred while getting session. + +ERR_BL_LOAD_PROPERTIES = Error while loading properties file. + +ERR_BL_GET_SOURCECODE_FAILED = An error occurred while getting source code. + +ERR_BL_REFRESH_OBJECT_FAILED = An error occurred while refreshing object. + +ERR_BL_SYNC_FAILED = An error occurred while sync. + +STATUS_MSG_VARIABLE_COLUMN_THREE = Value + +STATUS_MSG_PLVIEWER_OPTION_CUT = Cu&t +STATUS_MSG_PLVIEWER_OPTION_COPY =&Copy +STATUS_MSG_PLVIEWER_OPTION_PASTE=Paste + STATUS_MSG_PLVIEWER_OPTION_SELECTALL=Select &All + STATUS_MSG_PLVIEWER_OPTION_EXECUTE_DB_OBJECT=&Execute + STATUS_MSG_PLVIEWER_OPTION_EXECUTE_STATEMENT=E&xecute Statement + STATUS_MSG_PLVIEWER_OPTION_COMPILE_STATEMENT=Co&mpile + +ERR_BL_GET_SESSION_ID_FAILED = An error while getting Session ID. + +ERR_BL_GET_SERVER_SYNC_FAILED = An error occurred while getting the server sync status. + +ERR_BL_GET_DRIVER_VERSION_FAILED = An error occurred while getting the driver version. + +ERR_BL_REFCUR_EXECUTION_TEMPLATE_FAILURE = Execution of functions with REFCURSOR as IN/INOUT parameter is not supported. + +ERR_GUI_SOURCE_NOT_AVAILABLE = Source not available. + +MSG_GUI_REFRESH_STATUSBAR = Refreshing... + +MSG_GUI_TERMINATE_STATUSBAR = Terminating.... + +MSG_GUI_EXECUTE_STATUSBAR = Executing SQL... + +MSG_GUI_GENERATEQUERYPLAN_STATUSBAR=Generating Visual Query Plan... + +ERR_BL_INVALID_STATE = Data Studio state to perform this operation. + +ERR_BL_SERVER_CONNECTION_FAILED = Connection Failed + +ERR_UI_INTERNAL_FAILURE = An unknown internal error occurred. Contact Data Studio support team with log file information. + +ERR_BL_NO_NAMESPACE_AVAILABLE = Namespace not available in the cache. + +ERR_EXE_PLAN_QUERY_PARSE_FAILED=Query parsing failed. Check if the query is complete. + +MSG_HINT_REFRESH_OBJECTBROWSER = \nHint: Check whether function/procedure has been dropped/modified from another terminal or access privilege is modified. \ + \nTry refreshing after some time. + +MSG_HINT_GETSOURCE = \nHINT: Try refreshing after sometime. + +MSG_CLEAR_EDITOR_CONTENT_ON_ERROR = Error refreshing object opened in editor: Clearing editor contents + +MSG_GUI_OBJECT_MAY_DROPPED = Object may have been dropped. + +MSG_HINT_DATABASE_CRITICAL_ERROR = Critical error occurred in database session. Unable to proceed. Connect to the server again. + +ERR_MSG_OUT_OF_MEMORY_ERROR_OCCURRED = Out of memory error occurred. Connection will be closed. \ + \nHint: \n 1. Try increasing the heap memory size in configuration file. + +ERR_TITLE_DB_CRITICAL_ERROR = Database Critical Error + +ERR_QUERY_EXECUTION_FAILED = Update failed. No rows affected. Cancel changes, refresh the data and try again. + +ERR_ALREADY_CONNECTION_PROFILE_EXISTS = Another connection profile already exists for "{0}" + +ERR_DEFAULT_DATATYPE_NOT_FOUND = Default datatype {0} not found in pg_catalog. + +ERR_CONNECTION_INVALID_STATE = You cannot change the state from {0} to {1}. + +ERR_FILLFACTOR_LESS_THAN_10 = Fill factor cannot be less than 10. + +ERR_FILLFACTOR_MORE_THAN_100 = Fill factor cannot be more than 100. + +ERR_INDEX_NAME_EMPTY = Index name cannot be empty. + +ERR_EXECTION_IN_PROGRESS = {0} is in progress, try after some time. + +ERR_PARTITION_COLUMN_EMPTY = Create a partition column to proceed. + +ERR_PARTITION_NAME_EMPTY = Partition name cannot be empty. + +ERR_PARTITION_VALUE_EMPTY = Partition value cannot be empty. + +ERR_PARTITION_INTERVAL_COLUMN_TYPE = Interval partition column type should be time type. + +ERR_PARTITION_INTERVAL_VALUE_EMPTY = Partition interval value cannot be empty. + +ERR_DUPLICATE_PARTITION_NAME = Partition name already exists. Enter different name. + +ERR_PREFIX_DB_MESSAGE=Error: + +STATUS_MSG_CREATE_DATABASE = Creating Database... + +STATUS_MSG_DROP_DATABASE = Dropping Database... + +STATUS_MSG_UPDATE_DATABASE = Renaming Database... + +STATUS_MSG_CONNECT_DATABASE = Connecting to Database... + +STATUS_MSG_CREATE_INDEX = Creating Index... + +STATUS_MSG_CREATE_SCHEMA = Creating Schema... + +STATUS_MSG_CREATE_TABLE = Creating Table... + +STATUS_MSG_DISCONNECT_ALL_DB = Disconnecting all DBs... + +STATUS_MSG_DROP_DEBUG_OBJECT = Dropping Function... + +STATUS_MSG_DROP_SCHEMA = Dropping Schema... + +STATUS_MSG_RENAME_SCHEMA = Renaming Schema... + +STATUS_MSG_ADD_COLUMN = Adding Column... + +STATUS_MSG_ADD_CONSTRAINT = Adding Constraint... + +STATUS_MSG_SET_COLUMN_DEFAULT_VALUE = Setting Default Value... + +STATUS_MSG_ANALYSE_TABLE = Analyzing Table... + +STATUS_MSG_CHANGE_DATATYPE = Changing Data type... + +STATUS_MSG_CHANGE_FILLFACTOR = Changing Fill Factor... + +STATUS_MSG_CHANGE_INDEX_TBLSPACE = Changing Index Tablespace... + +STATUS_MSG_DROP_COLUMN = Dropping Column... + +STATUS_MSG_DROP_CONSTRAINT = Dropping Constraint... + +STATUS_MSG_DROP_INDEX = Dropping Index... + +STATUS_MSG_DROP_TABLE = Dropping Table... + +STATUS_MSG_REINDEX_TABLE = Reindexing table... + +STATUS_MSG_RENAME_COLUMN = Renaming Column... + +STATUS_MSG_RENAME_CONSTRAINT = Renaming Constraint... + +STATUS_MSG_RENAME_INDEX = Renaming Index... + +STATUS_MSG_RENAME_TABLE = Renaming Table... + +STATUS_MSG_SET_COLUMN_NOTNULL = Setting Not Null... + +STATUS_MSG_SET_SCHEMA = Setting Schema... + +STATUS_MSG_STATUS=Executed Successfully... + +STATUS_MSG_SET_TBL_DESC = Setting Table Description... + +STATUS_MSG_SET_TBLSPACE = Setting Tablespace... + +STATUS_MSG_TRUNCATE_TABLE = Truncating Table... + +STATUS_MSG_VACUUM_TABLE = Vacuuming Table... + +STATUS_MSG_VALIDATE_CONSTRAINT = Validating Constraint... + +STATUS_MSG_AUTO_SUGGEST = Loading Auto Suggestion + +ERR_MSG_NO_OTHER_CONNECTION = No other connection available. + +ERR_RENAME_NEED_ANOTHER_CON = No other database connection available. Renaming a database require another active connection. + +ERR_NO_CONNECTION_AVAILABLE = No connection is available. At least one connection is required. + +ERR_DUPLICATE_INDEX_NAME = Index name already exists. Enter different name. + +ERR_INDEX_COLS_EMPTY = Select at least one column. + +COPYRIGHT_MSG_HUAWEI = Copyright \u00a9 2016-2020 Huawei Technologies Co. Ltd. +RIGHTS_RESERVRED_MSG_HUAWEI = All Rights Reserved. +ABOUT_DATA_STUDIO_MSG= About Data Studio +VERSION_NO_MSG=Version: +JAVA_VERSION_NO_MSG=Java Version: +JAVA_HOME_MSG=Java Home: +JAVA_HOME_NOT_SET=Environment not set. Please refer to User Manual for instructions. +WEB_HUAWEI_LINK=http://www.huawei.com + +BREAKPOINT_WINDOW_ERROR_MSG_HEADING=PLSQL Unknown Error +BREAKPOINT_WINDOW_ERROR_MSG=An unknown internal error occurred. Contact Data Studio support team with log file. + +CONSOLE_WINDOW_ERROR_MSG= Error occurred while trimming initial messages log messages. +CONSOLE_WINDOW_ERROR_SCROLLING_MSG=Error occurred while scrolling to last of messages window content. + CONSOLE_WINDOW_MEMORY_MSG= Current memory usage is: + CONSOLE_WINDOW_LINE_NUMBER_MSG=number of lines: + CONSOLE_WINDOW_OFFSET_MSG = offset: + CONSOLE_WINDOW_LENGTH_MSG = length: + +EXECDIALOG_PARAMETER_VALUE=Enter the parameter values. +EXECDIALOG_EXEC_PL_SQL=Execute Function/Procedure + +EXECDIALOG_PARAMETER=Parameter +EXECDIALOG_TYPE=Type +EXECDIALOG_DATATYPE=Data type +EXECDIALOG_VALUE=Value +EXECDIALOG_HINT= HINT: + +OBJECT_BROWSER_LABEL_MSG=Unknown Type + + LABEL_VIEW_SOURCE=View Source + +PL_SOURCE_EDITOR_AT= at # {0} + +ANALYSE_TABLE_ERROR_MSG=Error while analyzing + +ANALYZING_TABLE= Analyze Table + +CHANGE_INDEX_FILLFACTOR_NEW=Select new fill factor to for {0} index: +CHANGE_INDEX_FILLFACTOR_MIN=Fill factor cannot be less than 10. +CHANGE_INDEX_FILLFACTOR_MAX=Fill factor cannot be more than 100. +CHANGE_INDEX_FILLFACTOR_FOR=Change fill factor for {0} index, processing... + +CHANGE_INDEX_FILLFACTOR_CONN_ERROR=Connection error during changing fill factor for {0} index: {1} Error: {2} + +CHANGE_INDEX_FILLFACTOR_CHANGED=Changed index fill factor to: {0} + +CHANGE_INDEX_FILLFACTOR_TITLE=Change Fill Factor +CHANGE_INDEX_FILLFACTOR_SELECT=Select the fill factor for {0} index: + +CHANGE_INDEX_TABLESPACE_NEW=Select new tablespace for {0} index: +CHANGE_INDEX_TABLESPACE_FOR=Change tablespace for {0} index, processing... +CHANGE_INDEX_TABLESPACE_CONN_ERROR=Connection error during changing tablespace for {0} index.: {1} Error: {2} +CHANGE_INDEX_TABLESPACE_TO=Updated index tablespace: {0} to {1} +CHANGE_INDEX_TABLESPACE_TITLE= Change Tablespace +CHANGE_INDEX_TABLESPACE_SELECT= Select tablespace for {0}: + +DROP_COLUMN_DIA_TITLE=Drop Column +DROP_COLUMN_DIA_MSG=Are you sure you want to drop {0} column from {1}.{2} Table? + +DROP_COLUMN_ERROR=Error when dropping column +DROP_COLUMN_UNABLE_MSG=Error dropping column: {0}.{1}.{2} +DROP_COLUMN_UNABLE=Unable to drop {0} column from {1}.{2} table. Server Message: {3} +DROP_COLUMN_SUCCESS=Dropped column: {0}.{1}.{2} + +DROP_CONSTRAINT_DIA_TITLE=Drop Constraint +DROP_CONSTRAINT_FROM=Are you sure you want to drop {0} constraint from {1}.{2} table? +DROP_CONSTRAINT_DROPPING=Dropped constraint {0}.{1}.{2} +DROP_CONSTRAINT_ERROR=Error when dropping constraint +DROP_CONSTRAINT_UNABLE_TO_DROP=Error dropping constraint: {0}.{1}.{2} + +DROP_INDEX_DIA_TITLE=Drop Index +DROP_INDEX=Are you sure you want to drop {0} index? +DROP_INDEX_SUCCESS=Dropped index: {0}.{1} +DROP_INDEX_ERROR_TITLE=Drop Index Error +DROP_INDEX_ERROR_MSG=Error dropping index: {0}.{1}.{2} + +DROP_INDEX_CONN_FAIL=Error dropping index: {0}.{1}.{2}: Connection issue + +DROP_TABLE_DIA_TITLE=Drop Table +DROP_TABLE=Are you sure you want to drop {0}.{1} table? +DROP_TABLE_SUCCESS=Dropped table: {0}.{1} +DROP_TABLE_ERROR=Error when dropping table +DROP_TABLE_UNABLE=Unable to drop table. {0} Server message: {1} +DROP_TABLE_UNABLE_MSG=Error dropping table: {0}.{1} + +REINDEX_TABLE=Reindexed table: {0}.{1} + +REINDEX_TABLE_ERROR=Error while reindexing {0}.{1} table. Server Message:{2} +REINDEX_TABLE_CONN_ERROR=Connection error while reindexing {0}.{1} table. Server Message: {2} +REINDEX_TABLE_TITLE= Reindex Table + +RENAME_COLUMN={0} column in {1}.{2} table +RENAME_COLUMN_NEW=Enter new name for {0} + +RENAME_COLUMN_ERROR=Error while renaming {0}.{1} Error:{2} +RENAME_COLUMN_CONN_ERROR=Connection error during renaming column. {0} Error: {1} + +RENAME_COLUMN_RENAMED=Renamed {0} to {1} column in {2}.{3} table + +RENAME_COLUMN_TITLE=Rename Column +RENAME_COLUMN_NEW_NAME=Enter new name for {0} column in table {1}.{2} + +RENAME_CONSTRAINT=constraint +RENAME_CONSTRAINT_NEW_NAME=Enter new name for {0} constraint +RENAME_CONSTRAINT_CONN_ERROR=Connection error during renaming constraint. {0} Error: {1} + +RENAME_CONSTRAINT_TITLE=Rename Constraint +RENAME_CONSTRAINT_WAIT=Renaming {0} constraint, processing... +RENAME_CONSTRAINT_ERROR=Error while renaming {0}.{1} Error:{2} +RENAME_CONSTRAINT_RENAMED=Renamed constraint: {0} to {1} + +RENAME_INDEX_NEW_NAME=Enter new name for {0} index +RENAME_INDEX_WAIT=Renaming {0} index, processing... +RENAME_INDEX_ERROR=Error while renaming {0}.{1} Error: {2} +RENAME_INDEX_CONN_ERROR=Connection error during renaming index. {0} Error: {1} +RENAME_INDEX_TITLE=Rename Index +RENAME_INDEX_RENAMED=Renamed index:{0} to {1}. +RENAME_INDEX_NEW=Enter the new name for {0} index + +RENAME_TABLE_NEW_NAME=Enter new name for {0} table +RENAME_TABLE_WAIT=Renaming {0} table, processing... +RENAME_TABLE_ERROR=Error while renaming {0}.{1} Error: {2} +RENAME_TABLE_CONN_ERROR=Connection error during renaming table. {0} Error: {1} +RENAME_TABLE_TO= Renamed table: {0} to {1}.{2} +RENAME_TABLE_NEW=Enter new name for {0} regular table in schema +RENAME_TABLE_TITLE=Rename Table + +RENAME_TRIGGER_WAIT=Rename {0} trigger, processing... + +SET_COLUMN_TOGGLE_TITLE=Toggle Not Null Property +SET_COLUMN_TOGGLE_MSG=Are you sure you want to toggle NOT NULL property of {0} column? +SET_COLUMN=column +SET_COLUMN_ERROR=Error while Toggling NOT NULL property +SET_COLUMN_UNABLE=Unable to toggle NOT NULL property. {0} Server message: {1} + +SET_COLUMN_NOT_NULL_SUCCESSFUL=Toggled NOT NULL for column: {0}.{1}.{2} + +SET_SCEMA_SELECT=Select new Schema for {0} table +SET_SCEMA_MOVING=Moving {0} table, to {1} Schema processing... + +SET_SCEMA_ERROR=Error while moving table {0} to {1} schema.{2}{3} +SET_SCEMA=schema. +SET_SCEMA_CONN_ERROR=Connection error during renaming table.{0}Error: {1} +SET_SCEMA_MOVED=Moved table: {0}.{1} to {2}.{1} + +SET_SCEMA_TITLE=Set Schema + +SET_SCEMA_SELECT_NEW=Select a new schema name for table {1}.{0} +SET_TABLE_NEW_DESC=Enter new description for the table {0}.{1} +SET_TABLE_UPDATE_DESC=Updating the table description for {0}.{1} table, processing... + +SET_TABLE_UPDATE_ERROR=Error while updating the description.{0} Error:{1} +SET_TABLE_CONN_ERROR=Connection error during table description updation.{0} Error:{1} +SET_TABLE_DESC_SUCCES=Description Updated: {0}.{1} table + +SET_TABLE_DESC_TITLE=Update Table Description +SET_TABLE_NEW_DESC_FOR=Enter new description for table {0}.{1} + +SET_TABLESPACE_NEW=Select new tablespace for {0} table +SET_TABLESPACE_FROM_CURRENT=Moving {0} table from current tablespace {1} to {2} tablespace processing... +SET_TABLESPACE_FROM_CURRENT_NULL=Moving {0} table to {1} tablespace, please wait... + +SET_TABLESPACE_ERROR=Error while moving table {0} from tablespace {1} to {2} tablespace.{3}{4} +SET_TABLESPACE_ERROR_NULL= Error while moving table {0} to {1} tablespace.{2}{3} +SET_TABLESPACE_CONN_ERROR=Connection error during renaming table. {0} Error: {1} +SET_TABLESPACE_FROM=from tablespace +SET_TABLESPACE=tablespace. + +SET_TABLE_FROM_TABLESPACE=Moved table: {0} from {1} to {2} +SET_TABLE_FROM_TABLESPACE_NULL = Moved tablespace: table {0} moved from {1} to {2} +SET_TABLESPACE_TITLE=Set Tablespace +SET_TABLESPACE_IN=Select a new tablespace for table {0}.{1} + +TRUNCATE_TABLE_TITLE=Truncate Table +TRUNCATE_TABLE_MSG=Are you sure you want to truncate {0}.{1} table? +TRUNCATE_TABLE_TRUNCATED=Truncated table: {0}.{1} +TRUNCATE_TABLE_ERROR=Error truncating table: {0}.{1} +TRUNCATE_TABLE_CONN_ERROR=Error while truncating {0}.{1} table. Server Message: {2} + +VACCUM_TABLE_SUCCESS=Vacuumed table: {0}.{1} +VACCUME_TABLE_ERROR=Error vacuuming table: {0}.{1} +VACCUME_TABLE_CONN_ERROR=Connection error while vacuuming {0}.{1} table. Server Message: {2} +VACCUME_TABLE_TITLE= Vacuum Table + +VALIDATE_CONSTRAINT_SUCCESS=Validated constraint: {0}.{1}.{2} +VALIDATE_CONSTRAINT_ERROR=Error while validating constraint +VALIDATE_CONSTRAINT_UNABLE=Error validating constraint: {0}.{1}.{2} + +VIEW_TABALE_DATA_ERROR=View Data Error +VIEW_TABALE_DATA_UNABLE=An error occurred while fetching data. +VIEW_TABALE_DATA_UNABLE_VIEW=Error viewing table data: {0}.{1} +UNABLE_TO_ADD_COL = Unable to add column. {0}Server message:{1} + +EXEC_PLAN_TITLE=Execution Plan + +EXEC_PLAN_PARSE_FAIL=Explain Plan Query Parse Failed + +EXEC_PLAN_TEXT=Text + +EXEC_PLAN_OK=OK + +EXEC_PLAN_FAIL_MSG=Execution failed.{0}Error code:[{1}]{2} + +FIND_REPLACE_TITLE=Find and Replace +FIND_REPLCAE_WHAT=F&ind what: +FIND_REPLACE_WITH=Rep&lace with: +FIND_REPLACE_BACK=&Backward search +FIND_REPLACE_MATCH=Match &case +FIND_REPLACE_WHOLE=Whole &word only +FIND_REPLACE_WRAP=Wra&p around +FIND_REPLACE_NEXT=Find &Next +FIND_REPLACE=&Find && Replace +FIND_REPLACE_ALL=Replace &All + +FIND_REPLACE_SEARCH_NOT_FOUND=Search Text Not Found + +PL_SOURCE_VIEWER_ERROR=Source Viewer Error +PL_SOURCE_VIEWER_UNABLE=Unable to find source viewer. +PL_SOURCE_CODE_ERROR=Source code error +PL_SOURCE_DISPLAY_ERROR=Unable to display PLSQL source code for the selected object. + +PROPERTIES_WID_PROPERTY=Property +PROPERTIES_WID_VALUE=Value + +RESULT_WINDOW_REFRESH=Refresh in progress + +COLUMN_OLD_NAME ={0} column in {1}.{2} table + +SQL_TERMINAL_CONN=Connection: +SQL_TERMINAL_CONNS= -- Connections -- + +#Default Schema +DEFAULT_SCHEMA_INITIAL_MSG= --Default Schema-- +DEFAULT_SCHEMA_ERROR_TITLE = Search path error +DEFAULT_SCHEMA_ERROR_MSG = Error while setting/fetching search path + +#Block root user in linux +USER_ROOT_ERROR_TITLE = Forbidden user error. +USER_ROOT_ERROR_MSG = Cannot launch application as ROOT, login as other user. + +MPPDBIDE_DIA_BTN_YES=Yes +MPPDBIDE_DIA_BTN_NO=No +MPPDBIDE_DIA_BTN_CANC=Cancel +MPPDBIDE_DIA_BTN_DISCARD=Discard Changes + +MPPDB_IDE_MOM_MAX=Data Studio Maximum Memory: + +UI_DISPLAY_PERFORMING=Performing {0}... + +DB_CONN_DIA_TITLE=New Database Connection +DB_CONN_DIA_MSG=Provide connection parameters +DB_CONN_DIA_HELP=Help +DB_CONN_DIA_TO_SERVER=Connecting to server +DB_CONN_DIA_CONN_NAME=Connection Name* +DB_CONN_DIA_HOST=Host* +DB_CONN_DIA_HOST_PORT=Host Port* +DB_CONN_DIA_MAX_VALUE=Max Value +DB_CONN_DIA_DB_NAME_OLAP=Database Name* +DB_CONN_REM_PSW=Remember Password +DB_CONN_DIA_USER_NAME=User Name* +DB_CONN_DIA_PSW=Password* +DB_CONN_DIA_SSL=SSL +DB_CONN_DIA_ENABLE_SSL=Enable SSL + +DB_CONN_DIA_T=T + +DB_CONN_DIA_SSL_PROPERTY=SSL property already set. +DB_CONN_DIA_INVALID_SERVER_IP_TITLE=Invalid Server IP +DB_CONN_DIA_INVALID_SERVER_IP_MSG=Server IP address is invalid. Enter valid IP address. +DB_CONN_DIA_VALID_STATUS=Server IP Validation Status:{0} +DB_CONN_DIA_CONN_PROFILE=Connection profile connected: {0} +CREATE_SCHEMA_SUCCESS=Created schema: {0}.{1} +OBJECT_ITEM_REFRESHED=refreshed +REMOVE_SERVER=Server + +ADD_NEW_COLUMN=Add New Column + +DB_CONN_DIA_MOM_USAGE=Memory Usage +DB_CONN_DIA_MOM_USAGE_MSG=Memory usage reached 90%. Close unused components. +DB_CONN_DIA_GAUSS_SERVER_ERROR=Error connecting to server. +DB_CONN_DIA_REASON=Reason: +DB_CONN_DIA_GUI_ERROR_MSG=GUI: Connecting to server failed. +DB_CONN_DIA_CONN_PROFILE_ERROR=Error creating connection profile. +DB_CONN_DIA_FUN_TRI_PROC=Function/Procedure +DB_CONN_DIA_UPDATE_OBJ_BROW_ERROR=Error while updating Object Browser. + +USER_INPUT_PSW_DIA_MSG= Connect to the DB + +INDEX_UI_NAME=Index Name +INDEX_UI_MSG=Select index columns +INDEX_UI_UNIQUE_INDEX=Unique Index +INDEX_UI_FILLFACTOR=Fill Factor +INDEX_UI_PARTIAL_INDEX=Partial Index: WHERE Expression +INDEX_UI_USER_EXPRESSION=User Defined Expression +INDEX_UI_OR= (OR) +INDEX_UI_AVA_COLUMNS=Available Columns +INDEX_UI_INDEX_CLMS=Index Columns +INDEX_UI_ADD_TO=Add to Index +INDEX_UI_REMOVE=Remove from index +INDEX_UI_MOVE_UP=Move Up +INDEX_UI_MOVE_DOWN=Move Down +INDEX_UI_TYPE=Index Type +INDEX_UI_ACCESS_METHOD=Access Method +INDEX_UI_TABLESPACE=Tablespace + +DATA_DIST_UI_HAST_FUN=HASH Function Options + +DATA_DIST_UI_DEFAULT_DIST=DEFAULT DISTRIBUTION +DATA_DIST_UI_DIST_TYPE=Distribution Type + +DATA_DIST_UI_AVAI_CLMS=Available Columns +DATA_DIST_UI_NEW_FUN=New Button +DATA_DIST_UI_HASH_CLMNS=HASH Columns + +COL_NAME = Column Name +CREATE_NEW_TABLE=Create Regular Table +CREATE_TABLE_CLM_NAME=Column Name +CREATE_TABLE_DATA_TYPE=Data Type +CREATE_TABLE_CONSTRAINT=Constraints +ARRAY_DIMENSIONS = Array Dimensions +CREATE_TABLE_ADD=Add +CREATE_TABLE_EDIT=Edit +CREATE_TABLE_DELETE=Delete + +CREATE_TABLE_GENERAL=General +CREATE_TABLE_COLUMNS=Columns + +CREATE_TABLE_INDEXES=Indexes + +CREATE_TABLE_SQL_PREVIEW=SQL Preview +CREATE_TABLE_EDIT_MSG= Select at least one column from the table to edit. +CREATE_TABLE_DELETE_MSG= Select at least one column from the table to delete. +CREATE_TABLE_CONSTRAINT_MSG= Select columns for constraint or check for duplicate name. +CREATE_TABLE_CONST_EDIT_MSG= Select at least one constraint from the table to edit. +CREATE_TABLE_CONST_DELETE= Select at least one constraint from the table to delete. +CREATE_TABLE_VALID_NAME= Enter valid column name. +CREATE_TABLE_COLUMN_EXISTS = Column {0} already exists. +CREATE_TABLE_NO_CLM_MSG= No column selected or there are no more rows available to move. +CREATE_TABLE_FINISH_BTN=Finish +CREATE_TABLE_NEXT_BTN=Next +CREATE_TABLE_BACK_BTN=Back +CREATE_TABLE_ENTER_TABLE_NM=Enter table name +CREATE_TABLE_CREATE_SUCCESS=Created table: {0} +CREATE_TABLE_CREATE_ERROR=Error creating table: {0} +CREATE_TABLE_SCEMA=Schema +CREATE_TABLE_TABLE_NAME=Table Name +CREATE_TABLE_CASE=Case +CREATE_TABLE_NORMAL=Normal +CREATE_TABLE_UNLOGGED=UNLOGGED +CREATE_TABLE_TEMPORARY = Temporary +CREATE_TABLE_TYPE=Table Type +CREATE_TABLE_OPTIONS=Options +CREATE_TABLE_NOT_EXISTS=IF NOT EXISTS +CREATE_TABLE_OIDS=WITH OIDS +CREATE_TABLE_FILL_FACTOR=Fill Factor + +CREATE_TABLE_DESC=Description of Table +CREATE_TABLE_INDEX_DEF=Index Definition +CREATE_TABLE_CLM_DELETE=Select at least one index from the table to delete +CREATE_TABLE_CLM_EDIT=Select at least one index from the table to edit + +CREATE_TABLE_PARTITION_DELETE=Select at least one partition from the table to delete +CREATE_TABLE_PARTITION_EDIT=Select at least one partition from the table to edit +CREATE_TABLE_NO_PARTITION_MSG=No partition selected or no more rows available to move. + +ENTER_NEW_NAME_FOR = Enter the new name for {0} schema. +RENAME_SCHEMA = Rename Schema +DB_RENAME_RENAMED = Renamed schema: {0} to {1} +CONNECTION_ERR_DURING_REMANING = Connection error during renaming {0} schema.{1} {2} +RENAMING_SCHEMA = Renaming the schema, processing... +NEW_NAME_FOR_SCHEMA_TO_CONTINUE = Enter a new name for the schema to continue... + +DB_RENAME_RENAMING = Renaming {0} schema failed.{1}{2} + +CHECK_COLUMN_UI =CHECK + +ENTER_NEW_NAME_FOR_DB = Enter new name for {0} database. +DB_RENAME_RENAMING_DATABASE = Renaming {0} database, processing... +DB_RENAME_RENAMED_DATABASE = Renamed database: {0} to {1} +RENAME_DATABASE = Rename Database +DATABASE_RENAME_CONFIRMATION = Database will be disconnected in order to rename it. Are you sure you want to rename the database? + +UNABLE_TO_CONNECT_TO_DATABASE = Unable to connect database ''{0}''.{1}Message:{2}{3} + +ERR_WHILE_RENAMING_DATABASE = Error while renaming {0}{1} + +REMOVE_SEVER = Remove Connection Confirmation +REMOVE_SERVER_CONFIRMATION = All the databases will be disconnected before removing the connection.{0}Are you sure you want to remove ''{1}'' server? \ + \n\ + \n\ + Note: Disconnecting DB may cancel all ongoing database operations.\ +SERVER_REMOVED = Removed server: {0} +DISCONN_IN_PROGRESS = Disconnect is in progress + +REFRESH_IN_PROGRESS = Refresh is in progress +MEMORY_USAGE = Memory Usage +MEMORY_USAGE_WARNING = Memory usage reached 90%. Close unused components. +ERR_WHILE_REFRESHING =Error refreshing + +EXCEPTION_OCCURED_WHILE_FETCHING_OBJECTS = Exception occurred while fetching Database objects. +PLSQL_ERR = PLSQL Unknown Error +UNKNOWN_INTERNAL_ERR = An unknown internal error occurred. Contact Data Studio support team with log file information. +ERR_DURING_REFRESHING = Error refreshing object: {0} + +PROP_HANDLER_PROPERTIES_ERROR = Properties Error +PROP_HANDLER_PROPERTIES = {0} Properties +PROPERTIES_WARNING = Error while fetching properties. Error:{0} + +HLP_DOC_NOT_EXIST = Help Document Does Not Exist +UNABLE_TO_FIND_HLP_DOC = Unable to find help document. + +ROWS_AFFECTED = Rows Affected: {0} + +DISPLAY_SOURCE_CODE_FAILED = Display source code failed +ERR_OCCURED_WHILE_DISPLAYING_CODE = An error occurred while displaying source in Source Viewer +FETCHING_SOURCE_CODE_FAILED =Error fetching source code: {0} +HANDLER_UTILITIES_CANNOT = Cannot {0} Function/Procedure +HANDLER_UTILITIES_CANNOT_PERFORM = Cannot {0} function/procedure as unsupported data type exists in parameter list ({1}). + +ERR_GUI_SOURCE_NOT_AVAILABLE_HANDLER =Source not available for: {0} + +FILE_OVERWRITE = File Overwrite Confirmation + +COULD_NOT_SET_READABLE = Could not set readable/writable flag for the exported file. +EXPORT_TABLE = Table ''{0}'' data successfully exported. +ERR_EXPORT_TABLE_TO_CSV_HANDLER = Error while exporting table data.{0}Error:{1} +ERR_SAVE_SQL_HANDLER=Error saving SQL file: {0}. +DATA_EXPORTED_TO = Data successfully exported to ''{0}'' file. + +EXIT_APPLICATION = Exit Application + +EXIT_APPLICATION_CONFIRMATION = Are you sure you want to exit application? \ +\nNote: \ +\n Force Exit: Exit without saving unsaved SQL history. \ +\n Graceful Exit: Exit after saving unsaved SQL History \ +\n and queries/functions/procedures. \ +\n\ +\n All other unsaved data will be lost. + +GRACEFULL_EXIT_DATASTUDIO = Graceful Exit +FORCE_EXIT_DATSTUDIO = Force Exit + +DATABASE_CONNECTION_ERR = Database Connection Error + +ERR_QUERY_LENGTH_TOO_BIG = Query is too big to handle + +OPERATION_CANNOT_BE_PERFOREMD = Operation cannot be performed. Failed with error:{0} +ERR_WHILE_STARTING_EXECUTE_SQL = Error while starting execute sql object from Object Browser. +SOURCE_CODE_CHANGE = Source Code Change +SOURCE_HAS_BEEN_CHANGED = Source code has been changed. Are you sure you want to compile and execute? +EXECUTION_FAILED_ITEM = Execution failed.{0} Error Code:[{1}]{2} + +ERR_WHILE_STARTING_TO_EXECUTE_SQL_OBJECT = Error while starting to execute SQL object from Source Viewer. + +DROP_SCHEMA = Drop Schema +DROP_SCHEMA_CONFIRMATION = Are you sure you want to drop ''{0}'' schema? +DB_DROPPED = Dropped schema: {0}.{1} +DROP_SUCCESS = Schema dropped successfully. +ERR_WHILE_DROPPING_SCHEMS = Error while dropping ''{0}'' schema. Server Message:{1} +ERR_WHILE_DROPPING_SCHEMS_MESSAGE = Error while dropping ''{0}'' schema.{1} Server Message:{2} + +ERR_WHEN_DROPPING_SCHEMA = Error when dropping schema +SERVER_MSG = Server Message: +CONNECTION_ERR_WHEN_DROPPING_SCHEMA = Connection error while dropping ''{0}'' schema. Server Message:{1} + +DROP_FUNC_PROC = Drop Function/Procedure +DROP_FUNC_PROC_CONFIRMATION = Are you sure you want to drop ''{0}'' Function/Procedure? +FUNC_PROC_DROPPED = Function/Procedure ''{0}'' successfully dropped. + +ERR_DROP_FUNC_PROC = Error while dropping Function/Procedure. +EXECUTION_FAILED = Execution failed.{0} Error code: [{1}]{2} + +ADD_MSG =Add +EDIT_MSG =Edit +DELETE_MSG=Delete +UP_MSG =Up +DOWN_MSG=Down +UPDATE_MSG=Update +CANCEL_MSG=Cancel + +DROP_DATABASE = Drop Database +DROP_DATABASE_ALERT = Database will be disconnected before dropping it.{0}Are you sure you want to drop ''{1}'' database? +DB_DROPPED_DATABASE = Dropped database: {0}.{1} + +DATABASE_SUCCESSFULLY = Created database: {0}.{1} +ERR_WHEN_DROPPING_DB = Error when dropping database +UNABLE_TO_DROP_DB = Error dropping database: {0}.{1} + +UNABLE_TO_DROP = Unable to drop ''{0}''database. Server Message:{1} + +ERROR_DURING_SCHEMA_CREATION = Error creating schema.{0}.{1} + +DATABASE_DISCONNECT = Disconnect Confirmation +DISCONNECT_CONFIRMATION = Are you sure you want to disconnect ''{0}''? \ + \n\ + \n\ + Note: Disconnecting DB may cancel all ongoing database operations.\ + + +DISCONNECTED_FROM_SERVER = Disconnected database: {0}.{1} + +DISCONNECT_ALL_DB = Disconnected all DBs in connection: {0} + +ENTER_SCHEMA_NAME_TO_CONTINUE = Enter schema name to continue... +STATUS_CREATING_SCHEMA = Creating new schema, processing... +ERROR_WHILE_CREATING_SCHEMA = Error while creating schema.{0}{1} +CONNECTION_ERROR_DURING_SCHEMA_CREATION = Connection error during schema creation.{0}{1} + +CREATE_SCHEMA = Create Schema +ENTER_SCHMEA_NAME = Enter schema name + +ENTER_DATABASE_NAME_TO_CREATE = Enter the database name to create +CREATING_DATABASE = Creating database, processing... +ERROR_WHILE_CREATING_DATABASE = Error while creating database.{0}{1} + +NAME_OF_THE_DATABASE = Name of the database +CURRENT_USER_CIPHER_TO_CONNECT_TO_DB = Current user's password to connect to DB + +SUCCESSFULLY_CONNECTED_TO = Connected to database: {0}.{1} +CONNECTION_ERR = Connection Error +LOADING_OBJECT_INTO_BROWSER = Loading database objects +OBJECT_SUCCESSFULLY_LOADED = Database objects loaded +ENTRE_CIPHER = Enter Password +ENTER_CURRENT_USER_CIPHER = Enter current user's password: + +LOGIN_TIMEOUT_CHECKED_FAILED = Login Timeout Check Failed +TIMEOUT_VALUE_CHECK_FAILED = Data Studio login timeout value check failed. +ENTER_VALID_TIMEOUT_VALUE = Enter valid timeout value in configuration file to proceed. + +DS_DEFAULT_ENCODING = Invalid encoding {0}. Setting to default (UTF-8) +JDK_VERSION_CHECK_FAILED = JDK version check failed +IDE_JDK_VERSION_CHECK_FAILED = Data Studio jdk version check failed. +ENTER_VALID_JDK_VERSION = Enter valid jdk version to proceed. + +DS_DEFAULT_CONSOLE_LINE_COUNT = Invalid ConsoleLineCount configuration. Setting to minimum ConsoleLineCount (1000). + +DS_INVALID_ENABLE_SECURITY_WARNING = The specified value for enableSecurityWarning is invalid. Setting default value. + +EXE_TERMINAL_EXC_TIME_MSG= Execution time: {0} ms +EXE_TERMINAL_EXC_TIME_MSG_RESULT= Execution time: {0} +CREATE_DATABASE=Create Database + +UNABLE_TO_CONNECT_TO_DATABASE_DB = Unable to connect database \"{0}\".{1}Message:{2} +ADD_COLUMN = Created column: {0}.{1} +ERR_WHILE_ADDING_COL = Error Adding New Column +UNABLE_TO_ADD_COL = Unable to add column. {0}Server message:{1} +TABLE_ANALYZED = Analyzed table: {0}.{1} +TABLE_ANALYZED_ERROR = Error analyzing table: {0}.{1} +TABLE_ANALYZED_CONNECTION_ERROR = Error analyzing table: {0}.{1}: Connection error +ADD_NEW_CONSTRAINT =Add New Constraint +EDIT_CONSTRAINT = Edit Constraint +EDIT_CONSTRAINT_LABEL= Previous Expression: +ALTER_COLUMN_SHELL_TEXT=Set Default Value + +PLS_ENTER_COL_NAME = Enter column name. +PLS_SELECT_DATA_TYPE = Select Valid Data type. + +CREATE_INDEX=Create Index +CREATE_INDEX_SET_TEXT=dummy +CREATE_INDEX_GENERATE_QUERY=Generated Query: +CREATE_INDEX_PREVIEW=Preview Query +CREATE_INDEX_BTN=Create +CREATE_INDEX_SUCCESS=Created index: {0}.{1} + +CREATE_INDEX_ERROR=Error creating index: {0}.{1} +CREATE_INDEX_CONN_ERROR=Connection failed while creating index {0}. +UNABLE_TO_ADD_CONS = Unable to add new constraint.{0}Server message:{1} + +ERR_WHILE_STNG_COL_VAL = Error while setting column default value +PLS_ENTER_TABLE_FOR_CONS = Select columns for constraint. +CUURENT_DFLT_VAL = Current Default Value: {0} +CUURENT_DFLT_VALUE=Default Value: +CONSTRAINT_TYPE=Constraint Type +CONSTRAINT_NAME=Constraint Name +CONSTRAINT_DESC=Select at least one column for foreign key reference +CONSTRAINT_SELECTED_COLUMNS=Selected Columns +DATA_TYPE_CONVERSION_TIP = Based on implicit type conversion, so some type conversion may fail. +UPDATE_DATA_TYPE = Change Data Type +TYPE_DES = Type Description +CURRENT_DATA_TYPE = Current Data Type for {0}: {1} +CHANGE_DATA_TYPE_FOR_COL = Updated datatype for column: {0}.{1}.{2} + +ERR_CHANGE_DTYPE = Error - Change datatype +UNABLE_TO_CHANGE_DTYPE_OF = Error changing datatype for column: {0}.{1}.{2} + +SET_COL_VAL_OF_DEFAULT_TYPE=Set column default value: {0}.{1}.{2} +UNABLE_TO_SET_COL_VAL = Unable to set column default value.{0}Server message: {1} +DTYPE_SCHEMA = Data Type Schema +DATA_TYPE = Data Type +SIZE = Precision/Size +SCALE_MSG = Scale +COL_CONS = Column Constraints +DFLT_CLM_UI =DEFAULT +NOT_NULL = NOT NULL + +ON_DELETE = On Delete +REF_COL = Referenced Columns +UNIQUE_MSG = UNIQUE +CASE_MSG = Case +CONSTRAINT_AVAILABLE_COLUMNS=Available Columns +CONSTRAINT_NEW_BTN=New Button +CONSTRAINT_ON_TABLESPACE=On Tablespace +CONSTRAINT_DEFERABLE=DEFERRABLE +CONSTRAINT_INITIALLY_DEFERRED=INITIALLY DEFERRED +CONSTRAINT_FILL_FACTOR=Fill factor +CONSTRAINT_COLUMN_NAME=ColumnName +CONSTRAINT_DATA_TYPE=DataType + +AVL_COL = Available Columns +CONSTRAINT_EXPRESSION=Enter check constraint expression +CONSTRAINT_CHECK_EXPRESSION=Check Expression + +CONSTRAINT_FOREIGN_NAMESPACE =Namespace +CONSTRAINT_FOREIGE_TABLENAME =TableName +CONSTRAINT_FOREIGE_COLUMNNAME =ColumnName + +NEW_NONAME_CONSTRAINT_CREATED = New constraint added to table {0}.{1} +NEW_CONSTRAINT_CREATED = Created constraint: {0}.{1}.{2} +ERR_WHILE_ADDING_CONSTRAINT = Error while adding new constraint + +EXEC_DEBUG_DIALOG_OUT_PARA_MSG=For OUT parameters no value is passed. +EXECUTION_PLAN_DISPLAY=Execution Plan : +GENERAL_MSG=General +COLUMN_MSG=Columns +DATA_DIST=Data Distribution +TABLE_CONS=Table Constraints +INDEX_MSG=Indexes + +SQL_PREVIEW=SQL Preview +OID_MSG=OID +NAME_MSG=Name +ENCODING_MSG=Encoding +ALLOW_CON=Connection allowed +CONNECTION_LIMIT=Connection limit +DFLT_TBSPACE=Default tablespace +COLLECTION_MSG=Collation +CHAR_TYPE=Character type +TABLESPACE_MSG=Tablespace +IS_TEMP=Is Temporary Table +TYEP_MSG=Type +OWNER_MSG=Owner +PAGES_MSG=Pages +ROW_COUNT=Estimated Row Count +HAS_INDEX=Has Index +IS_SHARED=Is Shared + +OPTION_MSG=Options +DESC_MSG=Description + +GUI_PLSOURCEEDITORCORE_REMOVE_ANNOTATION = GUI: PLSourceEditorCore: Remove annotation. +GUI_PLSOURCEEDITORCORE_ADD_ANNOTATION = GUI: PLSourceEditorCore: Add annotation. +GUI_PLSOURCEEDITORCORE_SOURCE_EDITOR_CLEARED = GUI: PLSourceEditorCore: Source editor cleared. + +MOVING_TABLE_SELECTED_TABLESPACE_SUCCESFULL = Moving table to selected tablespace is successful: + +CLEARED_CONSOLE_CONTENTS = Cleared Messages contents +GUI_FORMATTING_SQL_QUERY_STATEMENTS_FROM_FORMAT_MENU = GUI: Formatting the Sql Query Statements from the Format menu +NEGATIVE_NUMBER = Negative number: {0} + +GUI_CREATE_FUNCTION = GUI: Create Function. +GUI_CREATE_PROCEDURE = GUI: Create Procedure. + +GUI_DROPDEBUGOBJECT_DROP_DEBUG_OBJECT = GUI: DropDebugObject: Drop debug object. +GUI_EXECUTEEDITORITEM_EXECUTE_CLICKED = GUI: ExecuteEditorItem: Execute clicked. +GUI_EXECUTEOBJECTBROWSERITEM_EXECUTE_OBJECT_BROWSER_CLICKED = GUI: ExecuteObjectBrowserItem: Execute object browser clicked. +GUI_EXECUTED_SQL_TERMINAL_STATEMENT = GUI: Executed sql terminal statement. +TIME_BY_TAKEN_APPLICATION_EXECUTE_QUERY = Time taken by the application to execute the query is {0} +GUI_EXITAPPLICATION_EXIT_CLICKED = GUI: ExitApplication: Exit clicked. +GUI_APPLICATION_EXITED = GUI: Application exited. + +LOCALE_CHANGE_CONFIG_FILE=/Data Studio.ini +LOCALE_CHANGE_CONFIG_ERR_TITLE= Configuration Error +LOCALE_CHANGE_CONFIG_ERR_MES= Unable to find Data Studio configuration file. +LOCALE_CHANGE_RD_WD_ERROR=Error reading/writing configuration file +LOCALE_CHANGE_APP_RESTART_TITLE=Restart Data Studio +LOCALE_CHANGE_APP_RESTART_MSG=All connections will be closed and any unsaved data will be lost. Do you want to restart now? +LOCALE_CHANGE_APP_RESTART_NOTE= Note : +LOCALE_CHANGE_APP_RESTART_NOTE_NO= No : Language will not be changed even after Data Studio restart. + +TYPE_ALIGN = Type Align + +FUNCTION_PROCEDURE_NAME = Functions/Procedures + +FOREIGN_TABLE_GROUP = Foreign Tables +PARTITION_TABLE_GROUP = Partition Tables +PARTITION_GROUP_NAME = Partitions + +TABLES_NAME = Regular Tables + +DATATYPE_NAME = Data types + +ACCESS_METHOD_NAME = Access Methods +COLUMNS_NAME = Columns +CONSTRAINTS_NAME = Constraints +INDEXES_NAME = Indexes +TITLE_IMPORT_TBL_DATA = Import Table Data + +MSG_IMPORT_SUCCESS = Imported data to table: {0}.{1} +MSG_TOTAL_ROWS_IMPORT = Total rows imported: {0} +ERR_IMPORT_TABLE_TO_CSV=Error while importing table data. +ERR_IMPORT_TABLE_TO_CSV_HANDLER = Error while importing table data.{0}{1} +STATUS_MSG_IMPORT_TABLE_DATA = Importing Table Data... + +BTN_OK = OK +BTN_CANCEL = Cancel +BTN_CLEAR = Clear + +MSG_DS__NO_DATA_ENCRYPT_DISCLAIMER = 1) Data Studio does not support data encryption. Sensitive information may be accessible to hackers.\n Action Required: Ensure that the file is saved in a secure location.\n + +MSG_DS__NO_DATA_ENCRYPT_DISCLAIMER_SECONDPART2 = 2) Data Studio will not set any permissions of the exported files.\n Action Required: Read/Write permissions of folders must be set by the user. +MSG_DO_NOT_SHOW_AGAIN = Do not show again. +TITLE_DISCLAIMER = Data Studio Security Warning +TITLE_OPEN_SQL = Open SQL +MSG_SELECT_SQL_FILE = Select SQL file only. +MSG_SELECT_FILE_DOES_NOT_EXIST = Selected file does not exist. Select correct file. +MSG_NEED_APPEND_OVERWRITE = Do you want to overwrite the SQL or append? +BTN_LABEL_APPEND = Append +BTN_LABEL_OVERWRITE = Overwrite +MSG_APPEND_OVERWRITE_SUCCESS =SQL {0} to SQL Terminal +ERR_OUT_OF_MEMORY_OCCURED = Out of memory: Increase heap memory size in configuration file +ERR_OUT_OF_MEMORY_SEARCH_OCCURED =Insufficient memory: Please increase the heap memory size (example: -Xmx2048m) in the configuration file \ + \n "Data Studio.ini" in the DS installation directory and restart the DS to take effect. +ERR_OUT_OF_MEMORY_REOCCURED = Unable to retain existing content. +TITLE_OUT_OF_MEMORY = Out Of Memory +TITLE_SAVE_SQL = Save SQL +MSG_SQL_SAVE_SUCCESS = SQL saved: {0} Time: {1} + +MSG_EXPORT_SUCC_FILE = Exported Current Page Result Data from :{0} tab +MSG_EXPORT_EXEC_SUCC_FILE = Exported data from {0} tab +TITLE_EXPORT_IN_PROGRESS = Export In Progress + +ERR_WHILE_EXPORTING = Error while exporting query data.\nError : +GUI_NEWDBCONNECTION_OPEN_CONNECTION_WIZARD=GUI: NewDbConnection: Open connection wizard. + +CIPHER_EXPIRE_CONFIRMATION = Password Expire Information +CIPHER_EXPIRED = The password has expired. Contact the administrator to change the password. +CIPHER_YET_TO_EXPIRE = {0} days left before password expired, please change the password. + +MSG_LOADED = loaded + +FILE_PERMISSION =File Permission +FILE_PERMISSION_ERROR = Setting file permission failed. + +ERR_SQL_FILE_READ = SQL File read error + +MSG_TOTAL_ROWS_EXPORT = Total rows exported: {0} +TITLE_EXPORT_DATA = Export Data + +INCORRECT_PATH = Incorrect Path +INCORRECT_PATH_MSG = The specified path is either incorrect or does not exist. Logs will be created at default location. + +ERR_GUI_DEBUG_CONNECTION_ERROR=Connection Error + +ERR_IO_ERROR_EXPORT = Error while writing data to file. +SQL_TERMINAL_EXEC=Compile/Execute Statement +IO_EXCEPTION_WHILE_EXPORT = IO Exception occurred while exporting. +EMPTY_PLSOURCE_TITEL=ERROR +EMPTY_PLSOURCE_VIEWER=Function or Procedure is not defined +NAMESPACE_RETRIVE_ERROR=Error while retrieving data in background for {0} namespace. +TABLE_RETRIVE_ERROR=Error while retrieving data in background for {0} table. + +SQL_QUREY_CANCEL_MSG=Canceled the query on user request. +SQL_QUERY_CANCEL_CANCELMSG=Error while Canceling Query. +SQL_QUERY_CANCELMSG_PROGRESS=Query submitted for cancellation. Refer the status bar for cancel progress. + +UI_CANCEL_QUERY_MSG=One or more queries after the canceled query are not executed +SQL_BUTTON_TOOL_TIP=Cancel Executing Query + +ERR_DS_SECURITY_ERROR=An error occurred while encrypting/decrypting data.\n +TITLE_DS_SECURITY= Data Studio Security Error +SECURITY_FAILURE_SUGGESTION=1. Delete the security folder from Data Studio folder -> UserData -> Profile -> security folder \n2. Restart Data Studio + +EDIT_DATA_WIZARD_TITLE=Edit Table Data Wizard + + + +CANCEL_OPERATION_TITLE= Cancel Operation +CANCEL_OPERATION_MSG= Are you sure you want to cancel the operation? + +CANCEL_EXPORT_SUCCES_DAILOG_TITLE=Data Exported Successfully +CANCEL_EXPORT_FAIL_DAILOG_TITLE=Data Export Failed +CANCEL_EXPORT_JOB_NAME=Exporting data: {0} +CANCEL_EXPORT_SUCCES_CONSOLE_MESSAGE=Canceled export +CANCEL_IMPORT_SUCCES_DAILOG_TITLE=Data Imported Successfully +CANCEL_IMPORT_FAIL_DAILOG_TITLE=Data Import failed +CANCEL_IMPORT_JOB_NAME=Importing data: {0} +CANCEL_IMPORT_SUCCES_CONSOLE_MESSAGE=Canceled Data Import on user request. +CANCEL_IMPORTEXPORT_CONSOLE= Cancel Operation +CANCEL_IMPORTEXPORT_CONSOLE_MSG= Are you sure you want to cancel the operation? + +CANCEL_EXPORT_CANCELMSG=Error exporting query. +CANCEL_IMPORT_CANCELMSG=Error importing query + +CANCEL_WINDOW_TITLE=Progress View +NO_PROPOSAL =No Proposal +AUTO_SUGGEST_LOADING=Loading... + +SQL_QUERY_EXECUTE=Executing Query in SQL Terminal: {0} +STATUS_JOB_SI=running job +STATUS_JOB=running jobs + +CANCEL_PROGRESS_TABLE_HEARDER=Progress + +DS_EXIT_CONFIRMATION_TITLE=Exit Confirmation + +ERROR_READING_DATA=Error while reading the row data + +DISCARD_CHANGES_TITLE =Confirm Discard Changes +SAVE_CHANGES_TITLE =Save/Discard changes +EXPORT_CHANGES_TITLE =Export Result Data + +COPY_ADVANCED_RESULT_WINDOW_CONTENTS=Advanced Copy (Ctrl+Shift+C) +COPY_RESULT_WINDOW_CONTENTS=Copy (Ctrl+C) + +RESULT_WINDOW_SQL_SEARCH_EXECUTE=Text Mode Searching is in progress:{0} +RESULT_WINDOW_SQL_REFRESH_EXECUTE=Text Mode Refreshing is in progress:{0} +RESULT_WINDOW_SQL_LOADING_EXECUTE=Text Mode Loading is in progress:{0} +RESULT_WINDOW_SQL_ENCODING_EXECUTE=Text Mode Encoding is in progress:{0} +RESULT_WINDOW_SHOW_GRID=Grid +RESULT_WINDOW_SHOW_TEXT=Text + +RESULT_WINDOW_TEXT_CELL_VALUE_DIALOG_TITLE=Column value: +RESULT_WINDOW_TEXT_CELL_INVISIBLE_VALUE_TITLE=Data length warning +RESULT_WINDOW_TEXT_CELL_INVISIBLE_VALUE_BODY=Data is too large to display.\ +\n DS has copied the data, please paste to another Editor to view it. +EXPORT_CSV_STAR =Export all data +EXPORT_CSV = Export current page data +EXPORT_EXEC = Export Execution Plan +CLEAR_CONSOLE = Clear + +MENU_OPEN = Open +MENU_SAVE = Save +MENU_SAVE_AS = Save As +MENU_FIND = Find and Replace + +INFO_MAX_SOURCE_VIEWER = Maximum number of tabs limit is reached. Close unused tabs and try. + +MAX_SOURCE_VIEWER = Maximum Number of Tabs + +TABLESPACES_NAME = Tablespaces +DATABASES_NAME = Databases +USER_NAMESPACE_NAME = Schemas +SYSTEM_NAMESPACE_NAME = Catalogs +STATUS_MSG_DROP_TABLESPACE =Dropping Tablespace... +DROP_TABLESPACE_DIA_TITLE =Drop Tablespace +DROP_TABLESPACE = Are you sure you want to drop ''{0}'' Tablespace? +ERR_WHEN_DROPPING_TABLESPACE =Error Dropping Tablespace +DROP_TABLESPACE_SUCCESS=Dropped tablespace: {0}.{1} + +ERR_WHILE_DROPPING_TABLESPACE_MESSAGE = Error dropping tablespace: {0}.{1} +CONNECTION_ERR_WHEN_DROPPING_TABLESPACE = Error dropping tablespace: {0}.{1}: Connection error +STATUS_MSG_CREATE_TABLESPACE =Creating Tablespace... +CREATE_TABLESPACE_DIA_TITILE = Create Tablespace +TABLESPACE_SUCCESSFULLY = Created tablespace: {0}.{1} +CREATING_TABLESPACE = Creating tablespace, processing... +CONNECTION_ERROR_DURING_TABLESPACE_CREATION = Connection error during tablespace creation.{0}{1} +ERROR_WHILE_CREATING_TABLESPACE = Error while creating tablespace.{0}{1} +STATUS_MSG_RENAME_TABLESPACE = Renaming Tablespace... +RENAME_TABLESPACE_NEW_NAME=Enter new name for {0} tablespace +RENAME_TABLESPACE_WAIT=Renaming {0} table, processing... +RENAME_TABLESPACE_DIA_TITILE = Rename Tablespace +RENAME_TABLESPACE_NEW=Enter new name for {0} tablespace +RENAME_TABLESPACE_TO= Renamed tablespace: {0} to {1}.{2} +CONNECTION_ERR_DURING_RENAMING_TABLESPACE = Connection error during renaming tablespace.{0} Error:{1} +ERR_WHILE_RENAMING_TABLESPACE = Error while renaming {0}.{1} Error: {2} +SET_TABLESPACE_OPTION = Set Tablespace Option +SET_TABLESPACE_OPTION_SUCCESS = Updated tablespace options for: {0}.{1} +SET_TABLESPACE_OPTION_ERROR= Error setting options for tablespace: {0}.{1} +STATUS_MSG_OPTION_TABLESPACE = Setting Tablespace option... +CONNECTION_ERR_DURING_SETTING_TABLESPACE_OPTION = Error setting tablespace option: {0}.{1}: Connection error +STATUS_MSG_RESIZE_TABLESPACE = Resizing Tablespace... +SET_MAX_SIZE = Set Tablespace Maxsize +RESIZE_TABLESPACE_NEW_NAME =Enter new Max Size for ''{0}'' tablespace. +RESIZE_TABLESPACE_SUCCESS =Updated Maxsize to {0} for tablespace: {1} +SET_TABLESPACE_RESIZING_ERROR= Error resizing maxsize for tablespace: {0}.{1} + +PREF_SYNTAX_COLORING_TITLE=Syntax Coloring +PREF_SYNTAX_COLORING_MSG=Syntax coloring selection: +PREF_SYNTAX_COLORING_SINGLE_LINE_COMM=Comment Lines +PREF_SYNTAX_COLORING_DEFAULT=Default +PREF_SYNTAX_COLORING_UNRESERVED_KEY=Unreserved Keyword +PREF_SYNTAX_COLORING_RESERVED_KEY=Reserved Keyword +PREF_SYNTAX_COLORING_TYPE=Type +PREF_SYNTAX_COLORING_PREDICATE=Predicate +PREF_SYNTAX_COLORING_CONSTANTS=Constant +PREF_SYNTAX_COLORING_STRINGS=String + +PREF_SYNTAX_COLORING_SAVE_FAIL_MSG=Error while saving preferences to file. +PREF_SYNTAX_COLORING_LOAD_FAIL_MSG=Error while loading preferences from file. + +PREF_SYNTAX_COLORING_SAVE_FAIL_TITLE=Save Preferences Failure +PREF_SYNTAX_COLORING_LOAD_FAIL_TITLE=Load Preferences Failure +ENABL_ING = Enable +DISABL_ING = Disable +REMOVE_BP = Remove +REMOVE_CONN_TITLE=Remove Connection Profile +REMOVE_CONN_MSG=Are you sure you want to remove the connection profile? +SELECT_CONN_TO_REMOVE=Select one connection profile to remove. +REMOVE_PROFILE = Delete Profile +HELP_LABEL = Help + +DATABASE_ENCODING=Database Encoding + +DATABASE_CONNECTION_LIMIT_REACHED = Maximum connection limit({0}) reached for database. Close unused terminals and proceed. +VIEWS_NAME = Views +VIEW_COLUMNS_NAME=Columns +DROP_VIEW_SUCCESS = Dropped view: {0}.{1} +DROP_VIEW_CASCADE_SUCCESS = Dropped view and dependent objects: {0}.{1} +DROP_VIEW_FAILURE_TITLE = Error dropping View +DROP_VIEW_FAILURE = Unable to drop view {0}. {1}Server message: {2} +DROP_VIEW_UNABLE_MSG=Error dropping view: {0} +RENAME_VIEW_TITLE = Rename View +RENAME_VIEW_SUCCESS=Renamed view: {0} to {1}.{2} +ENTER_NEW_VIEW_NAME = Enter the new name for {0} view + +RENAME_VIEW_FAILURE = Unable to rename view {0}. {1}Server message: {2} +SET_VIEW_SCHEMA = Set Schema +SET_VIEW_MESSAGE = Select a new schema for view {0}.{1} +SET_VIEW_SCHEMA_SUCCESS = Moved view : {0}.{1} to {2}.{3} + +SET_VIEW_SCHEMA_FAILURE = Unable to set schema for view {0}. {1}Server message: {2} +SET_VIEW_SCHEMA_MOVING=Moving {0} view, to {1} Schema. Processing... +DROP_VIEW_CONFIRM_TITLE = Drop View +DROP_VIEW_CONFIRM_MSG = Are you sure you want drop ''{0}'' view? +DROP_VIEW_CASCADE_CONFIRM_MSG=Are you sure you want to drop ''{0}'' view and its dependent objects? + +VIEW_COLUMN_SET_DEFAULT_TITLE = Set Default value for {0}.{1}.{2} +SET_VIEW_COL_DEFAULT_STATUS_BAR=Set view column default value + +CONSOLE_TAB = Messages +RESULT_TAB = Result +EXECUTION_PLAN_TAB = Execution Plan + +DS_EXIT_MSG_FOR_JOBS=There are running jobs. Are you sure you want to exit? + +ERR_DROP_CON_PROF_FILE = Deleting connection profile folder failed. + +ERR_PROFILE_WRITE_DISK = Error writing profile to disk. + +ERR_PROFILE_WRITE_INVALID = Error writing profile to disk. Invalid Profile. + +PERMANENTLY_SAVE = Permanently +CURRENT_SESSION_ONLY = Current Session Only +DO_NOT_SAVE = Do Not Save + +CONNECTION_NAME = Connection Name +CONNECTION_DETAILS = Connection Details + +ERR_BL_SQL_HISTORY_NOT_LOADED=SQL History loading is not completed, Please try again later. +DELETE_SELECTED_HISTORY_ALERT= Are you sure you want to delete the selected SQL query history of ''{0}'' connection profile? {1}{1}Note: Pinned queries cannot be deleted. +DELETE_ALL_HISTORY_ALERT= Are you sure you want to delete the SQL query history of ''{0}'' connection profile? {1}{1}Note: Pinned queries cannot be deleted. +PREFERENCE_EXAMPLE=e.g.- +SQL_DATA = Export Data +SQL_DDL = Export Schema +SQL_DDL_DATA = Export Schema and Data + +EXPORT_DDL_HEADER = Export {0} +EXPORT_DDL_FAIL_HEADER = Export {0} Failed +EXPORT_DDL_SUCCESS = Exported {0} to path: {1}. +EXPORT_DDL_FAIL = Export failed: Cannot locate external export utility + +EXPORT_FAIL_DISK_WRITE_ERROR=Disk Write failed. +EXPORT_FAIL_PROCESS_INTRUPTED=Export/show DDL process failed.\ + \n{0} +EXPORT_FAIL_UNSUPPORTED_SERVER_VERSION = Show/Export DDL feature is disabled for this server version. +CANNOT_LOCATE_GSDUMP=Cannot locate external export utility (gs_dump). +EXPORT_CANCEL_ON_USER_REQUEST=Canceled export operation on your request. + +LOAD_SQL_TERMINAL = Load in SQL Terminal +LOAD_TERMINAL_CLOSE_HISTORY = Load in SQL Terminal and close History +DELETE_SQL = Delete SQL +DELETE_ALL = Delete All +PIN_SQL = Pin the SQL +SQL_HISTORY_TOOL_TRIP = SQL Execution History +SQL_HISTORY_DISABLED_TOOL_TIP = SQL Execution History - Profile Not Loaded +SQL_HISTORY_TITLE = SQL Execution History - {0} +SQL_AUTOCOMMIT_ON_TOOL_TIP = Auto Commit On +SQL_AUTOCOMMIT_OFF_TOOL_TIP = Auto Commit Off + + +SQL_AUTOCOMMIT_DISABLED_TOOL_TIP = Turn Auto Commit On/Off - No Active Connections +ERR_SQL_AUTOCOMMIT_TOGGLE_TITLE = Turning Auto Commit On Failed +ERR_SQL_AUTOCOMMIT_TOGGLE = Commit or Rollback the existing transaction. +SQL_AUTOCOMMIT_SAVE_CHANGES_TITLE = Save Changes +SQL_AUTOCOMMIT_SAVE_CHANGES_MSG = New changes will be saved but not committed.\nExecute COMMIT command in SQL Terminal to commit the changes. + +SQL_STATEMENT = SQL Statement +SQL_ROW_SELECTION= Number of Records +DATABASE_NAME = Database Name +START_TIME = Start Time +ELAPSED_TIME = Execution time (ms) +FINAL_STATUS = Execution Status +PIN_STATUS = Pin Status +PROFILE_NAME = Profile Name +UNPIN_SQL = Unpin SQL +SERIAL_NO = Serial No +CONN_PROFILE_ERROR_MSG=Error occurred while loading profiles : {0}.These profiles are removed from the profile list. +CIPHER_DECRYPT_ERROR_MSG=Error occurred while loading profiles : {0}. Decrypting passwords for these profiles failed. Re-enter the password. + +TABLESPACE_NAME=Name* +TABLESPACE_RELATIVE_PATH=Relative Path +TABLESPACE_LOCATION=Location* +TABLESPACE_MAXSIZE=Max Size +TABLESPACE_SEQCOST=Sequential Page Cost +TABLESPACE_RANCOST=Random Page Cost +TABLESPACE_UNSUPPORTED_SERVER_VERSION=Unsupported Server version +TABLESPACE_GENERAL=General +TABLE_EDIT_MESSAGE=A column is currently being edited. Complete or cancel the Edit operation to perform other operations. +UNLIMITED_SIZE=Unlimited Size +CONN_DIALOG_SAVE_CIPHER = Save Password +TABLESPACE_CREATION_SUCCEEDED = Tablespace Successfully Created +TABLESPACE_CREATION_FAILED = Error Creating Tablespace +RUN_IN_BACK_GROUND =Run in Background + +SHORTCUT_MAPPER =Shortcut Mapper +SELECT_SHORTCUTKEY = Select Shortcut keys: +MODIFY_KEY = Modify +UNBIND_KEY = Unbind Key +KEY_NAME = Name: +BINDING_KEY = Binding: +COMMAND_NAME = Command Name +KEY_BINDING = Key Binding +KEY_DESCRIPTION = Description +HISTORY_LOADING_IN_PROGRESS_TILTLE=History Loading In Progress +PREFERENCES_SHOW = Preferences +PREF_LOAD_ERROR=Error in preferences +PREF_LOAD_MSG=For invalid preference values, we are setting Default preference values. +PREF_FILE_ERR_TITLE=Error in File Loading +PREF_FILE_ERR_MSG=Error in keybinding file loading + +PINNED_DELETION =Pinned queries cannot be deleted. +SELECT_QUERY_TO_DELETE = Select at least one query to delete +CONNECTION_ERR_DURING_RESIZING_TABLESPACE =Connection error during resizing tablespace.{0} Error :{1} + +PREFERENCE_DEFAULT=Restore &Defaults +PREFERENCE_APPLY=&Apply + +PREFERENCEDIALOG_OK = OK +PREFERENCEDIALOG_CANCEL = Cancel + +DES_NEW_CONN =Establish a new connection +DISSCONN_FRM_DB =Disconnect a database +EXE_DB_OBJECT =Execute a procedure or function +REF_SREVER_OBJECT = Refresh a server object +EXE_SQL_TERMINAL = Execute statements in SQL Terminal +EXECUTION_PLAN_AND_COST=Shows the execution plan for the Query +VISUAL_EXPLAIN_PLAN=Visual representation of the query execution plan +FORMAT_SQL_STATEMENT = Format the statements in SQL Terminal and Procedure/Function Source Viewer +OPEN_SAVED_FILE =Open a saved SQL file in SQL Terminal +TO_SAVE_FILE =Save the contents in SQL or File Terminal to a SQL file +TO_SAVE_FILE_AS = Save the contents in SQL or File Terminal to a new SQL file +CANCEL_SQL_STETEMNT =Cancel execution in SQL Terminal +OPEN_NEW_INSTANCE = To Open New SQL Instance +CLOSE_ACTIVE_VIEWER =Close active Procedure/Function source viewer +COLAPSE_ALL_OBJECTS =Collapse opened objects in Object Browser +SHOW_LIST_OF_OBJECTS =Show list of objects for use in the SQL Terminal +SHOW_MATCHING_PATTERN=Shows/replaces with the matching template in the editor + +INVALID_USERNAME_MSG = Invalid user name/password, login denied +CREATE_TABLE_EMPTY_COLUMN = Must have at least one column +LOADING_NS=Loading +INVALID_LOGGINGLEVEL=Invalid log level. Setting to default (WARN) + +TO_UPPER_CASE =Convert the selected text to upper case +TO_LOWER_CASE = Convert the selected text to lower case +GO_TO_LINE=Jump to the line entered in the Go To Line field +GO_TO_LINE_POPUP_TITLE= Go To Line +INVALID_INPUT_FOR_GO_TO_LINE=Invalid Input +FORWARD_SEARCH= Search forward for the text entered in the Search field +BACKWARD_SEARCH= Search backward for the text entered in the Search field +ENTER_LINE_NUMBER=Enter the line number + +IMPORTEXPORT_VALIDATION_OTHER=Enter delimiter value. +IMPORTEXPORT_VALIDATION_NULL_STRING=Null String should not contain newline or carriage return. +IMPORTEXPORT_VALIDATION_NULL_LENGTH=Maximum 100 characters allowed for null string. +IMPORTEXPORT_VALIDATION_DELIMITER_LENGTH=Delimiter must be maximum of 10 bytes. +IMPORTEXPORT_VALIDATION_NULL_AS_DELIMITOR=Null parameter can not be same as the delimiter and quote parameter. +IMPORTEXPORT_VALIDATION_NULL_AS_QUOTE=Null parameter can not be same as the default quote parameter. +IMPORTEXPORT_VALIDATION_QUOTE_SINGLE_CHAR=Only single character is allowed for quote/escape. +IMPORTEXPORT_VALIDATION_QUOTE_AS_DELI=Quote character should not be same as the delimiter. +EXPORT_VALIDATION_QUOTE_NO_COLS_SELECTED = Select at least one column to Export. +IMPORT_VALIDATION_QUOTE_NO_COLS_SELECTED = Select at least one column to Import. +IMPORTEXPORT_VALIDATION_QUOTE_AS_ESCAPE=Quote character should not be same as the Escape character. + +EXPORT_OPTION_TITLE=Export Table Data: +IMPORT_OPTION_TITLE=Import Table Data: +EXPORT_ERROR=Export Error +IMPORT_ERROR=Import Error +OPTION_DELIMITER=Delimiter +OPTION_FORMAT=Format : +OPTION_HEADER=Include Header +OPTION_QUOTE=Quotes: +OPTION_ESCAPE=Escape: +OPTION_TOOLTIP=Single character only +OPTION_REPLACE_NULL=Replace NULL with: +OPTION_REPLACE_WITHNULL=Replace with NULL: +OPTION_NULL_TOOLTIP=Maximum 100 characters +OPTION_ENCODING=Encoding: + +OPTION_OTHERTOOLTIP= A maximum of 10 bytes allowed +OPTION_SELECTCOLUMNS=Select Columns +OPTION_ALLCOLUMNS=All Columns (Uncheck to Reorder/Remove) +OPTION_SELECTED_COL=Selected Columns +OPTION_AVAILABLE_COL=Available Columns +OPTION_I_AGREE=I Agree +IMPORT_FILE_BROWSE=Browse +IMPORT_DATA_FILE=Import Data File: + +RESULT_WINDOW_QUERY_SUBMIT_TIME=Query Submit Time: {0} +RESULT_WINDOW_EXECUTION_TIME=Execution time: {0} +RESULT_WINDOW_RECORD_FETCHED=Record Fetched: {0} {1} +RESULT_WINDOW_RECORD_MORE= (more...) + +RESULT_WINDOW_ROWS_FETCHED={0} rows fetched in {1}{2} +RESULT_WINDOW_ROW_FETCHED={0} row fetched in {1}{2} +RESULT_WINDOW_EXECUTED_QUERY_TOOLTIP= Executed Query +RESULT_WINDOW_RECORD_FETCHED_ALL={0} rows fetched in {1} +RESULT_WINDOW_RECORD_FETCHED_ONE={0} row fetched in {1} +CREATE_FUNCTION_PROCEDURE=Created Function/Procedure Successfully +RESULT_WINDOW_EDITTABLE_COMMIT_SUCCESS=Success: {0}{1} {2} {3} +RESULT_WINDOW_EDITTABLE_COMMIT_FAILURE=/Failure: {0} + +LAST_SUCCESSFULL_LOGIN_MESSAGE=Last Successful Login: +LAST_FAILURE_LOGIN_MESSAGE=Failed Login Attempts: +DATA_STUDIO_NOTIFIFICATIONS= RECENT LOGIN ACTIVITY +DATABASE_NAME_NOTIFICATION= Database: {0} +LAST_LOGIN_MESSAGE= Loading last login notification: {0} +LOGIN_NOTIFICATION_STARTED=Login Notification job has been started +LOGIN_NOTIFICATION_ENDED=Login Notification job has been ended +INFO_MAX_RESULT_SOURCE_VIEWER= Maximum number of Result tabs limit is reached.Close unused tabs to run unexecuted queries. +SSL_DISABLED_CONTINUE_OR_CANCEL=SSL not enabled for this connection.\nSSL connection is recommended when high security is required.\nClick Continue to proceed without SSL or click Cancel to enable SSL. +MPPDBIDE_DIA_BTN_CLOSE=Close +MPPDBIDE_DIA_BTN_CONTINUE=Continue +CONNECTION_SECURITY_ALERT=Connection Security Alert +CREATE_NEW_PARTITION_TABLE= Create Partition Table +TABLE_ORIENTATION=Table Orientation +ENTER_DESCRIPTIONS_TEXT=Description of Table(Max 5000 chars) +RENAME_PARTITION_TABLE_TO=Renamed Partition: {0} to {1}.{2}.{3} +STATUS_MSG_RENAME_PARTITION_TABLE=Renaming Partition Table... + +RENAME_PARTITION_TABLE_WAIT=Renaming {0} Partition, processing... +RENAME_PARTITION_TABLE_TITLE=Rename Table +RENAME_PARTITION_TITLE=Rename Partition +RENAME_PARTITION_TABLE_NEW=Enter new name for {0} partition in table {1} + +ERR_TITLE_CREATE_FILE_DIRECTORY = Create/Load of Logs File Failed +ERR_BL_CREATE_FILE_DIRECTORY = Access denied. Failed to create/load logs. Closing Data Studio. +ERR_TITLE_LAUNCH_DATASTUDIO = Launch Failed +ERR_BL_LAUNCH_MULTIPLE_INSTANCE_DATASTUDIO = Opening multiple instances of Data Studio for same user is not supported. + +DROP_PARTITION_TITLE=Drop Partition +DROP_PARTITION=Are you sure you want to drop {0} partition from {1}.{2} table? +STATUS_MSG_DROP_PARTITION = Dropping Partition... +DROP_PARTITION_SUCCESS=Dropped partition: {0}.{1}.{2} +DROP_PARTITION_ERROR_TITLE=Error When Dropping Partition +DROP_PARTITION_UNABLE_MSG=Error dropping partition: {0}.{1}.{2} +CIPHER_EDIT_MESSAGE=A partition is being edited. Complete or cancel the editing to perform other operations. +DB_CONN_LBL_CLIENT_SSL_KEY=Client SSL Key +DB_CONN_LBL_CLIENT_SSL_CERT=Client SSL Certificate +DB_CONN_BTN_CLIENT_KEY=*.pk8 +DB_CONN_BTN_CLIENT_CERT=*.crt +DB_CONN_BROWSE=... + +EXPORT_QUERY=Exported All Result Data from :{0} tab +EXPORT_RESULT_TITLE= Export ResultSet Data: +EXPORT_EXEC_TITLE= Export data : {0} +EXPORT_RESULT_INVALID_CONNECTION = Connection for this Export Result Data is not valid .Export Data can not be continued. +SHOW_TABLE_DDL=Show DDL in Progress +SHOW_DDL_FAILED= Show DDL Failed +SHOW_TABLE_DDL_FAILED=Error showing DDL: {0}.{1} +SHOW_TABLE_DDL_CANCELING=Canceled show DDL: {0}.{1} + +PARTITION_TAB_ORIENTATION=Orientation +PARTITION_TAB_TYPE=Partition Type +PARTITION_TAB_INTERVAL_PARTITION_EXPR=Interval Value +PARTITION_TAB_PARTITION_BY_RANGE=Partition by Range +PARTITION_TAB_AVAILABLE_COLUMN=Available Column +PARTITION_TAB_PARTITION_COLUMN=Partition Column +PARTITION_TAB_PATITION_NAME=Partition Name +PARTITION_TAB_PARTITION_VALUE=Partition Value +PARTITION_TAB_TABLESPACE=Tablespace +PARTITION_TAB_PARTITIONS=Partitions +PARTITION_TAB_PARTITION_DEF=Partition Definition +RENAME_CONNECTION_TITILE=Rename Connection +RENAME_CONNECTION_NEW_NAME=Enter new name for {0} +STATUS_MSG_RENAME_CONNECTION = Renaming Connection... +RENAME_CONNECTION_WAIT=Renaming {0} connection, processing... +RENAME_CONNECTION_TO= Renamed connection: {0} to {1} +RENAME_CONNECTION_ERROR=Failed to rename connection: {0} \n Error: {1} +INF_NOEDIT_DONE_MSG_BODY=There are no changes to be saved. +INF_NOEDIT_DONE_MSG_TITLE=Connection parameters not saved + +EDIT_CONNECTION_WIZARD_TITLE=Edit Connection +EDIT_CONNECTION_SUBTITLE=Modify Connection Parameters + +GENERAL_OPTION_TEXT=Provide the general information for creating the table . Click Next to proceed to the next section. +TABLE_OPTIONS_TEXT=Table options and values may be changed for different table orientations. Refer to User Manual for details. + +ERR_NONSELECT_CANCELLED= Cannot complete the operation as object is locked by another operation. +DISCARD_TERMINAL_DATA_BODY=You have unsaved data.\nDo you want to discard the unsaved changes? +SAVE_CHANGES_DATA_BODY=You have unsaved data.\nPlease commit/discard changes to load more records. +EXPORT_DIRTY_DATA_BODY=You have unsaved data.\nDo you want to export the unsaved changes? + +IMPORT_EXPORT_DELIMETER_COMMA=Comma (,) +IMPORT_EXPORT_DELIMETER_TAB=Tab +IMPORT_EXPORT_DELIMETER_PIPE=Pipe (|) +IMPORT_EXPORT_DELIMETER_SEMICOLON=Semicolon (;) +IMPORT_EXPORT_DELIMETER_OTHER=Other: +LAST_LOGIN_UNAVAILABE=Last login details not available +LASTLOGIN_CONNECTION_NAME=Connection name: {0} +PROTOCOL_VERSION_ERROR=FATAL: unsupported frontend protocol +SEQUENCE=Sequences + +SEARCH_SCOPE_LBL=Search Scope +SEARCH_CONNECTION_LBL=Connection +SEARCH_CONNECTION_MAND_MSG= Select Profile +SEARCH_DATABASE_LBL=Database +SEARCH_DATABASE_MAND_MSG=Select Database +SEARCH_NAMESPACE_LBL=Schema +SEARCH_NAMESPACE_MAND_MSG=Select Schema +SEARCH_WITHIN_LBL=Search Within +SEARCH_WITHIN_TABLE_LBL=Tables +SEARCH_WITHIN_FUN_LBL=Functions/Procedures +SEARCH_WITHIN_VIEWS=Views +SEARCH_OPTIONS_LBL=Search Options +SEARCH_NAME_LBL=Search for +SEARCH_NAME_MAND_MSG=Enter Search Text +SEARCH_NAME_MATCH_LBL=Search Criteria +SEARCH_NAME_MATCH_CONTAINS=Contains +SEARCH_NAME_MATCH_STARTS_LBL= Starts with +SEARCH_NAME_MATCH_EXACT_LBL=Exact Word +SEARCH_NAME_MATCH_REGU_EXPRESS_LBL= Regular Expression +SEARCH_MATCH_CASE_LBL=Match Case +SEARCH_BTN=Search +SEARCH_CANCEL_BTN=Cancel +SEARCH_RESULT_LBL= Search Result + +SEARCH_WINDOW_LBL=Search +OB_REFRESH_TOOL=Refresh +SEARCH_RECORD_FETCHED_MSG={0} object(s) found +SEARCH_NO_RECORD_FOUND_MSG= No object(s) found +SEARCH_EXE_TIME_MSG=Execution time: {0} +KEY_BINDING_SEARCH= Search Objects + +SEARCH_PROGRESS_STATS_MSG=Search is in progress +SEARCH_PROGRESS_MONITOR_MSG= Searching Objects from: {0} +SEARCH_OBJ_ERROR= Error searching objects +SEARCH_NO_CONN_MSG=Check if the connection is active and try again +SEARCH_SELECT_SEARCH_WITHIN_OPT=Select at least one object type from Search Within list +CLOSE_TAB_MENU=&Close +CLOSE_ALL_TAB_MENU=Close &All +CLOSE_OTHER_TABS_MENU=Close &Others +CLOSE_LEFT_TABS_MENU=Close Tabs to the &Left +CLOSE_RIGHT_TABS_MENU=Close Tabs to the &Right +SAVE_PARTS=Save Parts +SELECT_PARTS_FOR_SAVE=Select the parts to save: +RENAME_TERMINAL_TITLE=Rename Terminal +RENAME_TERMINAL_MSG=Enter the new name for {0} terminal +RENAME_TERMINAL_NAME=Rename &Terminal +RENAME_TERMINAL_DUPLICATE_NAME_ERROR = Renaming {0} terminal failed. \n Error: Terminal {1} already exists. +IMPORT_EXPORT_INVALIDFILENAME=Invalid file name. The file name cannot contain any of the following characters: \ /: *? " < > | + +EXPORT_OUTPUTPATH=Output Path +DROP_SEQUENCE_CONFIRM_TITLE = Drop Sequence +DROP_SEQUENCE_CONFIRM_MSG = Are you sure you want to drop ''{0}'' Sequence? +DROP_SEQUENCE_CASCADE_CONFIRM_MSG=Are you sure you want to drop ''{0}'' Sequence and its dependent objects? + +CREATE_NEW_SEQUENCE=Create New Sequence +SEQUENCE_CREATED_SUCESSFULLY=Created sequence: {0}.{1} +CREATE_SEQUENCE_ERROR = Error creating sequence: {0}.{1} + +SEQUENCE_NAME=Sequence Name * +MINIMUM_VALUE =Minimum Value: +MAXIMUM_VALUE = Maximum Value: +INCREMENT_BY = Increment By: +START_VALUE = Start Value: +SEQUENCE_CACHE = Cache: +ORDER = Order: +CYCLE_MSG = Cycle +CYCLE = Cycle: +OWNER = Owner: +TABLE_NAME= Table +COLUMN_NAME=Column +SELECT_SCHEMA_NAME=Schema + +BROWSE_BTN_ROOT_CERT=*.crt +BROWSE_BTN_PEM_CERT=*.pem +ROOTCERT_FILETEXT=Root Certificate +SSL_CIPHER=SSL Password +CTAB_GENERAL=General +CTAB_SSL=SSL +CTAB_ADVANCED=Advanced +DROPDOWN_SSLMODE=SSL Mode + +GENERAL_NODE=General +EDITOR_NODE=Editor +SECURITY_NODE=Security +ENVIRONMENT_NODE=Environment +CIPHER_PREFERENCE_OPTION=Password +CIPHER_PREFERENCE_OPTION_TITLE=Enable Permanently Save Password option +YES_OPTION=Yes +NO_OPTION=No +NO_TEXT=Save Password Permanently option will not be available in the connection profile.\n Previously saved passwords will be deleted. +YES_TEXT=Save Password Permanently option will be available in connection profile. +SECURITY_WARNING_OPTION=Security Warning +ENABLE_OPTION=Enable +DISABLE_OPTION=Disable +ENABLE_WARNING_MSG=Security warning message will be displayed for any unsecure connections/file operations. +DISABLE_WARNING_MSG=Click \"I Agree\" to confirm the following:\n\nSecurity warning message will not be displayed for non-SSL connection.\nData Studio will not perform data encryption. \nData Studio will not set the permissions of the exported files. \nSensitive information may be accessible to hackers. +SESSION_SETTNG_NODE=Session Setting +DATA_STUDIO_ENCODING=Data Studio Encoding +ENCODING_PREFERENCES_TITLE=Encoding Preferences +FILE_ENCODING=File Encoding +IAGREE_TEXT=I Agree + +LBL_INCLUDE = Include +LBL_EXCLUDE = Exclude +LBL_FAST_LOAD_OPTIONS = Fast Load Options +LBL_LOAD_LIMIT = Load Limit +LBL_GRP_SCHEMA = Schema + +PREF_RESULT_WINDOW_TITLE=Result Management + +PREF_RESULT_VIEW_TITLE=Query Results +PREF_CUSTOM_LENGTH=Custom Length: +PREF_CONTENT_LENGTH=Content Length +PREF_COLUMN_WIDTH=Column Width +ERROR_ANNOTATION_LABEL=Error +EDITTABLE_PREFERENCE_OPTION=Edit Table Data + +TERMINAL_ERROR_WHILE_EXECUTION = Do not show additional errors for this execution +ERROR_POPUP_HEADER = Execution Failure +ERROR_POPUP_MESSAGE_TEXT = Do you want to continue execution? + +DROP_SEQUENCE_SUCCESS = Dropped sequence: {0}.{1} +DROP_SEQUENCE_FAILURE = Unable to drop sequence {0}{1} {2} +DROP_SEQUENCE_CASCADE_SUCCESS = Dropped sequence and dependent objects: {0}.{1} +EXPORT_PREFERENCES= Export +EXPORT_DDL_PREFERENCES = Export DDL +EXPORT_DATA_PREFERENCES = Export Data +INCLUDE_EXPORT_DATA_OPTION = Enable this option to allow Export Data +INCLUDE_TABLESPACE_IN_DDL= Include Tablespace in DDL +EXPORT_IMPORT_PREFERENCES=Export/Import + +DATE_TIME_PREFERENCES = Date/Time +USER_DEFINED = User defined format +DATE_PREFERENCE = Date +TIME_PREFERENCE = Time +SYSTEM_FORMAT = Default format +DATE_FORMAT_ERROR_MSG = Please enter valid date format, for example: yyyy-MM-dd +TIME_FORMAT_ERROR_MSG = Please enter valid time format, for example: HH:mm:ss +DATE_FORMAT_EXAMPLE_HINT = Valid date format examples: yyyy-MM-dd, yyyy/MM/dd, yyyyMMdd +TIME_FORMAT_EXAMPLE_HINT = Valid time format examples: HH:mm:ss, HH:mm:ss.SSS, HH:mm:ss.SS + +PREF_RS_DATA_FETCH_COUNT_SUBTITLE=Result Fetch Count +PREF_RS_DATA_FETCH_ALL_MSG=Fetch All records +PREF_RS_DATA_FETCH_COUNT_MSG=Fetch custom number of records +PREF_RS_CONTENT_LENGTH_HINT=Sets the width of the column based on the content length of the column +PREF_EXPORT_DDL_W_TABLESPACE_HINT=Tablespace information will be included while exporting DDL. +PREF_RS_CUSTOM_LENGTH_HINT=Sets the minimum width of the column based on the length of the value in pixel for Grid Mode.\ + \nSets the minimum width of the column based on the length of the value in character length for Text Mode. + +PREF_RS_COLUMN_WIDTH_INPUT_ERR_MSG=Invalid input for Column Width. Enter a number between 100 and 500. +PREF_RS_FETCH_COUNT_INPUT_ERR_MSG=Invalid input for Result fetch count. Enter a number between 100 and 5000. +SHOW_HIDE_QUERY_BAR=Show/Hide Query Bar +SHOW_HIDE_SEARCH_BAR=Show/Hide Search Bar +SEARCH_GRID=Search +CLEAR_SEARCH_GRID=Clear Search Text +SEARCH_OPT_CONTAINS=Contains +SEARCH_OPT_EQUALS=Equals +SEARCH_OPT_STARTS_WITH=Starts with +SEARCH_OPT_REGEX=REGEX +SEARCH_OPT_NULL=Null Values +TABLE_DOES_NOT_EXIST=Table does not exist +VIEW_DOES_NOT_EXIST=View does not exist +PREF_RS_DATA_COPY_COL_HEADER_MSG=Include column header +PREF_RS_DATA_COPY_ROW_HEADER_MSG=Include row number +PREF_RS_COPY_HEADING=Result Advanced Copy +PREF_RS_COPY_COLUMN_HEADER_HINT=Copies selected content along with the column header +PREF_RS_COPY_ROW_HEADER_HINT=Copies selected content along with the row number +CREATE_SEQUENCE_INPUT_FORMATE=Invalid input entered in {0} field. \nEnter a valid number between {1} and {2}. +EXPORTING_DATA_STATUS_MSG=Exporting data... +LOADING_DATA_STATUS_MSG=Loading data... +MINIMUM_VALUE_FIELD =Minimum Value +MAXIMUM_VALUE_FIELD = Maximum Value +INCREMENT_BY_FIELD = Increment By +START_VALUE_FIELD = Start Value +SEQUENCE_CACHE_FIELD = Cache +ERROR_LOADING_DATA_STATUS_MSG=Error Loading data. + +GENERAL_NODE_LABLE =General provides the following options: \ + \n \ + \n\u2022 Modify the default keys for a command.\ + \n \ + \n Users must save their work in DS before using this option as DS will restart \ + \n and any unsaved data will be lost. \ + \n \ + \n Changes to general settings affect the use of shortcut keys. +EDITOR_NODE_LABLE =Editor provides the following options:\ + \n \ + \n\u2022 Set syntax coloring in SQL Terminal and Procedure/Function Viewer. Syntax coloring is available\ + \n for single-line comments, unreserved and reserved keywords, types, predicates, constants,\ + \n and strings. Syntax coloring change affects the display in SQL Terminal and Procedure/Function Viewer.\ + \n\u2022 Set SQL history query count and the number of characters to be saved for each query.\ + \n\u2022 Define SQL templates for SQL editor and Procedure/Function source viewer.\ + \n\u2022 Define tab settings for SQL Editor and Procedure/Function source viewer.\ + \n\u2022 Define number of characters required for triggering Auto Suggest on user typing.\ + \n\ + \n Prior to changing the settings of syntax coloring, users must save their work in DS as it \ + \n will restart and any unsaved data will be lost.\ + \n\ + \n Changes to SQL history count and number of characters to be saved in a query will not restart DS. +SECURITY_NODE_LABLE =Security provides the following options: \ + \n \ + \n\u2022 Show/Hide the Security warning message for any unsecured \ + \n connection/file operations.\ + \n\u2022 Show/Hide the Permanently option for saving the password while \ + \n establishing a connection. \ + \n \ + \n Users must save their work in DS before using this option as DS will restart \ + \n and any unsaved data will be lost. \ + \n \ + \n Changes to Security settings affect connection setup and the export function.\ + +ENVIRONMENT_NODE_LABLE =Environment provides the following options: \ + \n \ + \n\u2022 Data Studio Character Encoding\ + \n\u2022 File Character Encoding \ + \n \ + \n Users must save their work in DS before using this option as DS will restart\ + \n and any unsaved data will be lost. \ + \n \ + \n Changes to Environment settings affect the DS character encoding in result\ + \n and table data display. \ + \n \ + \n Show/Hide SQL Assistant for SQL and Procedure/Function Viewer suggestions.\ + \n \ + \n Auto saves unsaved information in SQL Terminal and Procedure/Function Viewer as per defined time \ + \n interval and encrypts the saved data. +PREF_RESULT_WINDOW_NODE_LABLE =Result Management provides the following options: \ + \n \ + \n\u2022 Set the default number of records to be fetched at a time. Fetch the \ + \n desired number of rows.\ + \n\u2022 Set the preferred column widths for the table data/result set. \ + \n\u2022 Include the column headers and/or row number in table copy operations.\ + \n\u2022 Set the preferred behavior to save table data modifications.\ + \n\u2022 Include the result data encoding in edit table, view table, and query results.\ + \n \ + \n Changes will be applied immediately without restarting DS.\ + \n \ + \n Changes to Result Management setting affect the data display in ResultSet, View, and\ + \n Edit Table Data tabs. +EXPORT_IMPORT_PREFERENCES_LABLE = Export/Import provides the following options: \ + \n \ + \n\u2022 Include/Exclude tablespace details during Export DDL and Show DDL\ + \n operations.\ + \n \ + \n\u2022 Enable/Disable export data option during Export DDL and Data, Export Table Data, \ + \n Export all Data, Export Current Page Data and Generate SQL Operations. \ + \n \ + \n Changes will be applied immediately without restarting DS.\ + \n \ + \n Changes to Export/Import settings affect Show DDL and Table Export DDL\ + \n operations. +PROPERTIES_GENERAL_TAB=General +PROPERTIES_COLUMNS_TAB=Columns +PROPERTIES_CONSTRAINTS_TAB=Constraints +PROPERTIES_INDEX_TAB=Index +PROPERTIES_PARTITIONS_TAB=Partition +PARTITION_COLUMN_ID=Partition Column +PROPERTIES_VIEW_NAME=View Name +PROPERTIES_VIEW_OWNER=View Owner +PROPERTIES_VIEW_DEF=View Definition +DS_RESTART_CONFIRMATION_TITLE = Restart Confirmation +DS_RESTART_MSG_FOR_JOBS = There are running jobs. Are you sure you want to restart? + +TABLEPROPERTIES_OPTIONS_ORIENTATION=Orientation +TABLEPROPERTIES_OPTIONS_FILLFACTOR=fill factor +TABLEPROPERTIES_OPTIONS_COMPRESSION=Compression +TABLEPROPERTIES_OPTIONS_MAX_BATCHROW=MAX_Batchrow +TABLEPROPERTIES_OPTIONS_PARTIAL_CLUSTER_ROWS=Partial_cluster_rows +SEARCH_ITEM_TEXT=Enter a search term here. +TABLE_PROPERTIES_GROUP=Table Properties + +PARTITION_ERROR_MESSAGE=At least one partition is required +ENTER_TABLE_NAME=Enter Table Name +ENTER_COLUMN_NAME=Enter Column Name +ENTER_INDEX_NAME=Enter Index Name + +PARTITION_COLUMN_ERROR_THAN_FOUR=Partition column list cannot be greater than 4 +PARTITION_COLUMN_ERROR_THAN_ONE=Partition column list cannot be greater than 1 +SQL_HISTORY_STATUS_SUCCESS= Success + +SQL_HISTORY_STATUS_FAILURE=Failure +PARTITION_UI_SELECT=Select +PREFERENCE_COMMAND_NEW_NODE_CONNECTION=New Connection +PREFERENCE_SHORTCUT_DISSCONN_FRM_DB =Disconnect From DB +PREFERENCE_SHORTCUT_EXE_DB_OBJECT =Execute DB Object + +PREFERENCE_SHORTCUT_REF_SREVER_OBJECT =Refresh +PREFERENCE_SHORTCUT_EXE_SQL_TERMINAL =Execute Statement + +PREFERENCE_SHORTCUT_EXECUTION_PLAN_AND_COST=Explain Plan and Cost +PREFERENCE_SHORTCUT_VISUAL_EXPLAIN_PLAN=Visual Explain Plan +PREFERENCE_SHORTCUT_FORMAT_SQL_STATEMENT = Format +PREFERENCE_SHORTCUT_OPEN_SAVED_FILE =Open + +PREFERENCE_SHORTCUT_TO_SAVE_FILE =Save +PREFERENCE_SHORTCUT_TO_SAVE_FILE_AS =Save As +PREFERENCE_SHORTCUT_CANCEL_SQL_STETEMNT =Cancel +PREFERENCE_SHORTCUT_CLOSE_ACTIVE_VIEWER =Close Active Source Viewer + + +PREFERENCE_SHORTCUT_COLAPSE_ALL_OBJECTS=Collapse Open Objects +PREFERENCE_SHORTCUT_AUTO_SUGGEST=Auto Suggest +PREFERENCE_SHORTCUT_CODE_TEMPLATE=Templates +PREFERENCE_SHORTCUT_TO_UPPER_CASE =UPPERCASE +PREFERENCE_SHORTCUT_TO_LOWER_CASE =lowercase + +PREFERENCE_SHORTCUT_GO_TO_LINE= Go to Line +PREFERENCE_SHORTCUT_FORWARD_SEARCH= Forward Search +PREFERENCE_SHORTCUT_BACKWARD_SEARCH = Backward Search +PREFERENCE_SHORTCUT_KEY_BINDING_SEARCH_DESC=Search Objects +KEY_BINDING_SEARCH_DESC=Search for objects in database + +PREFERENCE_RESTART_REQUIRED_MSG=Preferences have been modified. Restart Data Studio to apply the changes. + + +CIPHER_EXPIRY_TITLE = Indicates whether to allow login to the database seven days before the password expires. +YES_EXPIRY_OPTION= Allow +NO_EXPIRY_OPTION = Not Allow +CIPHER_EXPIRY_MSG_TITLE = The password is about to expire. +CIPHER_EXPIRY_INFORMATION = The password is about to expire and certain operations may be restricted. Contact administrator to reset password. + +EDITTABLE_TITLE = Table Data Save Option +YES_EDITTABLE_OPTION=Valid data will be saved. All invalid data will be highlighted for correction and will not be saved. +NO_EDITTABLE_OPTION=If an error occurs no data will be saved. Invalid data will be highlighted for correction. +EDIT_TABLE_ENABLE_OPTION=Save Valid Data +EDIT_TABLE_DISABLE_OPTION=Do Not Save + + + SHOW_USER_MSG_ON_TABLE_UPDATE_TITLE =Table Property Update + SHOW_USER_MSG_ON_TABLE_UPDATE_BODY =Modifying the {0} will delete the information from {1} tab. + + + CONSTRAINT_INDEXES_HANDLER_NOT_SUPPORTED_TITLE=Operation Not Supported + CONSTRAINT_HANDLER_FOR_COLUMN_ORIENTATION_BODY=Creation of constraints for column orientation table is not supported. + CHANGE_INDEX_FOR_COLUMN_ORIENTATION_TABLE= Modification of fill factor for index in column orientation table is not supported. This value has been set by default to 100. + + DATA_DISTRIBUTION_TAB=data distribution + INDEXES_TAB=indexes + CONSTRAINT_TAB=constraint + PARTITION_TAB=partition + +CANCEL_CONNECTION_TITLE=Cancel Connection +CANCEL_CONNECTION_BODY=Do you wish to cancel connecting to the database? +USER_CANCEL_MSG =Operation canceled on user request + + REFRESH_TABLE_TOOLTIP=Refresh + REFRESH_TABLE_TOOLTIP_DISABLED = Save/Cancel changes to refresh + INSERT_ROW_TOOLTIP= Add + DELETE_ROW_TOOLTIP= Delete + COMMIT_CHANGES_TOOLTIP= Save Changes + ROLLBACK_CHANGES_TOOLTIP= Cancel Changes + PASTE_TOOTIP=Paste to Grid + DEFINE_UNIQUE_KEY_TITLE=Define Unique Key + UNIQUE_CONSTRAINT_COLNAME_HEADER=Column Name + UNIQUE_CONSTRAINT_DATATYPE_HEADER=Data Types + UNIQUE_CONSTRAINT_SELECT_ALL_BTN_LABEL=Select All + UNIQUE_CONSTRAINT_CLEAR_ALL_BTN_LABEL=Clear All + UNIQUE_CONSTRAINT_TABLE_LABEL= Table + USE_ALL_COLUMNS_LABEL=Use All Columns + CUSTOM_UNIQUE_KEY_LABEL=Custom Unique Key + CANCEL_LABEL=Cancel + EDIT_TABLE_DATA_CONNECTION_LOST_ERR_MSG= An error occurred while saving table data. Connection may be lost. Reconnect and perform the edit table operation again. + COMMITING_DATA=Commit in progress + GROUP_COLUMNS_HEADER=Columns + NO_PHYSICAL_UNQ_KEY_MSG=There is no physical unique key defined for + DEFINE_UNQ_KEY_MSG =Define Unique key or Select all columns to proceed. + + CONNECT_DB_CANCEL_MSG=Cancelled connecting to database on user request. + + PASTE_INVALID_SELECTION_DIALOG_TITLE=Invalid Selection + PASTE_INVALID_SELECTION_DIALOG_MSG=The number of pasted cell and the selected cell does not match + QUERY_EXECUTION_FAILURE_ERROR_TITLE=Data Modification Failed + QUERY_EXECUTION_FAILURE_ERROR=Failed to update one or more rows. Please move the cursor on row line number to check the error message in tool tip. + + GRID_EDIT_STATUS_INSERTED = Inserted: + GRID_EDIT_STATUS_UPDATED = Modified: + GRID_EDIT_STATUS_DELETED = Deleted: + +DB_ASSISTANT_LANGUAGE=en_IN +DB_ASSISTANT_NAME=SQL Assistant +DB_ASSISTANT_ENABLE=Enable +DB_ASSISTANT_DISABLE=Disable +DB_ASSIST_ENABLE_DESC=SQL Assistant will be available to provide suggestions or reference for the \n information entered in the SQL Terminal and Procedure/Function Viewer. +DB_ASSIST_DISABLE_DESC=SQL Assistant will not be available to provide suggestions or reference for the \n information entered in the SQL Terminal and Procedure/Function Viewer. + +EDIT_TABLE_DATA_ERROR_POPUP_HEADER= Edit Table Data Error +VIEW_TABLE_DATA_ERROR_POPUP_HEADER= Object Dropped Error +PROPERTIES_WINDOW_ERROR_POPUP_HEADER=Table Properties Error +EDIT_TABLE_DATA_ERROR_POPUP_MESSAGE=An error occurred while editing table data. + +ERR_CIPHER_EXPIRED =Password expired +ERR_TO_BEGIN_TRANSACTION=Unable to begin transaction +ERR_EDIT_TABLE_COMMIT_FAIL=SQL Error Code +ERR_LAZY_BACKEND_LOAD_TITLE=Error while loading Object + +ERR_EDIT_TABLE_DROP_TABLE=Unable to edit table data as the object has been modified/dropped. Refresh Object Browser and try again. +ERR_DENIED_ACCESS_PRIVILEGE=Access denied. +USER_CANCEL = user cancellation +LAST_LOGING_FAILED_RETREIVAL_DATABASE = Failed to get Last login information from database +ERR_DATABASE_OPERATION_FAILURE=Error while doing database operation. +ERR_FETCH_DATABASE_OPERATION=Error fetching database list from the node. +ERR_WRITING_PROFILE_TO_DISK=Write to Profile meta data disk failed +ERR_PROFILE_FILE_REACHABLE=Profiles file not readable +ERR_READING_PROFILE_DATA=Error reading profiles meta data file. +ERR_TO_CONVERT_SEQ_DATA=Error while converting data from result set +ERR_LAZY_LOADING_TABLE=Error while loading the table + +ERR_VIEW_TABLE_FAILURE=Refresh Object Browser and try again. +FAILED_TO_LOCK_FILE=Failed to lock the file +EDIT_TABLE_FORGET_OPTIONS=Clear saved unique key selection +EDIT_TABLE_REMEMBER_CHOICE=Remember the selection for this window +VERSION=Version + +EDIT_TABLE_INVALID_DATE_DATATYPE=The Date/Time entry is invalid. Date and time columns must be in yyyy-mm-dd HH:mm:ss and HH:mm:ss format. +EDIT_TABLE_INVALID_NUMBER_DATATYPE=Data entered is not valid. Enter valid data. + +DRP_OBJ_ERRTITLE = Drop Object Error +DROP_OBJECT_ERROR = Error Dropping Object: {0} +TABLESPACE_CREATION_ERROR = Error creating tablespace: {0}.{1} +SEARCH_OBJ_CANCEL_MSG = Canceled searching objects on user request +SET_COL_VAL_ERROR = Error setting column default value: {0}.{1}.{2} +ADD_COLUMN_ERROR = Error adding new column: {0}.{1} +NEW_CONSTRAINT_CREATED_ERROR = Error creating constraint: {0}.{1} +TITLE_IOEXCEPTION = IO Exception + +LOAD_CONN_ERR_TITLE = Load Connection Error +LOAD_CONN_ERR_MSG = Error loading user profile. Server message: {0} +LOG_ERR_TITLE = Create Log Error +LOG_ERR_MSG = Error creating log. Server message: {0} +REINDEX_TABLE_FAIL = Error reindexing table: {0}.{1} +SET_COLUMN_FAIL = Error setting NOT NULL for column: {0}.{1}.{2} +DROP_SCHEMA_FAIL = Error dropping schema: {0}.{1} +REMOVE_CONN_ERROR = Error removing connection profile. Server message: {0} +REMOVE_CONNPROF_TITLE = Connection Removal Error +ERR_PROFILE_WRITE_DISK_TITLE = Profile Write to Disk Error +ERR_CONNECTION_FAILED = Connection Error + +SET_TABLESPACE_FAIL= Error Setting Tablespace +EDIT_TABLE_INVALID_BOOLEAN_DATATYPE=The pasted entry does not match the format for boolean/bit data type +TABLE_PROPERTIES_INVALID_BOOLEAN_DATATYPE=The pasted entry does not match the format for boolean value + +DROP_SEQUENCE_ERROR = Error dropping sequence: {0}.{1} +EXPORT_TABLE_SUCESS = Exported data from table: {0} +EXPORT_DDL_CANCEL_MSG=Canceled the export operation on user request + +#for Visual explain Plan--start + +VIS_EXPLAIN_ICON_TOOLTIP_ZOOM_RESET=Reset + +VIS_EXPLAIN_JOB_DETAILS=Generating Visual Explain plan for the query +VIS_EXPLAIN_JOB_RESULT_DETAILS=Visual Explain Plan Property + +VIS_EXPLAIN_MAN_WINDOW_TITLE=Visual Plan Analysis +VIS_EXPLAIN_WINDOW_LBL=Visual Explain Plan +VIS_EXPLAIN_WINDOW_TEXT_LBL=General Details +VIS_EXPLAIN_WINDOW_ALL_NODES_LBL=Properties + +VIS_EXPLAIN_OVERALL_DETAILS_ALLNODES_TAB=All Nodes +VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_ANALYSIS=Analysis +VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_CONTRIBUTION=Contribution (%) +VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_EXECUTIONTIME=Execution time (ms) +VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_NODENAME=Node Name +VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_ROWSOUTPUT=Rows Output +VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_ROWSOUTPUTDEVIATION=Rows Output Deviation (%) +VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_SELFCOST=Self Cost +VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_TOTALCOST=Total Cost + +VIS_EXPLAIN_OVERALL_DETAILS_GENERAL_TAB=General +VIS_EXPLAIN_OVERALL_DETAILS_GENERAL_COLUMN_PROP=Property +VIS_EXPLAIN_OVERALL_DETAILS_GENERAL_COLUMN_VALUE=Value +VIS_EXPLAIN_OVERALL_DETAILS_ROOTNODE_TOTALRUNTIME=Total Runtime (ms) + +VIS_EXPLAIN_PROP_PERDN_ACTUALSINDETAIL_COLUMNGRP=Actuals +VIS_EXPLAIN_PROP_PERDN_ACTUALS_COLUMN_LOOPS=Loops +VIS_EXPLAIN_PROP_PERDN_ACTUALS_COLUMN_ROWS=Rows +VIS_EXPLAIN_PROP_PERDN_ACTUALS_COLUMN_STARTUPTIME=Startup Time (ms) +VIS_EXPLAIN_PROP_PERDN_ACTUALS_COLUMN_TOTALTIME=Total Time (ms) +VIS_EXPLAIN_PROP_PERDN_AGGREGATEINDETAIL=Aggregate Details +VIS_EXPLAIN_PROP_PERDN_BUFFERSINDETAIL=Buffer Details +VIS_EXPLAIN_PROP_PERDN_CPUINDETAIL=CPU Details +VIS_EXPLAIN_PROP_PERDN_HASHDETAIL=Hash Detail +VIS_EXPLAIN_PROP_PERDN_SETOPDETAIL=SetOp Detail +VIS_EXPLAIN_PROP_PERDN_DN_COLUMNGRP=DN Information +VIS_EXPLAIN_PROP_PERDN_DN_COLUMN=DN Name +VIS_EXPLAIN_PROP_PERDN_JOININDETAIL=Join Details +VIS_EXPLAIN_PROP_PERDN_LLVM_COLUMNGRP=LLVM Details +VIS_EXPLAIN_PROP_PERDN_LLVM_COLUMN=LLVM + +VIS_EXPLAIN_PER_NODE_COLUMN_PROP=Property +VIS_EXPLAIN_PER_NODE_COLUMN_VALUE=Value +VIS_EXPLAIN_PER_NODE_DETAILS_PART_LBL=DN Details +VIS_EXPLAIN_PER_NODE_DETAILS_GENERAL_TAB=General +VIS_EXPLAIN_PER_NODE_DETAILS_PERDN_TAB=DN Details + +VIS_EXPLAIN_NODCATEGORY_AGGREGATE=Aggregate +VIS_EXPLAIN_NODCATEGORY_FUNCTION=Function Scan +VIS_EXPLAIN_NODCATEGORY_GROUPAGGREGATE=Group Aggregate +VIS_EXPLAIN_NODCATEGORY_HASH=Hash +VIS_EXPLAIN_NODCATEGORY_HASHJOIN=Hash Join +VIS_EXPLAIN_NODCATEGORY_MODIFYTABLE=Modify Table +VIS_EXPLAIN_NODCATEGORY_NESTLOOPJOIN=Nest Loop Join +VIS_EXPLAIN_NODCATEGORY_NESTEDLOOP=Nested Loop +VIS_EXPLAIN_NODCATEGORY_PARTITIONITERATOR=Partition Iterator +VIS_EXPLAIN_NODCATEGORY_ROWADAPTER=Row Adapter +VIS_EXPLAIN_NODCATEGORY_SCAN=Scan +VIS_EXPLAIN_NODCATEGORY_SETOP=SetOp +VIS_EXPLAIN_NODCATEGORY_SORT=Sort +VIS_EXPLAIN_NODCATEGORY_STREAM=Stream +VIS_EXPLAIN_NODCATEGORY_UNKNOWN=Unknown +VIS_EXPLAIN_NODCATEGORY_UNION=Union + +VIS_EXPLAIN_PROP_ANALYSISNODE_ANALYSIS=Analysis +VIS_EXPLAIN_PROP_ANALYSISNODE_OUTPUT=Output +VIS_EXPLAIN_PROP_ANALYSISNODE_ROWSOUTPUTDEVIATION=Rows Output Deviation (%) + +VIS_EXPLAIN_PROP_BASICNODE_ACTUALLOOPS=Actual Loops +VIS_EXPLAIN_PROP_BASICNODE_ACTUALOUTROWS=Actual Output Rows +VIS_EXPLAIN_PROP_BASICNODE_ACTUALSTARTUPTIME=Actual Startup Time +VIS_EXPLAIN_PROP_BASICNODE_ACTUALTOTALTIME=Actual Total Time + +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_IOREADTIME=I/O Read Time (ms) +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_IOWRITETIME=I/O Write Time (ms) +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALDIRTIEDBLOCKS=Local Dirtied Blocks +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALHITBLOCKS=Local Hit Blocks +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALREADHITBLOCKS=Local Read Blocks +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALWRITTENBLOCKS=Local Written Blocks +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDDIRTIEDBLOCKS=Shared Dirtied Blocks +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDHITBLOCKS=Shared Hit Blocks +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDREADBLOCKS=Shared Read Blocks +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDWRITTENBLOCKS=Shared Written Blocks +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_TEMPREADBLOCKS=Temp Read Blocks +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_TEMPWRITTENBLOCKS=Temp Written Blocks + +VIS_EXPLAIN_PROP_BASICNODE_CPU_EXCLUSIVECYCLESROW=Exclusive Cycles/Row +VIS_EXPLAIN_PROP_BASICNODE_CPU_EXCLUSIVECYCLES=Exclusive Cycles +VIS_EXPLAIN_PROP_BASICNODE_CPU_INCLUSIVECYCLES=Inclusive Cycles + +VIS_EXPLAIN_PROP_BASICNODE_HASH_HASHBATCHES=Hash Batches +VIS_EXPLAIN_PROP_BASICNODE_HASH_HASHBUCKETS=Hash Buckets +VIS_EXPLAIN_PROP_BASICNODE_HASH_ORIGINALHASHBATCHES=Original Hash Batches +VIS_EXPLAIN_PROP_BASICNODE_HASH_PEAKMEMORYUSAGE=Peak Memory Usage + +VIS_EXPLAIN_PROP_BASICNODE_ISVECTORIZED=Is Column Store +VIS_EXPLAIN_PROP_BASICNODE_NODETYPE=Node Type +VIS_EXPLAIN_PROP_BASICNODE_PARENTRELATIONSHIP=Parent Relationship +VIS_EXPLAIN_PROP_BASICNODE_PLANROWS=Plan Output Rows +VIS_EXPLAIN_PROP_BASICNODE_PLANWIDTH=Row Width(Bytes) + +VIS_EXPLAIN_PROP_BASICNODE_STARTUPCOST=Startup Cost +VIS_EXPLAIN_PROP_BASICNODE_TOTALCOST=Total Cost + +VIS_EXPLAIN_PROP_CSTORESCANNODE_FILTER=Filter +VIS_EXPLAIN_PROP_CSTORESCANNODE_ROWREMOVEDFILTER=Rows Removed by Filter + +VIS_EXPLAIN_PROP_DATANODESCAN_PRIMARYNODECOUNT=Primary Node Count +VIS_EXPLAIN_PROP_DATANODESCAN_NODECOUNT=Node Count + +VIS_EXPLAIN_PROP_FUNCTIONSCANNODE_FUNCTIONALIASNAME=Alias +VIS_EXPLAIN_PROP_FUNCTIONSCANNODE_FUNCTIONCALL=Function Call +VIS_EXPLAIN_PROP_FUNCTIONSCANNODE_FUNCTIONNAME=Function Name +VIS_EXPLAIN_PROP_FUNCTIONSCANNODE_SCHEMANAME=Schema + +VIS_EXPLAIN_PROP_GROUP_BY_GRPBYKEYS=Group By key +VIS_EXPLAIN_PROP_JOIN_JOINTYPE=Join Type + +VIS_EXPLAIN_PROP_HASHNODE_HASHBUCKETS=Hash Buckets +VIS_EXPLAIN_PROP_HASHNODE_HASHBATCHES=Hash Batches +VIS_EXPLAIN_PROP_HASHNODE_ORIGINALHASHBATCHES=Original Hash Batches +VIS_EXPLAIN_PROP_HASHNODE_PEAKMEMORYUSAGE=Peak Memory Usage + +VIS_EXPLAIN_PROP_HASH_JOIN_JOINCOND=Hash Condition + +VIS_EXPLAIN_PROP_INDEXSCANNODE_INDEXCOND=Index Condition +VIS_EXPLAIN_PROP_INDEXSCANNODE_INDEXNAME=Index Name +VIS_EXPLAIN_PROP_INDEXSCANNODE_ROWSREMOVEDRECHECK=Rows Removed by Index Recheck +VIS_EXPLAIN_PROP_INDEXSCANNODE_SCANDIRECTION=Scan Direction + +VIS_EXPLAIN_PROP_MODIFYTABLE_OPERATION=Operation +VIS_EXPLAIN_PROP_NESTLOOP_JOIN_JOINFILTER =Join Filter +VIS_EXPLAIN_PROP_NESTLOOP_JOIN_ROWSREMOVEDBYJOINFILTER =Rows Removed By Join Filter +VIS_EXPLAIN_PROP_NESTEDLOOP_SUBPLAN=Subplan Name +VIS_EXPLAIN_PROP_NODE_REMOTEQUERY=Remote Query +VIS_EXPLAIN_PROP_NODE_SUBPLANNAME=Subplan Name + +VIS_EXPLAIN_PROP_OPERATIONALNODE_CHILD1NAME=Inner Node Name +VIS_EXPLAIN_PROP_OPERATIONALNODE_CHILD2NAME=Outer node Name +VIS_EXPLAIN_PROP_OPERATIONALNODE_CHILDRENNAME=Child Name + +VIS_EXPLAIN_PROP_SCANNODE_ALIASNAME=Alias +VIS_EXPLAIN_PROP_SCANNODE_SCANTABLEALIASNAME=Table Alias +VIS_EXPLAIN_PROP_SCANNODE_SCANTABLENAME=Table Name +VIS_EXPLAIN_PROP_SCANNODE_SCHEMANAME=Schema Name +VIS_EXPLAIN_PROP_SCANNODE_SELECTEDPARTITIONS=Selected Partitions +VIS_EXPLAIN_PROP_SETOPNODE_TEMPFILENUM=Temp File Num +VIS_EXPLAIN_PROP_SETOP_COMMAND=Command +VIS_EXPLAIN_PROP_SETOP_STRATEGY=Strategy +VIS_EXPLAIN_PROP_SORT_SORTKEYS=Sort keys + +VIS_EXPLAIN_PROP_STREAM_GATHER_NODES=Node/s +VIS_EXPLAIN_PROP_STREAM_REDISTRIBUTE_DISTRKEY=Distribution Key +VIS_EXPLAIN_PROP_STREAM_REDISTRIBUTE_SPAWNON=Spawn On +VIS_EXPLAIN_PROP_WORKTABLESCANNODE_FILTER=Filter +VIS_EXPLAIN_PROP_WORKTABLESCANNODE_ROWREMOVEDFILTER=Rows Removed by Filter + +VIS_EXPLAIN_ANALYSIS_COSTLIEST=COSTLIEST +VIS_EXPLAIN_ANALYSIS_HEAVIEST=HEAVIEST +VIS_EXPLAIN_ANALYSIS_SLOWEST=SLOWEST + +VIS_EXPLAIN_JSON_PARSING_FAILED=Invalid JSON format from server. + +VIS_EXPLAIN_PLAN_ERROR_POPUP_HEADER=Visual Explain Plan Error +EXPLAIN_PLAN_ERROR_POPUP_HEADER=Explain Plan Error + +#for Visual explain Plan--end + +CANCEL_OPERATION_IN_PROGRESS=Canceling operation... +TABLE_PROPERTIES_TABLE_NAME=Table Name +USER_CANCEL_MSG_TITLE=Cancel Operation + +INVALID_INCLUDE_EXCLUDE_SCHEMA=Schema information {0} entered in Exclude and {1} entered in Include Fast Load Options are not valid. +INVALID_EXCLUDE_SCHEMA=Schema information {0} entered in Exclude Fast Load Options is not valid. +INVALID_INCLUDE_SCHEMA=Schema information {0} entered in Include Fast Load Options is not valid. +INVALID_INCLUDE_EXCLUDE_TITLE=Invalid Include/Exclude Schema +USER_CANCEL_MSG_TITLE=Cancel Operation +UKNOWN_COMPLEX_DATATYPE=Unknown +INVALID_INCLUDE_EXCLUDE_TITLE=Invalid Include/Exclude Schema +LOAD_LIMIT_UNIT=(DB Object Count) +EDIT_TABLE_DATA_DROPPED_REFRESH_ERROR=An error occurred while editing table data.\n Unable to edit table data as the object has been modified/dropped.\n Reopen Edit Table Data window. +VIEW_TABLE_DATA_DROPPED_REFRESH_ERROR=An error occurred while fetching data.\n Unable to fetch data as the object has been modified/dropped.\n Reopen the window. +CANCELLING_JOB=Canceling {0} + +SQL_HIST_PINNED=Pinned +# NO Translation Required as only consumed by code +ERR_EDITTABLE_REFRESH_FAILED=Requested Table data not available + +PARTITION_TABLE_COL_REMOVE_TITLE=Modify Partition Column +PARTITION_TABLE_COL_REMOVE_BODY =Changing partition column list will remove all partition definitions if applicable.\ \nAre you sure you want to continue? + +EDIT_DUPLICATE_MODIFICATION_TITLE= Identical rows updated + +PARTITION_VALUE_TOOLTIP=Click to enter partition value +PARTITION_VALUE_POPUP_TITLE=Define Partition Value +PARTITION_COLUMN=Column +PARTITION_VALUE=Value +EDIT_DUPLICATE_MODIFICATION_MSG= More than one identical row found. All the identified rows are updated. + +RESULT_WINDOW_EDITTABLE_COMMIT_REFRESH= Refresh to view updated data. + +RESULT_WINDOW_EDITTABLE_COMMIT_UPDATED=/Updated Rows: {0} +ERR_EXPORT_TABLE_DROP_TABLE=Unable to export table data as the object has been modified/dropped. Refresh Object Browser and try again. +ERR_IMPORT_TABLE_DROP_TABLE=Unable to import table data as the object has been modified/dropped. Refresh Object Browser and try again. +TOOLTIP_DISTRIBUTION_COL=\n[Distribution Column] +TOOLTIP_READONLY_COL=\n[Non-editable column] +EXPORT_DDL_PROGRESS_NAME=Exporting DDL: {0} +EXPORT_DDL_DATA_PROGRESS_NAME=Exporting DDL and Data: {0} + +DS_DEFAULT_MAX_CONSOLE_LINE_COUNT=Invalid ConsoleLineCount configuration. Setting to maximum ConsoleLineCount (5000). +EXPORT_DDL=DDL +EXPORT_DDL_DATA=DDL and Data +HAS_OID=Has OID + +NAMESPACE_RETRIVE_CRITICAL_ERROR=Error loading schema objects. +CONNECT_TO_DB_STATE_MACHINE_ERROR =Cannot perform the requested operation as connection is in progress.\nTry again later. + +EDIT_TABLE_PROGRESS_NAME=Editing table data query: {0} +EDIT_TABLE_COMMIT_PROGRESS_NAME=Committing edited data: {0} +VIEW_TABLE_PROGRESS_NAME=Viewing table data: {0} +VIEW_PROGRESS_NAME=Viewing view data: {0} +LAZYLOAD_NAMESPACE_PROGRESS_NAME=Lazy Loading of schema at backend: {0} +CHANGE_INDEX_TBLSPACE_PROGRESS_NAME=Changing index tablespace: {0} +DROP_COLUMN_PROGRESS_NAME=Dropping column: {0} +DROP_PARTITION_PROGRESS_NAME=Dropping partition: {0} +DROP_TABLE_PROGRESS_NAME=Dropping table: {0} +RENAME_COLUMN_PROGRESS_NAME=Renaming column: {0} +VALIDATE_CONSTRAINT_PROGRESS_NAME=Validating constraint: {0} +SHOW_VIEW_DDL_PROGRESS_NAME=Displaying show DDL for view: {0} +CONNECT_DB_PROGRESS_NAME=Connecting to database: {0} +CREATE_DB_PROGRESS_NAME=Creating database: {0} +DROP_SCHEMA_PROGRESS_NAME=Dropping schema: {0} +DROP_DEBUGOBJECT_PROGRESS_NAME=Dropping Debug Object: {0} +REINDEX_TABLE_PROGRESS_NAME=Reindexing table: {0} +RENAME_DATABASE_PROGRESS_NAME=Renaming Database: {0} +SHOW_DDL_TABLE_PROGRESS_NAME=Displaying show DDL for table: {0} +ADD_COLUMN_PROGRESS_NAME=Adding column: {0} +ADD_CONSTRAINT_PROGRESS_NAME=Adding constraint: {0} +ALTER_COLUMN_DEFAULT_PROGRESS_NAME=Setting column default value: {0} +ALTER_VIEWCOLUMN_DEFAULT_PROGRESS_NAME=Setting view column default value: {0} +CREATE_INDEX_PROGRESS_NAME=Creating index: {0} +CREATE_TABLE_PROGRESS_NAME=Creating table: {0} +EXPORT_ALL_RESULTDATA_PROGRESS_NAME=Exporting all result data: {0} +EXPORT_ALL_DATA_PROGRESS_NAME=Exporting all data for object : {0} +EXPORT_CURRENT_RESULTDATA_PROGRESS_NAME=Exporting current page result data: {0} +CREATE_SEQ_PROGRESS_NAME=Creating Sequence: {0} +REEXECUTE_QUERY_PROGRESS_NAME=Re-executing query in SQL Terminal: {0} +CONN_PROP_HOST=Host +CONN_PROP_PORT=Port +CONN_PROP_USERNAME=Username +CONN_PROP_SERVER_TYPE=Server Type +CONN_PROP_DB_VERSION=Server Information +CONNECTION_VERSION_NUMBER_FAILED_MSG=Unknown +CONNECTION_PROPERTIES_UNAVAILABLE= connection properties not available + +#TRANSLATION FOR SQL HISTORY STARTS +SQL_HISTORY=SQL History +SET_SQL_SIZE=SQL History Count +SQL_SIZE_DESC_LABEL=Sets the number of queries that can be saved in the history.\nPinned queries will not be affected by this change. +SET_SQL_QUERY_LENGTH= SQL Query Characters +SQL_HISTORY_RANGE=Range: +DEFAULT_VALUE=Default: +SQL_QUERY_LENGTH_NO_LIMIT=No limit: +SQL_QUERY_DESC_LABEL1=Sets the number of characters of the query to be saved in the SQL History.\nAffects only the queries added after this settings change. +SQL_SIZE_ERROR_MSG=Invalid input for SQL History Count. +SQL_QUERY_ERROR_MSG=Invalid input for SQL Query Characters. +UPDATE_SQL_HISTORY_SETTING_TITLE=Update SQL History Settings +UPDATE_SQL_HISTORY_SETTING_BODY=The value entered in SQL History Queries field is lesser than current value.\nSome of the SQL history queries may be lost.\nDo you want to continue? +SQL_HISTORY_SETTING_UNSAVED_DATA_BODY=There are unsaved settings changes. Do you want to save the changes? \ + \n\ + \n\ + Note: Entries will be restored to current value in case of error.\ +SAVING_PREFERENCES=Saving Preferences .. + +#TRANSLATION FOR SQL HISTORY ENDS +CONNECTION_PROPERTIES_UNAVAILABLE= connection properties not available +REEXECUTE_QUERY_PROGRESS_NAME=Re-executing query in SQL Terminal: {0} + +#Templates Preference Page Starts +CODE_TEMPLATE_PREFPAGE_MESSAGE=&Create, edit or remove templates: +CODE_TEMPLATE_PREFPAGE_TITLE=Templates +CODE_TEMPLATE_DUPLICATE_MSG=The template name {0} already exists. + +CODE_TEMPLATE_PREFPAGE_EDIT=&Edit +CODE_TEMPLATE_PREFPAGE_NEW=&New +CODE_TEMPLATE_PREFPAGE_REMOVE=&Remove +CODE_TEMPLATE_PREFPAGE_RESTORE=Restore Re&moved +CODE_TEMPLATE_PREFPAGE_REVERT=Re&vert to Default + +CODE_TEMPLATE_PREFPAGE_COLUMN_NAME=Name +CODE_TEMPLATE_PREFPAGE_COLUMN_DESCRIPTION=Description + +CODE_TEMPLATE_PREFPAGE_MATCH_CASE=Matc&h Case + +CODE_TEMPLATE_PREFPAGE_PREVIEW=Previe&w: + +CODE_TEMPLATE_PREFPAGE_ERROR_READ_TITLE=Reading Templates +CODE_TEMPLATE_PREFPAGE_ERROR_READ_MESSAGE= Failed to read templates. +CODE_TEMPLATE_PREFPAGE_ERROR_WRITE_TITLE=Writing Templates +CODE_TEMPLATE_PREFPAGE_ERROR_WRITE_MESSAGE= Failed to write templates. +FAILED_TO_WRITE_TO_EXCEL = Failed to write to file + +# Template Dialog +CODE_TEMPLATE_DIALOG_TITLE_NEW=New Template +CODE_TEMPLATE_DIALOG_TITLE_EDIT=Edit Template + +CODE_TEMPLATE_DIALOG_NAME=&Name +CODE_TEMPLATE_DIALOG_DESCRIPTION=&Description: +CODE_TEMPLATE_DIALOG_PATTERN=&Pattern +CODE_TEMPLATE_DIALOG_MANDATORY_MARK=* +CODE_TEMPLATE_DIALOG_COLON=: +CODE_TEMPLATE_DIALOG_MAX_CHAR=[{0}/{1}] + +CODE_TEMPLATE_DIALOG_NAME_RESTRICTION_MSG=(Whitespace characters are not allowed) + +CODE_TEMPLATE_DIALOG_UNDO=&Undo +CODE_TEMPLATE_DIALOG_REDO=&Redo +CODE_TEMPLATE_DIALOG_CUT=Cu&t +CODE_TEMPLATE_DIALOG_COPY=&Copy +CODE_TEMPLATE_DIALOG_PASTE=&Paste +CODE_TEMPLATE_DIALOG_SELECT_ALL=Select &All + +CODE_TEMPLATE_DUPLICATE_ID=Duplicate template id. +CODE_TEMPLATE_ILLEGAL_BOOLEAN_ATTR=Illegal boolean attribute, must be "true" or "false". +CODE_TEMPLATE_JSONEXCEPTION=Json parsing failed. Invalid json data. +CODE_TEMPLATE_MISSING_REQUIRED_ATTR=Missing required attribute. + +CODE_TEMPLATE_PREFPAGE_UNSAVEDCHANGED_TITLE=Update Templates Settings +PREFERENCE_CHANGE_NOT_APPLIED_MESSAGE=There are unsaved changed. Do you want to apply the changes? +#Templates Preference Page Ends + +DB_CONN_SERVER_DOMAIN_NAME_ERROR=The connection attempt failed. +DB_CONN_DOMAIN_NAME_ERROR=Verify the details entered in General tab and try again.\ + \nHINT (Try one of the below): \ + \n1. Domain Name must start with a letter.\ + \n2. Domain Name allows letters, digits, hyphens (-), and period (.). All other special characters are not allowed.\ + \n3. Space/Tabs are not allowed.\ + \n4. A fully qualified Domain Name can have up to 253 character (including periods). +CONN_PROP_SERVER_IP= Server IP +SERVERIP_TOOLTIP=Server IP: {0} +SERVERIP_TOOLTIP_FAIL=Unknown +SERVERVERSION_TOOLTIP=Server Version: {0} + +EXECUTION_FAILURE_LINE_NUMEBR=Line Number: +BUTTON_LABEL_SHOW_DETAILS=Details>> +BUTTON_LABEL_HIDE_DETAILS=Details<< +EXECUTION_FAILURE_DETAILS_DESCRIPTION=Click Details for more information. + +EXEC_PLAN_COST_TOOLTIP = Execution Plan and Cost +VIS_EXPLAIN_EXEC_PLAN_COLUMN_ENTITYNAME = Entity Name +VIS_EXPLAIN_EXEC_PLAN_COLUMN_COST = Cost +VIS_EXPLAIN_EXEC_PLAN_COLUMN_ROWS = Rows +VIS_EXPLAIN_EXEC_PLAN_COLUMN_LOOPS = Loops +VIS_EXPLAIN_EXEC_PLAN_COLUMN_WIDTH = Width +VIS_EXPLAIN_EXEC_PLAN_COLUMN_ACTUAL_ROWS = Actual Rows +VIS_EXPLAIN_EXEC_PLAN_COLUMN_ACTUAL_TIME = Actual Time +VIS_EXPLAIN_PROPERTIES_EXEC_PLAN_TITLE = Exec. Plan + +DOMAINNAME_REDIRECT_FAILURE = {0}Try connecting again. +#Batch Delete Messages +DROP_OBJECTS_WINDOW_TITLE=Drop Objects - {0} ({1}) +DROP_OBJECTS_WINDOW_SHORTTITLE=Drop Objects ({1}) + +DROP_OBJECTS_NATTABLE_COLUMN_ERR_MSG=Error Message +DROP_OBJECTS_NATTABLE_COLUMN_NAME=Name +DROP_OBJECTS_NATTABLE_COLUMN_QUERY=Query +DROP_OBJECTS_NATTABLE_COLUMN_STATUS=Status +DROP_OBJECTS_NATTABLE_COLUMN_TYPE=Type + +DROP_OBJECTS_OPER_ATOMIC=Atomic +DROP_OBJECTS_OPER_CASCADE=Cascade +DROP_OBJECTS_OPER_START=Start +DROP_OBJECTS_OPER_STOP=Stop + +DROP_OBJECTS_OPER_DB_NAME=Name: +DROP_OBJECTS_OPER_LBL_RUNS=Runs: +DROP_OBJECTS_OPER_LBL_ERRORS=Errors: + +DROP_OBJECTS_OPER_STATUS_COMPLETED=Completed +DROP_OBJECTS_OPER_STATUS_ERROR=Error +DROP_OBJECTS_OPER_STATUS_INPROGRESS=In progress +DROP_OBJECTS_OPER_STATUS_TOSTART=To start + +DROP_OBJECTS_NOT_ALLOWED_DIALOG_TITLE=Drop Objects +DROP_OBJECTS_NOT_ALLOWED_DIALOG_MESSAGE=Objects can be dropped only within a database. +DROP_OBJECTS_NOT_ALLOWED_NO_DB_DIALOG_MESSAGE=Drop objects operation is not allowed from Object Groups. +DROP_OBJECTS_NOT_ALLOWED_OBJECT_DIALOG_MESSAGE=Drop objects operation failed. Click Details for more information. +DROP_OBJECTS_NOT_ALLOWED_OBJECT_DIALOG_OBJ_LIST=The following objects cannot be dropped :\nConnection\nDatabase\nTablespace\nForeign Table + +DROP_OBJECTS_OPER_STOP_DIALOG_TITLE=Drop Objects +DROP_OBJECTS_OPER_STOP_DIALOG_MESSAGE=Drop objects operation is in progress. Are you sure you want to stop the operation? + +DROP_OBJECTS_JOB_NAME=Dropping objects: {0} +DROP_OBJECTS_JOB_FINISHED_STATUS=Dropped objects from: {0} +DROP_OBJECTS_JOB_FAILURE_STATUS=Error dropping objects from: {0} +DROP_OBJECTS_JOB_STOPPED_STATUS=Stopped dropping objects from: {0} +ERR_COLUMN_NAME_EMPTY = Column name cannot be empty +ERR_CONSTRAINT_NAME_EMPTY = Constraint name cannot be empty +PROPERTIES_ERROR_MESSAGE={0} has been modified/dropped. Cancel changes, refresh, and try again. +PROPERTIES_ERROR_MESSAGE_FOR_CONSTRAINT=Constraint name has been modified. Cancel changes, refresh, and try again. +PROPERTIES_COMPLEX_DATATYPE_ERROR_MSG={0} has been modified/dropped, refresh, and try again. +PREFERENCE_SHORTCUT_KEY_BINDING_TOGGLE_LINE_COMMENTS=Comment/Uncomment Lines +KEY_BINDING_TOGGLE_LINE_COMMENTS_DESC=Comment/Uncomment each line individually in SQL Terminal and Procedure/Function Source Viewer +PREFERENCE_SHORTCUT_KEY_BINDING_TOGGLE_BLOCK_COMMENTS=Comment/Uncomment Block +KEY_BINDING_TOGGLE_BLOCK_COMMENTS_DESC=Comment/Uncomment block of lines/content in SQL Terminal and Procedure/Function Source Viewer +OBJECT_NAME_MORE_THAN_LIMIT_ERROR_MESSAGE= Maximum 64 characters allowed for table, column, constraint, and index name. +MAX_CHARATCTERS_ALLOWED_FOR_TABLE_DESC=Maximum 5000 characters allowed for table description. + +#debug +PREFERENCE_SHORTCUT_KEY_BINDING_START_DEBUG = Start Debugging +PREFERENCE_SHORTCUT_KEY_BINDING_TERNIMATE_DEBUG = Stop Debugging +PREFERENCE_SHORTCUT_KEY_BINDING_STEPIN_DEBUG = Step In +PREFERENCE_SHORTCUT_KEY_BINDING_STEPOUT_DEBUG = Step Out +PREFERENCE_SHORTCUT_KEY_BINDING_STEPOVER_DEBUG = Step Over +PREFERENCE_SHORTCUT_KEY_BINDING_CONTINUE_DEBUG = Continue +KEY_BINDING_COMMENTS_DESC_START_DEBUG = Start Debugging +KEY_BINDING_COMMENTS_DESC_TERNIMATE_DEBUG = Stop Debugging +KEY_BINDING_COMMENTS_DESC_STEPIN_DEBUG = Step In +KEY_BINDING_COMMENTS_DESC_STEPOUT_DEBUG = Step Out +KEY_BINDING_COMMENTS_DESC_STEPOVER_DEBUG = Step Over +KEY_BINDING_COMMENTS_DESC_CONTINUE_DEBUG = Continue + +#PreservSQL Messages +PRESERVESQL_STARTUP_DIALOG_MESSAGE=Loading auto saved queries, functions, and procedures... +PRESERVESQL_STARTUP_JOB_NAME=Loading the SQL terminal... +PRESERVESQL_STARTUP_LAZY_JOB_NAME=Loading the SQL terminal in background... +PRESERVESQL_STARTUP_LOADING_FAILED=Terminals data load failed. +PRESERVESQL_STARTUP_LOADING_FINISHED=Terminals data load completed. +PRESERVESQL_STARTUP_MAX_TAB_REACHED=Maximum number of tabs limit is reached. Further Tabs will not be loaded. + +PRESERVE_SQL_GRACEFUL_EXIT_MSG=Saving unsaved changes... +PRESERVESQL_PERIODIC_JOB_NAME=Periodic AutoSave Job... +PRESERVESQL_JSONEXCEPTION=Json parsing failed. Invalid json data. +PRESERVESQL_FOLDERCREATEDELETEEXCEPTION=Folder create/delete failed. +PRESERVESQL_FILEREADEXCEPTION=File read failed. +PRESERVESQL_FILEENCODINGEXCEPTION=File data encoding failed. +PREFERENCE_AUTOSAVE=Auto Save +PREFERENCE_ENABLE_AUTOSAVE=Auto Save +PREFERENCE_INTERVAL_AUTOSAVE=Interval +PREFERENCE_INTERVAL_AUTOSAVE_RANGE=minutes (Range: {0}-{1}; Default: {2}) +PREFERENCE_ENABLE_ENCRYPTION=Encryption +PREFERENCE_INTERVAL_ERROR_MSG=Invalid interval: Range ({0}-{1}) minutes. +SESSIONSETTINGS_PREFPAGE_UNSAVEDCHANGED_TITLE=Update Session Settings +PRESERVESQL_PERIODIC_SAVE_FINISHED=Auto save completed: {0}. +PRESERVESQL_PERIODIC_SAVE_TAB_STATUS=Auto save completed: {0}. +PRESERVESQL_FILEWRITEEXCEPTION=File write failed. +PREFERENCE_AUTOSAVE_DESC=Auto saves unsaved information in SQL Terminal and Procedure/Function Viewer as per\n the time interval defined in Interval field. +PREFERENCE_INTERVAL_DESC=Sets the time interval for auto save operation. +PREFERENCE_ENCRYPTION_DESC=Encrypt the saved data as result of auto save. + +MAX_CHARATCTERS_ALLOWED_FOR_TABLE_DESC=Maximum 5000 characters allowed for table description. +# TRANSLATION FOR ENCODING ENCODING STARTS + +ENCODING_QUERY_RESULT_DATA_ENCODING_HEADER=Result Data Encoding +ENCODING_QUERY_RESULT_DATA_ENCODING_BODY=Include result data encoding +ENCODING_QUERY_RESULT_DATA_ENCODING_DESC=Result data encoding option will be available in edit table, view table, and query results. +# TRANSLATION FOR ENCODING ENCODING ENDS +BUILD_TIME=Build Time: + +TEXTMODE_QUERY_RESULT_DATA_TEXTMODE_HEADER=Result Data Text Mode +TEXTMODE_QUERY_RESULT_DATA_TEXTMODE_BODY=Include result data TextMode +TEXTMODE_QUERY_RESULT_DATA_TEXTMODE_DESC=Result data Text Mode option will be available in query results(Supports maximum to {0} characters of data). + +PREF_FORMATTER_SETTING = Formatter +FORMATTER_NODE = Formatter + +FORMATTER_PREFPAGE_UNSAVEDCHANGED_TITLE= Update Formatter Settings +BUILD_TIME_UNKNOWN=Unknown +EXPORT_FAIL_PROCESS_INTRUPTED_WITHOUT_SERVER_MSG= Export/show DDL process failed. +EXPORT_FAIL_PROCESS_TITLE=Show DDL Error + +#FUNCTION CHANGE INTIMATION +FUNCTN_CHANGE_TITLE=Function/Procedure Modified +FUNCTN_CHANGE_MSG=Source code has been changed in server. Refresh to update code from server; Overwrite to save your changes to the server. +FUNCTN_CHANGE_REFRESH=&Refresh +FUNCTN_CHANGE_OVERWRITE=&Overwrite +FUNCTN_CHANGE_CANCEL=&Cancel +FUNCTN_CHANGE_VIEWSOURCE_MSG=Source code has been changed in server. Do you want to refresh source code to match with server changes? +FUNCTN_CHANGE_PREVIEW=Server Code Previe&w: +FUNCT_CHANGE_VIEWSOURCE_ERR=An error occurred while getting source code. Refresh Object Browser and try again.\n Server Message: +FUNCT_CHANGE_COMPILE_ERR=An error occurred while compiling function/procedure.\n Server Message:{0} \n {1} +FUNCT_CHANGE_EXECUTE_ERR=An error occurred while executing function/procedure. Refresh Object Browser and try again.\n Server Message: +FUNCT_CHANGE_ERR_COMPILE_BACKEND=The function/procedure has been dropped. Do you want to compile the changes? + +# TRANSLATION FOR TEMP TABLE SUPPORT +SQL_TERMINAL_REUSE_CONNECTION_TOOLTIP = Reuse Connection: ON\nReuse SQL Terminal DB connection for all services (Resultset Refresh, Data Export, Commit Changes \u2026) in this terminal. +SQL_TERMINAL_NEW_CONNECTION_TOOLTIP = Reuse Connection: OFF\nCreate and use new DB connections for all services (Resultset Refresh, Data Export, Commit Changes \u2026) in this terminal. +MPPDBIDE_DIA_BTN_RECONNECT=Reconnect +MPPDBIDE_DIA_BTN_RECONNECT_CONTINUE=Reconnect and Execute +MULTIPLE_CONNECTION_ATTEMPT_ON_CRITICAL_ERROR=Failed to establish connection after multiple attempts. Database disconnected from Object Browser. Connect and try again. +CONNECTION_ATTEMPT_ON_CRITICAL_ERROR=An error occurred during execution.\nNote:\n\tReconnect - Reestablish connection.\n\tReconnect and Execute - Reestablishes connection and executes.\n\tCancel - Disconnects database in Object Browser and terminates associated \n\tSQL Terminal connections. +RECONNECT_FOR_EXECUTION_PLAN_VISUAL_EXPLAIN=An error occurred during execution. Do you want to reestablish connection?\nNote:\n\tOK - Reestablishes connection and executes.\n\tCancel - Disconnects database in Object Browser. +PROPERTIES_CONSTRAINT_CONSTRAINTNAME=Constraint Name +PROPERTIES_CONSTRAINT_COLUMNS=Constraint Columns +PROPERTIES_CONSTRAINT_TYPE=Constraint Type +PROPERTIES_EXPRESSION=Expression +PROPERTIES_CONSTRAINT_ISDEFFERED=Is Deferred +PROPERTIES_CONSTRAINT_SCHEMA=Schema +PROPERTIES_TABLESPACE=Tablespace +PROPERTIES_COLUMNS_COLUMNSNAME=Column Name +PROPERTIES_COLUMNS_DATATYPE=Data Type +PROPERTIES_COLUMNS_ISNULLABLE=Is Nullable +PROPERTIES_COLUMNS_COMMENTS=Comments +PROPERTIES_INDEX_INDEXNAME=Index Name +PROPERTIES_INDEX_INDEXCOLUMNS=Index Columns +PROPERTIES_INDEX_ISUNIQUE=Is Unique +PROPERTIES_PARTITION_PARTITIONNAME=Partition Name +PROPERTIES_PARTITION_PARTITIONBOUNDARIES=Partition Boundaries + +#Windows 10 Issue +CREATE_FILE_FAIL_ERR = Creation of file failed. +CREATE_FOLDER_FAIL_ERR = Creation of folder failed. +RECONNECT_SUCCESSFUL_MSG=Connection reestablished successfully... +RECONNECT_ATTEMP_FAILURE_MSG=Connection failed. Click Ok to reestablish connection. + +# Edit Query Results +RESULTSET_EDITABLE_MSG = Query Results can be edited. +RESULTSET_NON_EDITABLE_MSG = Query results cannot be edited. +RESULTSET_ALL_DATALOAD_MSG = Query results cannot be edited(Text data has reached the maximum characters limitation,load data{0}lines). + +#TRANSALATION FOR DB TYPES +LBL_DBTYPE =Database Type + +OPEN_GAUSS = openGauss + +#Export Excel +ERROR_EXPORT_EXCEL_RESULTSET = Fetching result set failed. +ERROR_EXPORT_EXCEL_PARSER = Parsing of date datatype failed. Converting to default string datatype. +ERR_EXPORT_TABLE_FAIL = Error exporting data from table: {0}.{1} +ERR_EXPORT_EXCEL_OPERATION = Error while exporting current page.{0}Error:{1} + +ERROR_EXCEL_ROW_COLUMN_LIMIT = Exporting to Excel Failed.\n Note: \nxlsx: Supports maximum of 1 million rows and 16384 columns.\nxls: Supports maximum of 64K rows and 256 columns. +EXPORT_INFORMATION = Export Parser Failure Info + +VERSION_NO_INCOMPATIBLE=Version Number not compatible. +#SQL Terminal right click menu related +SQL_TERMINAL_RIGHT_CLICK_MENU_ITEM_FORMAT = Format + +#Execution Progress Bar in Terminal/Editor +EXECUTION_DYANMIC_TIME_LABEL = Executing - +EXECUTION_ELAPSED_TIME_LABEL = Elapsed Time : + +#menu in ResultSet +COPY_TO_EXCEL_RESULT_WINDOW_MENU = Copy to Excel +COPY_TO_EXCEL_XLS_RESULT_WINDOW_MENUITEM = Copy as xls.. +COPY_TO_EXCEL_XLSX_RESULT_WINDOW_MENUITEM = Copy as xlsx.. +SEARCH_RESULT_WINDOW_CONTENTS = Search +SET_NULL_RESULT_WINDOW_CONTENTS = Set Null +RIGHT_CLICK_COPY_ADVANCED_RESULT_WINDOW_CONTENTS = Advanced Copy +RIGHT_CLICK_COPY_RESULT_WINDOW_CONTENTS = Copy +RIGHT_CLICK_COPY_TO_CLIPBOARD_RESULT_WINDOW_CONTENTS = Copy Data +RIGHT_CLICK_EXPORT_RESULT_WINDOW_CONTENTS = Export +RIGHT_CLICK_EXPORT_ALL_DATA_RESULT_WINDOW_CONTENTS = All Pages +RIGHT_CLICK_EXPORT_CURRENT_PAGE_DATA_RESULT_WINDOW_CONTENTS = Current Page +COPY_TO_EXCEL_RESULT_FILE_NAME = tmp +ERR_OPEN_IN_EXCEL_OPERATION = Error while copying to excel.{0}Error:{1} +EXPORT_OPEN_IN_EXCEL_PROGRESS_NAME=Copying to excel: {0} +RIGHT_CLICK_GENERATE_INSERT_RESULT_WINDOW_CONTENTS = Generate SQL +RIGHT_CLICK_SELECTED_ROW_INSERT_RESULT_WINDOW_CONTENTS = Selected Line +RIGHT_CLICK_CURRENT_INSERT_RESULT_WINDOW_CONTENTS = Current Page +RIGHT_CLICK_ALL_DATA_INSERT_RESULT_WINDOW_CONTENTS = All Pages +GENERATE_SQL_SUCCES_DAILOG_TITLE=Generate Sql Successfully +GENERATE_INSERT_SQL = Generate Insert Data from :{0} tab +ERR_GENERATE_INSERT_SQL = Error while generating sql.\nError : +ERR_GENERATE_INSERT_SQLL_OPERATION = Error while generating sql.{0}Error:{1} + +DIRTY_GENERATE_INSERT_DIALOG_SAVE_FILE_ERROR = Failed to save Sql "{0}". +GENERATE_INSERT_ERROR = Generate sql error +ERR_UI_GENERATE_INSERT_ERROR =Error while generating sql. +ERR_UI_SEARCH_ERROR=Failed to perform search in Text Mode. +GENERATE_INSERT_ALL_RESULTDATA_PROGRESS_NAME = Generating all pages sql: {0} +MSG_TOTAL_ROWS_EXPORT_INSERT_SQL = Total rows exported: {0} + +# User Role Management +USER_ROLE_GROUP_DISPLAY_NAME = Users/Roles +GRANT_REVOKE_WIZARD = Grant/Revoke +GRANT_REVOKE_WIZARD_OBJECT_SELECTION = Object Selection +GRANT_REVOKE_WIZARD_PRIVILEGE_SELECTION = Privilege Selection +GRANT_REVOKE_WIZARD_SQL_PREVIEW = SQL Preview + +USER_ROLE_TAB_COLUMN_TITLE_PROPERTY = Property +USER_ROLE_TAB_COLUMN_TITLE_VALUE = Value + +USER_ROLE_NAME = Name + +USER_ROLE_CONNECT_LIMIT = Connection Limit +USER_ROLE_VALID_BEGIN = Begin Date +USER_ROLE_VALID_UNTIL = End Date +USER_ROLE_CREATE_ROLE = Create Role +USER_ROLE_CREATE_DB = Create Database +USER_ROLR_INHERIT = Inherit +USER_ROLE_REPLICATION = Replication +USER_ROLE_CAN_LOGIN = Login +USER_ROLE_SYSTEM_ADMIN = System Admin +USER_ROLE_RESOURCE_POOL = Resource Pool +USER_ROLE_COMMENT = Description(Max 4000 chars) +USER_ROLE_COMMENT_ERROR_MESSAGE = Maximum 4000 characters allowed for user/role description. +USER_ROLE_PROPERTY_TAB_GENERAL = General +USER_ROLE_PROPERTY_TAB_PRIVILEGE = Privilege +USER_ROLE_PROPERTY_TAB_MEMBERSHIP = Membership +USER_ROLE_AUDITOR = Audit Admin +USER_ROLE_IS_LOCK = Lock +USER_ROLE_TAB_COLUMN_TITLE_USER_ROLE = User/Role +USER_ROLE_TAB_COLUMN_TITLE_BELONG_TO = Belong To +USER_ROLE_TAB_COLUMN_TITLE_IS_ENABLE = Enable +ERR_USER_ROLE_IS_NOT_EXIST = User/role of oid "{0}" no longer exists. +ERR_FETCH_USER_ROLE_LOCK_STATUS = Failed to fetch user/role (oid:{0}) account lock status. +ERR_USER_ROLE_ALTER_FAILURE = Failed to alter user/role. Reason:\r\n{0} +ERR_USER_ROLE_BEGIN_DATE_NULL = Begin date cannot be empty +ERR_USER_ROLE_VALID_UNTIL_DATE_NULL = End date cannot be empty +USER_ROLE_PREVIEW_SQL_CONFIRM = Update User/Role Properties +GRANT_REVOKE_PLS_SELECT_OBJECT = Select at least one object +GRANT_REVOKE_PLS_SELECT_USER_ROLE = Select at least one user/role +GRANT_REVOKE_PLS_SELECT_PRIVILEGE = Select at least one privilege +UPDATE_OBJECT_PRIVILEGE_DIALOG_TITLE = Grant/Revoke Privilege +ERR_UPDATE_OBJECT_PRIVILEGE_DETAIL = Failed to grant/revoke object privilege. +SUCCESS_UPDATE_OBJECT_PRIVILEGE_DETAIL = Granted/revoked object privileges successfully. + +UPDATE_OBJECT_PRIVILEGE_DIALOG_DIFF_OBJECT_TYPE = Batch grant/revoke is supported only with same object type within a schema. +GRANT_REVOKE_SELECT_ALL_OBJECT = Select all objects +GRANT_REVOKE_SEARCH_OBJECT = Search by object name +GRANT_REVOKE_ROLE = Role +GRANT_REVOKE_GRANT_OPTION = Grant +GRANT_REVOKE_REVOKE_OPTION = Revoke +USER_ROLE_PREVIEW_SQL_CHANGE_NOTHING = There are no changes to be saved. +STATUS_MSG_MODIFYING_OBJECT_PRIVILEGE = Modifying Object Privilege... +ERR_USER_ROLE_CONNECT_LIMIT_INVALID = Only integer values allowed in Connection Limit. +USER_ROLE_PREVIEW_SQL_CONFIRM_MESSAGE = The following SQL will be sent to the server to change the user/role properties. Please confirm. +ERR_USER_ROLE_NAME_EMPTY = User/role name can not be empty. +SHOW_USER_ROLE_DDL_NO_DATABASE = There are no connected database. +SHOW_USER_ROLE_DDL_ERROR = Failed to show user/role DDL. +SHOW_USER_ROLE_DDL_JOB_NAME = Showing user/role DDL-{0} +CREATE_USER_ROLE_NO_DATABASE = There are no connected database. + +EXPORT_ALL_DATA_NOT_ENOUGH_SPACE = There is not enough space on the disk + +PARTIAL_SUCCESS_UPDATE_OBJECT_PRIVILEGE_DETAIL = Granted/revoked object privileges successfully. Click Details to view additional information. + +CREATE_NEW_ROLE=Create User/Role +CREATE_USERROLE_FINISH_BTN=Finish +CREATE_USERROLE_NEXT_BTN=Next +CREATE_USERROLE_BACK_BTN=Back +CREATE_USERROLE_CANCEL_BTN=Cancel +CREATE_USERROLE_ENTER_NM=Enter user/role name +CREATE_USERROLE_NAME_INVALID=User/role name is invalid +CREATE_USERROLE_NAME_EXCEED_MAX=Maximum 63 characters allowed for user/role name +CREATE_USERROLE_ENTER_PAS=Enter password + +CREATE_USERROLE_CREATE_ERROR=Error creating user/role: {0} +USER_ROLE_NM_PAS=User/Role Properties +CREATE_USERROLE_NAME=Name +CREATE_USERROLE_CIPHER=Password +CREATE_USERROLE_PRIVILEGE=Privileges +CREATE_USERROLE_SYSADMIN=System Administrator +CREATE_USERROLE_AUDITADMIN=Audit Administrator +CREATE_USERROLE_CREATEDB=Create DataBase +CREATE_USERROLE_CREATEROLE=Create Role +CREATE_USERROLE_INHERIT=Inherit +CREATE_USERROLE_LOGIN=Login +CREATE_USERROLE_REPLICATION=Replication +USER_ROLE_PRIVILEGE_OPTION=More Privileges Option +CREATE_USERROLE_CONNECT_LIMIT=Connection Limit +CREATE_USERROLE_VALID_BEGIN=Start Date +CREATE_USERROLE_VALID_UNTIL=End Date +CREATE_USERROLE_RES_POOL=Resource Pool +CREATE_USERROLE_ROLE_GROUP_MEMBER=Role Group +CREATE_USERROLE_ADMIN_GROUP_MEMBER=Administrator Group +CREATE_USERROLE_CREATE_SUCCESS=Created user/role: {0} +DROP_ROLE_DIA_TITLE=Drop User/Role +DROP_ROLE=Are you sure you want to drop user/role {0}? +DROP_USERROLE_PROGRESS_NAME=Dropping user/role: {0}@{1} +DROP_USERROLE_SUCCESS=Dropped user/role: {0} +CREATE_USERROLE_NO_PRIVILEGE=No Privilege +CREATE_USERROLE_NO_PRIVILEGE_CREATE=You do not have the privilege to create new user or role. +ENTER_ROLE_NAME=Enter Role Name +ENTER_CIPHER=Enter Password +CREATE_USERROLE_PAS_NOT_MATCH=Inconsistent passwords entered two times +ENTER_CIPHER_TWICE=Re-enter Password +CREATE_USERROLE_ALL=All +CREATE_USERROLE_SSL_NOT_ENABLE=The connection is not secure, because SSL is disabled. +PRIVILEGE_ADVANCED=Advanced +STATUS_MSG_DROP_ROLE=Dropping User/Role... +DROP_USERROLE_ERROR=Drop User/Role +DROP_USERROLE_UNABLE=Unable to drop user/role. +DROP_USERROLE_UNABLE_MSG=Error dropping user/role: {0}@{1} + +EXPORT_ALL_DATA_DISABLE_TOOLTIP=Disabled for EXPLAIN query + +CREATE_USER=User +CREATE_ROLE=Role + +UNKNOW_CLOB_TYPE= Unknown type + +EXCEL_ROW_LIMIT_REACHED= Export successful for maximum rows.\n Note: \nxlsx: Supports maximum of 1 million rows.\nxls: Supports maximum of 64K rows. +#Need no translate the below message as it is used internally +MAXIMUM_EXCEL_ROW_REACHED=Maximum excel row limits reached +SQL_QUERY_SETTING_ZERO_DATA_HEADER=Setting Query count to 0 +SQL_QUERY_SETTING_ZERO_DATA_BODY=Setting query size to zero saves the complete query in the history. This could increase the disk space usage. Do you want to save the changes? +SQL_QUERY_SETTING_COMBO_DATA_BODY=Setting the query size to zero and decreasing the value entered in the SQL History Queries field may result in loss of SQL history queries and increase the disk space usage. Do you want to continue? + +#Save/Save As +CONNECTION_OPTION_DIALOG_TITLE = Database Connections +DIRTY_TERMINAL_DIALOG_TITLE = Saving File Terminal +DIRTY_TERMINAL_DIALOG_SELECT_ALL_BUTTON = Select All +DIRTY_TERMINAL_DIALOG_DESELECT_ALL_BUTTON = Deselect All +DIRTY_TERMINAL_DIALOG_SELECTION_MESSAGE = Select the terminals to save: +FILE_UPDATE_CONFLICT_DIALOG_TITLE = Update Conflict +FILE_UPDATE_CONFLICT_DIALOG_DETAIL = The file "{0}" has been changed on the file system. Do you want to overwrite the changes made on the file system? +DIRTY_TERMINAL_DIALOG_SAVE_BUTTON = Save +DIRTY_TERMINAL_DIALOG_NOT_SAVE_BUTTON = Don't Save +DIRTY_TERMINAL_DIALOG_SAVE_WARNING = "{0}" has been modified. Save changes? +DIRTY_TERMINAL_DIALOG_SAVE_FILE_ERROR = Failed to save file "{0}". + +#TABLE PROPERTIES +OLAP_PROP_COLUMNTAB_DATATYPE=Data Type +OLAP_PROP_COLUMNTAB_ISNULLABLE=Is Nullable +OLAP_PROP_KEYTAB_TYPE=Type +OLAP_PROP_KEYTAB_COLUMNS=Columns +OLAP_PROP_KEYTAB_REFERENCINGTABLE=Referencing table +OLAP_PROP_KEYTAB_REFERENCINGCOL=Referencing columns +OLAP_PROP_KEYTAB_ONDELETE=On delete +OLAP_PROP_KEYTAB_DEFERRABLE=Deferrable +OLAP_PROP_KEYTAB_DEFERRED=Deferred +OLAP_PROP_KEYTAB_VALIDATED=Validated +OLAP_PROP_INDEXTAB_COLUMNS=Columns +OLAP_PROP_INDEXTAB_ISUNIQUE=Is Unique +OLAP_PROP_INDEXTAB_TABLESPACE=Tablespace +OLAP_PROP_CHECKTAB_CONDITION=Condition +OLAP_PROP_CHECKTAB_ENABLED=Enabled +OLAP_PROP_CHECKTAB_DEFERRABLE=Deferrable +OLAP_PROP_CHECKTAB_DEFERRED=Deferred +OLAP_PROP_CHECKTAB_VALIDATED=Validated +OLAP_PROP_PARTITIONTAB_TYPE=Partition Type +OLAP_PROP_PARTITIONTAB_KEYS=Partition Keys +PROPERTIES_CHECKS_TAB=Checks +PROPERTIES_DISTRIBUTION_TAB=Distribution +PROPERTIES_KEYS_TAB=Keys + +RESULT_WINDOW_EDITTABLE_COMMIT_NONEXECUTED=/NonExecuted: {0} + +OLAP_PROP_PARTITIONTAB_PARTITIONVALUE=Partition Value +OLAP_PROP_PARTITIONTAB_TABLESPACENAME=Tablespace + +EDIT_TABLE_PROPERTIES_DATA_DROPPED_REFRESH_ERROR=An error occurred while editing.\n Unable to edit as the object has been modified/dropped/connection is lost.\n Reopen properties window. + +DATA_TOO_LARGE_DISPLAY_EDIT =Data is too large to display.\nPlease copy the cell data and paste to another Editor to view or modify it.\nModified data should be pasted back. +DATA_TOO_LARGE_WARNING = Data length warning + +NEW_OBJECT_WILL_BE_OPENED=New Function/Procedure will be opened + +CURSOR_IMPLEMENT_DIALOG_TITLE = Query Execution +CURSOR_IMPLEMENT_DIALOG_HEADER = Pagination cannot be supported for this particular query result. Do you want to continue? +CURSOR_FAILURE_SQL_ERROR=SQL Error Code +COLUMN_DEFAULT_VALUE_EXPRESSION = Is Default Expression + +REFRESH_TABLE_LABEL_FAILURE = Loading columns failed +REFRESH_TABLE_LABEL_SUCCESS = Columns loaded +REFRESH_TABLE_LABEL_IN_PROGRESS = Loading columns... + +CREATE_TABLE_DDL_TAB = DDL +FAILED_TO_OPEN_FILE_TITLE= Failed to open file +FAILED_TO_OPEN_FILE_MESSAGE= Error : No application is associated with the specified file for this operation. + +FAILED_TO_OPEN_FILE_MESSAGE= Error : No application is associated with the specified file for this operation. +ERR_START_TRANSACTION_FAILED = An error occurred while starting transaction. + +ERR_ROLL_BACK_TRANSACTION_FAILED = An error occurred while rolling back transaction. +PREF_TRANSACTION_SETTING=Transaction +PREF_TRANSACTION_AUTOCOMMIT=Auto Commit +AUTOCOMMIT_ENABLE=Enable +AUTOCOMMIT_DISABLE=Disable +TRANSACTION_DIALOG_TITLE=Transaction in progress +TRANSACTION_DIALOG_BODY=Below SQL terminals have transaction in progress, please commit or rollback them firstly. +TRANSACTION_COMMIT_FEEDBACK=Commit success +TRANSACTION_ROLLBACK_FEEDBACK=Rollback success +TRANSACTION_OPERATION_EXCEPTION_TITLE=Transaction operation failure +TRANSACTION_COMMIT_EXCEPTION_BODY = Commit failure +TRANSACTION_ROLLBACK_EXCEPTION_BODY =Rollback failure +TRANSACTION_RESET_BUTTIONS_EXCEPTION=Reset commit and rollback buttons status failure +TRANSACTION_OPERATION_TOGGLE_TITLE=Transaction operation +AUTOCOMMIT_ENABLE_DESC=Enabled auto commit feature, transaction will be committed automatically. +AUTOCOMMIT_DISABLE_DESC=Disabled auto commit feature, user need to commit or rollback transaction manually. +TRANSACTION_DIALOG_OK_BUTTION=OK +TRANSACTION_COMMIT_JOB=Manual submission is in progress +TRANSACTION_ROLLBACK_JOB=Manual rollback is in progress + +TRANSACTION_COMMIT_TOOL_TIP = Commit +TRANSACTION_ROLLBACK_TOOL_TIP = Rollback +TRANSACTION_COMMIT_CONFIRMATION = Commit current transaction? +TRANSACTION_ROLLBACK_CONFIRMATION = Rollback current transaction? +NO_TRANSACTION_COMMIT_ROLLBACK_TOGGLE = No Transaction is in progress +RESULT_TAB_CONNECTION_LOST_ERR_MSG = An error occurred.\nUnable to perform the operation\nas the object is modified/dropped/connection lost\nReopen ResultTab window + +SHOW_SEQUENCE_DDL_CANCELING = Canceled show sequence DDL: {0}.{1} +SHOW_SEQUENCE_DDL_PROGRESS_NAME = Showing DDL for sequence: {0} +SHOW_SEQUENCE_DDL_FAILED = Error showing sequence DDL: {0}.{1} +BATCH_EXPORT_NO_RELATION_PREVILAGE = Permission denied for relation of exported database object. + +PREFERENCE_COMMAND_OPEN_NEW_TERMINAL=Open Terminal +OPEN_NEW_TERMINAL=Open New SQL Terminal +SHORTCUT_KEY_ALREADY_EXIST=The shortcut key already used in:" +SELECT_SHORTCUT_KEY_AGAIN="Please select another one! +SHORTCUT_KEY_DUPLICATE=Duplicate shortcut key + +EXECUTE_DEBUGE = Function Execution +WRITE_HERE= write text in here: + +PARAMETER_INPUT_TABLE_PARAM_NAME_COLUMN = Name +PARAMETER_INPUT_TABLE_PARAM_TYPE_COLUMN = Data Type +PARAMETER_INPUT_TABLE_PARAM_VALUE_COLUMN = Value + +OPERATION_CANNOT_BE_PERFOREMD_TITLE = Operation cannot be performed. + +ERROR_IMPORTING_CONNECTION_PROFILES = Error while importing the profiles +EXPORTING_CONNECTION_PROFILES = Exporting connection profiles +IMPORTING_CONNECTION_PROFILES = Importing connection profiles + +EXPORT_CONNECTION_PROFILE_DIALOG_HEADER = Export Connection Profiles +EXPORT_CONNECTION_PROFILE_DIALOG_GROUP = Connections +EXPORT_CONNECTION_PROFILE_SUCCESS_MESSAGE=Exported files successfully +EXPORT_CONNECTION_PROFILE_LOAD_ERR_MSG = Error while loading the file for export +EXPORT_CONNECTION_PROF_LOADING_STATUS_MESSAGE = Load connection profiles +IMPORT_CONNECTIONS_LOADING_STATUS_MSG =Importing connections +IMPORT_CONNECTIONS_PROFILE_DIALOG_HEADER = Import Connection Profiles +IMPORT_CONNECTIONS_PROFILE_ERR_MSG=error while importing the file +IMPORT_CONN_PROFILE_REPLACE_LABEL = Replace +IMPORT_CONN_PROFILE_KEEP_BOTH_FILES_LBL=Copy,but keep both files +IMPORT_CONN_PROFILE_DONT_CPY_LBL=Don't Copy +IMPORT_CONN_PROFILE_CONFLICTS_LBL=Do this for all conflicts + +IMPORT_PROFILE_INCORRECT_FILE =Invalid file format, please import the correct connection profile. +IMPORT_CONNECTIONS_PROFILE_INVALID_FORMAT_EXCEPTION=Exception occurred while importing the connection profiles + +PROCESS_TIMEOUT_ERROR=Process has timeout.\nPlease check the preference page (Settings/preferences/ExportImport/ExportDDL) and set a higher timeout for process. +EXPORT_TIMEOUT=Export Timeout +DEFAULT_TIMEOUT=Default Timeout +CUSTOM_TIMEOUT=Custom Timeout +SECONDS=Sec + +ROLLBACK_COMPLETED = Rollback Completed + +RENAME_TABLESPACE_FAILED = Rename Tablespace Failed + +ERR_FETCH_RESULT_SET_COLUMN_COMMENT = Failed to get comment of result set column. + +FILE_LIMIT_WARNING_MESSAGE = Data Limit exceeded.\nplease check the preference page (Settings/preferences/Environment/Session Setting) and set the Data Limit +FILE_LIMIT = File Limit +FILE_LIMIT_HEADER = Data Limit Warning +IMPORT_TABLE_DATA_LIMIT = Import Table Data Limit +IMPORT_FILE_DATA_LIMIT = Import File Data Limit +IMPORT_BYTEA_DATA_LIMIT = Import Bytea Data Limit +SUFFIX_DATA_LIMIT = MB (0 is Unlimited) +IMPORT_UNLIMITED_NOTE = NOTE : Choosing file import size as 0 will cause delay in importing + +#LAZY RENDERING +SHOW_MORE_OBJECTS=More Objects... +LAZY_RENDER_PREFERENCE_GROUP_NAME= Lazy Rendering +LAZY_RENDER_OBJECT_COUNT_LABEL = Number of objects in a batch +LAZY_RENDER_SUFFIX_LABEL = (Range: 1000-1,00,000; Default: 10,000) +LAZY_RENDERING_ERROR_MSG = Invalid Range. ({0}-{1}) + +INVALID_EXTENSION_HEADER = INVALID FILE EXTENSION +INVALID_EXTENSION_MESSAGE = Select valid file extensions only. +IMPORT_TABLE_FILE_INVALID_DATA_LIMIT = Import Table/files Data Limit value should not be empty + +VALIDATE_CIPHER_FAIL = Validate Failure + +#olap table excell format import +IMPORT_DATA_FORMAT = Data conversion +IMPORT_EXCEL_DATE = Date format: +IMPORT_EXCEL_NUM = Number format: +IMPORT_EXCEL_CHAR = Character format: +IMPORT_RESULT_INVALID_CONNECTION = Connection for this Import Result Data is not valid .Import Data can not be continued. +ENCODING_NOTE = NOTE: Select the same encoding format as the imported file data. Otherwise, the import may fail or garbled characters will be displayed. +OPTION_ZIP=(.zip) +COMPRESS_FAIL_DAILOG_TITLE = Data Compress failed +COMPRESS_FAILED = compress failed +SQL_DDL_EXPORT_WINDOW_TITLE = Export DDL +SQL_DDL_DATA_EXPORT_WINDOW_TITLE = Export DDL and Data +GENERATE_SQL_EXPORT_WINDOW_TITLE = Generate SQL : {0} +INVALID_TEMP_ENVIRONMENT_VARIABLE = The value of TEMP environment variable setup is invalid. It should be an existing directory path. +ERR_ZIP_EXPORT_DAILOG_TITLE=Exporting Failure +ERR_ZIP_EXPORT_DAILOG_DESC = Error while exporting data.{0}Error: {1} + +#column level comment +CREATE_CLM_COMMENT=Description +ENTER_COL_DESCRIPTIONS_TEXT=Description of Column(Max 5000 chars) +DESCRIBE_IMPACT_OF_COLUMN_SEQUENCE = The sequence of columns in the imported file must be the same as that of the selected columns. + +LOAD_MORE_RECORD_TOOL_ITEM = Load More Record +ERR_REMOVE_TARGET_SESSION_FAILED = To initialize target session as normal session Failed +ERR_ATTACH_TARGET_SESSION_FAILED = Attach target session Failed +ERR_BL_QUERY_EXEC_STATUS_FAILED = An error occurred while execute function/procedure. + +RESULT_WINDOW =Result Window +RESULT_TAB_GENERATE_NEW =Overwrite ResultSet +RESULT_TAB_RETAIN_CURRENT =Retain Current +RESULT_TAB_GENERATE_NEW_HINT =Current result set window/s (if any opened) will be closed and new result set window/s will be opened +RESULT_TAB_RETAIN_CURRENT_HINT =New result set window/s will be opened retaining already opened result set window/s + +BUTTON_OVERWRITE_RESULTSET_TOOLTIP =Compile/Execute Statement in New Tab + +ERR_IMPORT_TABLE_TO_EXCEL = Error while importing table data. +PREPARED_QUERY_RELATED_TABLE_FAILED = Preparing to query related table sql failed +PREPARED_QUERY_RELATED_SEQUENCE_FAILED = Preparing to query related sequence sql failed +AUTO_COMPLETE_SETTING = Auto Suggest +AUTO_COMPLETE_MIN_SIZE = Minimum characters for Auto suggest +AUTO_COMPLETE_MIN_SIZE_DESC = This field is for setting minimum characters required to trigger auto suggest \ + \n on user type +AUTO_SUGGEST_ERROR_MSG=Invalid input for Auto Suggest minimum characters +PREPARED_QUERY_RELATED_SEQUENCE_FAILED = Preparing to query related sequence sql failed + +MPPDBIDE_DIA_BTN_DISCARD_ALL = Discard All + +PREF_FOLDING_SETTING = Folding +PREF_FOLDING_ENABLE_DESC = Enable SQL folding feature. Supported SQL statements can be folded/unfolded. +PREF_FOLDING_DISABLE_DESC = Disable SQL folding feature. +PREF_FOLDING_DESC = Change in settings will reflect in newly opened editor. Already opened editors will remain with previous setting until restart. + +ERR_WRITE_FILE = Happened an error during writing file. + +#font preference +PREF_FONT_SETTING = Font +PREF_FONT_STYLE = Font Setup +PREF_FONT_STYLE_SIZE = Size: +PREF_FONT_STYLE_SIZE_EXPLANATION = (Range: 1-50) + +ERR_DELETE_FILE_MSG = Error while deleting file. +PREF_FONT_STYLE_SIZE_EXPLANATION = (Range: 1-50; Default: 10) +FILTER_INTIAL_TEXT=Provide filter text and press Enter key... + +ERR_IMPORT_DATE_FORMAT = Incorrect date format. Please try again. +ERR_IMPORT_DATA_FILE = The imported file does not exist. +FILTER_CLEAR_TOOLTIP=Clear +ERR_IMPORT_DIFF_FILE_FORMAT = The format of the imported file is different from the selected format. + +LOCALE_CHANGE_APP_EXIT_MSG=All connections will be closed and any unsaved data will be lost. Are you sure you want to exit? +LOCAL_CHANGE_EXIT_NOTE_YES= Yes : Manually reopen application for updated language . +ERR_INVALID_CONNECTION_NAME=Invalid connection name, Please enter valid connection name + +MSG_HINT_GUI_CONNECTION_OPEN_SOCKET_FAIL =\n4. Check whether the DB service is running normally and Data Studio running machine can telnet ip port of DB service. + +LOADING_DATA =Data is being loaded +LOADED_DATA =Data loading completed +FILE_SIZE_EXCEEDED_FOUR =The file size exceeds 4 MB. No preview is available. + +# view ER diagram +ER_JOB_DETAILS = Generating ER Diagram for the query + +ER_ERROR_POPUP_HEADER = ER Error +ER_DESC_PRIMARYKEY = PrimaryKey +ER_DESC_FOREIGNKEY = ForeignKey +ER_DESC_CURRENT_COLOR = Current Table +ER_DESC_RELATED_COLOR = Related Table +ER_VIEW_FAILED = Failed to view ER diagram +ER_VIEW_FAILED_MSG = Failed to view ER diagram for: {0} +ER_VIEW_INSUFFICIENT_PRIVILEGES_MSG = Insufficient Privileges to view ER diagram. \ + \n"grant select on SYS.SYS_CONSTRAINT_DEFS to " to view ER diagram. +VIEW_STYLES = View Styles +SHOW_ATTRIBUTES = Show Attributes +SHOW_ICONS = Show Icons +SHOW_DATA_TYPES = Show Data Types +SHOW_NULLABILITY = Show Nullability +SHOW_COMMENTS = Show Comments +SHOW_FULLY_QUALIFIED_NAMES = Show Fully qualified names +ATTRIBUTE_VIS_ALL = All +ATTRIBUTE_VIS_ANY_KEY = Any Keys +ATTRIBUTE_VIS_PRIMARY_KEY = Primary Key +ATTRIBUTE_VIS_NONE = None + +ERR_TEMPLATE_LOAD_FAILURE_TITLE=Template load Failure +PREF_LOAD_ERROR_TITLE=Preferences load Failure +ERR_PREFERENCE_LOAD_FAILURE_DETAIL=Clean disk space and restart the Data Studio + +#Synonyms start +SYNONYM_GROUP_NAME = Synonyms +CREATE_NEW_SYNONYM = Create New Synonym + +SYNONYM_NAME = Synonym Name +OBJECT_OWNER = Object Owner +OBJECT_TYPE = Object Type +OBJECT_NAME = Object Name +REPLACE_IF_EXIST = Replace if exist + +SYNONYM_NAME_ENTER_NM = Enter synonym name +SYNONYM_NAME_EXCEED_MAX = Maximum 64 characters allowed for synonym name +OBJECT_OWNER_SELECT_NM = Select object owner +OBJECT_TYPE_SELECT_NM = Select object type +OBJECT_NAME_SELECT_NM = Select object name +CREATE_SYNONYM_NO_DATABASE = There are no connected database. +CREATED_SYNONYM_SUCESS = Created synonym: {0}.{1} +CREATE_SYNONYM_ERROR = Error creating synonym: {0} +DROP_SYNONYM_CONFIRM_MSG = Are you sure you want to drop ''{0}'' synonym? +DROP_SYNONYM_TITLE = Drop Synonym +STATUS_MSG_DROP_SYNONYM = Dropping synonym... +DROP_SYNONYM_PROGRESS_NAME = Dropping synonym: {0}@{1} +DROP_SYNONYM_SUCCESS = Dropped synonym: {0}.{1} +DROP_SYNONYM_ERROR = Error while dropping synonym: {0}.{1} +DROP_SYNONYM_UNABLE = Unable to drop synonym. +PROPERTIES_SYNONYM_NAME = Synonym Name +PROPERTIES_SYNONYM_OWNER = Object Owner +PROPERTIES_OBJECT_OWNER = Owner +PROPERTIES_OBJECT_NAME = Object Name +#Synonyms end + +# Triggers start +TRIGGER_GROUP_NAME = Triggers +#Triggers end + +# DS Commandline parameter support start +DS_COMMANDLINE_ERROR = ERROR: +DS_COMMANDLINE_MANDATORY_PARAM_MISSING = 1 or more mandatory parameter is missing. Check if all following mandatory parameters are passed, +DS_COMMANDLINE_SSL_MODE_NOT_SUPPORTED = SSL mode is not supported for this server. +DS_COMMANDLINE_UNIDENTIFIED_PARAM = Unidentified parameter supplied. Supported parameters are, +DS_COMMANDLINE_DB_TYPE_PARAM_MISSING = dbType parameter is missing, add the parameter and retry. +DS_COMMANDLINE_INVALID_CONNECTION_NAME_VALUE = Invalid connectionName value. +DS_COMMANDLINE_INVALID_VALUE_LENGTH = {0} value length more than 63 characters. Try with shorter name. +DS_COMMANDLINE_NULL_VALUE_FOR_PARAM = Null value supplied for parameter {0}. Enter non-null value. +DS_COMMANDLINE_INVALID_FILE_PATH = File does not exits/ is a directory, for parameter {0}. Enter valid file path. +DS_COMMANDLINE_INVALID_HOST_PORT_VALUE = Invalid hostPort value. Enter positive integer value less than {0}. + +DS_COMMANDLINE_INVALID_SAVE_CIPHER_VALUE = Invalid value supplied for savePassword parameter. Value can be any of the following, +DS_COMMANDLINE_INVALID_SSL_ENABLE_VALUE = Warning: Invalid value for sslEnable parameter. Continuing with default option(false). +DS_COMMANDLINE_INVALID_SSL_MODE_VALUE = Invalid value supplied for sslMode parameter. Value can be any of the following, +DS_COMMANDLINE_ATTEMPTING_CONNECTION_MSG = Attempting connection using commandline arguments... +DS_COMMANDLINE_ENTER_CIPHER = Please enter password... +DS_COMMANDLINE_PRESS_ENTER_FOLLOWED_BY_CIPHER = Please press enter followed by password... +# DS Commandline parameter support end + +# Formatter preference start +FORMATTER_PREVIEW = Preview +FORMATTER_RIGHT_MARGIN = Max length per line +FORMATTER_INDENT = Indentation size +FORMATTER_USE_TAB_CHAR = Use +FORMATTER_TABS = Tabs +FORMATTER_SPACES = Spaces +FORMATTER_TAB_CHAR_SIZE = Tab size +FORMATTER_ALIGN_DECLARATION = Align type declarations +FORMATTER_ALIGN_ASSIGNMENTS = Align assignments operator +FORMATTER_THEN_ON_NEW_LINE = Line break before THEN +FORMATTER_LOOP_ON_NEW_LINE = Line break before LOOP +FORMATTER_SPLIT_AND_OR = AND/OR line break +FORMATTER_AND_OR_AFTER_EXP = AND/OR after where item +FORMATTER_AND_OR_UNDER = AND/OR under where keyword + +FORMATTER_DML = DML +FORMATTER_GENERAL = Common +FORMATTER_SELECT = SELECT +FORMATTER_INSERT = INSERT +FORMATTER_UPDATE = UPDATE +FORMATTER_OTHERS = Others +FORMATTER_LEFT_ALIGN_KEYWORDS = Left align keywords +FORMATTER_LEFT_ALIGN_ITEMS = Left align items +FORMATTER_FORMAT = Format +FORMATTER_ON_ONE_LINE = All items in one line +FORMATTER_ONE_PARAM_PER_LINE = Each item in new line +FORMATTER_FIT = Fit alignment of items +FORMATTER_ALIGN = Align +FORMATTER_COMMA_AFTER_ITEM = Comma after item + +FORMATTER_PARAMATER = Function/Procedure Parameters +FORMATTER_ALIGN_DATATYPES = Align datatypes +FORMATTER_COMMA_AFTER_DATATYPE = Comma after datatype +FORMATTER_LIST_AT_LEFT_MARGIN = List at left margin + +FORMATTER_IMPORT = Import +FORMATTER_EXPORT = Export + +FORMATTER_INVALID_FILE_SELECTED = Invalid file selected +FORMATTER_SELECT_VALID_JSON = Select a valid JSON file +FORMATTER_FILE_CREATION_ERROR_HEADER = File creation error +FORMATTER_FILE_READ_ERROR_HEADER = File read error +FORMATTER_FILE_CREATION_ERROR = Error occurred while writing formatter to disk +FORMATTER_FILE_READ_ERROR = Error occurred while reading formatter from disk +FORMATTER_ERROR_RESIDE_IN_FILE = Error resides within the file +# Formatter preference end + +FORMATTER_UNABLE_TO_PARSE_STMT = Unable to parse statement + +RESULT_TAB_COL_NAME = Name + +RESULT_TAB_COL_DATA_TYPE = Data Type + +RESULT_TAB_COL_PARAMETER_TYPE = Parameter Type + +CURSOR_DATA_NODE = Cursor Data + +RESULT_TAB_COL_VALUE = Value + +CURSOR_TOOLTIP_TEXT = double click to see the full data + +VOID_VALUE_TOOLTIP_TEXT = no value returned by server + +EDIT_TERMINAL_INPUT_VALUE = Edit Function/procedure input parameter values + +EDITOR_DATA_TAB = Data +EDITOR_IMAGE_TAB = Image +EDITOR_IMAGE_NOT_SUPPORTED = Not supported +EDITOR_DATA_INVALID_NUMBER_DIGITS = invalid hexadecimal data: odd number of digits +AUTO_REFRESH_SUCCESS_MSG=Auto refresh successful + +RESTORE_DEFAULTS = Restore Defaults +MAXIMUM_PREF_FILE_SIZE=Please check preference file size .Maximum preference file size is 5 MB + +MUTIPLE_MARKERS=Multiple markers at this line +RESULT_MANAGER=Result Manager + +PREF_RS_MAX_RESULT_WINDOW_INPUT_ERR_MSG=Invalid input for Maximum Result Window count.Enter a number between 100 and 300. +MAX_RESULT_SET_LBL=Max ResultSet : +MAX_RESULT_SET_RANGE=(Value Range 100-300) +MAX_RESULT_WINDOW_HINT= Set maximum result windows should be opened in one instance of Data Studio application. + +PREFERENCE_SHORTCUT_KEY_OVERWRITE_RESULTSET =Execute Statement in New Tab +PREFERENCE_SHORTCUT_KEY_OVERWRITE_RESULTSET_DESC =Execute statement in new tab retaining current tabs +COLUMN_LAYOUT_ERROR=Unknown column layout data + +IMPORT_EXPORT_LIMIT_PREF_TITLE=Parallel Import/Export Limit +IMPORT_EXPORT_LIMIT_PREF_RANGE =( Value Range : 0-20 ) +IMPORT_EXPORT_LIMIT_PREF_INFO=Number of Import/Export operations run in parallel .Unlimited Import/Export can be done if set value 0. +IMPORT_EXPORT_LIMIT_MSG_TITLE= Import/Export operations limit +IMPORT_EXPORT_LIMIT_MSG_INFO= Number of Import/Export parallel operations reached maximum limit. +IMPORT_EXPORT_LOGIN_FAILED = Login Failed +ERROR_POSITION_LABEL=Error Position +OBJECT_BROWSER=Object Browser +OBJECT_BROWSER_FILTER_TIMEOUT=Filter Timeout +OBJECT_BROWSER_FILTER_TIMEOUT_INFO= Set timeout period for filtering object browser.\ + \n Object browser filtering will be stopped after timeout period. +OBJECT_BROWSER_FILTER_TIMEOUT_ERR_MSG=Invalid object browser filter timeout +OBJECT_BROWSER_FILTER_TIMEOUT_ERROR= Object Browser filtering timeout occured.Check timeout period in Preference-->Object Browser-->Filter Timeout +OBJECT_BROWSER_FILTER_TIMEOUT_ERROR_TITLE=Filter timeout error +OBJECT_BROWSER_FILTER_FINISH_MSG=Filtering completed +OBJECT_BROWSER_FILTER_TIMEOUT_TOOLTIP_MESSAGE=Filter/Clear object browser filter is incomplete. Refresh connections: %s to get filtered objects. +LABEL_LOAD_CHILD_OBJECT=Load child objects of Tables and Views +FILE_SIZE_EXCEED_WARNING_MSG=The file size exceeds.\nPlease check the preference page (Settings/preferences/Environment/Session Setting) and set the File Data Limit +INVALID_LINE_SEPERATOR=Invalid line separator is set in environment variable. +ERROR_WHILE_FETCHING_OWNER_NAME=Error occurred while fetching owner name for database object +ERR_WHILE_FETCHING_SEQ_VALUE=Error occurred while fetching sequence data + +BREAKPOINT_ANNOTATION_LABEL=Breakpoint +DEBUG_POSITION_LABEL=Debug Position + +DEBUG_TABLE_ORDER = Order +DEBUG_STACK_INVOKING_LEVEL = Invoking level +DEBUG_STACK_FUNCTION_INFO = Function information +DEBUG_STACK_CURRENT_LINE_NUM = Current line number +DEBUG_BREAKPOINT_LINE_NUM = Line number +DEBUG_BREAKPOINT_STATEMENT = Statement +DEBUG_BREAKPOINT_ENABLE= Enable +DEBUG_VARIABLE_VARIABLE = Variable +DEBUG_VARIABLE_VALUE = Value +DEBUG_VARIABLE_DATA_TYPE = Data type +DEBUG_VARIABLE_PARAM_TYPE = Param type +DEBUG_NOT_SUPPORT_WARN = server not support debuger! +DEBUG_PREFREENCE_ID = Debug +DEBUG_PREFREENCE_WHEN_ROLLBACK = Use Rollback When Debug + +CREATE_FUNCTION_UI_CREATE_FUNCTION = Create Function +CREATE_FUNCTION_UI_CREATE_PROCEDURE = Create Procedure +CREATE_FUNCTION_UI_SQL_PREVIEW = SQL Preview +CREATE_FUNCTION_UI_SCHEMA = Schema(*) +CREATE_FUNCTION_UI_FUNCTION_NAME = Function Name(*) +CREATE_FUNCTION_UI_FUNCTION = Function +CREATE_FUNCTION_UI_PROCEDURE = Procedure +CREATE_FUNCTION_UI_LANGUAGE = Language(*) +CREATE_FUNCTION_UI_RETURN_TYPE = Return Type +CREATE_FUNCTION_UI_PARAM_LIST = Parameter List +CREATE_FUNCTION_UI_BUTTON_RESET = Reset +CREATE_FUNCTION_UI_BUTTON_ADD = Add +CREATE_FUNCTION_UI_BUTTON_DELETE = Delete +CREATE_FUNCTION_UI_FUNCTION_BODY = Function Body(*) +CREATE_FUNCTION_UI_BUTTON_NEXT = Next +CREATE_FUNCTION_UI_BUTTON_CANCEL = Cancel +CREATE_FUNCTION_UI_BUTTON_BACK = Back +CREATE_FUNCTION_UI_BUTTON_NO_COMPILE = No Compile +CREATE_FUNCTION_UI_BUTTON_COMPILE = Compile +CREATE_FUNCTION_UI_PARAM_NAME = Name +CREATE_FUNCTION_UI_PARAM_MODE = Mode +CREATE_FUNCTION_UI_PARAM_TYPE = Type +CREATE_FUNCTION_UI_PARAM_DEFAULT = Default +CREATE_FUNCTION_UI_TOOLTIP_NO_COMPILE = Enter data studio terminal, but don't compile the created function automatically, you need to compile the function manually! +CREATE_FUNCTION_UI_TOOLTIP_COMPILE = Enter data studio terminal and compile the created function automatically! +CREATE_FUNCTION_UI_TRIGGER = Trigger +CREATE_FUNCTION_UI_CREATE = Create +CREATE_FUNCTION_UI_ERR_FUNC_NAME = Function name can't be empty! +CREATE_FUNCTION_UI_ERR_FUNC_BODY = Function body can't be empty! + +DROP_TRIGGER = Drop Trigger +DROP_TRIGGER_TITLE = Drop Trigger +RENAME_TRIGGER = Rename +RENAME_TRIGGER_TITLE = Enter a new name for {0} trigger + +CREATE_TRIGGER_UI_CREATE_TRIGGER = Create Trigger +CREATE_TRIGGER_UI_EDIT_TRIGGER = Edit Trigger +CREATE_TRIGGER_UI_GENERAL_PAGE = General +CREATE_TRIGGER_UI_TRIGGER_NAME = Trigger Name(*): +CREATE_TRIGGER_UI_TRIGGER_TABLE_NAME = Trigger Table/View Name(*) +CREATE_TRIGGER_UI_TIME_TO_TRIGGER = Time To Trigger +CREATE_TRIGGER_UI_OPERATION_TYPE = Operation Type +CREATE_TRIGGER_UI_COLUMN_NAME = Column Name +CREATE_TRIGGER_UI_DATA_TYPE = Data Type +CREATE_TRIGGER_UI_TRIGGER_LEVEL = Trigger Level: +CREATE_TRIGGER_UI_TUPLE_LEVEL_TRIGGER = Tuple-Level Trigger(R) +CREATE_TRIGGER_UI_STATEMENT_LEVEL_TRIGGER = Statement-Level Trigger(M) +CREATE_TRIGGER_UI_TRIGGER_CONDITION = Trigger Condition +CREATE_TRIGGER_UI_TRIGGER_FUNCTION = Trigger Function(*) +CREATE_TRIGGER_UI_NEXT = Next +CREATE_TRIGGER_UI_CANCEL = Cancel +CREATE_TRIGGER_UI_SQL_PREVIEW = SQL Preview +CREATE_TRIGGER_UI_PREVIOUS = Previous +CREATE_TRIGGER_UI_FINISH = Finish + +EDIT_VIEW_UI_EDIT_VIEW = Edit View +CREATE_VIEW_UI_CREATE_VIEW = Create View +CREATE_VIEW_UI_SCHEMA_NAME = Schema Name +CREATE_VIEW_UI_VIEW_NAME = View Name(*) +CREATE_VIEW_UI_TABLE_NAME = Table Name +CREATE_VIEW_UI_TABLE_FULL_NAME = Table Full Name +CREATE_VIEW_UI_TABLE_ALIAS_NAME = Table Alias Name +CREATE_VIEW_UI_COLUMN_NAME = Column Name +CREATE_VIEW_UI_COLUMN_ALIAS_NAME = Column Alias Name +CREATE_VIEW_UI_COLUMN_1 = Column 1 +CREATE_VIEW_UI_COLUMN_2 = Column 2 +CREATE_VIEW_UI_PREVIEW = Preview +CREATE_VIEW_UI_NEXT = Next +CREATE_VIEW_UI_PREVIOUS = Previous +CREATE_VIEW_UI_CANCEL = Cancel +CREATE_VIEW_UI_FINISH = Finish +CREATE_VIEW_UI_WHERE = Where +CREATE_VIEW_UI_ADD = Add +CREATE_VIEW_UI_DELETE = Delete +CREATE_VIEW_UI_MATERVIEW = Materialized view +CREATE_VIEW_UI_VIEW = View +CREATE_VIEW_UI_NAME_NOT_EMPTY = View name cann't be empty! \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/messages_zh_CN.properties b/code/datastudio/src/org.opengauss.mppdbide.utils/src/messages_zh_CN.properties new file mode 100644 index 0000000000000000000000000000000000000000..01f4f4595fc9360ad1fcb2722aa59227a00a953b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/messages_zh_CN.properties @@ -0,0 +1,3160 @@ + +ENTRE_CLIENTSSLKEY = \u5BA2\u6237\u7AEFSSL\u79D8\u94A5 +ENTER_CLIENT_SSLPVT_KEYFILE = \u8F93\u5165\u5BA2\u6237\u7AEFSSL\u79C1\u94A5\u6587\u4EF6 +BTN_CLIENT_PVTKEY = *.key +INVALID_SSL_KEY = SSL\u5BC6\u94A5\u6587\u4EF6\u65E0\u6548 + +COLUMN_DEFAULT_VALUE_EXPRESSION = \u7f3a\u7701\u8868\u8FBE\u5F0F +MULTISORT_POPUP_WINDOW_TITLE = \u591A\u5217\u6392\u5E8F +COLUMN_PRIORITY = \u4F18\u5148\u7EA7 +COLUMN_COLUMN_NAME = \u5217\u540D +COLUMN_DATATYPE = \u6570\u636E\u7C7B\u578B +COLUMN_SORT_ORDER = \u987A\u5E8F +BUTTON_ADD_COLUMN = \u6DFB\u52A0\u5217 +BUTTON_DELETE_COLUMN = \u5220\u9664\u5217 +BUTTON_UP_COLUMN = \u4E0A\u79FB +BUTTON_DOWN_COULMN = \u4E0B\u79FB +BUTTON_APPLY_SORT = \u5E94\u7528 +COMBO_TEXT_SORT_COLUMN = -- \u6392\u5E8F\u5217 -- +COMBO_TEXT_SORT_OREDER = -- \u987A\u5E8F -- +COMBO_OPTION_ASCENDING = \u5347\u5E8F +COMBO_OPTION_DESCENDING = \u964D\u5E8F +GRIDDATA_SORT = \u591A\u5217\u6392\u5E8F +SORT_ERROR_WINDOW_TITLE = \u591A\u5217\u6392\u5E8F\u51FA\u9519 +SORT_ERROR_BLANK_COLUMN = \u6240\u6709\u6392\u5E8F\u6761\u4EF6\u5747\u9700\u8981\u6307\u5B9A\u5217\u540D\u3002\n\u8BF7\u4E3A{0}\u4F18\u5148\u7EA7\u9009\u62E9\u6709\u6548\u7684\u5217\u540D\uFF0C\u7136\u540E\u91CD\u8BD5\u3002 +SORT_ERROR_DUPLICATE_COLUMN = {0}\u5217\u88AB\u591A\u6B21\u6392\u5E8F\u3002\n\u8BF7\u5220\u9664{1}\u4F18\u5148\u7EA7\u4E2D\u91CD\u590D\u7684\u6392\u5E8F\u6761\u4EF6\uFF0C\u7136\u540E\u91CD\u8BD5\u3002 +CLEAR_SORT = \u6E05\u9664\u6392\u5E8F + +COLUMN_HEADER_QUERY_PLAN = \u67E5\u8BE2\u8BA1\u5212 +EXPLAIN_PLAN_MORE_THAN_ONE_QUERY_TITLE = \u6267\u884C\u8BA1\u5212 +EXPLAIN_PLAN_MORE_THAN_ONE_QUERY_MSG =\u6267\u884C\u8BA1\u5212\u9009\u62E9\u591A\u4E2A\u67E5\u8BE2\uFF0C\u4EC5\u4E3A\u9996\u4E2A\u67E5\u8BE2\u63D0\u4F9B\u6267\u884C\u8BA1\u5212\uFF0C\u5176\u4ED6\u67E5\u8BE2\u4F9D\u7136\u6267\u884C\u3002\u8BF7\u786E\u8BA4\u662F\u5426\u7EE7\u7EED\uFF1F +EXPLAIN_ANALYZE_WINDOW_TITLE = \u6267\u884C\u5206\u6790\u8BA1\u5212 +EXPLAIN_ANALYZE_WARNING_MSG = \u5982\u679C\u5728\u89E3\u91CA\u8BA1\u5212\u4E2D\u9009\u62E9\u201C\u5305\u542BANALYZE\u7ED3\u679C\u201D\uFF0C\u67E5\u8BE2\u5C06\u88AB\u6267\u884C\u3002\u5982\u679C\u67E5\u8BE2\u5305\u542BDML\u8BED\u53E5\uFF0C\u4F1A\u5F71\u54CD\u8868\u6570\u636E\u3002\u786E\u8BA4\u8981\u7EE7\u7EED\u5417\uFF1F +TOOLBAR_TREE_VIEW = \u6811\u5F62\u6837\u5F0F +TOOLBAR_TEXT_VIEW = \u6587\u672C\u6837\u5F0F +EXECUTION_PLAN_JOB = \u6B63\u5728\u6267\u884C\u89E3\u91CA\u8BA1\u5212 +EXECUTION_PLAN_SAVE = \u4FDD\u5B58\u89E3\u91CA\u8BA1\u5212 +EXECUTION_PLAN_SAVE_POPUP_TITLE = \u6210\u529F\u5BFC\u51FA\u89E3\u91CA\u8BA1\u5212 +EXECUTION_PLAN_SAVE_POPUP_MSG = \u89E3\u91CA\u8BA1\u5212\u5DF2\u5BFC\u51FA\u3002 +INCLUDE_ANALYZE_DROPDOWN = \u5305\u542BANALYZE\u7ED3\u679C + +SET_GBK_FILE_ENCODE_PREF = \u5904\u7406\u4E2D\u6587\u8868\u65F6\uFF0C\u8BF7\u5C06\u6587\u4EF6\u7F16\u7801\u8BBE\u4E3AGBK\u3002 +CHECK_FILE_ENCODE_SET = \n\n\u63D0\u793A: \ + \n1. \u53EF\u5728\u201C\u9996\u9009\u9879 > \u73AF\u5883 > \u4F1A\u8BDD\u8BBE\u7F6E\u201D\u754C\u9762\u67E5\u770B\u6587\u4EF6\u7F16\u7801\u3002 \ + \n2. \u8BF7\u5237\u65B0\u5BF9\u8C61\u6D4F\u89C8\u5668\uFF0C\u67E5\u770B\u5BF9\u8C61\u662F\u5426\u5B58\u5728\u4E8E\u6570\u636E\u5E93\u4E2D\u3002 + +BATCH_EXPORT_DDL_ERROR_FAIL_OBJ = \u5BFC\u51FA{0}\u65F6\u51FA\u9519 +BATCH_EXPORT_WARNING_TEXT = \u5BFC\u51FA{0}\u65F6\u9009\u62E9\u7684\u5BF9\u8C61\u8D85\u8FC7\u4E86100\u4E2A\u3002\u8BE5\u64CD\u4F5C\u53EF\u80FD\u9700\u8981\u4E00\u6BB5\u65F6\u95F4\u624D\u80FD\u5B8C\u6210\u3002\n\n\u662F\u5426\u8981\u7EE7\u7EED\u5BFC\u51FA{0}\uFF1F +BATCH_EXPORT_JOB = \u6B63\u5728\u6279\u91CF\u5BFC\u51FA +BATCH_EXPORT_DDL_VALID_OBJ = \u4EC5\u4EE5\u4E0B\u5BF9\u8C61\u652F\u6301\u5BFC\u51FA{0}\u64CD\u4F5C\uFF1A +BATCH_EXPORT_DDL_VALID_OBJ_LIST = \n\u6A21\u5F0F\n\u666E\u901A\u8868\n\u5206\u533A\u8868\n\u51FD\u6570/\u8FC7\u7A0B\n\u89C6\u56FE\n\u5E8F\u5217 +BATCH_EXPORT_DDLDATA_VALID_OBJ_LIST = \n\u6A21\u5F0F\n\u666E\u901A\u8868\n\u5206\u533A\u8868\n\u5E8F\u5217 +BATCH_EXPORT_DDL_MULTIPLE_DB = \u5BFC\u51FA{0}\u64CD\u4F5C\u53EA\u80FD\u5728\u540C\u4E00\u6570\u636E\u5E93\u4E2D\u6267\u884C\u3002 +BATCH_EXPORT_DDL_NO_OBJ = \u4E0D\u5141\u8BB8\u4ECE\u5BF9\u8C61\u7EC4\u4E2D\u5BFC\u51FA{0}\u3002 +EXPORT_FAIL_PROCESS_INTRUPTED_FOR_OBJ=\u5BFC\u51FA\u5931\u8D25\u3002\n\u539F\u56E0\uFF1A{0} + +BATCH_EXPORT_NO_USER_PREVILAGE = \u5F53\u524D\u7528\u6237\u4E0D\u662F\u8D85\u7EA7\u7528\u6237\u6216\u7BA1\u7406\u5458\u7528\u6237 +BATCH_EXPORT_ERROR_SHORT_MSG = \u5BFC\u51FA\u5931\u8D25\u3002 + +UPDATE_DBG_OBJ_TITLE = \u66F4\u6539\u6E90\u4EE3\u7801 +UPDATE_DBG_OBJ_QUESTION = \u8C03\u8BD5\u5BF9\u8C61{0}\u672A\u4E0E\u670D\u52A1\u5668\u540C\u6B65\u3002\u662F\u5426\u653E\u5F03\u66F4\u6539\u5E76\u4E0E\u670D\u52A1\u5668\u540C\u6B65\uFF1F +LBL_GRP_OB_ACESS = \u5BF9\u8C61\u6D4F\u89C8\u5668 +LBL_OBJS = \u52A0\u8F7D\u5BF9\u8C61 +OB_ACCESS_TYPE_ALL = \u6240\u6709\u5BF9\u8C61 +OB_ACCESS_TYPE_PRIVILEGED = \u7528\u6237\u6743\u9650\u8303\u56F4\u5185\u7684\u5BF9\u8C61 +ERR_GUI_SERVER_CONNECTION_FAILED = \u8FDE\u63A5\u5931\u8D25! +ERR_DENIED_ACCESS_PRIVILEGE=\u8BBF\u95EE\u88AB\u62D2\u7EDD\u3002 +ERR_GUI_COMPILE_FUN_PROC_TRIG_QUERY_FAILED = \u7F16\u8BD1{0}\u5931\u8D25.\u8BF7\u68C0\u67E5{1}\u4EE3\u7801. + +ERR_GUI_EXECUTE_FUN_PROC_TRIG_QUERY_FAILED = \u6267\u884C\u5931\u8D25\u3002\u8BF7\u68C0\u67E5\u4EE3\u7801\u3002 + +ERR_GUI_LOADING_FUN_PROC_TRIG_FAILED = \u52A0\u8F7D\u5BF9\u8C61\u65F6\u51FA\u9519\uFF1A {0} + +ERR_GUI_INVALID_CONNECTION_DETAILS = \u8BF7\u68C0\u67E5\u8FDE\u63A5\u8BE6\u7EC6\u4FE1\u606F\u662F\u5426\u6709\u6548\uFF0C\u5E76\u4E14\u670D\u52A1\u5668\u6B63\u5728\u8FD0\u884C. + +MSG_HINT_GUI_CONNECTION_FAIL = \u63D0\u793A\uFF08\u8BF7\u5C1D\u8BD5\u4EE5\u4E0B\u5176\u4E00\uFF09\uFF1A \ + \n1. \u9A8C\u8BC1\u6307\u5B9A\u7684\u8FDE\u63A5\u5C5E\u6027. \ + \n2. \u68C0\u67E5 Data Studio \u548C\u670D\u52A1\u5668\u7248\u672C\u662F\u5426\u517C\u5BB9. \ + \n3. \u68C0\u67E5\u914D\u7F6E\u662F\u5426\u6B63\u786E\u8BBE\u7F6E\uFF0C\u8BF7\u5728\u5BA2\u6237\u7AEF\u548C\u670D\u52A1\u5668\u624B\u518C\u83B7\u53D6\u66F4\u591A\u4FE1\u606F. + +MSG_HINT_GUI_CONNECTION_FAIL_FOR_SSL = \u63D0\u793A\uFF08\u5C1D\u8BD5\u5982\u4E0B\u65B9\u6CD5\uFF09\uFF1A \ + \n1. \u68C0\u67E5SSL\u5BC6\u7801\u662F\u5426\u5408\u6CD5 \ + \n2. \u68C0\u67E5\u4F7F\u7528\u7684\u8BC1\u4E66\u548C\u79D8\u94A5\u6587\u4EF6\u662F\u5426\u5408\u6CD5 + + +ERR_GUI_RESULT_SET_INVALID = \u83B7\u53D6\u7ED3\u679C\u65E0\u6548. +ERR_SYNONYM_NOT_SUPPORTED = \u670D\u52A1\u5668\u4E0D\u652F\u6301\u540C\u4E49\u8BCD\u3002\u8BF7\u53D6\u6D88\u540C\u4E49\u8BCD\u68C0\u67E5\u548C\u641C\u7D22\u3002 +ERR_EXPORT_TABLE_TO_CSV= \u5BFC\u51FA\u8868\u6570\u636E\u51FA\u9519.. + + + +EDIT_TABLE_INVALID_BOOLEAN_DATATYPE=\u7C98\u8D34\u7684\u5185\u5BB9\u4E0D\u5339\u914DBoolean/Bit\u6570\u636E\u7C7B\u578B\u683C\u5F0F\u3002 +#BL Error messages + +ERR_BL_ATTACH_TARGET_FAILED = \u8FDE\u63A5\u5230\u76EE\u6807\u4F1A\u8BDD\u65F6\u51FA\u9519 + +ERR_BL_DETACH_TARGET_FAILED = \u91CA\u653E\u4F1A\u8BDD\u65F6\u51FA\u9519 + +ERR_BL_CONNECT_FAILED = \u5728\u8FDE\u63A5\u65F6\u51FA\u9519. + +ERR_BL_EXECUTE_FAILED = \u6267\u884C\u65F6\u51FA\u9519 + + LOG_SOURCE = \u6E90. + +ERR_UI_EXPORT_FILE_OVERWRITE = \u786E\u8BA4\u6587\u4EF6\u8986\u76D6 +ERR_UI_NAME_EXIT = \u4F60\u786E\u5B9A\u8981\u7528\u76F8\u540C\u7684\u540D\u5B57\u8986\u76D6\u73B0\u6709\u7684\u6587\u4EF6\u5417\uFF1F + +ERR_UI_EXPORT_QUERY = \u5728\u5BFC\u51FA\u67E5\u8BE2\u6570\u636E\u65F6\u51FA\u9519. +IDE_INTERNAL_ERR = Data Studio \u7684\u5185\u90E8\u9519\u8BEF + +USER_GUIDE_NAME=docs/Data Studio \u7528\u6237\u624B\u518C.pdf +EXE_BL_CLS =\u5173\u95ED\u5C5E\u6027\u6587\u4EF6\u65F6\u53D1\u751FI/O\u5F02\u5E38 + +ERR_BL_GET_SESSION_FAILED = \u83B7\u53D6\u4F1A\u8BDD\u65F6\u51FA\u9519. + +ERR_BL_LOAD_PROPERTIES = \u52A0\u8F7D\u5C5E\u6027\u6587\u4EF6\u9519\u8BEF. + +ERR_BL_GET_SOURCECODE_FAILED = \u83B7\u53D6\u6E90\u4EE3\u7801\u65F6\u51FA\u9519. + +ERR_BL_REFRESH_OBJECT_FAILED = \u5237\u65B0\u5BF9\u8C61\u65F6\u51FA\u9519. + +ERR_BL_SYNC_FAILED = \u540C\u6B65\u65F6\u51FA\u9519. + +STATUS_MSG_VARIABLE_COLUMN_THREE = \u503C + +STATUS_MSG_PLVIEWER_OPTION_CUT = \u526A\u5207 +STATUS_MSG_PLVIEWER_OPTION_COPY = \u62F7\u8D1D +STATUS_MSG_PLVIEWER_OPTION_PASTE= \u7C98\u8D34 +STATUS_MSG_PLVIEWER_OPTION_SELECTALL= \u5168\u9009 +STATUS_MSG_PLVIEWER_OPTION_EXECUTE_DB_OBJECT= &\u6267\u884C +STATUS_MSG_PLVIEWER_OPTION_EXECUTE_STATEMENT= \u6267\u884C\u8BED\u53E5 +STATUS_MSG_PLVIEWER_OPTION_COMPILE_STATEMENT=\u7F16\u8BD1 + +ERR_BL_GET_SESSION_ID_FAILED = \u83B7\u53D6\u4F1A\u8BDDID\u65F6\u51FA\u9519 + +ERR_BL_GET_SERVER_SYNC_FAILED = \u5728\u83B7\u53D6\u670D\u52A1\u5668\u7684\u540C\u6B65\u72B6\u6001\u65F6\u51FA\u9519 + +ERR_BL_GET_DRIVER_VERSION_FAILED = \u5728\u83B7\u53D6\u9A71\u52A8\u7A0B\u5E8F\u7248\u672C\u65F6\u51FA\u9519 + +ERR_BL_REFCUR_EXECUTION_TEMPLATE_FAILURE = \u4E0D\u652F\u6301\u6267\u884C\u5C06REFCURSOR\u4F5C\u4E3AIN/INOUT\u53C2\u6570\u7684\u51FD\u6570\u3002 + +ERR_GUI_SOURCE_NOT_AVAILABLE = \u8D44\u6E90\u4E0D\u53EF\u7528 + +MSG_GUI_REFRESH_STATUSBAR = \u5237\u65B0... + +MSG_GUI_TERMINATE_STATUSBAR = \u7EC8\u6B62... + +MSG_GUI_EXECUTE_STATUSBAR = \u6267\u884C SQL... + +ERR_BL_INVALID_STATE = Data Studio \u7684 \u72B6\u6001\u6765\u6267\u884C\u6B64\u64CD\u4F5C. + +ERR_BL_SERVER_CONNECTION_FAILED = \u8FDE\u63A5\u5931\u8D25\uFF01 + +ERR_UI_INTERNAL_FAILURE = \u53D1\u751F\u672A\u77E5\u5185\u90E8\u9519\u8BEF.\u8BF7\u8054\u7CFBData Studio\u6280\u672F\u652F\u6301\u56E2\u961F\u4E86\u89E3\u65E5\u5FD7\u6587\u4EF6\u8BE6\u60C5\u3002 + +ERR_BL_NO_NAMESPACE_AVAILABLE = \u547D\u540D\u7A7A\u95F4\u5728\u7F13\u5B58\u4E2D\u4E0D\u53EF\u7528. + +ERR_EXE_PLAN_QUERY_PARSE_FAILED=\u67E5\u8BE2\u89E3\u6790\u5931\u8D25.\u8BF7\u68C0\u67E5\u67E5\u8BE2\u662F\u5426\u5B8C\u6210. + +MSG_HINT_REFRESH_OBJECTBROWSER = \n\u63D0\u793A: \ \u68C0\u67E5\u8FC7\u7A0B/\u51FD\u6570\u662F\u5426\u88AB\u6765\u81EA\u5176\u4ED6\u7EC8\u7AEF\u4E22\u5F03/\u4FEE\u6539.\ + \n\u5C1D\u8BD5\u4E00\u6BB5\u65F6\u95F4\u540E\u5237\u65B0. + +MSG_HINT_GETSOURCE = \n\u63D0\u793A: \u5C1D\u8BD5\u4E00\u6BB5\u65F6\u95F4\u540E\u5237\u65B0. + +MSG_CLEAR_EDITOR_CONTENT_ON_ERROR = \u5237\u65B0\u7F16\u8F91\u5668\u4E2D\u7684\u5BF9\u8C61\u65F6\u51FA\u9519\uFF1A\u6B63\u5728\u6E05\u9664\u7F16\u8F91\u5668\u4E2D\u5185\u5BB9\u3002 + +MSG_GUI_OBJECT_MAY_DROPPED = \u5BF9\u8C61\u53EF\u80FD\u672A\u5220\u9664\u3002 + +MSG_HINT_DATABASE_CRITICAL_ERROR = \u6570\u636E\u5E93\u4F1A\u8BDD\u53D1\u751F\u4E25\u91CD\u9519\u8BEF\uFF0C\u65E0\u6CD5\u7EE7\u7EED\u3002\u8BF7\u91CD\u65B0\u8FDE\u63A5\u670D\u52A1\u5668\u3002 + +ERR_MSG_OUT_OF_MEMORY_ERROR_OCCURRED = \u53D1\u751F\u6EA2\u51FA\u9519\u8BEF.\u8FDE\u63A5\u5C06\u88AB\u5173\u95ED. \ +\n\u63D0\u793A: \n \u5C1D\u8BD5\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u589E\u52A0\u5806\u5185\u5B58\u5927\u5C0F + +ERR_TITLE_DB_CRITICAL_ERROR = \u6570\u636E\u5E93\u4E25\u91CD\u9519\u8BEF + +ERR_QUERY_EXECUTION_FAILED = \u66F4\u65B0\u5931\u8D25\uFF0C\u5404\u884C\u5747\u672A\u53D7\u5230\u5F71\u54CD\u3002\u8BF7\u53D6\u6D88\u66F4\u6539\uFF0C\u5237\u65B0\u6570\u636E\uFF0C\u7136\u540E\u91CD\u8BD5\u3002 + +ERR_ALREADY_CONNECTION_PROFILE_EXISTS = \u5DF2\u5B58\u5728\u201C{0}\u201D\u7684\u8FDE\u63A5\u4FE1\u606F + +ERR_DEFAULT_DATATYPE_NOT_FOUND = \u9ED8\u8BA4\u6570\u636E\u7C7B\u578B{0} pg_catalog \u6CA1\u6709\u627E\u5230 + +ERR_CONNECTION_INVALID_STATE = \u4E0D\u5F97\u64C5\u81EA\u6539\u53D8\u4ECE{0}\u72B6\u6001\u81F3{1}\u72B6\u6001 + +ERR_FILLFACTOR_LESS_THAN_10 = \u586B\u5145\u7CFB\u6570\u4E0D\u80FD\u5C0F\u4E8E10. + +ERR_FILLFACTOR_MORE_THAN_100 = \u586B\u5145\u7CFB\u6570\u4E0D\u80FD\u8D85\u8FC710. + +ERR_INDEX_NAME_EMPTY = \u7D22\u5F15\u540D\u4E0D\u80FD\u4E3A\u7A7A + +ERR_EXECTION_IN_PROGRESS = \u5F53\u524D{0}\u64CD\u4F5C\u8FC7\u7A0B\u4E2D\uFF0C\u6B63\u5728\u5904\u7406\u4E2D\u518D\u8BD5. + +STATUS_MSG_CREATE_DATABASE = \u521B\u5EFA\u6570\u636E\u5E93... + +STATUS_MSG_DROP_DATABASE = \u5220\u9664\u6570\u636E\u5E93... + +STATUS_MSG_UPDATE_DATABASE = \u91CD\u533F\u540D\u6570\u636E\u5E93... + +STATUS_MSG_CONNECT_DATABASE = \u8FDE\u63A5\u5230\u6570\u636E\u5E93... + +STATUS_MSG_CREATE_INDEX = \u521B\u5EFA\u7D22\u5F15... + +STATUS_MSG_CREATE_SCHEMA = \u521B\u5EFA\u6A21\u5F0F... + +STATUS_MSG_CREATE_TABLE = \u521B\u5EFA\u8868... + +STATUS_MSG_DISCONNECT_ALL_DB = \u65AD\u5F00\u6240\u6709 DBs... + +STATUS_MSG_DROP_DEBUG_OBJECT = \u5220\u9664\u51FD\u6570/\u89E6\u53D1\u5668... + +STATUS_MSG_DROP_SCHEMA = \u5220\u9664\u6A21\u5F0F... + +STATUS_MSG_RENAME_SCHEMA = \u91CD\u547D\u540D\u6A21\u5F0F... + +STATUS_MSG_ADD_COLUMN = \u6DFB\u52A0\u5217... + +STATUS_MSG_ADD_CONSTRAINT = \u6DFB\u52A0\u7EA6\u675F... + +STATUS_MSG_SET_COLUMN_DEFAULT_VALUE = \u8BBE\u7F6E\u7f3a\u7701\u503C... + +STATUS_MSG_ANALYSE_TABLE = \u5206\u6790\u8868... + +STATUS_MSG_CHANGE_DATATYPE = \u66F4\u6539\u6570\u636E\u7C7B\u578B... + +STATUS_MSG_CHANGE_FILLFACTOR = \u6539\u53D8\u586B\u5145\u7CFB\u6570... + +STATUS_MSG_CHANGE_INDEX_TBLSPACE = \u66F4\u6539\u7D22\u5F15\u8868\u7A7A\u95F4... + +STATUS_MSG_DROP_COLUMN = \u5220\u9664\u5217... + +STATUS_MSG_DROP_CONSTRAINT = \u5220\u9664\u7EA6\u675F... + +STATUS_MSG_DROP_INDEX = \u5220\u9664\u7D22\u5F15... + +STATUS_MSG_DROP_TABLE = \u5220\u9664\u8868... + +STATUS_MSG_REINDEX_TABLE = \u91CD\u5EFA\u7D22\u5F15\u8868... + +STATUS_MSG_RENAME_COLUMN = \u91CD\u547D\u540D\u5217... + +STATUS_MSG_RENAME_CONSTRAINT = \u91CD\u547D\u540D\u7EA6\u675F... + +STATUS_MSG_RENAME_INDEX = \u91CD\u547D\u540D\u7D22\u5F15... + +STATUS_MSG_RENAME_TABLE = \u91CD\u547D\u540D\u8868... + +STATUS_MSG_SET_COLUMN_NOTNULL = \u8BBE\u7F6E\u975E\u7A7A... + +STATUS_MSG_SET_SCHEMA = \u8BBE\u7F6E\u6A21\u5F0F... + +STATUS_MSG_STATUS= \u6267\u884C\u6210\u529F... + +STATUS_MSG_SET_TBL_DESC = \u8BBE\u7F6E\u8868\u63CF\u8FF0... + +STATUS_MSG_SET_TBLSPACE = \u8BBE\u7F6E\u8868\u7A7A\u95F4... + +STATUS_MSG_TRUNCATE_TABLE = \u6E05\u7A7A\u8868... + +STATUS_MSG_VACUUM_TABLE = \u6E05\u7406\u8868... + +STATUS_MSG_VALIDATE_CONSTRAINT = \u9A8C\u8BC1\u7EA6\u675F... + +STATUS_MSG_AUTO_SUGGEST = \u6B63\u5728\u52A0\u8F7D\u81EA\u52A8\u5EFA\u8BAE\u2026\u2026 + +ERR_MSG_NO_OTHER_CONNECTION = \u6CA1\u6709\u5176\u4ED6\u53EF\u7528\u7684\u8FDE\u63A5 + +ERR_RENAME_NEED_ANOTHER_CON = \u6CA1\u6709\u5176\u4ED6\u53EF\u7528\u7684\u6570\u636E\u5E93\u8FDE\u63A5.\u91CD\u547D\u540D\u6570\u636E\u5E93\u9700\u8981\u53E6\u4E00\u4E2A\u6D3B\u52A8\u8FDE\u63A5 + +ERR_NO_CONNECTION_AVAILABLE = \u65E0\u7F51\u7EDC\u8FDE\u63A5.\u81F3\u5C11\u6709\u4E00\u4E2A\u8FDE\u63A5\u662F\u5FC5\u9700\u7684 + +ERR_DUPLICATE_INDEX_NAME = \u7D22\u5F15\u540D\u79F0\u5DF2\u7ECF\u5B58\u5728.\u8BF7\u8F93\u5165\u4E0D\u540C\u7684\u540D\u79F0. + +ERR_INDEX_COLS_EMPTY = \u8BF7\u81F3\u5C11\u9009\u62E9\u4E00\u5217. + +COPYRIGHT_MSG_HUAWEI = \u7248\u6743\u6240\u6709 \u00a9 \u534E\u4E3A\u6280\u672F\u6709\u9650\u516C\u53F82016-2020\u3002 +RIGHTS_RESERVRED_MSG_HUAWEI = \u4FDD\u7559\u4E00\u5207\u6743\u5229\u3002 +ABOUT_DATA_STUDIO_MSG= \u5173\u4E8E Data Studio +VERSION_NO_MSG=\u7248\u672C: +JAVA_VERSION_NO_MSG=Java\u7248\u672C: +#Don't translate this two lines +JAVA_HOME_MSG=Java \u8DEF\u5F84: +WEB_HUAWEI_LINK=http://www.huawei.com + +JAVA_HOME_NOT_SET=\u73AF\u5883\u672A\u8BBE\u7F6E\u3002\u6709\u5173\u8BF4\u660E\uFF0C\u8BF7\u53C2\u9605\u7528\u6237\u624B\u518C\u3002 + +BREAKPOINT_WINDOW_ERROR_MSG_HEADING=PLSQL \u672A\u77E5\u9519\u8BEF +BREAKPOINT_WINDOW_ERROR_MSG=\u53D1\u751F\u672A\u77E5\u5185\u90E8\u9519\u8BEF.\u8BF7\u8054\u7CFBData Studio\u6280\u672F\u652F\u6301\u56E2\u961F\u4E86\u89E3\u65E5\u5FD7\u8BE6\u60C5\u3002 + +CONSOLE_WINDOW_ERROR_MSG= \u4FEE\u6574\u521D\u59CB\u5316\u6D88\u606F\u65E5\u5FD7\u6D88\u606F\u65F6\u51FA\u9519. +CONSOLE_WINDOW_ERROR_SCROLLING_MSG= \u6EDA\u52A8\u5230\u6D88\u606F\u7A97\u53E3\u4E2D\u6700\u540E\u7684\u5185\u5BB9\u65F6\u51FA\u9519. + CONSOLE_WINDOW_MEMORY_MSG= \u5F53\u524D\u5185\u5B58\u4F7F\u7528\u7387 + CONSOLE_WINDOW_LINE_NUMBER_MSG=\u884C\u7684\u6570\u76EE + CONSOLE_WINDOW_OFFSET_MSG = \u504F\u79FB\u91CF + CONSOLE_WINDOW_LENGTH_MSG = \u957F\u5EA6 + +EXECDIALOG_PARAMETER_VALUE=\u8F93\u5165\u53C2\u6570\u503C +EXECDIALOG_EXEC_PL_SQL=\u8C03\u8BD5\u51FD\u6570/\u8FC7\u7A0B +EXECDIALOG_PARAMETER=\u53C2\u6570 +EXECDIALOG_TYPE=\u7C7B\u578B +EXECDIALOG_DATATYPE=\u6570\u636E\u7C7B\u578B +EXECDIALOG_VALUE=\u503C +EXECDIALOG_HINT= \u63D0\u793A + +OBJECT_BROWSER_LABEL_MSG=\u672A\u77E5\u7C7B\u578B + + LABEL_VIEW_SOURCE=\u67E5\u770B\u6765\u6E90 + +PL_SOURCE_EDITOR_AT= \u3002\u6240\u5728\u884C\uFF1A# {0} + +ANALYSE_TABLE_ERROR_MSG=\u5206\u6790\u65F6\u9519\u8BEF + +CHANGE_INDEX_FILLFACTOR_NEW=\u9009\u62E9\u65B0\u7684\u586B\u5145\u6761\u4EF6\u4E3A{0}\u6307\u6570\uFF1A +CHANGE_INDEX_FILLFACTOR_MIN=\u586B\u5145\u6761\u4EF6\u4E0D\u80FD\u5C0F\u4E8E10. +CHANGE_INDEX_FILLFACTOR_MAX= \u586B\u5145\u6761\u4EF6\u4E0D\u80FD\u5927\u4E8E100. +CHANGE_INDEX_FILLFACTOR_FOR=\u66F4\u6539{0}\u6307\u6570\u7684\u586B\u5145\u6761\u4EF6\uFF0C\u8BF7\u7A0D\u5019... + +CHANGE_INDEX_FILLFACTOR_CONN_ERROR=\u66F4\u6539\u586B\u5145{0}\u7684\u6307\u6807\u65F6\u8FDE\u63A5\u9519\u8BEF\uFF1A{1}\u9519\u8BEF\uFF1A{2} + +CHANGE_INDEX_FILLFACTOR_CHANGED=\u5DF2\u4FEE\u6539\u7D22\u5F15\u7684\u586B\u5145\u56E0\u5B50\u4E3A\uFF1A{0} + +CHANGE_INDEX_FILLFACTOR_TITLE=\u66F4\u6539\u586B\u5145\u56E0\u5B50 +CHANGE_INDEX_FILLFACTOR_SELECT=\u9009\u62E9{0}\u6307\u6570\u7684\u586B\u5145\u6761\u4EF6\uFF1A +CHANGE_INDEX_TABLESPACE_NEW=\u9009\u62E9{0}\u6307\u6570\u65B0\u7684\u8868\u7A7A\u95F4\uFF1A +CHANGE_INDEX_TABLESPACE_FOR= \u66F4\u6539{0}\u7D22\u5F15\u8868\u7A7A\u95F4\uFF0C\u8BF7\u7A0D\u5019... +CHANGE_INDEX_TABLESPACE_CONN_ERROR=\u6539\u53D8\u8868\u7A7A\u95F4{0}\u6307\u6570\u4E2D\u8FDE\u63A5\u9519\u8BEF.\uFF1A{1}\u9519\u8BEF\uFF1A{2} +CHANGE_INDEX_TABLESPACE_TO= \u5DF2\u66F4\u65B0\u7D22\u5F15\u8868\u7A7A\u95F4 {0} \u4E3A {1}\u3002 +CHANGE_INDEX_TABLESPACE_TITLE= \u66F4\u6539\u8868\u7A7A\u95F4 +CHANGE_INDEX_TABLESPACE_SELECT= \u5BF9\u4E8E\u9009\u62E9\u8868{0} + +DROP_COLUMN_DIA_TITLE=\u5220\u9664\u5217 +DROP_COLUMN_DIA_MSG= \u786E\u5B9A\u8981\u5220\u9664\u4ECE\u201C{1} \u201D.\u201C{2}\u201D\u8868\u5220\u9664 {0} \u5217\uFF1F + +DROP_COLUMN_ERROR=\u5220\u9664\u5217\u65F6\u51FA\u9519 +DROP_COLUMN_UNABLE_MSG=\u5220\u9664\u8BE5\u5217\u65F6\u51FA\u9519\uFF1A {0}.{1}.{2} +DROP_COLUMN_UNABLE=\u65E0\u6CD5\u4ECE\u201C{1}\u201D.\u201C{2}\u201D\u8868\u5220\u9664{0}\u5217.\u670D\u52A1\u5668\u6D88\u606F\uFF1A{3} +DROP_COLUMN_SUCCESS=\u5DF2\u5220\u9664\u5217\uFF1A{0}.{1}.{2} + +DROP_CONSTRAINT_DIA_TITLE=\u5220\u9664\u7EA6\u675F +DROP_CONSTRAINT_FROM=\u786E\u5B9A\u8981\u4ECE\u201C{1}\u201D.\u201C{2}\u201D\u8868\u4E2D\u5220\u9664\u201C{0}\u201D\u7EA6\u675F\u5417\uFF1F +DROP_CONSTRAINT_DROPPING=\u5DF2\u5220\u9664\u7EA6\u675F: {0}.{1}.{2} +DROP_CONSTRAINT_ERROR=\u5220\u9664\u7EA6\u675F\u65F6\u51FA\u9519 +DROP_CONSTRAINT_UNABLE_TO_DROP=\u5220\u9664\u7EA6\u675F\u65F6\u51FA\u9519\uFF1A {0}.{1}.{2} + +DROP_INDEX_DIA_TITLE=\u5220\u9664\u7D22\u5F15 +DROP_INDEX=\u4F60\u786E\u5B9A\u8981\u5220\u9664{0}\u7D22\u5F15\uFF1F +DROP_INDEX_SUCCESS=\u5DF2\u5220\u9664\u7D22\u5F15\uFF1A {0}.{1} +DROP_INDEX_ERROR_TITLE=\u5220\u9664\u7D22\u5F15\u51FA\u9519 +DROP_INDEX_ERROR_MSG=\u5220\u9664\u7D22\u5F15\u65F6\u51FA\u9519\uFF1A {0}.{1}.{2} + +DROP_INDEX_CONN_FAIL=\u5220\u9664\u7D22\u5F15\u65F6\u53D1\u751F\u8FDE\u63A5\u9519\u8BEF\uFF1A {0}.{1}.{2} + +DROP_TABLE_DIA_TITLE=\u5220\u9664 +DROP_TABLE=\u4F60\u786E\u5B9A\u8981\u5220\u9664\u201C{0}\u201D.\u201C{1}\u201D\u8868\uFF1F +DROP_TABLE_SUCCESS=\u5DF2\u5220\u9664\u8868\uFF1A {0}.{1} +DROP_TABLE_ERROR=\u5220\u9664\u8868\u65F6\u51FA\u9519 +DROP_TABLE_UNABLE=\u65E0\u6CD5\u5220\u9664\u8868. {0}\u670D\u52A1\u5668\u6D88\u606F\uFF1A{1} +DROP_TABLE_UNABLE_MSG=\u5220\u9664\u8868\u65F6\u51FA\u9519\uFF1A{0}.{1} + +REINDEX_TABLE=\u5DF2\u4E3A\u8BE5\u8868\u91CD\u5EFA\u7D22\u5F15\uFF1A {0}.{1} + +REINDEX_TABLE_ERROR=\u91CD\u5EFA\u7D22\u5F15\u201C{0}\u201D.\u201C{1}\u201D\u8868\u65F6\u9519\u8BEF.\u670D\u52A1\u5668\u6D88\u606F\uFF1A{2} +REINDEX_TABLE_CONN_ERROR=\u91CD\u5EFA\u7D22\u5F15\u201C{0}\u201D.\u201C{1}\u201D\u8868\u8FDE\u63A5\u9519\u8BEF.\u670D\u52A1\u5668\u6D88\u606F\uFF1A{2} + +RENAME_COLUMN=\u5728{1}\u5217\u201C.\u201D{2}\u8868 +RENAME_COLUMN_NEW=\u4E3A{0}\u8F93\u5165\u65B0\u7684\u540D\u79F0 + +RENAME_COLUMN_ERROR=\u91CD\u547D\u540D\u65F6\u51FA\u9519 \u201C{0}\u201D\uFF0C\u201C{1}\u201D\u9519\u8BEF\uFF1A{2} +RENAME_COLUMN_CONN_ERROR= \u91CD\u547D\u540D\u5217\u5728\u8FDE\u63A5\u65F6\u9519\u8BEF. {0}\u9519\u8BEF\uFF1A{1} + +RENAME_COLUMN_RENAMED=\u66F4\u540D\u201C{2}\u201D.\u201C{3}\u201D\u8868\u7684{0}{1}\u5217 + +RENAME_COLUMN_TITLE=\u91CD\u547D\u540D\u5217 +RENAME_COLUMN_NEW_NAME=\u4E3A\u8868\u201C{1}\u201D.\u201C{2}\u201D {0}\u5217\u8F93\u5165\u65B0\u540D\u79F0 +RENAME_CONSTRAINT=\u7EA6\u675F +RENAME_CONSTRAINT_NEW_NAME=\u4E3A{0}\u7EA6\u675F\u8F93\u5165\u65B0\u7684\u540D\u79F0 +RENAME_CONSTRAINT_CONN_ERROR=\u91CD\u547D\u540D\u7EA6\u675F\u65F6\u8FDE\u63A5\u9519\u8BEF. {0}\u9519\u8BEF\uFF1A{1} + +RENAME_CONSTRAINT_TITLE=\u91CD\u547D\u540D\u7EA6\u675F +RENAME_CONSTRAINT_WAIT=\u91CD\u547D\u540D{0}\u7EA6\u675F\uFF0C\u6B63\u5728\u5904\u7406\u4E2D... +RENAME_CONSTRAINT_ERROR=\u91CD\u547D\u540D\u201C{0}\u201D\u51FA\u9519\uFF0C\u201C{1}\u201D\u9519\u8BEF\uFF1A{2} +RENAME_CONSTRAINT_RENAMED=\u5DF2\u5C06{0}\u7EA6\u675F\u91CD\u547D\u540D\u4E3A{1} \u3002 + +RENAME_INDEX_NEW_NAME=\u4E3A{0}\u7D22\u5F15\u8F93\u5165\u65B0\u7684\u540D\u79F0 +RENAME_INDEX_WAIT=\u91CD\u547D\u540D{0}\u7D22\u5F15\uFF0C\u6B63\u5728\u5904\u7406\u4E2D... +RENAME_INDEX_ERROR=\u91CD\u547D\u540D\u201C{0}\u201D\u51FA\u9519\uFF0C\u201C{1}\u201D\u9519\u8BEF\uFF1A{2} +RENAME_INDEX_CONN_ERROR=\u91CD\u547D\u540D\u7D22\u5F15\u65F6\u8FDE\u63A5\u9519\u8BEF. {0}\u9519\u8BEF\uFF1A{1} +RENAME_INDEX_TITLE=\u91CD\u547D\u540D\u7D22\u5F15 +RENAME_INDEX_RENAMED=\u5DF2\u5C06{0} \u7D22\u5F15\u91CD\u547D\u540D\u4E3A {1}\u3002 +RENAME_INDEX_NEW=\u8F93\u5165{0}\u7D22\u5F15\u7684\u65B0\u540D\u79F0 + +RENAME_TABLE_NEW_NAME=\u4E3A{0}\u8868\u8F93\u5165\u65B0\u7684\u540D\u79F0 +RENAME_TABLE_WAIT=\u91CD\u547D\u540D{0}\u8868\uFF0C\u6B63\u5728\u5904\u7406\u4E2D... +RENAME_TABLE_ERROR=\u91CD\u65B0\u547D\u540D{0}.{1}\u9519\u8BEF\uFF1A{2} +RENAME_TABLE_CONN_ERROR=\u5728\u91CD\u547D\u540D\u8868\u65F6\u8FDE\u63A5\u9519\u8BEF. {0}\u9519\u8BEF\uFF1A{1} +RENAME_TABLE_TO= \u5DF2\u5C06{0}\u8868\u91CD\u547D\u540D\u4E3A {1}.{2}\u3002 +RENAME_TABLE_NEW=\u4E3A\u6A21\u5F0F\u4E2D\u7684{0}\u5206\u533A\u8868\u8F93\u5165\u65B0\u540D\u79F0 +RENAME_TABLE_TITLE=\u91CD\u547D\u540D + +RENAME_TRIGGER_WAIT =\u91CD\u547D\u540D{0}\u89e6\u53d1\u5668\uFF0C\u6B63\u5728\u5904\u7406\u4E2D... + +SET_COLUMN_TOGGLE_TITLE=\u5207\u6362\u975E\u7A7A\u5C5E\u6027 +SET_COLUMN_TOGGLE_MSG=\u60A8\u786E\u5B9A\u8981\u5207\u6362{0}\u5217\u4E3A\u975E\u7A7A\u5C5E\u6027\uFF1F +SET_COLUMN=\u5217 +SET_COLUMN_ERROR=\u5207\u6362\u975E\u7A7A\u5C5E\u6027\u51FA\u9519 +SET_COLUMN_UNABLE=\u65E0\u6CD5\u5207\u6362\u4E3A\u975E\u7A7A\u5C5E\u6027. {0}\u670D\u52A1\u5668\u6D88\u606F\uFF1A{1} + +SET_COLUMN_NOT_NULL_SUCCESSFUL=\u5DF2\u5C06{0}\uFF0C{1}\uFF0C{2}\u5217\u8BBE\u7F6E\u4E3ANOT NULL\u3002 + +SET_SCEMA_SELECT=\u4E3A{0}\u8868\u9009\u62E9\u65B0\u6A21\u5F0F +SET_SCEMA_MOVING=\u79FB\u52A8{0}\u8868\uFF0C\u5230{1}\u6A21\u5F0F\uFF0C\u6B63\u5728\u5904\u7406\u4E2D... + +SET_SCEMA_ERROR=\u79FB\u52A8\u8868{0}\u5230{1}\u6A21\u5F0F\u51FA\u9519.{2}\u9519\u8BEF\uFF1A{3} +SET_SCEMA=\u8BBE\u7F6E\u8868\u6A21\u5F0F +SET_SCEMA_CONN_ERROR=\u5728\u91CD\u547D\u540D\u8868\u8FC7\u7A0B\u4E2D\u8FDE\u63A5\u9519\u8BEF.{0}\u9519\u8BEF\uFF1A{1} +SET_SCEMA_MOVED= \u8BE5\u8868\u5DF2\u4ECE{0}.{1}\u79FB\u52A8\u5230{2}.{1}\u3002 + +SET_SCEMA_TITLE=\u8BBE\u7F6E\u6A21\u5F0F + +SET_SCEMA_SELECT_NEW=\u8BF7\u4E3A\u8868{1}.{0} \u9009\u62E9\u4E00\u4E2A\u65B0\u7684\u6A21\u5F0F +SET_TABLE_NEW_DESC=\u4E3A\u8868\u201C{0}\u201D.\u201C{1}\u201D\u8F93\u5165\u65B0\u63CF\u8FF0 +SET_TABLE_UPDATE_DESC=\u4E3A\u201C{0}\u201D.\u201C{1}\u201D\u8868\u66F4\u65B0\u8BF4\u660E\uFF0C\u6B63\u5728\u5904\u7406\u4E2D... + +SET_TABLE_UPDATE_ERROR=\u66F4\u65B0\u8BF4\u660E\u65F6\u51FA\u9519.{0}\u9519\u8BEF\uFF1A{1} +SET_TABLE_CONN_ERROR=\u5728\u66F4\u65B0\u8868\u63CF\u8FF0\u8FC7\u7A0B\u4E2D\u8FDE\u63A5\u9519\u8BEF.{0}\u9519\u8BEF\uFF1A{1} +SET_TABLE_DESC_SUCCES=\u5DF2\u66F4\u65B0{0}.{1}\u8868\u8BF4\u660E\u3002 + +SET_TABLE_DESC_TITLE=\u66F4\u65B0\u63CF\u8FF0 +SET_TABLE_NEW_DESC_FOR=\u8BF7\u4E3A\u8868{0}.{1} \u8BBE\u7F6E\u65B0\u7684\u63CF\u8FF0 + +SET_TABLESPACE_NEW={0}\u8868\u9009\u62E9\u65B0\u8868\u7A7A\u95F4 +SET_TABLESPACE_FROM_CURRENT=\u6B63\u5728\u5C06\u8868 {0} \u4ECE\u5F53\u524D\u8868\u7A7A\u95F4 {1} \u79FB\u52A8\u5230\u8868\u7A7A\u95F4 {2} \u8BF7\u7B49\u5F85\u2026 +SET_TABLESPACE_FROM_CURRENT_NULL=\u6B63\u5728\u5C06\u8868 {0} \u79FB\u52A8\u5230\u8868\u7A7A\u95F4 {1} \uFF0C\u8BF7\u7B49\u5F85\u2026 + +SET_TABLESPACE_ERROR=\u5C06\u8868{0}\u4ECE\u5F53\u524D\u8868\u7A7A\u95F4{1}\u79FB\u52A8\u5230\u8868\u7A7A\u95F4{2}\u65F6\u51FA\u73B0\u9519\u8BEF\u3002{3}{4} +SET_TABLESPACE_ERROR_NULL=\u5C06\u8868{0}\u79FB\u52A8\u5230\u8868\u7A7A\u95F4{1}\u65F6\u51FA\u73B0\u9519\u8BEF\u3002{2}{3} +SET_TABLESPACE_CONN_ERROR=\u91CD\u547D\u540D\u8868\u8FC7\u7A0B\u4E2D\u8FDE\u63A5\u9519\u8BEF. {0}\u9519\u8BEF\uFF1A{1} +SET_TABLESPACE_FROM=\u4ECE\u8868\u7A7A\u95F4 +EXEC_PLAN_OK=\u786E\u5B9A +SET_TABLESPACE=\u8868\u7A7A\u95F4 + +SET_TABLE_FROM_TABLESPACE=\u8BE5\u8868\u5DF2\u4ECE {0}\u79FB\u52A8\u5230{1}.{2}\u3002 +SET_TABLE_FROM_TABLESPACE_NULL=\u8be5\u8868 {0} \u5df2\u4ece {1} \u79fb\u52a8\u5230 {2} +SET_TABLESPACE_TITLE=\u8BBE\u7F6E\u8868\u7A7A\u95F4 +SET_TABLESPACE_IN=\u8BF7\u4E3A\u8868{0}.{1}\u9009\u62E9\u4E00\u4E2A\u65B0\u7684\u8868\u7A7A\u95F4 +TRUNCATE_TABLE_TITLE=\u622A\u65AD +TRUNCATE_TABLE_MSG= \u4F60\u786E\u5B9A\u8981\u6E05\u7A7A\u201C{0}\u201D.\u201C{1}\u201D\u8868\uFF1F +TRUNCATE_TABLE_TRUNCATED=\u5DF2\u622A\u65AD\u8868\uFF1A{0}.{1} +TRUNCATE_TABLE_ERROR= \u622A\u65AD\u8868\u65F6\u51FA\u9519\uFF1A{0}.{1} +TRUNCATE_TABLE_CONN_ERROR= \u6E05\u7A7A\u201C{0}\u201D.\u201C{1}\u201D\u8868\u65F6\u9519\u8BEF.\u670D\u52A1\u5668\u6D88\u606F\uFF1A{2} + +VACCUM_TABLE_SUCCESS=\u5DF2\u6E05\u7406\u8868\uFF1A{0}.{1} +VACCUME_TABLE_ERROR= \u6E05\u7406\u8868\u65F6\u51FA\u9519\uFF1A{0}.{1} +VACCUME_TABLE_CONN_ERROR=\u6E05\u7406\u201C{0}\u201D.\u201C{1}\u201D\u7684\u8868\u65F6\u8FDE\u63A5\u9519\u8BEF.\u670D\u52A1\u5668\u6D88\u606F\uFF1A{2} + +VALIDATE_CONSTRAINT_SUCCESS=\u5DF2\u9A8C\u8BC1\u7EA6\u675F: {0}.{1}.{2} +VALIDATE_CONSTRAINT_ERROR=\u5728\u9A8C\u8BC1\u7EA6\u675F\u65F6\u9519\u8BEF +VALIDATE_CONSTRAINT_UNABLE=\u9A8C\u8BC1\u7EA6\u675F\u65F6\u51FA\u9519\uFF1A{0}.{1}.{2} + +VIEW_TABALE_DATA_ERROR=\u67E5\u770B\u6570\u636E\u51FA\u9519 +VIEW_TABALE_DATA_UNABLE=\u83B7\u53D6\u6570\u636E\u65F6\u51FA\u9519 +VIEW_TABALE_DATA_UNABLE_VIEW=\u67E5\u770B\u8868\u6570\u636E\u65F6\u51FA\u9519\uFF1A {0}.{1} + +DISCONN_IN_PROGRESS = \u65AD\u5F00\u6B63\u5728\u8FDB\u884C\u4E2D + +EXEC_PLAN_TITLE=\u6267\u884C\u8BA1\u5212 + +EXEC_PLAN_PARSE_FAIL=Explain Plan\u67E5\u8BE2\u89E3\u6790\u5931\u8D25 + +EXEC_PLAN_TEXT=\u6587\u672C + +EXEC_PLAN_FAIL_MSG=\u6267\u884C\u5931\u8D25\u3002{0}\u9519\u8BEF\u4EE3\u7801 :[{1}]{2} + +FIND_REPLACE_TITLE=\u67E5\u627E\u548C\u66FF\u6362 +FIND_REPLCAE_WHAT=\u67E5\u627E\u5185\u5BB9: +FIND_REPLACE_WITH=\u66FF\u6362\u4E3A: +FIND_REPLACE_BACK=\u53CD\u5411\u641C\u7D22 +FIND_REPLACE_MATCH=\u533A\u5206\u5927\u5C0F\u5199 +FIND_REPLACE_WHOLE=\u5168\u5B57\u5339\u914D +FIND_REPLACE_WRAP=\u4ECE\u8D77\u59CB\u4F4D\u7F6E\u5230\u7ED3\u675F\u5FAA\u73AF\u641C\u7D22 +FIND_REPLACE_NEXT=\u67E5\u627E\u4E0B\u4E00\u5904 +FIND_REPLACE=\u67E5\u627E\u5E76\u66FF\u6362 +FIND_REPLACE_ALL=\u5168\u90E8\u66FF\u6362 + +FIND_REPLACE_SEARCH_NOT_FOUND=\u641C\u7D22\u6587\u672C\u672A\u627E\u5230 + +PL_SOURCE_VIEWER_ERROR=\u6E90\u4EE3\u7801\u67E5\u770B\u5668\u9519\u8BEF +PL_SOURCE_VIEWER_UNABLE=\u65E0\u6CD5\u627E\u5230\u6E90\u4EE3\u7801\u67E5\u770B\u5668. +PL_SOURCE_CODE_ERROR=\u6E90\u4EE3\u7801\u9519\u8BEF +PL_SOURCE_DISPLAY_ERROR=\u65E0\u6CD5\u663E\u793APLSQL\u6E90\u4EE3\u7801\u9009\u5B9A\u7684\u5BF9\u8C61. + +PROPERTIES_WID_PROPERTY=\u5C5E\u6027 +PROPERTIES_WID_VALUE=\u503C +RESULT_WINDOW_REFRESH=\u5237\u65B0\u8FDB\u5EA6 + +SQL_TERMINAL_CONN=\u8FDE\u63A5\uFF1A +SQL_TERMINAL_CONNS= -- \u8FDE\u63A5 -- + +#Default Schema +DEFAULT_SCHEMA_INITIAL_MSG= \u9ED8\u8BA4\u67B6\u6784 +DEFAULT_SCHEMA_ERROR_TITLE = \u641C\u7D22\u8DEF\u5F84\u9519\u8BEF +DEFAULT_SCHEMA_ERROR_MSG = \u8BBE\u7F6E/\u83B7\u53D6\u641C\u7D22\u8DEF\u5F84\u65F6\u51FA\u9519 + +#Block root user in linux +USER_ROOT_ERROR_TITLE = \u7981\u7528\u7528\u6237\u9519\u8BEF +USER_ROOT_ERROR_MSG = \u65E0\u6CD5\u4EE5root\u7528\u6237\u542F\u52A8\u5E94\u7528\u3002\u8BF7\u5C1D\u8BD5\u4F7F\u7528\u5176\u4ED6\u7528\u6237\u767B\u5F55\u3002 + +MPPDBIDE_DIA_BTN_YES=\u662F +MPPDBIDE_DIA_BTN_NO=\u5426 +MPPDBIDE_DIA_BTN_CANC=\u53D6\u6D88 +MPPDBIDE_DIA_BTN_DISCARD=\u653E\u5F03\u4FEE\u6539 + +MPPDB_IDE_MOM_MAX= Data Studio\u7684\u6700\u5927\u5185\u5B58\uFF1A + +UI_DISPLAY_PERFORMING=\u6267\u884C + +DB_CONN_DIA_TITLE= \u65B0\u5EFA/\u9009\u62E9\u6570\u636E\u5E93\u8FDE\u63A5 +DB_CONN_DIA_MSG= \u8FDE\u63A5\u53C2\u6570 +DB_CONN_DIA_HELP = \u5E2E\u52A9 +DB_CONN_DIA_TO_SERVER=\u8FDE\u63A5\u5230\u670D\u52A1\u5668 +DB_CONN_DIA_CONN_NAME=\u540D\u79F0* +DB_CONN_DIA_HOST=\u4E3B\u673A* +DB_CONN_DIA_HOST_PORT=\u7AEF\u53E3\u53F7* +DB_CONN_DIA_MAX_VALUE=\u6700\u5927\u503C +DB_CONN_DIA_DB_NAME_OLAP=\u6570\u636E\u5E93* +DB_CONN_DIA_USER_NAME=\u7528\u6237\u540D* +DB_CONN_DIA_PSW=\u5BC6\u7801* +DB_CONN_DIA_SSL=SSL +DB_CONN_DIA_ENABLE_SSL= \u542F\u7528SSL +DB_CONN_REM_PSW=\u4FDD\u5B58\u5BC6\u7801\uFF1A + +DB_CONN_DIA_T=T + +DB_CONN_DIA_SSL_PROPERTY=\u5B89\u5168\u5957\u63A5\u5B57\u5C42\u5C5E\u6027\u5DF2\u7ECF\u8BBE\u7F6E. +DB_CONN_DIA_INVALID_SERVER_IP_TITLE=\u65E0\u6548\u7684\u670D\u52A1\u5668IP +DB_CONN_DIA_INVALID_SERVER_IP_MSG=\u670D\u52A1\u5668\u7684IP\u5730\u5740\u662F\u65E0\u6548\u7684.\u8BF7\u8F93\u5165\u6709\u6548\u7684IP\u5730\u5740. +DB_CONN_DIA_VALID_STATUS=\u670D\u52A1\u5668IP\u9A8C\u8BC1\u72B6\u6001\uFF1A +DB_CONN_DIA_CONN_PROFILE=\u5DF2\u521B\u5EFA\u8FDE\u63A5\uFF1A {0} +CREATE_SCHEMA_SUCCESS=\u5DF2\u521B\u5EFA\u6A21\u5F0F\uFF1A {0}.{1} +OBJECT_ITEM_REFRESHED=\u5237\u65B0 +REMOVE_SERVER=\u670D\u52A1\u5668 + +ADD_NEW_COLUMN=\u6DFB\u52A0\u65B0\u5217 + +DB_CONN_DIA_MOM_USAGE= \u5185\u5B58\u4F7F\u7528\u60C5\u51B5 +DB_CONN_DIA_MOM_USAGE_MSG= \u5185\u5B58\u4F7F\u7528\u7387\u8FBE\u523090\uFF05.\u8BF7\u5173\u95ED\u672A\u4F7F\u7528\u7684\u7EC4\u4EF6. +DB_CONN_DIA_GAUSS_SERVER_ERROR=\u8FDE\u63A5\u670D\u52A1\u5668\u51FA\u9519 +DB_CONN_DIA_REASON=\u539F\u56E0 +DB_CONN_DIA_GUI_ERROR_MSG=\u56FE\u5F62\u7528\u6237\u754C\u9762\uFF1A\u8FDE\u63A5\u670D\u52A1\u5668\u5931\u8D25. +DB_CONN_DIA_CONN_PROFILE_ERROR= \u521B\u5EFA\u8FDE\u63A5\u914D\u7F6E\u6587\u4EF6\u51FA\u9519. +DB_CONN_DIA_FUN_TRI_PROC=\u51FD\u6570/\u8FC7\u7A0B/\u89E6\u53D1\u5668 +DB_CONN_DIA_UPDATE_OBJ_BROW_ERROR=\u66F4\u65B0\u5BF9\u8C61\u6D4F\u89C8\u5668\u65F6\u51FA\u9519. + +ADD_MSG =\u6DFB\u52A0 +EDIT_MSG =\u7F16\u8F91 +DELETE_MSG=\u5220\u9664 +UP_MSG =\u5411\u4E0A +DOWN_MSG=\u5411\u4E0B +UPDATE_MSG= \u66F4\u65B0 +CANCEL_MSG= \u53D6\u6D88 + +USER_INPUT_PSW_DIA_MSG=\u8FDE\u63A5\u5230\u8BE5\u6570\u636E\u5E93 + +INDEX_UI_NAME=\u7D22\u5F15\u540D +INDEX_UI_MSG=\u8BF7\u9009\u62E9\u7D22\u5F15\u5217 +INDEX_UI_UNIQUE_INDEX= \u552F\u4E00\u7D22\u5F15 +INDEX_UI_FILLFACTOR=\u586B\u5145\u56E0\u5B50 +INDEX_UI_PARTIAL_INDEX= \u90E8\u5206\u7D22\u5F15\uFF1AWHERE \u8868\u8FBE\u5F0F +INDEX_UI_USER_EXPRESSION=\u7528\u6237\u81EA\u5B9A\u4E49\u8868\u8FBE\u5F0F +INDEX_UI_OR=\u6216 +INDEX_UI_AVA_COLUMNS=\u53EF\u7528\u5217 +INDEX_UI_INDEX_CLMS=\u7D22\u5F15\u5217 +INDEX_UI_ADD_TO=\u589E\u52A0\u7D22\u5F15 +INDEX_UI_REMOVE=\u4ECE\u7D22\u5F15\u4E2D\u5220\u9664 +INDEX_UI_MOVE_UP=\u5347\u7EA7 +INDEX_UI_MOVE_DOWN=\u964D\u7EA7 +INDEX_UI_TYPE=\u7d22\u5f15\u7c7b\u578b +INDEX_UI_ACCESS_METHOD=\u8BBF\u95EE\u65B9\u5F0F +INDEX_UI_TABLESPACE=\u8868\u7A7A\u95F4 + +DATA_DIST_UI_HAST_FUN=HASH\u51FD\u6570\u7684\u9009\u62E9 + +DATA_DIST_UI_DEFAULT_DIST=\u9ED8\u8BA4\u5206\u5E03 +DATA_DIST_UI_DIST_TYPE= \u5206\u5E03\u7C7B\u578B + +DATA_DIST_UI_AVAI_CLMS=\u53EF\u7528\u5217 +DATA_DIST_UI_NEW_FUN=\u65B0\u5EFA\u6309\u94AE +DATA_DIST_UI_HASH_CLMNS= Hash\u5217 + +COL_NAME =\u5217\u540D +CREATE_NEW_TABLE=\u521B\u5EFA\u666E\u901A\u8868 +CREATE_TABLE_CLM_NAME=\u5217\u540D +CREATE_TABLE_DATA_TYPE= \u6570\u636E\u7C7B\u578B +CREATE_TABLE_CONSTRAINT=\u7EA6\u675F +CREATE_TABLE_ADD=\u6DFB\u52A0 +CREATE_TABLE_EDIT=\u7F16\u8F91 +CREATE_TABLE_DELETE=\u5220\u9664 + +CREATE_TABLE_GENERAL=\u4E00\u822C +CREATE_TABLE_COLUMNS=\u5217 + +CREATE_TABLE_INDEXES=\u7D22\u5F15 + +CREATE_TABLE_SQL_PREVIEW= SQL \u9884\u89C8 +CREATE_TABLE_EDIT_MSG= \u8BF7\u4ECE\u8868\u4E2D\u9009\u62E9\u81F3\u5C11\u4E00\u5217\u7F16\u8F91 +CREATE_TABLE_DELETE_MSG= \u8BF7\u4ECE\u8868\u4E2D\u9009\u62E9\u81F3\u5C11\u4E00\u5217\u5220\u9664 +CREATE_TABLE_CONSTRAINT_MSG= \u8BF7\u9009\u62E9\u5217\u7EA6\u675F\u6216\u68C0\u67E5\u91CD\u590D\u7684\u540D\u79F0 +CREATE_TABLE_CONST_EDIT_MSG= \u8BF7\u4ECE\u8868\u4E2D\u9009\u62E9\u81F3\u5C11\u4E00\u4E2A\u7EA6\u675F\u7F16\u8F91 +CREATE_TABLE_CONST_DELETE= \u8BF7\u4ECE\u8868\u4E2D\u9009\u62E9\u81F3\u5C11\u4E00\u4E2A\u7EA6\u675F\u5220\u9664 +CREATE_TABLE_VALID_NAME= \u8BF7\u8F93\u5165\u6709\u6548\u7684\u5217\u540D +CREATE_TABLE_COLUMN_EXISTS = {0} \u5217\u5df2\u5b58\u5728\u3002 +CREATE_TABLE_NO_CLM_MSG= \u60A8\u8FD8\u6CA1\u6709\u9009\u62E9\u4EFB\u4F55\u5217\u6216\u6CA1\u6709\u66F4\u591A\u7684\u884C\u53EF\u79FB\u52A8 +CREATE_TABLE_FINISH_BTN=\u5B8C\u6210 +CREATE_TABLE_NEXT_BTN=\u4E0B\u4E00\u6B65 +CREATE_TABLE_BACK_BTN=\u4E0A\u4E00\u6B65 +CREATE_TABLE_ENTER_TABLE_NM=\u8BF7\u8F93\u5165\u8868\u540D. +CREATE_TABLE_CREATE_SUCCESS=\u5DF2\u521B\u5EFA\u8868\uFF1A {0} +CREATE_TABLE_CREATE_ERROR=\u521B\u5EFA\u8868\u65F6\u51FA\u9519\uFF1A{0} +CREATE_TABLE_SCEMA=\u6A21\u5F0F +CREATE_TABLE_TABLE_NAME=\u8868\u540D +CREATE_TABLE_CASE=\u533A\u5206\u5927\u5C0F\u5199 +CREATE_TABLE_NORMAL=\u6B63\u5E38 +CREATE_TABLE_UNLOGGED=UNLOGGED +CREATE_TABLE_TEMPORARY = \u4E34\u65F6 +CREATE_TABLE_TYPE= \u8868\u7C7B\u578B +CREATE_TABLE_OPTIONS=\u9009\u9879 +CREATE_TABLE_NOT_EXISTS= \u5982\u679C\u4E0D\u5B58\u5728 +CREATE_TABLE_OIDS= \u5E26OIDS +CREATE_TABLE_FILL_FACTOR= \u586B\u5145\u56E0\u5B50 + +CREATE_TABLE_DESC=\u8BBE\u7F6E\u8868\u63CF\u8FF0 +CREATE_TABLE_INDEX_DEF=\u7D22\u5F15\u5B9A\u4E49 +CREATE_TABLE_CLM_DELETE=\u8BF7\u4ECE\u8868\u4E2D\u9009\u62E9\u81F3\u5C11\u4E00\u4E2A\u7D22\u5F15\u5220\u9664 +CREATE_TABLE_CLM_EDIT=\u8BF7\u4ECE\u8868\u4E2D\u9009\u62E9\u81F3\u5C11\u4E00\u4E2A\u7D22\u5F15\u7F16\u8F91 + +ENTER_NEW_NAME_FOR = \u8F93\u5165{0}\u6A21\u5F0F\u7684\u65B0\u540D\u79F0. +RENAME_SCHEMA = \u91CD\u547D\u540D\u6A21\u5F0F +DB_RENAME_RENAMED = \u5DF2\u5C06 {0} \u6A21\u5F0F\u91CD\u547D\u540D\u4E3A {1}\u3002 +CONNECTION_ERR_DURING_REMANING = \u91CD\u547D\u540D{0}\u6A21\u5F0F\u65F6\u8FDE\u63A5\u9519\u8BEF.{1}{2} +RENAMING_SCHEMA = \u91CD\u547D\u540D\u6A21\u5F0F\uFF0C\u8BF7\u7A0D\u5019... +NEW_NAME_FOR_SCHEMA_TO_CONTINUE = \u8BF7\u4E3A\u6A21\u5F0F\u8F93\u5165\u65B0\u540D\u79F0\uFF0C\u65B9\u53EF\u7EE7\u7EED\u64CD\u4F5C... + +DB_RENAME_RENAMING = \u91CD\u547D\u540D{0}\u6A21\u5F0F\u5931\u8D25.{1}{2} + +ENTER_NEW_NAME_FOR_DB = \u4E3A{0}\u6570\u636E\u5E93\u8F93\u5165\u65B0\u540D\u79F0. +DB_RENAME_RENAMING_DATABASE = \u91CD\u547D\u540D{0}\u6570\u636E\u5E93\uFF0C\u8BF7\u7A0D\u5019... +DB_RENAME_RENAMED_DATABASE = \u5DF2\u5C06{0} \u6570\u636E\u5E93\u91CD\u547D\u540D\u4E3A {1}\u3002 +RENAME_DATABASE = \u91CD\u547D\u540D\u6570\u636E\u5E93 +ERR_SAVE_SQL_HANDLER=\u4FDD\u5B58SQL\u6587\u4EF6\u65F6\u51FA\u9519\uFF1A{0} + +DATABASE_RENAME_CONFIRMATION = \u91CD\u547D\u540D\u6570\u636E\u5E93\u9700\u8981\u65AD\u5F00\u8FDE\u63A5\uFF0C\u4F60\u786E\u5B9A\u8981\u91CD\u547D\u540D\u6570\u636E\u5E93\u5417\uFF1F + +UNABLE_TO_CONNECT_TO_DATABASE = \u65E0\u6CD5\u8FDE\u63A5\u6570\u636E\u5E93''{0}''{1}\u6D88\u606F\uFF1A{2}{3} + +ERR_WHILE_RENAMING_DATABASE = \u91CD\u547D\u540D{0}\u65F6\u51FA\u9519{1} + +REMOVE_SEVER = \u786E\u8BA4\u5220\u9664\u8FDE\u63A5 +REMOVE_SERVER_CONFIRMATION = \u5728\u5220\u9664\u8FDE\u63A5\u4E4B\u524D\u6240\u6709\u6570\u636E\u5E93\u5C06\u88AB\u65AD\u5F00.{0}\u662F\u5426\u786E\u5B9E\u8981\u5220\u9664''{1}''\u670D\u52A1\u5668\uFF1F \ + \n\ + \n\ + \u8BF4\u660E: \u65AD\u5F00\u6570\u636E\u5E93\u8FDE\u63A5\u53EF\u80FD\u4F1A\u53D6\u6D88\u6B63\u5728\u6267\u884C\u7684SQL\u8BED\u53E5 +SERVER_REMOVED =\u5DF2\u5220\u9664\u670D\u52A1\u5668\uFF1A {0} + +REFRESH_IN_PROGRESS = \u5237\u65B0\u8FDB\u5EA6 +MEMORY_USAGE = \u5185\u5B58\u4F7F\u7528\u60C5\u51B5 +MEMORY_USAGE_WARNING =\u5185\u5B58\u4F7F\u7528\u7387\u8FBE\u523090\uFF05.\u8BF7\u5173\u95ED\u672A\u4F7F\u7528\u7684\u7EC4\u4EF6. +ERR_WHILE_REFRESHING =\u5237\u65B0\u65F6\u51FA\u9519\u3002 + +PLSQL_ERR = PLSQL\u672A\u77E5\u9519\u8BEF +UNKNOWN_INTERNAL_ERR = \u53D1\u751F\u672A\u77E5\u5185\u90E8\u9519\u8BEF.\u8BF7\u8054\u7CFB\u7684Data Studio\u6280\u672F\u652F\u6301\u56E2\u961F\u4E86\u89E3\u65E5\u5FD7\u8BE6\u60C5\u3002 + +ERR_DURING_REFRESHING = \u5237\u65B0\u5BF9\u8C61\u65F6\u51FA\u9519\uFF1A {0} + +PROP_HANDLER_PROPERTIES_ERROR = \u5C5E\u6027\u9519\u8BEF +PROP_HANDLER_PROPERTIES = {0} \u5C5E\u6027 +PROPERTIES_WARNING = \u83B7\u53D6\u5C5E\u6027\u65F6\u51FA\u9519.\u9519\u8BEF\uFF1A{0} + +HLP_DOC_NOT_EXIST = \u5E2E\u52A9\u6587\u4EF6\u4E0D\u5B58\u5728 +UNABLE_TO_FIND_HLP_DOC = \u65E0\u6CD5\u627E\u5230\u5E2E\u52A9\u6587\u6863. + +ROWS_AFFECTED = \u64CD\u4F5C\u5F71\u54CD\u7684\u8BB0\u5F55\u884C\u6570 : {0} + +DISPLAY_SOURCE_CODE_FAILED = \u663E\u793A\u6E90\u4EE3\u7801\u5931\u8D25 +ERR_OCCURED_WHILE_DISPLAYING_CODE = \u5728\u6E90\u4EE3\u7801\u67E5\u770B\u5668\u663E\u793A\u6E90\u4EE3\u7801\u65F6\u51FA\u9519 +FETCHING_SOURCE_CODE_FAILED = \u83B7\u53D6\u6E90\u4EE3\u7801\u65F6\u51FA\u9519\uFF1A {0} +HANDLER_UTILITIES_CANNOT = \u65E0\u6CD5{0}\u51FD\u6570/\u8FC7\u7A0B +HANDLER_UTILITIES_CANNOT_PERFORM = \u65E0\u6CD5{0}\u51FD\u6570/\u8FC7\u7A0B\u4E3A\u4E0D\u652F\u6301\u7684\u6570\u636E\u7C7B\u578B\u5B58\u5728\u53C2\u6570\u5217\u8868\u4E2D\uFF08{1}\uFF09. + +ERR_GUI_SOURCE_NOT_AVAILABLE_HANDLER = \u6E90\u4EE3\u7801\u4E0D\u53EF\u7528\u4E8E\uFF1A {0} + +FILE_OVERWRITE = \u6587\u4EF6\u8986\u76D6\u786E\u8BA4 + +COULD_NOT_SET_READABLE = \u65E0\u6CD5\u4E3A\u5BFC\u51FA\u7684\u6587\u4EF6\u8BBE\u7F6E\u53EF\u8BFB/\u5199\u6807\u8BB0. +EXPORT_TABLE = \u8868''{0}''\u6570\u636E\u5BFC\u51FA\u6210\u529F +ERR_EXPORT_TABLE_TO_CSV_HANDLER = \u5BFC\u51FA\u8868\u6570\u636E\u65F6\u51FA\u9519.{0}\u9519\u8BEF:{1} + +DATA_EXPORTED_TO = \u6570\u636E\u6210\u529F\u51FA\u53E3\u5230''{0}''\u7684\u6587\u4EF6. + +EXIT_APPLICATION = \u9000\u51FA\u5E94\u7528\u7A0B\u5E8F + +EXIT_APPLICATION_CONFIRMATION = \u786E\u5B9A\u8981\u9000\u51FA\u5E94\u7528\u7A0B\u5E8F\u5417\uFF1F \ + \n \u8BF4\u660E\uFF1A \ + \n \u5F3A\u5236\u9000\u51FA\uFF1A\u76F4\u63A5\u9000\u51FA\uFF0C\u4E0D\u4FDD\u5B58\u5C1A\u672A\u4FDD\u5B58\u7684\u5386\u53F2\u6267\u884CSQL \ + \n \u6807\u51C6\u9000\u51FA\uFF1A\u9000\u51FA\u524D\u4FDD\u5B58\u5C1A\u672A\u4FDD\u5B58\u7684SQL\u5386\u53F2\u548C\u67E5\u8BE2/\u51FD\u6570/\u8FC7\u7A0B\u3002 \ + \n\ + \n \u5176\u4ED6\u672A\u4FDD\u5B58\u6570\u636E\u5C06\u4F1A\u4E22\u5931\u3002 + +EXCEPTION_OCCURED_WHILE_FETCHING_OBJECTS = \u83B7\u53D6\u6570\u636E\u5E93\u5BF9\u8C61\u65F6\u53D1\u751F\u5F02\u5E38\u3002 +GRACEFULL_EXIT_DATASTUDIO=\u6807\u51C6\u9000\u51FA +FORCE_EXIT_DATSTUDIO = \u5F3A\u5236\u9000\u51FA + +DATABASE_CONNECTION_ERR = \u6570\u636E\u5E93\u8FDE\u63A5\u9519\u8BEF + +ERR_QUERY_LENGTH_TOO_BIG = \u67E5\u8BE2\u8D85\u51FA\u4E0A\u9650\uFF0C\u65E0\u6CD5\u5904\u7406 +OPERATION_CANNOT_BE_PERFOREMD = \u64CD\u4F5C\u4E0D\u80FD\u88AB\u6267\u884C.\u5931\u8D25\uFF0C\u9519\u8BEF\uFF1A{0} +ERR_WHILE_STARTING_EXECUTE_SQL = \u5728\u5BF9\u8C61\u6D4F\u89C8\u5668\u4E2D\u6267\u884CSQL\u5BF9\u8C61\u65F6\u51FA\u9519 + +SOURCE_CODE_CHANGE = \u6539\u53D8\u6E90\u4EE3\u7801 +SOURCE_HAS_BEEN_CHANGED = \u6E90\u4EE3\u7801\u5DF2\u7ECF\u6539\u53D8\u4E86\uFF0C\u4F60\u786E\u5B9A\u8981\u7F16\u8BD1\u548C\u6267\u884C\uFF1F +EXECUTION_FAILED_ITEM = \u6267\u884C\u5931\u8D25{0}\u9519\u8BEF\u4EE3\u7801\uFF1A[{1}]{2} +ERR_WHILE_STARTING_TO_EXECUTE_SQL_OBJECT = \u5F00\u59CB\u5C1D\u8BD5\u4ECESourceViewer\u6E90\u4EE3\u7801\u67E5\u770B\u5668\u4E2D\u6267\u884CSQL\u5BF9\u8C61\u65F6\u9519\u8BEF\u51FA\u9519. + +DROP_SCHEMA = \u5220\u9664\u6A21\u5F0F +DROP_SCHEMA_CONFIRMATION = \u786E\u5B9A\u8981\u5220\u9664\u201C''{0}''\u201D\u6A21\u5F0F\u5417\uFF1F +DB_DROPPED = \u5DF2\u5220\u9664\u6A21\u5F0F\uFF1A {0}.{1} +DROP_SUCCESS = \u6210\u529F\u6A21\u5F0F +ERR_WHILE_DROPPING_SCHEMS = \u5220\u9664''{0}''\u6A21\u5F0F\u51FA\u9519.\u670D\u52A1\u5668\u6D88\u606F\uFF1A{1} +ERR_WHILE_DROPPING_SCHEMS_MESSAGE = \u5220\u9664''{0}''\u6A21\u5F0F.{1} \u670D\u52A1\u5668\u6D88\u606F\uFF1A{2} + +ERR_WHEN_DROPPING_SCHEMA = \u5220\u9664\u6A21\u5F0F\u65F6\u51FA\u9519 +SERVER_MSG = \u670D\u52A1\u5668\u6D88\u606F\uFF1A +CONNECTION_ERR_WHEN_DROPPING_SCHEMA = \u5220\u9664''{0}''\u6A21\u5F0F\u65F6\u8FDE\u63A5\u9519\u8BEF.\u670D\u52A1\u5668\u6D88\u606F\uFF1A{1} + +DROP_FUNC_PROC = \u5220\u9664\u51FD\u6570/\u8FC7\u7A0B +DROP_FUNC_PROC_CONFIRMATION = \u786E\u5B9A\u8981\u5220\u9664''{0}''\u51FD\u6570/\u8FC7\u7A0B\u5417\uFF1F +FUNC_PROC_DROPPED = ''{0}''\u51FD\u6570/\u8FC7\u7A0B\u5DF2\u5220\u9664\u3002 + +ERR_DROP_FUNC_PROC = \u5220\u9664\u51FD\u6570/\u8FC7\u7A0B\u65F6\u51FA\u9519\u3002 +EXECUTION_FAILED = \u6267\u884C\u5931\u8D25{0}\u9519\u8BEF\u4EE3\u7801\uFF1A[{1}]{2} + +DROP_DATABASE = \u5220\u9664\u6570\u636E\u5E93 +DROP_DATABASE_ALERT = \u5220\u9664\u6570\u636E\u5E93\u524D\u5C06\u88AB\u65AD\u5F00\u8FDE\u63A5.{0}\u662F\u5426\u786E\u5B9E\u8981\u5220\u9664''{1}''\u6570\u636E\u5E93 +DB_DROPPED_DATABASE = \u5DF2\u5220\u9664\u6570\u636E\u5E93\uFF1A {0}.{1} + +DATABASE_SUCCESSFULLY = \u5DF2\u521B\u5EFA\u6570\u636E\u5E93\uFF1A {0}.{1} +ERR_WHEN_DROPPING_DB = \u5220\u9664\u6570\u636E\u5E93\u65F6\u51FA\u9519 +UNABLE_TO_DROP_DB = \u5220\u9664\u6570\u636E\u5E93\u65F6\u51FA\u9519\uFF1A {0}.{1} + +UNABLE_TO_DROP = \u65E0\u6CD5\u5220\u9664'{0}''\u6570\u636E\u5E93.\u670D\u52A1\u5668\u6D88\u606F\uFF1A{1} + +ERROR_DURING_SCHEMA_CREATION = \u521B\u5EFA\u6A21\u5F0F\u65F6\u51FA\u9519\uFF1A {0}.{1} +DATABASE_DISCONNECT = \u65AD\u5F00\u8FDE\u63A5\u786E\u8BA4 +DISCONNECT_CONFIRMATION = \u786E\u5B9A\u8981\u65AD\u5F00''{0}''\u5417\uFF1F \ + \n\ + \u8BF4\u660E: \u65ad\u5f00\u6570\u636e\u5e93\u8fde\u63a5\u53ef\u80fd\u4f1a\u53d6\u6d88\u6240\u6709\u6b63\u5728\u8fdb\u884c\u7684\u6570\u636e\u5e93\u64cd\u4f5c\u3002 + +DISCONNECTED_FROM_SERVER = \u5DF2\u65AD\u5F00\u6570\u636E\u5E93\u8FDE\u63A5\uFF1A {0}.{1} + +DISCONNECT_ALL_DB = \u5DF2\u65AD\u8FDE\u6240\u6709\u8FDE\u63A5\u7684\u6570\u636E\u5E93\uFF1A {0} + +ENTER_SCHEMA_NAME_TO_CONTINUE = \u7EE7\u7EED\u8F93\u5165\u6A21\u5F0F\u540D\u79F0... +STATUS_CREATING_SCHEMA = \u521B\u5EFA\u65B0\u7684\u6A21\u5F0F\u4E2D\uFF0C\u8BF7\u7A0D\u5019... +ERROR_WHILE_CREATING_SCHEMA = \u5EFA\u7ACB\u6A21\u5F0F\u51FA\u9519.{0} {1} +CONNECTION_ERROR_DURING_SCHEMA_CREATION = \u6A21\u5F0F\u521B\u5EFA\u8FC7\u7A0B\u4E2D\u8FDE\u63A5\u9519\u8BEF.{0} {1} + +CREATE_SCHEMA = \u521B\u5EFA\u6A21\u5F0F +ENTER_SCHMEA_NAME = \u8F93\u5165\u6A21\u5F0F\u540D +DS_DEFAULT_ENCODING = \u7F16\u7801\u65E0\u6548 {0}\uFF0C\u5C06\u8BBE\u4E3A\u9ED8\u8BA4\u503C\uFF08UTF-8\uFF09\u3002 + +DS_DEFAULT_CONSOLE_LINE_COUNT = ConsoleLineCount\u914D\u7F6E\u65E0\u6548\u3002\u6B63\u5728\u8BBE\u4E3A\u6700\u5C0F\u503C\uFF081000\uFF09\u3002 + +DS_INVALID_ENABLE_SECURITY_WARNING = \u6307\u5B9A\u7684enableSecurityWarning\u503C\u65E0\u6548\u3002\u6B63\u5728\u8BBE\u4E3A\u9ED8\u8BA4\u503C\u3002 + +ENTER_DATABASE_NAME_TO_CREATE = \u8F93\u5165\u521B\u5EFA\u7684\u6570\u636E\u5E93\u540D\u79F0 +CREATING_DATABASE = \u521B\u5EFA\u6570\u636E\u5E93\uFF0C\u6B63\u5728\u5904\u7406\u4E2D\u2026 +ERROR_WHILE_CREATING_DATABASE = \u521B\u5EFA\u6570\u636E\u5E93\u51FA\u9519.{0} {1} + +NAME_OF_THE_DATABASE = \u6570\u636E\u5E93\u7684\u540D\u79F0 +CURRENT_USER_CIPHER_TO_CONNECT_TO_DB = \u5F53\u524D\u7528\u6237\u7684\u5BC6\u7801\u8FDE\u63A5\u5230\u6570\u636E\u5E93 + +SUCCESSFULLY_CONNECTED_TO = \u5DF2\u8FDE\u63A5\u5230\u6570\u636E\u5E93\uFF1A {0}.{1} +CONNECTION_ERR = \u8FDE\u63A5\u51FA\u9519 +LOADING_OBJECT_INTO_BROWSER = \u6B63\u5728\u52A0\u8F7D\u6570\u636E\u5E93\u5BF9\u8C61\u3002 +OBJECT_SUCCESSFULLY_LOADED = \u5DF2\u52A0\u8F7D\u6570\u636E\u5E93\u5BF9\u8C61\u3002 +ENTRE_CIPHER = \u8F93\u5165\u5BC6\u7801 +ENTER_CURRENT_USER_CIPHER = \u8F93\u5165\u5F53\u524D\u7528\u6237\u5BC6\u7801\uFF1A + +LOGIN_TIMEOUT_CHECKED_FAILED = \u767B\u5F55\u8D85\u65F6\u68C0\u67E5\u5931\u8D25 +TIMEOUT_VALUE_CHECK_FAILED = \u68C0\u67E5Data Studio\u767B\u5F55\u8D85\u65F6\u5931\u8D25 +ENTER_VALID_TIMEOUT_VALUE = \u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u8F93\u5165\u6709\u6548\u7684\u8D85\u65F6\u503C\u3002 + +JDK_VERSION_CHECK_FAILED = JDK\u7248\u672C\u68C0\u67E5\u5931\u8D25 +IDE_JDK_VERSION_CHECK_FAILED = Data Studio \u7684JDK\u7248\u672C\u68C0\u67E5\u5931\u8D25. +ENTER_VALID_JDK_VERSION = \u8BF7\u8F93\u5165\u6709\u6548\u7684JDK\u7248\u672C\u7EE7\u7EED. + +EXE_TERMINAL_EXC_TIME_MSG= \u6267\u884C\u65F6\u95F4 : {0} \u6BEB\u79D2 +EXE_TERMINAL_EXC_TIME_MSG_RESULT= \u6267\u884C\u65F6\u95F4 : {0} +CREATE_DATABASE=\u521B\u5EFA\u6570\u636E\u5E93 + +UNABLE_TO_CONNECT_TO_DATABASE_DB = \u65E0\u6CD5\u8FDE\u63A5\u6570\u636E\u5E93\"{0}\"{1}\u6D88\u606F\uFF1A{2} +ADD_COLUMN = \u5DF2\u521B\u5EFA\u5217\uFF1A {0}.{1} +ERR_WHILE_ADDING_COL = \u589E\u52A0\u65B0\u5217\u65F6\u9519\u8BEF +UNABLE_TO_ADD_COL = \u65E0\u6CD5\u6DFB\u52A0\u5217. {0}\u670D\u52A1\u5668\u6D88\u606F\uFF1A{1} +TABLE_ANALYZED = \u5DF2\u5206\u6790\u8868\uFF1A {0}.{1} +TABLE_ANALYZED_ERROR = \u5206\u6790\u8868\u65F6\u51FA\u9519\uFF1A {0}.{1} +TABLE_ANALYZED_CONNECTION_ERROR = \u5206\u6790\u8868\u65F6\u53D1\u751F\u8FDE\u63A5\u9519\u8BEF\uFF1A {0}.{1} +PLS_ENTER_COL_NAME = \u8BF7\u8F93\u5165\u5217\u540D +PLS_SELECT_DATA_TYPE = \u8BF7\u9009\u62E9\u6709\u6548\u7684\u6570\u636E\u7C7B\u578B +CREATE_INDEX= \u521B\u5EFA\u7D22\u5F15 +CREATE_INDEX_SET_TEXT=\u4F2A/\u7A7A +CREATE_INDEX_GENERATE_QUERY=\u751F\u6210\u67E5\u8BE2\uFF1A +CREATE_INDEX_PREVIEW= \u9884\u89C8\u67E5\u8BE2 +CREATE_INDEX_BTN=\u521B\u5EFA +CREATE_INDEX_SUCCESS=\u5DF2\u521B\u5EFA\u7D22\u5F15\uFF1A{0}.{1} + +CREATE_INDEX_ERROR=\u521B\u5EFA\u7D22\u5F15\u65F6\u51FA\u9519\uFF1A{0}.{1} +CREATE_INDEX_CONN_ERROR=\u521B\u5EFA\u7684\u7D22\u5F15{0}\u65F6\u8FDE\u63A5\u5931\u8D25. +UNABLE_TO_ADD_CONS = \u65E0\u6CD5\u6DFB\u52A0\u65B0\u7684\u7EA6\u675F.{0}\u670D\u52A1\u5668\u6D88\u606F\uFF1A{1} + +ERR_WHILE_STNG_COL_VAL = \u8BBE\u7F6E\u5217\u7F3A\u7701\u503C\u65F6\u51FA\u9519 +PLS_ENTER_TABLE_FOR_CONS = = \u8BF7\u9009\u62E9\u7EA6\u675F\u5F15\u7528\u5217 +CUURENT_DFLT_VAL = \u5F53\u524D\u7f3a\u7701\u503C\uFF1A{0} +CUURENT_DFLT_VALUE=\u7f3a\u7701\u503C\uFF1A +CONSTRAINT_TYPE=\u7EA6\u675F\u7C7B\u578B +CONSTRAINT_NAME=\u7EA6\u675F\u540D +CONSTRAINT_DESC=\u8BF7\u9009\u62E9\u81F3\u5C11\u4E00\u5217\u4F5C\u4E3A\u5916\u952E\u5F15\u7528 +CONSTRAINT_SELECTED_COLUMNS=\u9009\u5B9A\u7684\u5217 +DATA_TYPE_CONVERSION_TIP = \u63d0\u793a\uff1a\u501f\u52a9\u9690\u5f0f\u7c7b\u578b\u8f6c\u6362\uff0c\u6709\u4e9b\u7c7b\u578b\u8f6c\u6362\u53ef\u80fd\u4f1a\u5931\u8d25 +UPDATE_DATA_TYPE = \u66F4\u6539\u6570\u636E\u7C7B\u578B +TYPE_DES = \u7C7B\u578B\u8BF4\u660E +CURRENT_DATA_TYPE = {0}\u5217\u5f53\u524d\u6570\u636e\u7c7b\u578b: {1} +CHANGE_DATA_TYPE_FOR_COL =\u5DF2\u4FEE\u6539\u8BE5\u5217\u7684\u6570\u636E\u7C7B\u578B\uFF1A{0}.{1}.{2} + +ERR_CHANGE_DTYPE = \u9519\u8BEF - \u66F4\u6539\u6570\u636E\u7C7B\u578B +UNABLE_TO_CHANGE_DTYPE_OF = \u4FEE\u6539\u8BE5\u5217\u7684\u6570\u636E\u7C7B\u578B\u65F6\u51FA\u9519\uFF1A {0}.{1}.{2} + +SET_COL_VAL_OF_DEFAULT_TYPE = \u8BBE\u7F6E\u5217\u7F3A\u7701\u503C\uFF1A {0}.{1}.{2} +UNABLE_TO_SET_COL_VAL = \u65E0\u6CD5\u8BBE\u7F6E\u5217\u7F3A\u7701\u503C.{0}\u670D\u52A1\u5668\u6D88\u606F\uFF1A{1} +DTYPE_SCHEMA = \u6A21\u5F0F\u6570\u636E\u7C7B\u578B +DATA_TYPE = \u6570\u636E\u7C7B\u578B +SIZE = \u7CBE\u5EA6/\u5927\u5C0F +SCALE_MSG = \u8303\u56F4 +COL_CONS = \u5217\u7EA6\u675F +NOT_NULL = \u975E\u7A7A +UNIQUE_MSG = \u552F\u4E00 +CASE_MSG = \u533A\u5206\u5927\u5C0F\u5199 +CONSTRAINT_AVAILABLE_COLUMNS= \u53EF\u7528\u5217 +CONSTRAINT_NEW_BTN= \u65B0\u5EFA\u6309\u94AE +CONSTRAINT_ON_TABLESPACE= \u5728\u8868\u7A7A\u95F4 +CONSTRAINT_DEFERABLE=\u5EF6\u8FDF +ARRAY_DIMENSIONS = \u9635\u5217\u7EF4\u5EA6 +CHECK_COLUMN_UI =\u68C0\u67E5 +DFLT_CLM_UI =\u7f3a\u7701 + +ON_DELETE = \u5220\u9664 +REF_COL = \u5F15\u7528\u5217 +ADD_NEW_CONSTRAINT =\u6DFB\u52A0\u65B0\u7EA6\u675F +EDIT_CONSTRAINT =\u7f16\u8f91\u7ea6\u675f +ALTER_COLUMN_SHELL_TEXT=\u4e3a {0}.{1}.{2}\u8bbe\u7f6e\u7f3a\u7701\u503c +EDIT_CONSTRAINT_LABEL=\u5F53\u524D\u8868\u8FBE\u5F0F: +CONSTRAINT_INITIALLY_DEFERRED= \u521D\u59CB\u5316\u5EF6\u8FDF +CONSTRAINT_FILL_FACTOR=\u586B\u5145\u56E0\u5B50 +CONSTRAINT_COLUMN_NAME=\u5217\u540D +CONSTRAINT_DATA_TYPE=\u6570\u636E\u7C7B\u578B + +AVL_COL = \u53EF\u7528\u5217 +CONSTRAINT_EXPRESSION=\u8BF7\u8F93\u5165\u68C0\u67E5\u7EA6\u675F\u7684\u8868\u8FBE\u5F0F +CONSTRAINT_CHECK_EXPRESSION=\u68C0\u67E5\u8868\u8FBE\u5F0F + +CONSTRAINT_FOREIGN_NAMESPACE =\u547d\u540d\u7a7a\u95f4 +CONSTRAINT_FOREIGE_TABLENAME =\u8868\u540d\u79f0 +CONSTRAINT_FOREIGE_COLUMNNAME =\u5217\u540d + +NEW_NONAME_CONSTRAINT_CREATED = \u5DF2\u5C06\u65B0\u7EA6\u675F\u6DFB\u52A0\u5230\u8BE5\u8868\uFF1A {0}.{1} +NEW_CONSTRAINT_CREATED = \u5DF2\u521B\u5EFA\u7EA6\u675F\uFF1A {0}.{1}.{2} +ERR_WHILE_ADDING_CONSTRAINT = \u589E\u52A0\u65B0\u7EA6\u675F\u65F6\u9519\u8BEF + +EXEC_DEBUG_DIALOG_OUT_PARA_MSG=\u5BF9\u4E8E\u8F93\u51FA\u53C2\u6570\u6CA1\u6709\u4F20\u9012\u503C +EXECUTION_PLAN_DISPLAY=\u6267\u884C\u8BA1\u5212 : +GENERAL_MSG=\u4E00\u822C +COLUMN_MSG=\u5217 +DATA_DIST=\u6570\u636E\u5206\u5E03 +TABLE_CONS=\u8868\u7EA6\u675F +INDEX_MSG=\u7D22\u5F15 + +SQL_PREVIEW=SQL\u9884\u89C8 +OID_MSG=OID +NAME_MSG=\u540D\u79F0 +ENCODING_MSG=\u5B57\u7B26\u7F16\u7801 +ALLOW_CON=\u662f\u5426\u5141\u8bb8\u8fde\u63a5 +CONNECTION_LIMIT=\u8FDE\u63A5\u6570\u9650\u5236 +DFLT_TBSPACE=\u9ED8\u8BA4\u8868\u7A7A\u95F4 +COLLECTION_MSG=\u6392\u5E8F\u89C4\u5219 +CHAR_TYPE=\u5B57\u7B26\u7C7B\u578B +TABLESPACE_MSG=\u8868\u7A7A\u95F4 +IS_TEMP=\u662F\u5426\u4E34\u65F6\u8868 +TYEP_MSG=\u7C7B\u578B +OWNER_MSG=\u6240\u6709\u8005 +PAGES_MSG= \u9875\u6570 +ROW_COUNT=\u884C\u6570(\u5DF2\u4F30\u7B97) +HAS_INDEX=\u662F\u5426\u5305\u542B\u7D22\u5F15 +IS_SHARED=\u662F\u5426\u5171\u4EAB + +OPTION_MSG=\u9009\u9879 +DESC_MSG=\u63CF\u8FF0 + +GUI_PLSOURCEEDITORCORE_REMOVE_ANNOTATION = \u56FE\u5F62\u7528\u6237\u754C\u9762: \u6E90\u7F16\u8F91\u5668\u5185\u6838: \u79FB\u9664\u6CE8\u91CA +GUI_PLSOURCEEDITORCORE_ADD_ANNOTATION = \u56FE\u5F62\u7528\u6237\u754C\u9762: \u6E90\u7F16\u8F91\u5668\u5185\u6838: \u6DFB\u52A0\u6CE8\u91CA +GUI_PLSOURCEEDITORCORE_SOURCE_EDITOR_CLEARED = \u56FE\u5F62\u7528\u6237\u754C\u9762: \u6E90\u7F16\u8F91\u5668\u5185\u6838: \u5DF2\u6E05\u9664\u6E90\u7F16\u8F91\u5668 + +MOVING_TABLE_SELECTED_TABLESPACE_SUCCESFULL = \u6210\u529F\u5C06\u8868\u79FB\u5230\u6240\u9009\u8868\u7A7A\u95F4: + +CLEARED_CONSOLE_CONTENTS = \u5DF2\u6E05\u9664\u6D88\u606F\u5185\u5BB9 +GUI_FORMATTING_SQL_QUERY_STATEMENTS_FROM_FORMAT_MENU = \u56FE\u5F62\u7528\u6237\u754C\u9762: \u6B63\u5728\u4ECE\u683C\u5F0F\u5316\u83DC\u5355\u683C\u5F0F\u5316SQL\u67E5\u8BE2\u8BED\u53E5 +NEGATIVE_NUMBER = \u8D1F\u6570: {0} + +GUI_CREATE_FUNCTION = u56FE\u5F62\u7528\u6237\u754C\u9762\uFF1A\u521B\u5EFA\u51FD\u6570 +GUI_CREATE_PROCEDURE = \u521B\u5EFA\u8FC7\u7A0B + +GUI_DROPDEBUGOBJECT_DROP_DEBUG_OBJECT = \u56FE\u5F62\u7528\u6237\u754C\u9762\uFF1ADropDebugObject\uFF1A\u5220\u9664\u8C03\u8BD5\u5BF9\u8C61 +GUI_EXECUTEEDITORITEM_EXECUTE_CLICKED =\u56FE\u5F62\u7528\u6237\u754C\u9762\uFF1AExecuteEditorItem\uFF1A \u70B9\u51FB\u6267\u884C +GUI_EXECUTEOBJECTBROWSERITEM_EXECUTE_OBJECT_BROWSER_CLICKED =\u56FE\u5F62\u7528\u6237\u754C\u9762\uFF1AExecuteObjectBrowserItem\uFF1A\u70B9\u51FB\u6267\u884C\u5BF9\u8C61\u6D4F\u89C8\u5668 +GUI_EXECUTED_SQL_TERMINAL_STATEMENT = \u56FE\u5F62\u7528\u6237\u754C\u9762: \u6267\u884CSQL\u7EC8\u7AEF\u8BED\u53E5 +TIME_BY_TAKEN_APPLICATION_EXECUTE_QUERY = \u5E94\u7528\u7A0B\u5E8F\u6267\u884C\u67E5\u8BE2\u8017\u65F6{0} +GUI_EXITAPPLICATION_EXIT_CLICKED = \u56FE\u5F62\u7528\u6237\u754C\u9762\uFF1AExitApplication\uFF1A \u70B9\u51FB\u9000\u51FA +GUI_APPLICATION_EXITED = \u56FE\u5F62\u7528\u6237\u754C\u9762: \u5E94\u7528\u7A0B\u5E8F\u5DF2\u9000\u51FA + +LOCALE_CHANGE_CONFIG_FILE=/Data Studio.ini +LOCALE_CHANGE_CONFIG_ERR_TITLE= \u914D\u7F6E\u9519\u8BEF +LOCALE_CHANGE_CONFIG_ERR_MES= \u65E0\u6CD5\u627E\u5230Data Studio\u7684\u914D\u7F6E\u6587\u4EF6\u3002 +LOCALE_CHANGE_RD_WD_ERROR=\u8BFB/\u5199\u914D\u7F6E\u6587\u4EF6\u65F6\u51FA\u9519\u3002 +LOCALE_CHANGE_APP_RESTART_TITLE=Data Studio\u5373\u5C06\u91CD\u542F +LOCALE_CHANGE_APP_RESTART_MSG=\u6240\u6709\u7684\u8FDE\u63A5\u5C06\u88AB\u5173\u95ED\uFF0C\u6240\u6709\u672A\u4FDD\u5B58\u7684\u6570\u636E\u90FD\u5C06\u4E22\u5931\u3002\u4F60\u60F3\u73B0\u5728\u91CD\u65B0\u542F\u52A8\uFF1F +LOCALE_CHANGE_APP_RESTART_NOTE=\u6CE8\u610F\uFF1A +LOCALE_CHANGE_APP_RESTART_NOTE_NO= \u5982\u679C\u9009\u62E9\u201C\u5426\u201D\uFF0C\u5373\u4F7FData Studio\u91CD\u542F\u4E5F\u4E0D\u4F1A\u6539\u53D8\u5F53\u524D\u8BED\u8A00\u3002 + + +TYPE_ALIGN = \u6309\u7C7B\u522B\u5206\u6790 + +FUNCTION_PROCEDURE_NAME = \u51FD\u6570/\u8FC7\u7A0B + +DATATYPE_NAME = \u6570\u636E\u7C7B\u578B + +ACCESS_METHOD_NAME = \u8BBF\u95EE\u65B9\u6CD5 +COLUMNS_NAME = \u5217 +CONSTRAINTS_NAME = \u7EA6\u675F +INDEXES_NAME = \u7D22\u5F15 + +TITLE_IMPORT_TBL_DATA =\u5BFC\u5165\u8868\u6570\u636E + +MSG_IMPORT_SUCCESS =\u5DF2\u5BFC\u5165\u6570\u636E\u5230\u8BE5\u8868\uFF1A {0}.{1} +MSG_TOTAL_ROWS_IMPORT = \u5bfc\u5165\u7684\u603b\u8bb0\u5f55\u6570\uff1a{0} +ERR_IMPORT_TABLE_TO_CSV=\u9519\u8BEF\u5728\u5BFC\u5165\u8868\u6570\u636E\u3002 +ERR_IMPORT_TABLE_TO_CSV_HANDLER = \u5BFC\u5165\u8868\u6570\u636E\u9519\u8BEF{0}{1} +STATUS_MSG_IMPORT_TABLE_DATA = \u5BFC\u5165\u8868\u6570\u636E... + +BTN_OK = \u786E\u5B9A +BTN_CANCEL = \u53D6\u6D88 +BTN_CLEAR = \u6e05\u7a7a + +MSG_DO_NOT_SHOW_AGAIN =\u4E0D\u518D\u663E\u793A +TITLE_DISCLAIMER = Data Studio \u5B89\u5168\u8B66\u544A +TITLE_OPEN_SQL =\u6253\u5F00SQL +MSG_SELECT_SQL_FILE =\u8BF7\u53EA\u9009\u62E9SQL\u6587\u4EF6\u3002 +MSG_SELECT_FILE_DOES_NOT_EXIST =\u6240\u9009\u6587\u4EF6\u4E0D\u5B58\u5728\u3002\u8BF7\u9009\u62E9\u6B63\u786E\u7684\u6587\u4EF6\u3002 +MSG_NEED_APPEND_OVERWRITE =\u4F60\u60F3\u8986\u76D6SQL\u6216\u8FFD\u52A0\uFF1F +BTN_LABEL_APPEND = \u9644\u52A0 +BTN_LABEL_OVERWRITE = \u8986\u76D6 +MSG_APPEND_OVERWRITE_SUCCESS = {0}SQL\u5230SQL\u7EC8\u7AEF\u3002 +ERR_OUT_OF_MEMORY_OCCURED = \u5185\u5B58\u4E0D\u8DB3\uFF1A\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u589E\u52A0\u5806\u5185\u5B58\u5927\u5C0F\u3002 +ERR_OUT_OF_MEMORY_SEARCH_OCCURED =\u5185\u5B58\u4E0D\u8DB3\uFF1A\u8BF7\u5230DS\u5B89\u88C5\u76EE\u5F55\u4E0B\u7684\u914D\u7F6E\u6587\u4EF6\ + \n \u201CData Studio.ini\u201D\u589E\u52A0\u5806\u5185\u5B58\u5927\u5C0F\uFF08\u793A\u4F8B\uFF1A-Xmx2048m\uFF09\uFF0C\u5E76\u91CD\u542FDS\u4F7F\u5176\u751F\u6548\u3002 +ERR_OUT_OF_MEMORY_REOCCURED = \u65E0\u6CD5\u4FDD\u7559\u73B0\u6709\u7684\u5185\u5BB9 +TITLE_OUT_OF_MEMORY = \u5185\u5B58\u4E0D\u8DB3 +TITLE_SAVE_SQL = \u4FDD\u5B58SQL +MSG_SQL_SAVE_SUCCESS =\u5DF2\u4FDD\u5B58SQL\uFF1A {0} \u65F6\u95F4: {1} + +MSG_EXPORT_SUCC_FILE = \u4ECE{0}\u9875\u7B7E\u5BFC\u51FA\u5F53\u524D\u9875\u9762\u7ED3\u679C\u6570\u636E +MSG_EXPORT_EXEC_SUCC_FILE = \u4ECE{0}\u9875\u7B7E\u5BFC\u51FA\u7684\u6570\u636E +TITLE_EXPORT_IN_PROGRESS = \u51FA\u53E3\u8FDB\u5EA6 + +ERR_WHILE_EXPORTING = \u3002\u5728\u5BFC\u51FA\u67E5\u8BE2\u6570\u636E\u9519\u8BEF\\u9519\u8BEF\uFF1A +GUI_NEWDBCONNECTION_OPEN_CONNECTION_WIZARD=\u7528\u6237\u624B\u518C... + +CIPHER_EXPIRE_CONFIRMATION = \u5BC6\u7801\u8FC7\u671F\u4FE1\u606F +CIPHER_EXPIRED = \u5BC6\u7801\u5DF2\u8FC7\u671F\u3002\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458\u66F4\u6539\u5BC6\u7801\u3002 +CIPHER_YET_TO_EXPIRE = \u8be5\u5bc6\u7801\u5c06\u5728 {0} \u5929\u540e\u8fc7\u671f\u3002\u8bf7\u66f4\u6539\u5bc6\u7801\u3002 + +MSG_LOADED = \u52A0\u8F7D + +FILE_PERMISSION =\u6587\u4EF6\u6743\u9650 +FILE_PERMISSION_ERROR = \u8BBE\u7F6E\u6587\u4EF6\u6743\u9650\u5931\u8D25\u3002 + +ERR_SQL_FILE_READ = SQL\u6587\u4EF6\u8BFB\u53D6\u9519\u8BEF +MSG_TOTAL_ROWS_EXPORT = \u5BFC\u51FA\u7684\u603B\u8BB0\u5F55\u6570\uFF1A{0} +TITLE_EXPORT_DATA = \u5BFC\u51FA\u6570\u636E + +INCORRECT_PATH = \u4E0D\u6B63\u786E\u7684\u8DEF\u5F84 +INCORRECT_PATH_MSG = \u6307\u5B9A\u7684\u8DEF\u5F84\u4E0D\u6B63\u786E\u6216\u4E0D\u5B58\u5728\u3002\u65E5\u5FD7\u5C06\u5728\u9ED8\u8BA4\u4F4D\u7F6E\u521B\u5EFA\u3002 + +ERR_GUI_DEBUG_CONNECTION_ERROR=\u8FDE\u63A5\u9519\u8BEF + +ERR_IO_ERROR_EXPORT = \u5411\u6587\u4EF6\u4E2D\u5199\u6570\u636E\u65F6\u51FA\u9519 +SQL_TERMINAL_EXEC = \u7F16\u8BD1\/\u6267\u884C +IO_EXCEPTION_WHILE_EXPORT = \u5BFC\u51FA\u65F6IO\u4EA7\u751F\u4E86\u5F02\u5E38\uFF0C\u8BF7\u91CD\u65B0\u8FDE\u63A5\u6570\u636E\u5E93\u3002 +EMPTY_PLSOURCE_TITEL=\u9519\u8BEF +EMPTY_PLSOURCE_VIEWER=\u51FD\u6570\u6216\u5B58\u50A8\u8FC7\u7A0B\u6CA1\u6709\u5B9A\u4E49 +NAMESPACE_RETRIVE_ERROR=\u5728\u540E\u53F0\u83B7\u53D6\u8868\u7A7A\u95F4{0}\u6570\u636E\u65F6\u51FA\u9519\u3002 +TABLE_RETRIVE_ERROR=\u5728\u540E\u53F0\u83B7\u53D6\u8868{0}\u6570\u636E\u65F6\u51FA\u9519\u3002 + +UI_CANCEL_QUERY_MSG=\u53D6\u6D88\u540E\u53EF\u80FD\u6709\u4E00\u4E2A\u6216\u591A\u4E2A\u8BED\u53E5\u672A\u88AB\u6267\u884C +SQL_QUREY_CANCEL_MSG=\u6309\u7167\u7528\u6237\u8BF7\u6C42\u7EC8\u6B62\u67E5\u8BE2 +SQL_QUERY_CANCEL_CANCELMSG=\u7EC8\u6B62\u67E5\u8BE2\u65F6\u62A5\u9519 +SQL_QUERY_CANCELMSG_PROGRESS=\u63D0\u4EA4\u53D6\u6D88\u7684\u67E5\u8BE2\uFF0C\u8BF7\u53C2\u8003\u53D6\u6D88\u8FDB\u5EA6\u72B6\u6001\u680F\u3002 +SQL_BUTTON_TOOL_TIP=\u53D6\u6D88 + +ERR_DS_SECURITY_ERROR=\u52A0\u5BC6/\u89E3\u5BC6\u65F6\u4EA7\u751F\u9519\u8BEF\u3002\n +TITLE_DS_SECURITY= Data Studio\u5B89\u5168\u9519\u8BEF +SECURITY_FAILURE_SUGGESTION=1.\u5728Data Studio\u5B89\u88C5\u8DEF\u5F84\u4E0B\u5220\u9664security\u6587\u4EF6\u5939\uFF08UserData > \u4EE5\u5F53\u524D\u64CD\u4F5C\u7CFB\u7EDF\u7528\u6237\u547D\u540D\u7684\u6587\u4EF6\u5939 > security\uFF09\n2.\u91CD\u542FData Studio + +EDIT_DATA_WIZARD_TITLE=\u7F16\u8F91\u8868\u6570\u636E\u5411\u5BFC + +CANCEL_OPERATION_TITLE= \u53D6\u6D88\u64CD\u4F5C +CANCEL_OPERATION_MSG= \u786E\u8BA4\u8981\u53D6\u6D88\u64CD\u4F5C\u5417\uFF1F + +CANCEL_EXPORT_SUCCES_DAILOG_TITLE=\u6570\u636E\u5BFC\u51FA\u6210\u529F +CANCEL_EXPORT_FAIL_DAILOG_TITLE=\u6570\u636E\u5BFC\u51FA\u5931\u8D25 +CANCEL_EXPORT_JOB_NAME=\u6B63\u5728\u5BFC\u51FA\u6570\u636E\uFF1A{0} +CANCEL_EXPORT_SUCCES_CONSOLE_MESSAGE=\u5DF2\u53D6\u6D88\u5BFC\u51FA\u3002 +CANCEL_IMPORT_SUCCES_DAILOG_TITLE=\u6570\u636E\u5BFC\u5165\u6210\u529F +CANCEL_IMPORT_FAIL_DAILOG_TITLE=\u6570\u636E\u5BFC\u5165\u5931\u8D25 +CANCEL_IMPORT_JOB_NAME=\u6B63\u5728\u5BFC\u5165\u6570\u636E\uFF1A{0} +CANCEL_IMPORT_SUCCES_CONSOLE_MESSAGE=\u5DF2\u53D6\u6D88\u7528\u6237\u7684\u5BFC\u5165\u6570\u636E\u8BF7\u6C42 +CANCEL_IMPORTEXPORT_CONSOLE= \u53D6\u6D88\u64CD\u4F5C +CANCEL_IMPORTEXPORT_CONSOLE_MSG= \u8BF7\u786E\u8BA4\u53D6\u6D88\u64CD\u4F5C\u3002 +CANCEL_EXPORT_CANCELMSG=\u5BFC\u51FA\u67E5\u8BE2\u65F6\u51FA\u9519\u3002. +CANCEL_IMPORT_CANCELMSG=\u5BFC\u5165\u67E5\u8BE2\u65F6\u51FA\u9519\u3002 + +CANCEL_WINDOW_TITLE=\u8FDB\u5EA6\u89C6\u56FE +NO_PROPOSAL =\u6CA1\u6709\u5EFA\u8BAE +AUTO_SUGGEST_LOADING=\u6B63\u5728\u52A0\u8F7D\u2026\u2026 + +SQL_QUERY_EXECUTE=\u5728SQL\u7EC8\u7AEF\u6267\u884C\u4EFB\u52A1: {0} +STATUS_JOB_SI=\u8FD0\u884C\u4F5C\u4E1A +STATUS_JOB=\u8FD0\u884C\u4F5C\u4E1A + +CANCEL_PROGRESS_TABLE_HEARDER=\u8FDB\u7A0B\u6B63\u5728\u8FD0\u884C + +DS_EXIT_CONFIRMATION_TITLE=\u9000\u51FA\u786E\u8BA4 + +ERROR_READING_DATA=\u8BFB\u53D6\u884C\u6570\u636E\u65F6\u62A5\u9519 + +DISCARD_CHANGES_TITLE =\u786E\u8BA4\u653E\u5F03\u4FEE\u6539 +SAVE_CHANGES_TITLE =\u4FDD\u5B58/\u653E\u5F03\u66F4\u6539 + +COPY_ADVANCED_RESULT_WINDOW_CONTENTS=\u9AD8\u7EA7\u590D\u5236 (Ctrl+Shift+C) +COPY_RESULT_WINDOW_CONTENTS=\u590D\u5236 (Ctrl+C) + +RESULT_WINDOW_SQL_SEARCH_EXECUTE=\u6587\u672C\u6A21\u5F0F\u6B63\u5728\u6267\u884C\u641C\u7D22:{0} +RESULT_WINDOW_SQL_REFRESH_EXECUTE=\u6587\u672C\u6A21\u5F0F\u6B63\u5728\u6267\u884C\u5237\u65B0:{0} +RESULT_WINDOW_SQL_LOADING_EXECUTE=\u6587\u672C\u6A21\u5F0F\u6B63\u5728\u6267\u884C\u52A0\u8F7D:{0} +RESULT_WINDOW_SQL_ENCODING_EXECUTE=\u6587\u672C\u6A21\u5F0F\u6B63\u5728\u6267\u884C\u8F6C\u7801:{0} +RESULT_WINDOW_SHOW_GRID=\u7F51\u683C +RESULT_WINDOW_SHOW_TEXT=\u6587\u672C +RESULT_WINDOW_TEXT_CELL_VALUE_DIALOG_TITLE=\u5217\u503C\uFF1A +RESULT_WINDOW_TEXT_CELL_INVISIBLE_VALUE_TITLE=\u6570\u636E\u957F\u5EA6\u8B66\u544A +RESULT_WINDOW_TEXT_CELL_INVISIBLE_VALUE_BODY=\u6570\u636E\u91CF\u592A\u5927\uFF0C\u65E0\u6CD5\u5B8C\u6574\u663E\u793A\u3002 \ +\n\u5DF2\u62F7\u8D1D\uFF0C\u8BF7\u9ECF\u8D34\u5230\u5176\u5B83\u7F16\u8F91\u5668\u8FDB\u884C\u67E5\u770B\u3002 + +EXPORT_CSV_STAR = \u5BFC\u51FA\u6240\u6709\u6570\u636E +EXPORT_CSV = \u5BFC\u51FA\u5F53\u524D\u9875\u6570\u636E +EXPORT_EXEC = \u5BFC\u51FA\u6267\u884C\u8BA1\u5212 +CLEAR_CONSOLE = \u6e05\u9664 + +MENU_OPEN = \u6253\u5F00 +MENU_SAVE = \u4FDD\u5B58 +MENU_SAVE_AS = \u53E6\u5B58\u4E3A +MENU_FIND = \u67E5\u627E\u548C\u66FF\u6362 + +INFO_MAX_SOURCE_VIEWER = \u6807\u7B7E\u6570\u9650\u5236\u5DF2\u8FBE\u5230\u6700\u5927\u9650\u5236. \u8BF7\u5173\u95ED\u4E0D\u7528\u7684\u6807\u7B7E\u540E\u5C1D\u8BD5 + +MAX_SOURCE_VIEWER = \u6700\u5927\u6807\u7B7E\u6570 + +TABLESPACES_NAME = \u8868\u7A7A\u95F4 +DATABASES_NAME = \u6570\u636E\u5E93 +USER_NAMESPACE_NAME = \u7528\u6237\u6A21\u5F0F +SYSTEM_NAMESPACE_NAME = \u7CFB\u7EDF\u6A21\u5F0F +STATUS_MSG_DROP_TABLESPACE =\u6B63\u5728\u91CA\u653E\u8868\u7A7A\u95F4... +DROP_TABLESPACE_DIA_TITLE =\u5220\u9664\u8868\u7A7A\u95F4 +DROP_TABLESPACE = \u662F\u5426\u786E\u5B9A\u91CA\u653E''{0}'' \u8868\u7A7A\u95F4? +ERR_WHEN_DROPPING_TABLESPACE =\u91CA\u653E\u8868\u7A7A\u95F4\u65F6\u51FA\u9519 +DROP_TABLESPACE_SUCCESS=\u5DF2\u5220\u9664\u8868\u7A7A\u95F4\uFF1A {0}.{1} + +ERR_WHILE_DROPPING_TABLESPACE_MESSAGE = \u5220\u9664\u8868\u7A7A\u95F4\u65F6\u51FA\u9519\uFF1A {0}.{1} +CONNECTION_ERR_WHEN_DROPPING_TABLESPACE = \u5220\u9664\u8868\u7A7A\u95F4\u65F6\u53D1\u751F\u8FDE\u63A5\u9519\u8BEF\uFF1A {0}.{1} +STATUS_MSG_CREATE_TABLESPACE =\u6B63\u5728\u521B\u5EFA\u8868\u7A7A\u95F4... +CREATE_TABLESPACE_DIA_TITILE = \u521B\u5EFA\u8868\u7A7A\u95F4 +TABLESPACE_SUCCESSFULLY = \u5DF2\u521B\u5EFA\u8868\u7A7A\u95F4\uFF1A {0}.{1} +CREATING_TABLESPACE = \u6B63\u5728\u521B\u5EFA\u8868\u7A7A\u95F4, \u6B63\u5728\u5904\u7406\u4E2D... +CONNECTION_ERROR_DURING_TABLESPACE_CREATION = \u5728\u521B\u5EFA\u8868\u7A7A\u95F4\u65F6\u53D1\u751F\u8FDE\u63A5\u9519\u8BEF.{0}{1} +ERROR_WHILE_CREATING_TABLESPACE =\u5F53\u521B\u5EFA\u8868\u7A7A\u95F4{0}{1}.\u65F6\u51FA\u9519 +STATUS_MSG_RENAME_TABLESPACE = \u6B63\u5728\u91CD\u547D\u540D\u6570\u636E\u5E93... +RENAME_TABLESPACE_NEW_NAME=\u4E3A{0}\u8868\u7A7A\u95F4\u8F93\u5165\u65B0\u7684\u540D\u79F0 +RENAME_TABLESPACE_WAIT=\u6B63\u5728\u91CD\u547D\u540D\u8868{0}, \u6B63\u5728\u5904\u7406\u4E2D.. +RENAME_TABLESPACE_DIA_TITILE = \u91CD\u547D\u540D\u8868\u7A7A\u95F4 +RENAME_TABLESPACE_NEW=\u4E3A{0}\u8868\u7A7A\u95F4\u8F93\u5165\u65B0\u7684\u540D\u79F0 +RENAME_TABLESPACE_TO= \u5C06{0}\u8868\u7A7A\u95F4\u91CD\u547D\u540D\u4E3A{1}.{2}\u3002 +CONNECTION_ERR_DURING_RENAMING_TABLESPACE = \u91CD\u547D\u540D\u8868\u7A7A\u95F4.{0}\u65F6\u51FA\u9519:{1} +ERR_WHILE_RENAMING_TABLESPACE = \u5F53\u91CD\u547D\u540D {0}.{1} \u65F6\u51FA\u9519 : {2} +SET_TABLESPACE_OPTION = \u8BBE\u7F6E\u8868\u7A7A\u95F4\u9009\u9879 +SET_TABLESPACE_OPTION_SUCCESS = \u5DF2\u66F4\u65B0\u8868\u7A7A\u95F4\u9009\u9879\uFF1A {0}.{1} +SET_TABLESPACE_OPTION_ERROR= \u8BBE\u7F6E\u8868\u7A7A\u95F4\u9009\u9879\u65F6\u51FA\u9519\uFF1A{0}.{1} +STATUS_MSG_OPTION_TABLESPACE = \u6B63\u5728\u8BBE\u7F6E\u8868\u7A7A\u95F4\u64CD\u4F5C... +CONNECTION_ERR_DURING_SETTING_TABLESPACE_OPTION = \u8BBE\u7F6E\u8868\u7A7A\u95F4\u9009\u9879\u65F6\u53D1\u751F\u8FDE\u63A5\u9519\u8BEF\uFF1A {0}.{1} +STATUS_MSG_RESIZE_TABLESPACE = \u6B63\u5728\u91CD\u65B0\u8BBE\u7F6E\u8868\u7A7A\u95F4\u5927\u5C0F... +SET_MAX_SIZE = \u8BBE\u7F6E\u8868\u7A7A\u95F4\u6700\u5927\u5B58\u50A8 +RESIZE_TABLESPACE_NEW_NAME =\u7ED9\u8868\u7A7A\u95F4''{0}'' \u8F93\u5165\u65B0\u7684\u5927\u5C0F. +RESIZE_TABLESPACE_SUCCESS =\u5DF2\u66F4\u65B0\u8868\u7A7A\u95F4{1}\u6700\u5927\u5927\u5C0F\u4E3A{0} +SET_TABLESPACE_RESIZING_ERROR= \u8C03\u6574\u6700\u5927\u8868\u7A7A\u95F4\u5927\u5C0F\u65F6\u51FA\u9519\uFF1A{0}.{1} + +PREF_SYNTAX_COLORING_TITLE=\u8BED\u6CD5\u9AD8\u4EAE +PREF_SYNTAX_COLORING_MSG=\u8BED\u6CD5\u9AD8\u4EAE\u8BBE\u7F6E\u533A\u57DF +PREF_SYNTAX_COLORING_SINGLE_LINE_COMM=\u6CE8\u91CA +PREF_SYNTAX_COLORING_DEFAULT=\u9ED8\u8BA4\u503C +PREF_SYNTAX_COLORING_UNRESERVED_KEY=\u975E\u4FDD\u7559\u5173\u952E\u5B57 +PREF_SYNTAX_COLORING_RESERVED_KEY=\u4FDD\u7559\u5173\u952E\u5B57 +PREF_SYNTAX_COLORING_TYPE=\u6570\u636E\u7C7B\u578B +PREF_SYNTAX_COLORING_PREDICATE=\u7B26\u53F7 +PREF_SYNTAX_COLORING_CONSTANTS=\u5E38\u91CF +PREF_SYNTAX_COLORING_STRINGS=\u5B57\u7B26\u4E32 + +PREF_SYNTAX_COLORING_SAVE_FAIL_MSG=\u4FDD\u5B58\u8BED\u6CD5\u9AD8\u91CF\u8BBE\u7F6E\u5230\u6587\u4EF6\u51FA\u9519 +PREF_SYNTAX_COLORING_LOAD_FAIL_MSG=\u4ECE\u6587\u4EF6\u52A0\u8F7D\u7279\u6027\u8BBE\u7F6E\u65F6 + +PREF_SYNTAX_COLORING_SAVE_FAIL_TITLE=\u4FDD\u5B58\u8BBE\u7F6E\u5931\u8D25 +PREF_SYNTAX_COLORING_LOAD_FAIL_TITLE=\u52A0\u8F7D\u8BBE\u7F6E\u5931\u8D25 + +ENABL_ING = \u542F\u7528 +DISABL_ING = \u7981\u7528 +REMOVE_BP = \u79FB\u9664 + +DATABASE_ENCODING=\u6570\u636E\u5E93\u7F16\u7801 + +DATABASE_CONNECTION_LIMIT_REACHED = \u8FDE\u63A5\u6570({0}) \u5DF2\u8FBE\u5230\u6570\u636E\u5E93\u7684\u4E0A\u9650. \u8BF7\u5173\u6389\u4E0D\u7528\u7684\u7A97\u53E3\u548C\u8FDB\u7A0B. +VIEWS_NAME = \u89C6\u56FE +VIEW_COLUMNS_NAME=\u5217\u540D +DROP_VIEW_SUCCESS = \u5DF2\u5220\u9664\u89C6\u56FE\uFF1A{0}.{1}.{2} +DROP_VIEW_CASCADE_SUCCESS = \u5DF2\u5220\u9664\u89C6\u56FE\u548C\u4ECE\u5C5E\u5BF9\u8C61\uFF1A{0}.{1} +DROP_VIEW_FAILURE_TITLE = \u5220\u9664\u89C6\u56FE\u51FA\u9519 +DROP_VIEW_FAILURE = \u65E0\u6CD5\u5220\u9664\u89C6\u56FE {0}. {1}\u670D\u52A1\u5668\u9519\u8BEF\u4FE1\u606F: {2} +DROP_VIEW_UNABLE_MSG= \u89C6\u56FE\u5220\u9664\u9519\u8BEF {0} +RENAME_VIEW_SUCCESS=\u5DF2\u5C06{0}\u89C6\u56FE\u91CD\u547D\u540D\u4E3A{1}.{2}\u3002 +RENAME_VIEW_TITLE = \u91CD\u547D\u540D\u89C6\u56FE +ENTER_NEW_VIEW_NAME = \u4E3A {0} \u89C6\u56FE\u8F93\u5165\u65B0\u7684\u540D\u5B57 + +RENAME_VIEW_FAILURE = \u65E0\u6CD5\u4E3A\u89C6\u56FE {0}\u91CD\u547D\u540D. \u670D\u52A1\u5668\u9519\u8BEF\u4FE1\u606F: {1} +SET_VIEW_SCHEMA_SUCCESS = \u8BE5\u89C6\u56FE\u5DF2\u4ECE{0}.{1}\u79FB\u52A8\u5230{2}.{3}\u3002 +SET_VIEW_SCHEMA = \u8BBE\u7F6E\u6A21\u5F0F +SET_VIEW_MESSAGE = \u4E3A\u89C6\u56FE {0}.{1}\u8BBE\u7F6E\u65B0\u6A21\u5F0F + +SET_VIEW_SCHEMA_FAILURE = \u65e0\u6cd5\u4e3a\u89c6\u56fe {0}{1}\u8bbe\u7f6e\u6a21\u5f0f\uff0c\u670d\u52a1\u5668\u9519\u8bef\u4fe1\u606f\uff1a{2} +SET_VIEW_SCHEMA_MOVING=\u79FB\u52A8 {0} \u89C6\u56FE\u5230 {1} \u6A21\u5F0F. \u8BF7\u7B49\u5F85... +DROP_VIEW_CONFIRM_TITLE = \u5220\u9664\u89C6\u56FE +DROP_VIEW_CONFIRM_MSG = \u4F60\u786E\u5B9A\u8981\u5220\u9664 ''{0}'' \u89C6\u56FE? +DROP_VIEW_CASCADE_CONFIRM_MSG=\u4F60\u786E\u5B9A\u8981\u5220\u9664 ''{0}'' \u89C6\u56FE\u4EE5\u53CA\u548C\u5B83\u76F8\u5173\u8054\u7684? + +VIEW_COLUMN_SET_DEFAULT_TITLE = \u4E3A {0}.{1}.{2}\u8BBE\u7F6E\u7f3a\u7701\u503C +SET_VIEW_COL_DEFAULT_STATUS_BAR=\u8BBE\u7F6E\u89C6\u56FE\u5217\u9ED8\u8BA4\u503C + +CONSOLE_TAB = \u6D88\u606F +RESULT_TAB = \u7ED3\u679C +EXECUTION_PLAN_TAB = \u6267\u884C\u8BA1\u5212 + +DS_EXIT_MSG_FOR_JOBS=\u7A0B\u5E8F\u6B63\u5728\u8FD0\u884C\uFF0C\u4F60\u786E\u5B9A\u8981\u9000\u51FA\u5417? + +ERR_DROP_CON_PROF_FILE = \u5220\u9664\u8FDE\u63A5\u6587\u4EF6\u5939\u65F6\u5931\u8D25 + +ERR_PROFILE_WRITE_DISK = \u5411\u78C1\u76D8\u5199\u6587\u4EF6\u65F6\u51FA\u9519 + +ERR_PROFILE_WRITE_INVALID = \u5411\u78C1\u76D8\u5199\u6587\u4EF6\u65F6\u51FA\u9519 + +PERMANENTLY_SAVE = \u6C38\u4E45\u4FDD\u5B58 +CURRENT_SESSION_ONLY = \u4EC5\u5F53\u524D\u4F1A\u8BDD +DO_NOT_SAVE = \u4E0D\u4FDD\u5B58 + +CONNECTION_NAME = \u8FDE\u63A5\u540D\u79F0 +CONNECTION_DETAILS = \u8FDE\u63A5\u4FE1\u606F +ERR_BL_SQL_HISTORY_NOT_LOADED= \u52A0\u8F7DSQL\u5386\u53F2\u6CA1\u6709\u5B8C\u6210\uFF0C\u6B63\u5728\u5904\u7406\u4E2D\u518D\u8BD5 + +DELETE_SELECTED_HISTORY_ALERT= \u4F60\u786E\u5B9A\u8981\u5220\u9664\u201C{0}\u201D\u8FDE\u63A5\u914D\u7F6E\u6587\u4EF6\u7684\u9009\u5B9A\u7684SQL\u67E5\u8BE2\u5386\u53F2\uFF1F{1}{1}\u6CE8\u610F\uFF1A\u9501\u5B9A\u7684\u67E5\u8BE2\u4E0D\u80FD\u88AB\u5220\u9664 +DELETE_ALL_HISTORY_ALERT=\u4F60\u786E\u5B9A\u8981\u5220\u9664\u201C{0}\u201D\u8FDE\u63A5\u914D\u7F6E\u6587\u4EF6\u7684SQL\u67E5\u8BE2\u5386\u53F2\uFF1F{1}{1}\u6CE8\u610F\uFF1A\u9501\u5B9A\u7684\u67E5\u8BE2\u4E0D\u80FD\u88AB\u5220\u9664 + +DELETE_SQL = \u5220\u9664SQL +DELETE_ALL=\u5220\u9664\u5168\u90E8 +PREFERENCE_EXAMPLE= \u4F8B\u5982\uFF1A +SQL_DATA = \u5BFC\u51FA\u6570\u636E +SQL_DDL = \u5BFC\u51FA\u6A21\u5F0F +SQL_DDL_DATA = \u5BFC\u51FA\u6A21\u5F0F\u548C\u6570\u636E + +EXPORT_DDL_HEADER = \u5BFC\u51FA\u5B8C\u6210 +EXPORT_DDL_FAIL_HEADER = {0}\u5BFC\u51FA\u5931\u8D25 +EXPORT_DDL_SUCCESS = \u5C06{0}\u5BFC\u51FA\u81F3\u5982\u4E0B\u8DEF\u5F84\uFF1A{1} +EXPORT_DDL_FAIL = \u5BFC\u51FA\u5931\u8D25\uFF1A\u627E\u4E0D\u5230\u5916\u90E8\u5BFC\u51FA\u5DE5\u5177\u3002 + +EXPORT_FAIL_DISK_WRITE_ERROR=\u78C1\u76D8\u5199\u5165\u5931\u8D25. +EXPORT_FAIL_PROCESS_INTRUPTED=\u5BFC\u51FA/\u663E\u793ADDL\u6267\u884C\u8FC7\u7A0B\u5931\u8D25 :\ + \n{0} +EXPORT_FAIL_UNSUPPORTED_SERVER_VERSION = \u663E\u793A/\u5BFC\u51FADDL\u5DF2\u7981\u7528\u4E8E\u5F53\u524D\u7684\u6570\u636E\u5E93\u7248\u672C +CANNOT_LOCATE_GSDUMP=\u65E0\u6CD5\u627E\u5230\u5916\u90E8\u5BFC\u51FA\u5B9E\u7528\u7A0B\u5E8F (gs_dump). +EXPORT_CANCEL_ON_USER_REQUEST=\u5DF2\u6839\u636E\u60A8\u7684\u8BF7\u6C42\u53D6\u6D88\u5BFC\u51FA\u64CD\u4F5C. + +LOAD_SQL_TERMINAL = \u52A0\u8F7D\u81F3SQL\u7EC8\u7AEF +LOAD_TERMINAL_CLOSE_HISTORY = \u52A0\u8F7D\u81F3SQL\u7EC8\u7AEF\u5E76\u5173\u95ED +PIN_SQL = \u9501\u5B9ASQL +SERIAL_NO = \u5E8F\u53F7 +SQL_STATEMENT = SQL\u8BED\u53E5 +SQL_ROW_SELECTION=\u83B7\u53D6\u8BB0\u5F55\u6570 +DATABASE_NAME = \u6570\u636E\u5E93 +START_TIME = \u5F00\u59CB\u65F6\u95F4 +ELAPSED_TIME = \u6267\u884C\u65F6\u95F4 (\u6BEB\u79D2) +FINAL_STATUS = \u72B6\u6001 +PIN_STATUS = \u9501\u5B9A\u72B6\u6001 +PROFILE_NAME = \u914D\u7F6E\u6587\u4EF6\u72B6\u6001 +UNPIN_SQL =\u89E3\u9501SQL +SQL_HISTORY = \u5386\u53F2\u6267\u884CSQL +SQL_HISTORY_TOOL_TRIP = \u5386\u53F2\u6267\u884CSQL +SQL_HISTORY_DISABLED_TOOL_TIP = SQL\u6267\u884c\u5386\u53f2-\u8fde\u63a5\u4fe1\u606f\u672a\u52a0\u8f7d\u3002 +SQL_HISTORY_TITLE = \u5386\u53F2\u6267\u884CSQL - {0} +HISTORY_LOADING_IN_PROGRESS_TILTLE=\u6B63\u5728\u52A0\u8F7D\u5386\u53F2\u8BB0\u5F55 +CONN_PROFILE_ERROR_MSG=\u52A0\u8F7D\u7A0B\u5E8F\u6587\u4EF6:{0}\u65F6\u51FA\u9519\ . \u7A0B\u5E8F\u6587\u4EF6\u5DF2\u4ECE\u7A0B\u5E8F\u6587\u4EF6\u5217\u8868\u4E2D\u79FB\u9664 +SQL_AUTOCOMMIT_ON_TOOL_TIP = \u542F\u7528\u81EA\u52A8\u63D0\u4EA4 +SQL_AUTOCOMMIT_OFF_TOOL_TIP = \u7981\u7528\u81EA\u52A8\u63D0\u4EA4 + +SQL_AUTOCOMMIT_DISABLED_TOOL_TIP = \u542F\u7528/\u7981\u7528\u81EA\u52A8\u63D0\u4EA4\u2013\u65E0\u6D3B\u8DC3\u8FDE\u63A5 +ERR_SQL_AUTOCOMMIT_TOGGLE_TITLE = \u672A\u80FD\u542F\u7528\u81EA\u52A8\u63D0\u4EA4 +ERR_SQL_AUTOCOMMIT_TOGGLE = \u8BF7\u63D0\u4EA4\u6216\u56DE\u6EDA\u5F53\u524D\u4E8B\u52A1\u3002 +SQL_AUTOCOMMIT_SAVE_CHANGES_TITLE = \u4FDD\u5B58\u66F4\u6539 +SQL_AUTOCOMMIT_SAVE_CHANGES_MSG = \u65B0\u7684\u66F4\u6539\u5C06\u88AB\u4FDD\u5B58\uFF0C\u4F46\u4E0D\u4F1A\u63D0\u4EA4\u3002\n\u8BF7\u5728SQL\u7EC8\u7AEF\u4E2D\u6267\u884CCOMMIT\u547D\u4EE4\u4EE5\u63D0\u4EA4\u66F4\u6539\u3002 + +REMOVE_CONN_TITLE=\u5220\u9664\u8FDE\u63A5\u6587\u4EF6 +REMOVE_CONN_MSG=\u60A8\u786E\u5B9A\u8981\u79FB\u9664\u8FDE\u63A5\u6587\u4EF6\u5417\uFF1F +SELECT_CONN_TO_REMOVE=\u8BF7\u9009\u62E9\u4E00\u4E2A\u8981\u5220\u9664\u7684\u8FDE\u63A5\u6587\u4EF6 +REMOVE_PROFILE = \u5220\u9664\u8FDE\u63A5\u4FE1\u606F +HELP_LABEL = \u5E2E\u52A9 + +TABLESPACE_NAME=\u540D\u79F0* +TABLESPACE_RELATIVE_PATH=\u76F8\u5BF9\u8DEF\u5F84 +TABLESPACE_LOCATION=\u4f4d\u7f6e* +TABLESPACE_MAXSIZE=\u6700\u5927\u5b58\u50a8\u5bb9\u91cf +TABLESPACE_SEQCOST=\u987a\u5e8f\u78c1\u76d8\u9875\u9762\u5f00\u9500 +TABLESPACE_RANCOST=\u975e\u987a\u5e8f\u78c1\u76d8\u9875\u9762\u5f00\u9500 +TABLESPACE_UNSUPPORTED_SERVER_VERSION=\u670D\u52A1\u5668\u7248\u672C\u4E0D\u652F\u6301 +TABLESPACE_GENERAL=General +TABLE_EDIT_MESSAGE=\u5F53\u524D\u6B63\u5728\u7F16\u8F91\u5217\u3002\u5B8C\u6210\u6216\u53D6\u6D88\u7F16\u8F91\u64CD\u4F5C\u540E\u624D\u80FD\u6267\u884C\u5176\u4ED6\u64CD\u4F5C\u3002 +UNLIMITED_SIZE=\u4E0D\u9650\u5236\u5927\u5C0F +CONN_DIALOG_SAVE_CIPHER =\u4FDD\u5B58\u5BC6\u7801 + +CIPHER_DECRYPT_ERROR_MSG=\u52A0\u8F7D\u914D\u7F6E\u6587\u4EF6\u65F6\u51FA\u9519\uFF1A{ 0 }\u3002\u89E3\u5BC6\u8FD9\u4E9B\u914D\u7F6E\u6587\u4EF6\u7684\u5BC6\u7801\u5931\u8D25\uFF0C\u8BF7\u518D\u6B21\u8F93\u5165\u5BC6\u7801\u3002 + +MSG_DS__NO_DATA_ENCRYPT_DISCLAIMER = 1\uFF09Data Studio\u4E0D\u652F\u6301\u6570\u636E\u52A0\u5BC6\uFF0C\u9ED1\u5BA2\u53EF\u80FD\u8BBF\u95EE\u5230\u654F\u611F\u4FE1\u606F\u3002 \n\u5E94\u5BF9\u63AA\u65BD\uFF1A\u786E\u4FDD\u6587\u4EF6\u4FDD\u5B58\u5728\u5B89\u5168\u7684\u4F4D\u7F6E\u3002 + +MSG_DS__NO_DATA_ENCRYPT_DISCLAIMER_SECONDPART2 =\n2\uFF09Data Studio\u5BF9\u5BFC\u51FA\u7684\u6570\u636E\u6587\u4EF6\u4E0D\u8BBE\u7F6E\u4EFB\u4F55\u6743\u9650\u3002 \n\u5E94\u5BF9\u63AA\u65BD\uFF1A\u7528\u6237\u9700\u81EA\u884C\u8BBE\u7F6E\u6570\u636E\u6587\u4EF6\u6240\u5728\u6587\u4EF6\u5939\u7684\u6743\u9650\u3002 + +TABLESPACE_CREATION_SUCCEEDED = \u8868\u7A7A\u95F4\u521B\u5EFA\u6210\u529F +TABLESPACE_CREATION_FAILED = \u521B\u5EFA\u8868\u7A7A\u95F4\u5931\u8D25 +RUN_IN_BACK_GROUND = \u5728\u540E\u53F0\u6267\u884C + +SHORTCUT_MAPPER =\u5FEB\u6377\u952E +SELECT_SHORTCUTKEY = \u9009\u62E9\u5FEB\u6377\u952E : +MODIFY_KEY = \u4FEE\u6539 +UNBIND_KEY = \u53D6\u6D88\u5FEB\u6377\u952E +KEY_NAME = \u83DC\u5355\u540D\u79F0 : +BINDING_KEY = \u5FEB\u6377\u952E : +COMMAND_NAME = \u83DC\u5355\u540D\u79F0 +KEY_BINDING = \u5FEB\u6377\u952E +KEY_DESCRIPTION = \u63CF\u8FF0 +PREFERENCES_SHOW = \u9996\u9009\u9879 +PREF_LOAD_ERROR=\u9996\u9009\u9879\u51FA\u9519 +PREF_LOAD_MSG=\u65E0\u6548\u7684\u9996\u9009\u9879\u503C, \u5C06\u81EA\u52A8\u8BBE\u7F6E\u4E3A\u9ED8\u8BA4\u9996\u9009\u9879\u503C +PREF_FILE_ERR_TITLE =\u52A0\u8F7D\u6587\u4EF6\u65F6\u51FA\u9519 +PREF_FILE_ERR_MSG =\u52A0\u8F7D\u5FEB\u6377\u952E\u7ED1\u5B9A\u6587\u4EF6\u65F6\u51FA\u9519 + +PINNED_DELETION =\u65E0\u6CD5\u5220\u9664\u56FA\u5B9A\u7684\u67E5\u8BE2 +SELECT_QUERY_TO_DELETE = \u8BF7\u9009\u62E9\u81F3\u5C11\u4E00\u4E2A\u67E5\u8BE2\u6765\u5220\u9664 +CONNECTION_ERR_DURING_RESIZING_TABLESPACE =\u8C03\u6574\u8868\u7A7A\u95F4\u5927\u5C0F\u65F6\u8FDE\u63A5\u9519\u8BEF\u3002{0}\u9519\u8BEF\u4FE1\u606F\uFF1A{1} + +PREFERENCE_DEFAULT=\u6062\u590D\u9ED8\u8BA4(&D) +PREFERENCE_APPLY=\u5E94\u7528(&A) + +PREFERENCEDIALOG_OK = \u786E\u8BA4 +PREFERENCEDIALOG_CANCEL = \u53D6\u6D88 + +DES_NEW_CONN =\u65B0\u5EFA\u8FDE\u63A5 +DISSCONN_FRM_DB =\u65AD\u5F00\u6570\u636E\u5E93\u8FDE\u63A5 +EXE_DB_OBJECT =\u6267\u884C\u8FC7\u7A0B\u6216\u51FD\u6570 +REF_SREVER_OBJECT = \u5237\u65B0\u670D\u52A1\u5668\u5BF9\u8C61 +EXE_SQL_TERMINAL = \u5728SQL\u7EC8\u7AEF\u4E2D\u6267\u884C\u8BED\u53E5 +EXECUTION_PLAN_AND_COST=\u663E\u793A\u67E5\u8BE2\u7684\u6267\u884C\u8BA1\u5212 +VISUAL_EXPLAIN_PLAN=\u53EF\u89C6\u5316\u7684\u67E5\u8BE2\u6267\u884C\u8BA1\u5212 +FORMAT_SQL_STATEMENT =\u683C\u5F0F\u5316SQL\u7EC8\u7AEF\u548C\u5B58\u50A8\u8FC7\u7A0B/\u51FD\u6570\u6E90\u67E5\u770B\u5668\u4E2D\u7684\u8BED\u53E5 +OPEN_SAVED_FILE = \u5728SQL\u7EC8\u7AEF\u4E2D\u6253\u5F00\u5DF2\u4FDD\u5B58\u7684SQL\u6587\u4EF6 +TO_SAVE_FILE =\u5C06SQL\u7EC8\u7AEF\u4E2D\u7684\u5185\u5BB9\u4FDD\u5B58\u5230SQL\u6587\u4EF6 +TO_SAVE_FILE_AS = \u5C06SQL\u6216\u6587\u672C\u7EC8\u7AEF\u4E2D\u7684\u5185\u5BB9\u4FDD\u5B58\u5230\u65B0\u7684SQL\u6587\u4EF6 +CANCEL_SQL_STETEMNT = \u7EC8\u6B62SQL\u7EC8\u7AEF\u4E2D\u7684\u8BED\u53E5\u6267\u884C +OPEN_NEW_INSTANCE = \u6253\u5F00\u65B0\u7684SQL\u5B9E\u4F8B +CLOSE_ACTIVE_VIEWER =\u5173\u95ED\u5F53\u524D\u5B58\u50A8\u8FC7\u7A0B/\u51FD\u6570\u6E90\u67E5\u770B\u5668 +COLAPSE_ALL_OBJECTS = \u6298\u53E0\u5BF9\u8C61\u6D4F\u89C8\u5668\u4E2D\u6253\u5F00\u7684\u5BF9\u8C61 +SHOW_LIST_OF_OBJECTS = \u663E\u793ASQL\u7EC8\u7AEF\u4E2D\u4F7F\u7528\u7684\u5BF9\u8C61\u5217\u8868 +SHOW_MATCHING_PATTERN=\u7528\u7F16\u8F91\u5668\u4E2D\u7684\u5339\u914D\u6A21\u677F\u663E\u793A/\u66FF\u6362 + +INVALID_USERNAME_MSG = \u767B\u9646\u88AB\u62D2\u7EDD\uFF1A\u7528\u6237\u540D/\u5BC6\u7801\u9519\u8BEF +CREATE_TABLE_EMPTY_COLUMN = \u8868\u521B\u5EFA\u81F3\u5C11\u8981\u5305\u542B\u4E00\u5217 +LOADING_NS=\u52A0\u8F7D +INVALID_LOGGINGLEVEL=\u65E5\u5FD7\u7EA7\u522B\u65E0\u6548\uFF0C\u5C06\u8BBE\u4E3A\u9ED8\u8BA4\u503C\uFF08WARN\uFF09\u3002 + +GO_TO_LINE=\u5230\u8FBE\u201C\u8F6C\u5230\u884C\u201D\u5B57\u6BB5\u4E2D\u8F93\u5165\u7684\u884C +GO_TO_LINE_POPUP_TITLE= \u8F6C\u5230\u884C +TO_LOWER_CASE=\u5C06\u9009\u5B9A\u7684\u6587\u672C\u8F6C\u6362\u4E3A\u5C0F\u5199 +TO_UPPER_CASE=\u5C06\u9009\u5B9A\u7684\u6587\u672C\u8F6C\u6362\u4E3A\u5927\u5199 +INVALID_INPUT_FOR_GO_TO_LINE=\u975E\u6CD5\u8F93\u5165 +FORWARD_SEARCH=\u641C\u7D22\u4E0B\u4E00\u5904\u201C\u67E5\u627E\u201D\u5B57\u6BB5\u4E2D\u6307\u5B9A\u7684\u6587\u672C +BACKWARD_SEARCH=\u641C\u7D22\u4E0A\u4E00\u5904\u201C\u67E5\u627E\u201D\u5B57\u6BB5\u4E2D\u6307\u5B9A\u7684\u6587\u672C +ENTER_LINE_NUMBER=\u8BF7\u8F93\u5165\u884C\u53F7 + +IMPORTEXPORT_VALIDATION_OTHER=\u8BF7\u8F93\u5165\u5206\u9694\u7B26\u503C +IMPORTEXPORT_VALIDATION_NULL_STRING=\u7A7A\u5B57\u7B26\u4E32\u4E0D\u5E94\u5305\u542B\u6362\u884C\u6216\u56DE\u8F66. +IMPORTEXPORT_VALIDATION_NULL_LENGTH=\u7A7A\u5B57\u7B26\u4E32\u6700\u591A\u5141\u8BB8100\u4E2A\u5B57\u7B26. +IMPORTEXPORT_VALIDATION_DELIMITER_LENGTH=\u5206\u9694\u7B26\u5FC5\u987B\u662F10\u4E2A\u5B57\u8282\u7684\u6700\u5927\u503C. +IMPORTEXPORT_VALIDATION_NULL_AS_DELIMITOR=\u7A7A\u53C2\u6570\u4E0D\u80FD\u4E0E\u5206\u9694\u7B26\u548C\u5F15\u7528\uFF08\u5F15\u8BC1\uFF09\u53C2\u6570\u76F8\u540C. +IMPORTEXPORT_VALIDATION_NULL_AS_QUOTE=Null\u53C2\u6570\u4E0D\u80FD\u4E0E\u9ED8\u8BA4\u7684\u5F15\u7528\u53C2\u6570\u76F8\u540C. +IMPORTEXPORT_VALIDATION_QUOTE_SINGLE_CHAR=\u53EA\u5141\u8BB8\u5355\u5B57\u7B26\u5F15\u7528\u548C\u9038\u51FA\uFF08\u6362\u7801\uFF09\u3002. +IMPORTEXPORT_VALIDATION_QUOTE_AS_DELI=\u5F15\u7528\u5B57\u7B26\u4E0D\u5E94\u4E0E\u5206\u9694\u7B26\u76F8\u540C. +IMPORTEXPORT_VALIDATION_QUOTE_AS_ESCAPE=\u5F15\u7528\u5B57\u7B26\uFF08\u5F15\u8BC1\u5B57\u7B26\uFF09\u4E0D\u80FD\u4E0E\u8F6C\u4E49\u7B26\uFF08\u6362\u7801\u5B57\u7B26\uFF0C\u9038\u51FA\u5B57\u7B26\uFF09\u76F8\u540C. +EXPORT_VALIDATION_QUOTE_NO_COLS_SELECTED =\u8BF7\u81F3\u5C11\u9009\u62E9\u4E00\u5217\u5BFC\u51FA. +IMPORT_VALIDATION_QUOTE_NO_COLS_SELECTED =\u8BF7\u81F3\u5C11\u9009\u62E9\u4E00\u5217\u5BFC\u5165. + +EXPORT_OPTION_TITLE=\u5BFC\u51FA\u8868\u6570\u636E : +IMPORT_OPTION_TITLE=\u5BFC\u5165\u8868\u6570\u636E : +EXPORT_ERROR=\u5BFC\u51FA\u9519\u8BEF +IMPORT_ERROR=\u5BFC\u5165\u9519\u8BEF +OPTION_DELIMITER=\u5206\u9694\u7B26 +OPTION_FORMAT=\u683C\u5F0F\uFF1A +OPTION_HEADER=\u5305\u542B\u6807\u9898 +OPTION_QUOTE=\u5F15\u53F7\uFF1A +OPTION_ESCAPE=\u8F6C\u4E49\u7B26\uFF1A +OPTION_TOOLTIP=\u4EC5\u5355\u5B57\u7B26 +OPTION_REPLACE_NULL=\u5C06NULL\u66FF\u6362\u4E3A\uFF1A +OPTION_REPLACE_WITHNULL=\u7528Null\u66FF\u6362 : +OPTION_NULL_TOOLTIP=\u6700\u591A100\u4E2A\u5B57\u7B26 +OPTION_ENCODING=\u7F16\u7801 : + +OPTION_OTHERTOOLTIP=\u957F\u5EA6\u4E0D\u5F97\u8D85\u8FC710\u5B57\u8282 +OPTION_SELECTCOLUMNS=\u9009\u62E9\u5217 +OPTION_ALLCOLUMNS=\u6240\u6709\u5217\uFF08\u53BB\u52FE\u9009\u8868\u793A\u91CD\u7EC4/\u5220\u9664\u5217\uFF09 +OPTION_SELECTED_COL=\u9009\u5B9A\u7684\u5217 +OPTION_AVAILABLE_COL=\u53EF\u7528\u5217 +OPTION_I_AGREE=\u6211\u540C\u610F +IMPORT_DATA_FILE=\u5BFC\u5165\u6570\u636E\u6587\u4EF6: +IMPORT_FILE_BROWSE=\u6D4F\u89C8 + +RESULT_WINDOW_QUERY_SUBMIT_TIME=\u67E5\u8BE2\u63D0\u4EA4\u65F6\u95F4\uFF1A{0} +RESULT_WINDOW_EXECUTION_TIME=. \u6267\u884C\u65F6\u95F4\uFF1A{0} +RESULT_WINDOW_RECORD_FETCHED=\u83B7\u53D6\u7684\u8BB0\u5F55\uFF1A{0}{1} +RESULT_WINDOW_RECORD_MORE=\uFF08\u6301\u7EED\u83B7\u53D6\u4E2D\u2026\uFF09 + +RESULT_WINDOW_ROWS_FETCHED=\u5DF2\u83B7\u53D6{0}\u884C\uFF0C\u8017\u65F6{1}{2} +RESULT_WINDOW_ROW_FETCHED=\u5DF2\u83B7\u53D6{0}\u884C\uFF0C\u8017\u65F6{1}{2} +RESULT_WINDOW_EXECUTED_QUERY_TOOLTIP=\u6267\u884C\u67E5\u8BE2 +RESULT_WINDOW_RECORD_FETCHED_ALL=\u83B7\u53D6{0}\u884C\uFF0C\u5171{1} +RESULT_WINDOW_RECORD_FETCHED_ONE=\u83B7\u53D6{0}\u884C\uFF0C\u5171{1} +LAST_SUCCESSFULL_LOGIN_MESSAGE = \u6700\u540E\u4E00\u6B21\u6210\u529F\u767B\u9646 +LAST_FAILURE_LOGIN_MESSAGE=\u767B\u5F55\u5C1D\u8BD5\u5931\u8D25\uFF1A +DATA_STUDIO_NOTIFIFICATIONS= \u6700\u8FD1\u767B\u5F55\u6D3B\u52A8 +DATABASE_NAME_NOTIFICATION= \u6570\u636E\u5E93 - {0} +LAST_LOGIN_MESSAGE=\u6B63\u5728\u8F7D\u5165\u4E0A\u6B21\u767B\u5F55\u901A\u77E5\uFF1A{0} +LOGIN_NOTIFICATION_STARTED=\u767B\u5F55\u901A\u77E5\u5DF2\u542F\u52A8\u3002 +LOGIN_NOTIFICATION_ENDED=\u767B\u5F55\u901A\u77E5\u5DF2\u5173\u95ED\u3002 +CREATE_FUNCTION_PROCEDURE=\u521B\u5EFA\u51FD\u6570/\u5B58\u50A8\u8FC7\u7A0B\u6210\u529F +INFO_MAX_RESULT_SOURCE_VIEWER=\u7ED3\u679C\u9875\u7B7E\u6570\u91CF\u5DF2\u8FBE\u4E0A\u9650\u3002\u5173\u95ED\u591A\u4F59\u9875\u7B7E\u4EE5\u8FD0\u884C\u672A\u6267\u884C\u7684\u67E5\u8BE2\u3002 +ERR_TITLE_CREATE_FILE_DIRECTORY = \u521B\u5EFA\u6216\u52A0\u8F7D\u65E5\u5FD7\u6587\u4EF6\u5931\u8D25 +ERR_BL_CREATE_FILE_DIRECTORY = \u8BBF\u95EE\u88AB\u62D2\u7EDD\u3002\u65E0\u6CD5\u521B\u5EFA\u6216\u52A0\u8F7D\u65E5\u5FD7\u6587\u4EF6\u3002\u6B63\u5728\u5173\u95EDData Studio\u3002 +ERR_TITLE_LAUNCH_DATASTUDIO = \u542F\u52A8\u5931\u8D25 +ERR_BL_LAUNCH_MULTIPLE_INSTANCE_DATASTUDIO = Data Studio\u4E0D\u652F\u6301\u540C\u4E00\u7528\u6237\u6253\u5F00\u591A\u4E2A\u5B9E\u4F8B\u3002 + +MPPDBIDE_DIA_BTN_CLOSE=\u5173\u95ED +MPPDBIDE_DIA_BTN_CONTINUE=\u7EE7\u7EED +CONNECTION_SECURITY_ALERT=\u8FDE\u63A5\u5B89\u5168\u544A\u8B66 +SSL_DISABLED_CONTINUE_OR_CANCEL=\u6B64\u8FDE\u63A5\u672A\u542F\u7528SSL\u3002\u5728\u9AD8\u5B89\u5168\u6027\u9700\u6C42\u573A\u666F\u4E0B\uFF0C\u63A8\u8350\u4F7F\u7528SSL\u8FDE\u63A5\u3002\u5355\u51FB\u201C\u7EE7\u7EED\u201D\u8FDB\u884C\u975E\u5B89\u5168\u8FDE\u63A5\u6216\u5355\u51FB\u201C\u53D6\u6D88\u201D\u914D\u7F6ESSL\u3002 +DB_CONN_LBL_CLIENT_SSL_KEY=\u5BA2\u6237\u7AEFSSL\u5BC6\u94A5 +DB_CONN_LBL_CLIENT_SSL_CERT=\u5BA2\u6237\u7AEFSSL\u8BC1\u4E66 +DB_CONN_BTN_CLIENT_KEY=*.pk8 +DB_CONN_BTN_CLIENT_CERT=*.crt +DB_CONN_BROWSE=... +EXPORT_QUERY=\u4ECE{0}\u9875\u7B7E\u5BFC\u51FA\u6240\u6709\u7ED3\u679C\u6570\u636E +EXPORT_RESULT_TITLE= \u5BFC\u51FA\u7ED3\u679C\u96C6\u6570\u636E\uFF1A +EXPORT_EXEC_TITLE= \u5BFC\u51FA\u6570\u636E:{0} +EXPORT_RESULT_INVALID_CONNECTION = \u5BFC\u51FA\u7ED3\u679C\u6570\u636E\u7684\u8FDE\u63A5\u65E0\u6548\uFF0C\u65E0\u6CD5\u7EE7\u7EED\u5BFC\u51FA\u6570\u636E\u3002 +SHOW_TABLE_DDL=\u6B63\u5728\u663E\u793ADDL +SHOW_DDL_FAILED= \u663E\u793ADDL\u5931\u8D25 +SHOW_TABLE_DDL_FAILED=\u663E\u793ADDL\u65F6\u51FA\u9519\uFF1A {0}.{1} +SHOW_TABLE_DDL_CANCELING=\u5DF2\u53D6\u6D88\u663E\u793ADDL\uFF1A {0}.{1} + +ERR_PARTITION_COLUMN_EMPTY=\u8BF7\u521B\u5EFA\u5206\u533A\u5217\u4EE5\u7EE7\u7EED\u64CD\u4F5C\u3002 +ERR_PARTITION_NAME_EMPTY=\u5206\u533A\u540D\u4E0D\u80FD\u4E3A\u7A7A\u3002 +ERR_PARTITION_VALUE_EMPTY=\u5206\u533A\u503C\u4E0D\u80FD\u4E3A\u7A7A\u3002 +ERR_PARTITION_INTERVAL_VALUE_EMPTY=\u5206\u533a\u95f4\u9694\u503c\u4e0d\u80fd\u4e3a\u7a7a +ERR_PARTITION_INTERVAL_COLUMN_TYPE=\u95f4\u9694\u5206\u533a\u5217\u7c7b\u578b\u5e94\u4e3a\u65f6\u95f4\u7c7b\u578b + +ERR_DUPLICATE_PARTITION_NAME=\u5206\u533A\u540D\u79F0\u5DF2\u5B58\u5728\u3002\u8BF7\u8F93\u5165\u5176\u4ED6\u540D\u79F0\u3002 +ERR_PREFIX_DB_MESSAGE=\u9519\u8BEF\uFF1A +CREATE_TABLE_PARTITION_DELETE=\u8BF7\u4ECE\u8868\u4E2D\u9009\u62E9\u81F3\u5C11\u4E00\u4E2A\u8981\u5220\u9664\u7684\u5206\u533A +CREATE_TABLE_PARTITION_EDIT=\u8BF7\u4ECE\u8868\u4E2D\u9009\u62E9\u81F3\u5C11\u4E00\u4E2A\u8981\u7F16\u8F91\u7684\u5206\u533A +CREATE_TABLE_NO_PARTITION_MSG=\u672A\u9009\u62E9\u5206\u533A\u6216\u65E0\u5176\u4ED6\u53EF\u79FB\u52A8\u7684\u884C\u3002 +FOREIGN_TABLE_GROUP=\u5916\u8868 +PARTITION_TABLE_GROUP=\u5206\u533A\u8868 +TABLES_NAME=\u666E\u901A\u8868 +CREATE_NEW_PARTITION_TABLE=\u521B\u5EFA\u5206\u533A\u8868 +TABLE_ORIENTATION=\u8868\u5B58\u50A8\u65B9\u5F0F +RENAME_PARTITION_TABLE_TO=\u5DF2\u5C06{0}\u5206\u533A\u91CD\u547D\u540D\u4E3A{1}.{2}.{3}\u3002 +STATUS_MSG_RENAME_PARTITION_TABLE=\u6B63\u5728\u91CD\u547D\u540D\u5206\u533A\u8868\u2026\u2026 + +RENAME_PARTITION_TABLE_WAIT=\u6B63\u5728\u91CD\u547D\u540D{0}\u5206\u533A\u8868\uFF0C\u8BF7\u7A0D\u5019\u2026\u2026 +RENAME_PARTITION_TABLE_TITLE=\u91CD\u547D\u540D +RENAME_PARTITION_TITLE=\u91CD\u547D\u540D\u5206\u533A +RENAME_PARTITION_TABLE_NEW=\u4E3A{1}\u8868\u4E2D\u7684{0}\u5206\u533A\u8F93\u5165\u65B0\u540D\u79F0 +DROP_PARTITION_TITLE=\u5220\u9664\u5206\u533A +DROP_PARTITION=\u786E\u5B9A\u8981\u4ECE{1}.{2}\u8868\u4E2D\u5220\u9664{0}\u5206\u533A\u5417\uFF1F +STATUS_MSG_DROP_PARTITION=\u6B63\u5728\u5220\u9664\u5206\u533A\u2026\u2026 +DROP_PARTITION_SUCCESS=\u5DF2\u5220\u9664\u5206\u533A\uFF1A {0}.{1}.{2} +DROP_PARTITION_ERROR_TITLE=\u5220\u9664\u5206\u533A\u65F6\u51FA\u9519 +DROP_PARTITION_UNABLE_MSG=\u5220\u9664\u5206\u533A\u65F6\u51FA\u9519\uFF1A{0}.{1}.{2} +CIPHER_EDIT_MESSAGE=\u6709\u5206\u533A\u6B63\u5728\u7F16\u8F91\u4E2D\u3002\u5B8C\u6210\u6216\u53D6\u6D88\u7F16\u8F91\ + \u4EE5\u6267\u884C\u5176\u4ED6\u64CD\u4F5C\u3002 +PARTITION_GROUP_NAME=\u5206\u533A +PARTITION_TAB_ORIENTATION=\u5B58\u50A8\u65B9\u5F0F +PARTITION_TAB_TYPE=\u5206\u533A\u7C7B\u578B +PARTITION_TAB_INTERVAL_PARTITION_EXPR=\u95f4\u9694\u503c +PARTITION_TAB_PARTITION_BY_RANGE=\u6309\u7C7B\u578B\u5206\u533A +PARTITION_TAB_AVAILABLE_COLUMN=\u53EF\u7528\u5217 +PARTITION_TAB_PARTITION_COLUMN=\u5206\u533A\u5217 +PARTITION_TAB_PATITION_NAME=\u5206\u533A\u540D\u79F0 +PARTITION_TAB_PARTITION_VALUE=\u5206\u533A\u503C +PARTITION_TAB_TABLESPACE=\u8868\u7A7A\u95F4 +PARTITION_TAB_PARTITIONS=\u5206\u533A +PARTITION_TAB_PARTITION_DEF=\u5206\u533A\u5B9A\u4E49 +RENAME_CONNECTION_TITILE=\u91CD\u547D\u540D\u8FDE\u63A5 +RENAME_CONNECTION_NEW_NAME=\u4E3A{0}\u8F93\u5165\u65B0\u540D\u79F0 +STATUS_MSG_RENAME_CONNECTION =\u6B63\u5728\u91CD\u547D\u540D\u8FDE\u63A5\u2026\u2026 +RENAME_CONNECTION_WAIT=\u6B63\u5728\u91CD\u547D\u540D{0}\u8FDE\u63A5\uFF0C\u8BF7\u7A0D\u5019\u2026\u2026 +RENAME_CONNECTION_TO= \u5DF2\u5C06{0}\u8FDE\u63A5\u91CD\u547D\u540D\u4E3A {1}\u3002 +RENAME_CONNECTION_ERROR=\u91CD\u547D\u540D\u5982\u4E0B\u8FDE\u63A5\u5931\u8D25\uFF1A{0}\n\u9519\u8BEF\uFF1A{1} + +INF_NOEDIT_DONE_MSG_BODY=\u6CA1\u6709\u8981\u4FDD\u5B58\u7684\u66F4\u6539\u3002 +INF_NOEDIT_DONE_MSG_TITLE=\u8FDE\u63A5\u53C2\u6570\u672A\u4FDD\u5B58 + +EDIT_CONNECTION_WIZARD_TITLE=\u7F16\u8F91\u8FDE\u63A5 +EDIT_CONNECTION_SUBTITLE=\u4FEE\u6539\u8FDE\u63A5\u53C2\u6570 +ENTER_DESCRIPTIONS_TEXT=\u8BBE\u7F6E\u8868\u63CF\u8FF0\uFF08\u6700\u591A5000\u4E2A\u5B57\u7B26\uFF09 +GENERAL_OPTION_TEXT=\u63D0\u4F9B\u521B\u5EFA\u8868\u7684\u901A\u7528\u4FE1\u606F\u3002\u5355\u51FB\u201C\u4E0B\u4E00\u6B65\u201D\u7EE7\u7EED\u4E0B\u4E00\u90E8\u5206\u3002 +TABLE_OPTIONS_TEXT=\u5BF9\u4E8E\u4E0D\u540C\u7684\u8868\u5B58\u50A8\u65B9\u5F0F\uFF0C\u5176\u8868\u9009\u9879\u548C\u503C\u4E5F\u4E0D\u540C\u3002\u6709\u5173\u8BE6\u7EC6\u4FE1\u606F\uFF0C\u8BF7\u53C2\u89C1\u7528\u6237\u624B\u518C\u3002 + +ERR_NONSELECT_CANCELLED= \u65E0\u6CD5\u5B8C\u6210\u64CD\u4F5C\uFF0C\u56E0\u4E3A\u5BF9\u8C61\u5DF2\u88AB\u5176\u4ED6\u64CD\u4F5C\u9501\u5B9A\u3002 +DISCARD_TERMINAL_DATA_BODY=\u5B58\u5728\u672A\u4FDD\u5B58\u7684\u6570\u636E\u3002\u786E\u5B9A\u8981\u653E\u5F03\u672A\u4FDD\u5B58\u7684\u66F4\u6539\u5417\uFF1F +SAVE_CHANGES_DATA_BODY=\u5B58\u5728\u672A\u4FDD\u5B58\u7684\u6570\u636E\u3002\n\u8BF7\u63D0\u4EA4/\u653E\u5F03\u66F4\u6539\u4EE5\u52A0\u8F7D\u66F4\u591A\u8BB0\u5F55\u3002 + +IMPORT_EXPORT_DELIMETER_COMMA=\u9017\u53F7(,) +IMPORT_EXPORT_DELIMETER_TAB=Tab\u952E +IMPORT_EXPORT_DELIMETER_PIPE=\u7AD6\u7EBF\u7B26\u53F7(|) +IMPORT_EXPORT_DELIMETER_SEMICOLON=\u5206\u53F7(;) +IMPORT_EXPORT_DELIMETER_OTHER=\u5176\u4ED6\uFF1A +LAST_LOGIN_UNAVAILABE=\u672A\u83B7\u53D6\u5230\u4E0A\u6B21\u767B\u5F55\u4FE1\u606F +LASTLOGIN_CONNECTION_NAME=\u8FDE\u63A5\u540D\u79F0 : {0} + +SEARCH_SCOPE_LBL=\u641C\u7D22\u8303\u56F4 +SEARCH_CONNECTION_LBL=\u8FDE\u63A5 +SEARCH_CONNECTION_MAND_MSG= \u9009\u62E9\u8FDE\u63A5\u4FE1\u606F\u3002 +SEARCH_DATABASE_LBL=\u6570\u636E\u5E93 +SEARCH_DATABASE_MAND_MSG=\u9009\u62E9\u6570\u636E\u5E93\u3002 +SEARCH_NAMESPACE_LBL=\u6A21\u5F0F +SEARCH_NAMESPACE_MAND_MSG=\u9009\u62E9\u6A21\u5F0F\u3002 +SEARCH_WITHIN_LBL=\u641C\u7D22\u5BF9\u8C61 +SEARCH_WITHIN_TABLE_LBL=\u8868 +SEARCH_WITHIN_FUN_LBL=\u51FD\u6570/\u8FC7\u7A0B +SEARCH_WITHIN_VIEWS=\u89C6\u56FE +SEARCH_OPTIONS_LBL=\u641C\u7D22\u9009\u9879 +SEARCH_NAME_LBL=\u641C\u7D22\u5185\u5BB9 +SEARCH_NAME_MAND_MSG=\u8F93\u5165\u641C\u7D22\u5185\u5BB9\u3002 +SEARCH_NAME_MATCH_LBL=\u641C\u7D22\u6761\u4EF6 +SEARCH_NAME_MATCH_CONTAINS=\u5305\u542B\u641C\u7D22\u5185\u5BB9 +SEARCH_NAME_MATCH_STARTS_LBL=\u4EE5\u641C\u7D22\u5185\u5BB9\u4E3A\u5F00\u5934 +SEARCH_NAME_MATCH_EXACT_LBL=\u5168\u5B57\u5339\u914D +SEARCH_NAME_MATCH_REGU_EXPRESS_LBL=\u6B63\u5219\u8868\u8FBE\u5F0F +SEARCH_MATCH_CASE_LBL=\u5339\u914D\u5927\u5C0F\u5199 +SEARCH_BTN=\u641C\u7D22 +SEARCH_CANCEL_BTN=\u53D6\u6D88 +SEARCH_RESULT_LBL= \u641C\u7D22\u7ED3\u679C + +SEARCH_WINDOW_LBL=\u641C\u7D22 +OB_REFRESH_TOOL=\u5237\u65B0 +SEARCH_RECORD_FETCHED_MSG=\u67E5\u627E\u5230{0}\u4E2A\u5BF9\u8C61 +SEARCH_NO_RECORD_FOUND_MSG= \u672A\u627E\u5230\u5BF9\u8C61 +SEARCH_EXE_TIME_MSG=\u6267\u884C\u65F6\u95F4\uFF1A{0} +KEY_BINDING_SEARCH= \u641C\u7D22\u5BF9\u8C61 +KEY_BINDING_SEARCH_DESC=\u641C\u7D22\u6570\u636E\u5E93\u4E2D\u7684\u5BF9\u8C61 + +SEARCH_PROGRESS_STATS_MSG=\u6B63\u5728\u641C\u7D22 +SEARCH_PROGRESS_MONITOR_MSG=\u6B63\u5728\u4ECE{0}\u641C\u7D22\u5BF9\u8C61 +SEARCH_OBJ_ERROR= \u641C\u7D22\u5BF9\u8C61\u65F6\u51FA\u9519\u3002 +SEARCH_NO_CONN_MSG=\u68C0\u67E5\u8FDE\u63A5\u662F\u5426\u6D3B\u8DC3\u5E76\u91CD\u8BD5\u3002 +SEARCH_SELECT_SEARCH_WITHIN_OPT=\u201C\u67E5\u627E\u5BF9\u8C61\u201D\u5217\u8868\u4E2D\u81F3\u5C11\u9700\u9009\u4E2D\u4E00\u4E2A\u5BF9\u8C61\u3002 + +BROWSE_BTN_ROOT_CERT=*.crt +BROWSE_BTN_PEM_CERT=*.pem +ROOTCERT_FILETEXT=\u6839\u8BC1\u4E66 +SSL_CIPHER=SSL \u5BC6\u7801 +CTAB_GENERAL=\u901A\u7528 +CTAB_SSL=SSL +CTAB_ADVANCED=\u9AD8\u7EA7 +DROPDOWN_SSLMODE=SSL\u6A21\u5F0F + +GENERAL_NODE=\u901A\u7528 +EDITOR_NODE=\u7F16\u8F91\u5668 +SECURITY_NODE=\u5B89\u5168 +ENVIRONMENT_NODE=\u73AF\u5883 +CIPHER_PREFERENCE_OPTION=\u5BC6\u7801 +CIPHER_PREFERENCE_OPTION_TITLE=\u5BF9\u201C\u4FDD\u5B58\u5BC6\u7801\u201D\u9009\u9879\u542F\u7528\u201C\u6C38\u4E45\u4FDD\u5B58\u201D +YES_OPTION=\u662F +NO_OPTION=\u5426 +NO_TEXT=\u201C\u4FDD\u5B58\u5BC6\u7801\u201D\u4E2D\u7684\u201C\u6C38\u4E45\u4FDD\u5B58\u201D\u9009\u9879\u4E0D\u4F1A\u51FA\u73B0\u5728\u8FDE\u63A5\u4FE1\u606F\u754C\u9762\uFF0C\u4E14\u5DF2\u4FDD\u5B58\u7684\u5BC6\u7801\u4F1A\u5220\u9664\u3002 +YES_TEXT=\u201C\u4FDD\u5B58\u5BC6\u7801\u201D\u4E2D\u7684\u201C\u6C38\u4E45\u4FDD\u5B58\u201D\u9009\u9879\u4F1A\u51FA\u73B0\u5728\u8FDE\u63A5\u4FE1\u606F\u754C\u9762\u3002 +SECURITY_WARNING_OPTION=\u5B89\u5168\u8B66\u544A +ENABLE_OPTION=\u542F\u7528 +DISABLE_OPTION=\u7981\u7528 +ENABLE_WARNING_MSG=\u5982\u679C\u7528\u6237\u5BF9\u8FDE\u63A5\u6216\u6587\u4EF6\u7684\u64CD\u4F5C\u53EF\u80FD\u5F15\u8D77\u6570\u636E\u5B89\u5168\u95EE\u9898\uFF0CData Studio\u5C06\u5F39\u51FA\u5B89\u5168\u8B66\u544A\u63D0\u793A\u3002 +DISABLE_WARNING_MSG=\u5982\u679C\u9700\u8981\u7981\u7528\u5B89\u5168\u8B66\u544A\u529F\u80FD\uFF0C\u8BF7\u9605\u8BFB\u5982\u4E0B\u5F71\u54CD\uFF0C\u5E76\u52FE\u9009\u201C\u6211\u540C\u610F\u201D\u3002\n\n\u5BF9\u4E8E\u975ESSL\u8FDE\u63A5\uFF0C\u4E0D\u4F1A\u663E\u793A\u5B89\u5168\u8B66\u544A\u3002\nData Studio\u4E0D\u52A0\u5BC6\u6570\u636E\u3002 \nData Studio\u4E0D\u8BBE\u7F6E\u5BFC\u51FA\u6587\u4EF6\u7684\u6743\u9650\u3002 \n\u9ED1\u5BA2\u53EF\u80FD\u8BBF\u95EE\u654F\u611F\u4FE1\u606F\u3002 +SESSION_SETTNG_NODE=\u4F1A\u8BDD\u8BBE\u7F6E +DATA_STUDIO_ENCODING=Data Studio\u7F16\u7801 +ENCODING_PREFERENCES_TITLE=\u7F16\u7801\u9996\u9009\u9879 +FILE_ENCODING=\u6587\u4EF6\u7F16\u7801 +IAGREE_TEXT=\u6211\u540C\u610F + +LBL_INCLUDE = \u5305\u542B +LBL_EXCLUDE = \u4E0D\u5305\u542B +LBL_FAST_LOAD_OPTIONS = \u5FEB\u901F\u52A0\u8F7D\u9009\u9879\uFF1A +LBL_LOAD_LIMIT = \u52A0\u8F7D\u4E0A\u9650\uFF1A +LBL_GRP_SCHEMA = \u6A21\u5F0F + +ERROR_ANNOTATION_LABEL=Error +TERMINAL_ERROR_WHILE_EXECUTION =\u4E0D\u663E\u793A\u6B64\u6B21\u6267\u884C\u4E2D\u53D1\u751F\u7684\u5176\u4ED6\u9519\u8BEF\u3002 +ERROR_POPUP_HEADER = \u6267\u884C\u5931\u8D25 +ERROR_POPUP_MESSAGE_TEXT = \u786E\u8BA4\u8981\u7EE7\u7EED\u6267\u884C\u5417\uFF1F +#do not translate to chinese +PROTOCOL_VERSION_ERROR=FATAL: unsupported frontend protocol + +CLOSE_TAB_MENU=\u5173\u95ED +CLOSE_ALL_TAB_MENU=\u5173\u95ED\u6240\u6709 +CLOSE_OTHER_TABS_MENU=\u5173\u95ED\u5176\u5B83 +CLOSE_LEFT_TABS_MENU=\u5173\u95ED\u5DE6\u4FA7\u7684\u6807\u7B7E +CLOSE_RIGHT_TABS_MENU=\u5173\u95ED\u53F3\u4FA7\u7684\u6807\u7B7E +SAVE_PARTS=\u4FDD\u5B58\u811A\u672C +SELECT_PARTS_FOR_SAVE=\u9009\u62E9\u9700\u8981\u4FDD\u5B58\u7684\u811A\u672C +RENAME_TERMINAL_TITLE=\u91CD\u547D\u540D\u7EC8\u7AEF +RENAME_TERMINAL_MSG=\u4E3A{0}\u7EC8\u7AEF\u8F93\u5165\u65B0\u540D\u79F0 +RENAME_TERMINAL_NAME=\u91CD\u547D\u540D\u7EC8\u7AEF +RENAME_TERMINAL_DUPLICATE_NAME_ERROR = \u91CD\u547D\u540D{0}\u7EC8\u7AEF\u5931\u8D25\u3002 \n \u9519\u8BEF\uFF1A{1}\u7EC8\u7AEF\u5DF2\u5B58\u5728\u3002 + +IMPORT_EXPORT_INVALIDFILENAME=\u6587\u4EF6\u540D\u65E0\u6548\u3002\u6587\u4EF6\u540D\u4E0D\u80FD\u5305\u542B\u4E0B\u5217\u4EFB\u4F55\u5B57\u7B26\uFF1A\ / : * ? " < > | + +PREF_RESULT_WINDOW_TITLE=\u7ED3\u679C\u7BA1\u7406 + +EXPORT_OUTPUTPATH=\u5BFC\u51FA\u8DEF\u5F84 +SEQUENCE=\u5E8F\u5217 +SEQUENCE_CREATED_SUCESSFULLY=\u5DF2\u521B\u5EFA\u5E8F\u5217\uFF1A {0}.{1} +CREATE_SEQUENCE_ERROR =\u521B\u5EFA\u5E8F\u5217\u65F6\u51FA\u9519\uFF1A {0}.{1} + +DROP_SEQUENCE_CONFIRM_TITLE = \u5220\u9664\u5E8F\u5217 +DROP_SEQUENCE_CONFIRM_MSG = \u786E\u8BA4\u8981\u5220\u9664''{0}''\u5E8F\u5217\u5417\uFF1F +DROP_SEQUENCE_CASCADE_CONFIRM_MSG=\u786E\u8BA4\u8981\u5220\u9664''{0}''\u5E8F\u5217\u5417\uFF1F + +SEQUENCE_NAME=\u5E8F\u5217\u540D\u79F0*\uFF1A +MINIMUM_VALUE =\u6700\u5C0F\u503C\uFF1A +MAXIMUM_VALUE = \u6700\u5927\u503C\uFF1A +INCREMENT_BY = \u589E\u91CF\uFF1A +START_VALUE = \u521D\u59CB\u503C\uFF1A +SEQUENCE_CACHE = \u7F13\u5B58\u6570\u503C\uFF1A +ORDER = \u987A\u5E8F\uFF1A +CYCLE_MSG = \u5FAA\u73AF +CYCLE=\u5FAA\u73AF\uFF1A +OWNER = \u6240\u5C5E\u5BF9\u8C61\uFF1A +TABLE_NAME= \u8868 +COLUMN_NAME=\u5217 +SELECT_SCHEMA_NAME=\u6A21\u5F0F + +CREATE_NEW_SEQUENCE=\u521B\u5EFA\u5E8F\u5217 +DROP_SEQUENCE_SUCCESS = \u5DF2\u5220\u9664\u5E8F\u5217\uFF1A{0}.{1} +DROP_SEQUENCE_FAILURE = \u5220\u9664{0}{1}\u5E8F\u5217\u5931\u8D25\u3002 {2} +DROP_SEQUENCE_CASCADE_SUCCESS = \u5DF2\u5220\u9664\u5E8F\u5217\u548C\u4F9D\u8D56\u5BF9\u8C61\uFF1A{0}.{1} +EXPORT_DDL_PREFERENCES=\u5BFC\u51FADDL +INCLUDE_TABLESPACE_IN_DDL=\u5728DDL\u4E2D\u5305\u542B\u8868\u7A7A\u95F4 + +EXPORT_PREFERENCES=\u5BFC\u51FA +EXPORT_DATA_PREFERENCES=\u5BFC\u51FA\u6570\u636E +INCLUDE_EXPORT_DATA_OPTION=\u52FE\u9009\u6B64\u9009\u9879\u4EE5\u5F00\u542F\u6570\u636E\u5BFC\u51FA\u529F\u80FD\u3002 + +PREF_RESULT_VIEW_TITLE=\u67E5\u8BE2\u7ED3\u679C +PREF_CUSTOM_LENGTH=\u81EA\u5B9A\u4E49\u957F\u5EA6 +PREF_CONTENT_LENGTH=\u5185\u5BB9\u957F\u5EA6 +PREF_COLUMN_WIDTH=\u5217\u5BBD +EXPORT_IMPORT_PREFERENCES=\u5BFC\u5165/\u5BFC\u51FA +EXPORT_CHANGES_TITLE =\u5BFC\u51FA\u7ED3\u679C\u6570\u636E +EXPORT_DIRTY_DATA_BODY=\u5B58\u5728\u672A\u4FDD\u5B58\u7684\u6570\u636E\u3002\n\u662F\u5426\u8981\u5BFC\u51FA\u672A\u4FDD\u5B58\u7684\u66F4\u6539\uFF1F + +PREF_RS_DATA_FETCH_COUNT_SUBTITLE=\u7ED3\u679C\u83B7\u53D6\u91CF +PREF_RS_DATA_FETCH_ALL_MSG=\u83B7\u53D6\u6240\u6709\u8BB0\u5F55 +PREF_RS_DATA_FETCH_COUNT_MSG=\u83B7\u53D6\u6307\u5B9A\u6570\u91CF\u7684\u8BB0\u5F55 +PREF_RS_CONTENT_LENGTH_HINT=\u6839\u636E\u5217\u7684\u5185\u5BB9\u957F\u5EA6\u8BBE\u7F6E\u5217\u7684\u5BBD\u5EA6\u3002 +PREF_RS_CUSTOM_LENGTH_HINT=\u6839\u636E\u7F51\u683C\u6A21\u5F0F\u4E0B\u7684\u53D6\u503C\u957F\u5EA6\u8BBE\u7F6E\u5217\u7684\u6700\u5C0F\u5BBD\u5EA6\uFF0C\u5355\u4F4D\u4E3A\u50CF\u7D20\u3002\ + \n\u6839\u636E\u6587\u672C\u6A21\u5F0F\u4E0B\u7684\u5B57\u7B26\u957F\u5EA6\u8BBE\u7F6E\u5217\u7684\u6700\u5C0F\u5BBD\u5EA6\u3002 +PREF_RS_COLUMN_WIDTH_INPUT_ERR_MSG=\u5217\u5BBD\u65E0\u6548\u3002\u8BF7\u8F93\u5165\u4ECB\u4E8E100\u548C500\u4E4B\u95F4\u7684\u6570\u5B57\u3002 +PREF_RS_FETCH_COUNT_INPUT_ERR_MSG=\u7ED3\u679C\u83B7\u53D6\u91CF\u8BB0\u5F55\u6570\u503C\u65E0\u6548\uFF0C\u8BF7\u8F93\u5165\u4ECB\u4E8E100\u548C5000\u4E4B\u95F4\u7684\u6570\u503C\u3002 +SHOW_HIDE_QUERY_BAR=\u663E\u793A/\u9690\u85CF\u67E5\u8BE2\u9762\u677F +SHOW_HIDE_SEARCH_BAR=\u663E\u793A/\u9690\u85CF\u641C\u7D22\u9762\u677F +SEARCH_GRID=\u641C\u7D22 +CLEAR_SEARCH_GRID=\u6E05\u7A7A\u641C\u7D22\u5185\u5BB9 +SEARCH_OPT_CONTAINS=\u5305\u542B\u641C\u7D22\u5185\u5BB9 +SEARCH_OPT_EQUALS=\u4E0E\u641C\u7D22\u5185\u5BB9\u76F8\u540C +SEARCH_OPT_STARTS_WITH=\u4EE5\u641C\u7D22\u5185\u5BB9\u4E3A\u5F00\u5934 +SEARCH_OPT_REGEX=\u6B63\u5219\u8868\u8FBE\u5F0F +SEARCH_OPT_NULL=Null\u503C +PREF_EXPORT_DDL_W_TABLESPACE_HINT=\u5BFC\u51FADDL\u65F6\u4F1A\u5305\u542B\u8868\u7A7A\u95F4\u4FE1\u606F\u3002 +PREF_RS_DATA_COPY_COL_HEADER_MSG=\u5305\u542B\u5217\u6807\u9898 +PREF_RS_DATA_COPY_ROW_HEADER_MSG=\u5305\u542B\u884C\u53F7 +PREF_RS_COPY_HEADING=\u9AD8\u7EA7\u590D\u5236\u7ED3\u679C +PREF_RS_COPY_COLUMN_HEADER_HINT=\u590D\u5236\u6240\u9009\u5185\u5BB9\u548C\u5217\u6807\u9898 +PREF_RS_COPY_ROW_HEADER_HINT=\u590D\u5236\u6240\u9009\u5185\u5BB9\u548C\u884C\u53F7 +CREATE_SEQUENCE_INPUT_FORMATE= {0}\u5B57\u6BB5\u8F93\u5165\u65E0\u6548\uFF0C\u8BF7\u8F93\u5165{1}\u81F3{2}\u4E4B\u95F4\n\u7684\u503C\u3002 +EXPORTING_DATA_STATUS_MSG=\u6B63\u5728\u5BFC\u51FA\u6570\u636E +LOADING_DATA_STATUS_MSG=\u6B63\u5728\u52A0\u8F7D\u6570\u636E +ERROR_LOADING_DATA_STATUS_MSG=\u52A0\u8F7D\u6570\u636E\u65F6\u51FA\u9519 +TABLE_DOES_NOT_EXIST=\u8BE5\u8868\u4E0D\u5B58\u5728\u3002 +VIEW_DOES_NOT_EXIST=\u8BE5\u89C6\u56FE\u4E0D\u5B58\u5728\u3002 +MINIMUM_VALUE_FIELD =\u6700\u5C0F\u503C +MAXIMUM_VALUE_FIELD = \u6700\u5927\u503C +INCREMENT_BY_FIELD = \u589E\u91CF +START_VALUE_FIELD = \u521D\u59CB\u503C +SEQUENCE_CACHE_FIELD = \u7F13\u5B58\u6570\u503C + +GENERAL_NODE_LABLE = \u201C\u901A\u7528\u201D\u9875\u7B7E\u63D0\u4F9B\u4EE5\u4E0B\u9009\u9879\uFF1A \ + \n \ + \n\u2022 \u4FEE\u6539\u547D\u4EE4\u7684\u9ED8\u8BA4\u5FEB\u6377\u952E\u3002\ + \n \ + \n \u8BE5\u9009\u9879\u4F1A\u91CD\u542FData Studio\uFF0C\u4F7F\u7528\u524D\u9700\u4FDD\u5B58Data Studio\u4E2D\u7684\u6570\u636E\u3002\ \u672A\u4FDD\u5B58\u7684\u6570\u636E\u5C06\u4F1A\u4E22\u5931\u3002\ + \n \ + \n \u66F4\u6539\u901A\u7528\u8BBE\u7F6E\u4F1A\u5F71\u54CD\u5FEB\u6377\u952E\u4F7F\u7528\u3002 +EDITOR_NODE_LABLE =\u201C\u7F16\u8F91\u5668\u201D\u9875\u7B7E\u63D0\u4F9B\u4EE5\u4E0B\u9009\u9879\uFF1A \ + \n \ + \n\u2022 \u8BBE\u7F6E\u201CSQL\u7EC8\u7AEF\u201D\u548C\u201C\u5B58\u50A8\u8FC7\u7A0B/\u51FD\u6570\u7EC8\u7AEF\u201D\u9875\u7B7E\u4E2D\u7684\u8BED\u6CD5\u9AD8\u4EAE\u3002\ + \n \u8BED\u6CD5\u9AD8\u4EAE\u53EF\u7528\u4E8E\u5355\u884C\u6CE8\u91CA\uFF0C\u975E\u4FDD\u7559\u5173\u952E\u5B57\uFF0C\u4FDD\u7559\u5173\u952E\u5B57\uFF0C\u7C7B\u578B\uFF0C\u8C13\u8BCD\uFF0C\u5E38\u91CF\uFF0C\u5B57\u7B26\u4E32\u3002\ + \n \u4FEE\u6539\u8BED\u6CD5\u9AD8\u4EAE\u8BBE\u7F6E\u4F1A\u6539\u53D8SQL\u7EC8\u7AEF\u548C\u5B58\u50A8\u8FC7\u7A0B/\u51FD\u6570\u6E90\u67E5\u770B\u5668\u7684\u663E\u793A\u6548\u679C\u3002\ + \n\u2022 \u4E3A\u6BCF\u4E2A\u67E5\u8BE2\u8BBE\u7F6ESQL\u5386\u53F2\u67E5\u8BE2\u6570\u548C\u8981\u4FDD\u5B58\u7684\u5B57\u7B26\u6570\u3002\ + \n\u2022 \u4E3ASQL\u7F16\u8F91\u5668\u548C\u5B58\u50A8\u8FC7\u7A0B/\u51FD\u6570\u6E90\u67E5\u770B\u5668\u5B9A\u4E49SQL\u6A21\u677F\u3002\ + \n\u2022 \u5B9A\u4E49SQL\u7F16\u8F91\u5668\u548C\u5B58\u50A8\u8FC7\u7A0B/\u51FD\u6570\u6E90\u67E5\u770B\u5668\u7684\u9009\u9879\u5361\u8BBE\u7F6E\u3002\ + \n\u2022 \u5B9A\u4E49\u7528\u6237\u5728SQL\u8F93\u5165\u65F6\u89E6\u53D1\u81EA\u52A8\u5EFA\u8BAE\u6240\u9700\u7684\u5B57\u7B26\u6570\u3002 + \n\ + \n \u66F4\u6539\u8BED\u6CD5\u9AD8\u4EAE\u8BBE\u7F6E\u524D\uFF0C\u8BF7\u4FDD\u5B58\u5728Data Studio\u4E2D\u64CD\u4F5C\u7684\u6240\u6709\u5185\u5BB9\u3002\u66F4\u6539\u5B8C\u6BD5\u540E\ + \n Data Studio\u4F1A\u91CD\u65B0\u542F\u52A8\uFF0C\u4EFB\u4F55\u672A\u4FDD\u5B58\u7684\u6570\u636E\u90FD\u5C06\u4E22\u5931\u3002\ + \n\ + \n \u4FEE\u6539SQL\u5386\u53F2\u67E5\u8BE2\u6570\u548C\u67E5\u8BE2\u4E2D\u8981\u4FDD\u5B58\u7684\u5B57\u7B26\u6570\u540E\uFF0CData Studio\u4E0D\u4F1A\u91CD\u65B0\u542F\u52A8\u3002 + +SECURITY_NODE_LABLE =\u201C\u5B89\u5168\u201D\u9875\u7B7E\u63D0\u4F9B\u4EE5\u4E0B\u9009\u9879\uFF1A \ + \n \ + \n\u2022 \u5728\u7528\u6237\u4F7F\u7528\u4E0D\u5B89\u5168\u8B66\u544A\u63A5\u6216\u6587\u4EF6\u65F6\uFF0C\u663E\u793A\u6216\u9690\u85CF\u201C\u5B89\u5168\u8B66\u544A\u201D\u3002\ + \n\u2022 \u5728\u5EFA\u7ACB\u8FDE\u63A5\u65F6\uFF0C\u663E\u793A\u6216\u9690\u85CF\u201C\u6C38\u4E45\u201D\u9009\u9879\u3002\ + \n \ + \n \u8BE5\u9009\u9879\u4F1A\u91CD\u542FData Studio\uFF0C\u4F7F\u7528\u524D\u9700\u4FDD\u5B58Data Studio\u4E2D\u7684\u6570\u636E\uFF0C\ \u672A\u4FDD\u5B58\u7684\u6570\u636E\u5C06\u4F1A\u4E22\u5931\u3002\ + \n \ + \n \u66F4\u6539\u5B89\u5168\u8BBE\u7F6E\u4F1A\u5F71\u54CD\u8FDE\u63A5\u7684\u5EFA\u7ACB\u548C\u5BFC\u51FA\u64CD\u4F5C\u3002\ + +ENVIRONMENT_NODE_LABLE =\u201C\u73AF\u5883\u201D\u9875\u7B7E\u63D0\u4F9B\u4EE5\u4E0B\u9009\u9879\uFF1A \ + \n \ + \n\u2022 Data Studio\u5B57\u7B26\u7F16\u7801\ + \n\u2022 \u6587\u4EF6\u5B57\u7B26\u7F16\u7801\ + \n \ + \n \u8BE5\u9009\u9879\u4F1A\u91CD\u542FData Studio\uFF0C\u4F7F\u7528\u524D\u9700\u4FDD\u5B58Data Studio\u4E2D\u7684\u6570\u636E\uFF0C\u672A\u4FDD\u5B58\u7684\u6570\u636E\u5C06\u4F1A\u4E22\u5931\u3002\ + \n \ + \n \u66F4\u6539\u73AF\u5883\u8BBE\u7F6E\u4F1A\u5F71\u54CD\u201C\u7ED3\u679C\u201D\u9875\u7B7E\u4E2D\u7684Data Studio\u5B57\u7B26\u7F16\u7801\u548C\u8868\u6570\u636E\u663E\u793A\u6548\u679C\u3002\ + \n \ + \n \u663E\u793A/\u9690\u85CFSQL\u548C\u5B58\u50A8\u8FC7\u7A0B/\u51FD\u6570\u7EC8\u7AEF\u5EFA\u8BAE\u4E2D\u7684\u201CSQL\u52A9\u624B\u201D\u9875\u7B7E\u3002\ + \n \ + \n \u6839\u636E\u201C\u65F6\u95F4\u95F4\u9694\u201D\u5B57\u6BB5\u4E2D\u5B9A\u4E49\u7684\u503C\uFF0C\u5B9A\u671F\u81EA\u52A8\u4FDD\u5B58SQL\u7EC8\u7AEF\u548C\u5B58\u50A8\u8FC7\u7A0B/\u51FD\u6570\u7EC8\u7AEF\ + \n \u4E2D\u7684\u6570\u636E\uFF0C\u5E76\u52A0\u5BC6\u4FDD\u5B58\u7684\u6570\u636E\u3002 +PREF_RESULT_WINDOW_NODE_LABLE = \u201C\u7ED3\u679C\u7BA1\u7406\u201D\u9875\u7B7E\u63D0\u4F9B\u4EE5\u4E0B\u9009\u9879\uFF1A\ + \n \ + \n\u2022 \u8BBE\u7F6E\u4E00\u6B21\u6027\u83B7\u53D6\u7684\u8BB0\u5F55\u6570\uFF0C\u83B7\u53D6\u6240\u9700\u884C\u6570\u3002\ + \n\u2022 \u8BBE\u7F6E\u8868\u6570\u636E/\u7ED3\u679C\u96C6\u7684\u5217\u5BBD\u3002\ + \n\u2022 \u5728\u590D\u5236\u8868\u65F6\u4E00\u5E76\u590D\u5236\u5217\u6807\u9898\u548C\u884C\u53F7\u3002\ + \n\u2022 \u8BBE\u7F6E\u4FDD\u5B58\u8868\u6570\u636E\u66F4\u6539\u65F6\u7684\u9996\u9009\u884C\u4E3A\u3002\ + \n\u2022 \u7ED3\u679C\u6570\u636E\u7F16\u7801\u9009\u9879\u5728\u7F16\u8F91\u8868\u3001\u67E5\u770B\u8868\u548C\u67E5\u8BE2\u7ED3\u679C\u65F6\u53EF\u7528\u3002 + \n \ + \n \u66F4\u6539\u4F1A\u7ACB\u5373\u751F\u6548\uFF0C\u65E0\u9700\u91CD\u542FData Studio\u3002\ + \n \ + \n \u66F4\u6539\u7ED3\u679C\u7BA1\u7406\u8BBE\u7F6E\u4F1A\u5F71\u54CD\u7ED3\u679C\u96C6\u548C\u67E5\u770B\uFF0C\u7F16\u8F91\u8868\u6570\u636E\u65F6\u7684\u663E\u793A\u6548\u679C\u3002 +EXPORT_IMPORT_PREFERENCES_LABLE = \u201C\u5BFC\u51FA/\u5BFC\u5165\u201D\u9875\u7B7E\u63D0\u4F9B\u4EE5\u4E0B\u9009\u9879\uFF1A\ + \n \ + \n\u2022 \u5BFC\u51FA\u548C\u663E\u793A\u5B9A\u4E49\u64CD\u4F5C\u65F6\u5305\u542B/\u4E0D\u5305\u542B\u8868\u7A7A\u95F4\u8BE6\u60C5\ + \n \ + \n\u2022\u5728\u5BFC\u51FADDL\u53CA\u6570\u636E\uFF0C\u5BFC\u51FA\u8868\u6570\u636E\uFF0C\u5BFC\u51FA\u6240\u6709\u6570\u636E\uFF0C\u5BFC\u51FA\u5F53\u524D\u9875\u6570\u636E\uFF0C\ + \n \u4EE5\u53CA\u751F\u6210SQL\u64CD\u4F5C\u671F\u95F4\uFF0C\u53EF\u4EE5\u5F00\u542F\u6216\u7981\u7528\u6570\u636E\u5BFC\u51FA\u529F\u80FD\u3002\ + \n \ + \n \u66F4\u6539\u4F1A\u7ACB\u5373\u751F\u6548\uFF0C\u65E0\u9700\u91CD\u542FData Studio\u3002\ + \n \ + \n \u66F4\u6539\u5BFC\u51FA\u8BBE\u7F6E\u4F1A\u5F71\u54CD\u663E\u793A\u5B9A\u4E49\u548C\u5BFC\u51FA\u8868\u5B9A\u4E49\u64CD\u4F5C\u3002\ + +PROPERTIES_GENERAL_TAB=\u4E00\u822C +PROPERTIES_COLUMNS_TAB=\u5217 +PROPERTIES_CONSTRAINTS_TAB=\u7EA6\u675F +PROPERTIES_INDEX_TAB=\u7D22\u5F15 +PROPERTIES_PARTITIONS_TAB=\u5206\u533A +PARTITION_COLUMN_ID=\u5206\u533A\u5217 +PROPERTIES_VIEW_NAME=\u89C6\u56FE\u540D +PROPERTIES_VIEW_OWNER=\u5C5E\u4E3B +PROPERTIES_VIEW_DEF=\u89C6\u56FE\u5B9A\u4E49 +DS_RESTART_CONFIRMATION_TITLE = \u91CD\u542F\u786E\u8BA4 +DS_RESTART_MSG_FOR_JOBS = \u4F5C\u4E1A\u6B63\u5728\u8FD0\u884C\u4E2D\u3002\u786E\u5B9A\u8981\u91CD\u65B0\u542F\u52A8\u5417\uFF1F +PROPERTIES_VIEW_DEF=\u89C6\u56FE\u5B9A\u4E49 + +TABLEPROPERTIES_OPTIONS_ORIENTATION= \u5B58\u50A8\u65B9\u5F0F +TABLEPROPERTIES_OPTIONS_FILLFACTOR= \u586B\u5145\u56E0\u5B50 +TABLEPROPERTIES_OPTIONS_COMPRESSION=\u662F\u5426\u538B\u7F29 +TABLEPROPERTIES_OPTIONS_MAX_BATCHROW= \u5B58\u50A8\u5355\u5143\u5BB9\u7EB3\u6700\u5927\u8BB0\u5F55\u6570 +TABLEPROPERTIES_OPTIONS_PARTIAL_CLUSTER_ROWS= \u5C40\u90E8\u805A\u7C07\u5B58\u50A8\u8BB0\u5F55\u6570 +SEARCH_ITEM_TEXT=\u8BF7\u8F93\u5165\u641C\u7D22\u5185\u5BB9 +TABLE_PROPERTIES_GROUP=\u8868\u5C5E\u6027 + +PARTITION_ERROR_MESSAGE=\u8BF7\u8F93\u5165\u81F3\u5C11\u4E00\u4E2A\u5206\u533A\u3002 + +ENTER_TABLE_NAME=\u8F93\u5165\u5B57\u6BB5\u540D + +ENTER_COLUMN_NAME=\u8F93\u5165\u7D22\u5F15\u540D +ENTER_INDEX_NAME=\u8BF7\u81F3\u5C11\u9009\u62E9\u4E00\u9879 + +PARTITION_COLUMN_ERROR_THAN_FOUR=\u5206\u533A\u8868\u5217\u7684\u6570\u91CF\u4E0D\u80FD\u5927\u4E8E 4 +PARTITION_COLUMN_ERROR_THAN_ONE=\u5206\u533A\u8868\u5217\u7684\u6570\u91CF\u4E0D\u80FD\u5927\u4E8E 1 +SQL_HISTORY_STATUS_SUCCESS= \u6210\u529F + +SQL_HISTORY_STATUS_FAILURE= \u5931\u8D25 +PARTITION_UI_SELECT=\u8BF7\u9009\u62E9 +VERSION=\u7248\u672C +PREFERENCE_COMMAND_NEW_NODE_CONNECTION= \u65B0\u5EFA\u8FDE\u63A5 +PREFERENCE_SHORTCUT_DISSCONN_FRM_DB =\u65AD\u5F00\u8FDE\u63A5 + +PREFERENCE_SHORTCUT_EXE_DB_OBJECT = \u6267\u884C + +PREFERENCE_SHORTCUT_REF_SREVER_OBJECT = \u5237\u65B0 +PREFERENCE_SHORTCUT_EXE_SQL_TERMINAL =\u6267\u884C\u8BED\u53E5 + +PREFERENCE_SHORTCUT_EXECUTION_PLAN_AND_COST=\u89E3\u91CA\u8BA1\u5212\u548C\u6210\u672C +PREFERENCE_SHORTCUT_VISUAL_EXPLAIN_PLAN=\u53EF\u89C6\u5316\u89E3\u91CA\u8BA1\u5212 +PREFERENCE_SHORTCUT_FORMAT_SQL_STATEMENT = \u683C\u5F0F\u5316 +PREFERENCE_SHORTCUT_OPEN_SAVED_FILE =\u6253\u5F00 + +PREFERENCE_SHORTCUT_TO_SAVE_FILE = \u4FDD\u5B58 +PREFERENCE_SHORTCUT_TO_SAVE_FILE_AS = \u53E6\u5B58\u4E3A +PREFERENCE_SHORTCUT_CANCEL_SQL_STETEMNT = \u7EC8\u6B62\u8BED\u53E5 +PREFERENCE_SHORTCUT_CLOSE_ACTIVE_VIEWER = \u5173\u95ED\u5F53\u524D\u7684\u6E90\u67E5\u770B\u5668 + + +PREFERENCE_SHORTCUT_COLAPSE_ALL_OBJECTS= \u6298\u53E0\u5DF2\u6253\u5F00\u7684\u5BF9\u8C61 +PREFERENCE_SHORTCUT_AUTO_SUGGEST= \u81EA\u52A8\u5EFA\u8BAE +PREFERENCE_SHORTCUT_CODE_TEMPLATE=\u6A21\u677F +PREFERENCE_SHORTCUT_TO_UPPER_CASE = \u5927\u5199 +PREFERENCE_SHORTCUT_TO_LOWER_CASE = \u5C0F\u5199 + +PREFERENCE_SHORTCUT_GO_TO_LINE= \u8F6C\u5230\u884C +PREFERENCE_SHORTCUT_FORWARD_SEARCH= \u67E5\u627E\u4E0B\u4E00\u5904 +PREFERENCE_SHORTCUT_BACKWARD_SEARCH = \u67E5\u627E\u4E0A\u4E00\u5904 +PREFERENCE_SHORTCUT_KEY_BINDING_SEARCH_DESC= \u641C\u7D22\u5BF9\u8C61 + +PREFERENCE_RESTART_REQUIRED_MSG=\u5DF2\u66F4\u6539\u9996\u9009\u9879\u3002\u8BF7\u91CD\u542FData Studio\u4EE5\u4F7F\u66F4\u6539\u751F\u6548\u3002 +COLUMN_OLD_NAME ={1}.{2}\u8868\u4E2D\u7684{0}\u5217 + +CIPHER_EXPIRY_TITLE = \u5bc6\u7801\u8fc7\u671f\u524d\u0037\u5929\u662f\u5426\u5141\u8bb8\u767b\u5f55\u6570\u636e\u5e93 +YES_EXPIRY_OPTION=\u5141\u8bb8\u767b\u5f55 +NO_EXPIRY_OPTION = \u4e0d\u5141\u8bb8\u767b\u5f55 +CIPHER_EXPIRY_MSG_TITLE=\u5bc6\u7801\u5373\u5c06\u8fc7\u671f +CIPHER_EXPIRY_INFORMATION = \u5bc6\u7801\u5c06\u8981\u8fc7\u671f\uff0c\u67d0\u4e9b\u64cd\u4f5c\u53ef\u80fd\u53d7\u5230\u9650\u5236\u3002\u8bf7\u8054\u7cfb\u7ba1\u7406\u5458\u91cd\u7f6e\u5bc6\u7801\u3002 + +RESULT_WINDOW_EDITTABLE_COMMIT_SUCCESS=\u6210\u529F\uFF1A{0} {1} {2} {3} + RESULT_WINDOW_EDITTABLE_COMMIT_FAILURE=/\u5931\u8D25\uFF1A{0} + EDITTABLE_PREFERENCE_OPTION=\u7F16\u8F91\u8868\u6570\u636E +EDITTABLE_TITLE = \u8868\u6570\u636E\u4FDD\u5B58\u6A21\u5F0F +YES_EDITTABLE_OPTION=\u4FDD\u5B58\u6709\u6548\u6570\u636E\u3002\u4E0D\u4FDD\u5B58\u65E0\u6548\u6570\u636E\uFF0C\u5E76\u5C06\u5176\u9AD8\u4EAE\u663E\u793A\uFF0C\u4EE5\u5F85\u66F4\u6B63\u3002 +NO_EDITTABLE_OPTION=\u4E0D\u4FDD\u5B58\u4EFB\u4F55\u6570\u636E\u3002\u9AD8\u4EAE\u663E\u793A\u65E0\u6548\u6570\u636E\uFF0C\u4EE5\u5F85\u66F4\u6B63\u3002 +EDIT_TABLE_ENABLE_OPTION=\u4FDD\u5B58\u6709\u6548\u6570\u636E +EDIT_TABLE_DISABLE_OPTION=\u6570\u636E\u51FA\u9519\u65F6\uFF0C\u4E0D\u4FDD\u5B58\u4EFB\u4F55\u6570\u636E + +ANALYZING_TABLE= \u5206\u6790\u8868 +REINDEX_TABLE_TITLE= \u91CD\u5EFA\u8868\u7D22\u5F15 +VACCUME_TABLE_TITLE= \u6E05\u7A7A\u8868 + + SHOW_USER_MSG_ON_TABLE_UPDATE_TITLE =\u66F4\u65B0\u5217 + SHOW_USER_MSG_ON_TABLE_UPDATE_BODY =\u5982\u679C\u4FEE\u6539\u8BE5\u5217\uFF0C{0}\u9875\u7B7E\u4E2D\u7684\u4FE1\u606F\u5C06\u88AB\u5220\u9664\u3002 + + + CONSTRAINT_INDEXES_HANDLER_NOT_SUPPORTED_TITLE=\u4E0D\u652F\u6301\u7684\u64CD\u4F5C + CONSTRAINT_HANDLER_FOR_COLUMN_ORIENTATION_BODY=\u4E0D\u652F\u6301\u4E3A\u5217\u5B58\u8868\u521B\u5EFA\u7EA6\u675F\u3002 + CHANGE_INDEX_FOR_COLUMN_ORIENTATION_TABLE= \u5217\u5B58\u8868\u4E2D\u65E0\u6CD5\u4FEE\u6539\u7D22\u5F15\u7684\u586B\u5145\u56E0\u5B50\u3002\u8BE5\u503C\u5DF2\u88AB\u8BBE\u7F6E\u4E3A\u9ED8\u8BA4\u503C100\u3002 + + DATA_DISTRIBUTION_TAB=\u6570\u636E\u5206\u5E03 + INDEXES_TAB=\u7D22\u5F15 + CONSTRAINT_TAB=\u7EA6\u675F + PARTITION_TAB= \u5206\u533A + +CANCEL_CONNECTION_TITLE=\u53D6\u6D88\u8FDE\u63A5 +CANCEL_CONNECTION_BODY=\u786E\u5B9A\u8981\u53D6\u6D88\u8BE5\u6570\u636E\u5E93\u7684\u8FDE\u63A5\u5417\uFF1F +USER_CANCEL_MSG =\u5DF2\u6839\u636E\u7528\u6237\u8BF7\u6C42\u53D6\u6D88\u8BE5\u64CD\u4F5C\u3002 + + REFRESH_TABLE_TOOLTIP=\u5237\u65B0 + REFRESH_TABLE_TOOLTIP_DISABLED = \u5237\u65B0\u524D\u8BF7\u4FDD\u5B58/\u53D6\u6D88\u66F4\u6539 + INSERT_ROW_TOOLTIP=\u6DFB\u52A0 + DELETE_ROW_TOOLTIP=\u5220\u9664 + COMMIT_CHANGES_TOOLTIP= \u4FDD\u5B58\u66F4\u6539 + ROLLBACK_CHANGES_TOOLTIP= \u53D6\u6D88\u66F4\u6539 + PASTE_TOOTIP=\u7C98\u8D34\u5230\u8868\u683C + DEFINE_UNIQUE_KEY_TITLE=\u5B9A\u4E49\u552F\u4E00\u952E + UNIQUE_CONSTRAINT_COLNAME_HEADER=\u5217\u540D\u79F0 + UNIQUE_CONSTRAINT_DATATYPE_HEADER=\u6570\u636E\u7C7B\u578B + UNIQUE_CONSTRAINT_SELECT_ALL_BTN_LABEL=\u5168\u9009 + UNIQUE_CONSTRAINT_CLEAR_ALL_BTN_LABEL=\u5168\u90E8\u6E05\u9664 + UNIQUE_CONSTRAINT_TABLE_LABEL= \u8868 + USE_ALL_COLUMNS_LABEL=\u4F7F\u7528\u6240\u6709\u5217 + CUSTOM_UNIQUE_KEY_LABEL=\u81EA\u5B9A\u4E49\u552F\u4E00\u952E + CANCEL_LABEL=\u53D6\u6D88 + GROUP_COLUMNS_HEADER=\u5217 + NO_PHYSICAL_UNQ_KEY_MSG=\u5BF9\u8BE5\u8868\u672A\u5B9A\u4E49\u552F\u4E00\u7269\u7406\u952E\uFF1A + DEFINE_UNQ_KEY_MSG =\u8981\u7EE7\u7EED\u64CD\u4F5C\uFF0C\u8BF7\u5B9A\u4E49\u552F\u4E00\u952E\u6216\u9009\u62E9\u6240\u6709\u5217\u3002 + + + +CONNECT_DB_CANCEL_MSG=\u5DF2\u6839\u636E\u7528\u6237\u8BF7\u6C42\u53D6\u6D88\u6570\u636E\u5E93\u8FDE\u63A5\u3002 + + PASTE_INVALID_SELECTION_DIALOG_TITLE=\u6240\u9009\u5185\u5BB9\u65E0\u6548 + PASTE_INVALID_SELECTION_DIALOG_MSG=\u590D\u5236\u7684\u5355\u5143\u683C\u6570\u5FC5\u987B\u4E0EData Studio\u4E2D\u9009\u62E9\u7684\u5355\u5143\u683C\u6570\u5339\u914D\u3002 + QUERY_EXECUTION_FAILURE_ERROR_TITLE=\u6570\u636E\u4FEE\u6539\u5931\u8D25 + QUERY_EXECUTION_FAILURE_ERROR=\u65E0\u6CD5\u66F4\u65B0\u4E00\u884C\u6216\u591A\u884C\u3002\u8BF7\u5C06\u9F20\u6807\u60AC\u505C\u5728\u7EA2\u8272\u884C\u53F7\u5904\uFF0C\u68C0\u67E5\u5177\u4F53\u7684\u9519\u8BEF\u4FE1\u606F\u3002 + + GRID_EDIT_STATUS_INSERTED = \u63D2\u5165\uFF1A + GRID_EDIT_STATUS_UPDATED = \u4FEE\u6539\uFF1A + GRID_EDIT_STATUS_DELETED = \u5220\u9664\uFF1A + EDIT_TABLE_DATA_CONNECTION_LOST_ERR_MSG= \u4FDD\u5B58\u8868\u6570\u636E\u65F6\u53D1\u751F\u9519\u8BEF\uFF0C\u8FDE\u63A5\u53EF\u80FD\u4E22\u5931\u3002\u8BF7\u91CD\u65B0\u8FDE\u63A5\u5E76\u7F16\u8F91\u8868\u6570\u636E\u3002 + + +DB_ASSISTANT_LANGUAGE=zh_CN + +DB_ASSISTANT_NAME=SQL\u52a9\u624b +DB_ASSISTANT_ENABLE=\u5f00\u542f +DB_ASSISTANT_DISABLE=\u5173\u95ed +DB_ASSIST_ENABLE_DESC=SQL\u52A9\u624B\u4E3ASQL\u7EC8\u7AEF\u548C\u5B58\u50A8\u8FC7\u7A0B/\u51FD\u6570\u7EC8\u7AEF\u4E2D\u8F93\u5165\u7684\u4FE1\u606F\u63D0\u4F9B\u5EFA\u8BAE\u6216\u53C2\u8003\u3002 +DB_ASSIST_DISABLE_DESC=SQL\u52A9\u624B\u4E0D\u4E3ASQL\u7EC8\u7AEF\u548C\u5B58\u50A8\u8FC7\u7A0B/\u51FD\u6570\u7EC8\u7AEF\u4E2D\u8F93\u5165\u7684\u4FE1\u606F\u63D0\u4F9B\u5EFA\u8BAE\u6216\u53C2\u8003\u3002 + +EDIT_TABLE_DATA_ERROR_POPUP_HEADER= \u7F16\u8F91\u8868\u6570\u636E\u51FA\u9519 +VIEW_TABLE_DATA_ERROR_POPUP_HEADER= \u5BF9\u8C61\u5220\u9664\u5931\u8D25 +EDIT_TABLE_DATA_ERROR_POPUP_MESSAGE=\u7F16\u8F91\u8868\u6570\u636E\u65F6\u53D1\u751F\u9519\u8BEF\u3002 +PROPERTIES_WINDOW_ERROR_POPUP_HEADER=\u8868\u5C5E\u6027\u9519\u8BEF + +ERR_CIPHER_EXPIRED =\u5BC6\u7801\u5DF2\u8FC7\u671F\u3002 +ERR_TO_BEGIN_TRANSACTION=\u65E0\u6CD5\u5F00\u59CB\u4E8B\u52A1\u3002 +ERR_EDIT_TABLE_COMMIT_FAIL=SQL\u9519\u8BEF\u7801\uFF1A +ERR_LAZY_BACKEND_LOAD_TITLE=\u52A0\u8F7D\u5BF9\u8C61\u65F6\u51FA\u9519\u3002 + +ERR_EDIT_TABLE_DROP_TABLE=\u65E0\u6CD5\u7F16\u8F91\u8868\u6570\u636E\uFF0C\u56E0\u4E3A\u5BF9\u8C61\u5DF2\u88AB\u4FEE\u6539/\u5220\u9664\u3002\u8BF7\u5237\u65B0\u5BF9\u8C61\u6D4F\u89C8\u5668\uFF0C\u7136\u540E\u91CD\u8BD5\u3002 +USER_CANCEL = \u7528\u6237\u53D6\u6D88\u64CD\u4F5C +LAST_LOGING_FAILED_RETREIVAL_DATABASE = \u65E0\u6CD5\u83B7\u53D6\u6570\u636E\u5E93\u7684\u4E0A\u6B21\u767B\u5F55\u4FE1\u606F\u3002 +ERR_DATABASE_OPERATION_FAILURE=\u6570\u636E\u5E93\u64CD\u4F5C\u65F6\u51FA\u9519\u3002 +ERR_FETCH_DATABASE_OPERATION=\u4ECE\u8282\u70B9\u83B7\u53D6\u6570\u636E\u5E93\u5217\u8868\u65F6\u51FA\u9519\u3002 +ERR_WRITING_PROFILE_TO_DISK=\u672A\u80FD\u5199\u5165\u8FDE\u63A5\u6587\u4EF6\u7684\u5143\u6570\u636E\u78C1\u76D8\u3002 +ERR_PROFILE_FILE_REACHABLE=\u8FDE\u63A5\u6587\u4EF6\u4E0D\u53EF\u8BFB\u3002 +ERR_READING_PROFILE_DATA=\u8BFB\u53D6\u8FDE\u63A5\u6587\u4EF6\u7684\u5143\u6570\u636E\u6587\u4EF6\u65F6\u51FA\u9519\u3002 +ERR_TO_CONVERT_SEQ_DATA=\u8F6C\u6362\u7ED3\u679C\u96C6\u4E2D\u7684\u6570\u636E\u65F6\u51FA\u9519\u3002 +ERR_LAZY_LOADING_TABLE=\u52A0\u8F7D\u8868\u65F6\u51FA\u9519\u3002 + +ERR_VIEW_TABLE_FAILURE=\u8BF7\u5237\u65B0\u5BF9\u8C61\u6D4F\u89C8\u5668\uFF0C\u7136\u540E\u91CD\u8BD5\u3002 +FAILED_TO_LOCK_FILE=\u65E0\u6CD5\u9501\u5B9A\u6587\u4EF6\u3002 +EDIT_TABLE_FORGET_OPTIONS=\u6E05\u9664\u5DF2\u4FDD\u5B58\u7684\u552F\u4E00\u952E\u9009\u9879 +EDIT_TABLE_REMEMBER_CHOICE= \u8BB0\u4F4F\u6B64\u9009\u62E9 + +EDIT_TABLE_INVALID_DATE_DATATYPE=\u65E5\u671F/\u65F6\u95F4\u6761\u76EE\u8F93\u5165\u65E0\u6548\u3002\u65E5\u671F\u548C\u65F6\u95F4\u5B57\u6BB5\u5FC5\u987B\u4E3A\u201Cyyyy-mm-dd HH:mm:ss\u201D\u6216\u201CHH:mm:ss\u201D\u683C\u5F0F\u3002 +EDIT_TABLE_INVALID_NUMBER_DATATYPE=\u8BF7\u8F93\u5165\u6709\u6548\u6570\u636E\u3002 + +DRP_OBJ_ERRTITLE = \u5220\u9664\u5BF9\u8C61\u51FA\u9519 +DROP_OBJECT_ERROR = \u5220\u9664\u5BF9\u8C61\u65F6\u51FA\u9519\uFF1A{0} +TABLESPACE_CREATION_ERROR = \u521B\u5EFA\u8868\u7A7A\u95F4\u65F6\u51FA\u9519\uFF1A{0}.{1} +SEARCH_OBJ_CANCEL_MSG = \u6839\u636E\u7528\u6237\u8BF7\u6C42\u505C\u6B62\u641C\u7D22\u5BF9\u8C61\u3002 +SET_COL_VAL_ERROR = \u8BBE\u7F6E\u5217\u9ED8\u8BA4\u503C\u65F6\u51FA\u9519\uFF1A{0}.{1}.{2} +ADD_COLUMN_ERROR = \u6DFB\u52A0\u5217\u65F6\u51FA\u9519\uFF1A{0}.{1} +NEW_CONSTRAINT_CREATED_ERROR = \u521B\u5EFA\u7EA6\u675F\u65F6\u51FA\u9519\uFF1A{0}.{1} +TITLE_IOEXCEPTION = I/O\u5F02\u5E38 + +LOAD_CONN_ERR_TITLE = \u52A0\u8F7D\u8FDE\u63A5\u51FA\u9519 +LOAD_CONN_ERR_MSG = \u52A0\u8F7D\u7528\u6237\u4FE1\u606F\u65F6\u51FA\u9519\u3002\u670D\u52A1\u5668\u6D88\u606F\uFF1A{0} +LOG_ERR_TITLE = \u521B\u5EFA\u65E5\u5FD7\u51FA\u9519 +LOG_ERR_MSG = \u521B\u5EFA\u65E5\u5FD7\u65F6\u51FA\u9519\u3002\u670D\u52A1\u5668\u6D88\u606F\uFF1A{0} +REINDEX_TABLE_FAIL = \u91CD\u65B0\u7D22\u5F15\u8868\u65F6\u51FA\u9519\uFF1A{0}.{1} +SET_COLUMN_FAIL = \u4E3A\u5217\u8BBE\u7F6ENOT NULL\u65F6\u51FA\u9519\uFF1A{0}.{1}.{2} +DROP_SCHEMA_FAIL = \u5220\u9664\u6A21\u5F0F\u65F6\u51FA\u9519\uFF1A{0}.{1} +REMOVE_CONN_ERROR = \u5220\u9664\u8FDE\u63A5\u914D\u7F6E\u6587\u4EF6\u65F6\u51FA\u9519\u3002\u670D\u52A1\u5668\u6D88\u606F\uFF1A{0} +REMOVE_CONNPROF_TITLE = \u5220\u9664\u8FDE\u63A5\u51FA\u9519 +ERR_PROFILE_WRITE_DISK_TITLE = \u914D\u7F6E\u6587\u4EF6\u5199\u5165\u78C1\u76D8\u65F6\u51FA\u9519 +ERR_CONNECTION_FAILED = \u8FDE\u63A5\u9519\u8BEF + +SET_TABLESPACE_FAIL= \u8BBE\u7F6E\u8868\u7A7A\u95F4\u65F6\u51FA\u9519\u3002 + +DROP_SEQUENCE_ERROR = \u5220\u9664\u5E8F\u5217\u65F6\u51FA\u9519\uFF1A{0}.{1} +EXPORT_TABLE_SUCESS = \u5DF2\u5BFC\u51FA\u8868\u6570\u636E\uFF1A{0} +EXPORT_DDL_CANCEL_MSG=\u6839\u636E\u7528\u6237\u8BF7\u6C42\u53D6\u6D88\u5BFC\u51FA\u64CD\u4F5C + +#for Visual explain Plan--start + +VIS_EXPLAIN_ICON_TOOLTIP_ZOOM_RESET=\u91CD\u7F6E + +VIS_EXPLAIN_JOB_DETAILS=Generating Visual Explain plan for the query +VIS_EXPLAIN_JOB_RESULT_DETAILS=Visual Explain Plan Property + +VIS_EXPLAIN_MAN_WINDOW_TITLE=\u53EF\u89C6\u5316\u8BA1\u5212\u5206\u6790 +VIS_EXPLAIN_WINDOW_LBL=\u53EF\u89C6\u5316\u89E3\u91CA\u8BA1\u5212 +VIS_EXPLAIN_WINDOW_TEXT_LBL=\u822C\u4FE1\u606F +VIS_EXPLAIN_WINDOW_ALL_NODES_LBL=\u5C5E\u6027 + +VIS_EXPLAIN_OVERALL_DETAILS_ALLNODES_TAB=\u6240\u6709\u8282\u70B9 +VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_ANALYSIS=\u5206\u6790 +VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_CONTRIBUTION=\u8D21\u732E (%) +VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_EXECUTIONTIME=\u6267\u884C\u65F6\u95F4 (ms) +VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_NODENAME=\u8282\u70B9\u540D\u79F0 +VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_ROWSOUTPUT=\u884C\u8F93\u51FA +VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_ROWSOUTPUTDEVIATION=\u884C\u8F93\u51FA\u504F\u5DEE (%) +VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_SELFCOST=\u672C\u8282\u70B9\u5F00\u9500 +VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_TOTALCOST=\u603B\u6210\u672C + +VIS_EXPLAIN_OVERALL_DETAILS_GENERAL_TAB=\u4E00\u822C +VIS_EXPLAIN_OVERALL_DETAILS_GENERAL_COLUMN_PROP=\u5C5E\u6027 +VIS_EXPLAIN_OVERALL_DETAILS_GENERAL_COLUMN_VALUE=\u503C +VIS_EXPLAIN_OVERALL_DETAILS_ROOTNODE_TOTALRUNTIME=Total Runtime (ms) + +VIS_EXPLAIN_PROP_PERDN_ACTUALSINDETAIL_COLUMNGRP=Actuals +VIS_EXPLAIN_PROP_PERDN_ACTUALS_COLUMN_LOOPS=Loops +VIS_EXPLAIN_PROP_PERDN_ACTUALS_COLUMN_ROWS=Rows +VIS_EXPLAIN_PROP_PERDN_ACTUALS_COLUMN_STARTUPTIME=Startup Time (ms) +VIS_EXPLAIN_PROP_PERDN_ACTUALS_COLUMN_TOTALTIME=Total Time (ms) +VIS_EXPLAIN_PROP_PERDN_AGGREGATEINDETAIL=Aggregate Details +VIS_EXPLAIN_PROP_PERDN_BUFFERSINDETAIL=Buffer Details +VIS_EXPLAIN_PROP_PERDN_CPUINDETAIL=CPU Details +VIS_EXPLAIN_PROP_PERDN_HASHDETAIL=Hash Detail +VIS_EXPLAIN_PROP_PERDN_SETOPDETAIL=SetOp Detail +VIS_EXPLAIN_PROP_PERDN_DN_COLUMNGRP=DN Information +VIS_EXPLAIN_PROP_PERDN_DN_COLUMN=DN Name +VIS_EXPLAIN_PROP_PERDN_JOININDETAIL=Join Details +VIS_EXPLAIN_PROP_PERDN_LLVM_COLUMNGRP=LLVM Details +VIS_EXPLAIN_PROP_PERDN_LLVM_COLUMN=LLVM + +VIS_EXPLAIN_PER_NODE_COLUMN_PROP=\u5C5E\u6027 +VIS_EXPLAIN_PER_NODE_COLUMN_VALUE=\u503C +VIS_EXPLAIN_PER_NODE_DETAILS_PART_LBL=DN\u8BE6\u7EC6\u4FE1\u606F +VIS_EXPLAIN_PER_NODE_DETAILS_GENERAL_TAB=\u4E00\u822C +VIS_EXPLAIN_PER_NODE_DETAILS_PERDN_TAB=DN\u8BE6\u7EC6\u4FE1\u606F + +VIS_EXPLAIN_NODCATEGORY_AGGREGATE=Aggregate +VIS_EXPLAIN_NODCATEGORY_FUNCTION=Function Scan +VIS_EXPLAIN_NODCATEGORY_GROUPAGGREGATE=Group Aggregate +VIS_EXPLAIN_NODCATEGORY_HASH=Hash +VIS_EXPLAIN_NODCATEGORY_HASHJOIN=Hash Join +VIS_EXPLAIN_NODCATEGORY_MODIFYTABLE=Modify Table +VIS_EXPLAIN_NODCATEGORY_NESTLOOPJOIN=Nest Loop Join +VIS_EXPLAIN_NODCATEGORY_NESTEDLOOP=Nested Loop +VIS_EXPLAIN_NODCATEGORY_PARTITIONITERATOR=Partition Iterator +VIS_EXPLAIN_NODCATEGORY_ROWADAPTER=Row Adapter +VIS_EXPLAIN_NODCATEGORY_SCAN=Scan +VIS_EXPLAIN_NODCATEGORY_SETOP=SetOp +VIS_EXPLAIN_NODCATEGORY_SORT=Sort +VIS_EXPLAIN_NODCATEGORY_STREAM=Stream +VIS_EXPLAIN_NODCATEGORY_UNKNOWN=Unknown +VIS_EXPLAIN_NODCATEGORY_UNION=Union + +VIS_EXPLAIN_PROP_ANALYSISNODE_ANALYSIS=Analysis +VIS_EXPLAIN_PROP_ANALYSISNODE_OUTPUT=Output +VIS_EXPLAIN_PROP_ANALYSISNODE_ROWSOUTPUTDEVIATION=Rows Output Deviation (%) + +VIS_EXPLAIN_PROP_BASICNODE_ACTUALLOOPS=Actual Loops +VIS_EXPLAIN_PROP_BASICNODE_ACTUALOUTROWS=Actual Output Rows +VIS_EXPLAIN_PROP_BASICNODE_ACTUALSTARTUPTIME=Actual Startup Time +VIS_EXPLAIN_PROP_BASICNODE_ACTUALTOTALTIME=Actual Total Time + +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_IOREADTIME=I/O Read Time (ms) +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_IOWRITETIME=I/O Write Time (ms) +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALDIRTIEDBLOCKS=Local Dirtied Blocks +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALHITBLOCKS=Local Hit Blocks +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALREADHITBLOCKS=Local Read Blocks +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALWRITTENBLOCKS=Local Written Blocks +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDDIRTIEDBLOCKS=Shared Dirtied Blocks +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDHITBLOCKS=Shared Hit Blocks +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDREADBLOCKS=Shared Read Blocks +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDWRITTENBLOCKS=Shared Written Blocks +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_TEMPREADBLOCKS=Temp Read Blocks +VIS_EXPLAIN_PROP_BASICNODE_BUFFER_TEMPWRITTENBLOCKS=Temp Written Blocks + +VIS_EXPLAIN_PROP_BASICNODE_CPU_EXCLUSIVECYCLESROW=Exclusive Cycles/Row +VIS_EXPLAIN_PROP_BASICNODE_CPU_EXCLUSIVECYCLES=Exclusive Cycles +VIS_EXPLAIN_PROP_BASICNODE_CPU_INCLUSIVECYCLES=Inclusive Cycles + +VIS_EXPLAIN_PROP_BASICNODE_HASH_HASHBATCHES=Hash Batches +VIS_EXPLAIN_PROP_BASICNODE_HASH_HASHBUCKETS=Hash Buckets +VIS_EXPLAIN_PROP_BASICNODE_HASH_ORIGINALHASHBATCHES=Original Hash Batches +VIS_EXPLAIN_PROP_BASICNODE_HASH_PEAKMEMORYUSAGE=Peak Memory Usage + +VIS_EXPLAIN_PROP_BASICNODE_ISVECTORIZED=Is Column Store +VIS_EXPLAIN_PROP_BASICNODE_NODETYPE=Node Type +VIS_EXPLAIN_PROP_BASICNODE_PARENTRELATIONSHIP=Parent Relationship +VIS_EXPLAIN_PROP_BASICNODE_PLANROWS=Plan Output Rows +VIS_EXPLAIN_PROP_BASICNODE_PLANWIDTH=Row Width(Bytes) + +VIS_EXPLAIN_PROP_BASICNODE_STARTUPCOST=Startup Cost +VIS_EXPLAIN_PROP_BASICNODE_TOTALCOST=Total Cost + +VIS_EXPLAIN_PROP_CSTORESCANNODE_FILTER=Filter +VIS_EXPLAIN_PROP_CSTORESCANNODE_ROWREMOVEDFILTER=Rows Removed by Filter + +VIS_EXPLAIN_PROP_DATANODESCAN_PRIMARYNODECOUNT=Primary Node Count +VIS_EXPLAIN_PROP_DATANODESCAN_NODECOUNT=Node Count + +VIS_EXPLAIN_PROP_FUNCTIONSCANNODE_FUNCTIONALIASNAME=Alias +VIS_EXPLAIN_PROP_FUNCTIONSCANNODE_FUNCTIONCALL=Function Call +VIS_EXPLAIN_PROP_FUNCTIONSCANNODE_FUNCTIONNAME=Function Name +VIS_EXPLAIN_PROP_FUNCTIONSCANNODE_SCHEMANAME=Schema + +VIS_EXPLAIN_PROP_GROUP_BY_GRPBYKEYS=Group By key +VIS_EXPLAIN_PROP_JOIN_JOINTYPE=Join Type + +VIS_EXPLAIN_PROP_HASHNODE_HASHBUCKETS=Hash Buckets +VIS_EXPLAIN_PROP_HASHNODE_HASHBATCHES=Hash Batches +VIS_EXPLAIN_PROP_HASHNODE_ORIGINALHASHBATCHES=Original Hash Batches +VIS_EXPLAIN_PROP_HASHNODE_PEAKMEMORYUSAGE=Peak Memory Usage + +VIS_EXPLAIN_PROP_HASH_JOIN_JOINCOND=Hash Condition + +VIS_EXPLAIN_PROP_INDEXSCANNODE_INDEXCOND=Index Condition +VIS_EXPLAIN_PROP_INDEXSCANNODE_INDEXNAME=Index Name +VIS_EXPLAIN_PROP_INDEXSCANNODE_ROWSREMOVEDRECHECK=Rows Removed by Index Recheck +VIS_EXPLAIN_PROP_INDEXSCANNODE_SCANDIRECTION=Scan Direction + +VIS_EXPLAIN_PROP_MODIFYTABLE_OPERATION=Operation +VIS_EXPLAIN_PROP_NESTLOOP_JOIN_JOINFILTER =Join Filter +VIS_EXPLAIN_PROP_NESTLOOP_JOIN_ROWSREMOVEDBYJOINFILTER =Rows Removed By Join Filter +VIS_EXPLAIN_PROP_NESTEDLOOP_SUBPLAN=Subplan Name +VIS_EXPLAIN_PROP_NODE_REMOTEQUERY=Remote Query +VIS_EXPLAIN_PROP_NODE_SUBPLANNAME=Subplan Name + +VIS_EXPLAIN_PROP_OPERATIONALNODE_CHILD1NAME=Inner Node Name +VIS_EXPLAIN_PROP_OPERATIONALNODE_CHILD2NAME=Outer node Name +VIS_EXPLAIN_PROP_OPERATIONALNODE_CHILDRENNAME=Child Name + +VIS_EXPLAIN_PROP_SCANNODE_ALIASNAME=Alias +VIS_EXPLAIN_PROP_SCANNODE_SCANTABLEALIASNAME=Table Alias +VIS_EXPLAIN_PROP_SCANNODE_SCANTABLENAME=Table Name +VIS_EXPLAIN_PROP_SCANNODE_SCHEMANAME=Schema Name +VIS_EXPLAIN_PROP_SCANNODE_SELECTEDPARTITIONS=Selected Partitions +VIS_EXPLAIN_PROP_SETOPNODE_TEMPFILENUM=Temp File Num +VIS_EXPLAIN_PROP_SETOP_COMMAND=Command +VIS_EXPLAIN_PROP_SETOP_STRATEGY=Strategy +VIS_EXPLAIN_PROP_SORT_SORTKEYS=Sort keys + +VIS_EXPLAIN_PROP_STREAM_GATHER_NODES=Node/s +VIS_EXPLAIN_PROP_STREAM_REDISTRIBUTE_DISTRKEY=Distribution Key +VIS_EXPLAIN_PROP_STREAM_REDISTRIBUTE_SPAWNON=Spawn On +VIS_EXPLAIN_PROP_WORKTABLESCANNODE_FILTER=Filter +VIS_EXPLAIN_PROP_WORKTABLESCANNODE_ROWREMOVEDFILTER=Rows Removed by Filter + +VIS_EXPLAIN_ANALYSIS_COSTLIEST=\u5F00\u9500\u6700\u5927 +VIS_EXPLAIN_ANALYSIS_HEAVIEST=\u8D1F\u8F7D\u6700\u5927 +VIS_EXPLAIN_ANALYSIS_SLOWEST=\u6700\u6162 + +VIS_EXPLAIN_JSON_PARSING_FAILED=\u6765\u81EA\u670D\u52A1\u5668\u7684JSON\u683C\u5F0F\u65E0\u6548. + +VIS_EXPLAIN_PLAN_ERROR_POPUP_HEADER=\u53EF\u89C6\u5316\u89E3\u91CA\u67E5\u8BE2\u8BA1\u5212\u51FA\u9519 +EXPLAIN_PLAN_ERROR_POPUP_HEADER=\u89E3\u91CA\u67E5\u8BE2\u8BA1\u5212\u51FA\u9519 + +#for Visual explain Plan--end + +CANCEL_OPERATION_IN_PROGRESS=\u6B63\u5728\u53D6\u6D88\u64CD\u4F5C\u2026\u2026 +TABLE_PROPERTIES_TABLE_NAME=\u8868\u540D +USER_CANCEL_MSG_TITLE=\u53D6\u6D88\u64CD\u4F5C + +INVALID_INCLUDE_EXCLUDE_SCHEMA=\u5FEB\u901F\u52A0\u8F7D\u9009\u9879\u7684\u201C\u4E0D\u5305\u542B\u201D\u5B57\u6BB5\u4E2D\u8F93\u5165\u7684\u6A21\u5F0F\u4FE1\u606F{0}\u548C\u201C\u5305\u542B\u201D\u5B57\u6BB5\u4E2D\u8F93\u5165\u7684\u6A21\u5F0F\u4FE1\u606F{1} +INVALID_EXCLUDE_SCHEMA=\u5728\u5FEB\u901F\u52A0\u8F7D\u9009\u9879\u4E2D\u8F93\u5165\u7684\u6A21\u5F0F\u4FE1\u606F{0}\u65E0\u6548\u3002 +INVALID_INCLUDE_SCHEMA=\u5FEB\u901F\u52A0\u8F7D\u9009\u9879\u7684\u201C\u5305\u542B\u201D\u5B57\u6BB5\u4E2D\u8F93\u5165\u7684\u6A21\u5F0F\u4FE1\u606F{0}\u65E0\u6548\u3002 +INVALID_INCLUDE_EXCLUDE_TITLE=\u65E0\u6548\u7684\u201C\u5305\u542B\u201D/\u201C\u4E0D\u5305\u542B\u201D\u5B57\u6BB5\u5185\u5BB9 + +UKNOWN_COMPLEX_DATATYPE=\u672A\u77E5 +EDIT_TABLE_DATA_DROPPED_REFRESH_ERROR=\u7F16\u8F91\u8868\u6570\u636E\u65F6\u53D1\u751F\u9519\u8BEF\u3002\n\u65E0\u6CD5\u7F16\u8F91\u8868\u6570\u636E\uFF0C\u56E0\u4E3A\u5BF9\u8C61\u5DF2\u88AB\u4FEE\u6539/\u5220\u9664\u3002\n\u8BF7\u91CD\u65B0\u6253\u5F00\u201C\u7F16\u8F91\u8868\u6570\u636E\u201D\u7A97\u53E3\u3002 +VIEW_TABLE_DATA_DROPPED_REFRESH_ERROR= \u83B7\u53D6\u6570\u636E\u5931\u8D25\uFF0C\u5BF9\u8C61\u5DF2\u88AB\u4FEE\u6539\u6216\u5220\u9664\u3002\u8BF7\u91CD\u65B0\u6253\u5F00\u7A97\u53E3\u3002 +LOAD_LIMIT_UNIT=\uFF08\u6570\u636E\u5E93\u5BF9\u8C61\u6570\uFF09 +CANCELLING_JOB=\u6B63\u5728\u53D6\u6D88{0} + +SQL_HIST_PINNED=\u9501\u5B9A +# NO Translation Required as only consumed by code +ERR_EDITTABLE_REFRESH_FAILED=Requested Table data not available + +# Translartion required for following +PARTITION_TABLE_COL_REMOVE_TITLE=\u4FEE\u6539\u5206\u533A\u5217 +PARTITION_TABLE_COL_REMOVE_BODY =\u66F4\u6539\u5206\u533A\u5217\u7684\u5217\u8868\u540E\uFF0C\u5C06\u5220\u9664\u6240\u6709\u5206\u533A\u5B9A\u4E49\uFF08\u5982\u6709\uFF09\u3002\u786E\u8BA4\u8981\u7EE7\u7EED\u5417\uFF1F + +PARTITION_VALUE_TOOLTIP=\u5355\u51FB\u8F93\u5165\u5206\u533A\u503C +PARTITION_VALUE_POPUP_TITLE=\u5B9A\u4E49\u5206\u533A\u503C +PARTITION_COLUMN=\u5217 +PARTITION_VALUE=\u503C + +EDIT_DUPLICATE_MODIFICATION_TITLE=\u91CD\u590D\u884C\u5DF2\u66F4\u65B0 +EDIT_DUPLICATE_MODIFICATION_MSG= \u627E\u5230\u591A\u4E2A\u91CD\u590D\u884C\uFF0C\u6240\u6709\u7684\u91CD\u590D\u884C\u5DF2\u88AB\u66F4\u65B0\u3002 + +RESULT_WINDOW_EDITTABLE_COMMIT_REFRESH= \u5237\u65B0\u4EE5\u67E5\u770B\u6570\u636E\u66F4\u65B0 + +RESULT_WINDOW_EDITTABLE_COMMIT_UPDATED=/\u5DF2\u66F4\u65B0\u884C\u6570: {0} +ERR_EXPORT_TABLE_DROP_TABLE=\u65E0\u6CD5\u5BFC\u51FA\u8868\u683C\u6570\u636E\uFF0C\u5BF9\u8C61\u5DF2\u88AB\u4FEE\u6539/\u5220\u9664\u3002\u8BF7\u5237\u65B0\u5BF9\u8C61\u6D4F\u89C8\u5668\u5E76\u91CD\u8BD5\u3002 +ERR_IMPORT_TABLE_DROP_TABLE=\u65E0\u6CD5\u5BFC\u5165\u8868\u683C\u6570\u636E\uFF0C\u5BF9\u8C61\u5DF2\u88AB\u4FEE\u6539/\u5220\u9664\u3002\u8BF7\u5237\u65B0\u5BF9\u8C61\u6D4F\u89C8\u5668\u5E76\u91CD\u8BD5\u3002 +TOOLTIP_DISTRIBUTION_COL=\n[\u5206\u5E03\u5217] +TOOLTIP_READONLY_COL=\n[\u8BE5\u5217\u4E0D\u53EF\u7F16\u8F91] +EXPORT_DDL_PROGRESS_NAME=\u6B63\u5728\u5BFC\u51FADDL\uFF1A{0} +EXPORT_DDL_DATA_PROGRESS_NAME=\u6B63\u5728\u5BFC\u51FADDL\u548C\u6570\u636E\uFF1A{0} + +DS_DEFAULT_MAX_CONSOLE_LINE_COUNT=ConsoleLineCount\u914D\u7F6E\u65E0\u6548\u3002\u6B63\u5728\u8BBE\u4E3A\u6700\u5927\u503C\uFF085000\uFF09\u3002 + +EXPORT_DDL=DDL +EXPORT_DDL_DATA=DDL\u548C\u6570\u636E +HAS_OID=\u662F\u5426\u6709OID + +NAMESPACE_RETRIVE_CRITICAL_ERROR=\u52A0\u8F7D\u6A21\u5F0F\u5BF9\u8C61\u65F6\u51FA\u9519\u3002 +CONNECT_TO_DB_STATE_MACHINE_ERROR =Cannot perform the requested operation as connection is in progress.\nTry again later. + +EDIT_TABLE_PROGRESS_NAME=\u6B63\u5728\u7F16\u8F91\u8868\u6570\u636E\u67E5\u8BE2\uFF1A{0} +EDIT_TABLE_COMMIT_PROGRESS_NAME=\u6B63\u5728\u63D0\u4EA4\u7F16\u8F91\u7684\u6570\u636E\uFF1A{0} +VIEW_TABLE_PROGRESS_NAME=\u6B63\u5728\u67E5\u770B\u8868\u6570\u636E\uFF1A{0} +VIEW_PROGRESS_NAME=\u6B63\u5728\u83B7\u53D6\u89C6\u56FE\u6570\u636E\uFF1A{0} +LAZYLOAD_NAMESPACE_PROGRESS_NAME=\u6B63\u5728\u540E\u53F0\u5EF6\u8FDF\u52A0\u8F7D\u6A21\u5F0F\uFF1A{0} +CHANGE_INDEX_TBLSPACE_PROGRESS_NAME=\u6B63\u5728\u66F4\u6539\u7D22\u5F15\u8868\u7A7A\u95F4\uFF1A{0} +DROP_COLUMN_PROGRESS_NAME=\u6B63\u5728\u5220\u9664\u5217\uFF1A{0} +DROP_PARTITION_PROGRESS_NAME=\u6B63\u5728\u5220\u9664\u5206\u533A\uFF1A{0} +DROP_TABLE_PROGRESS_NAME=\u6B63\u5728\u5220\u9664\u8868\uFF1A{0} +RENAME_COLUMN_PROGRESS_NAME=\u6B63\u5728\u91CD\u547D\u540D\u5217\uFF1A{0} +VALIDATE_CONSTRAINT_PROGRESS_NAME=\u6B63\u5728\u9A8C\u8BC1\u7EA6\u675F\uFF1A{0} +SHOW_VIEW_DDL_PROGRESS_NAME=\u6B63\u5728\u663E\u793A\u89C6\u56FEDDL\uFF1A{0} +CONNECT_DB_PROGRESS_NAME=\u6B63\u5728\u8FDE\u63A5\u5230\u6570\u636E\u5E93\uFF1A{0} +CREATE_DB_PROGRESS_NAME=\u6B63\u5728\u521B\u5EFA\u6570\u636E\u5E93\uFF1A{0} +DROP_SCHEMA_PROGRESS_NAME=\u6B63\u5728\u5220\u9664\u6A21\u5F0F\uFF1A{0} +DROP_DEBUGOBJECT_PROGRESS_NAME=\u6B63\u5728\u5220\u9664\u8C03\u8BD5\u5BF9\u8C61\uFF1A{0} +REINDEX_TABLE_PROGRESS_NAME=\u6B63\u5728\u4E3A{0}\u8868\u91CD\u5EFA\u7D22\u5F15 +RENAME_DATABASE_PROGRESS_NAME=\u6B63\u5728\u91CD\u547D\u540D\u6570\u636E\u5E93\uFF1A{0} +SHOW_DDL_TABLE_PROGRESS_NAME=\u6B63\u5728\u663E\u793A\u8868DDL\uFF1A{0} +ADD_COLUMN_PROGRESS_NAME=\u6B63\u5728\u6DFB\u52A0\u5217\uFF1A{0} +ADD_CONSTRAINT_PROGRESS_NAME=\u6B63\u5728\u6DFB\u52A0\u7EA6\u675F\uFF1A{0} +ALTER_COLUMN_DEFAULT_PROGRESS_NAME=\u6B63\u5728\u8BBE\u7F6E\u5217\u7684\u9ED8\u8BA4\u503C\uFF1A{0} +ALTER_VIEWCOLUMN_DEFAULT_PROGRESS_NAME=\u6B63\u5728\u8BBE\u7F6E\u89C6\u56FE\u5217\u7684\u9ED8\u8BA4\u503C\uFF1A{0} +CREATE_INDEX_PROGRESS_NAME=\u6B63\u5728\u521B\u5EFA\u7D22\u5F15\uFF1A{0} +CREATE_TABLE_PROGRESS_NAME=\u6B63\u5728\u521B\u5EFA\u8868\uFF1A{0} +EXPORT_ALL_RESULTDATA_PROGRESS_NAME=\u6B63\u5728\u5BFC\u51FA\u6240\u6709\u7ED3\u679C\u6570\u636E\uFF1A{0} +EXPORT_ALL_DATA_PROGRESS_NAME=\u6B63\u5728\u5BFC\u51FA\u6B64\u5BF9\u8C61\u7684\u5168\u90E8\u6570\u636E\uFF1A{0} +EXPORT_CURRENT_RESULTDATA_PROGRESS_NAME=\u6B63\u5728\u5BFC\u51FA\u5F53\u524D\u9875\u7ED3\u679C\u6570\u636E\uFF1A{0} +CREATE_SEQ_PROGRESS_NAME=\u6B63\u5728\u521B\u5EFA\u5E8F\u5217\uFF1A{0} +REEXECUTE_QUERY_PROGRESS_NAME=\u6B63\u5728SQL\u7EC8\u7AEF\u91CD\u65B0\u6267\u884C\u67E5\u8BE2\uFF1A{0} +CONN_PROP_HOST=\u4E3B\u673A +CONN_PROP_PORT=\u7AEF\u53E3 +CONN_PROP_USERNAME=\u7528\u6237\u540D +CONN_PROP_SERVER_TYPE=\u6570\u636E\u5E93\u7C7B\u578B +CONN_PROP_DB_VERSION=\u7248\u672C\u4FE1\u606F +CONNECTION_VERSION_NUMBER_FAILED_MSG=\u672A\u77E5 +CONNECTION_PROPERTIES_UNAVAILABLE= \u8FDE\u63A5\u5C5E\u6027\u4E0D\u53EF\u7528\u3002 +CONN_PROP_LOG_FOLDER=Logs folder + +#TRANSLATION FOR SQL HISTORY STARTS +SQL_HISTORY=SQL\u5386\u53F2\u8BB0\u5F55 +SET_SQL_SIZE=SQL\u5386\u53F2\u8BB0\u5F55\u6570 +SQL_SIZE_DESC_LABEL=\u8BBE\u7F6E\u53EF\u5728\u5386\u53F2\u8BB0\u5F55\u4E2D\u4FDD\u5B58\u7684\u67E5\u8BE2\u6570\u91CF\u3002\n\u66F4\u6539\u8BE5\u53C2\u6570\u540E\uFF0C\u53C2\u6570\u8BBE\u7F6E\u4F1A\u5BF9\u6B64\u540E\u65B0\u589E\u7684\u67E5\u8BE2\u751F\u6548\u3002 +#SQL_SIZE_DESC_PINNED_QUERIES_LABEL=Pinned queries will not be affected by this change. +SET_SQL_QUERY_LENGTH= SQL\u67E5\u8BE2\u5B57\u7B26\u6570 +SQL_HISTORY_RANGE=\u8303\u56F4: +DEFAULT_VALUE=\u9ED8\u8BA4\u503C: +SQL_QUERY_LENGTH_NO_LIMIT=\u65E0\u9650\u5236: +SQL_QUERY_DESC_LABEL1=\u8BBE\u7F6ESQL\u5386\u53F2\u8BB0\u5F55\u4E2D\u4FDD\u5B58\u7684\u67E5\u8BE2\u7684\u5B57\u7B26\u6570\u3002\n\u66F4\u6539\u8BE5\u53C2\u6570\u540E\uFF0C\u53C2\u6570\u8BBE\u7F6E\u4F1A\u5BF9\u6B64\u540E\u65B0\u589E\u7684\u67E5\u8BE2\u751F\u6548\u3002 +#SQL_QUERY_DESC_LABEL2=Affects only the queries added after this settings change. +SQL_SIZE_ERROR_MSG=Please enter valid value for SQL History Size. +SQL_QUERY_ERROR_MSG=Please enter valid value for SQL Query Characters. +UPDATE_SQL_HISTORY_SETTING_TITLE=\u66F4\u65B0SQL\u5386\u53F2\u8BB0\u5F55\u8BBE\u7F6E\u3002 +UPDATE_SQL_HISTORY_SETTING_BODY=\u5728\u201CSQL\u5386\u53F2\u67E5\u8BE2\u201D\u5B57\u6BB5\u4E2D\u8F93\u5165\u7684\u503C\u5C0F\u4E8E\u5F53\u524D\u503C\u3002\n \u67D0\u4E9BSQL\u5386\u53F2\u67E5\u8BE2\u53EF\u80FD\u4E22\u5931\u3002\n \u786E\u8BA4\u8981\u7EE7\u7EED\u5417\uFF1F +SQL_HISTORY_SETTING_UNSAVED_DATA_BODY=\u90E8\u5206\u8BBE\u7F6E\u66F4\u6539\u540E\u672A\u4FDD\u5B58\u3002 \u786E\u8BA4\u8981\u4FDD\u5B58\u66F4\u6539\u5417\uFF1F\n\n\u8BF4\u660E: \u5F53\u51FA\u73B0\u9519\u8BEF\u65F6\uFF0C\u5C06\u6062\u590D\u5230\u5F53\u524D\u503C\u3002 +SAVING_PREFERENCES=Saving Preferences .. + +#TRANSLATION FOR SQL HISTORY ENDS +CONNECTION_PROPERTIES_UNAVAILABLE= \u8FDE\u63A5\u5C5E\u6027\u4E0D\u53EF\u7528\u3002 + +#Templates Preference Page +CODE_TEMPLATE_PREFPAGE_MESSAGE=\u521B\u5EFA\u3001\u7F16\u8F91\u6216\u5220\u9664\u6A21\u677F(&C)\uFF1A +CODE_TEMPLATE_PREFPAGE_TITLE=\u6A21\u677F +CODE_TEMPLATE_DUPLICATE_MSG=\u8BE5\u6A21\u677F\u540D\u79F0{0}\u5DF2\u5B58\u5728 + +CODE_TEMPLATE_PREFPAGE_EDIT=\u7F16\u8F91(&E) +CODE_TEMPLATE_PREFPAGE_NEW=\u65B0\u5EFA(&N) +CODE_TEMPLATE_PREFPAGE_REMOVE=\u5220\u9664(&R) +CODE_TEMPLATE_PREFPAGE_RESTORE=\u8FD8\u539F\u5220\u9664\u9879(&M) +CODE_TEMPLATE_PREFPAGE_REVERT=\u6062\u590D\u9ED8\u8BA4(&V) + +CODE_TEMPLATE_PREFPAGE_COLUMN_NAME=\u540D\u79F0 +CODE_TEMPLATE_PREFPAGE_COLUMN_DESCRIPTION=\u63CF\u8FF0 + +CODE_TEMPLATE_PREFPAGE_MATCH_CASE=\u533A\u5206\u5927\u5C0F\u5199(&H) + +CODE_TEMPLATE_PREFPAGE_PREVIEW=\u9884\u89C8(&W)\uFF1A + +CODE_TEMPLATE_PREFPAGE_ERROR_READ_TITLE=\u6B63\u5728\u8BFB\u53D6\u6A21\u677F +CODE_TEMPLATE_PREFPAGE_ERROR_READ_MESSAGE= \u6A21\u677F\u8BFB\u53D6\u5931\u8D25\u3002 +CODE_TEMPLATE_PREFPAGE_ERROR_WRITE_TITLE=\u6B63\u5728\u5199\u5165\u6A21\u677F +CODE_TEMPLATE_PREFPAGE_ERROR_WRITE_MESSAGE= \u6A21\u677F\u5199\u5165\u5931\u8D25\u3002 +FAILED_TO_WRITE_TO_EXCEL= \u5199\u5165\u6587\u4EF6\u5931\u8D25\u3002 + +# Template Dialog +CODE_TEMPLATE_DIALOG_TITLE_NEW=\u65B0\u6A21\u677F +CODE_TEMPLATE_DIALOG_TITLE_EDIT=\u7F16\u8F91\u6A21\u677F + +CODE_TEMPLATE_DIALOG_NAME=\u540D\u79F0(&N) +CODE_TEMPLATE_DIALOG_DESCRIPTION=\u8BF4\u660E(&D)\uFF1A +CODE_TEMPLATE_DIALOG_PATTERN=\u6A21\u5F0F(&P) +CODE_TEMPLATE_DIALOG_MANDATORY_MARK=* +CODE_TEMPLATE_DIALOG_COLON=\uFF1A +CODE_TEMPLATE_DIALOG_MAX_CHAR=[{0}/{1}] + +CODE_TEMPLATE_DIALOG_NAME_RESTRICTION_MSG=\uFF08\u4E0D\u652F\u6301\u7A7A\u683C\uFF09 + +CODE_TEMPLATE_DIALOG_UNDO=\u64A4\u9500(&U) +CODE_TEMPLATE_DIALOG_REDO=\u91CD\u505A(&R) +CODE_TEMPLATE_DIALOG_CUT=\u526A\u5207(&T) +CODE_TEMPLATE_DIALOG_COPY=\u590D\u5236(&C) +CODE_TEMPLATE_DIALOG_PASTE=\u7C98\u8D34(&P) +CODE_TEMPLATE_DIALOG_SELECT_ALL=\u5168\u9009(&A) + +CODE_TEMPLATE_DUPLICATE_ID=Duplicate template id. +CODE_TEMPLATE_ILLEGAL_BOOLEAN_ATTR=Illegal boolean attribute, must be "true" or "false". +CODE_TEMPLATE_JSONEXCEPTION=Json parsing failed. Invalid json data. +CODE_TEMPLATE_MISSING_REQUIRED_ATTR=Missing required attribute. + +CODE_TEMPLATE_PREFPAGE_UNSAVEDCHANGED_TITLE=\u66F4\u65B0\u6A21\u677F\u8BBE\u7F6E +PREFERENCE_CHANGE_NOT_APPLIED_MESSAGE=\u6709\u672A\u4FDD\u5B58\u7684\u66F4\u6539\u3002\u786E\u8BA4\u8981\u5E94\u7528\u66F4\u6539\u5417\uFF1F +#Templates Preference Page Ends + +DB_CONN_SERVER_DOMAIN_NAME_ERROR=\u8FDE\u63A5\u5931\u8D25\u3002 +DB_CONN_DOMAIN_NAME_ERROR=\u8BF7\u68C0\u67E5\u201C\u4E00\u822C\u201D\u9875\u7B7E\u4E2D\u8F93\u5165\u7684\u8BE6\u7EC6\u4FE1\u606F\u5E76\u91CD\u8BD5\u3002.\ + \n\u5EFA\u8BAE\uFF08\u8BF7\u5C1D\u8BD5\u4E0B\u5217\u65B9\u6CD5\u4E4B\u4E00\uFF09\uFF1A\ + \n1\uFF09\u57DF\u540D\u987B\u4EE5\u5B57\u6BCD\u5F00\u5934\u3002\ + \n2\uFF09\u57DF\u540D\u4E2D\u5141\u8BB8\u4F7F\u7528\u82F1\u6587\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u8FDE\u5B57\u7B26\uFF08-\uFF09\u548C\u82F1\u6587\u53E5\u70B9\uFF08.\uFF09\u3002\u8BF7\u52FF\u4F7F\u7528\u5176\u4ED6\u7279\u6B8A\u5B57\u7B26\u3002\ + \n3\uFF09\u8BF7\u52FF\u4F7F\u7528\u7A7A\u683C/\u5236\u8868\u7B26\u3002\ + \n4\uFF09\u6709\u6548\u7684\u57DF\u540D\u6700\u591A\u53EF\u5305\u542B253\u4E2A\u5B57\u7B26\uFF08\u5305\u62EC\u82F1\u6587\u53E5\u70B9\uFF09\u3002\ + +CONN_PROP_SERVER_IP= \u6570\u636E\u5E93IP +SERVERIP_TOOLTIP=\u6570\u636E\u5E93IP\uFF1A {0} +SERVERIP_TOOLTIP_FAIL=\u672A\u77E5 +SERVERVERSION_TOOLTIP=\u6570\u636E\u5E93\u7248\u672C\uFF1A{0} + +EXECUTION_FAILURE_LINE_NUMEBR=\u884C\u53F7\uFF1A +BUTTON_LABEL_SHOW_DETAILS=\u8BE6\u7EC6\u4FE1\u606F>> +BUTTON_LABEL_HIDE_DETAILS=\u8BE6\u7EC6\u4FE1\u606F<< +EXECUTION_FAILURE_DETAILS_DESCRIPTION=\u5355\u51FB\u201C\u8BE6\u7EC6\u4FE1\u606F\u201D\u4E86\u89E3\u8BE6\u60C5\u3002 + +EXEC_PLAN_COST_TOOLTIP = \u6267\u884C\u8BA1\u5212\u548C\u5F00\u9500 +VIS_EXPLAIN_EXEC_PLAN_COLUMN_ENTITYNAME = \u5B9E\u4F53\u540D\u79F0 +VIS_EXPLAIN_EXEC_PLAN_COLUMN_COST = \u5F00\u9500 +VIS_EXPLAIN_EXEC_PLAN_COLUMN_ROWS = \u884C +VIS_EXPLAIN_EXEC_PLAN_COLUMN_LOOPS = \u5FAA\u73AF +VIS_EXPLAIN_EXEC_PLAN_COLUMN_WIDTH = \u5BBD\u5EA6 +VIS_EXPLAIN_EXEC_PLAN_COLUMN_ACTUAL_ROWS = \u5B9E\u9645\u884C\u6570 +VIS_EXPLAIN_EXEC_PLAN_COLUMN_ACTUAL_TIME = \u5B9E\u9645\u65F6\u95F4 +VIS_EXPLAIN_PROPERTIES_EXEC_PLAN_TITLE = \u6267\u884C\u8BA1\u5212 + +DOMAINNAME_REDIRECT_FAILURE = {0}\u8BF7\u5C1D\u8BD5\u91CD\u65B0\u8FDE\u63A5\u3002 +#Batch Delete Messages +DROP_OBJECTS_WINDOW_TITLE=\u5220\u9664\u5BF9\u8C61 - {0} ({1}) +DROP_OBJECTS_WINDOW_SHORTTITLE=\u5220\u9664\u5BF9\u8C61 ({1}) + +DROP_OBJECTS_NATTABLE_COLUMN_ERR_MSG=\u9519\u8BEF\u6D88\u606F +DROP_OBJECTS_NATTABLE_COLUMN_NAME=\u540D\u79F0 +DROP_OBJECTS_NATTABLE_COLUMN_QUERY=\u67E5\u8BE2 +DROP_OBJECTS_NATTABLE_COLUMN_STATUS=\u72B6\u6001 +DROP_OBJECTS_NATTABLE_COLUMN_TYPE=\u7C7B\u578B + +DROP_OBJECTS_OPER_ATOMIC=\u539F\u5B50 +DROP_OBJECTS_OPER_CASCADE=\u7EA7\u8054 +DROP_OBJECTS_OPER_START=\u5F00\u59CB +DROP_OBJECTS_OPER_STOP=\u505C\u6B62 + +DROP_OBJECTS_OPER_DB_NAME=\u540D\u79F0\uFF1A +DROP_OBJECTS_OPER_LBL_RUNS=\u8FD0\u884C\uFF1A +DROP_OBJECTS_OPER_LBL_ERRORS=\u9519\u8BEF\uFF1A + +DROP_OBJECTS_OPER_STATUS_COMPLETED=\u5DF2\u5B8C\u6210 +DROP_OBJECTS_OPER_STATUS_ERROR=\u9519\u8BEF +DROP_OBJECTS_OPER_STATUS_INPROGRESS=\u8FDB\u884C\u4E2D +DROP_OBJECTS_OPER_STATUS_TOSTART=\u672A\u5F00\u59CB + +DROP_OBJECTS_NOT_ALLOWED_DIALOG_TITLE=\u5220\u9664\u5BF9\u8C61 +DROP_OBJECTS_NOT_ALLOWED_DIALOG_MESSAGE=\u4EC5\u80FD\u5220\u9664\u540C\u4E00\u6570\u636E\u5E93\u4E2D\u7684\u6570\u636E\u3002 +DROP_OBJECTS_NOT_ALLOWED_NO_DB_DIALOG_MESSAGE=\u4E0D\u5141\u8BB8\u5220\u9664\u5BF9\u8C61\u7EC4\u3002 +DROP_OBJECTS_NOT_ALLOWED_OBJECT_DIALOG_MESSAGE=\u5220\u9664\u5BF9\u8C61\u5931\u8D25\u3002\u6709\u5173\u8BE6\u60C5\uFF0C\u8BF7\u5355\u51FB\u201C\u8BE6\u7EC6\u4FE1\u606F\u201D\u3002 +DROP_OBJECTS_NOT_ALLOWED_OBJECT_DIALOG_OBJ_LIST=\u4EE5\u4E0B\u5BF9\u8C61\u65E0\u6CD5\u5220\u9664\uFF1A\n\u8FDE\u63A5\n\u6570\u636E\u5E93\n\u8868\u7A7A\u95F4\n\u5916\u8868 + +DROP_OBJECTS_OPER_STOP_DIALOG_TITLE=\u5220\u9664\u5BF9\u8C61 +DROP_OBJECTS_OPER_STOP_DIALOG_MESSAGE=\u6B63\u5728\u5220\u9664\u5BF9\u8C61\u3002\u786E\u8BA4\u8981\u505C\u6B62\u64CD\u4F5C\u5417\uFF1F + +DROP_OBJECTS_JOB_NAME=\u6B63\u5728\u5220\u9664\u5BF9\u8C61\uFF1A{0} +DROP_OBJECTS_JOB_FINISHED_STATUS=\u4ECE {0} \u4E2D\u5220\u9664\u5BF9\u8C61 +DROP_OBJECTS_JOB_FAILURE_STATUS=\u4ECE\u5982\u4E0B\u4F4D\u7F6E\u5220\u9664\u5BF9\u8C61\u65F6\u51FA\u9519\uFF1A{0} +DROP_OBJECTS_JOB_STOPPED_STATUS=\u5DF2\u505C\u6B62\u4ECE\u5982\u4E0B\u6570\u636E\u5E93\u5220\u9664\u5BF9\u8C61\uFF1A{0} +ERR_COLUMN_NAME_EMPTY = \u5217\u540D\u4E0D\u80FD\u4E3A\u7A7A\u3002 +ERR_CONSTRAINT_NAME_EMPTY =\u7EA6\u675F\u540D\u4E0D\u5F97\u4E3A\u7A7A\u3002 +PROPERTIES_ERROR_MESSAGE={0} \u5DF2\u88AB\u4FEE\u6539/\u5220\u9664\u3002\u8BF7\u53D6\u6D88\u66F4\u6539\u5E76\u5237\u65B0\uFF0C\u7136\u540E\u91CD\u8BD5\u3002 +PROPERTIES_ERROR_MESSAGE_FOR_CONSTRAINT=\u7EA6\u675F\u540D\u79F0\u5DF2\u88AB\u4FEE\u6539\u3002\u8BF7\u53D6\u6D88\u66F4\u6539\u5E76\u5237\u65B0\uFF0C\u7136\u540E\u91CD\u8BD5\u3002 +TABLE_PROPERTIES_INVALID_BOOLEAN_DATATYPE=\u7C98\u8D34\u7684\u6761\u76EE\u4E0E\u5E03\u5C14\u503C\u7684\u683C\u5F0F\u4E0D\u5339\u914D\u3002 +PROPERTIES_COMPLEX_DATATYPE_ERROR_MSG={0}\u5DF2\u88AB\u4FEE\u6539/\u5220\u9664\u3002\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5\u3002 +PREFERENCE_SHORTCUT_KEY_BINDING_TOGGLE_LINE_COMMENTS=\u884C\u6CE8\u91CA/\u53D6\u6D88\u884C\u6CE8\u91CA +KEY_BINDING_TOGGLE_LINE_COMMENTS_DESC=\u6CE8\u91CA/\u53D6\u6D88\u6CE8\u91CASQL\u7EC8\u7AEF\u548C\u5B58\u50A8\u8FC7\u7A0B/\u51FD\u6570\u7EC8\u7AEF\u4E2D\u7684\u884C +PREFERENCE_SHORTCUT_KEY_BINDING_TOGGLE_BLOCK_COMMENTS=\u5757\u6CE8\u91CA/\u53D6\u6D88\u5757\u6CE8\u91CA +KEY_BINDING_TOGGLE_BLOCK_COMMENTS_DESC=\u6CE8\u91CA/\u53D6\u6D88\u6CE8\u91CASQL\u7EC8\u7AEF\u548C\u5B58\u50A8\u8FC7\u7A0B/\u51FD\u6570\u7EC8\u7AEF\u4E2D\u7684\u6574\u6BB5\u5185\u5BB9 +OBJECT_NAME_MORE_THAN_LIMIT_ERROR_MESSAGE= \u8868\u3001\u5217\u3001\u7EA6\u675F\u548C\u7D22\u5F15\u540D\u79F0\u6700\u591A\u53EF\u5305\u542B64\u4E2A\u5B57\u7B26\u3002 +MAX_CHARATCTERS_ALLOWED_FOR_TABLE_DESC=\u8868\u63CF\u8FF0\u6700\u591A\u53EF\u5305\u542B5000\u4E2A\u5B57\u7B26\u3002 + +#debug +PREFERENCE_SHORTCUT_KEY_BINDING_START_DEBUG=\u542f\u52a8\u8c03\u8bd5 +PREFERENCE_SHORTCUT_KEY_BINDING_TERNIMATE_DEBUG=\u505c\u6b62\u8c03\u8bd5 +PREFERENCE_SHORTCUT_KEY_BINDING_STEPIN_DEBUG=\u6b65\u5165 +PREFERENCE_SHORTCUT_KEY_BINDING_STEPOUT_DEBUG=\u6b65\u51fa +PREFERENCE_SHORTCUT_KEY_BINDING_STEPOVER_DEBUG=\u6b65\u8fdb +PREFERENCE_SHORTCUT_KEY_BINDING_CONTINUE_DEBUG=\u7ee7\u7eed +KEY_BINDING_COMMENTS_DESC_START_DEBUG = \u542f\u52a8\u8c03\u8bd5 +KEY_BINDING_COMMENTS_DESC_TERNIMATE_DEBUG =\u505c\u6b62\u8c03\u8bd5 +KEY_BINDING_COMMENTS_DESC_STEPIN_DEBUG =\u6b65\u5165 +KEY_BINDING_COMMENTS_DESC_STEPOUT_DEBUG = \u6b65\u51fa +KEY_BINDING_COMMENTS_DESC_STEPOVER_DEBUG =\u6b65\u8fdb +KEY_BINDING_COMMENTS_DESC_CONTINUE_DEBUG =\u7ee7\u7eed + +#PreservSQL Messages +PRESERVESQL_STARTUP_DIALOG_MESSAGE=\u6B63\u5728\u52A0\u8F7D\u81EA\u52A8\u4FDD\u5B58\u7684\u67E5\u8BE2\u3001\u51FD\u6570\u548C\u8FC7\u7A0B\u2026 +PRESERVESQL_STARTUP_JOB_NAME=\u6B63\u5728\u52A0\u8F7DSQL\u7EC8\u7AEF\u2026 +PRESERVESQL_STARTUP_LAZY_JOB_NAME=\u6B63\u5728\u540E\u53F0\u52A0\u8F7DSQL\u7EC8\u7AEF\u2026 +PRESERVESQL_STARTUP_LOADING_FAILED=\u7EC8\u7AEF\u6570\u636E\u52A0\u8F7D\u5931\u8D25\u3002 +PRESERVESQL_STARTUP_LOADING_FINISHED=\u7EC8\u7AEF\u6570\u636E\u52A0\u8F7D\u5B8C\u6210\u3002 +PRESERVESQL_STARTUP_MAX_TAB_REACHED=\u9875\u7B7E\u6570\u91CF\u5DF2\u8FBE\u5230\u4E0A\u9650\uFF0C\u65E0\u6CD5\u52A0\u8F7D\u66F4\u591A\u9875\u7B7E\u3002 + +PRESERVE_SQL_GRACEFUL_EXIT_MSG=\u6B63\u5728\u4FDD\u5B58\u66F4\u6539\u2026 +PRESERVESQL_PERIODIC_JOB_NAME=\u5B9A\u671F\u81EA\u52A8\u4FDD\u5B58\u4F5C\u4E1A\u2026 +PRESERVESQL_JSONEXCEPTION=JSON\u89E3\u6790\u5931\u8D25\u3002JSON\u6570\u636E\u65E0\u6548\u3002 +PRESERVESQL_FOLDERCREATEDELETEEXCEPTION=Folder create/delete failed. +PRESERVESQL_FILEREADEXCEPTION=\u6587\u4EF6\u8BFB\u53D6\u5931\u8D25\u3002 +PRESERVESQL_FILEENCODINGEXCEPTION=\u6587\u4EF6\u6570\u636E\u7F16\u7801\u5931\u8D25\u3002 +PREFERENCE_AUTOSAVE=\u81EA\u52A8\u4FDD\u5B58 +PREFERENCE_ENABLE_AUTOSAVE=\u81EA\u52A8\u4FDD\u5B58 +PREFERENCE_INTERVAL_AUTOSAVE=\u65F6\u95F4\u95F4\u9694 +PREFERENCE_INTERVAL_AUTOSAVE_RANGE=\u5206\u949F\uFF08\u8303\u56F4\uFF1A{0}-{1}\uFF1B\u9ED8\u8BA4\u503C\uFF1A{2}\uFF09 +PREFERENCE_ENABLE_ENCRYPTION=\u52A0\u5BC6 +PREFERENCE_INTERVAL_ERROR_MSG=\u65E0\u6548\u7684\u65F6\u95F4\u95F4\u9694\u3002\u6709\u6548\u8303\u56F4\u4E3A{0}-{1}\u3002 +SESSIONSETTINGS_PREFPAGE_UNSAVEDCHANGED_TITLE=\u66F4\u65B0\u4F1A\u8BDD\u8BBE\u7F6E +PRESERVESQL_PERIODIC_SAVE_FINISHED=\u81EA\u52A8\u4FDD\u5B58\u5B8C\u6210\uFF1A{0} +PRESERVESQL_PERIODIC_SAVE_TAB_STATUS=\u81EA\u52A8\u4FDD\u5B58\u5B8C\u6210\uFF1A{0} +PRESERVESQL_FILEWRITEEXCEPTION=\u6587\u4EF6\u5199\u5165\u5931\u8D25\u3002 +PREFERENCE_AUTOSAVE_DESC=\u6839\u636E\u201C\u65F6\u95F4\u95F4\u9694\u201D\u5B57\u6BB5\u4E2D\u5B9A\u4E49\u7684\u503C\uFF0C\u5B9A\u671F\u81EA\u52A8\u4FDD\u5B58SQL\u7EC8\u7AEF\u548C\u5B58\u50A8\u8FC7\u7A0B/\u51FD\u6570\u7EC8\u7AEF\u4E2D\u7684\u6570\u636E\u3002 +PREFERENCE_INTERVAL_DESC=\u8BBE\u7F6E\u81EA\u52A8\u4FDD\u5B58\u64CD\u4F5C\u7684\u65F6\u95F4\u95F4\u9694\u3002 +PREFERENCE_ENCRYPTION_DESC=\u5C06\u5DF2\u4FDD\u5B58\u6570\u636E\u52A0\u5BC6\u4E3A\u81EA\u52A8\u4FDD\u5B58\u7ED3\u679C\u3002 +MAX_CHARATCTERS_ALLOWED_FOR_TABLE_DESC=Maximum 5000 characters allowed for table description. +# TRANSLATION FOR ENCODING ENCODING STARTS + +ENCODING_QUERY_RESULT_DATA_ENCODING_HEADER=\u7ED3\u679C\u6570\u636E\u7F16\u7801 +ENCODING_QUERY_RESULT_DATA_ENCODING_BODY=\u5305\u542B\u7ED3\u679C\u6570\u636E\u7F16\u7801 +ENCODING_QUERY_RESULT_DATA_ENCODING_DESC=\u7ED3\u679C\u6570\u636E\u7F16\u7801\u9009\u9879\u5C06\u5728\u7F16\u8F91\u8868\u3001\u67E5\u770B\u8868\u548C\u67E5\u8BE2\u7ED3\u679C\u65F6\u53EF\u7528\u3002 +# TRANSLATION FOR ENCODING ENCODING ENDS +BUILD_TIME=\u6784\u5EFA\u65F6\u95F4 + +TEXTMODE_QUERY_RESULT_DATA_TEXTMODE_HEADER=\u7ED3\u679C\u6570\u636E\u6587\u672C\u6A21\u5F0F +TEXTMODE_QUERY_RESULT_DATA_TEXTMODE_BODY=\u5305\u542B\u7ED3\u679C\u6570\u636E\u6587\u672C\u6A21\u5F0F +TEXTMODE_QUERY_RESULT_DATA_TEXTMODE_DESC=\u7ED3\u679C\u6570\u636E\u6587\u672C\u6A21\u5F0F\u5C06\u5728\u67E5\u8BE2\u7ED3\u679C\u65F6\u53EF\u7528\uFF08\u6700\u5927\u652F\u6301{0}\u4E2A\u5B57\u7B26\uFF09\u3002 + +#TRANSLATION FOR INDENT AND UNINDENT + +PREF_FORMATTER_SETTING=\u683C\u5F0F\u5316 +FORMATTER_NODE= \u683C\u5F0F\u5316 + +FORMATTER_PREFPAGE_UNSAVEDCHANGED_TITLE= \u66F4\u65B0\u683C\u5F0F\u5316\u8BBE\u7F6E +BUILD_TIME_UNKNOWN=\u672A\u77E5 +EXPORT_FAIL_PROCESS_INTRUPTED_WITHOUT_SERVER_MSG=\u5BFC\u51FA/\u663E\u793ADDL\u6267\u884C\u8FC7\u7A0B\u5931\u8D25\u3002 +EXPORT_FAIL_PROCESS_TITLE=\u663E\u793ADDL\u9519\u8BEF + +#TRANSLATION FOR FUNCTION CHANGE INTIMATION +FUNCTN_CHANGE_TITLE=\u51FD\u6570/\u8FC7\u7A0B\u5DF2\u4FEE\u6539 +FUNCTN_CHANGE_MSG=\u6E90\u4EE3\u7801\u5DF2\u5728\u670D\u52A1\u5668\u4E2D\u66F4\u6539\u3002\u60A8\u53EF\u4EE5\u5355\u51FB\u201C\u5237\u65B0\u201D\u540C\u6B65\u670D\u52A1\u5668\u4E0A\u7684\u66F4\u6539\uFF0C\u6216\u5355\u51FB\u201C\u8986\u76D6\u201D\u5C06\u5F53\u524D\u66F4\u6539\u4FDD\u5B58\u5230\u670D\u52A1\u5668\u3002 +FUNCTN_CHANGE_REFRESH=\u5237\u65B0(&R) +FUNCTN_CHANGE_OVERWRITE=\u8986\u76D6(&O) +FUNCTN_CHANGE_CANCEL=\u53D6\u6D88(&C) +FUNCTN_CHANGE_VIEWSOURCE_MSG=\u6E90\u4EE3\u7801\u5DF2\u5728\u670D\u52A1\u5668\u4E2D\u66F4\u6539\u3002\u662F\u5426\u8981\u6839\u636E\u670D\u52A1\u5668\u66F4\u6539\u5237\u65B0\u6E90\u4EE3\u7801\uFF1F +FUNCTN_CHANGE_PREVIEW=\u670D\u52A1\u5668\u4EE3\u7801\u9884\u89C8(&W) +FUNCT_CHANGE_VIEWSOURCE_ERR=\u83B7\u53D6\u6E90\u4EE3\u7801\u65F6\u53D1\u751F\u9519\u8BEF\u3002\u8BF7\u5237\u65B0\u5BF9\u8C61\u6D4F\u89C8\u5668\u5E76\u91CD\u8BD5\u3002\n\u670D\u52A1\u5668\u6D88\u606F\uFF1A +FUNCT_CHANGE_COMPILE_ERR=\u7F16\u8BD1\u51FD\u6570/\u8FC7\u7A0B\u65F6\u53D1\u751F\u9519\u8BEF\u3002\n\u670D\u52A1\u5668\u6D88\u606F\uFF1A{0}\n{1} +FUNCT_CHANGE_EXECUTE_ERR=\u6267\u884C\u51FD\u6570/\u8FC7\u7A0B\u65F6\u53D1\u751F\u9519\u8BEF\u3002\u8BF7\u5237\u65B0\u5BF9\u8C61\u6D4F\u89C8\u5668\u5E76\u91CD\u8BD5\u3002\n\u670D\u52A1\u5668\u6D88\u606F\uFF1A +FUNCT_CHANGE_ERR_COMPILE_BACKEND=\u51FD\u6570/\u8FC7\u7A0B\u5DF2\u88AB\u5220\u9664\u3002\u8981\u91CD\u65B0\u521B\u5EFA\u5E76\u8FDB\u884C\u7F16\u8BD1\u5417\uFF1F + +#TRANSLATIONS FOR TEMP TABLE SUPPORT +SQL_TERMINAL_REUSE_CONNECTION_TOOLTIP = \u91CD\u7528\u8FDE\u63A5\uFF1A\u542F\u7528\n\u7528\u6237\u5728\u6B64\u7EC8\u7AEF\u8FDB\u884C\u64CD\u4F5C\uFF08\u5237\u65B0\u7ED3\u679C\u96C6\u3001\u5BFC\u51FA\u6570\u636E\u3001\u63D0\u4EA4\u66F4\u6539\u7B49\uFF09\u65F6\uFF0C\u91CD\u7528SQL\u7EC8\u7AEF\u4E2D\u7684\u6570\u636E\u5E93\u8FDE\u63A5\u3002 +SQL_TERMINAL_NEW_CONNECTION_TOOLTIP = \u91cd\u7528\u4f7f\u7528\u8fde\u63a5\uff1a\u5173\u95ed\u000d\u000a\u7528\u6237\u5728\u6b64\u7ec8\u7aef\u8fdb\u884c\u64cd\u4f5c\uff08\u5237\u65b0\u7ed3\u679c\u96c6\u3001\u5bfc\u51fa\u6570\u636e\u3001\u63d0\u4ea4\u66f4\u6539\u7b49\uff09\u65f6\uff0c\u521b\u5efa\u5e76\u4f7f\u7528\u65b0\u7684\u6570\u636e\u5e93\u8fde\u63a5\u3002 +MPPDBIDE_DIA_BTN_RECONNECT=\u91CD\u65B0\u8FDE\u63A5 +MPPDBIDE_DIA_BTN_RECONNECT_CONTINUE=\u91CD\u65B0\u8FDE\u63A5\u5E76\u6267\u884C +MULTIPLE_CONNECTION_ATTEMPT_ON_CRITICAL_ERROR=\u7531\u4E8E\u591A\u6B21\u5C1D\u8BD5\u540E\u4ECD\u65E0\u6CD5\u5EFA\u7ACB\u8FDE\u63A5\uFF0C\u5BF9\u8C61\u6D4F\u89C8\u5668\u5DF2\u4E0E\u6570\u636E\u5E93\u65AD\u8FDE\u3002\u8BF7\u91CD\u65B0\u8FDE\u63A5\u5E76\u91CD\u8BD5\u3002 +CONNECTION_ATTEMPT_ON_CRITICAL_ERROR=\u6267\u884C\u671F\u95F4\u53D1\u751F\u9519\u8BEF\u3002\n\u8BF4\u660E\uFF1A\n\t\u91CD\u65B0\u8FDE\u63A5\uFF1A\u91CD\u65B0\u5EFA\u7ACB\u8FDE\u63A5\u3002\n\t\u91CD\u65B0\u8FDE\u63A5\u5E76\u6267\u884C\uFF1A\u91CD\u65B0\u5EFA\u7ACB\u8FDE\u63A5\u5E76\u6267\u884C\u3002\n\t\u53D6\u6D88\uFF1A\u5728\u5BF9\u8C61\u6D4F\u89C8\u5668\u4E2D\u65AD\u5F00\u6570\u636E\u5E93\u8FDE\u63A5\u3002 +RECONNECT_FOR_EXECUTION_PLAN_VISUAL_EXPLAIN=\u6267\u884C\u671F\u95F4\u53D1\u751F\u9519\u8BEF\u3002\u662F\u5426\u91CD\u65B0\u5EFA\u7ACB\u8FDE\u63A5\uFF1F\n\u8BF4\u660E\uFF1A\n\t\u662F\uFF1A\u91CD\u65B0\u5EFA\u7ACB\u8FDE\u63A5\u5E76\u6267\u884C\u3002\n\t\u5426\uFF1A\u5728\u5BF9\u8C61\u6D4F\u89C8\u5668\u4E2D\u65AD\u5F00\u6570\u636E\u5E93\u8FDE\u63A5\u3002 +PROPERTIES_CONSTRAINT_CONSTRAINTNAME=\u5217\u540D\u79F0 +PROPERTIES_CONSTRAINT_COLUMNS=\u7EA6\u675F\u5217 +PROPERTIES_CONSTRAINT_TYPE=\u7EA6\u675F\u7C7B\u578B +PROPERTIES_EXPRESSION=\u8868\u8FBE\u5F0F +PROPERTIES_CONSTRAINT_ISDEFFERED=\u80FD\u5426\u5EF6\u8FDF +PROPERTIES_CONSTRAINT_SCHEMA=\u6A21\u5F0F +PROPERTIES_TABLESPACE=\u8868\u7A7A\u95F4 +PROPERTIES_COLUMNS_COLUMNSNAME=\u5217\u540D\u79F0 +PROPERTIES_COLUMNS_DATATYPE=\u6570\u636E\u7C7B\u578B +PROPERTIES_COLUMNS_ISNULLABLE=\u80FD\u5426\u4E3ANULL +PROPERTIES_COLUMNS_COMMENTS=\u5907\u6CE8 +PROPERTIES_INDEX_INDEXNAME=\u7D22\u5F15\u540D\u79F0 +PROPERTIES_INDEX_INDEXCOLUMNS=\u7D22\u5F15\u5217 +PROPERTIES_INDEX_ISUNIQUE=\u662F\u5426\u552F\u4E00 +PROPERTIES_PARTITION_PARTITIONNAME=\u5206\u533A\u540D\u79F0 +PROPERTIES_PARTITION_PARTITIONBOUNDARIES= \u5206\u533A\u8FB9\u754C + +#Translations for Windows 10 Issue +CREATE_FILE_FAIL_ERR = \u6587\u4EF6\u521B\u5EFA\u5931\u8D25\u3002 +CREATE_FOLDER_FAIL_ERR = \u6587\u4EF6\u5939\u521B\u5EFA\u5931\u8D25\u3002 +RECONNECT_SUCCESSFUL_MSG=\u91CD\u5EFA\u8FDE\u63A5\u6210\u529F\u2026 +RECONNECT_ATTEMP_FAILURE_MSG=\u8FDE\u63A5\u5931\u8D25\u3002\u8BF7\u5355\u51FB\u201C\u786E\u8BA4\u201D\u91CD\u5EFA\u8FDE\u63A5\u3002 + +# Edit Query Results +RESULTSET_EDITABLE_MSG = \u53EF\u4EE5\u7F16\u8F91\u67E5\u8BE2\u7ED3\u679C\u3002 +RESULTSET_NON_EDITABLE_MSG = \u65E0\u6CD5\u7F16\u8F91\u67E5\u8BE2\u7ED3\u679C\u3002 +RESULTSET_ALL_DATALOAD_MSG = \u65E0\u6CD5\u7F16\u8F91\u67E5\u8BE2\u7ED3\u679C\uFF08\u6587\u672C\u6570\u636E\u5DF2\u8FBE\u4E0A\u9650\uFF0C\u52A0\u8F7D\u6570\u636E{0}\u884C\uFF09\u3002 +#TRANSALATION FOR DB TYPES +LBL_DBTYPE =\u6570\u636E\u5E93\u7C7B\u578B + +OPEN_GAUSS = openGauss + +#Export Excel +ERROR_EXPORT_EXCEL_RESULTSET = \u63D0\u53D6\u7ED3\u679C\u96C6\u5931\u8D25\u3002 +ERROR_EXPORT_EXCEL_PARSER = \u89E3\u6790\u65E5\u671F\u6570\u636E\u7C7B\u578B\u5931\u8D25\u3002\u6B63\u5728\u8F6C\u6362\u4E3A\u9ED8\u8BA4\u5B57\u7B26\u4E32\u6570\u636E\u7C7B\u578B\u3002 +ERR_EXPORT_TABLE_FAIL = \u4ECE\u8868\u4E2D\u5BFC\u51FA\u6570\u636E\u65F6\u51FA\u9519\uFF1A{0}.{1} +ERR_EXPORT_EXCEL_OPERATION = \u5BFC\u51FA\u5F53\u524D\u9875\u65F6\u51FA\u9519\u3002{0}\u9519\u8BEF\uFF1A{1} + +ERROR_EXCEL_ROW_COLUMN_LIMIT = \u5BFC\u51FA\u5230Excel\u5931\u8D25\u3002\n\u6CE8\u610F\uFF1A\n\u5355\u4E2Axlsx\u6587\u4EF6\u6700\u591A\u652F\u6301100\u4E07\u884C\u548C16384\u5217\u3002\n\u5355\u4E2Axls\u6587\u4EF6\u6700\u591A\u652F\u63016.4\u4E07\u884C\u548C256\u5217\u3002 +EXPORT_INFORMATION = \u5BFC\u51FA\u89E3\u6790\u5668\u5931\u8D25\u4FE1\u606F + +EXPORT_INFORMATION = Export Parser Failure Info + +#menu in ResultSet +COPY_TO_EXCEL_RESULT_WINDOW_MENU = \u590D\u5236\u5230excel +COPY_TO_EXCEL_XLS_RESULT_WINDOW_MENUITEM = \u590D\u5236\u4E3Axls.. +COPY_TO_EXCEL_XLSX_RESULT_WINDOW_MENUITEM = \u590D\u5236\u4E3Axlsx.. +SEARCH_RESULT_WINDOW_CONTENTS = \u641C\u7D22 +SET_NULL_RESULT_WINDOW_CONTENTS = \u5C06\u5355\u5143\u683C\u7F6E\u7A7A +RIGHT_CLICK_COPY_ADVANCED_RESULT_WINDOW_CONTENTS = \u9AD8\u7EA7\u590D\u5236 +RIGHT_CLICK_COPY_RESULT_WINDOW_CONTENTS = \u590D\u5236 +RIGHT_CLICK_COPY_TO_CLIPBOARD_RESULT_WINDOW_CONTENTS = \u590D\u5236\u6570\u636E +RIGHT_CLICK_EXPORT_RESULT_WINDOW_CONTENTS = \u5BFC\u51FA +RIGHT_CLICK_EXPORT_ALL_DATA_RESULT_WINDOW_CONTENTS = \u6240\u6709\u9875 +RIGHT_CLICK_EXPORT_CURRENT_PAGE_DATA_RESULT_WINDOW_CONTENTS = \u5F53\u524D\u9875 +COPY_TO_EXCEL_RESULT_FILE_NAME = tmp +ERR_OPEN_IN_EXCEL_OPERATION = \u590D\u5236\u5230Excel\u65F6\u51FA\u9519.{0}\u9519\u8BEF:{1} +EXPORT_OPEN_IN_EXCEL_PROGRESS_NAME=\u590D\u5236\u5230excel: {0} +RIGHT_CLICK_GENERATE_INSERT_RESULT_WINDOW_CONTENTS = \u751F\u6210SQL +RIGHT_CLICK_SELECTED_ROW_INSERT_RESULT_WINDOW_CONTENTS = \u6309\u9009\u4E2D\u884C +RIGHT_CLICK_CURRENT_INSERT_RESULT_WINDOW_CONTENTS = \u5F53\u524D\u9875 +RIGHT_CLICK_ALL_DATA_INSERT_RESULT_WINDOW_CONTENTS = \u6240\u6709\u9875 +GENERATE_SQL_SUCCES_DAILOG_TITLE=\u751F\u6210SQL\u6210\u529F +GENERATE_INSERT_SQL = \u4ECE{0}\u9875\u751F\u6210insert\u6570\u636E +ERR_GENERATE_INSERT_SQL = \u751F\u6210SQL\u65F6\u51FA\u9519.\n\u9519\u8BEF : +ERR_GENERATE_INSERT_SQLL_OPERATION = \u751F\u6210sql\u65F6\u51FA\u9519.{0}\u9519\u8BEF:{1} + +DIRTY_GENERATE_INSERT_DIALOG_SAVE_FILE_ERROR = \u65E0\u6CD5\u4FDD\u5B58SQL "{0}". +GENERATE_INSERT_ERROR = \u751F\u6210SQL\u9519\u8BEF +ERR_UI_GENERATE_INSERT_ERROR =\u751F\u6210sql\u65F6\u51FA\u9519. +ERR_UI_SEARCH_ERROR=\u6587\u672C\u6A21\u5F0F\u6267\u884C\u641C\u7D22\u65F6\u51FA\u9519 +GENERATE_INSERT_ALL_RESULTDATA_PROGRESS_NAME = \u751F\u6210\u6240\u6709\u9875\u9762SQL: {0} +MSG_TOTAL_ROWS_EXPORT_INSERT_SQL = \u5BFC\u51FA\u7684\u603B\u8BB0\u5F55\u6570\uFF1A{0} + +#SQL Terminal right click menu related +SQL_TERMINAL_RIGHT_CLICK_MENU_ITEM_FORMAT = \u683C\u5F0F\u5316 + +VERSION_NO_INCOMPATIBLE=Version Number not compatible. + +#Execution Progress Bar in Terminal/Editor +EXECUTION_DYANMIC_TIME_LABEL = \u6B63\u5728\u8FD0\u884C\u4E2D - +EXECUTION_ELAPSED_TIME_LABEL = \u8FD0\u884C\u65F6\u95F4 : + +# User Role Management +USER_ROLE_GROUP_DISPLAY_NAME = \u7528\u6237/\u89D2\u8272 +GRANT_REVOKE_WIZARD = \u6388\u6743/\u64A4\u9500\u6743\u9650 +GRANT_REVOKE_WIZARD_OBJECT_SELECTION = \u9009\u62E9\u5BF9\u8C61 +GRANT_REVOKE_WIZARD_PRIVILEGE_SELECTION = \u9009\u62E9\u6743\u9650 +GRANT_REVOKE_WIZARD_SQL_PREVIEW = SQL\u9884\u89C8 + +USER_ROLE_TAB_COLUMN_TITLE_PROPERTY = \u5C5E\u6027 +USER_ROLE_TAB_COLUMN_TITLE_VALUE = \u503C + +USER_ROLE_NAME = \u540D\u79F0 + +USER_ROLE_CONNECT_LIMIT = \u8FDE\u63A5\u9650\u5236 +USER_ROLE_VALID_BEGIN = \u5F00\u59CB\u65E5\u671F +USER_ROLE_VALID_UNTIL = \u7ED3\u675F\u65E5\u671F +USER_ROLE_CREATE_ROLE = \u53EF\u521B\u5EFA\u89D2\u8272 +USER_ROLE_CREATE_DB = \u53EF\u521B\u5EFA\u6570\u636E\u5E93 +USER_ROLR_INHERIT = \u7EE7\u627F +USER_ROLE_REPLICATION = \u590D\u5236 +USER_ROLE_CAN_LOGIN = \u53EF\u767B\u5F55 +USER_ROLE_SYSTEM_ADMIN = \u7CFB\u7EDF\u7BA1\u7406\u5458 +USER_ROLE_RESOURCE_POOL = \u8D44\u6E90\u6C60 +USER_ROLE_COMMENT = \u63cf\u8ff0\uff08\u6700\u591a\u0034\u0030\u0030\u0030\u4e2a\u5b57\u7b26\uff09 +USER_ROLE_COMMENT_ERROR_MESSAGE=\u7528\u6237/\u89D2\u8272\u63CF\u8FF0\u6700\u591A\u53EF\u5305\u542B4000\u4E2A\u5B57\u7B26\u3002 +USER_ROLE_PROPERTY_TAB_GENERAL = \u901A\u7528 +USER_ROLE_PROPERTY_TAB_PRIVILEGE = \u6743\u9650 +USER_ROLE_PROPERTY_TAB_MEMBERSHIP = \u6210\u5458\u5C5E\u6027 +USER_ROLE_AUDITOR = \u5BA1\u8BA1\u5458 +USER_ROLE_IS_LOCK = \u5DF2\u9501\u5B9A +USER_ROLE_TAB_COLUMN_TITLE_USER_ROLE = \u7528\u6237/\u89D2\u8272 +USER_ROLE_TAB_COLUMN_TITLE_BELONG_TO = \u5C5E\u4E8E +USER_ROLE_TAB_COLUMN_TITLE_IS_ENABLE = \u542F\u7528 +ERR_USER_ROLE_IS_NOT_EXIST = OID\u4E3A\u201C{0}\u201D\u7684\u7528\u6237/\u89D2\u8272\u5DF2\u4E0D\u5B58\u5728\u3002 +ERR_FETCH_USER_ROLE_LOCK_STATUS = \u65E0\u6CD5\u83B7\u53D6\u7528\u6237/\u89D2\u8272(OID\u4E3A{0})\u7684\u5E10\u6237\u9501\u5B9A\u72B6\u6001\u3002 +ERR_USER_ROLE_ALTER_FAILURE = \u65E0\u6CD5\u66F4\u6539\u7528\u6237/\u89D2\u8272\u3002\u539F\u56E0\uFF1A\r\n{0} +ERR_USER_ROLE_BEGIN_DATE_NULL = \u5F00\u59CB\u65E5\u671F\u4E0D\u80FD\u4E3A\u7A7A +ERR_USER_ROLE_VALID_UNTIL_DATE_NULL = \u7ED3\u675F\u65E5\u671F\u4E0D\u80FD\u4E3A\u7A7A +USER_ROLE_PREVIEW_SQL_CONFIRM = \u66F4\u65B0\u7528\u6237/\u89D2\u8272\u5C5E\u6027 +GRANT_REVOKE_PLS_SELECT_OBJECT = \u8BF7\u9009\u62E9\u81F3\u5C11\u4E00\u4E2A\u5BF9\u8C61 +GRANT_REVOKE_PLS_SELECT_USER_ROLE = \u8BF7\u9009\u62E9\u81F3\u5C11\u4E00\u4E2A\u7528\u6237/\u89D2\u8272 +GRANT_REVOKE_PLS_SELECT_PRIVILEGE = \u8BF7\u9009\u62E9\u81F3\u5C11\u4E00\u4E2A\u6743\u9650 +UPDATE_OBJECT_PRIVILEGE_DIALOG_TITLE = \u6388\u6743/\u64A4\u9500\u6743\u9650 +ERR_UPDATE_OBJECT_PRIVILEGE_DETAIL = \u65E0\u6CD5\u6388\u4E88/\u64A4\u6D88\u5BF9\u8C61\u6743\u9650\u3002 +SUCCESS_UPDATE_OBJECT_PRIVILEGE_DETAIL = \u6210\u529F\u6388\u4E88/\u64A4\u6D88\u5BF9\u8C61\u6743\u9650\u3002 + +UPDATE_OBJECT_PRIVILEGE_DIALOG_DIFF_OBJECT_TYPE = \u6279\u91CF\u6388\u4E88/\u64A4\u6D88\u6743\u9650\u4EC5\u80FD\u5BF9\u540C\u4E00\u6A21\u5F0F\u4E2D\u7684\u540C\u7C7B\u578B\u5BF9\u8C61\u6267\u884C\u3002 +GRANT_REVOKE_SELECT_ALL_OBJECT = \u9009\u62E9\u6240\u6709\u5BF9\u8C61 +GRANT_REVOKE_SEARCH_OBJECT = \u6309\u5BF9\u8C61\u540D\u79F0\u641C\u7D22 +GRANT_REVOKE_ROLE = \u89D2\u8272 +GRANT_REVOKE_GRANT_OPTION = \u6388\u4E88 +GRANT_REVOKE_REVOKE_OPTION = \u64A4\u6D88 +USER_ROLE_PREVIEW_SQL_CHANGE_NOTHING = \u5F53\u524D\u65E0\u4EFB\u4F55\u4FEE\u6539\u3002 +STATUS_MSG_MODIFYING_OBJECT_PRIVILEGE = \u4FEE\u6539\u5BF9\u8C61\u6743\u9650... +ERR_USER_ROLE_CONNECT_LIMIT_INVALID = \u8FDE\u63A5\u9650\u5236\u4EC5\u5141\u8BB8\u4E3A\u6574\u6570. +USER_ROLE_PREVIEW_SQL_CONFIRM_MESSAGE = \u4EE5\u4E0BSQL\u5C06\u88AB\u7528\u4E8E\u4FEE\u6539\u7528\u6237/\u89D2\u8272\u5C5E\u6027\uFF0C\u8BF7\u6838\u5B9E\u3002 +SHOW_USER_ROLE_DDL_NO_DATABASE = \u5F53\u524D\u65E0\u8FDE\u63A5\u7684\u6570\u636E\u5E93\u3002 +SHOW_USER_ROLE_DDL_ERROR = \u65E0\u6CD5\u67E5\u770B\u7528\u6237/\u89D2\u8272\u5B9A\u4E49\u3002 +SHOW_USER_ROLE_DDL_JOB_NAME = \u6B63\u5728\u67E5\u770B\u7528\u6237/\u89D2\u8272DDL-{0} +ERR_USER_ROLE_NAME_EMPTY = \u7528\u6237/\u89D2\u8272\u540D\u5B57\u4E0D\u80FD\u4E3A\u7A7A\u3002 +CREATE_USER_ROLE_NO_DATABASE = \u5F53\u524D\u65E0\u8FDE\u63A5\u7684\u6570\u636E\u5E93\u3002 + +EXPORT_ALL_DATA_NOT_ENOUGH_SPACE = \u78C1\u76D8\u7A7A\u95F4\u4E0D\u8DB3 + +USER_ROLE_PREVIEW_SQL_CHANGE_NOTHING = \u6CA1\u6709\u8981\u4FDD\u5B58\u7684\u66F4\u6539\u3002STATUS_MSG_MODIFYING_OBJECT_PRIVILEGE = \u6B63\u5728\u4FEE\u6539\u5BF9\u8C61\u6743\u9650... +ERR_USER_ROLE_CONNECT_LIMIT_INVALID = \u201C\u8FDE\u63A5\u9650\u5236\u201D\u4E2D\u4EC5\u80FD\u8F93\u5165\u6574\u6570\u3002 +PARTIAL_SUCCESS_UPDATE_OBJECT_PRIVILEGE_DETAIL = \u5DF2\u6210\u529F\u6388\u4E88/\u64A4\u6D88\u5BF9\u8C61\u6743\u9650\u3002\u53EF\u5355\u51FB\u201C\u8BE6\u7EC6\u4FE1\u606F\u201D\u67E5\u770B\u8BE6\u60C5\u3002 +CREATE_NEW_ROLE = \u521b\u5efa\u7528\u6237\u002f\u89d2\u8272 +CREATE_USERROLE_FINISH_BTN = \u5b8c\u6210 +CREATE_USERROLE_NEXT_BTN = \u4e0b\u4e00\u6b65 +CREATE_USERROLE_BACK_BTN = \u4e0a\u4e00\u6b65 +CREATE_USERROLE_CANCEL_BTN = \u53d6\u6d88 +CREATE_USERROLE_ENTER_NM = \u8f93\u5165\u7528\u6237\u002f\u89d2\u8272\u540d\u79f0 +CREATE_USERROLE_NAME_INVALID = \u7528\u6237\u002f\u89d2\u8272\u540d\u79f0\u65e0\u6548 +CREATE_USERROLE_NAME_EXCEED_MAX = \u7528\u6237\u002f\u89d2\u8272\u540d\u79f0\u6700\u591a\u53ef\u5305\u542b\u0036\u0033\u4e2a\u5b57\u7b26 +CREATE_USERROLE_ENTER_PAS = \u8f93\u5165\u5bc6\u7801 + +CREATE_USERROLE_CREATE_ERROR = \u521b\u5efa\u7528\u6237\u002f\u89d2\u8272\u65f6\u51fa\u9519: {0} +USER_ROLE_NM_PAS = \u7528\u6237\u002f\u89d2\u8272\u5c5e\u6027 +CREATE_USERROLE_NAME = \u540d\u79f0 +CREATE_USERROLE_CIPHER = \u5bc6\u7801 +CREATE_USERROLE_PRIVILEGE = \u6743\u9650 +CREATE_USERROLE_SYSADMIN = \u7cfb\u7edf\u7ba1\u7406\u5458 +CREATE_USERROLE_AUDITADMIN = \u5ba1\u8ba1\u7ba1\u7406\u5458 +CREATE_USERROLE_CREATEDB = \u521b\u5efa\u6570\u636e\u5e93 +CREATE_USERROLE_CREATEROLE = \u521b\u5efa\u89d2\u8272 +CREATE_USERROLE_INHERIT = \u7ee7\u627f +CREATE_USERROLE_LOGIN = \u767b\u5f55 +CREATE_USERROLE_REPLICATION = \u590d\u5236 +USER_ROLE_PRIVILEGE_OPTION = \u9ad8\u7ea7 +CREATE_USERROLE_CONNECT_LIMIT = \u8fde\u63a5\u9650\u5236 +CREATE_USERROLE_VALID_BEGIN = \u5f00\u59cb\u65e5\u671f +CREATE_USERROLE_VALID_UNTIL = \u7ed3\u675f\u65e5\u671f +CREATE_USERROLE_RES_POOL = \u8d44\u6e90\u6c60 +CREATE_USERROLE_ROLE_GROUP_MEMBER = \u89d2\u8272\u7ec4 +CREATE_USERROLE_ADMIN_GROUP_MEMBER = \u7ba1\u7406\u5458\u7ec4 +CREATE_USERROLE_CREATE_SUCCESS = \u5DF2\u521B\u5EFA\u7528\u6237/\u89D2\u8272: {0} +DROP_ROLE_DIA_TITLE = \u5220\u9664\u7528\u6237\u002f\u89d2\u8272 +DROP_ROLE = \u786e\u5b9a\u8981\u5220\u9664\u7528\u6237\u002f\u89d2\u8272{0}\u5417? +DROP_USERROLE_PROGRESS_NAME = \u6b63\u5728\u5220\u9664\u7528\u6237\u002f\u89d2\u8272: {0}@{1} +DROP_USERROLE_SUCCESS = \u5df2\u5220\u9664\u7528\u6237\u002f\u89d2\u8272: {0} +CREATE_USERROLE_NO_PRIVILEGE = \u65e0\u7279\u6743 +CREATE_USERROLE_NO_PRIVILEGE_CREATE = \u60a8\u65e0\u6743\u521b\u5efa\u65b0\u7528\u6237\u6216\u89d2\u8272\u3002 +ENTER_ROLE_NAME = \u8f93\u5165\u7528\u6237\u002f\u89d2\u8272\u540d\u79f0 +ENTER_CIPHER = \u8f93\u5165\u5bc6\u7801 +CREATE_USERROLE_PAS_NOT_MATCH = \u4E24\u6B21\u8F93\u5165\u7684\u5BC6\u7801\u4E0D\u4E00\u81F4 +ENTER_CIPHER_TWICE = \u518d\u6b21\u8f93\u5165\u5bc6\u7801 +CREATE_USERROLE_ALL = \u6240\u6709 +CREATE_USERROLE_SSL_NOT_ENABLE = \u8fde\u63a5\u4e0d\u5b89\u5168\uff0c\u56e0\u4e3a\u0053\u0053\u004c\u5df2\u7981\u7528\u3002 +PRIVILEGE_ADVANCED = \u9ad8\u7ea7 +STATUS_MSG_DROP_ROLE = \u6b63\u5728\u5220\u9664\u7528\u6237\u002f\u89d2\u8272\u002e\u002e\u002e +DROP_USERROLE_ERROR = \u5220\u9664\u7528\u6237\u002f\u89d2\u8272 +DROP_USERROLE_UNABLE = \u65e0\u6cd5\u5220\u9664\u7528\u6237\u002f\u89d2\u8272\u3002 +DROP_USERROLE_UNABLE_MSG = \u5220\u9664\u7528\u6237/\u89D2\u8272\u65F6\u51FA\u9519: {0}@{1} + +EXPORT_ALL_DATA_DISABLE_TOOLTIP=\u5BF9EXPLAIN\u67E5\u8BE2\u7981\u7528 + +CREATE_USER=\u7528\u6237 +CREATE_ROLE=\u89d2\u8272 + +UNKNOW_CLOB_TYPE= \u672A\u77E5\u7C7B\u578B + +EXCEL_ROW_LIMIT_REACHED= \u5BFC\u51FA\u6210\u529F\uFF0C\u4F46\u5DF2\u8FBE\u5230\u6700\u5927\u8BB0\u5F55\u6570\u3002\n\u6CE8\u610F\uFF1A\nxlsx\uFF1A\u652F\u6301\u6700\u5927\u884C\u6570\u4E3A100\u4E07\nxls\uFF1A\u652F\u6301\u6700\u5927\u884C\u6570\u4E3A64000 +#Need no translate the below message as it is used internally +MAXIMUM_EXCEL_ROW_REACHED=Maximum excel row limits reached +SQL_QUERY_SETTING_ZERO_DATA_HEADER=\u5C06\u67E5\u8BE2\u5B57\u7B26\u6570\u8BBE\u7F6E\u4E3A0 +SQL_QUERY_SETTING_ZERO_DATA_BODY=\u5982\u679C\u5C06\u67E5\u8BE2\u5B57\u7B26\u6570\u8BBE\u7F6E\u4E3A0\uFF0C\u5386\u53F2\u8BB0\u5F55\u4E2D\u4F1A\u4FDD\u5B58\u5B8C\u6574\u67E5\u8BE2\u3002\u8FD9\u53EF\u80FD\u4F1A\u589E\u52A0\u78C1\u76D8\u7A7A\u95F4\u7684\u7528\u91CF\u3002\u786E\u8BA4\u8981\u4FDD\u5B58\u66F4\u6539\u5417\uFF1F +SQL_QUERY_SETTING_COMBO_DATA_BODY=\u5982\u679C\u5C06\u67E5\u8BE2\u5927\u5C0F\u8BBE\u7F6E\u4E3A0\uFF0C\u5E76\u51CF\u5C0F\u201CSQL\u5386\u53F2\u67E5\u8BE2\u201D\u7684\u503C\uFF0C\u53EF\u80FD\u4F1A\u5BFC\u81F4SQL\u5386\u53F2\u67E5\u8BE2\u4E22\u5931\uFF0C\u5E76\u589E\u52A0\u78C1\u76D8\u7A7A\u95F4\u4F7F\u7528\u91CF\u3002\u786E\u8BA4\u8981\u7EE7\u7EED\u5417\uFF1F + +#Save/Save As +CONNECTION_OPTION_DIALOG_TITLE = \u6570\u636E\u5E93\u8FDE\u63A5 +DIRTY_TERMINAL_DIALOG_TITLE = \u4FDD\u5B58\u6587\u4EF6 +DIRTY_TERMINAL_DIALOG_SELECT_ALL_BUTTON = \u5168\u9009 +DIRTY_TERMINAL_DIALOG_DESELECT_ALL_BUTTON = \u53D6\u6D88\u5168\u9009 +DIRTY_TERMINAL_DIALOG_SELECTION_MESSAGE = \u9009\u62E9\u8981\u4FDD\u5B58\u7684\u6587\u4EF6: +FILE_UPDATE_CONFLICT_DIALOG_TITLE = \u66F4\u65B0\u51B2\u7A81 +FILE_UPDATE_CONFLICT_DIALOG_DETAIL = \u6587\u4EF6\u7CFB\u7EDF\u4E2D\u7684\u201C{0}\u201D\u6587\u4EF6\u5DF2\u66F4\u6539\u3002\u662F\u5426\u8981\u8986\u76D6\u6587\u4EF6\u7CFB\u7EDF\u4E2D\u7684\u66F4\u6539\uFF1F +DIRTY_TERMINAL_DIALOG_SAVE_BUTTON = \u4FDD\u5B58 +DIRTY_TERMINAL_DIALOG_NOT_SAVE_BUTTON = \u4E0D\u4FDD\u5B58 +DIRTY_TERMINAL_DIALOG_SAVE_WARNING = \u201C{0}\u201D\u53D1\u751F\u4FEE\u6539\uFF0C\u662F\u5426\u4FDD\u5B58? +DIRTY_TERMINAL_DIALOG_SAVE_FILE_ERROR = \u4FDD\u5B58\u6587\u4EF6\u201C{0}\u201D\u5931\u8D25\u3002 + +#TABLE PROPERTIES +OLAP_PROP_COLUMNTAB_DATATYPE=\u6570\u636E\u7C7B\u578B +OLAP_PROP_COLUMNTAB_ISNULLABLE=\u80FD\u5426\u4E3ANull +OLAP_PROP_KEYTAB_TYPE=\u7C7B\u578B +OLAP_PROP_KEYTAB_COLUMNS=\u5217 +OLAP_PROP_KEYTAB_REFERENCINGTABLE=\u5F15\u7528\u8868 +OLAP_PROP_KEYTAB_REFERENCINGCOL=\u5F15\u7528\u5217 +OLAP_PROP_KEYTAB_ONDELETE=ON DELETE +OLAP_PROP_KEYTAB_DEFERRABLE=DEFERRABLE +OLAP_PROP_KEYTAB_DEFERRED=DEFERRED +OLAP_PROP_KEYTAB_VALIDATED=\u5DF2\u9A8C\u8BC1 +OLAP_PROP_INDEXTAB_COLUMNS=\u5217 +OLAP_PROP_INDEXTAB_ISUNIQUE=\u662F\u5426\u552F\u4E00 +OLAP_PROP_INDEXTAB_TABLESPACE=\u8868\u7A7A\u95F4 +OLAP_PROP_CHECKTAB_CONDITION=\u6761\u4EF6 +OLAP_PROP_CHECKTAB_ENABLED=\u5DF2\u542F\u7528 +OLAP_PROP_CHECKTAB_DEFERRABLE=DEFERRABLE +OLAP_PROP_CHECKTAB_DEFERRED=DEFERRED +OLAP_PROP_CHECKTAB_VALIDATED=\u5DF2\u9A8C\u8BC1 +OLAP_PROP_PARTITIONTAB_TYPE=\u5206\u533A\u7C7B\u578B +OLAP_PROP_PARTITIONTAB_KEYS=\u5206\u533A\u952E +PROPERTIES_CHECKS_TAB=\u68C0\u67E5 +PROPERTIES_DISTRIBUTION_TAB=\u5206\u5E03 +PROPERTIES_KEYS_TAB=\u952E + +RESULT_WINDOW_EDITTABLE_COMMIT_NONEXECUTED==/\u672A\u6267\u884C\uFF1A{0} + +OLAP_PROP_PARTITIONTAB_PARTITIONVALUE=\u5206\u533A\u503C +OLAP_PROP_PARTITIONTAB_TABLESPACENAME=\u8868\u7A7A\u95F4 + +EDIT_TABLE_PROPERTIES_DATA_DROPPED_REFRESH_ERROR=\u7F16\u8F91\u65F6\u53D1\u751F\u9519\u8BEF\u3002\n\u65E0\u6CD5\u7EE7\u7EED\u7F16\u8F91\uFF0C\u56E0\u4E3A\u8BE5\u5BF9\u8C61\u5DF2\u88AB\u4FEE\u6539\u3001\u5220\u9664\uFF0C\u6216\u8FDE\u63A5\u5DF2\u4E22\u5931\u3002\n\u8BF7\u91CD\u65B0\u6253\u5F00\u5C5E\u6027\u7A97\u53E3\u3002 + +DATA_TOO_LARGE_DISPLAY_EDIT =\u6570\u636E\u91CF\u592A\u5927\uFF0C\u65E0\u6CD5\u5B8C\u6574\u663E\u793A\u3002\n\u8BF7\u62F7\u8D1D\u5355\u5143\u683C\u6570\u636E\u5230\u5176\u4ED6\u7F16\u8F91\u5668\u8FDB\u884C\u67E5\u770B\u6216\u4FEE\u6539\u3002\n\u6570\u636E\u4FEE\u6539\u5B8C\u4E4B\u540E\u9700\u8981\u91CD\u65B0\u62F7\u8D1D\u56DE\u5355\u5143\u683C\u3002 +DATA_TOO_LARGE_WARNING =\u6570\u636E\u957F\u5EA6\u8B66\u544A + +NEW_OBJECT_WILL_BE_OPENED=\u65b0\u51fd\u6570\u002f\u8fc7\u7a0b\u5c06\u88ab\u6253\u5f00 + +CURSOR_IMPLEMENT_DIALOG_TITLE = \u67E5\u8BE2\u6267\u884C +CURSOR_IMPLEMENT_DIALOG_HEADER = \u5F53\u524D\u7279\u5B9A\u67E5\u8BE2\u7ED3\u679C\u4E0D\u652F\u6301\u5206\u9875\uFF0C\u786E\u8BA4\u8981\u7EE7\u7EED\u5417\uFF1F +CURSOR_FAILURE_SQL_ERROR=SQL\u9519\u8BEF\u7801: + +REFRESH_TABLE_LABEL_FAILURE = \u52A0\u8F7D\u5217\u5931\u8D25 +REFRESH_TABLE_LABEL_SUCCESS = \u5DF2\u52A0\u8F7D\u5217 +REFRESH_TABLE_LABEL_IN_PROGRESS = \u5217\u52A0\u8F7D\u4E2D + +CREATE_TABLE_DDL_TAB = DDL + +RESULT_TAB_CONNECTION_LOST_ERR_MSG=\u64CD\u4F5C\u51FA\u9519\n\u5BF9\u8C61\u88AB\u4FEE\u6539\u6216\u5220\u9664\uFF0C\u6216\u8FDE\u63A5\u4E22\u5931\uFF0C\u5BFC\u81F4\u64CD\u4F5C\u65E0\u6CD5\u8FDB\u884C\n\u91CD\u65B0\u6253\u5F00\u201C\u7ED3\u679C\u201D\u9875\u7B7E\u3002 +ERR_START_TRANSACTION_FAILED = \u542F\u52A8\u4E8B\u52A1\u65F6\u51FA\u9519 + +ERR_ROLL_BACK_TRANSACTION_FAILED = \u56DE\u6EDA\u4E8B\u52A1\u65F6\u51FA\u9519 + +PREF_TRANSACTION_SETTING=\u4E8B\u52A1 +PREF_TRANSACTION_AUTOCOMMIT=\u81EA\u52A8\u63D0\u4EA4 +AUTOCOMMIT_ENABLE=\u542F\u7528 +AUTOCOMMIT_DISABLE=\u7981\u7528 +TRANSACTION_DIALOG_TITLE=\u5B58\u5728\u672A\u5173\u95ED\u4E8B\u52A1 +TRANSACTION_DIALOG_BODY=\u5982\u4E0BSQL\u7F16\u8F91\u7A97\u53E3\u5B58\u5728\u672A\u5173\u95ED\u7684\u4E8B\u52A1\uFF0C\u8BF7\u5148\u624B\u52A8\u63D0\u4EA4\u6216\u56DE\u6EDA\u4E8B\u52A1\u3002 +TRANSACTION_COMMIT_FEEDBACK=\u63D0\u4EA4\u6210\u529F +TRANSACTION_ROLLBACK_FEEDBACK=\u56DE\u6EDA\u6210\u529F +TRANSACTION_OPERATION_EXCEPTION_TITLE=\u64CD\u4F5C\u4E8B\u52A1\u5931\u8D25 +TRANSACTION_COMMIT_EXCEPTION_BODY = \u63D0\u4EA4\u4E8B\u52A1\u5931\u8D25 +TRANSACTION_ROLLBACK_EXCEPTION_BODY =\u56DE\u6EDA\u4E8B\u52A1\u5931\u8D25 +TRANSACTION_RESET_BUTTIONS_EXCEPTION=\u63D0\u4EA4\u548C\u56DE\u6EDA\u6309\u94AE\u72B6\u6001\u91CD\u7F6E\u5931\u8D25 +TRANSACTION_OPERATION_TOGGLE_TITLE=\u4E8B\u52A1\u64CD\u4F5C +AUTOCOMMIT_ENABLE_DESC=\u542F\u7528\u81EA\u52A8\u63D0\u4EA4\u529F\u80FD\uFF0C\u4E8B\u52A1\u5C06\u4F1A\u88AB\u81EA\u52A8\u63D0\u4EA4\u3002 +AUTOCOMMIT_DISABLE_DESC=\u7981\u7528\u81EA\u52A8\u63D0\u4EA4\u529F\u80FD\uFF0C\u7528\u6237\u9700\u624B\u52A8\u63D0\u4EA4\u6216\u56DE\u6EDA\u4E8B\u52A1\u3002 +TRANSACTION_DIALOG_OK_BUTTION=\u786E\u8BA4 +TRANSACTION_COMMIT_JOB=\u6B63\u5728\u6267\u884C\u624B\u52A8\u63D0\u4EA4 +TRANSACTION_ROLLBACK_JOB=\u6B63\u5728\u6267\u884C\u624B\u52A8\u56DE\u6EDA + +TRANSACTION_COMMIT_TOOL_TIP = \u63D0\u4EA4 +TRANSACTION_ROLLBACK_TOOL_TIP = \u56DE\u6EDA +TRANSACTION_COMMIT_CONFIRMATION = \u63D0\u4EA4\u5F53\u524D\u4E8B\u52A1\uFF1F +TRANSACTION_ROLLBACK_CONFIRMATION = \u56DE\u6EDA\u5F53\u524D\u4E8B\u52A1\uFF1F +NO_TRANSACTION_COMMIT_ROLLBACK_TOGGLE = \u5F53\u524D\u65E0\u6B63\u5728\u5F00\u542F\u7684\u4E8B\u52A1 + +SHOW_SEQUENCE_DDL_CANCELING=\u5DF2\u53D6\u6D88\u663E\u793A\u5E8F\u5217DDL\uFF1A {0}.{1} +SHOW_SEQUENCE_DDL_PROGRESS_NAME = \u6B63\u5728\u663E\u793A\u5E8F\u5217DDL\uFF1A{0} +SHOW_SEQUENCE_DDL_FAILED = \u663E\u793A\u5E8F\u5217DDL\u65F6\u51FA\u9519\uFF1A {0}.{1} +BATCH_EXPORT_NO_RELATION_PREVILAGE = \u6743\u9650\u4E0D\u8DB3\uFF0C\u65E0\u6CD5\u83B7\u53D6\u5F53\u524D\u5BF9\u8C61\u7684\u5B9A\u4E49\u6216\u6570\u636E\u3002 + +PREFERENCE_COMMAND_OPEN_NEW_TERMINAL=\u6253\u5F00\u65B0\u7684\u7EC8\u7AEF +OPEN_NEW_TERMINAL=\u6253\u5F00\u65B0\u7684SQL\u7EC8\u7AEF\u7A97\u53E3 +SHORTCUT_KEY_ALREADY_EXIST=\u5FEB\u6377\u952E\u5DF2\u5728" +SELECT_SHORTCUT_KEY_AGAIN="\u4E2D\u4F7F\u7528,\u8BF7\u91CD\u65B0\u9009\u62E9! +SHORTCUT_KEY_DUPLICATE=\u5FEB\u6377\u952E\u91CD\u590D + +EXECUTE_DEBUGE= \u51FD\u6570\u6267\u884C +WRITE_HERE = \u8bf7\u5728\u4e0b\u65b9\u8f93\u5165\uff1a + +PARAMETER_INPUT_TABLE_PARAM_NAME_COLUMN = \u53C2\u6570\u540D +PARAMETER_INPUT_TABLE_PARAM_TYPE_COLUMN = \u6570\u636E\u7C7B\u578B +PARAMETER_INPUT_TABLE_PARAM_VALUE_COLUMN = \u503C + +OPERATION_CANNOT_BE_PERFOREMD_TITLE = \u64CD\u4F5C\u4E0D\u80FD\u88AB\u6267\u884C\u3002 +ERROR_IMPORTING_CONNECTION_PROFILES = \u5BFC\u5165\u914D\u7F6E\u6587\u4EF6\u65F6\u51FA\u9519 +EXPORTING_CONNECTION_PROFILES = \u6B63\u5728\u5BFC\u51FA\u914D\u7F6E\u6587\u4EF6 +IMPORTING_CONNECTION_PROFILES = \u6B63\u5728\u5BFC\u5165\u914D\u7F6E\u6587\u4EF6 + +EXPORT_CONNECTION_PROFILE_DIALOG_HEADER = \u5BFC\u51FA\u8FDE\u63A5\u914D\u7F6E\u6587\u4EF6 +EXPORT_CONNECTION_PROFILE_DIALOG_GROUP = \u8FDE\u63A5 +EXPORT_CONNECTION_PROFILE_SUCCESS_MESSAGE=\u6587\u4EF6\u5BFC\u51FA\u6210\u529F +EXPORT_CONNECTION_PROFILE_LOAD_ERR_MSG = \u52A0\u8F7D\u5F85\u5BFC\u51FA\u6587\u4EF6\u65F6\u51FA\u9519 +EXPORT_CONNECTION_PROF_LOADING_STATUS_MESSAGE = \u52A0\u8F7D\u8FDE\u63A5\u914D\u7F6E\u6587\u4EF6 +IMPORT_CONNECTIONS_LOADING_STATUS_MSG =\u6B63\u5728\u5BFC\u5165\u914D\u7F6E\u6587\u4EF6 +IMPORT_CONNECTIONS_PROFILE_DIALOG_HEADER = \u5BFC\u5165\u8FDE\u63A5\u914D\u7F6E\u6587\u4EF6 +IMPORT_CONNECTIONS_PROFILE_ERR_MSG=\u5BFC\u5165\u6587\u4EF6\u65F6\u51FA\u9519 +IMPORT_CONN_PROFILE_REPLACE_LABEL = \u66FF\u6362 +IMPORT_CONN_PROFILE_KEEP_BOTH_FILES_LBL=\u590D\u5236\uFF0C\u4F46\u4FDD\u7559\u4E24\u4E2A\u6587\u4EF6 +IMPORT_CONN_PROFILE_DONT_CPY_LBL=\u4E0D\u590D\u5236 +IMPORT_CONN_PROFILE_CONFLICTS_LBL=\u6240\u6709\u51B2\u7A81\u6267\u884C\u8BE5\u64CD\u4F5C + +IMPORT_PROFILE_INCORRECT_FILE =\u65E0\u6548\u7684\u6587\u4EF6\u683C\u5F0F, \u8bf7\u5bfc\u5165\u6b63\u786e\u7684\u8fde\u63a5\u914d\u7f6e\u6587\u4ef6\u3002 +IMPORT_CONNECTIONS_PROFILE_INVALID_FORMAT_EXCEPTION=\u5BFC\u5165\u8FDE\u63A5\u914D\u7F6E\u6587\u4EF6\u65F6\u53D1\u751F\u5F02\u5E38 + +PROCESS_TIMEOUT_ERROR=\u8FDB\u7A0B\u8D85\u65F6 \n\u8BF7\u67E5\u770B\u9996\u9009\u9879\u7A97\u53E3\uFF08\u8BBE\u7F6E > \u9996\u9009\u9879 > \u5BFC\u5165/\u5BFC\u51FA > \u5BFC\u51FADDL\uFF09\uFF0C\u589E\u5927\u8BE5\u8FDB\u7A0B\u7684\u8D85\u65F6\u8BBE\u7F6E\u3002 +EXPORT_TIMEOUT=\u5BFC\u51FA\u8D85\u65F6 +DEFAULT_TIMEOUT=\u9ED8\u8BA4\u8D85\u65F6\u65F6\u95F4 +CUSTOM_TIMEOUT=\u81EA\u5B9A\u4E49\u8D85\u65F6\u65F6\u95F4 +SECONDS=\u79D2 + +ROLLBACK_COMPLETED = \u56DE\u6EDA\u5DF2\u5B8C\u6210 + +RENAME_TABLESPACE_FAILED =\u91CD\u547D\u540D\u8868\u7A7A\u95F4\u5931\u8D25 + +ERR_FETCH_RESULT_SET_COLUMN_COMMENT = \u83B7\u53D6\u7ED3\u679C\u96C6\u5217\u7684\u5907\u6CE8\u4FE1\u606F\u5931\u8D25\u3002 + +FILE_LIMIT_WARNING_MESSAGE = \u8D85\u51FA\u6570\u636E\u9650\u5236\u3002 \n\u8BF7\u68C0\u67E5\u9996\u9009\u9879\u9875\u9762\uFF08\u8BBE\u7F6E > \u9996\u9009\u9879 > \u73AF\u5883 > \u4F1A\u8BDD\u8BBE\u7F6E\uFF09\uFF0C\u5E76\u8BBE\u7F6E\u6570\u636E\u9650\u5236\u3002 +FILE_LIMIT = \u6587\u4EF6\u9650\u5236 +FILE_LIMIT_HEADER = \u6570\u636E\u9650\u5236\u544A\u8B66 +IMPORT_TABLE_DATA_LIMIT = \u5BFC\u5165\u8868\u6570\u636E\u9650\u5236 +IMPORT_FILE_DATA_LIMIT = \u5BFC\u5165\u6587\u4EF6\u6570\u636E\u9650\u5236 +IMPORT_BYTEA_DATA_LIMIT = \u5BFC\u5165BYTEA\u7C7B\u578B\u6570\u636E\u9650\u5236 +SUFFIX_DATA_LIMIT = MB\uFF080\u4EE3\u8868\u4E0D\u9650\u5236\uFF09 +IMPORT_UNLIMITED_NOTE = \u6CE8\u610F\uFF1A\u9009\u62E9\u6587\u4EF6\u5BFC\u5165\u5927\u5C0F\u4E3A0\uFF0C\u5C06\u5BFC\u81F4\u5BFC\u5165\u5EF6\u8FDF\u3002 + +#LAZY RENDERING +SHOW_MORE_OBJECTS=\u66F4\u591A\u5BF9\u8C61... +LAZY_RENDER_PREFERENCE_GROUP_NAME= \u5EF6\u8FDF\u6E32\u67D3 +LAZY_RENDER_OBJECT_COUNT_LABEL = \u5355\u6279\u6B21\u5BF9\u8C61\u6570\u91CF +LAZY_RENDER_SUFFIX_LABEL = \uFF08\u53D6\u503C\u8303\u56F4\uFF1A1000-100000\uFF1B\u9ED8\u8BA4\u503C\uFF1A10000\uFF09 +LAZY_RENDERING_ERROR_MSG = \u8D85\u51FA\u8303\u56F4\uFF08{0}-{1}\uFF09 + +INVALID_EXTENSION_HEADER = \u6587\u4EF6\u6269\u5C55\u540D\u65E0\u6548 +INVALID_EXTENSION_MESSAGE = \u8BF7\u9009\u62E9\u6709\u6548\u7684\u6587\u4EF6\u6269\u5C55\u540D\u3002 +IMPORT_TABLE_FILE_INVALID_DATA_LIMIT= \u5BFC\u5165\u8868/\u6587\u4EF6\u6570\u636E\u9650\u989D\u503C\u4E0D\u80FD\u4E3A\u7A7A + +VALIDATE_CIPHER_FAIL = \u9A8C\u8BC1\u5931\u8D25 + +#olap table excell format import +IMPORT_DATA_FORMAT = \u6570\u636E\u8F6C\u6362 +IMPORT_EXCEL_DATE = \u65F6\u95F4\u683C\u5F0F: +IMPORT_EXCEL_NUM = \u6570\u503C\u683C\u5F0F: +IMPORT_EXCEL_CHAR = \u5B57\u7B26\u683C\u5F0F: +IMPORT_RESULT_INVALID_CONNECTION = \u5BFC\u5165\u7ED3\u679C\u6570\u636E\u7684\u8FDE\u63A5\u65E0\u6548\uFF0C\u65E0\u6CD5\u7EE7\u7EED\u5BFC\u5165\u636E\u6570\u3002 +ENCODING_NOTE = \u6CE8\u610F\uFF1A\u8BF7\u9009\u62E9\u4E0E\u5BFC\u5165\u6587\u4EF6\u6570\u636E\u76F8\u540C\u7684\u7F16\u7801\u683C\u5F0F\uFF0C\u5426\u5219\u53EF\u80FD\u5BFC\u81F4\u5BFC\u5165\u5931\u8D25\uFF0C\u6216\u8005\u5BFC\u5165\u6570\u636E\u4E71\u7801\u3002 +OPTION_ZIP= \uFF08.zip\uFF09 +COMPRESS_FAIL_DAILOG_TITLE = \u6570\u636e\u538b\u7f29\u5931\u8d25 +COMPRESS_FAILED = \u538B\u7F29\u5931\u8D25 +SQL_DDL_EXPORT_WINDOW_TITLE = \u5BFC\u51FA\u5BF9\u8C61\u5B9A\u4E49 +SQL_DDL_DATA_EXPORT_WINDOW_TITLE = \u5BFC\u51FA\u8868\u5B9A\u4E49\u548C\u6570\u636E +GENERATE_SQL_EXPORT_WINDOW_TITLE = \u751F\u6210\u63D2\u5165\u8BED\u53E5 +INVALID_TEMP_ENVIRONMENT_VARIABLE = \u73AF\u5883\u53D8\u91CF\u201CTEMP\u201D\u8BBE\u7F6E\u6709\u8BEF\uFF0C\u5176\u5E94\u4E3A\u4E00\u4E2A\u5B58\u5728\u7684\u76EE\u5F55\u8DEF\u5F84\u3002 +ERR_ZIP_EXPORT_DAILOG_TITLE = \u5BFC\u51FA\u5931\u8D25: {0} +ERR_ZIP_EXPORT_DAILOG_DESC = \u5BFC\u51FA\u65F6\u51FA\u9519.{0}\u9519\u8BEF:{1} + +#column level comment +CREATE_CLM_COMMENT=\u5217\u6CE8\u91CA +ENTER_COL_DESCRIPTIONS_TEXT=\u8BBE\u7F6E\u5217\u63CF\u8FF0\uFF08\u6700\u591A5000\u4E2A\u5B57\u7B26\uFF09 + +AUTO_COMPLETE_SETTING = \u81EA\u52A8\u5EFA\u8BAE +AUTO_COMPLETE_MIN_SIZE = \u81EA\u52A8\u5EFA\u8BAE\u6700\u5C0F\u5B57\u7B26\u6570 +AUTO_COMPLETE_MIN_SIZE_DESC = \u8BE5\u5B57\u6BB5\u8BBE\u7F6E\u7528\u6237\u5728SQL\u8F93\u5165\u65F6\u89E6\u53D1\u81EA\u52A8\u5EFA\u8BAE\u6240\u9700\u7684\u6700\u5C0F\u5B57\u7B26\u6570\u3002 +AUTO_SUGGEST_ERROR_MSG= \u81EA\u52A8\u5EFA\u8BAE\u6700\u5C0F\u5B57\u7B26\u6570\u8F93\u5165\u65E0\u6548 + +LOAD_MORE_RECORD_TOOL_ITEM = \u52A0\u8F7D\u66F4\u591A\u8BB0\u5F55 +ERR_REMOVE_TARGET_SESSION_FAILED = \u5C06\u76EE\u6807\u4F1A\u8BDD\u521D\u59CB\u5316\u4E3A\u6B63\u5E38\u4F1A\u8BDD\u5931\u8D25 +ERR_ATTACH_TARGET_SESSION_FAILED = \u670D\u52A1\u7AEF\u8FDE\u63A5\u76EE\u6807\u4F1A\u8BDD\u5931\u8D25 +ERR_BL_QUERY_EXEC_STATUS_FAILED = \u6267\u884C\u51FD\u6570/\u8FC7\u7A0B\u8BED\u53E5\u65F6\u51FA\u9519\u3002 + +RESULT_WINDOW =\u7ED3\u679C\u7A97\u53E3 +RESULT_TAB_GENERATE_NEW =\u8986\u76D6\u7ED3\u679C\u96C6 +RESULT_TAB_RETAIN_CURRENT =\u4FDD\u7559\u5F53\u524D\u7ED3\u679C\u96C6 +RESULT_TAB_GENERATE_NEW_HINT =\u5982\u679C\u5F53\u524D\u6709\u6253\u5F00\u7684\u7ED3\u679C\u96C6\u7A97\u53E3\uFF0C\u5173\u95ED\u4E4B\u540E\u6253\u5F00\u65B0\u7684\u7ED3\u679C\u96C6\u7A97\u53E3\u3002 +RESULT_TAB_RETAIN_CURRENT_HINT =\u6253\u5F00\u65B0\u7684\u7ED3\u679C\u96C6\u7A97\u53E3\uFF0C\u540C\u65F6\u4FDD\u7559\u5DF2\u6253\u5F00\u7684\u7ED3\u679C\u96C6\u7A97\u53E3 + +BUTTON_OVERWRITE_RESULTSET_TOOLTIP =\u65B0\u589E\u9875\u7B7E\u7F16\u8BD1/\u6267\u884C\u8BED\u53E5 + +ERR_IMPORT_TABLE_TO_EXCEL = \u9519\u8BEF\u5728\u5BFC\u5165\u8868\u6570\u636E\u3002 +DESCRIBE_IMPACT_OF_COLUMN_SEQUENCE = \u5BFC\u5165\u6587\u4EF6\u4E2D\u5217\u987A\u5E8F\u5E94\u4E0E\u9009\u5B9A\u7684\u5217\u7684\u987A\u5E8F\u4FDD\u6301\u4E00\u81F4\u3002 +PREPARED_QUERY_RELATED_TABLE_FAILED =\u51C6\u5907\u67E5\u8BE2\u76F8\u5173\u8868sql\u5931\u8D25 +PREPARED_QUERY_RELATED_SEQUENCE_FAILED = \u51C6\u5907\u67E5\u8BE2\u76F8\u5173\u5E8F\u5217sql\u5931\u8D25 + +MPPDBIDE_DIA_BTN_DISCARD_ALL =\u653E\u5F03\u6240\u6709 + +PREF_FOLDING_SETTING = \u6298\u53E0 +PREF_FOLDING_ENABLE_DESC = \u542F\u7528SQL\u6298\u53E0\u529F\u80FD\u3002\u652F\u6301\u5BF9\u76F8\u5E94SQL\u8BED\u53E5\u8FDB\u884C\u6298\u53E0/\u5C55\u5F00\u3002 +PREF_FOLDING_DISABLE_DESC = \u7981\u7528SQL\u6298\u53E0\u529F\u80FD\u3002 +PREF_FOLDING_DESC = \u8BE5\u529F\u80FD\u8BBE\u7F6E\u53D8\u66F4\u4EC5\u5728\u65B0\u7684\u7F16\u8F91\u5668\u4E2D\u751F\u6548\uFF1B\u5F53\u524D\u5DF2\u6253\u5F00\u7684\u7F16\u8F91\u5668\u4E0D\u751F\u6548\uFF0C\u91CD\u542F\u540E\u751F\u6548\u3002 + +ERR_WRITE_FILE = \u5199\u5165\u6587\u4EF6\u51FA\u9519\u3002 + +#font preference +PREF_FONT_SETTING = \u5B57\u4F53 +PREF_FONT_STYLE = \u8BBE\u7F6E +PREF_FONT_STYLE_SIZE = \u5927\u5C0F\uFF1A +PREF_FONT_STYLE_SIZE_EXPLANATION = \uFF08\u8303\u56F4\uFF1A1-50\uFF09 + +ERR_DELETE_FILE_MSG = \u5220\u9664\u6587\u4EF6\u9519\u8BEF +PREF_FONT_STYLE_SIZE_EXPLANATION = \uFF08\u8303\u56F4\uFF1A1-50\uFF1B\u9ED8\u8BA4\u503C\uFF1A10\uFF09 +FILTER_INTIAL_TEXT=\u8BF7\u8F93\u5165\u8FC7\u6EE4\u6761\u4EF6\uFF0C\u6309\u56DE\u8F66\u952E\u5F00\u59CB + +ERR_IMPORT_DATE_FORMAT = \u65F6\u95F4\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u91CD\u65B0\u8F93\u5165\u3002 +ERR_IMPORT_DATA_FILE = \u5BFC\u5165\u6587\u4EF6\u4E0D\u5B58\u5728 +FILTER_CLEAR_TOOLTIP=\u6e05\u7a7a +ERR_IMPORT_DIFF_FILE_FORMAT = \u5BFC\u5165\u6587\u4EF6\u683C\u5F0F\u4E0E\u6240\u9009\u683C\u5F0F\u4E0D\u540C + +LOCALE_CHANGE_APP_EXIT_MSG=\u6240\u6709\u7684\u8FDE\u63A5\u5C06\u88AB\u5173\u95ED\uFF0C\u6240\u6709\u672A\u4FDD\u5B58\u7684\u6570\u636E\u90FD\u5C06\u4E22\u5931\u3002\u4F60\u786E\u5B9A\u8981\u9000\u51FA\u5417? +LOCAL_CHANGE_EXIT_NOTE_YES= \u662F\uFF1A\u624B\u52A8\u91CD\u65B0\u6253\u5F00\u66F4\u65B0\u8BED\u8A00\u7684\u5E94\u7528\u3002 +ERR_INVALID_CONNECTION_NAME=\u8FDE\u63A5\u540D\u79F0\u65E0\u6548\uFF0C\u8BF7\u8F93\u5165\u6709\u6548\u7684\u8FDE\u63A5\u540D\u79F0\u3002 + +MSG_HINT_GUI_CONNECTION_OPEN_SOCKET_FAIL =\n4. \u68C0\u67E5\u6570\u636E\u5E93\u670D\u52A1\u662F\u5426\u8FD0\u884C\u6B63\u5E38\uFF0C\u4EE5\u53CA\u5728Data Studio\u670D\u52A1\u5668\u6267\u884Ctelnet ip port\u547D\u4EE4\u662F\u5426\u6210\u529F\u3002 + +LOADING_DATA =\u6570\u636E\u6B63\u5728\u52A0\u8F7D +LOADED_DATA =\u6570\u636E\u52A0\u8F7D\u5B8C\u6210 +FILE_SIZE_EXCEEDED_FOUR =\u6587\u4EF6\u5927\u5C0F\u8D85\u8FC74 MB\uFF0C\u6CA1\u6709\u9884\u89C8\u53EF\u7528 + +# view ER diagram +ER_JOB_DETAILS = \u751f\u6210\u0045\u0052\u56fe\u67e5\u8be2 + +ER_ERROR_POPUP_HEADER = \u0045\u0052\u56fe\u9519\u8bef +ER_DESC_PRIMARYKEY = \u4e3b\u952e +ER_DESC_FOREIGNKEY = \u5916\u952e +ER_DESC_CURRENT_COLOR = \u5f53\u524d\u8868 +ER_DESC_RELATED_COLOR = \u5173\u8054\u8868 +ER_VIEW_FAILED = \u67e5\u770b\u0045\u0052\u56fe\u5931\u8d25 +ER_VIEW_FAILED_MSG = \u67e5\u770b\u0045\u0052\u56fe\u5931\u8d25: {0} +ER_VIEW_INSUFFICIENT_PRIVILEGES_MSG = \u6743\u9650\u4E0D\u8DB3\uFF0C\u65E0\u6CD5\u67E5\u770BER\u56FE\u3002 \ + \n\u8BF7\u6267\u884Cgrant select on SYS.SYS_CONSTRAINT_DEFS to \u83B7\u53D6\u6743\u9650\u4EE5\u67E5\u770BER +VIEW_STYLES = \u663e\u793a\u6837\u5f0f +SHOW_ICONS = \u663e\u793a\u56fe\u6807 +SHOW_DATA_TYPES = \u663e\u793a\u6570\u636e\u7c7b\u578b +SHOW_NULLABILITY = \u663e\u793a\u662f\u5426\u4e3a\u7a7a +SHOW_COMMENTS = \u663e\u793a\u6ce8\u91ca\u4fe1\u606f +SHOW_FULLY_QUALIFIED_NAMES = \u663e\u793a\u5168\u9650\u5b9a\u540d\u79f0 +SHOW_ATTRIBUTES = \u663e\u793a\u6570\u636e\u884c +ATTRIBUTE_VIS_ALL = \u6240\u6709\u6570\u636e\u884c +ATTRIBUTE_VIS_ANY_KEY = \u4efb\u610f\u952e\u6570\u636e +ATTRIBUTE_VIS_PRIMARY_KEY = \u4e3b\u952e\u6570\u636e +ATTRIBUTE_VIS_NONE = \u4e0d\u663e\u793a\u6570\u636e + +ERR_TEMPLATE_LOAD_FAILURE_TITLE=\u6A21\u677F\u52A0\u8F7D\u5931\u8D25 +PREF_LOAD_ERROR_TITLE=\u9996\u9009\u9879\u52A0\u8F7D\u5931\u8D25 +ERR_PREFERENCE_LOAD_FAILURE_DETAIL=\u6E05\u7406\u78C1\u76D8\u7A7A\u95F4\uFF0C\u91CD\u542FData Studio + +#OLTP Synonyms start +SYNONYM_GROUP_NAME = \u540C\u4E49\u8BCD +CREATE_NEW_SYNONYM = \u521B\u5EFA\u540C\u4E49\u8BCD + +SYNONYM_NAME = \u540C\u4E49\u8BCD\u540D\u79F0 +OBJECT_OWNER = \u5BF9\u8C61\u6240\u6709\u8005 +OBJECT_TYPE = \u5BF9\u8C61\u7C7B\u578B +OBJECT_NAME = \u5BF9\u8C61\u540D\u79F0 +REPLACE_IF_EXIST = \u66FF\u6362\u5982\u679C\u5B58\u5728 + +SYNONYM_NAME_ENTER_NM = \u8BF7\u8F93\u5165\u540C\u4E49\u8BCD\u540D\u79F0 +SYNONYM_NAME_EXCEED_MAX = \u540C\u4E49\u8BCD\u540D\u79F0\u6700\u591A\u53EF\u5305\u542B\u0036\u0034\u4E2A\u5B57\u7B26 +OBJECT_OWNER_SELECT_NM = \u8BF7\u9009\u62E9\u5BF9\u8C61\u6240\u6709\u8005 +OBJECT_NAME_SELECT_NM = \u8BF7\u9009\u62E9\u5BF9\u8C61\u540D\u79F0 +CREATED_SYNONYM_SUCESS = \u5DF2\u521B\u5EFA\u540C\u4E49\u8BCD\uFF1A {0}.{1} +CREATE_SYNONYM_NO_DATABASE = \u5F53\u524D\u65E0\u8FDE\u63A5\u7684\u6570\u636E\u5E93\u3002 +CREATE_SYNONYM_ERROR = \u521B\u5EFA\u540C\u4E49\u8BCD\u65F6\u51FA\u9519\uFF1A{0} +DROP_SYNONYM_CONFIRM_MSG = \u786E\u5B9A\u8981\u5220\u9664 ''{0}'' \u540C\u4E49\u8BCD\u5417\uFF1F +DROP_SYNONYM_TITLE = \u5220\u9664\u540C\u4E49\u8BCD +STATUS_MSG_DROP_SYNONYM = \u6B63\u5728\u5220\u9664\u540C\u4E49\u8BCD... +DROP_SYNONYM_PROGRESS_NAME = \u6B63\u5728\u5220\u9664\u540C\u4E49\u8BCD: {0}@{1} +DROP_SYNONYM_SUCCESS = \u5DF2\u5220\u9664\u540C\u4E49\u8BCD\uFF1A{0}.{1} +DROP_SYNONYM_ERROR = \u5220\u9664\u540C\u4E49\u8BCD\u65F6\u51FA\u9519\uFF1A{0}.{1} +DROP_SYNONYM_UNABLE = \u65e0\u6cd5\u5220\u9664\u540C\u4E49\u8BCD\u3002 +PROPERTIES_SYNONYM_NAME = \u540C\u4E49\u8BCD\u540D\u79F0 +PROPERTIES_SYNONYM_OWNER = \u6A21\u5F0F +PROPERTIES_OBJECT_OWNER = \u5BF9\u8C61\u6240\u6709\u8005 +PROPERTIES_OBJECT_NAME = \u5BF9\u8C61\u540D\u79F0 +#OLTP Synonyms end + +# Triggers start +TRIGGER_GROUP_NAME = \u89e6\u53d1\u5668 +#Triggers end + +# DS Commandline parameter support start +DS_COMMANDLINE_ERROR = \u9519\u8BEF\uFF1A +DS_COMMANDLINE_MANDATORY_PARAM_MISSING = \u7F3A\u5C111\u4E2A\u6216\u591A\u4E2A\u5FC5\u9009\u53C2\u6570\u3002\u8BF7\u68C0\u67E5\u4EE5\u4E0B\u5FC5\u9009\u53C2\u6570\u662F\u5426\u5168\u90E8\u901A\u8FC7\u3002 +DS_COMMANDLINE_SSL_MODE_NOT_SUPPORTED = \u8BE5\u670D\u52A1\u5668\u4E0D\u652F\u6301SSL\u6A21\u5F0F\u3002 +DS_COMMANDLINE_UNIDENTIFIED_PARAM = \u53C2\u6570\u65E0\u6CD5\u8BC6\u522B\uFF0C\u652F\u6301\u7684\u53C2\u6570\u5982\u4E0B\uFF0C +DS_COMMANDLINE_DB_TYPE_PARAM_MISSING = \u7F3A\u5C11dbType\u53C2\u6570\u3002\u8BF7\u589E\u52A0\u53C2\u6570\u540E\u91CD\u8BD5\u3002 +DS_COMMANDLINE_INVALID_CONNECTION_NAME_VALUE = connectionName\u53C2\u6570\u503C\u65E0\u6548\u3002 +DS_COMMANDLINE_INVALID_VALUE_LENGTH = {0}\u53C2\u6570\u503C\u957F\u5EA6\u8D85\u8FC763\u4E2A\u5B57\u7B26\u3002\u8BF7\u4F7F\u7528\u8F83\u77ED\u7684\u540D\u79F0\u3002 +DS_COMMANDLINE_NULL_VALUE_FOR_PARAM = {0}\u53C2\u6570\u503C\u4E3A\u7A7A\u3002\u8BF7\u8F93\u5165\u975E\u7A7A\u503C\u3002 +DS_COMMANDLINE_INVALID_FILE_PATH = {0}\u53C2\u6570\u5BF9\u5E94\u7684\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u8005\u662F\u4E00\u4E2A\u76EE\u5F55\u3002\u8BF7\u8F93\u5165\u5408\u6CD5\u7684\u6587\u4EF6\u8DEF\u5F84\u3002 +DS_COMMANDLINE_INVALID_HOST_PORT_VALUE = hostPort\u53C2\u6570\u503C\u975E\u6CD5\uFF0C\u8BF7\u8F93\u5165\u5C0F\u4E8E{0}\u7684\u6B63\u6574\u6570\u3002 + +DS_COMMANDLINE_INVALID_SAVE_CIPHER_VALUE = savePassword\u53C2\u6570\u503C\u65E0\u6548\u3002\u652F\u6301\u7684\u503C\ + \u5982\u4E0B\uFF0C +DS_COMMANDLINE_INVALID_SSL_ENABLE_VALUE = \u8B66\u544A\uFF1AsslEnable\u53C2\u6570\u503C\u65E0\u6548\u3002\u7EE7\u7EED\u4F7F\u7528\u9ED8\u8BA4\u9009\u9879(false)\u3002 +DS_COMMANDLINE_INVALID_SSL_MODE_VALUE = sslMode\u53C2\u6570\u503C\u65E0\u6548\u3002\u652F\u6301\u7684\u503C\u5982\u4E0B\uFF0C +DS_COMMANDLINE_ATTEMPTING_CONNECTION_MSG = \u6B63\u5728\u4F7F\u7528\u547D\u4EE4\u884C\u53C2\u6570\u5C1D\u8BD5\u8FDE\u63A5... +DS_COMMANDLINE_ENTER_CIPHER = \u8BF7\u8F93\u5165\u5BC6\u7801... +DS_COMMANDLINE_PRESS_ENTER_FOLLOWED_BY_CIPHER = \u8BF7\u8F93\u5165\u5BC6\u7801\u5E76\u6309\u56DE\u8F66\u952E +# DS Commandline parameter support end + +# Formatter preference start +FORMATTER_PREVIEW = \u9884\u89C8 +FORMATTER_RIGHT_MARGIN = \u6BCF\u884C\u6700\u5927\u957F\u5EA6 +FORMATTER_INDENT = \u9996\u884C\u7F29\u8FDB +FORMATTER_USE_TAB_CHAR = \u4F7F\u7528\u9879 +FORMATTER_TABS = \u5236\u8868\u7B26 +FORMATTER_SPACES = \u7A7A\u95F4 +FORMATTER_TAB_CHAR_SIZE = \u5236\u8868\u7B26\u5927\u5C0F +FORMATTER_ALIGN_DECLARATION = \u5BF9\u9F50\u7C7B\u578B\u58F0\u660E +FORMATTER_ALIGN_ASSIGNMENTS = \u5BF9\u9F50\u8D4B\u503C\u8FD0\u7B97\u7B26 +FORMATTER_THEN_ON_NEW_LINE = THEN\u524D\u6362\u884C +FORMATTER_LOOP_ON_NEW_LINE = LOOP\u524D\u6362\u884C +FORMATTER_SPLIT_AND_OR = AND/OR\u6362\u884C +FORMATTER_AND_OR_AFTER_EXP = AND/OR\u5728WHERE\u9879\u540E +FORMATTER_AND_OR_UNDER = AND/OR\u5728WHERE\u5173\u952E\u5B57\u4E0B + +FORMATTER_DML = DML +FORMATTER_GENERAL = \u901A\u7528 +FORMATTER_SELECT = SELECT +FORMATTER_INSERT = INSERT +FORMATTER_UPDATE = UPDATE +FORMATTER_OTHERS = \u5176\u4ED6 +FORMATTER_LEFT_ALIGN_KEYWORDS = \u5DE6\u5BF9\u9F50\u5173\u952E\u5B57 +FORMATTER_LEFT_ALIGN_ITEMS = \u5DE6\u5BF9\u9F50\u9879 +FORMATTER_FORMAT = \u683C\u5F0F +FORMATTER_ON_ONE_LINE = \u5168\u90E8\u4F4D\u4E8E\u540C\u4E00\u884C +FORMATTER_ONE_PARAM_PER_LINE = \u4E00\u884C\u4E00\u9879 +FORMATTER_FIT = \u5339\u914D\u9879\u76EE\u5BF9\u9F50\u65B9\u5F0F +FORMATTER_ALIGN = \u5BF9\u9F50 +FORMATTER_COMMA_AFTER_ITEM = \u9879\u540E\u7528\u9017\u53F7 + +FORMATTER_PARAMATER = \u51FD\u6570/\u8FC7\u7A0B\u53C2\u6570 +FORMATTER_ALIGN_DATATYPES = \u5BF9\u9F50\u6570\u636E\u7C7B\u578B +FORMATTER_COMMA_AFTER_DATATYPE = \u6570\u636E\u7C7B\u578B\u540E\u7528\u9017\u53F7 +FORMATTER_LIST_AT_LEFT_MARGIN = \u5DE6\u8FB9\u8DDD\u6846\u5185\u7F16\u53F7 + +FORMATTER_IMPORT = \u5BFC\u5165 +FORMATTER_EXPORT = \u5BFC\u51FA + +FORMATTER_INVALID_FILE_SELECTED = \u9009\u5230\u65E0\u6548\u6587\u4EF6 +FORMATTER_SELECT_VALID_JSON = \u8BF7\u9009\u62E9\u6709\u6548JSON \u6587\u4EF6\u3002 +FORMATTER_FILE_CREATION_ERROR_HEADER = \u6587\u4EF6\u521B\u5EFA\u9519\u8BEF +FORMATTER_FILE_READ_ERROR_HEADER = \u6587\u4EF6\u8BFB\u53D6\u9519\u8BEF +FORMATTER_FILE_CREATION_ERROR = \u5411\u78C1\u76D8\u5199\u5165\u683C\u5F0F\u5668\u65F6\u53D1\u751F\u9519\u8BEF\u3002 +FORMATTER_FILE_READ_ERROR = \u4ECE\u78C1\u76D8\u8BFB\u53D6\u683C\u5F0F\u5668\u65F6\u53D1\u751F\u9519\u8BEF\u3002 +FORMATTER_ERROR_RESIDE_IN_FILE = \u6587\u4EF6\u5185\u9519\u8BEF +# Formatter preference end + +FORMATTER_UNABLE_TO_PARSE_STMT = \u65E0\u6CD5\u89E3\u6790\u8BE5\u8BED\u53E5\u3002 + +RESULT_TAB_COL_NAME = \u540D\u79F0 + +RESULT_TAB_COL_DATA_TYPE = \u6570\u636E\u7C7B\u578B + +RESULT_TAB_COL_PARAMETER_TYPE = \u53C2\u6570 + +RESULT_TAB_COL_VALUE = \u503C + +CURSOR_TOOLTIP_TEXT = \u53CC\u51FB\u4EE5\u663E\u793A\u5168\u90E8\u6570\u636E + +VOID_VALUE_TOOLTIP_TEXT = \u670D\u52A1\u5668\u672A\u8FD4\u56DE\u503C + +CURSOR_DATA_NODE = \u6307\u9488\u6570\u636E + +EDIT_TERMINAL_INPUT_VALUE = \u7F16\u8F91\u51FD\u6570/\u8FC7\u7A0B\u7684\u8F93\u5165\u53C2\u6570\u503C + +EDITOR_DATA_TAB = \u6570\u636E +EDITOR_IMAGE_TAB = \u56FE\u50CF +EDITOR_IMAGE_NOT_SUPPORTED = \u4E0D\u652F\u6301 +EDITOR_DATA_INVALID_NUMBER_DIGITS = \u65E0\u6548\u7684\u5341\u516D\u8FDB\u5236\u6570\u636E\uFF1A\u5947\u6570\u4F4D +AUTO_REFRESH_SUCCESS_MSG=\u81EA\u52A8\u5237\u65B0\u6210\u529F + +RESTORE_DEFAULTS = \u6062\u590D\u9ED8\u8BA4\u503C +MAXIMUM_PREF_FILE_SIZE=\u8BF7\u68C0\u67E5\u4F18\u60E0\u6587\u4EF6\u5927\u5C0F\uFF0C\u6700\u5927\u4E3A5M + +DATE_TIME_PREFERENCES = \u65E5\u671F/\u65F6\u95F4 +USER_DEFINED = \u81EA\u5B9A\u4E49\u683C\u5F0F +DATE_PREFERENCE = \u65E5\u671F +TIME_PREFERENCE = \u65F6\u95F4 +SYSTEM_FORMAT = \u9ED8\u8BA4\u683C\u5F0F +DATE_FORMAT_ERROR_MSG = \u8BF7\u8F93\u5165\u6709\u6548\u7684\u65E5\u671F\u683C\u5F0F\uFF0C\u5982\uFF1Ayyyy-MM-dd +TIME_FORMAT_ERROR_MSG = \u8BF7\u8F93\u5165\u6709\u6548\u7684\u65F6\u95F4\u683C\u5F0F\uFF0C\u5982\uFF1AHH:mm:ss +DATE_FORMAT_EXAMPLE_HINT = \u6709\u6548\u65E5\u671F\u683C\u5F0F\u793A\u4F8B\uFF1Ayyyy-MM-dd, yyyy/MM/dd, yyyyMMdd +TIME_FORMAT_EXAMPLE_HINT = \u6709\u6548\u65F6\u95F4\u683C\u5F0F\u793A\u4F8B\uFF1AHH:mm:ss, HH:mm:ss.SSS, HH:mm:ss.SS + +MUTIPLE_MARKERS=\u6B64\u884C\u6709\u591A\u4E2A\u6807\u8BB0 +RESULT_MANAGER=\u67E5\u8BE2\u7ED3\u679C + +PREF_RS_MAX_RESULT_WINDOW_INPUT_ERR_MSG=\u201C\u6700\u5927\u7ED3\u679C\u7A97\u53E3\u6570\u201D\u8F93\u5165\u4E0D\u5408\u6CD5\uFF0C\u8BF7\u8F93\u5165\u4ECB\u4E8E100\u548C300\u4E4B\u95F4\u7684\u6570\u5B57\u3002 +MAX_RESULT_SET_LBL=\u6700\u5927\u7ED3\u679C\u96C6\uFF1A +MAX_RESULT_SET_RANGE=\uFF08\u53D6\u503C\u8303\u56F4100-300\uFF09 +MAX_RESULT_WINDOW_HINT=\u8BBE\u7F6E\u6700\u5927\u7ED3\u679C\u7A97\u53E3\u5E94\u8BE5\u5728DataStudio\u5E94\u7528\u7A0B\u5E8F\u7684\u4E00\u4E2A\u5B9E\u4F8B\u4E2D\u6253\u5F00\u3002 + +PREFERENCE_SHORTCUT_KEY_OVERWRITE_RESULTSET =\u65B0\u589E\u9875\u7B7E\u6267\u884C\u8BED\u53E5 +PREFERENCE_SHORTCUT_KEY_OVERWRITE_RESULTSET_DESC =\u6253\u5F00\u65B0\u7684\u9875\u7B7E\u6267\u884C\u8BED\u53E5\uFF0C\u5E76\u4FDD\u7559\u5F53\u524D\u5DF2\u6253\u5F00\u7684\u9875\u7B7E\u3002 +COLUMN_LAYOUT_ERROR=\u672A\u77E5\u7684\u5217\u5E03\u5C40\u6570\u636E + +IMPORT_EXPORT_LIMIT_PREF_TITLE=\u5E76\u884C\u5BFC\u5165/\u5BFC\u51FA\u9650\u5236 +IMPORT_EXPORT_LIMIT_PREF_RANGE =\uFF08\u53D6\u503C\u8303\u56F4\uFF1A0-20\uFF09 +IMPORT_EXPORT_LIMIT_PREF_INFO=\u5E76\u884C\u5BFC\u5165/\u5BFC\u51FA\u64CD\u4F5C\u6B21\u6570\u3002\u5982\u8BBE\u7F6E\u4E3A0\uFF0C\u5219\u5BFC\u5165/\u5BFC\u51FA\u64CD\u4F5C\u6B21\u6570\u65E0\u9650\u5236\u3002 +IMPORT_EXPORT_LIMIT_MSG_TITLE= \u5BFC\u5165/\u5BFC\u51FA\u64CD\u4F5C\u9650\u5236 +IMPORT_EXPORT_LIMIT_MSG_INFO=\u5E76\u884C\u5BFC\u5165/\u5BFC\u51FA\u64CD\u4F5C\u6570\u8FBE\u5230\u4E0A\u9650\u3002 +IMPORT_EXPORT_LOGIN_FAILED = \u767B\u5F55\u5931\u8D25 +ERROR_POSITION_LABEL=\u9519\u8BEF\u4F4D\u7F6E +OBJECT_BROWSER=\u5BF9\u8C61\u6D4F\u89C8\u5668 +OBJECT_BROWSER_FILTER_TIMEOUT=\u8FC7\u6EE4\u8D85\u65F6 +OBJECT_BROWSER_FILTER_TIMEOUT_INFO= \u8BBE\u7F6E\u5BF9\u8C61\u6D4F\u89C8\u5668\u8FC7\u6EE4\u7684\u8D85\u65F6\u65F6\u95F4\u3002\ +\u5982\u679C\u8D85\u8FC7\u4E86\u8BBE\u7F6E\u7684\u65F6\u95F4\uFF0C\u5BF9\u8C61\u6D4F\u89C8\u5668\u5C06\u505C\u6B62\u8FC7\u6EE4\u3002 + +OBJECT_BROWSER_FILTER_TIMEOUT_ERR_MSG=\u8BBE\u7F6E\u7684\u5BF9\u8C61\u6D4F\u89C8\u5668\u8FC7\u6EE4\u8D85\u65F6\u65F6\u95F4\u65E0\u6548\u3002 +OBJECT_BROWSER_FILTER_TIMEOUT_ERROR=\u5BF9\u8C61\u6D4F\u89C8\u5668\u8FC7\u6EE4\u8D85\u65F6\uFF0C\u8BF7\u70B9\u51FB\u201C\u9996\u9009\u9879 > \u5BF9\u8C61\u6D4F\u89C8\u5668 > \u8FC7\u6EE4\u8D85\u65F6\u201D\u67E5\u770B\u8BBE\u7F6E\u7684\u8D85\u65F6\u65F6\u95F4\u3002 +OBJECT_BROWSER_FILTER_TIMEOUT_ERROR_TITLE=\u8FC7\u6EE4\u8D85\u65F6\u9519\u8BEF +OBJECT_BROWSER_FILTER_FINISH_MSG=\u8FC7\u6EE4\u5B8C\u6210 +OBJECT_BROWSER_FILTER_TIMEOUT_TOOLTIP_MESSAGE=\u7B5B\u9009\u5668/\u6E05\u9664\u5BF9\u8C61\u6D4F\u89C8\u5668\u7B5B\u9009\u5668\u4E0D\u5B8C\u6574\u3002\u5237\u65B0\u8FDE\u63A5\uFF1A%s\u83B7\u53D6\u8FC7\u6EE4\u5BF9\u8C61\u3002 +LABEL_LOAD_CHILD_OBJECT=\u52A0\u8F7D\u8868\u548C\u89C6\u56FE\u7684\u5B50\u5BF9\u8C61 +FILE_SIZE_EXCEED_WARNING_MSG= \u6587\u4EF6\u5927\u5C0F\u8D85\u8FC7\u3002\n\u8BF7\u68C0\u67E5\u4F18\u60E0\u9875\u9762\uFF08\u8BBE\u7F6E/\u4F18\u60E0/\u73AF\u5883/\u4F1A\u8BDD\u8BBE\u7F6E\uFF09\u5E76\u8BBE\u7F6E\u6587\u4EF6\u6570\u636E\u9650\u5236\u3002 +INVALID_LINE_SEPERATOR=\u73AF\u5883\u53D8\u91CF\u4E2D\u8BBE\u7F6E\u4E86\u65E0\u6548\u7684\u884C\u5206\u9694\u7B26\u3002 +ERROR_WHILE_FETCHING_OWNER_NAME=\u83B7\u53D6\u6570\u636E\u5E93\u5BF9\u8C61\u7684\u6240\u6709\u8005\u540D\u79F0\u65F6\u51FA\u9519 +ERR_WHILE_FETCHING_SEQ_VALUE=\u8BFB\u53D6\u5E8F\u5217\u6570\u636E\u65F6\u51FA\u9519 + +BREAKPOINT_ANNOTATION_LABEL=\u65ad\u70b9 +DEBUG_POSITION_LABEL=\u8C03\u8BD5\u4F4D\u7F6E + +DEBUG_TABLE_ORDER = \u5e8f\u53f7 +DEBUG_STACK_INVOKING_LEVEL = \u8c03\u7528\u5c42\u7ea7 +DEBUG_STACK_FUNCTION_INFO = \u51fd\u6570\u4fe1\u606f +DEBUG_STACK_CURRENT_LINE_NUM = \u5f53\u524d\u884c\u53f7 +DEBUG_BREAKPOINT_LINE_NUM = \u884c\u53f7 +DEBUG_BREAKPOINT_STATEMENT = \u8bed\u53e5 +DEBUG_BREAKPOINT_ENABLE= \u4f7f\u80fd +DEBUG_VARIABLE_VARIABLE = \u53d8\u91cf +DEBUG_VARIABLE_VALUE = \u503c +DEBUG_VARIABLE_DATA_TYPE = \u6570\u636e\u7c7b\u578b +DEBUG_VARIABLE_PARAM_TYPE = \u53c2\u6570\u7c7b\u578b +DEBUG_NOT_SUPPORT_WARN = \u670d\u52a1\u7aef\u4e0d\u652f\u6301\u8c03\u8bd5! +DEBUG_PREFREENCE_ID = \u8c03\u8bd5 +DEBUG_PREFREENCE_WHEN_ROLLBACK = \u8c03\u8bd5\u540e\u81ea\u52a8\u56de\u6eda + +CREATE_FUNCTION_UI_CREATE_FUNCTION = \u521b\u5efa\u51fd\u6570 +CREATE_FUNCTION_UI_CREATE_PROCEDURE = \u521b\u5efa\u5b58\u50a8\u8fc7\u7a0b +CREATE_FUNCTION_UI_SQL_PREVIEW= \u0053\u0051\u004c\u9884\u89c8 +CREATE_FUNCTION_UI_SCHEMA = \u6a21\u5f0f\u0028\u002a\u0029 +CREATE_FUNCTION_UI_FUNCTION_NAME = \u51fd\u6570\u540d\u0028\u002a\u0029 +CREATE_FUNCTION_UI_FUNCTION = \u51fd\u6570 +CREATE_FUNCTION_UI_PROCEDURE = \u5b58\u50a8\u8fc7\u7a0b +CREATE_FUNCTION_UI_LANGUAGE = \u8bed\u8a00\u0028\u002a\u0029 +CREATE_FUNCTION_UI_RETURN_TYPE = \u8fd4\u56de\u503c\u7c7b\u578b +CREATE_FUNCTION_UI_PARAM_LIST = \u53c2\u6570\u5217\u8868 +CREATE_FUNCTION_UI_BUTTON_RESET = \u91cd\u7f6e +CREATE_FUNCTION_UI_BUTTON_ADD = \u6dfb\u52a0 +CREATE_FUNCTION_UI_BUTTON_DELETE= \u5220\u9664 +CREATE_FUNCTION_UI_FUNCTION_BODY = \u51fd\u6570\u4f53\u0028\u002a\u0029 +CREATE_FUNCTION_UI_BUTTON_NEXT = \u4e0b\u4e00\u6b65 +CREATE_FUNCTION_UI_BUTTON_CANCEL = \u53d6\u6d88 +CREATE_FUNCTION_UI_BUTTON_BACK = \u4e0a\u4e00\u6b65 +CREATE_FUNCTION_UI_BUTTON_NO_COMPILE = \u4e0d\u7f16\u8bd1 +CREATE_FUNCTION_UI_BUTTON_COMPILE = \u7f16\u8bd1 +CREATE_FUNCTION_UI_PARAM_NAME = \u540d\u79f0 +CREATE_FUNCTION_UI_PARAM_MODE = \u6a21\u5f0f +CREATE_FUNCTION_UI_PARAM_TYPE = \u7c7b\u578b +CREATE_FUNCTION_UI_PARAM_DEFAULT = \u9ed8\u8ba4\u503c +CREATE_FUNCTION_UI_TOOLTIP_NO_COMPILE = \u8FDB\u5165Data Studio\u7EC8\u7AEF\uFF0C\u4F46\u4E0D\u81ea\u52a8\u7F16\u8BD1\u521B\u5EFA\u7684\u51FD\u6570\uFF0C\u9700\u8981\u624B\u52A8\u6267\u884C\u7F16\u8BD1\u64CD\u4F5C\u3002 +CREATE_FUNCTION_UI_TOOLTIP_COMPILE = \u8FDB\u5165Data Studio\u7EC8\u7AEF\uFF0C\u5E76\u81EA\u52A8\u7F16\u8BD1\u521B\u5EFA\u7684\u51FD\u6570\u3002 +CREATE_FUNCTION_UI_TRIGGER = \u89e6\u53d1\u5668 +CREATE_FUNCTION_UI_CREATE = \u521b\u5efa +CREATE_FUNCTION_UI_ERR_FUNC_NAME = \u51fd\u6570\u540d\u4e0d\u80fd\u4e3a\u7a7a +CREATE_FUNCTION_UI_ERR_FUNC_BODY = \u51fd\u6570\u4f53\u4e0d\u80fd\u4e3a\u7a7a + +DROP_TRIGGER = \u5220\u9664\u89e6\u53d1\u5668 +DROP_TRIGGER_TITLE = \u5220\u9664\u89e6\u53d1\u5668 +RENAME_TRIGGER = \u91cd\u547d\u540d +RENAME_TRIGGER_TITLE = \u4e3a{0}\u89e6\u53d1\u5668\u8f93\u5165\u65b0\u7684\u540d\u79f0 + +CREATE_TRIGGER_UI_CREATE_TRIGGER = \u521b\u5efa\u89e6\u53d1\u5668 +CREATE_TRIGGER_UI_EDIT_TRIGGER = \u7f16\u8f91\u89e6\u53d1\u5668 +CREATE_TRIGGER_UI_GENERAL_PAGE = \u5e38\u89c4 +CREATE_TRIGGER_UI_TRIGGER_NAME = \u89e6\u53d1\u5668\u540d(*) +CREATE_TRIGGER_UI_TRIGGER_TABLE_NAME = \u89e6\u53d1\u8868\u002f\u89c6\u56fe\u540d(*) +CREATE_TRIGGER_UI_TIME_TO_TRIGGER = \u89e6\u53d1\u65f6\u95f4 +CREATE_TRIGGER_UI_OPERATION_TYPE = \u64cd\u4f5c\u7c7b\u578b +CREATE_TRIGGER_UI_COLUMN_NAME = \u5217\u540d +CREATE_TRIGGER_UI_DATA_TYPE = \u6570\u636e\u7c7b\u578b +CREATE_TRIGGER_UI_TRIGGER_LEVEL = \u89e6\u53d1\u7ea7\u522b +CREATE_TRIGGER_UI_TUPLE_LEVEL_TRIGGER = \u5143\u7ec4\u7ea7\u89e6\u53d1\u5668(R) +CREATE_TRIGGER_UI_STATEMENT_LEVEL_TRIGGER = \u8bed\u53e5\u7ea7\u89e6\u53d1\u5668(M) +CREATE_TRIGGER_UI_TRIGGER_CONDITION = \u89e6\u53d1\u6761\u4ef6 +CREATE_TRIGGER_UI_TRIGGER_FUNCTION = \u89e6\u53d1\u51fd\u6570(*) +CREATE_TRIGGER_UI_NEXT = \u4e0b\u4e00\u6b65 +CREATE_TRIGGER_UI_CANCEL = \u53d6\u6d88 +CREATE_TRIGGER_UI_SQL_PREVIEW = SQL\u9884\u89c8 +CREATE_TRIGGER_UI_PREVIOUS = \u4e0a\u4e00\u6b65 +CREATE_TRIGGER_UI_FINISH = \u5b8c\u6210 + +EDIT_VIEW_UI_EDIT_VIEW = \u7f16\u8f91\u89c6\u56fe +CREATE_VIEW_UI_CREATE_VIEW = \u521b\u5efa\u89c6\u56fe +CREATE_VIEW_UI_SCHEMA_NAME = \u6a21\u5f0f\u540d +CREATE_VIEW_UI_VIEW_NAME = \u89c6\u56fe\u540d(*) +CREATE_VIEW_UI_TABLE_NAME = \u8868\u540d +CREATE_VIEW_UI_TABLE_FULL_NAME = \u8868\u5168\u540d +CREATE_VIEW_UI_TABLE_ALIAS_NAME = \u8868\u522b\u540d +CREATE_VIEW_UI_COLUMN_NAME = \u5217\u540d +CREATE_VIEW_UI_COLUMN_ALIAS_NAME = \u5217\u522b\u540d +CREATE_VIEW_UI_COLUMN_1 = \u52171 +CREATE_VIEW_UI_COLUMN_2 = \u52172 +CREATE_VIEW_UI_PREVIEW = \u9884\u89c8 +CREATE_VIEW_UI_NEXT = \u4e0b\u4e00\u6b65 +CREATE_VIEW_UI_PREVIOUS = \u4e0a\u4e00\u6b65 +CREATE_VIEW_UI_CANCEL = \u53d6\u6d88 +CREATE_VIEW_UI_FINISH = \u5b8c\u6210 +CREATE_VIEW_UI_WHERE = \u6761\u4ef6 +CREATE_VIEW_UI_ADD = \u6dfb\u52a0 +CREATE_VIEW_UI_DELETE = \u5220\u9664 +CREATE_VIEW_UI_MATERVIEW = \u7269\u5316\u89c6\u56fe +CREATE_VIEW_UI_VIEW = \u89c6\u56fe +CREATE_VIEW_UI_NAME_NOT_EMPTY = \u89c6\u56fe\u540d\u4e0d\u80fd\u4e3a\u7a7a \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/Activator.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/Activator.java new file mode 100644 index 0000000000000000000000000000000000000000..b4884ff85e3cecf8d81580614b60fbf20ace7e0d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/Activator.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; + +/** + * + * Title: class + * + * Description: The Class Activator. + * + * @since 3.0.0 + */ +public class Activator implements BundleActivator { + + private static BundleContext context; + + /** + * Gets the context. + * + * @return the context + */ + public static BundleContext getContext() { + return context; + } + + /** + * Start. + * + * @param bundleContext the bundle context + */ + public void start(BundleContext bundleContext) { + setContext(bundleContext); + } + + /** + * Sets the context. + * + * @param bundleContext the new context + */ + public static void setContext(BundleContext bundleContext) { + Activator.context = bundleContext; + } + + /** + * Stop. + * + * @param bundleContext the bundle context + */ + public void stop(BundleContext bundleContext) { + removeContext(); + } + + /** + * Removes the context. + */ + public static void removeContext() { + Activator.context = null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/CheckSelectQuery.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/CheckSelectQuery.java new file mode 100644 index 0000000000000000000000000000000000000000..84c7e3753b6a41c779420cbe3623f240942d6e0b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/CheckSelectQuery.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +import java.util.Locale; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Title: class + * Description: The Class CheckSelectQuery. + * + * @since 3.0.0 + */ +public class CheckSelectQuery { + /** + * Checks if is select query. + * + * @param query the query + * @return true, if is select query + */ + public static boolean isSelectQuery(String query) { + return query.toLowerCase(Locale.ENGLISH).startsWith("select") || checkForWithClauseAndSelect(query); + } + + private static boolean checkForWithClauseAndSelect(String query) { + Pattern withSelectPattern = Pattern.compile(MPPDBIDEConstants.WITH_CLAUSE_REGEX); + String queryToCheck = query.replaceAll(MPPDBIDEConstants.LINE_SEPARATOR, " "); + Matcher withSelectMatcher = withSelectPattern.matcher(queryToCheck); + if (withSelectMatcher.find()) { + String clauseFound = withSelectMatcher.group(4); + return clauseFound.equalsIgnoreCase(MPPDBIDEConstants.PRIVILEGE_SELECT); + } else { + return false; + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/ConvertTimeStampValues.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/ConvertTimeStampValues.java new file mode 100644 index 0000000000000000000000000000000000000000..4203f3efaf19289f8c351bbde71744a646796d45 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/ConvertTimeStampValues.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +import java.sql.Date; +import java.sql.Timestamp; +import java.text.SimpleDateFormat; + +/** + * + * Title: class + * + * Description: The Class ConvertTimeStampValues. + * + * @since 3.0.0 + */ +public class ConvertTimeStampValues extends Timestamp { + + private static final long serialVersionUID = 1L; + private String dateFormat; + private long timeStamp; + + /** + * Instantiates a new convert time stamp values. + * + * @param time the time + */ + public ConvertTimeStampValues(long time, String dateFormat) { + super(time); + this.dateFormat = dateFormat; + this.timeStamp = time; + } + + @Override + public String toString() { + SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); + String date = sdf.format(new Date(timeStamp)); + return date; + } + + @Override + public boolean equals(Object object) { + return super.equals(object); + } + + @Override + public int hashCode() { + return super.hashCode(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/ConvertTimeValues.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/ConvertTimeValues.java new file mode 100644 index 0000000000000000000000000000000000000000..9fa52ab9e82a240ccde44324d74ab9f0da5be67e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/ConvertTimeValues.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +import java.sql.Date; +import java.sql.Time; +import java.text.SimpleDateFormat; + +/** + * + * Title: class + * + * Description: The Class ConvertTimeValues. + * + * @since 3.0.0 + */ +public class ConvertTimeValues extends Time { + private static final long serialVersionUID = 1L; + private String timeFormat; + private long millisecs; + + /** + * Instantiates a new convert time values. + * + * @param millis the millis + */ + public ConvertTimeValues(long millis, String timeFormat) { + super(millis); + this.timeFormat = timeFormat; + this.millisecs = millis; + } + + @Override + public String toString() { + SimpleDateFormat sdf = new SimpleDateFormat(timeFormat); + String time = sdf.format(new Date(millisecs)); + return time; + } + + @Override + public boolean equals(Object object) { + return super.equals(object); + } + + @Override + public int hashCode() { + return super.hashCode(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/ConvertValueToInsertSqlFormat.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/ConvertValueToInsertSqlFormat.java new file mode 100644 index 0000000000000000000000000000000000000000..0dd23ce0c7c63145cf0c34777b855c2d03ff1b3b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/ConvertValueToInsertSqlFormat.java @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +import java.sql.Types; + +import org.apache.commons.lang3.BooleanUtils; + +/** + * + * Title: class + * + * Description: The Class ConvertValueToInsertSqlFormat. + * + * @since 3.0.0 + */ +public class ConvertValueToInsertSqlFormat { + + /** + * Convert value to SQL. + * + * @param dataType the data type + * @param value the value + * @param checkTypeName the check type name + * @return the string + */ + public String convertValueToSQL(int dataType, Object value, String checkTypeName) { + String dataValue = null; + String aimValue = String.valueOf(value); + if (aimValue.indexOf("'") > -1) { + aimValue = aimValue.replace("\'", "\'\'"); + } + if (null == value || "".equals(aimValue)) { + return null; + } + switch (dataType) { + case Types.NULL: { + dataValue = null; + break; + } + case Types.BIGINT: + case Types.TINYINT: + case Types.NUMERIC: + case Types.DECIMAL: + case Types.INTEGER: + case Types.SMALLINT: + case Types.FLOAT: + case Types.REAL: { + dataValue = aimValue; + break; + } + case Types.DOUBLE: { + if ("money".equalsIgnoreCase(checkTypeName)) { + dataValue = "\'" + aimValue + "\'"; + } else { + dataValue = aimValue; + } + break; + } + case Types.BIT: { + dataValue = convertBitValue(checkTypeName, aimValue); + break; + } + default: { + dataValue = "\'" + aimValue + "\'"; + break; + } + } + + return dataValue; + + } + + private String convertBitValue(String checkTypeName, String aimValue) { + String dataValue; + if ("bool".equalsIgnoreCase(checkTypeName)) { + dataValue = getBoolValue(aimValue); + } else { + dataValue = getBitValue(aimValue); + } + return dataValue; + } + + private String getBitValue(String aimValue) { + if (isBoolTypeInBit(aimValue)) { + if ("true".equalsIgnoreCase(aimValue)) { + return "\'" + "1" + "\'"; + } else { + return "\'" + "0" + "\'"; + } + } + StringBuffer buff = new StringBuffer(); + buff.append("'"); + buff.append(aimValue); + buff.append("'"); + return buff.toString(); + } + + private boolean isBoolTypeInBit(String aimValue) { + if ("true".equalsIgnoreCase(aimValue) || "false".equalsIgnoreCase(aimValue)) { + return true; + } + return false; + } + + private String getBoolValue(String aimValue) { + String dataValue; + Boolean boolValue = BooleanUtils.toBooleanObject(aimValue); + if (boolValue != null) { + dataValue = boolValue.toString(); + } else { + dataValue = aimValue; + } + return dataValue; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/CustomStringUtility.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/CustomStringUtility.java new file mode 100644 index 0000000000000000000000000000000000000000..10b78d887f1c445ec967c913ff0e698daa870c88 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/CustomStringUtility.java @@ -0,0 +1,255 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +import java.text.Normalizer; +import java.text.Normalizer.Form; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * + * Title: class + * + * Description: The Class CustomStringUtility. + * + * @since 3.0.0 + */ +public class CustomStringUtility { + private static final String OTHER_VERSION_BUILD_INFO_REGEX = "(\\s+(Release|build|debug)\\s+\\w+){0,}"; + + private static final String OPENGAUSS = "openGauss"; + private static final String OPENGAUSS_VERSION_REGEX = "(?i)(openGauss)\\s+([^\\s]+)"; + private static final String OPENGAUSS_POSTGRESQL_VERSION = "PostgreSQL 9.2.4 (GaussDB Kernel V500R001C20 build )"; + + /** + * Removes the delemeters. + * + * @param str the str + * @param del the del + * @return the string + */ + public static String removeDelemeters(String str, String del) { + if (str.contains(del)) { + str = str.replaceAll(del, " "); + } + return str; + } + + /** + * Gets the server type. + * + * @param vrsion the vrsion + * @return the server type + */ + public static String[] getServerType(String vrsion) { + String[] typeAndInfo = new String[2]; + typeAndInfo[0] = ""; + typeAndInfo[1] = ""; + if (vrsion == null) { + return typeAndInfo; + } + + String version = getFullServerVersionString(vrsion); + Matcher matchOpenGauss = Pattern.compile(OPENGAUSS_VERSION_REGEX).matcher(version); + if (matchOpenGauss.find()) { + typeAndInfo[0] = matchOpenGauss.group(1); + } + if (typeAndInfo[0].length() < version.length()) { + typeAndInfo[1] = version.substring(typeAndInfo[0].length(), version.length()).trim(); + } + return typeAndInfo; + } + + /** + * Gets the full server version string. + * + * @param version the version + * @return the full server version string + */ + public static String getFullServerVersionString(String version) { + version = removeDelemeters(version, "-"); + version = removeDelemeters(version, "_"); + Matcher matchOlap = Pattern.compile("(" + OPENGAUSS_VERSION_REGEX + ")" + OTHER_VERSION_BUILD_INFO_REGEX) + .matcher(version); + if (matchOlap.find()) { + return matchOlap.group().trim(); + } + + String olap = parseServerVersion(version); + return olap; + } + + /** + * Sanitize export file name. + * + * @param name the name + * @return the string + */ + + public static String sanitizeExportFileName(String name) { + if (name == null) { + return ""; + } + String sanitizedName = Normalizer.normalize(name, Form.NFKC); + + Pattern pattern = Pattern.compile(".*[\\\\/:*?\"<>|].*"); + + if (pattern.matcher(sanitizedName).matches()) { + sanitizedName = sanitizedName.replaceAll("[\\\\/:*?\"<>|]", ""); + } + pattern = Pattern.compile(".*[ ].*"); + if (pattern.matcher(sanitizedName).matches()) { + sanitizedName = sanitizedName.replaceAll("[ ]", "_"); + } + + return sanitizedName; + } + + /** + * Gets the formated output. + * + * @param s the s + * @param seperator the seperator + * @return the formated output + */ + public static String getFormatedOutput(List s, String seperator) { + if (null != s) { + int size = s.size(); + if (size > 0) { + if (1 == size) { + return s.get(0); + } else { + StringBuilder sb = new StringBuilder(s.get(0)); + for (int i = 1; i < size; i++) { + sb.append(seperator); + sb.append(s.get(i)); + } + + return sb.toString(); + } + } + } + return ""; + } + + /** + * Convert string date format. + * + * @param dateString the date string + * @param newFormat the new format + * @return the string + */ + public static String convertStringDateFormat(String dateString, String newFormat) { + try { + Date date = null; + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(MPPDBIDEConstants.DATE_FORMAT); + date = simpleDateFormat.parse(dateString); + String newDateString = new SimpleDateFormat(newFormat).format(date); + return newDateString; + } catch (ParseException e) { + return dateString; + } + } + + /** + * Gets the formatted string for alias compare. + * + * @param inString the in string + * @return the formatted string for alias compare + */ + public static String getFormattedStringForAliasCompare(String inString) { + if (inString.startsWith("\"") && inString.endsWith("\"")) { + return inString.substring(1, inString.length() - 1); + } else { + return inString.toLowerCase(Locale.ENGLISH); + } + } + + /** + * Checks if is ends with dot. + * + * @param prefix the prefix + * @return true, if is ends with dot + */ + public static boolean isEndsWithDot(String prefix) { + if (!prefix.isEmpty() && '.' == prefix.trim().charAt(prefix.length() - 1)) { + return true; + } + return false; + } + + /** + * Parses the server version. + * + * @param version the version + * @return the string + */ + public static String parseServerVersion(String version) { + Matcher matchOpenGauss = Pattern.compile(OPENGAUSS_VERSION_REGEX).matcher(version); + if (matchOpenGauss.find()) { + return matchOpenGauss.group(); + } else if (version.contains(OPENGAUSS_POSTGRESQL_VERSION)) { + return OPENGAUSS_POSTGRESQL_VERSION; + } else { + return OPENGAUSS; + } + } + + /** + * Sanitize excel sheet name. + * + * @param fileNameParam the file name param + * @return the string + */ + public static String sanitizeExcelSheetName(String fileNameParam) { + if (fileNameParam == null) { + return ""; + } + String fileName = fileNameParam; + Pattern pattern = Pattern.compile(".*[\\\\/:*?\"<>|\\[\\]'].*"); + + if (pattern.matcher(fileName).matches()) { + fileName = fileName.replaceAll("[\\\\/:*?\"<>|\\[\\]']", ""); + } + + pattern = Pattern.compile(".*[ ].*"); + if (pattern.matcher(fileName).matches()) { + fileName = fileName.replaceAll("[ ]", "_"); + } + + return fileName; + } + + /** + * Checks if is protocol version needed. + * + * @param driverName the driver name + * @return true, if is protocol version needed + */ + public static boolean isProtocolVersionNeeded(String driverName) { + if (driverName != null && (driverName.contains(MPPDBIDEConstants.GAUSS200V1R5DRIVER) + || driverName.contains(MPPDBIDEConstants.GAUSS200V1R6DRIVER))) { + return true; + } + return false; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/DateTimeFormatValidator.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/DateTimeFormatValidator.java new file mode 100644 index 0000000000000000000000000000000000000000..97780196fa4fb31dba8c01e40e490ab3ededcf97 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/DateTimeFormatValidator.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * + * Title: class + * + * Description: The Class DateTimeFormatValidator. + * + * @since 3.0.0 + */ +public class DateTimeFormatValidator { + public DateTimeFormatValidator() { + } + + /** + * validates date format + * + * @param format the date format + * @return true if date format is valid + */ + public static boolean validateDateFormat(String format) { + List dateFormatRegExList = new ArrayList(); + String dateFormatRegex1 = "^([y|Y]{2}|[y|Y]{4})(-|/|.|:|)([M]{2}|[m|M]{3})(-|/|.|:|)[d]{2}$"; + String dateFormatRegex2 = "^([y|Y]{2}|[y|Y]{4})(-|/|.|:|)[d]{2}(-|/|.|:|)([M]{2}|[M]{3})$"; + String dateFormatRegex3 = "^([M]{2}|[M]{3})(-|/|.|:|)([y|Y]{2}|[y|Y]{4})(-|/|.|:|)[d]{2}$"; + String dateFormatRegex4 = "^([M]{2}|[M]{3})(-|/|.|:|)[d]{2}(-|/|.|:|)([y|Y]{2}|[y|Y]{4})$"; + String dateFormatRegex5 = "^[d]{2}(-|/|.|:|)([y|Y]{2}|[y|Y]{4})(-|/|.|:|)([M]{2}|[M]{3})$"; + String dateFormatRegex6 = "^[d]{2}(-|/|.|:|)([M]{2}|[M]{3})(-|/|.|:|)([y|Y]{2}|[y|Y]{4})$"; + dateFormatRegExList.add(dateFormatRegex1); + dateFormatRegExList.add(dateFormatRegex2); + dateFormatRegExList.add(dateFormatRegex3); + dateFormatRegExList.add(dateFormatRegex4); + dateFormatRegExList.add(dateFormatRegex5); + dateFormatRegExList.add(dateFormatRegex6); + for (String df : dateFormatRegExList) { + Pattern pattern = Pattern.compile(df); + Matcher matcher = pattern.matcher(format); + if (matcher.matches()) { + return true; + } + } + return false; + } + + /** + * validates time format + * + * @param format the time format + * @return true if time format is valid + */ + public static boolean validateTimeFormat(String format) { + List timeFormatRegExList = new ArrayList(); + String timeFormatRegex1 = "^([h|H]{2})(:|)([m|M]{2})(:|)([s]{2})$"; + String timeFormatRegex2 = "^([h|H]{2})(:|)([m|M]{2})(:|)([s|S]{2})(.|)([s|S]{2}|[s|S]{3})$"; + String timeFormatRegex3 = "^([h|H]{2})(:|)([m|M]{2})$"; + timeFormatRegExList.add(timeFormatRegex1); + timeFormatRegExList.add(timeFormatRegex2); + timeFormatRegExList.add(timeFormatRegex3); + for (String timeformat : timeFormatRegExList) { + Pattern pattern = Pattern.compile(timeformat); + Matcher matcher = pattern.matcher(format); + if (matcher.matches()) { + return true; + } + } + return false; + } + + /** + * gets the DatePlusTimeFormat + * + * @param dateFormat the date format + * @param timeFormat the time format + * @return the date format + */ + public static String getDatePlusTimeFormat(String dateFormat, String timeFormat) { + StringBuilder format = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + format.append(dateFormat); + format.append(" " + timeFormat); + return format.toString(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/DsEncodingEnum.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/DsEncodingEnum.java new file mode 100644 index 0000000000000000000000000000000000000000..53adea04902057c761bddbfd2ab9e7b1b15cf4be --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/DsEncodingEnum.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +/** + * + * Title: enum + * + * Description: The Enum DsEncodingEnum. + * + * @since 3.0.0 + */ +public enum DsEncodingEnum { + UTF_8("UTF-8"), GBK("GBK"), LATIN1("LATIN1"); + + private final String value; + + /** + * Instantiates a new ds encoding enum. + * + * @param value the value + */ + private DsEncodingEnum(String value) { + this.value = value; + } + + /** + * Gets the encoding. + * + * @return the encoding + */ + public String getEncoding() { + return value; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/EnvirnmentVariableValidator.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/EnvirnmentVariableValidator.java new file mode 100644 index 0000000000000000000000000000000000000000..b9f2ae18130065108276a5ad529f4e257a64ee07 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/EnvirnmentVariableValidator.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +import java.text.Normalizer; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.opengauss.mppdbide.utils.files.FileValidationUtils; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: EnvirnmentVariableValidator + * + * @since 3.0.0 + */ +public class EnvirnmentVariableValidator { + /** + * validateAndGetJavaPath + * + * @return string value + */ + public static String validateAndGetLineSeperator() { + String lineSeperator = System.getProperty("line.separator"); + + if (lineSeperator != null && (lineSeperator.equals("\n") || lineSeperator.equals("\r\n") + || Integer.parseInt(lineSeperator) > 0)) { + return lineSeperator; + } + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.INVALID_LINE_SEPERATOR)); + return "\r\n"; + } + + /** + * validateAndGetJavaPath + * + * @return string value + */ + public static String validateAndGetUserName() { + String usrName = System.getProperty("user.name"); + String usrOsName = null; + if (usrName != null && usrName.length() <= 20) { + usrName = Normalizer.normalize(usrName, Normalizer.Form.NFD); + char[] usrNameArray = usrName.toCharArray(); + usrOsName = new String(usrNameArray); + Pattern pattern = Pattern.compile("\\[|\\]|\\:|\\;|\\||\\=|\\,|\\+|\\*|\\?|\\<|\\>|\\/|\\|\\\""); + Matcher matcher = pattern.matcher(usrOsName); + if (matcher.find()) { + MPPDBIDELoggerUtility.error("User name contains invalid special characters."); + return ""; + } else { + return new String(usrNameArray); + } + } else { + MPPDBIDELoggerUtility.error("User name length is more than allowed limit."); + return ""; + } + } + + /** + * validateAndGetJavaPath + * + * @return string value + */ + public static String validateAndGetJavaPath() { + String javaHomeStr = System.getProperty("java.home"); + if (javaHomeStr != null) { + javaHomeStr = Normalizer.normalize(System.getProperty("java.home"), Normalizer.Form.NFD); + if (FileValidationUtils.validateFilePathName(javaHomeStr)) { + return javaHomeStr; + } + } + return null; + } + + /** + * validateJavaVersion + * + * @return string value + */ + public static String validateJavaVersion() { + String javaVersion = System.getProperty("java.version"); + Pattern pattern = Pattern.compile("^[0-9][0-9._]*$"); + Matcher matcher = pattern.matcher(javaVersion); + if (matcher.matches()) { + return javaVersion; + } + MPPDBIDELoggerUtility.error("Invalid java version is set"); + return ""; + } + + /** + * validateAndGetFileSeperator + * + * @return string value + */ + public static String validateAndGetFileSeperator() { + String fileSeperator = System.getProperty("file.separator"); + if (fileSeperator != null && (fileSeperator.equals("\\") || fileSeperator.equals("/"))) { + return fileSeperator; + } + MPPDBIDELoggerUtility.error("Invalid file seperator is set"); + return MPPDBIDEConstants.FILE_SEPARATOR; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/ExpressionVisitorAdapterWrap.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/ExpressionVisitorAdapterWrap.java new file mode 100644 index 0000000000000000000000000000000000000000..f5d2c6527b2d877255872042324afd750afe1077 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/ExpressionVisitorAdapterWrap.java @@ -0,0 +1,305 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +import net.sf.jsqlparser.expression.AnalyticExpression; +import net.sf.jsqlparser.expression.AnyComparisonExpression; +import net.sf.jsqlparser.expression.CaseExpression; +import net.sf.jsqlparser.expression.CastExpression; +import net.sf.jsqlparser.expression.ExpressionVisitorAdapter; +import net.sf.jsqlparser.expression.ExtractExpression; +import net.sf.jsqlparser.expression.Function; +import net.sf.jsqlparser.expression.IntervalExpression; +import net.sf.jsqlparser.expression.JsonExpression; +import net.sf.jsqlparser.expression.KeepExpression; +import net.sf.jsqlparser.expression.NotExpression; +import net.sf.jsqlparser.expression.RowConstructor; +import net.sf.jsqlparser.expression.operators.arithmetic.Addition; +import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseAnd; +import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseLeftShift; +import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseOr; +import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseRightShift; +import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseXor; +import net.sf.jsqlparser.expression.operators.arithmetic.Concat; +import net.sf.jsqlparser.expression.operators.arithmetic.Division; +import net.sf.jsqlparser.expression.operators.arithmetic.Modulo; +import net.sf.jsqlparser.expression.operators.arithmetic.Multiplication; +import net.sf.jsqlparser.expression.operators.arithmetic.Subtraction; +import net.sf.jsqlparser.expression.operators.conditional.AndExpression; +import net.sf.jsqlparser.expression.operators.conditional.OrExpression; +import net.sf.jsqlparser.expression.operators.relational.Between; +import net.sf.jsqlparser.expression.operators.relational.EqualsTo; +import net.sf.jsqlparser.expression.operators.relational.GreaterThan; +import net.sf.jsqlparser.expression.operators.relational.GreaterThanEquals; +import net.sf.jsqlparser.expression.operators.relational.InExpression; +import net.sf.jsqlparser.expression.operators.relational.JsonOperator; +import net.sf.jsqlparser.expression.operators.relational.LikeExpression; +import net.sf.jsqlparser.expression.operators.relational.Matches; +import net.sf.jsqlparser.expression.operators.relational.MinorThan; +import net.sf.jsqlparser.expression.operators.relational.MinorThanEquals; +import net.sf.jsqlparser.expression.operators.relational.NotEqualsTo; +import net.sf.jsqlparser.expression.operators.relational.RegExpMatchOperator; +import net.sf.jsqlparser.statement.select.SubSelect; + +/** + * + * Title: class + * + * Description: The Class ExpressionVisitorAdapterWrap. + * + * @since 3.0.0 + */ +public class ExpressionVisitorAdapterWrap extends ExpressionVisitorAdapter { + private boolean hasNonEditableSelectItem = false; + + /** + * Checks for non editable select item. + * + * @return true, if successful + */ + public boolean hasNonEditableSelectItem() { + return this.hasNonEditableSelectItem; + } + + /** + * Reset has non editable select item. + */ + public void resetHasNonEditableSelectItem() { + this.hasNonEditableSelectItem = false; + } + + @Override + public void visit(Function function) { + this.hasNonEditableSelectItem = true; + super.visit(function); + } + + @Override + public void visit(Addition expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(Division expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(Multiplication expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(Subtraction expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(AndExpression expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(OrExpression expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(Between expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(EqualsTo expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(GreaterThan expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(GreaterThanEquals expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(InExpression expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(CaseExpression expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(LikeExpression expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(MinorThan expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(MinorThanEquals expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(NotEqualsTo expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(SubSelect subSelect) { + this.hasNonEditableSelectItem = true; + super.visit(subSelect); + } + + @Override + public void visit(AnyComparisonExpression expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(Concat expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(Matches expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(BitwiseAnd expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(BitwiseOr expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(BitwiseXor expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(CastExpression expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(Modulo expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(AnalyticExpression expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(ExtractExpression expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(IntervalExpression expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(RegExpMatchOperator expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(NotExpression notExpr) { + this.hasNonEditableSelectItem = true; + super.visit(notExpr); + } + + @Override + public void visit(JsonExpression jsonExpr) { + this.hasNonEditableSelectItem = true; + super.visit(jsonExpr); + } + + @Override + public void visit(JsonOperator expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(KeepExpression expr) { + this.hasNonEditableSelectItem = true; + super.visit(expr); + } + + @Override + public void visit(RowConstructor rowConstructor) { + this.hasNonEditableSelectItem = true; + super.visit(rowConstructor); + } + + @Override + public void visit(BitwiseRightShift expr) { + this.hasNonEditableSelectItem = true; + visitBinaryExpression(expr); + } + + @Override + public void visit(BitwiseLeftShift expr) { + this.hasNonEditableSelectItem = true; + visitBinaryExpression(expr); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/IMessagesConstants.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/IMessagesConstants.java new file mode 100644 index 0000000000000000000000000000000000000000..9ed69f4b5bf900edac773da187d0d58493296cdd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/IMessagesConstants.java @@ -0,0 +1,3018 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +/** + * Title: interface Description: The Interface IMessagesConstants. + * + * @since 3.0.0 + */ +public interface IMessagesConstants extends IMessagesConstantsOne { + + String SQL_PREVIEW = "SQL_PREVIEW"; + + String TABLE_CONS = "TABLE_CONS"; + + String OID_MSG = "OID_MSG"; + + String NAME_MSG = "NAME_MSG"; + + String ENCODING_MSG = "ENCODING_MSG"; + + String ALLOW_CON = "ALLOW_CON"; + + String CONNECTION_LIMIT = "CONNECTION_LIMIT"; + + String DFLT_TBSPACE = "DFLT_TBSPACE"; + + String COLLECTION_MSG = "COLLECTION_MSG"; + + String TABLESPACE_MSG = "TABLESPACE_MSG"; + + String CHAR_TYPE = "CHAR_TYPE"; + + String IS_TEMP = "IS_TEMP"; + + String TYEP_MSG = "TYEP_MSG"; + + String OWNER_MSG = "OWNER_MSG"; + + String PAGES_MSG = "PAGES_MSG"; + + String ROW_COUNT = "ROW_COUNT"; + + String HAS_INDEX = "HAS_INDEX"; + + String IS_SHARED = "IS_SHARED"; + + String OPTION_MSG = "OPTION_MSG"; + + String DESC_MSG = "DESC_MSG"; + + String NEGATIVE_NUMBER = "NEGATIVE_NUMBER"; + + String LOCALE_CHANGE_CONFIG_FILE = "LOCALE_CHANGE_CONFIG_FILE"; + + String LOCALE_CHANGE_CONFIG_ERR_TITLE = "LOCALE_CHANGE_CONFIG_ERR_TITLE"; + + String LOCALE_CHANGE_CONFIG_ERR_MES = "LOCALE_CHANGE_CONFIG_ERR_MES"; + + String LOCALE_CHANGE_RD_WD_ERROR = "LOCALE_CHANGE_RD_WD_ERROR"; + + String LOCALE_CHANGE_APP_RESTART_TITLE = "LOCALE_CHANGE_APP_RESTART_TITLE"; + + String LOCALE_CHANGE_APP_RESTART_MSG = "LOCALE_CHANGE_APP_RESTART_MSG"; + + String TYPE_ALIGN = "TYPE_ALIGN"; + + String FUNCTION_PROCEDURE_NAME = "FUNCTION_PROCEDURE_NAME"; + + String TABLES_NAME = "TABLES_NAME"; + + String DATATYPE_NAME = "DATATYPE_NAME"; + + String ACCESS_METHOD_NAME = "ACCESS_METHOD_NAME"; + + String COLUMNS_NAME = "COLUMNS_NAME"; + + String CONSTRAINTS_NAME = "CONSTRAINTS_NAME"; + + String INDEXES_NAME = "INDEXES_NAME"; + + String TITLE_IMPORT_TBL_DATA = "TITLE_IMPORT_TBL_DATA"; + + String MSG_IMPORT_SUCCESS = "MSG_IMPORT_SUCCESS"; + + String MSG_TOTAL_ROWS_IMPORT = "MSG_TOTAL_ROWS_IMPORT"; + + String ERR_IMPORT_TABLE_TO_CSV = "ERR_IMPORT_TABLE_TO_CSV"; + + String ERR_IMPORT_TABLE_TO_CSV_HANDLER = "ERR_IMPORT_TABLE_TO_CSV_HANDLER"; + + String STATUS_MSG_IMPORT_TABLE_DATA = "STATUS_MSG_IMPORT_TABLE_DATA"; + + String BTN_OK = "BTN_OK"; + + String BTN_CANCEL = "BTN_CANCEL"; + + String BTN_CLEAR = "BTN_CLEAR"; + + String MSG_DS_NO_DATA_ENCRYPT_DISCLAIMER = "MSG_DS__NO_DATA_ENCRYPT_DISCLAIMER"; + + String MSG_DS_NO_DATA_ENCRYPT_DISCLAIMER_SECONDPART2 = "MSG_DS__NO_DATA_ENCRYPT_DISCLAIMER_SECONDPART2"; + + String MSG_DO_NOT_SHOW_AGAIN = "MSG_DO_NOT_SHOW_AGAIN"; + + String TITLE_DISCLAIMER = "TITLE_DISCLAIMER"; + + String TITLE_OPEN_SQL = "TITLE_OPEN_SQL"; + + String MSG_SELECT_SQL_FILE = "MSG_SELECT_SQL_FILE"; + + String MSG_SELECT_FILE_DOES_NOT_EXIST = "MSG_SELECT_FILE_DOES_NOT_EXIST"; + + String MSG_NEED_APPEND_OVERWRITE = "MSG_NEED_APPEND_OVERWRITE"; + + String BTN_LABEL_APPEND = "BTN_LABEL_APPEND"; + + String BTN_LABEL_OVERWRITE = "BTN_LABEL_OVERWRITE"; + + String MSG_APPEND_OVERWRITE_SUCCESS = "MSG_APPEND_OVERWRITE_SUCCESS"; + + String ERR_OUT_OF_MEMORY_OCCURED = "ERR_OUT_OF_MEMORY_OCCURED"; + + String ERR_OUT_OF_MEMORY_SEARCH_OCCURED = "ERR_OUT_OF_MEMORY_SEARCH_OCCURED"; + + String TITLE_OUT_OF_MEMORY = "TITLE_OUT_OF_MEMORY"; + + String TITLE_SAVE_SQL = "TITLE_SAVE_SQL"; + + String MSG_SQL_SAVE_SUCCESS = "MSG_SQL_SAVE_SUCCESS"; + + String MSG_EXPORT_SUCC_FILE = "MSG_EXPORT_SUCC_FILE"; + + String MSG_EXPORT_EXEC_SUCC_FILE = "MSG_EXPORT_EXEC_SUCC_FILE"; + + String TITLE_EXPORT_IN_PROGRESS = "TITLE_EXPORT_IN_PROGRESS"; + + String ERR_WHILE_EXPORTING = "ERR_WHILE_EXPORTING"; + + String CIPHER_EXPIRE_CONFIRMATION = "CIPHER_EXPIRE_CONFIRMATION"; + + String CIPHER_EXPIRED = "CIPHER_EXPIRED"; + + String CIPHER_YET_TO_EXPIRE = "CIPHER_YET_TO_EXPIRE"; + + String MSG_LOADED = "MSG_LOADED"; + + String FILE_PERMISSION = "FILE_PERMISSION"; + + String FILE_PERMISSION_ERROR = "FILE_PERMISSION_ERROR"; + + String ERR_SQL_FILE_READ = "ERR_SQL_FILE_READ"; + + String ERR_OUT_OF_MEMORY_REOCCURED = "ERR_OUT_OF_MEMORY_REOCCURED"; + + String MSG_TOTAL_ROWS_EXPORT = "MSG_TOTAL_ROWS_EXPORT"; + + String TITLE_EXPORT_DATA = "TITLE_EXPORT_DATA"; + + String INCORRECT_PATH = "INCORRECT_PATH"; + + String INCORRECT_PATH_MSG = "INCORRECT_PATH_MSG"; + + String ERR_GUI_DEBUG_CONNECTION_ERROR = "ERR_GUI_DEBUG_CONNECTION_ERROR"; + + String SET_TABLESPACE_FROM_CURRENT_NULL = "SET_TABLESPACE_FROM_CURRENT_NULL"; + + String SET_TABLESPACE_ERROR_NULL = "SET_TABLESPACE_ERROR_NULL"; + + String SET_TABLE_FROM_TABLESPACE_NULL = "SET_TABLE_FROM_TABLESPACE_NULL"; + + String ERR_SAVE_SQL_HANDLER = "ERR_SAVE_SQL_HANDLER"; + + String ERR_IO_ERROR_EXPORT = "ERR_IO_ERROR_EXPORT"; + + String SQL_TERMINAL_EXEC = "SQL_TERMINAL_EXEC"; + + String IO_EXCEPTION_WHILE_EXPORT = "IO_EXCEPTION_WHILE_EXPORT"; + + String EMPTY_PLSOURCE_TITEL = "EMPTY_PLSOURCE_TITEL"; + + String EMPTY_PLSOURCE_VIEWER = "EMPTY_PLSOURCE_VIEWER"; + + String NAMESPACE_RETRIVE_ERROR = "NAMESPACE_RETRIVE_ERROR"; + + String TABLE_RETRIVE_ERROR = "TABLE_RETRIVE_ERROR"; + + String SQL_QUREY_CANCEL_MSG = "SQL_QUREY_CANCEL_MSG"; + + String SQL_QUERY_CANCEL_CANCELMSG = "SQL_QUERY_CANCEL_CANCELMSG"; + + String SQL_QUERY_CANCELMSG_PROGRESS = "SQL_QUERY_CANCELMSG_PROGRESS"; + + String UI_CANCEL_QUERY = "UI_CANCEL_QUERY_MSG"; + + String SQL_BUTTON_TOOL_TIP = "SQL_BUTTON_TOOL_TIP"; + + String ERR_DS_SECURITY_ERROR = "ERR_DS_SECURITY_ERROR"; + + String EDIT_DATA_WIZARD_TITLE = "EDIT_DATA_WIZARD_TITLE"; + + String CANCEL_OPERATION_TITLE = "CANCEL_OPERATION_TITLE"; + + String CANCEL_OPERATION_MSG = "CANCEL_OPERATION_MSG"; + + String CANCEL_EXPORT_SUCCES_DAILOG_TITLE = "CANCEL_EXPORT_SUCCES_DAILOG_TITLE"; + + String CANCEL_EXPORT_FAIL_DAILOG_TITLE = "CANCEL_EXPORT_FAIL_DAILOG_TITLE"; + + String CANCEL_EXPORT_JOB_NAME = "CANCEL_EXPORT_JOB_NAME"; + + String CANCEL_EXPORT_SUCCES_CONSOLE_MESSAGE = "CANCEL_EXPORT_SUCCES_CONSOLE_MESSAGE"; + + String CANCEL_IMPORT_SUCCES_DAILOG_TITLE = "CANCEL_IMPORT_SUCCES_DAILOG_TITLE"; + + String CANCEL_IMPORT_FAIL_DAILOG_TITLE = "CANCEL_IMPORT_FAIL_DAILOG_TITLE"; + + String CANCEL_IMPORT_JOB_NAME = "CANCEL_IMPORT_JOB_NAME"; + + String CANCEL_IMPORT_SUCCES_CONSOLE_MESSAGE = "CANCEL_IMPORT_SUCCES_CONSOLE_MESSAGE"; + + String CANCEL_IMPORTEXPORT_CONSOLE = "CANCEL_IMPORTEXPORT_CONSOLE"; + + String CANCEL_IMPORTEXPORT_CONSOLE_MSG = "CANCEL_IMPORTEXPORT_CONSOLE_MSG"; + + String CANCEL_IMPORT_CANCELMSG = "CANCEL_IMPORT_CANCELMSG"; + + String CANCEL_EXPORT_CANCELMSG = "CANCEL_EXPORT_CANCELMSG"; + + String CANCEL_WINDOW_TITLE = "CANCEL_WINDOW_TITLE"; + + String NO_PROPOSAL = "NO_PROPOSAL"; + + String AUTO_SUGGEST_LOADING = "AUTO_SUGGEST_LOADING"; + + String SQL_QUERY_EXECUTE = "SQL_QUERY_EXECUTE"; + + String STATUS_JOB_SI = "STATUS_JOB_SI"; + + String STATUS_JOB = "STATUS_JOB"; + + String DS_EXIT_MSG_FOR_JOBS = "DS_EXIT_MSG_FOR_JOBS"; + + String CANCEL_PROGRESS_TABLE_HEARDER = "CANCEL_PROGRESS_TABLE_HEARDER"; + + String DS_EXIT_CONFIRMATION_TITLE = "DS_EXIT_CONFIRMATION_TITLE"; + + String ERROR_READING_DATA = "ERROR_READING_DATA"; + + String DISCARD_CHANGES_TITLE = "DISCARD_CHANGES_TITLE"; + + String SAVE_CHANGES_TITLE = "SAVE_CHANGES_TITLE"; + + String EXPORT_CHANGES_TITLE = "EXPORT_CHANGES_TITLE"; + + String COPY_ADVANCED_RESULT_WINDOW_CONTENTS = "COPY_ADVANCED_RESULT_WINDOW_CONTENTS"; + + String COPY_RESULT_WINDOW_CONTENTS = "COPY_RESULT_WINDOW_CONTENTS"; + + String EXPORT_EXEC = "EXPORT_EXEC"; + + String EXPORT_CSV = "EXPORT_CSV"; + + String EXPORT_CSV_STAR = "EXPORT_CSV_STAR"; + + String CLEAR_CONSOLE = "CLEAR_CONSOLE"; + + String MENU_OPEN = "MENU_OPEN"; + + String MENU_SAVE = "MENU_SAVE"; + + String MENU_SAVE_AS = "MENU_SAVE_AS"; + + String MENU_FIND = "MENU_FIND"; + + String TABLESPACES_NAME = "TABLESPACES_NAME"; + + String DATABASES_NAME = "DATABASES_NAME"; + + String USER_NAMESPACE_NAME = "USER_NAMESPACE_NAME"; + + String SYSTEM_NAMESPACE_NAME = "SYSTEM_NAMESPACE_NAME"; + + String STATUS_MSG_DROP_TABLESPACE = "STATUS_MSG_DROP_TABLESPACE"; + + String DROP_TABLESPACE_DIA_TITLE = "DROP_TABLESPACE_DIA_TITLE"; + + String DROP_TABLESPACE = "DROP_TABLESPACE"; + + String DROP_TABLESPACE_SUCCESS = "DROP_TABLESPACE_SUCCESS"; + + String ERR_WHEN_DROPPING_TABLESPACE = "ERR_WHEN_DROPPING_TABLESPACE"; + + String ERR_WHILE_DROPPING_TABLESPACE_MESSAGE = "ERR_WHILE_DROPPING_TABLESPACE_MESSAGE"; + + String CONNECTION_ERR_WHEN_DROPPING_TABLESPACE = "CONNECTION_ERR_WHEN_DROPPING_TABLESPACE"; + + String STATUS_MSG_CREATE_TABLESPACE = "STATUS_MSG_CREATE_TABLESPACE"; + + String CREATE_TABLESPACE_DIA_TITILE = "CREATE_TABLESPACE_DIA_TITILE"; + + String TABLESPACE_SUCCESSFULLY = "TABLESPACE_SUCCESSFULLY"; + + String CREATING_TABLESPACE = "CREATING_TABLESPACE"; + + String CONNECTION_ERROR_DURING_TABLESPACE_CREATION = "CONNECTION_ERROR_DURING_TABLESPACE_CREATION"; + + String ERROR_WHILE_CREATING_TABLESPACE = "ERROR_WHILE_CREATING_TABLESPACE"; + + String STATUS_MSG_RENAME_TABLESPACE = "STATUS_MSG_RENAME_TABLESPACE"; + + String RENAME_TABLESPACE_NEW_NAME = "RENAME_TABLESPACE_NEW_NAME"; + + String RENAME_TABLESPACE_WAIT = "RENAME_TABLESPACE_WAIT"; + + String RENAME_TABLESPACE_DIA_TITILE = "RENAME_TABLESPACE_DIA_TITILE"; + + String RENAME_TABLESPACE_NEW = "RENAME_TABLESPACE_NEW"; + + String RENAME_TABLESPACE_TO = "RENAME_TABLESPACE_TO"; + + String CONNECTION_ERR_DURING_RENAMING_TABLESPACE = "CONNECTION_ERR_DURING_RENAMING_TABLESPACE"; + + String ERR_WHILE_RENAMING_TABLESPACE = "ERR_WHILE_RENAMING_TABLESPACE"; + + String SET_TABLESPACE_OPTION = "SET_TABLESPACE_OPTION"; + + String SET_TABLESPACE_OPTION_SUCCESS = "SET_TABLESPACE_OPTION_SUCCESS"; + + String SET_TABLESPACE_OPTION_ERROR = "SET_TABLESPACE_OPTION_ERROR"; + + String STATUS_MSG_OPTION_TABLESPACE = "STATUS_MSG_OPTION_TABLESPACE"; + + String CONNECTION_ERR_DURING_SETTING_TABLESPACE_OPTION = "CONNECTION_ERR_DURING_SETTING_TABLESPACE_OPTION"; + + String STATUS_MSG_RESIZE_TABLESPACE = "STATUS_MSG_RESIZE_TABLESPACE"; + + String SET_MAX_SIZE = "SET_MAX_SIZE"; + + String RESIZE_TABLESPACE_NEW_NAME = "RESIZE_TABLESPACE_NEW_NAME"; + + String RESIZE_TABLESPACE_SUCCESS = "RESIZE_TABLESPACE_SUCCESS"; + + String CONNECTION_ERR_DURING_RESIZING_TABLESPACE = "CONNECTION_ERR_DURING_RESIZING_TABLESPACE"; + + String SET_TABLESPACE_RESIZING_ERROR = "SET_TABLESPACE_RESIZING_ERROR"; + + String TITLE_DS_SECURITY = "TITLE_DS_SECURITY"; + + String SECURITY_FAILURE_SUGGESTION = "SECURITY_FAILURE_SUGGESTION"; + + String PREF_SYNTAX_COLORING_TITLE = "PREF_SYNTAX_COLORING_TITLE"; + + String PREF_SYNTAX_COLORING_MSG = "PREF_SYNTAX_COLORING_MSG"; + + String PREF_SYNTAX_COLORING_SINGLE_LINE_COMM = "PREF_SYNTAX_COLORING_SINGLE_LINE_COMM"; + + String PREF_SYNTAX_COLORING_DEFAULT = "PREF_SYNTAX_COLORING_DEFAULT"; + + String PREF_SYNTAX_COLORING_UNRESERVED_KEY = "PREF_SYNTAX_COLORING_UNRESERVED_KEY"; + + String PREF_SYNTAX_COLORING_RESERVED_KEY = "PREF_SYNTAX_COLORING_RESERVED_KEY"; + + String PREF_SYNTAX_COLORING_TYPE = "PREF_SYNTAX_COLORING_TYPE"; + + String PREF_SYNTAX_COLORING_PREDICATE = "PREF_SYNTAX_COLORING_PREDICATE"; + + String PREF_SYNTAX_COLORING_CONSTANTS = "PREF_SYNTAX_COLORING_CONSTANTS"; + + String PREF_SYNTAX_COLORING_STRINGS = "PREF_SYNTAX_COLORING_STRINGS"; + + String PREF_SYNTAX_COLORING_SAVE_FAIL_MSG = "PREF_SYNTAX_COLORING_SAVE_FAIL_MSG"; + + String PREF_SYNTAX_COLORING_LOAD_FAIL_MSG = "PREF_SYNTAX_COLORING_LOAD_FAIL_MSG"; + + String PREF_SYNTAX_COLORING_SAVE_FAIL_TITLE = "PREF_SYNTAX_COLORING_SAVE_FAIL_TITLE"; + + String PREF_SYNTAX_COLORING_LOAD_FAIL_TITLE = "PREF_SYNTAX_COLORING_LOAD_FAIL_TITLE"; + + String DATABASE_ENCODING = "DATABASE_ENCODING"; + + String DATABASE_CONNECTION_LIMIT_REACHED = "DATABASE_CONNECTION_LIMIT_REACHED"; + + String VIEWS_NAME = "VIEWS_NAME"; + + String VIEW_COLUMNS_NAME = "VIEW_COLUMNS_NAME"; + + String DROP_VIEW_SUCCESS = "DROP_VIEW_SUCCESS"; + + String DROP_VIEW_CASCADE_SUCCESS = "DROP_VIEW_CASCADE_SUCCESS"; + + String DROP_VIEW_FAILURE_TITLE = "DROP_VIEW_FAILURE_TITLE"; + + String DROP_VIEW_UNABLE_MSG = "DROP_VIEW_UNABLE_MSG"; + + String DROP_VIEW_FAILURE = "DROP_VIEW_FAILURE"; + + String RENAME_VIEW_SUCCESS = "RENAME_VIEW_SUCCESS"; + + String RENAME_VIEW_TITLE = "RENAME_VIEW_TITLE"; + + String RENAME_VIEW_FAILURE = "RENAME_VIEW_FAILURE"; + + String ENTER_NEW_VIEW_NAME = "ENTER_NEW_VIEW_NAME"; + + String SET_VIEW_SCHEMA_SUCCESS = "SET_VIEW_SCHEMA_SUCCESS"; + + String SET_VIEW_SCHEMA = "SET_VIEW_SCHEMA"; + + String SET_VIEW_MESSAGE = "SET_VIEW_MESSAGE"; + + String SET_VIEW_SCHEMA_FAILURE = "SET_VIEW_SCHEMA_FAILURE"; + + String SET_VIEW_SCHEMA_MOVING = "SET_VIEW_SCHEMA_MOVING"; + + String DROP_VIEW_CONFIRM_TITLE = "DROP_VIEW_CONFIRM_TITLE"; + + String DROP_VIEW_CONFIRM_MSG = "DROP_VIEW_CONFIRM_MSG"; + + String DROP_VIEW_CASCADE_CONFIRM_MSG = "DROP_VIEW_CASCADE_CONFIRM_MSG"; + + String VIEW_COLUMN_SET_DEFAULT_TITLE = "VIEW_COLUMN_SET_DEFAULT_TITLE"; + + String SET_VIEW_COL_DEFAULT_STATUS_BAR = "SET_VIEW_COL_DEFAULT_STATUS_BAR"; + + String CONSOLE_TAB = "CONSOLE_TAB"; + + String RESULT_TAB = "RESULT_TAB"; + + String EXECUTION_PLAN_TAB = "EXECUTION_PLAN_TAB"; + + String ERR_DROP_CON_PROF_FILE = "ERR_DROP_CON_PROF_FILE"; + + String ERR_PROFILE_WRITE_DISK = "ERR_PROFILE_WRITE_DISK"; + + String ERR_PROFILE_WRITE_INVALID = "ERR_PROFILE_WRITE_INVALID"; + + String PERMANENTLY = "PERMANENTLY"; + + String CURRENT_SESSION_ONLY = "CURRENT_SESSION_ONLY"; + + String DO_NOT_SAVE = "DO_NOT_SAVE"; + + String CONNECTION_NAME = "CONNECTION_NAME"; + + String CONNECTION_DETAILS = "CONNECTION_DETAILS"; + + String LOAD_SQL_TERMINAL = "LOAD_SQL_TERMINAL"; + + String LOAD_TERMINAL_CLOSE_HISTORY = "LOAD_TERMINAL_CLOSE_HISTORY"; + + String DELETE_SQL = "DELETE_SQL"; + + String DELETE_ALL = "DELETE_ALL"; + + String PIN_SQL = "PIN_SQL"; + + String SQL_STATEMENT = "SQL_STATEMENT"; + + String SQL_ROW_SELECTION = "SQL_ROW_SELECTION"; + + String DATABASE_NAME = "DATABASE_NAME"; + + String START_TIME = "START_TIME"; + + String ELAPSED_TIME = "ELAPSED_TIME"; + + String FINAL_STATUS = "FINAL_STATUS"; + + String PIN_STATUS = "PIN_STATUS"; + + String PROFILE_NAME = "PROFILE_NAME"; + + String UNPIN_SQL = "UNPIN_SQL"; + + String SERIAL_NO = "SERIAL_NO"; + + String SQL_HISTORY_TITLE = "SQL_HISTORY_TITLE"; + + String SQL_HISTORY_TOOL_TRIP = "SQL_HISTORY_TOOL_TRIP"; + + String SQL_HISTORY_DISABLED_TOOL_TIP = "SQL_HISTORY_DISABLED_TOOL_TIP"; + + String SQL_AUTOCOMMIT_ON_TOOL_TIP = "SQL_AUTOCOMMIT_ON_TOOL_TIP"; + + String SQL_AUTOCOMMIT_OFF_TOOL_TIP = "SQL_AUTOCOMMIT_OFF_TOOL_TIP"; + + String SQL_AUTOCOMMIT_DISABLED_TOOL_TIP = "SQL_AUTOCOMMIT_DISABLED_TOOL_TIP"; + + String ERR_SQL_AUTOCOMMIT_TOGGLE_TITLE = "ERR_SQL_AUTOCOMMIT_TOGGLE_TITLE"; + + String ERR_SQL_AUTOCOMMIT_TOGGLE = "ERR_SQL_AUTOCOMMIT_TOGGLE"; + + String SQL_AUTOCOMMIT_SAVE_CHANGES_TITLE = "SQL_AUTOCOMMIT_SAVE_CHANGES_TITLE"; + + String SQL_AUTOCOMMIT_SAVE_CHANGES_MSG = "SQL_AUTOCOMMIT_SAVE_CHANGES_MSG"; + + String DELETE_SELECTED_HISTORY_ALERT = "DELETE_SELECTED_HISTORY_ALERT"; + + String DELETE_ALL_HISTORY_ALERT = "DELETE_ALL_HISTORY_ALERT"; + + String SELECT_QUERY_TO_DELETE = "SELECT_QUERY_TO_DELETE"; + + String PREFERENCE_EXAMPLE = "PREFERENCE_EXAMPLE"; + + String SQL_DATA = "SQL_DATA"; + + String SQL_DDL = "SQL_DDL"; + + String SQL_DDL_DATA = "SQL_DDL_DATA"; + + String EXPORT_DDL_HEADER = "EXPORT_DDL_HEADER"; + + String EXPORT_DDL_FAIL_HEADER = "EXPORT_DDL_FAIL_HEADER"; + + String EXPORT_DDL_SUCCESS = "EXPORT_DDL_SUCCESS"; + + String EXPORT_DDL_FAIL = "EXPORT_DDL_FAIL"; + + String EXPORT_FAIL_DISK_WRITE_ERROR = "EXPORT_FAIL_DISK_WRITE_ERROR"; + + String EXPORT_FAIL_PROCESS_INTRUPTED = "EXPORT_FAIL_PROCESS_INTRUPTED"; + + String EXPORT_FAIL_UNSUPPORTED_SERVER_VERSION = "EXPORT_FAIL_UNSUPPORTED_SERVER_VERSION"; + + String CANNOT_LOCATE_GSDUMP = "CANNOT_LOCATE_GSDUMP"; + + String EXPORT_CANCEL_ON_USER_REQUEST = "EXPORT_CANCEL_ON_USER_REQUEST"; + + String HISTORY_LOADING_IN_PROGRESS_TILTLE = "HISTORY_LOADING_IN_PROGRESS_TILTLE"; + + String CONN_PROFILE_ERROR_MSG = "CONN_PROFILE_ERROR_MSG"; + + String REMOVE_CONN_TITLE = "REMOVE_CONN_TITLE"; + + String REMOVE_CONN_MSG = "REMOVE_CONN_MSG"; + + String SELECT_CONN_TO_REMOVE = "SELECT_CONN_TO_REMOVE"; + + String REMOVE_PROFILE = "REMOVE_PROFILE"; + + String HELP_LABEL = "HELP_LABEL"; + + String TABLESPACE_NAME = "TABLESPACE_NAME"; + + String TABLESPACE_LOCATION = "TABLESPACE_LOCATION"; + + String TABLESPACE_MAXSIZE = "TABLESPACE_MAXSIZE"; + + String TABLESPACE_SEQCOST = "TABLESPACE_SEQCOST"; + + String TABLESPACE_RANCOST = "TABLESPACE_RANCOST"; + + String TABLESPACE_UNSUPPORTED_SERVER_VERSION = "TABLESPACE_UNSUPPORTED_SERVER_VERSION"; + + String TABLESPACE_RELATIVE_PATH = "TABLESPACE_RELATIVE_PATH"; + + String TABLESPACE_GENERAL = "TABLESPACE_GENERAL"; + + String TABLE_EDIT_MESSAGE = "TABLE_EDIT_MESSAGE"; + + String UNLIMITED_SIZE = "UNLIMITED_SIZE"; + + String CIPHER_DECRYPT_ERROR_MSG = "CIPHER_DECRYPT_ERROR_MSG"; + + String TABLESPACE_CREATION_SUCCEEDED = "TABLESPACE_CREATION_SUCCEEDED"; + + String TABLESPACE_CREATION_FAILED = "TABLESPACE_CREATION_FAILED"; + + String RUN_IN_BACK_GROUND = "RUN_IN_BACK_GROUND"; + + String CONN_DIALOG_SAVE_CIPHER = "CONN_DIALOG_SAVE_CIPHER"; + + String SHORTCUT_MAPPER = "SHORTCUT_MAPPER"; + + String SELECT_SHORTCUTKEY = "SELECT_SHORTCUTKEY"; + + String MODIFY_KEY = "MODIFY_KEY"; + + String UNBIND_KEY = "UNBIND_KEY"; + + String KEY_NAME = "KEY_NAME"; + + String BINDING_KEY = "BINDING_KEY"; + + String COMMAND_NAME = "COMMAND_NAME"; + + String KEY_BINDING = "KEY_BINDING"; + + String KEY_DESCRIPTION = "KEY_DESCRIPTION"; + + String PREFERENCES_SHOW = "PREFERENCES_SHOW"; + + String DB_CONN_REM_PSW = "DB_CONN_REM_PSW"; + + String PREF_LOAD_MSG = "PREF_LOAD_MSG"; + + String PREF_LOAD_ERROR = "PREF_LOAD_ERROR"; + + String PREF_FILE_ERR_TITLE = "PREF_FILE_ERR_TITLE"; + + String PREF_FILE_ERR_MSG = "PREF_FILE_ERR_MSG"; + + String PINNED_DELETION = "PINNED_DELETION"; + + String PREFERENCE_DEFAULT = "PREFERENCE_DEFAULT"; + + String PREFERENCE_APPLY = "PREFERENCE_APPLY"; + + String PREFERENCEDIALOG_OK = "PREFERENCEDIALOG_OK"; + + String PREFERENCEDIALOG_CANCEL = "PREFERENCEDIALOG_CANCEL"; + + String INVALID_USERNAME_MSG = "INVALID_USERNAME_MSG"; + + String CREATE_TABLE_EMPTY_COLUMN = "CREATE_TABLE_EMPTY_COLUMN"; + + String LOADING_NS = "LOADING_NS"; + + String SHOW_MORE_OBJECTS = "SHOW_MORE_OBJECTS"; + + String INVALID_LOGGINGLEVEL = "INVALID_LOGGINGLEVEL"; + + String GO_TO_LINE_POPUP_TITLE = "GO_TO_LINE_POPUP_TITLE"; + + String ERROR_MESSAGE_FOR_GO_TO_LINE = "INVALID_INPUT_FOR_GO_TO_LINE"; + + String UPPER_CASE = "uppercase"; + + String LOWER_CASE = "lowercase"; + + String IMPORTEXPORT_VALIDATION_OTHER = "IMPORTEXPORT_VALIDATION_OTHER"; + + String IMPORTEXPORT_VALIDATION_NULL_STRING = "IMPORTEXPORT_VALIDATION_NULL_STRING"; + + String IMPORTEXPORT_VALIDATION_NULL_LENGTH = "IMPORTEXPORT_VALIDATION_NULL_LENGTH"; + + String IMPORTEXPORT_VALIDATION_DELIMITER_LENGTH = "IMPORTEXPORT_VALIDATION_DELIMITER_LENGTH"; + + String IMPORTEXPORT_VALIDATION_NULL_AS_DELIMITOR = "IMPORTEXPORT_VALIDATION_NULL_AS_DELIMITOR"; + + String IMPORTEXPORT_VALIDATION_NULL_AS_QUOTE = "IMPORTEXPORT_VALIDATION_NULL_AS_QUOTE"; + + String IMPORTEXPORT_VALIDATION_QUOTE_SINGLE_CHAR = "IMPORTEXPORT_VALIDATION_QUOTE_SINGLE_CHAR"; + + String IMPORTEXPORT_VALIDATION_QUOTE_AS_DELI = "IMPORTEXPORT_VALIDATION_QUOTE_AS_DELI"; + + String EXPORT_VALIDATION_QUOTE_NO_COLS_SELECTED = "EXPORT_VALIDATION_QUOTE_NO_COLS_SELECTED"; + + String IMPORT_VALIDATION_QUOTE_NO_COLS_SELECTED = "IMPORT_VALIDATION_QUOTE_NO_COLS_SELECTED"; + + String IMPORTEXPORT_VALIDATION_QUOTE_AS_ESCAPE = "IMPORTEXPORT_VALIDATION_QUOTE_AS_ESCAPE"; + + String EXPORT_OPTION_TITLE = "EXPORT_OPTION_TITLE"; + + String IMPORT_OPTION_TITLE = "IMPORT_OPTION_TITLE"; + + String EXPORT_ERROR = "EXPORT_ERROR"; + + String IMPORT_ERROR = "IMPORT_ERROR"; + + String OPTION_DELIMITER = "OPTION_DELIMITER"; + + String OPTION_FORMAT = "OPTION_FORMAT"; + + String OPTION_HEADER = "OPTION_HEADER"; + + String OPTION_QUOTE = "OPTION_QUOTE"; + + String OPTION_ESCAPE = "OPTION_ESCAPE"; + + String OPTION_TOOLTIP = "OPTION_TOOLTIP"; + + String OPTION_REPLACE_NULL = "OPTION_REPLACE_NULL"; + + String OPTION_REPLACE_WITHNULL = "OPTION_REPLACE_WITHNULL"; + + String OPTION_NULL_TOOLTIP = "OPTION_NULL_TOOLTIP"; + + String OPTION_ENCODING = "OPTION_ENCODING"; + + String OPTION_OTHERTOOLTIP = "OPTION_OTHERTOOLTIP"; + + String OPTION_SELECTCOLUMNS = "OPTION_SELECTCOLUMNS"; + + String OPTION_ALLCOLUMNS = "OPTION_ALLCOLUMNS"; + + String OPTION_SELECTED_COL = "OPTION_SELECTED_COL"; + + String OPTION_AVAILABLE_COL = "OPTION_AVAILABLE_COL"; + + String OPTION_I_AGREE = "OPTION_I_AGREE"; + + String IMPORT_FILE_BROWSE = "IMPORT_FILE_BROWSE"; + + String IMPORT_DATA_FILE = "IMPORT_DATA_FILE"; + + String ENTER_LINE_NUMBER = "ENTER_LINE_NUMBER"; + + String RESULT_WINDOW_QUERY_SUBMIT_TIME = "RESULT_WINDOW_QUERY_SUBMIT_TIME"; + + String RESULT_WINDOW_EXECUTION_TIME = "RESULT_WINDOW_EXECUTION_TIME"; + + String RESULT_WINDOW_RECORD_FETCHED = "RESULT_WINDOW_RECORD_FETCHED"; + + String RESULT_WINDOW_ROWS_FETCHED = "RESULT_WINDOW_ROWS_FETCHED"; + + String RESULT_WINDOW_EXECUTED_QUERY_TOOLTIP = "RESULT_WINDOW_EXECUTED_QUERY_TOOLTIP"; + + String RESULT_WINDOW_RECORD_MORE = "RESULT_WINDOW_RECORD_MORE"; + + String RESULT_WINDOW_EDITTABLE_COMMIT_SUCCESS = "RESULT_WINDOW_EDITTABLE_COMMIT_SUCCESS"; + + String RESULT_WINDOW_EDITTABLE_COMMIT_FAILURE = "RESULT_WINDOW_EDITTABLE_COMMIT_FAILURE"; + + String RESULT_WINDOW_EDITTABLE_COMMIT_UPDATED = "RESULT_WINDOW_EDITTABLE_COMMIT_UPDATED"; + + String RESULT_WINDOW_EDITTABLE_COMMIT_REFRESH = "RESULT_WINDOW_EDITTABLE_COMMIT_REFRESH"; + + String PARTITION_TABLE_GROUP = "PARTITION_TABLE_GROUP"; + + String PARTITION_GROUP_NAME = "PARTITION_GROUP_NAME"; + + String FOREIGN_TABLE_GROUP = "FOREIGN_TABLE_GROUP"; + + String LAST_SUCCESSFULL_LOGIN_MESSAGE = "LAST_SUCCESSFULL_LOGIN_MESSAGE"; + + String LAST_FAILURE_LOGIN_MESSAGE = "LAST_FAILURE_LOGIN_MESSAGE"; + + String DATA_STUDIO_NOTIFIFICATIONS = "DATA_STUDIO_NOTIFIFICATIONS"; + + String LAST_LOGIN_MESSAGE = "LAST_LOGIN_MESSAGE"; + + String LOGIN_NOTIFICATION_STARTED = "LOGIN_NOTIFICATION_STARTED"; + + String LOGIN_NOTIFICATION_ENDED = "LOGIN_NOTIFICATION_ENDED"; + + String DATABASE_NAME_NOTIFICATION = "DATABASE_NAME_NOTIFICATION"; + + String RESULT_WINDOW_RECORD_FETCHED_ALL = "RESULT_WINDOW_RECORD_FETCHED_ALL"; + + String CREATE_FUNCTION_PROCEDURE = "CREATE_FUNCTION_PROCEDURE"; + + String INFO_MAX_RESULT_SOURCE_VIEWER = "INFO_MAX_RESULT_SOURCE_VIEWER"; + + String ERR_TITLE_CREATE_FILE_DIRECTORY = "ERR_TITLE_CREATE_FILE_DIRECTORY"; + + String ERR_BL_CREATE_FILE_DIRECTORY = "ERR_BL_CREATE_FILE_DIRECTORY"; + + String ERR_TITLE_LAUNCH_DATASTUDIO = "ERR_TITLE_LAUNCH_DATASTUDIO"; + + String ERR_BL_LAUNCH_MULTIPLE_INSTANCE_DATASTUDIO = "ERR_BL_LAUNCH_MULTIPLE_INSTANCE_DATASTUDIO"; + + String MPPDBIDE_DIA_BTN_CLOSE = "MPPDBIDE_DIA_BTN_CLOSE"; + + String MPPDBIDE_DIA_BTN_CONT = "MPPDBIDE_DIA_BTN_CONTINUE"; + + String CONNECTION_SECURITY_ALERT = "CONNECTION_SECURITY_ALERT"; + + String SSL_DISABLED_CONTINUE_OR_CANCEL = "SSL_DISABLED_CONTINUE_OR_CANCEL"; + + String CREATE_NEW_PARTITION_TABLE = "CREATE_NEW_PARTITION_TABLE"; + + String TABLE_ORIENTATION = "TABLE_ORIENTATION"; + + String ENTER_DESCRIPTIONS_TEXT = "ENTER_DESCRIPTIONS_TEXT"; + + String RENAME_PARTITION_TABLE_TO = "RENAME_PARTITION_TABLE_TO"; + + String RENAME_PARTITION_TABLE_WAIT = "RENAME_PARTITION_TABLE_WAIT"; + + String RENAME_PARTITION_TABLE_TITLE = "RENAME_PARTITION_TABLE_TITLE"; + + String RENAME_PARTITION_TITLE = "RENAME_PARTITION_TITLE"; + + String RENAME_PARTITION_TABLE_NEW = "RENAME_PARTITION_TABLE_NEW"; + + String STATUS_MSG_RENAME_PARTITION_TABLE = "STATUS_MSG_RENAME_PARTITION_TABLE"; + + String DROP_PARTITION_TITLE = "DROP_PARTITION_TITLE"; + + String DROP_PARTITION = "DROP_PARTITION"; + + String STATUS_MSG_DROP_PARTITION = "STATUS_MSG_DROP_PARTITION"; + + String DROP_PARTITION_SUCCESS = "DROP_PARTITION_SUCCESS"; + + String DROP_PARTITION_ERROR_TITLE = "DROP_PARTITION_ERROR_TITLE"; + + String DROP_PARTITION_UNABLE_MSG = "DROP_PARTITION_UNABLE_MSG"; + + String EXPORT_QUERY = "EXPORT_QUERY"; + + String EXPORT_RESULT_TITLE = "EXPORT_RESULT_TITLE"; + + String EXPORT_EXEC_TITLE = "EXPORT_EXEC_TITLE"; + + String EXPORT_RESULT_INVALID_CONNECTION = "EXPORT_RESULT_INVALID_CONNECTION"; + + String DB_CONN_LBL_CLIENT_SSL_KEY = "DB_CONN_LBL_CLIENT_SSL_KEY"; + + String DB_CONN_LBL_CLIENT_SSL_CERT = "DB_CONN_LBL_CLIENT_SSL_CERT"; + + String DB_CONN_BTN_CLIENT_KEY = "DB_CONN_BTN_CLIENT_KEY"; + + String DB_CONN_BTN_CLIENT_CERT = "DB_CONN_BTN_CLIENT_CERT"; + + String DB_CONN_BROWSE = "DB_CONN_BROWSE"; + + String SHOW_TABLE_DDL = "SHOW_TABLE_DDL"; + + String SHOW_TABLE_DDL_FAILED = "SHOW_TABLE_DDL_FAILED"; + + String SHOW_TABLE_DDL_CANCELING = "SHOW_TABLE_DDL_CANCELING"; + + String PARTITION_TAB_ORIENTATION = "PARTITION_TAB_ORIENTATION"; + + String PARTITION_TAB_TYPE = "PARTITION_TAB_TYPE"; + + String PARTITION_TAB_INTERVAL_PARTITION_EXPR = "PARTITION_TAB_INTERVAL_PARTITION_EXPR"; + + String PARTITION_TAB_PARTITION_BY_RANGE = "PARTITION_TAB_PARTITION_BY_RANGE"; + + String PARTITION_TAB_AVAILABLE_COLUMN = "PARTITION_TAB_AVAILABLE_COLUMN"; + + String PARTITION_TAB_PARTITION_COLUMN = "PARTITION_TAB_PARTITION_COLUMN"; + + String PARTITION_TAB_PATITION_NAME = "PARTITION_TAB_PATITION_NAME"; + + String PARTITION_TAB_PARTITION_VALUE = "PARTITION_TAB_PARTITION_VALUE"; + + String PARTITION_TAB_TABLESPACE = "PARTITION_TAB_TABLESPACE"; + + String PARTITION_TAB_PARTITIONS = "PARTITION_TAB_PARTITIONS"; + + String PARTITION_TAB_PARTITION_DEF = "PARTITION_TAB_PARTITION_DEF"; + + String RENAME_CONNECTION_TITILE = "RENAME_CONNECTION_TITILE"; + + String RENAME_CONNECTION_NEW_NAME = "RENAME_CONNECTION_NEW_NAME"; + + String STATUS_MSG_RENAME_CONNECTION = "STATUS_MSG_RENAME_CONNECTION"; + + String RENAME_CONNECTION_WAIT = "RENAME_CONNECTION_WAIT"; + + String RENAME_CONNECTION_TO = "RENAME_CONNECTION_TO"; + + String RENAME_CONNECTION_ERROR = "RENAME_CONNECTION_ERROR"; + + String INF_NOEDIT_DONE_MSG_BODY = "INF_NOEDIT_DONE_MSG_BODY"; + + String INF_NOEDIT_DONE_MSG_TITLE = "INF_NOEDIT_DONE_MSG_TITLE"; + + String EDIT_CONNECTION_WIZARD_TITLE = "EDIT_CONNECTION_WIZARD_TITLE"; + + String EDIT_CONNECTION_SUBTITLE = "EDIT_CONNECTION_SUBTITLE"; + + String LAST_LOGING_FAILED_RETREIVAL_DATABASE = "LAST_LOGING_FAILED_RETREIVAL_DATABASE"; + + String USER_CANCEL = "USER_CANCEL"; + + String GENERAL_OPTION_TEXT = "GENERAL_OPTION_TEXT"; + + String TABLE_OPTIONS_TEXT = "TABLE_OPTIONS_TEXT"; + + String ERR_NONSELECT_CANCELLED = "ERR_NONSELECT_CANCELLED"; + + String DISCARD_TERMINAL_DATA_BODY = "DISCARD_TERMINAL_DATA_BODY"; + + String SAVE_CHANGES_DATA_BODY = "SAVE_CHANGES_DATA_BODY"; + + String EXPORT_DIRTY_DATA_BODY = "EXPORT_DIRTY_DATA_BODY"; + + String IMPORT_EXPORT_DELIMETER_COMMA = "IMPORT_EXPORT_DELIMETER_COMMA"; + + String IMPORT_EXPORT_DELIMETER_TAB = "IMPORT_EXPORT_DELIMETER_TAB"; + + String IMPORT_EXPORT_DELIMETER_PIPE = "IMPORT_EXPORT_DELIMETER_PIPE"; + + String IMPORT_EXPORT_DELIMETER_SEMICOLON = "IMPORT_EXPORT_DELIMETER_SEMICOLON"; + + String IMPORT_EXPORT_DELIMETER_OTHER = "IMPORT_EXPORT_DELIMETER_OTHER"; + + String LAST_LOGIN_UNAVAILABE = "LAST_LOGIN_UNAVAILABE"; + + String LASTLOGIN_CONNECTION_NAME = "LASTLOGIN_CONNECTION_NAME"; + + String CLOSE_TAB_MENU = "CLOSE_TAB_MENU"; + + String CLOSE_ALL_TAB_MENU = "CLOSE_ALL_TAB_MENU"; + + String CLOSE_OTHER_TABS_MENU = "CLOSE_OTHER_TABS_MENU"; + + String CLOSE_LEFT_TABS_MENU = "CLOSE_LEFT_TABS_MENU"; + + String CLOSE_RIGHT_TABS_MENU = "CLOSE_RIGHT_TABS_MENU"; + + String SAVE_PARTS = "SAVE_PARTS"; + + String SELECT_PARTS_FOR_SAVE = "SELECT_PARTS_FOR_SAVE"; + + String RENAME_TERMINAL_TITLE = "RENAME_TERMINAL_TITLE"; + + String RENAME_TERMINAL_MSG = "RENAME_TERMINAL_MSG"; + + String RENAME_TERMINAL_NAME = "RENAME_TERMINAL_NAME"; + + String RENAME_TERMINAL_DUPLICATE_NAME_ERROR = "RENAME_TERMINAL_DUPLICATE_NAME_ERROR"; + + String SEQUENCE = "SEQUENCE"; + + String SEARCH_SCOPE_LBL = "SEARCH_SCOPE_LBL"; + + String SEARCH_CONNECTION_LBL = "SEARCH_CONNECTION_LBL"; + + String SEARCH_CONNECTION_MAND_MSG = "SEARCH_CONNECTION_MAND_MSG"; + + String SEARCH_DATABASE_LBL = "SEARCH_DATABASE_LBL"; + + String SEARCH_DATABASE_MAND_MSG = "SEARCH_DATABASE_MAND_MSG"; + + String SEARCH_NAMESPACE_LBL = "SEARCH_NAMESPACE_LBL"; + + String SEARCH_NAMESPACE_MAND_MSG = "SEARCH_NAMESPACE_MAND_MSG"; + + String SEARCH_WITHIN_LBL = "SEARCH_WITHIN_LBL"; + + String SEARCH_WITHIN_TABLE_LBL = "SEARCH_WITHIN_TABLE_LBL"; + + String SEARCH_WITHIN_FUN_LBL = "SEARCH_WITHIN_FUN_LBL"; + + String SEARCH_WITHIN_VIEWS = "SEARCH_WITHIN_VIEWS"; + + String SEARCH_OPTIONS_LBL = "SEARCH_OPTIONS_LBL"; + + String SEARCH_NAME_LBL = "SEARCH_NAME_LBL"; + + String SEARCH_NAME_MAND_MSG = "SEARCH_NAME_MAND_MSG"; + + String SEARCH_NAME_MATCH_LBL = "SEARCH_NAME_MATCH_LBL"; + + String SEARCH_NAME_MATCH_CONTAINS = "SEARCH_NAME_MATCH_CONTAINS"; + + String SEARCH_NAME_MATCH_STARTS_LBL = "SEARCH_NAME_MATCH_STARTS_LBL"; + + String SEARCH_NAME_MATCH_EXACT_LBL = "SEARCH_NAME_MATCH_EXACT_LBL"; + + String SEARCH_NAME_MATCH_REGU_EXPRESS_LBL = "SEARCH_NAME_MATCH_REGU_EXPRESS_LBL"; + + String SEARCH_MATCH_CASE_LBL = "SEARCH_MATCH_CASE_LBL"; + + String SEARCH_BTN = "SEARCH_BTN"; + + String SEARCH_CANCEL_BTN = "SEARCH_CANCEL_BTN"; + + String SEARCH_RESULT_LBL = "SEARCH_RESULT_LBL"; + + String SEARCH_WINDOW_LBL = "SEARCH_WINDOW_LBL"; + + String OB_REFRESH_TOOL = "OB_REFRESH_TOOL"; + + String SEARCH_RECORD_FETCHED_MSG = "SEARCH_RECORD_FETCHED_MSG"; + + String SEARCH_NO_RECORD_FOUND_MSG = "SEARCH_NO_RECORD_FOUND_MSG"; + + String SEARCH_EXE_TIME_MSG = "SEARCH_EXE_TIME_MSG"; + + String KEY_BINDING_SEARCH = "KEY_BINDING_SEARCH"; + + String SEARCH_PROGRESS_STATS_MSG = "SEARCH_PROGRESS_STATS_MSG"; + + String SEARCH_PROGRESS_MONITOR_MSG = "SEARCH_PROGRESS_MONITOR_MSG"; + + String SEARCH_OBJ_ERROR = "SEARCH_OBJ_ERROR"; + + String BROWSE_BTN_ROOT_CERT = "BROWSE_BTN_ROOT_CERT"; + + String BROWSE_BTN_PEM_CERT = "BROWSE_BTN_PEM_CERT"; + + String ROOTCERT_FILETEXT = "ROOTCERT_FILETEXT"; + + String SSL_CIPHER = "SSL_CIPHER"; + + String CTAB_GENERAL = "CTAB_GENERAL"; + + String CTAB_SSL = "CTAB_SSL"; + + String CTAB_ADVANCED = "CTAB_ADVANCED"; + + String DROPDOWN_SSLMODE = "DROPDOWN_SSLMODE"; + + String ERROR_ANNOTATION_LABEL = "ERROR_ANNOTATION_LABEL"; + + String ERROR_WHILE_EXECUTION = "TERMINAL_ERROR_WHILE_EXECUTION"; + + String ERROR_POPUP_HEADER = "ERROR_POPUP_HEADER"; + + String ERROR_POPUP_MESSAGE_TEXT = "ERROR_POPUP_MESSAGE_TEXT"; + + String GENERAL_NODE = "GENERAL_NODE"; + + String EDITOR_NODE = "EDITOR_NODE"; + + String SECURITY_NODE = "SECURITY_NODE"; + + String ENVIRONMENT_NODE = "ENVIRONMENT_NODE"; + + String SESSION_SETTNG_NODE = "SESSION_SETTNG_NODE"; + + String CIPHER_PREFERENCE_OPTION = "CIPHER_PREFERENCE_OPTION"; + + String CIPHER_PREFERENCE_OPTION_TITLE = "CIPHER_PREFERENCE_OPTION_TITLE"; + + String YES_OPTION = "YES_OPTION"; + + String NO_OPTION = "NO_OPTION"; + + String SECURITY_WARNING_OPTION = "SECURITY_WARNING_OPTION"; + + String ENABLE_OPTION = "ENABLE_OPTION"; + + String DISABLE_OPTION = "DISABLE_OPTION"; + + String ENABLE_WARNING_MSG = "ENABLE_WARNING_MSG"; + + String DISABLE_WARNING_MSG = "DISABLE_WARNING_MSG"; + + String DATA_STUDIO_ENCODING = "DATA_STUDIO_ENCODING"; + + String ENCODING_PREFERENCES_TITLE = "ENCODING_PREFERENCES_TITLE"; + + String FILE_ENCODING = "FILE_ENCODING"; + + String LBL_INCLUDE = "LBL_INCLUDE"; + + String LBL_EXCLUDE = "LBL_EXCLUDE"; + + String LBL_FAST_LOAD_OPTIONS = "LBL_FAST_LOAD_OPTIONS"; + + String LBL_LOAD_LIMIT = "LBL_LOAD_LIMIT"; + + String LBL_GRP_SCHEMA = "LBL_GRP_SCHEMA"; + + String LBL_GRP_OB_ACESS = "LBL_GRP_OB_ACESS"; + + String LBL_OBJS = "LBL_OBJS"; + + String SEARCH_NO_CONN_MSG = "SEARCH_NO_CONN_MSG"; + + String SEARCH_SELECT_SEARCH_WITHIN_OPT = "SEARCH_SELECT_SEARCH_WITHIN_OPT"; + + String NO_TEXT = "NO_TEXT"; + + String YES_TEXT = "YES_TEXT"; + + String IAGREE_TEXT = "IAGREE_TEXT"; + + String IMPORT_EXPORT_INVALIDFILENAME = "IMPORT_EXPORT_INVALIDFILENAME"; + + String EXPORT_OUTPUTPATH = "EXPORT_OUTPUTPATH"; + + String EDITTABLE_PREFERENCE_OPTION = "EDITTABLE_PREFERENCE_OPTION"; + + String PREF_RESULT_WINDOW_TITLE = "PREF_RESULT_WINDOW_TITLE"; + + String PREF_RESULT_VIEW_TITLE = "PREF_RESULT_VIEW_TITLE"; + + String DROP_SEQUENCE_CONFIRM_TITLE = "DROP_SEQUENCE_CONFIRM_TITLE"; + String DROP_SEQUENCE_CONFIRM_MSG = "DROP_SEQUENCE_CONFIRM_MSG"; + + String DROP_SEQUENCE_CASCADE_CONFIRM_MSG = "DROP_SEQUENCE_CASCADE_CONFIRM_MSG"; + + String DROP_SEQUENCE_SUCCESS = "DROP_SEQUENCE_SUCCESS"; + + String DROP_SEQUENCE_CASCADE_SUCCESS = "DROP_SEQUENCE_CASCADE_SUCCESS"; + + String DROP_SEQUENCE_FAILURE = "DROP_SEQUENCE_FAILURE"; + + String CREATE_NEW_SEQUENCE = "CREATE_NEW_SEQUENCE"; + + String SEQUENCE_CREATED_SUCESSFULLY = "SEQUENCE_CREATED_SUCESSFULLY"; + + String CREATE_SEQUENCE_ERROR = "CREATE_SEQUENCE_ERROR"; + + String SEQUENCE_NAME = "SEQUENCE_NAME"; + + String MINIMUM_VALUE = "MINIMUM_VALUE"; + + String MAXIMUM_VALUE = "MAXIMUM_VALUE"; + + String INCREMENT_BY = "INCREMENT_BY"; + + String START_VALUE = "START_VALUE"; + + String SEQUENCE_CACHE = "SEQUENCE_CACHE"; + + String CYCLE_MSG = "CYCLE_MSG"; + + String CYCLE = "CYCLE"; + + String OWNER = "OWNER"; + + String TABLE_NAME = "TABLE_NAME"; + + String ORDER = "ORDER"; + + String COLUMN_NAME = "COLUMN_NAME"; + + String SELECT_SCHEMA_NAME = "SELECT_SCHEMA_NAME"; + + String EXPORT_PREFERENCES = "EXPORT_PREFERENCES"; + + String EXPORT_DDL_PREFERENCES = "EXPORT_DDL_PREFERENCES"; + + String EXPORT_DATA_PREFERENCES = "EXPORT_DATA_PREFERENCES"; + + String EXPORT_IMPORT_PREFERENCES = "EXPORT_IMPORT_PREFERENCES"; + + String INCLUDE_TABLESPACE_IN_DDL = "INCLUDE_TABLESPACE_IN_DDL"; + + String INCLUDE_EXPORT_DATA_OPTION = "INCLUDE_EXPORT_DATA_OPTION"; + + String PREF_COLUMN_WIDTH = "PREF_COLUMN_WIDTH"; + + String PREF_RS_COPY_HEADING = "PREF_RS_COPY_HEADING"; + + String PREF_CONTENT_LENGTH = "PREF_CONTENT_LENGTH"; + + String PREF_CUSTOM_LENGTH = "PREF_CUSTOM_LENGTH"; + + String PREF_RS_DATA_FETCH_COUNT_SUBTITLE = "PREF_RS_DATA_FETCH_COUNT_SUBTITLE"; + + String PREF_RS_DATA_FETCH_COUNT_MSG = "PREF_RS_DATA_FETCH_COUNT_MSG"; + + String PREF_RS_DATA_FETCH_ALL_MSG = "PREF_RS_DATA_FETCH_ALL_MSG"; + + String PREF_RS_DATA_COPY_COL_HEADER_MSG = "PREF_RS_DATA_COPY_COL_HEADER_MSG"; + + String PREF_RS_DATA_COPY_ROW_HEADER_MSG = "PREF_RS_DATA_COPY_ROW_HEADER_MSG"; + + String PREF_RS_CONTENT_LENGTH_HINT = "PREF_RS_CONTENT_LENGTH_HINT"; + + String PREF_RS_COPY_COLUMN_HEADER_HINT = "PREF_RS_COPY_COLUMN_HEADER_HINT"; + + String PREF_RS_COPY_ROW_HEADER_HINT = "PREF_RS_COPY_ROW_HEADER_HINT"; + + String PREF_RS_CUSTOM_LENGTH_HINT = "PREF_RS_CUSTOM_LENGTH_HINT"; + + String PREF_RS_COLUMN_WIDTH_INPUT_ERR_MSG = "PREF_RS_COLUMN_WIDTH_INPUT_ERR_MSG"; + + String PREF_RS_FETCH_COUNT_INPUT_ERR_MSG = "PREF_RS_FETCH_COUNT_INPUT_ERR_MSG"; + + String SHOW_HIDE_QUERY_BAR = "SHOW_HIDE_QUERY_BAR"; + + String SHOW_HIDE_SEARCH_BAR = "SHOW_HIDE_SEARCH_BAR"; + + String SEARCH_GRID = "SEARCH_GRID"; + + String CLEAR_SEARCH_GRID = "CLEAR_SEARCH_GRID"; + + String SEARCH_OPT_CONTAINS = "SEARCH_OPT_CONTAINS"; + + String SEARCH_OPT_EQUALS = "SEARCH_OPT_EQUALS"; + + String SEARCH_OPT_STARTS_WITH = "SEARCH_OPT_STARTS_WITH"; + + String SEARCH_OPT_REGEX = "SEARCH_OPT_REGEX"; + + String PREF_EXPORT_DDL_W_TABLESPACE_HINT = "PREF_EXPORT_DDL_W_TABLESPACE_HINT"; + + String EXPORTING_DATA_STATUS_MSG = "EXPORTING_DATA_STATUS_MSG"; + + String LOADING_DATA_STATUS_MSG = "LOADING_DATA_STATUS_MSG"; + + String ERROR_LOADING_DATA_STATUS_MSG = "ERROR_LOADING_DATA_STATUS_MSG"; + + String CREATE_SEQUENCE_INPUT_FORMATE = "CREATE_SEQUENCE_INPUT_FORMATE"; + + String TABLE_DOES_NOT_EXIST = "TABLE_DOES_NOT_EXIST"; + + String VIEW_DOES_NOT_EXIST = "VIEW_DOES_NOT_EXIST"; + + String MINIMUM_VALUE_FIELD = "MINIMUM_VALUE_FIELD"; + + String MAXIMUM_VALUE_FIELD = "MAXIMUM_VALUE_FIELD"; + + String INCREMENT_BY_FIELD = "INCREMENT_BY_FIELD"; + + String START_VALUE_FIELD = "START_VALUE_FIELD"; + + String SEQUENCE_CACHE_FIELD = "SEQUENCE_CACHE_FIELD"; + + String GENERAL_NODE_LABLE = "GENERAL_NODE_LABLE"; + + String EDITOR_NODE_LABLE = "EDITOR_NODE_LABLE"; + + String SECURITY_NODE_LABLE = "SECURITY_NODE_LABLE"; + + String ENVIRONMENT_NODE_LABLE = "ENVIRONMENT_NODE_LABLE"; + + String PREF_RESULT_WINDOW_NODE_LABLE = "PREF_RESULT_WINDOW_NODE_LABLE"; + + String EXPORT_IMPORT_PREFERENCES_LABLE = "EXPORT_IMPORT_PREFERENCES_LABLE"; + + String PROPERTIES_GENERAL_TAB = "PROPERTIES_GENERAL_TAB"; + + String PROPERTIES_COLUMNS_TAB = "PROPERTIES_COLUMNS_TAB"; + + String PROPERTIES_CONSTRAINTS_TAB = "PROPERTIES_CONSTRAINTS_TAB"; + + String PROPERTIES_INDEX_TAB = "PROPERTIES_INDEX_TAB"; + + String PROPERTIES_PARTITIONS_TAB = "PROPERTIES_PARTITIONS_TAB"; + + String PARTITION_COLUMN_ID = "PARTITION_COLUMN_ID"; + + String PROPERTIES_VIEW_NAME = "PROPERTIES_VIEW_NAME"; + + String PROPERTIES_VIEW_OWNER = "PROPERTIES_VIEW_OWNER"; + + String PROPERTIES_VIEW_DEF = "PROPERTIES_VIEW_DEF"; + + String DS_RESTART_CONFIRMATION_TITLE = "DS_RESTART_CONFIRMATION_TITLE"; + + String DS_RESTART_MSG_FOR_JOBS = "DS_RESTART_MSG_FOR_JOBS"; + + String TABLEPROPERTIES_OPTIONS_ORIENTATION = "TABLEPROPERTIES_OPTIONS_ORIENTATION"; + + String TABLEPROPERTIES_OPTIONS_FILLFACTOR = "TABLEPROPERTIES_OPTIONS_FILLFACTOR"; + + String TABLEPROPERTIES_OPTIONS_COMPRESSION = "TABLEPROPERTIES_OPTIONS_COMPRESSION"; + + String TABLEPROPERTIES_OPTIONS_MAX_BATCHROW = "TABLEPROPERTIES_OPTIONS_MAX_BATCHROW"; + + String TABLEPROPERTIES_OPTIONS_PARTIAL_CLUSTER_ROWS = "TABLEPROPERTIES_OPTIONS_PARTIAL_CLUSTER_ROWS"; + + String SEARCH_ITEM_TEXT = "SEARCH_ITEM_TEXT"; + + String TABLE_PROPERTIES_GROUP = "TABLE_PROPERTIES_GROUP"; + + String PARTITION_ERROR_MESSAGE = "PARTITION_ERROR_MESSAGE"; + + String PARTITION_COLUMN_ERROR_THAN_FOUR = "PARTITION_COLUMN_ERROR_THAN_FOUR"; + + String PARTITION_COLUMN_ERROR_THAN_ONE = "PARTITION_COLUMN_ERROR_THAN_ONE"; + + String ENTER_TABLE_NAME = "ENTER_TABLE_NAME"; + + String ENTER_COLUMN_NAME = "ENTER_COLUMN_NAME"; + + String ENTER_INDEX_NAME = "ENTER_INDEX_NAME"; + + String SQL_HISTORY_STATUS_SUCCESS = "SQL_HISTORY_STATUS_SUCCESS"; + + String SQL_HISTORY_STATUS_FAILURE = "SQL_HISTORY_STATUS_FAILURE"; + + String PARTITION_UI_SELECT = "PARTITION_UI_SELECT"; + + String VERSION = "VERSION"; + + String PREFERENCE_RESTART_REQUIRED_MSG = "PREFERENCE_RESTART_REQUIRED_MSG"; + + String CIPHER_EDIT_MESSAGE = "CIPHER_EDIT_MESSAGE"; + + String CIPHER_EXPIRY_TITLE = "CIPHER_EXPIRY_TITLE"; + + String YES_EXPIRY_OPTION = "YES_EXPIRY_OPTION"; + + String NO_EXPIRY_OPTION = "NO_EXPIRY_OPTION"; + + String CIPHER_EXPIRY_MSG_TITLE = "CIPHER_EXPIRY_MSG_TITLE"; + + String CIPHER_EXPIRY_INFORMATION = "CIPHER_EXPIRY_INFORMATION"; + + String SHOW_USER_MSG_ON_TABLE_UPDATE_TITLE = "SHOW_USER_MSG_ON_TABLE_UPDATE_TITLE"; + + String SHOW_USER_MSG_ON_TABLE_UPDATE_BODY = "SHOW_USER_MSG_ON_TABLE_UPDATE_BODY"; + + String CONSTRAINT_INDEXES_HANDLER_NOT_SUPPORTED_TITLE = "CONSTRAINT_INDEXES_HANDLER_NOT_SUPPORTED_TITLE"; + + String CONSTRAINT_HANDLER_FOR_COLUMN_ORIENTATION_BODY = "CONSTRAINT_HANDLER_FOR_COLUMN_ORIENTATION_BODY"; + + String DATA_DISTRIBUTION_TAB = "DATA_DISTRIBUTION_TAB"; + + String INDEXES_TAB = "INDEXES_TAB"; + + String CONSTRAINT_TAB = "CONSTRAINT_TAB"; + + String PARTITION_TAB = "PARTITION_TAB"; + + String INSERT_ROW_TOOLTIP = "INSERT_ROW_TOOLTIP"; + + String DELETE_ROW_TOOLTIP = "DELETE_ROW_TOOLTIP"; + + String COMMIT_CHANGES_TOOLTIP = "COMMIT_CHANGES_TOOLTIP"; + + String ROLLBACK_CHANGES_TOOLTIP = "ROLLBACK_CHANGES_TOOLTIP"; + + String REFRESH_TABLE_TOOLTIP = "REFRESH_TABLE_TOOLTIP"; + + String DEFINE_UNIQUE_KEY_TITLE = "DEFINE_UNIQUE_KEY_TITLE"; + + String UNIQUE_CONSTRAINT_COLNAME_HEADER = "UNIQUE_CONSTRAINT_COLNAME_HEADER"; + + String UNIQUE_CONSTRAINT_DATATYPE_HEADER = "UNIQUE_CONSTRAINT_DATATYPE_HEADER"; + + String UNIQUE_CONSTRAINT_SELECT_ALL_BTN_LABEL = "UNIQUE_CONSTRAINT_SELECT_ALL_BTN_LABEL"; + + String UNIQUE_CONSTRAINT_CLEAR_ALL_BTN_LABEL = "UNIQUE_CONSTRAINT_CLEAR_ALL_BTN_LABEL"; + + String UNIQUE_CONSTRAINT_TABLE_LABEL = "UNIQUE_CONSTRAINT_TABLE_LABEL"; + + String USE_ALL_COLUMNS_LABEL = "USE_ALL_COLUMNS_LABEL"; + + String CUSTOM_UNIQUE_KEY_LABEL = "CUSTOM_UNIQUE_KEY_LABEL"; + + String CANCEL_LABEL = "CANCEL_LABEL"; + + String GROUP_COLUMNS_HEADER = "GROUP_COLUMNS_HEADER"; + + String NO_PHYSICAL_UNQ_KEY_MSG = "NO_PHYSICAL_UNQ_KEY_MSG"; + + String DEFINE_UNQ_KEY_MSG = "DEFINE_UNQ_KEY_MSG"; + + String ANALYZING_TABLE = "ANALYZING_TABLE"; + + String REINDEX_TABLE_TITLE = "REINDEX_TABLE_TITLE"; + + String VACCUME_TABLE_TITLE = "VACCUME_TABLE_TITLE"; + + String CANCEL_CONNECTION_TITLE = "CANCEL_CONNECTION_TITLE"; + + String CANCEL_CONNECTION_BODY = "CANCEL_CONNECTION_BODY"; + + String USER_CANCEL_MSG = "USER_CANCEL_MSG"; + + String EDITTABLE_TITLE = "EDITTABLE_TITLE"; + + String YES_EDITTABLE_OPTION = "YES_EDITTABLE_OPTION"; + + String NO_EDITTABLE_OPTION = "NO_EDITTABLE_OPTION"; + + String CONNECT_DB_CANCEL_MSG = "CONNECT_DB_CANCEL_MSG"; + + String PASTE_INVALID_SELECTION_DIALOG_TITLE = "PASTE_INVALID_SELECTION_DIALOG_TITLE"; + + String PASTE_INVALID_SELECTION_DIALOG_MSG = "PASTE_INVALID_SELECTION_DIALOG_MSG"; + + String PASTE_TOOTIP = "PASTE_TOOTIP"; + + String QUERY_EXECUTION_FAILURE_ERROR_TITLE = "QUERY_EXECUTION_FAILURE_ERROR_TITLE"; + + String QUERY_EXECUTION_FAILURE_ERROR = "QUERY_EXECUTION_FAILURE_ERROR"; + + String REFRESH_TABLE_TOOLTIP_DISABLED = "REFRESH_TABLE_TOOLTIP_DISABLED"; + + String GRID_EDIT_STATUS_INSERTED = "GRID_EDIT_STATUS_INSERTED"; + + String GRID_EDIT_STATUS_UPDATED = "GRID_EDIT_STATUS_UPDATED"; + + String GRID_EDIT_STATUS_DELETED = "GRID_EDIT_STATUS_DELETED"; + + String EDIT_TABLE_DATA_CONNECTION_LOST_ERR_MSG = "EDIT_TABLE_DATA_CONNECTION_LOST_ERR_MSG"; + + String EDIT_TABLE_DATA_ERROR_POPUP_HEADER = "EDIT_TABLE_DATA_ERROR_POPUP_HEADER"; + + String VIEW_TABLE_DATA_ERROR_POPUP_HEADER = "VIEW_TABLE_DATA_ERROR_POPUP_HEADER"; + + String EDIT_TABLE_DATA_ERROR_POPUP_MESSAGE = "EDIT_TABLE_DATA_ERROR_POPUP_MESSAGE"; + + String SHOW_DDL_FAILED_TITLE = "SHOW_DDL_FAILED"; + + String ERR_CIPHER_EXPIRED = "ERR_CIPHER_EXPIRED"; + + String ERR_TO_BEGIN_TRANSACTION = "ERR_TO_BEGIN_TRANSACTION"; + + String ERR_EDIT_TABLE_COMMIT_FAIL = "ERR_EDIT_TABLE_COMMIT_FAIL"; + + String ERR_LAZY_BACKEND_LOAD_TITLE = "ERR_LAZY_BACKEND_LOAD_TITLE"; + + String ERR_EDIT_TABLE_DROP_TABLE = "ERR_EDIT_TABLE_DROP_TABLE"; + + String ERR_DATABASE_OPERATION_FAILURE = "ERR_DATABASE_OPERATION_FAILURE"; + + String ERR_FETCH_DATABASE_OPERATION = "ERR_FETCH_DATABASE_OPERATION"; + + String ERR_WRITING_PROFILE_TO_DISK = "ERR_WRITING_PROFILE_TO_DISK"; + + String ERR_PROFILE_FILE_REACHABLE = "ERR_PROFILE_FILE_REACHABLE"; + + String ERR_READING_PROFILE_DATA = "ERR_READING_PROFILE_DATA"; + + String ERR_TO_CONVERT_SEQ_DATA = "ERR_TO_CONVERT_SEQ_DATA"; + + String ERR_LAZY_LOADING_TABLE = "ERR_LAZY_LOADING_TABLE"; + + String ERR_VIEW_TABLE_FAILURE = "ERR_VIEW_TABLE_FAILURE"; + + String FAILED_TO_LOCK_FILE = "FAILED_TO_LOCK_FILE"; + + String EDIT_TABLE_FORGET_OPTIONS = "EDIT_TABLE_FORGET_OPTIONS"; + + String COMMITING_DATA = "COMMITING_DATA"; + + String EDIT_TABLE_REMEMBER_CHOICE = "EDIT_TABLE_REMEMBER_CHOICE"; + + String EDIT_TABLE_INVALID_DATE_DATATYPE = "EDIT_TABLE_INVALID_DATE_DATATYPE"; + + String EDIT_TABLE_INVALID_NUMBER_DATATYPE = "EDIT_TABLE_INVALID_NUMBER_DATATYPE"; + + String DRP_OBJ_ERRTITLE = "DRP_OBJ_ERRTITLE"; + + String DROP_OBJECT_ERROR = "DROP_OBJECT_ERROR"; + + String TABLESPACE_CREATION_ERROR = "TABLESPACE_CREATION_ERROR"; + + String SEARCH_OBJ_CANCEL_MSG = "SEARCH_OBJ_CANCEL_MSG"; + + String SET_COL_VAL_ERROR = "SET_COL_VAL_ERROR"; + + String ADD_COLUMN_ERROR = "ADD_COLUMN_ERROR"; + + String NEW_CONSTRAINT_CREATED_ERROR = "NEW_CONSTRAINT_CREATED_ERROR"; + + String TITLE_IOEXCEPTION = "TITLE_IOEXCEPTION"; + + String LOAD_CONN_ERR_TITLE = "LOAD_CONN_ERR_TITLE"; + + String LOAD_CONN_ERR_MSG = "LOAD_CONN_ERR_MSG"; + + String LOG_ERR_TITLE = "LOG_ERR_TITLE"; + + String LOG_ERR_MSG = "LOG_ERR_MSG"; + + String REINDEX_TABLE_FAIL = "REINDEX_TABLE_FAIL"; + + String SET_COLUMN_FAIL = "SET_COLUMN_FAIL"; + + String DROP_SCHEMA_FAIL = "DROP_SCHEMA_FAIL"; + + String REMOVE_CONN_ERROR = "REMOVE_CONN_ERROR"; + + String REMOVE_CONNPROF_TITLE = "REMOVE_CONNPROF_TITLE"; + + String ERR_PROFILE_WRITE_DISK_TITLE = "ERR_PROFILE_WRITE_DISK_TITLE"; + + String ERR_CONNECTION_FAILED = "ERR_CONNECTION_FAILED"; + + String EDIT_TABLE_ENABLE_OPTION = "EDIT_TABLE_ENABLE_OPTION"; + + String EDIT_TABLE_DISABLE_OPTION = "EDIT_TABLE_DISABLE_OPTION"; + + String DB_ASSIST_ENABLE_DESC = "DB_ASSIST_ENABLE_DESC"; + + String DB_ASSIST_DISABLE_DESC = "DB_ASSIST_DISABLE_DESC"; + + String DB_ASSISTANT_NAME = "DB_ASSISTANT_NAME"; + + String DB_ASSISTANT_ENABLE = "DB_ASSISTANT_ENABLE"; + + String DB_ASSISTANT_DISABLE = "DB_ASSISTANT_DISABLE"; + + String SET_TABLESPACE_FAIL = "SET_TABLESPACE_FAIL"; + + String EDIT_TABLE_INVALID_BOOLEAN_DATATYPE = "EDIT_TABLE_INVALID_BOOLEAN_DATATYPE"; + + String DROP_SEQUENCE_ERROR = "DROP_SEQUENCE_ERROR"; + + String EXPORT_TABLE_SUCESS = "EXPORT_TABLE_SUCESS"; + + String EXPORT_DDL_CANCEL_MSG = "EXPORT_DDL_CANCEL_MSG"; + + // for visual explain plan -- start + + String VIS_EXPLAIN_ICON_TOOLTIP_ZOOM_RESET = "VIS_EXPLAIN_ICON_TOOLTIP_ZOOM_RESET"; + + String VIS_EXPLAIN_JOB_DETAILS = "VIS_EXPLAIN_JOB_DETAILS"; + + String VIS_EXPLAIN_JOB_RESULT_DETAILS = "VIS_EXPLAIN_JOB_RESULT_DETAILS"; + + String VIS_EXPLAIN_MAN_WINDOW_TITLE = "VIS_EXPLAIN_MAN_WINDOW_TITLE"; + + String VIS_EXPLAIN_WINDOW_LBL = "VIS_EXPLAIN_WINDOW_LBL"; + + String VIS_EXPLAIN_WINDOW_ALL_NODES_LBL = "VIS_EXPLAIN_WINDOW_ALL_NODES_LBL"; + + String VIS_EXPLAIN_WINDOW_TEXT_LBL = "VIS_EXPLAIN_WINDOW_TEXT_LBL"; + + String VIS_EXPLAIN_OVERALL_DETAILS_ALLNODES_TAB = "VIS_EXPLAIN_OVERALL_DETAILS_ALLNODES_TAB"; + + String VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_ANALYSIS = "VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_ANALYSIS"; + + String VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_CONTRIBUTION = "VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_CONTRIBUTION"; + + String VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_EXECUTIONTIME = "VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_EXECUTIONTIME"; + + String VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_NODENAME = "VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_NODENAME"; + + String VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_ROWSOUTPUT = "VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_ROWSOUTPUT"; + + String VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_ROWSOUTPUTDEVIATION = "VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_ROWSOUTPUTDEVIATION"; + + String VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_SELFCOST = "VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_SELFCOST"; + + String VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_TOTALCOST = "VIS_EXPLAIN_OVERALL_DETAILS_COLUMN_TOTALCOST"; + + String VIS_EXPLAIN_OVERALL_DETAILS_GENERAL_TAB = "VIS_EXPLAIN_OVERALL_DETAILS_GENERAL_TAB"; + + String VIS_EXPLAIN_OVERALL_DETAILS_GENERAL_COLUMN_PROP = "VIS_EXPLAIN_OVERALL_DETAILS_GENERAL_COLUMN_PROP"; + + String VIS_EXPLAIN_OVERALL_DETAILS_GENERAL_COLUMN_VALUE = "VIS_EXPLAIN_OVERALL_DETAILS_GENERAL_COLUMN_VALUE"; + + String VIS_EXPLAIN_OVERALL_DETAILS_ROOTNODE_TOTALRUNTIME = "VIS_EXPLAIN_OVERALL_DETAILS_ROOTNODE_TOTALRUNTIME"; + + String VIS_EXPLAIN_PROP_PERDN_AGGREGATEINDETAIL = "VIS_EXPLAIN_PROP_PERDN_AGGREGATEINDETAIL"; + + String VIS_EXPLAIN_PROP_PERDN_BUFFERSINDETAIL = "VIS_EXPLAIN_PROP_PERDN_BUFFERSINDETAIL"; + + String VIS_EXPLAIN_PROP_PERDN_CPUINDETAIL = "VIS_EXPLAIN_PROP_PERDN_CPUINDETAIL"; + + String VIS_EXPLAIN_PROP_PERDN_HASHDETAIL = "VIS_EXPLAIN_PROP_PERDN_HASHDETAIL"; + + String VIS_EXPLAIN_PROP_PERDN_JOININDETAIL = "VIS_EXPLAIN_PROP_PERDN_JOININDETAIL"; + + String VIS_EXPLAIN_PROP_PERDN_SETOPDETAIL = "VIS_EXPLAIN_PROP_PERDN_SETOPDETAIL"; + + String VIS_EXPLAIN_PROP_PERDN_ACTUALSINDETAIL_COLUMNGRP = "VIS_EXPLAIN_PROP_PERDN_ACTUALSINDETAIL_COLUMNGRP"; + + String VIS_EXPLAIN_PROP_PERDN_ACTUALS_COLUMN_LOOPS = "VIS_EXPLAIN_PROP_PERDN_ACTUALS_COLUMN_LOOPS"; + + String VIS_EXPLAIN_PROP_PERDN_ACTUALS_COLUMN_ROWS = "VIS_EXPLAIN_PROP_PERDN_ACTUALS_COLUMN_ROWS"; + + String VIS_EXPLAIN_PROP_PERDN_ACTUALS_COLUMN_STARTUPTIME = "VIS_EXPLAIN_PROP_PERDN_ACTUALS_COLUMN_STARTUPTIME"; + + String VIS_EXPLAIN_PROP_PERDN_ACTUALS_COLUMN_TOTALTIME = "VIS_EXPLAIN_PROP_PERDN_ACTUALS_COLUMN_TOTALTIME"; + + String VIS_EXPLAIN_PROP_PERDN_DN_COLUMN = "VIS_EXPLAIN_PROP_PERDN_DN_COLUMN"; + + String VIS_EXPLAIN_PROP_PERDN_DN_COLUMNGRP = "VIS_EXPLAIN_PROP_PERDN_DN_COLUMNGRP"; + + String VIS_EXPLAIN_PROP_PERDN_LLVM_COLUMN = "VIS_EXPLAIN_PROP_PERDN_LLVM_COLUMN"; + + String VIS_EXPLAIN_PROP_PERDN_LLVM_COLUMNGRP = "VIS_EXPLAIN_PROP_PERDN_LLVM_COLUMNGRP"; + + String VIS_EXPLAIN_PER_NODE_COLUMN_PROP = "VIS_EXPLAIN_PER_NODE_COLUMN_PROP"; + + String VIS_EXPLAIN_PER_NODE_COLUMN_VALUE = "VIS_EXPLAIN_PER_NODE_COLUMN_VALUE"; + + String VIS_EXPLAIN_PER_NODE_DETAILS_PART_LBL = "VIS_EXPLAIN_PER_NODE_DETAILS_PART_LBL"; + + String VIS_EXPLAIN_PER_NODE_DETAILS_GENERAL_TAB = "VIS_EXPLAIN_PER_NODE_DETAILS_GENERAL_TAB"; + + String VIS_EXPLAIN_PER_NODE_DETAILS_PERDN_TAB = "VIS_EXPLAIN_PER_NODE_DETAILS_PERDN_TAB"; + + String VIS_EXPLAIN_NODCATEGORY_AGGREGATE = "VIS_EXPLAIN_NODCATEGORY_AGGREGATE"; + + String VIS_EXPLAIN_NODCATEGORY_FUNCTION = "VIS_EXPLAIN_NODCATEGORY_FUNCTION"; + + String VIS_EXPLAIN_NODCATEGORY_GROUPAGGREGATE = "VIS_EXPLAIN_NODCATEGORY_GROUPAGGREGATE"; + + String VIS_EXPLAIN_NODCATEGORY_HASH = "VIS_EXPLAIN_NODCATEGORY_HASH"; + + String VIS_EXPLAIN_NODCATEGORY_HASHJOIN = "VIS_EXPLAIN_NODCATEGORY_HASHJOIN"; + + String VIS_EXPLAIN_NODCATEGORY_MODIFYTABLE = "VIS_EXPLAIN_NODCATEGORY_MODIFYTABLE"; + + String VIS_EXPLAIN_NODCATEGORY_NESTLOOPJOIN = "VIS_EXPLAIN_NODCATEGORY_NESTLOOPJOIN"; + + String VIS_EXPLAIN_NODCATEGORY_NESTEDLOOP = "VIS_EXPLAIN_NODCATEGORY_NESTEDLOOP"; + + String VIS_EXPLAIN_NODCATEGORY_PARTITIONITERATOR = "VIS_EXPLAIN_NODCATEGORY_PARTITIONITERATOR"; + + String VIS_EXPLAIN_NODCATEGORY_ROWADAPTER = "VIS_EXPLAIN_NODCATEGORY_ROWADAPTER"; + + String VIS_EXPLAIN_NODCATEGORY_SCAN = "VIS_EXPLAIN_NODCATEGORY_SCAN"; + + String VIS_EXPLAIN_NODCATEGORY_SETOP = "VIS_EXPLAIN_NODCATEGORY_SETOP"; + + String VIS_EXPLAIN_NODCATEGORY_SORT = "VIS_EXPLAIN_NODCATEGORY_SORT"; + + String VIS_EXPLAIN_NODCATEGORY_STREAM = "VIS_EXPLAIN_NODCATEGORY_STREAM"; + + String VIS_EXPLAIN_NODCATEGORY_UNKNOWN = "VIS_EXPLAIN_NODCATEGORY_UNKNOWN"; + + String VIS_EXPLAIN_NODCATEGORY_UNION = "VIS_EXPLAIN_NODCATEGORY_UNION"; + + String VIS_EXPLAIN_PROP_ANALYSISNODE_ANALYSIS = "VIS_EXPLAIN_PROP_ANALYSISNODE_ANALYSIS"; + + String VIS_EXPLAIN_PROP_ANALYSISNODE_OUTPUT = "VIS_EXPLAIN_PROP_ANALYSISNODE_OUTPUT"; + + String VIS_EXPLAIN_PROP_ANALYSISNODE_ROWSOUTPUTDEVIATION = "VIS_EXPLAIN_PROP_ANALYSISNODE_ROWSOUTPUTDEVIATION"; + + String VIS_EXPLAIN_PROP_BASICNODE_ACTUALLOOPS = "VIS_EXPLAIN_PROP_BASICNODE_ACTUALLOOPS"; + + String VIS_EXPLAIN_PROP_BASICNODE_ACTUALOUTROWS = "VIS_EXPLAIN_PROP_BASICNODE_ACTUALOUTROWS"; + + String VIS_EXPLAIN_PROP_BASICNODE_ACTUALSTARTUPTIME = "VIS_EXPLAIN_PROP_BASICNODE_ACTUALSTARTUPTIME"; + + String VIS_EXPLAIN_PROP_BASICNODE_ACTUALTOTALTIME = "VIS_EXPLAIN_PROP_BASICNODE_ACTUALTOTALTIME"; + + String VIS_EXPLAIN_PROP_BASICNODE_BUFFER_IOREADTIME = "VIS_EXPLAIN_PROP_BASICNODE_BUFFER_IOREADTIME"; + + String VIS_EXPLAIN_PROP_BASICNODE_BUFFER_IOWRITETIME = "VIS_EXPLAIN_PROP_BASICNODE_BUFFER_IOWRITETIME"; + + String VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALDIRTIEDBLOCKS = "VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALDIRTIEDBLOCKS"; + + String VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALHITBLOCKS = "VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALHITBLOCKS"; + + String VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALREADHITBLOCKS = "VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALREADHITBLOCKS"; + + String VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALWRITTENBLOCKS = "VIS_EXPLAIN_PROP_BASICNODE_BUFFER_LOCALWRITTENBLOCKS"; + + String VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDDIRTIEDBLOCKS = "VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDDIRTIEDBLOCKS"; + + String VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDHITBLOCKS = "VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDHITBLOCKS"; + + String VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDREADBLOCKS = "VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDREADBLOCKS"; + + String VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDWRITTENBLOCKS = "VIS_EXPLAIN_PROP_BASICNODE_BUFFER_SHAREDWRITTENBLOCKS"; + + String VIS_EXPLAIN_PROP_BASICNODE_BUFFER_TEMPREADBLOCKS = "VIS_EXPLAIN_PROP_BASICNODE_BUFFER_TEMPREADBLOCKS"; + + String VIS_EXPLAIN_PROP_BASICNODE_BUFFER_TEMPWRITTENBLOCKS = "VIS_EXPLAIN_PROP_BASICNODE_BUFFER_TEMPWRITTENBLOCKS"; + + String VIS_EXPLAIN_PROP_BASICNODE_CPU_EXCLUSIVECYCLESROW = "VIS_EXPLAIN_PROP_BASICNODE_CPU_EXCLUSIVECYCLESROW"; + + String VIS_EXPLAIN_PROP_BASICNODE_CPU_EXCLUSIVECYCLES = "VIS_EXPLAIN_PROP_BASICNODE_CPU_EXCLUSIVECYCLES"; + + String VIS_EXPLAIN_PROP_BASICNODE_CPU_INCLUSIVECYCLES = "VIS_EXPLAIN_PROP_BASICNODE_CPU_INCLUSIVECYCLES"; + + String VIS_EXPLAIN_PROP_BASICNODE_HASH_HASHBATCHES = "VIS_EXPLAIN_PROP_BASICNODE_HASH_HASHBATCHES"; + + String VIS_EXPLAIN_PROP_BASICNODE_HASH_HASHBUCKETS = "VIS_EXPLAIN_PROP_BASICNODE_HASH_HASHBUCKETS"; + + String VIS_EXPLAIN_PROP_BASICNODE_HASH_ORIGINALHASHBATCHES = "VIS_EXPLAIN_PROP_BASICNODE_HASH_ORIGINALHASHBATCHES"; + + String VIS_EXPLAIN_PROP_BASICNODE_HASH_PEAKMEMORYUSAGE = "VIS_EXPLAIN_PROP_BASICNODE_HASH_PEAKMEMORYUSAGE"; + + String VIS_EXPLAIN_PROP_BASICNODE_ISVECTORIZED = "VIS_EXPLAIN_PROP_BASICNODE_ISVECTORIZED"; + + String VIS_EXPLAIN_PROP_BASICNODE_NODETYPE = "VIS_EXPLAIN_PROP_BASICNODE_NODETYPE"; + + String VIS_EXPLAIN_PROP_BASICNODE_PARENTRELATIONSHIP = "VIS_EXPLAIN_PROP_BASICNODE_PARENTRELATIONSHIP"; + + String VIS_EXPLAIN_PROP_BASICNODE_PLANROWS = "VIS_EXPLAIN_PROP_BASICNODE_PLANROWS"; + + String VIS_EXPLAIN_PROP_BASICNODE_PLANWIDTH = "VIS_EXPLAIN_PROP_BASICNODE_PLANWIDTH"; + + String VIS_EXPLAIN_PROP_BASICNODE_STARTUPCOST = "VIS_EXPLAIN_PROP_BASICNODE_STARTUPCOST"; + + String VIS_EXPLAIN_PROP_BASICNODE_TOTALCOST = "VIS_EXPLAIN_PROP_BASICNODE_TOTALCOST"; + + String VIS_EXPLAIN_PROP_CSTORESCANNODE_FILTER = "VIS_EXPLAIN_PROP_CSTORESCANNODE_FILTER"; + + String VIS_EXPLAIN_PROP_CSTORESCANNODE_ROWREMOVEDFILTER = "VIS_EXPLAIN_PROP_CSTORESCANNODE_ROWREMOVEDFILTER"; + + String VIS_EXPLAIN_PROP_DATANODESCAN_PRIMARYNODECOUNT = "VIS_EXPLAIN_PROP_DATANODESCAN_PRIMARYNODECOUNT"; + + String VIS_EXPLAIN_PROP_DATANODESCAN_NODECOUNT = "VIS_EXPLAIN_PROP_DATANODESCAN_NODECOUNT"; + + String VIS_EXPLAIN_PROP_FUNCTIONSCANNODE_FUNCTIONALIASNAME = "VIS_EXPLAIN_PROP_FUNCTIONSCANNODE_FUNCTIONALIASNAME"; + + String VIS_EXPLAIN_PROP_FUNCTIONSCANNODE_FUNCTIONCALL = "VIS_EXPLAIN_PROP_FUNCTIONSCANNODE_FUNCTIONCALL"; + + String VIS_EXPLAIN_PROP_FUNCTIONSCANNODE_FUNCTIONNAME = "VIS_EXPLAIN_PROP_FUNCTIONSCANNODE_FUNCTIONNAME"; + + String VIS_EXPLAIN_PROP_FUNCTIONSCANNODE_SCHEMANAME = "VIS_EXPLAIN_PROP_FUNCTIONSCANNODE_SCHEMANAME"; + + String VIS_EXPLAIN_PROP_GROUP_BY_GRPBYKEYS = "VIS_EXPLAIN_PROP_GROUP_BY_GRPBYKEYS"; + + String VIS_EXPLAIN_PROP_JOIN_JOINTYPE = "VIS_EXPLAIN_PROP_JOIN_JOINTYPE"; + + String VIS_EXPLAIN_PROP_HASHNODE_HASHBUCKETS = "VIS_EXPLAIN_PROP_HASHNODE_HASHBUCKETS"; + + String VIS_EXPLAIN_PROP_HASHNODE_HASHBATCHES = "VIS_EXPLAIN_PROP_HASHNODE_HASHBATCHES"; + + String VIS_EXPLAIN_PROP_HASHNODE_ORIGINALHASHBATCHES = "VIS_EXPLAIN_PROP_HASHNODE_ORIGINALHASHBATCHES"; + + String VIS_EXPLAIN_PROP_HASHNODE_PEAKMEMORYUSAGE = "VIS_EXPLAIN_PROP_HASHNODE_PEAKMEMORYUSAGE"; + + String VIS_EXPLAIN_PROP_HASH_JOIN_JOINCOND = "VIS_EXPLAIN_PROP_HASH_JOIN_JOINCOND"; + + String VIS_EXPLAIN_PROP_INDEXSCANNODE_INDEXCOND = "VIS_EXPLAIN_PROP_INDEXSCANNODE_INDEXCOND"; + + String VIS_EXPLAIN_PROP_INDEXSCANNODE_INDEXNAME = "VIS_EXPLAIN_PROP_INDEXSCANNODE_INDEXNAME"; + + String VIS_EXPLAIN_PROP_INDEXSCANNODE_ROWSREMOVEDRECHECK = "VIS_EXPLAIN_PROP_INDEXSCANNODE_ROWSREMOVEDRECHECK"; + + String VIS_EXPLAIN_PROP_INDEXSCANNODE_SCANDIRECTION = "VIS_EXPLAIN_PROP_INDEXSCANNODE_SCANDIRECTION"; + + String VIS_EXPLAIN_PROP_MODIFYTABLE_OPERATION = "VIS_EXPLAIN_PROP_MODIFYTABLE_OPERATION"; + + String VIS_EXPLAIN_PROP_NESTLOOP_JOIN_JOINFILTER = "VIS_EXPLAIN_PROP_NESTLOOP_JOIN_JOINFILTER"; + + String VIS_EXPLAIN_PROP_NESTLOOP_JOIN_ROWSREMOVEDBYJOINFILTER = "VIS_EXPLAIN_PROP_NESTLOOP_JOIN_ROWSREMOVEDBYJOINFILTER"; + + String VIS_EXPLAIN_PROP_NODE_REMOTEQUERY = "VIS_EXPLAIN_PROP_NODE_REMOTEQUERY"; + + String VIS_EXPLAIN_PROP_NODE_SUBPLANNAME = "VIS_EXPLAIN_PROP_NODE_SUBPLANNAME"; + + String VIS_EXPLAIN_PROP_OPERATIONALNODE_CHILD1NAME = "VIS_EXPLAIN_PROP_OPERATIONALNODE_CHILD1NAME"; + + String VIS_EXPLAIN_PROP_OPERATIONALNODE_CHILD2NAME = "VIS_EXPLAIN_PROP_OPERATIONALNODE_CHILD2NAME"; + + String VIS_EXPLAIN_PROP_OPERATIONALNODE_CHILDRENNAME = "VIS_EXPLAIN_PROP_OPERATIONALNODE_CHILDRENNAME"; + + String VIS_EXPLAIN_PROP_SCANNODE_ALIASNAME = "VIS_EXPLAIN_PROP_SCANNODE_ALIASNAME"; + + String VIS_EXPLAIN_PROP_SCANNODE_SCANTABLEALIASNAME = "VIS_EXPLAIN_PROP_SCANNODE_SCANTABLEALIASNAME"; + + String VIS_EXPLAIN_PROP_SCANNODE_SCANTABLENAME = "VIS_EXPLAIN_PROP_SCANNODE_SCANTABLENAME"; + + String VIS_EXPLAIN_PROP_SCANNODE_SCHEMANAME = "VIS_EXPLAIN_PROP_SCANNODE_SCHEMANAME"; + + String VIS_EXPLAIN_PROP_SCANNODE_SELECTEDPARTITIONS = "VIS_EXPLAIN_PROP_SCANNODE_SELECTEDPARTITIONS"; + + String VIS_EXPLAIN_PROP_SETOPNODE_TEMPFILENUM = "VIS_EXPLAIN_PROP_SETOPNODE_TEMPFILENUM"; + + String VIS_EXPLAIN_PROP_SETOP_COMMAND = "VIS_EXPLAIN_PROP_SETOP_COMMAND"; + + String VIS_EXPLAIN_PROP_SETOP_STRATEGY = "VIS_EXPLAIN_PROP_SETOP_STRATEGY"; + + String VIS_EXPLAIN_PROP_SORT_SORTKEYS = "VIS_EXPLAIN_PROP_SORT_SORTKEYS"; + + String VIS_EXPLAIN_PROP_STREAM_GATHER_NODES = "VIS_EXPLAIN_PROP_STREAM_GATHER_NODES"; + + String VIS_EXPLAIN_PROP_STREAM_REDISTRIBUTE_DISTRKEY = "VIS_EXPLAIN_PROP_STREAM_REDISTRIBUTE_DISTRKEY"; + + String VIS_EXPLAIN_PROP_STREAM_REDISTRIBUTE_SPAWNON = "VIS_EXPLAIN_PROP_STREAM_REDISTRIBUTE_SPAWNON"; + + String VIS_EXPLAIN_PROP_WORKTABLESCANNODE_FILTER = "VIS_EXPLAIN_PROP_WORKTABLESCANNODE_FILTER"; + + String VIS_EXPLAIN_PROP_WORKTABLESCANNODE_ROWREMOVEDFILTER = "VIS_EXPLAIN_PROP_WORKTABLESCANNODE_ROWREMOVEDFILTER"; + + String VIS_EXPLAIN_ANALYSIS_COSTLIEST = "VIS_EXPLAIN_ANALYSIS_COSTLIEST"; + + String VIS_EXPLAIN_ANALYSIS_HEAVIEST = "VIS_EXPLAIN_ANALYSIS_HEAVIEST"; + + String VIS_EXPLAIN_ANALYSIS_SLOWEST = "VIS_EXPLAIN_ANALYSIS_SLOWEST"; + + String VIS_EXPLAIN_JSON_PARSING_FAILED = "VIS_EXPLAIN_JSON_PARSING_FAILED"; + + String VIS_EXPLAIN_PLAN_ERROR_POPUP_HEADER = "VIS_EXPLAIN_PLAN_ERROR_POPUP_HEADER"; + + String EXPLAIN_PLAN_ERROR_POPUP_HEADER = "EXPLAIN_PLAN_ERROR_POPUP_HEADER"; + + // for visual explain plan -- end + + String CANCEL_OPERATION_IN_PROGRESS = "CANCEL_OPERATION_IN_PROGRESS"; + + String TABLE_PROPERTIES_TABLE_NAME = "TABLE_PROPERTIES_TABLE_NAME"; + + String USER_CANCEL_MSG_TITLE = "USER_CANCEL_MSG_TITLE"; + + String INVALID_INCLUDE_EXCLUDE_SCHEMA = "INVALID_INCLUDE_EXCLUDE_SCHEMA"; + + String INVALID_EXCLUDE_SCHEMA = "INVALID_EXCLUDE_SCHEMA"; + + String INVALID_INCLUDE_SCHEMA = "INVALID_INCLUDE_SCHEMA"; + + String INVALID_INCLUDE_EXCLUDE_TITLE = "INVALID_INCLUDE_EXCLUDE_TITLE"; + + String UKNOWN_COMPLEX_DATATYPE = "UKNOWN_COMPLEX_DATATYPE"; + + String LOAD_LIMIT_UNIT = "LOAD_LIMIT_UNIT"; + + String EDIT_TABLE_DATA_DROPPED_REFRESH_ERROR = "EDIT_TABLE_DATA_DROPPED_REFRESH_ERROR"; + + String VIEW_TABLE_DATA_DROPPED_REFRESH_ERROR = "VIEW_TABLE_DATA_DROPPED_REFRESH_ERROR"; + + String CANCELLING_JOB = "CANCELLING_JOB"; + + String SQL_HIST_PINNED = "SQL_HIST_PINNED"; + + String OB_ACCESS_TYPE_ALL = "OB_ACCESS_TYPE_ALL"; + + String OB_ACCESS_TYPE_PRIVILEGED = "OB_ACCESS_TYPE_PRIVILEGED"; + + String SEARCH_OPT_NULL = "SEARCH_OPT_NULL"; + + String ERR_EDITTABLE_REFRESH_FAILED = "ERR_EDITTABLE_REFRESH_FAILED"; + + String RESULT_WINDOW_ROW_FETCHED = "RESULT_WINDOW_ROW_FETCHED"; + + String RESULT_WINDOW_RECORD_FETCHED_ONE = "RESULT_WINDOW_RECORD_FETCHED_ONE"; + + String PARTITION_TABLE_COL_REMOVE_TITLE = "PARTITION_TABLE_COL_REMOVE_TITLE"; + + String PARTITION_TABLE_COL_REMOVE_BODY = "PARTITION_TABLE_COL_REMOVE_BODY"; + + String PARTITION_VALUE_TOOLTIP = "PARTITION_VALUE_TOOLTIP"; + + String PARTITION_VALUE_POPUP_TITLE = "PARTITION_VALUE_POPUP_TITLE"; + + String PARTITION_COLUMN = "PARTITION_COLUMN"; + + String PARTITION_VALUE = "PARTITION_VALUE"; + + String EDIT_DUPLICATE_MODIFICATION_TITLE = "EDIT_DUPLICATE_MODIFICATION_TITLE"; + + String EDIT_DUPLICATE_MODIFICATION_MSG = "EDIT_DUPLICATE_MODIFICATION_MSG"; + + String ERR_EXPORT_TABLE_DROP_TABLE = "ERR_EXPORT_TABLE_DROP_TABLE"; + + String ERR_IMPORT_TABLE_DROP_TABLE = "ERR_IMPORT_TABLE_DROP_TABLE"; + + String EXPORT_DDL_PROGRESS_NAME = "EXPORT_DDL_PROGRESS_NAME"; + + String EXPORT_DDL_DATA_PROGRESS_NAME = "EXPORT_DDL_DATA_PROGRESS_NAME"; + + String TOOLTIP_DISTRIBUTION_COL = "TOOLTIP_DISTRIBUTION_COL"; + + String TOOLTIP_READONLY_COL = "TOOLTIP_READONLY_COL"; + + String DS_DEFAULT_MAX_CONSOLE_LINE_COUNT = "DS_DEFAULT_MAX_CONSOLE_LINE_COUNT"; + + String EXPORT_DDL = "EXPORT_DDL"; + + String EXPORT_DDL_DATA = "EXPORT_DDL_DATA"; + + String HAS_OID = "HAS_OID"; + + String NAMESPACE_RETRIVE_CRITICAL_ERROR = "NAMESPACE_RETRIVE_CRITICAL_ERROR"; + + String CONNECT_TO_DB_STATE_MACHINE_ERROR = "CONNECT_TO_DB_STATE_MACHINE_ERROR"; + + // MESSAGES SQL HISTORY PREFRENCES START + String SQL_HISTORY = "SQL_HISTORY"; + + String SET_SQL_SIZE = "SET_SQL_SIZE"; + + String SQL_SIZE_DESC_LABEL = "SQL_SIZE_DESC_LABEL"; + + String SET_SQL_QUERY_LENGTH = "SET_SQL_QUERY_LENGTH"; + + String SQL_QUERY_DESC_LABEL1 = "SQL_QUERY_DESC_LABEL1"; + + String SQL_HISTORY_RANGE = "SQL_HISTORY_RANGE"; + + String DEFAULT_VALUE = "DEFAULT_VALUE"; + + String SQL_QUERY_LENGTH_NO_LIMIT = "SQL_QUERY_LENGTH_NO_LIMIT"; + + String SQL_SIZE_ERROR_MSG = "SQL_SIZE_ERROR_MSG"; + + String SQL_QUERY_ERROR_MSG = "SQL_QUERY_ERROR_MSG"; + + String UPDATE_SQL_HISTORY_SETTING_TITLE = "UPDATE_SQL_HISTORY_SETTING_TITLE"; + + String UPDATE_SQL_HISTORY_SETTING_BODY = "UPDATE_SQL_HISTORY_SETTING_BODY"; + + String SQL_HISTORY_SETTING_UNSAVED_DATA_BODY = "SQL_HISTORY_SETTING_UNSAVED_DATA_BODY"; + + // MESSAGES SQL HISTORY PREFRENCES ENDS + + String VIEW_TABLE_PROGRESS_NAME = "VIEW_TABLE_PROGRESS_NAME"; + + String VIEW_PROGRESS_NAME = "VIEW_PROGRESS_NAME"; + + String EDIT_TABLE_PROGRESS_NAME = "EDIT_TABLE_PROGRESS_NAME"; + + String DROP_TABLE_PROGRESS_NAME = "DROP_TABLE_PROGRESS_NAME"; + + String EDIT_TABLE_COMMIT_PROGRESS_NAME = "EDIT_TABLE_COMMIT_PROGRESS_NAME"; + + String CHANGE_INDEX_TBLSPACE_PROGRESS_NAME = "CHANGE_INDEX_TBLSPACE_PROGRESS_NAME"; + + String DROP_COLUMN_PROGRESS_NAME = "DROP_COLUMN_PROGRESS_NAME"; + + String DROP_PARTITION_PROGRESS_NAME = "DROP_PARTITION_PROGRESS_NAME"; + + String RENAME_COLUMN_PROGRESS_NAME = "RENAME_COLUMN_PROGRESS_NAME"; + + String VALIDATE_CONSTRAINT_PROGRESS_NAME = "VALIDATE_CONSTRAINT_PROGRESS_NAME"; + + String SHOW_VIEW_DDL_PROGRESS_NAME = "SHOW_VIEW_DDL_PROGRESS_NAME"; + + String CONNECT_DB_PROGRESS_NAME = "CONNECT_DB_PROGRESS_NAME"; + + String CREATE_DB_PROGRESS_NAME = "CREATE_DB_PROGRESS_NAME"; + + String DROP_SCHEMA_PROGRESS_NAME = "DROP_SCHEMA_PROGRESS_NAME"; + + String DROP_DEBUGOBJECT_PROGRESS_NAME = "DROP_DEBUGOBJECT_PROGRESS_NAME"; + + String REINDEX_TABLE_PROGRESS_NAME = "REINDEX_TABLE_PROGRESS_NAME"; + + String RENAME_DATABASE_PROGRESS_NAME = "RENAME_DATABASE_PROGRESS_NAME"; + + String SHOW_DDL_TABLE_PROGRESS_NAME = "SHOW_DDL_TABLE_PROGRESS_NAME"; + + String ADD_COLUMN_PROGRESS_NAME = "ADD_COLUMN_PROGRESS_NAME"; + + String ADD_CONSTRAINT_PROGRESS_NAME = "ADD_CONSTRAINT_PROGRESS_NAME"; + + String ALTER_COLUMN_DEFAULT_PROGRESS_NAME = "ALTER_COLUMN_DEFAULT_PROGRESS_NAME"; + + String CREATE_INDEX_PROGRESS_NAME = "CREATE_INDEX_PROGRESS_NAME"; + + String CREATE_TABLE_PROGRESS_NAME = "CREATE_TABLE_PROGRESS_NAME"; + + String EXPORT_ALL_RESULTDATA_PROGRESS_NAME = "EXPORT_ALL_RESULTDATA_PROGRESS_NAME"; + + String EXPORT_ALL_DATA_PROGRESS_NAME = "EXPORT_ALL_DATA_PROGRESS_NAME"; + + String CREATE_SEQ_PROGRESS_NAME = "CREATE_SEQ_PROGRESS_NAME"; + + String REEXECUTE_QUERY_PROGRESS_NAME = "REEXECUTE_QUERY_PROGRESS_NAME"; + + String LAZYLOAD_NAMESPACE_PROGRESS_NAME = "LAZYLOAD_NAMESPACE_PROGRESS_NAME"; + + String ALTER_VIEWCOLUMN_DEFAULT_PROGRESS_NAME = "ALTER_VIEWCOLUMN_DEFAULT_PROGRESS_NAME"; + + String EXPORT_CURRENT_RESULTDATA_PROGRESS_NAME = "EXPORT_CURRENT_RESULTDATA_PROGRESS_NAME"; + + String CHANGE_INDEX_FOR_COLUMN_ORIENTATION_TBL = "CHANGE_INDEX_FOR_COLUMN_ORIENTATION_TABLE"; + + String CONN_PROP_HOST = "CONN_PROP_HOST"; + + String CONN_PROP_PORT = "CONN_PROP_PORT"; + + String CONN_PROP_USERNAME = "CONN_PROP_USERNAME"; + + String CONN_PROP_SERVER_TYPE = "CONN_PROP_SERVER_TYPE"; + + String CONN_PROP_DB_VERSION = "CONN_PROP_DB_VERSION"; + + String CONNECTION_VERSION_NUMBER_FAILED_MSG = "CONNECTION_VERSION_NUMBER_FAILED_MSG"; + + String CONNECTION_PROPERTIES_UNAVAILABLE = "CONNECTION_PROPERTIES_UNAVAILABLE"; + + String SAVING_PREFERENCES = "SAVING_PREFERENCES"; + + // Templates Preference Page Starts + String CODE_TEMPLATE_PREFPAGE_MESSAGE = "CODE_TEMPLATE_PREFPAGE_MESSAGE"; + + String CODE_TEMPLATE_PREFPAGE_TITLE = "CODE_TEMPLATE_PREFPAGE_TITLE"; + + String CODE_TEMPLATE_DUPLICATE_MSG = "CODE_TEMPLATE_DUPLICATE_MSG"; + + String CODE_TEMPLATE_PREFPAGE_EDIT = "CODE_TEMPLATE_PREFPAGE_EDIT"; + + String CODE_TEMPLATE_PREFPAGE_NEW = "CODE_TEMPLATE_PREFPAGE_NEW"; + + String CODE_TEMPLATE_PREFPAGE_REMOVE = "CODE_TEMPLATE_PREFPAGE_REMOVE"; + + String CODE_TEMPLATE_PREFPAGE_RESTORE = "CODE_TEMPLATE_PREFPAGE_RESTORE"; + + String CODE_TEMPLATE_PREFPAGE_REVERT = "CODE_TEMPLATE_PREFPAGE_REVERT"; + + String CODE_TEMPLATE_PREFPAGE_COLUMN_NAME = "CODE_TEMPLATE_PREFPAGE_COLUMN_NAME"; + + String CODE_TEMPLATE_PREFPAGE_COLUMN_DESCRIPTION = "CODE_TEMPLATE_PREFPAGE_COLUMN_DESCRIPTION"; + + String CODE_TEMPLATE_PREFPAGE_MATCH_CASE = "CODE_TEMPLATE_PREFPAGE_MATCH_CASE"; + + String CODE_TEMPLATE_PREFPAGE_PREVIEW = "CODE_TEMPLATE_PREFPAGE_PREVIEW"; + + String CODE_TEMPLATE_PREFPAGE_ERROR_READ_TITLE = "CODE_TEMPLATE_PREFPAGE_ERROR_READ_TITLE"; + + String CODE_TEMPLATE_PREFPAGE_ERROR_READ_MESSAGE = "CODE_TEMPLATE_PREFPAGE_ERROR_READ_MESSAGE"; + + String CODE_TEMPLATE_PREFPAGE_ERROR_WRITE_TITLE = "CODE_TEMPLATE_PREFPAGE_ERROR_WRITE_TITLE"; + + String CODE_TEMPLATE_PREFPAGE_ERROR_WRITE_MESSAGE = "CODE_TEMPLATE_PREFPAGE_ERROR_WRITE_MESSAGE"; + + String FAILED_TO_WRITE_TO_EXCEL = "FAILED_TO_WRITE_TO_EXCEL"; + + String CODE_TEMPLATE_DIALOG_TITLE_EDIT = "CODE_TEMPLATE_DIALOG_TITLE_EDIT"; + + String CODE_TEMPLATE_DIALOG_TITLE_NEW = "CODE_TEMPLATE_DIALOG_TITLE_NEW"; + + String CODE_TEMPLATE_DIALOG_NAME = "CODE_TEMPLATE_DIALOG_NAME"; + + String CODE_TEMPLATE_DIALOG_DESCRIPTION = "CODE_TEMPLATE_DIALOG_DESCRIPTION"; + + String CODE_TEMPLATE_DIALOG_PATTERN = "CODE_TEMPLATE_DIALOG_PATTERN"; + + String CODE_TEMPLATE_DIALOG_MANDATORY_MARK = "CODE_TEMPLATE_DIALOG_MANDATORY_MARK"; + + String CODE_TEMPLATE_DIALOG_COLON = "CODE_TEMPLATE_DIALOG_COLON"; + + String CODE_TEMPLATE_DIALOG_MAX_CHAR = "CODE_TEMPLATE_DIALOG_MAX_CHAR"; + + String CODE_TEMPLATE_DIALOG_NAME_RESTRICTION_MSG = "CODE_TEMPLATE_DIALOG_NAME_RESTRICTION_MSG"; + + String CODE_TEMPLATE_DIALOG_UNDO = "CODE_TEMPLATE_DIALOG_UNDO"; + + String CODE_TEMPLATE_DIALOG_REDO = "CODE_TEMPLATE_DIALOG_REDO"; + + String CODE_TEMPLATE_DIALOG_CUT = "CODE_TEMPLATE_DIALOG_CUT"; + + String CODE_TEMPLATE_DIALOG_COPY = "CODE_TEMPLATE_DIALOG_COPY"; + + String CODE_TEMPLATE_DIALOG_PASTE = "CODE_TEMPLATE_DIALOG_PASTE"; + + String CODE_TEMPLATE_DIALOG_SELECT_ALL = "CODE_TEMPLATE_DIALOG_SELECT_ALL"; + + String CODE_TEMPLATE_DUPLICATE_ID = "CODE_TEMPLATE_DUPLICATE_ID"; + + String CODE_TEMPLATE_ILLEGAL_BOOLEAN_ATTR = "CODE_TEMPLATE_ILLEGAL_BOOLEAN_ATTR"; + + String CODE_TEMPLATE_JSONEXCEPTION = "CODE_TEMPLATE_JSONEXCEPTION"; + + String CODE_TEMPLATE_MISSING_REQUIRED_ATTR = "CODE_TEMPLATE_MISSING_REQUIRED_ATTR"; + + String CODE_TEMPLATE_PREFPAGE_UNSAVEDCHANGED_TITLE = "CODE_TEMPLATE_PREFPAGE_UNSAVEDCHANGED_TITLE"; + + String PREFERENCE_CHANGE_NOT_APPLIED_MESSAGE = "PREFERENCE_CHANGE_NOT_APPLIED_MESSAGE"; + + String DB_CONN_SERVER_DOMAIN_NAME_ERROR = "DB_CONN_SERVER_DOMAIN_NAME_ERROR"; + + String DB_CONN_DOMAIN_NAME_ERROR = "DB_CONN_DOMAIN_NAME_ERROR"; + + String CONN_PROP_SERVER_IP = "CONN_PROP_SERVER_IP"; + + String SERVERIP_TOOLTIP = "SERVERIP_TOOLTIP"; + + String SERVERIP_TOOLTIP_FAIL = "SERVERIP_TOOLTIP_FAIL"; + + String SERVERVERSION_TOOLTIP = "SERVERVERSION_TOOLTIP"; + + String EXECUTION_FAILURE_LINE_NUMEBR = "EXECUTION_FAILURE_LINE_NUMEBR"; + + String BUTTON_LABEL_SHOW_DETAILS = "BUTTON_LABEL_SHOW_DETAILS"; + + String BUTTON_LABEL_HIDE_DETAILS = "BUTTON_LABEL_HIDE_DETAILS"; + + String EXECUTION_FAILURE_DETAILS_DESCRIPTION = "EXECUTION_FAILURE_DETAILS_DESCRIPTION"; + + String EXEC_PLAN_COST_TOOLTIP = "EXEC_PLAN_COST_TOOLTIP"; + + String VIS_EXPLAIN_EXEC_PLAN_COLUMN_ENTITYNAME = "VIS_EXPLAIN_EXEC_PLAN_COLUMN_ENTITYNAME"; + + String VIS_EXPLAIN_EXEC_PLAN_COLUMN_COST = "VIS_EXPLAIN_EXEC_PLAN_COLUMN_COST"; + + String VIS_EXPLAIN_EXEC_PLAN_COLUMN_ROWS = "VIS_EXPLAIN_EXEC_PLAN_COLUMN_ROWS"; + + String VIS_EXPLAIN_EXEC_PLAN_COLUMN_LOOPS = "VIS_EXPLAIN_EXEC_PLAN_COLUMN_LOOPS"; + + String VIS_EXPLAIN_EXEC_PLAN_COLUMN_WIDTH = "VIS_EXPLAIN_EXEC_PLAN_COLUMN_WIDTH"; + + String VIS_EXPLAIN_EXEC_PLAN_COLUMN_ACTUAL_ROWS = "VIS_EXPLAIN_EXEC_PLAN_COLUMN_ACTUAL_ROWS"; + + String VIS_EXPLAIN_EXEC_PLAN_COLUMN_ACTUAL_TIME = "VIS_EXPLAIN_EXEC_PLAN_COLUMN_ACTUAL_TIME"; + + String VIS_EXPLAIN_PROPERTIES_EXEC_PLAN_TITLE = "VIS_EXPLAIN_PROPERTIES_EXEC_PLAN_TITLE"; + + String PROPERTIES_WINDOW_ERROR_POPUP_HEADER = "PROPERTIES_WINDOW_ERROR_POPUP_HEADER"; + + String ERR_CONSTRAINT_NAME_EMPTY = "ERR_CONSTRAINT_NAME_EMPTY"; + + String ERR_COLUMN_NAME_EMPTY = "ERR_COLUMN_NAME_EMPTY"; + + String PROPERTIES_ERROR_MESSAGE = "PROPERTIES_ERROR_MESSAGE"; + + String PROPERTIES_ERROR_MESSAGE_FOR_CONSTRAINT = "PROPERTIES_ERROR_MESSAGE_FOR_CONSTRAINT"; + + String DOMAINNAME_REDIRECT_FAILURE = "DOMAINNAME_REDIRECT_FAILURE"; + + // Batch Delete Messages + String DROP_OBJECTS_WINDOW_TITLE = "DROP_OBJECTS_WINDOW_TITLE"; + + String DROP_OBJECTS_WINDOW_SHORTTITLE = "DROP_OBJECTS_WINDOW_SHORTTITLE"; + + String DROP_OBJECTS_NATTABLE_COLUMN_ERR_MSG = "DROP_OBJECTS_NATTABLE_COLUMN_ERR_MSG"; + + String DROP_OBJECTS_NATTABLE_COLUMN_NAME = "DROP_OBJECTS_NATTABLE_COLUMN_NAME"; + + String DROP_OBJECTS_NATTABLE_COLUMN_QUERY = "DROP_OBJECTS_NATTABLE_COLUMN_QUERY"; + + String DROP_OBJECTS_NATTABLE_COLUMN_STATUS = "DROP_OBJECTS_NATTABLE_COLUMN_STATUS"; + + String DROP_OBJECTS_NATTABLE_COLUMN_TYPE = "DROP_OBJECTS_NATTABLE_COLUMN_TYPE"; + + String DROP_OBJECTS_OPER_ATOMIC = "DROP_OBJECTS_OPER_ATOMIC"; + + String DROP_OBJECTS_OPER_CASCADE = "DROP_OBJECTS_OPER_CASCADE"; + + String DROP_OBJECTS_OPER_START = "DROP_OBJECTS_OPER_START"; + + String DROP_OBJECTS_OPER_STOP = "DROP_OBJECTS_OPER_STOP"; + + String DROP_OBJECTS_OPER_DB_NAME = "DROP_OBJECTS_OPER_DB_NAME"; + + String DROP_OBJECTS_OPER_LBL_RUNS = "DROP_OBJECTS_OPER_LBL_RUNS"; + + String DROP_OBJECTS_OPER_LBL_ERRORS = "DROP_OBJECTS_OPER_LBL_ERRORS"; + + String DROP_OBJECTS_OPER_STATUS_COMPLETED = "DROP_OBJECTS_OPER_STATUS_COMPLETED"; + + String DROP_OBJECTS_OPER_STATUS_ERROR = "DROP_OBJECTS_OPER_STATUS_ERROR"; + + String DROP_OBJECTS_OPER_STATUS_INPROGRESS = "DROP_OBJECTS_OPER_STATUS_INPROGRESS"; + + String DROP_OBJECTS_OPER_STATUS_TOSTART = "DROP_OBJECTS_OPER_STATUS_TOSTART"; + + String DROP_OBJECTS_NOT_ALLOWED_DIALOG_TITLE = "DROP_OBJECTS_NOT_ALLOWED_DIALOG_TITLE"; + + String DROP_OBJECTS_NOT_ALLOWED_DIALOG_MESSAGE = "DROP_OBJECTS_NOT_ALLOWED_DIALOG_MESSAGE"; + + String DROP_OBJECTS_NOT_ALLOWED_NO_DB_DIALOG_MESSAGE = "DROP_OBJECTS_NOT_ALLOWED_NO_DB_DIALOG_MESSAGE"; + + String DROP_OBJECTS_NOT_ALLOWED_OBJECT_DIALOG_MESSAGE = "DROP_OBJECTS_NOT_ALLOWED_OBJECT_DIALOG_MESSAGE"; + + String DROP_OBJECTS_NOT_ALLOWED_OBJECT_DIALOG_OBJ_LIST = "DROP_OBJECTS_NOT_ALLOWED_OBJECT_DIALOG_OBJ_LIST"; + + String DROP_OBJECTS_OPER_STOP_DIALOG_TITLE = "DROP_OBJECTS_OPER_STOP_DIALOG_TITLE"; + + String DROP_OBJECTS_OPER_STOP_DIALOG_MESSAGE = "DROP_OBJECTS_OPER_STOP_DIALOG_MESSAGE"; + + String DROP_OBJECTS_JOB_NAME = "DROP_OBJECTS_JOB_NAME"; + + String DROP_OBJECTS_JOB_FINISHED_STATUS = "DROP_OBJECTS_JOB_FINISHED_STATUS"; + + String DROP_OBJECTS_JOB_FAILURE_STATUS = "DROP_OBJECTS_JOB_FAILURE_STATUS"; + + String DROP_OBJECTS_JOB_STOPPED_STATUS = "DROP_OBJECTS_JOB_STOPPED_STATUS"; + + String TABLE_PROPERTIES_INVALID_BOOLEAN_DATATYPE = "TABLE_PROPERTIES_INVALID_BOOLEAN_DATATYPE"; + + String PROPERTIES_COMPLEX_DATATYPE_ERROR_MSG = "PROPERTIES_COMPLEX_DATATYPE_ERROR_MSG"; + + String PREFERENCE_SHORTCUT_KEY_BINDING_TOGGLE_LINE_COMMENTS = "PREFERENCE_SHORTCUT_KEY_BINDING_TOGGLE_LINE_COMMENTS"; + + String PREFERENCE_SHORTCUT_KEY_BINDING_TOGGLE_BLOCK_COMMENTS = "PREFERENCE_SHORTCUT_KEY_BINDING_TOGGLE_BLOCK_COMMENTS"; + + // debug + String PREFERENCE_SHORTCUT_KEY_BINDING_START_DEBUG = "PREFERENCE_SHORTCUT_KEY_BINDING_START_DEBUG"; + String PREFERENCE_SHORTCUT_KEY_BINDING_TERNIMATE_DEBUG = "PREFERENCE_SHORTCUT_KEY_BINDING_TERNIMATE_DEBUG"; + String PREFERENCE_SHORTCUT_KEY_BINDING_STEPIN_DEBUG = "PREFERENCE_SHORTCUT_KEY_BINDING_STEPIN_DEBUG"; + String PREFERENCE_SHORTCUT_KEY_BINDING_STEPOUT_DEBUG = "PREFERENCE_SHORTCUT_KEY_BINDING_STEPOUT_DEBUG"; + String PREFERENCE_SHORTCUT_KEY_BINDING_STEPOVER_DEBUG = "PREFERENCE_SHORTCUT_KEY_BINDING_STEPOVER_DEBUG"; + String PREFERENCE_SHORTCUT_KEY_BINDING_CONTINUE_DEBUG = "PREFERENCE_SHORTCUT_KEY_BINDING_CONTINUE_DEBUG"; + + String MAX_CHARATCTERS_ALLOWED_FOR_TABLE_DESC = "MAX_CHARATCTERS_ALLOWED_FOR_TABLE_DESC"; + + String MPPDBIDE_DIA_BTN_RECONNECT = "MPPDBIDE_DIA_BTN_RECONNECT"; + + String MPPDBIDE_DIA_BTN_RECONNECT_CONTINUE = "MPPDBIDE_DIA_BTN_RECONNECT_CONTINUE"; + + String MULTIPLE_CONNECTION_ATTEMPT_ON_CRITICAL_ERROR = "MULTIPLE_CONNECTION_ATTEMPT_ON_CRITICAL_ERROR"; + + String CONNECTION_ATTEMPT_ON_CRITICAL_ERROR = "CONNECTION_ATTEMPT_ON_CRITICAL_ERROR"; + + String RECONNECT_FOR_EXECUTION_PLAN_VISUAL_EXPLAIN = "RECONNECT_FOR_EXECUTION_PLAN_VISUAL_EXPLAIN"; + + String OBJECT_NAME_MORE_THAN_LIMIT_ERROR_MESSAGE = "OBJECT_NAME_MORE_THAN_LIMIT_ERROR_MESSAGE"; + + String PRESERVESQL_STARTUP_DIALOG_MESSAGE = "PRESERVESQL_STARTUP_DIALOG_MESSAGE"; + + String PRESERVESQL_STARTUP_JOB_NAME = "PRESERVESQL_STARTUP_JOB_NAME"; + + String PRESERVESQL_STARTUP_LAZY_JOB_NAME = "PRESERVESQL_STARTUP_LAZY_JOB_NAME"; + + String PRESERVESQL_STARTUP_LOADING_FAILED = "PRESERVESQL_STARTUP_LOADING_FAILED"; + + String PRESERVESQL_STARTUP_LOADING_FINISHED = "PRESERVESQL_STARTUP_LOADING_FINISHED"; + + String PRESERVESQL_STARTUP_MAX_TAB_REACHED = "PRESERVESQL_STARTUP_MAX_TAB_REACHED"; + + String PRESERVESQL_GRACEFUL_EXIT_MSG = "PRESERVE_SQL_GRACEFUL_EXIT_MSG"; + + String PRESERVESQL_PERIODIC_JOB_NAME = "PRESERVESQL_PERIODIC_JOB_NAME"; + + String PRESERVESQL_JSONEXCEPTION = "PRESERVESQL_JSONEXCEPTION"; + + String PRESERVESQL_FOLDERCREATEDELETEEXCEPTION = "PRESERVESQL_FOLDERCREATEDELETEEXCEPTION"; + + String PRESERVESQL_FILEREADEXCEPTION = "PRESERVESQL_FILEREADEXCEPTION"; + + String PRESERVESQL_FILEENCODINGEXCEPTION = "PRESERVESQL_FILEENCODINGEXCEPTION"; + + String PREFERENCE_AUTOSAVE = "PREFERENCE_AUTOSAVE"; + + String PREFERENCE_ENABLE_AUTOSAVE = "PREFERENCE_ENABLE_AUTOSAVE"; + + String PREFERENCE_INTERVAL_AUTOSAVE = "PREFERENCE_INTERVAL_AUTOSAVE"; + + String PREFERENCE_INTERVAL_AUTOSAVE_RANGE = "PREFERENCE_INTERVAL_AUTOSAVE_RANGE"; + + String PREFERENCE_ENABLE_ENCRYPTION = "PREFERENCE_ENABLE_ENCRYPTION"; + + String PREFERENCE_INTERVAL_ERROR_MSG = "PREFERENCE_INTERVAL_ERROR_MSG"; + + String SESSIONSETTINGS_PREFPAGE_UNSAVEDCHANGED_TITLE = "SESSIONSETTINGS_PREFPAGE_UNSAVEDCHANGED_TITLE"; + + String PRESERVESQL_PERIODIC_SAVE_FINISHED = "PRESERVESQL_PERIODIC_SAVE_FINISHED"; + + String PRESERVESQL_PERIODIC_SAVE_TAB_STATUS = "PRESERVESQL_PERIODIC_SAVE_TAB_STATUS"; + + String PRESERVESQL_FILEWRITEEXCEPTION = "PRESERVESQL_FILEWRITEEXCEPTION"; + + String PREFERENCE_AUTOSAVE_DESC = "PREFERENCE_AUTOSAVE_DESC"; + + String PREFERENCE_INTERVAL_DESC = "PREFERENCE_INTERVAL_DESC"; + + String PREFERENCE_ENCRYPTION_DESC = "PREFERENCE_ENCRYPTION_DESC"; + + String UPDATE_DBG_OBJ_TITLE = "UPDATE_DBG_OBJ_TITLE"; + + String UPDATE_DBG_OBJ_QUESTION = "UPDATE_DBG_OBJ_QUESTION"; + + // TRANSLATION FOR ENCODING ENCODING STARTS + + String ENCODING_QUERY_RESULT_DATA_ENCODING_HEADER = "ENCODING_QUERY_RESULT_DATA_ENCODING_HEADER"; + + String ENCODING_QUERY_RESULT_DATA_ENCODING_BODY = "ENCODING_QUERY_RESULT_DATA_ENCODING_BODY"; + + String ENCODING_QUERY_RESULT_DATA_ENCODING_DESC = "ENCODING_QUERY_RESULT_DATA_ENCODING_DESC"; + + String TEXTMODE_QUERY_RESULT_DATA_TEXTMODE_HEADER = "TEXTMODE_QUERY_RESULT_DATA_TEXTMODE_HEADER"; + + String TEXTMODE_QUERY_RESULT_DATA_TEXTMODE_BODY = "TEXTMODE_QUERY_RESULT_DATA_TEXTMODE_BODY"; + + String TEXTMODE_QUERY_RESULT_DATA_TEXTMODE_DESC = "TEXTMODE_QUERY_RESULT_DATA_TEXTMODE_DESC"; + + String FORMATTER_NODE = "FORMATTER_NODE"; + + String BUILD_TIME = "BUILD_TIME"; + + String PREF_FORMATTER_SETTING = "PREF_FORMATTER_SETTING"; + + // TRANSLATION FOR ENCODING ENCODING ENDS + String BATCH_EXPORT_DDL_ERROR_FAIL_OBJ = "BATCH_EXPORT_DDL_ERROR_FAIL_OBJ"; + + String BATCH_EXPORT_WARNING_TEXT = "BATCH_EXPORT_WARNING_TEXT"; + + String BATCH_EXPORT_JOB = "BATCH_EXPORT_JOB"; + + String BATCH_EXPORT_DDL_VALID_OBJ = "BATCH_EXPORT_DDL_VALID_OBJ"; + + String BATCH_EXPORT_DDL_VALID_OBJ_LIST = "BATCH_EXPORT_DDL_VALID_OBJ_LIST"; + + String BATCH_EXPORT_DDLDATA_VALID_OBJ_LIST = "BATCH_EXPORT_DDLDATA_VALID_OBJ_LIST"; + + String BATCH_EXPORT_DDL_MULTIPLE_DB = "BATCH_EXPORT_DDL_MULTIPLE_DB"; + + String BATCH_EXPORT_DDL_NO_OBJ = "BATCH_EXPORT_DDL_NO_OBJ"; + + String EXPORT_FAIL_PROCESS_INTRUPTED_FOR_OBJ = "EXPORT_FAIL_PROCESS_INTRUPTED_FOR_OBJ"; + + String BATCH_EXPORT_NO_USER_PREVILAGE = "BATCH_EXPORT_NO_USER_PREVILAGE"; + + String BATCH_EXPORT_ERROR_SHORT_MSG = "BATCH_EXPORT_ERROR_SHORT_MSG"; + + String FORMATTER_PREFPAGE_UNSAVEDCHANGED_TITLE = "FORMATTER_PREFPAGE_UNSAVEDCHANGED_TITLE"; + + String BUILD_TIME_UNKNOWN = "BUILD_TIME_UNKNOWN"; + + String EXPORT_FAIL_PROCESS_INTRUPTED_WITHOUT_SERVER_MSG = "EXPORT_FAIL_PROCESS_INTRUPTED_WITHOUT_SERVER_MSG"; + + String EXPORT_FAIL_PROCESS_TITLE = "EXPORT_FAIL_PROCESS_TITLE"; + + // FUNCTION CHANGE INTIMATION + String FUNCTN_CHANGE_TITLE = "FUNCTN_CHANGE_TITLE"; + + String FUNCTN_CHANGE_MSG = "FUNCTN_CHANGE_MSG"; + + String FUNCTN_CHANGE_REFRESH = "FUNCTN_CHANGE_REFRESH"; + + String FUNCTN_CHANGE_OVERWRITE = "FUNCTN_CHANGE_OVERWRITE"; + + String FUNCTN_CHANGE_CANCEL = "FUNCTN_CHANGE_CANCEL"; + + String FUNCTN_CHANGE_VIEWSOURCE_MSG = "FUNCTN_CHANGE_VIEWSOURCE_MSG"; + + String FUNCTN_CHANGE_PREVIEW = "FUNCTN_CHANGE_PREVIEW"; + + String FUNCT_CHANGE_VIEWSOURCE_ERR = "FUNCT_CHANGE_VIEWSOURCE_ERR"; + + String FUNCT_CHANGE_COMPILE_ERR = "FUNCT_CHANGE_COMPILE_ERR"; + + String FUNCT_CHANGE_EXECUTE_ERR = "FUNCT_CHANGE_EXECUTE_ERR"; + + String FUNCT_CHANGE_ERR_COMPILE_BACKEND = "FUNCT_CHANGE_ERR_COMPILE_BACKEND"; + + String MSG_GUI_OBJECT_MAY_DROPPED = "MSG_GUI_OBJECT_MAY_DROPPED"; + + // TRANSLATION FOR TEMP TABLE SUPPORT + String SQL_TERMINAL_REUSE_CONNECTION_TOOLTIP = "SQL_TERMINAL_REUSE_CONNECTION_TOOLTIP"; + + String SQL_TERMINAL_NEW_CONNECTION_TOOLTIP = "SQL_TERMINAL_NEW_CONNECTION_TOOLTIP"; + + String SET_GBK_FILE_ENCODE_PREF = "SET_GBK_FILE_ENCODE_PREF"; + + String CHECK_FILE_ENCODE_SET = "CHECK_FILE_ENCODE_SET"; + + String PROPERTIES_CONSTRAINT_CONSTRAINTNAME = "PROPERTIES_CONSTRAINT_CONSTRAINTNAME"; + + String PROPERTIES_CONSTRAINT_COLUMNS = "PROPERTIES_CONSTRAINT_COLUMNS"; + + String PROPERTIES_CONSTRAINT_TYPE = "PROPERTIES_CONSTRAINT_TYPE"; + + String PROPERTIES_EXPRESSION = "PROPERTIES_EXPRESSION"; + + String PROPERTIES_CONSTRAINT_ISDEFFERED = "PROPERTIES_CONSTRAINT_ISDEFFERED"; + + String PROPERTIES_CONSTRAINT_SCHEMA = "PROPERTIES_CONSTRAINT_SCHEMA"; + + String PROPERTIES_TABLESPACE = "PROPERTIES_TABLESPACE"; + + String PROPERTIES_COLUMNS_COLUMNSNAME = "PROPERTIES_COLUMNS_COLUMNSNAME"; + + String PROPERTIES_COLUMNS_DATATYPE = "PROPERTIES_COLUMNS_DATATYPE"; + + String PROPERTIES_COLUMNS_ISNULLABLE = "PROPERTIES_COLUMNS_ISNULLABLE"; + + String PROPERTIES_COLUMNS_COMMENTS = "PROPERTIES_COLUMNS_COMMENTS"; + + String PROPERTIES_INDEX_INDEXNAME = "PROPERTIES_INDEX_INDEXNAME"; + + String PROPERTIES_INDEX_INDEXCOLUMNS = "PROPERTIES_INDEX_INDEXCOLUMNS"; + + String PROPERTIES_INDEX_ISUNIQUE = "PROPERTIES_INDEX_ISUNIQUE"; + + String PROP_PARTITION_PARTITIONNAME = "PROPERTIES_PARTITION_PARTITIONNAME"; + + String PROP_PARTITION_PARTITIONBOUNDARIES = "PROPERTIES_PARTITION_PARTITIONBOUNDARIES"; + + String CREATE_FILE_FAIL_ERR = "CREATE_FILE_FAIL_ERR"; + + String CREATE_FOLDER_FAIL_ERR = "CREATE_FOLDER_FAIL_ERR"; + + String RECONNECT_SUCCESSFUL_MSG = "RECONNECT_SUCCESSFUL_MSG"; + + String RECONNECT_ATTEMP_FAILURE_MSG = "RECONNECT_ATTEMP_FAILURE_MSG"; + + // Edit Query Results + String RESULTSET_EDITABLE_MSG = "RESULTSET_EDITABLE_MSG"; + + String RESULTSET_NON_EDITABLE_MSG = "RESULTSET_NON_EDITABLE_MSG"; + + String RESULTSET_ALL_DATALOAD_MSG = "RESULTSET_ALL_DATALOAD_MSG"; + + // execution plan views + String TOOLBAR_TREE_VIEW = "TOOLBAR_TREE_VIEW"; + + String TOOLBAR_TEXT_VIEW = "TOOLBAR_TEXT_VIEW"; + + String EXECUTION_PLAN_JOB = "EXECUTION_PLAN_JOB"; + + String EXECUTION_PLAN_SAVE = "EXECUTION_PLAN_SAVE"; + + String EXECUTION_PLAN_SAVE_POPUP_TITLE = "EXECUTION_PLAN_SAVE_POPUP_TITLE"; + + String EXECUTION_PLAN_SAVE_POPUP_MSG = "EXECUTION_PLAN_SAVE_POPUP_MSG"; + + String INCLUDE_ANALYZE_DROPDOWN = "INCLUDE_ANALYZE_DROPDOWN"; + + String ERROR_EXPORT_EXCEL_RESULTSET = "ERROR_EXPORT_EXCEL_RESULTSET"; + + String ERROR_EXPORT_EXCEL_PARSER = "ERROR_EXPORT_EXCEL_PARSER"; + + String ERR_EXPORT_TABLE_FAIL = "ERR_EXPORT_TABLE_FAIL"; + + String ERR_EXPORT_EXCEL_OPERATION = "ERR_EXPORT_EXCEL_OPERATION"; + + // DBTYPE + String LBL_DBTYPE = "LBL_DBTYPE"; + + String OPEN_GAUSS = "OPEN_GAUSS"; + + String ERROR_EXCEL_ROW_COLUMN_LIMIT = "ERROR_EXCEL_ROW_COLUMN_LIMIT"; + + String EXPORT_INFORMATION = "EXPORT_INFORMATION"; + + String ERR_WHILE_FUNCTION_REFRESH = "ERR_WHILE_FUNCTION_REFRESH"; + + String VERSION_NO_INCOMPATIBLE = "VERSION_NO_INCOMPATIBLE"; + + String SQL_TERMINAL_RIGHT_CLICK_MENU_ITEM_FORMAT = "SQL_TERMINAL_RIGHT_CLICK_MENU_ITEM_FORMAT"; + + // User Role Management + String USER_ROLE_GROUP_DISPLAY_NAME = "USER_ROLE_GROUP_DISPLAY_NAME"; + + String GRANT_REVOKE_WIZARD = "GRANT_REVOKE_WIZARD"; + + String GRANT_REVOKE_WIZARD_OBJECT_SELECTION = "GRANT_REVOKE_WIZARD_OBJECT_SELECTION"; + + String GRANT_REVOKE_WIZARD_PRIVILEGE_SELECTION = "GRANT_REVOKE_WIZARD_PRIVILEGE_SELECTION"; + + String GRANT_REVOKE_WIZARD_SQL_PREVIEW = "GRANT_REVOKE_WIZARD_SQL_PREVIEW"; + + String USER_ROLE_TAB_COLUMN_TITLE_PROPERTY = "USER_ROLE_TAB_COLUMN_TITLE_PROPERTY"; + + String USER_ROLE_TAB_COLUMN_TITLE_VALUE = "USER_ROLE_TAB_COLUMN_TITLE_VALUE"; + + String USER_ROLE_NAME = "USER_ROLE_NAME"; + + String USER_ROLE_CONNECT_LIMIT = "USER_ROLE_CONNECT_LIMIT"; + + String USER_ROLE_VALID_UNTIL = "USER_ROLE_VALID_UNTIL"; + + String USER_ROLE_CREATE_ROLE = "USER_ROLE_CREATE_ROLE"; + + String USER_ROLE_CREATE_DB = "USER_ROLE_CREATE_DB"; + + String USER_ROLR_INHERIT = "USER_ROLR_INHERIT"; + + String USER_ROLE_REPLICATION = "USER_ROLE_REPLICATION"; + + String USER_ROLE_CAN_LOGIN = "USER_ROLE_CAN_LOGIN"; + + String USER_ROLE_SYSTEM_ADMIN = "USER_ROLE_SYSTEM_ADMIN"; + + String USER_ROLE_VALID_BEGIN = "USER_ROLE_VALID_BEGIN"; + + String USER_ROLE_RESOURCE_POOL = "USER_ROLE_RESOURCE_POOL"; + + String USER_ROLE_COMMENT = "USER_ROLE_COMMENT"; + + String USER_ROLE_PROPERTY_TAB_GENERAL = "USER_ROLE_PROPERTY_TAB_GENERAL"; + + String USER_ROLE_PROPERTY_TAB_PRIVILEGE = "USER_ROLE_PROPERTY_TAB_PRIVILEGE"; + + String USER_ROLE_PROPERTY_TAB_MEMBERSHIP = "USER_ROLE_PROPERTY_TAB_MEMBERSHIP"; + + String USER_ROLE_AUDITOR = "USER_ROLE_AUDITOR"; + + String USER_ROLE_IS_LOCK = "USER_ROLE_IS_LOCK"; + + String USER_ROLE_TAB_COLUMN_TITLE_USER_ROLE = "USER_ROLE_TAB_COLUMN_TITLE_USER_ROLE"; + + String USER_ROLE_TAB_COLUMN_TITLE_BELONG_TO = "USER_ROLE_TAB_COLUMN_TITLE_BELONG_TO"; + + String USER_ROLE_TAB_COLUMN_TITLE_IS_ENABLE = "USER_ROLE_TAB_COLUMN_TITLE_IS_ENABLE"; + + String ERR_USER_ROLE_NAME_EMPTY = "ERR_USER_ROLE_NAME_EMPTY"; + + String ERR_USER_ROLE_IS_NOT_EXIST = "ERR_USER_ROLE_IS_NOT_EXIST"; + + String ERR_FETCH_USER_ROLE_LOCK_STATUS = "ERR_FETCH_USER_ROLE_LOCK_STATUS"; + + String ERR_USER_ROLE_ALTER_FAILURE = "ERR_USER_ROLE_ALTER_FAILURE"; + + String ERR_USER_ROLE_BEGIN_DATE_NULL = "ERR_USER_ROLE_BEGIN_DATE_NULL"; + + String ERR_USER_ROLE_VALID_UNTIL_DATE_NULL = "ERR_USER_ROLE_VALID_UNTIL_DATE_NULL"; + + String USER_ROLE_PREVIEW_SQL_CONFIRM = "USER_ROLE_PREVIEW_SQL_CONFIRM"; + + String GRANT_REVOKE_PLS_SELECT_OBJECT = "GRANT_REVOKE_PLS_SELECT_OBJECT"; + + String GRANT_REVOKE_PLS_SELECT_USER_ROLE = "GRANT_REVOKE_PLS_SELECT_USER_ROLE"; + + String GRANT_REVOKE_PLS_SELECT_PRIVILEGE = "GRANT_REVOKE_PLS_SELECT_PRIVILEGE"; + + String UPDATE_OBJECT_PRIVILEGE_DIALOG_TITLE = "UPDATE_OBJECT_PRIVILEGE_DIALOG_TITLE"; + + String ERR_UPDATE_OBJECT_PRIVILEGE_DETAIL = "ERR_UPDATE_OBJECT_PRIVILEGE_DETAIL"; + + String SUCCESS_UPDATE_OBJECT_PRIVILEGE_DETAIL = "SUCCESS_UPDATE_OBJECT_PRIVILEGE_DETAIL"; + + String UPDATE_OBJECT_PRIVILEGE_DIALOG_DIFF_OBJECT_TYPE = "UPDATE_OBJECT_PRIVILEGE_DIALOG_DIFF_OBJECT_TYPE"; + + String GRANT_REVOKE_SELECT_ALL_OBJECT = "GRANT_REVOKE_SELECT_ALL_OBJECT"; + + String GRANT_REVOKE_SEARCH_OBJECT = "GRANT_REVOKE_SEARCH_OBJECT"; + + String GRANT_REVOKE_ROLE = "GRANT_REVOKE_ROLE"; + + String GRANT_REVOKE_GRANT_OPTION = "GRANT_REVOKE_GRANT_OPTION"; + + String GRANT_REVOKE_REVOKE_OPTION = "GRANT_REVOKE_REVOKE_OPTION"; + + String USER_ROLE_PREVIEW_SQL_CHANGE_NOTHING = "USER_ROLE_PREVIEW_SQL_CHANGE_NOTHING"; + + String STATUS_MSG_MODIFYING_OBJECT_PRIVILEGE = "STATUS_MSG_MODIFYING_OBJECT_PRIVILEGE"; + + String ERR_USER_ROLE_CONNECT_LIMIT_INVALID = "ERR_USER_ROLE_CONNECT_LIMIT_INVALID"; + + String USER_ROLE_PREVIEW_SQL_CONFIRM_MESSAGE = "USER_ROLE_PREVIEW_SQL_CONFIRM_MESSAGE"; + + String USER_ROLE_COMMENT_ERROR_MESSAGE = "USER_ROLE_COMMENT_ERROR_MESSAGE"; + + String CREATE_USER_ROLE_NO_DATABASE = "CREATE_USER_ROLE_NO_DATABASE"; + + String EXPLAIN_PLAN_MORE_THAN_ONE_QUERY_TITLE = "EXPLAIN_PLAN_MORE_THAN_ONE_QUERY_TITLE"; + + String EXPLAIN_PLAN_MORE_THAN_ONE_QUERY_MSG = "EXPLAIN_PLAN_MORE_THAN_ONE_QUERY_MSG"; + + String EXPLAIN_ANALYZE_WINDOW_TITLE = "EXPLAIN_ANALYZE_WINDOW_TITLE"; + + String EXPLAIN_ANALYZE_WARNING_MSG = "EXPLAIN_ANALYZE_WARNING_MSG"; + + String COLUMN_HEADER_QUERY_PLAN = "COLUMN_HEADER_QUERY_PLAN"; + + String EXPORT_ALL_DATA_NOT_ENOUGH_SPACE = "EXPORT_ALL_DATA_NOT_ENOUGH_SPACE"; + + String PARTIAL_SUCCESS_UPDATE_OBJECT_PRIVILEGE_DETAIL = "PARTIAL_SUCCESS_UPDATE_OBJECT_PRIVILEGE_DETAIL"; + + String CREATE_NEW_ROLE = "CREATE_NEW_ROLE"; + + String CREATE_USERROLE_FINISH_BTN = "CREATE_USERROLE_FINISH_BTN"; + + String CREATE_USERROLE_NEXT_BTN = "CREATE_USERROLE_NEXT_BTN"; + + String CREATE_USERROLE_BACK_BTN = "CREATE_USERROLE_BACK_BTN"; + + String CREATE_USERROLE_CANCEL_BTN = "CREATE_USERROLE_CANCEL_BTN"; + + String CREATE_USERROLE_NAME_INVALID = "CREATE_USERROLE_NAME_INVALID"; + + String CREATE_USERROLE_NAME_EXCEED_MAX = "CREATE_USERROLE_NAME_EXCEED_MAX"; + + String CREATE_USERROLE_ENTER_PAS = "CREATE_USERROLE_ENTER_PAS"; + + String CREATE_USERROLE_ENTER_NM = "CREATE_USERROLE_ENTER_NM"; + + String CREATE_USERROLE_CREATE_ERROR = "CREATE_USERROLE_CREATE_ERROR"; + + String USER_ROLE_NM_PAS = "USER_ROLE_NM_PAS"; + + String CREATE_USERROLE_NAME = "CREATE_USERROLE_NAME"; + + String CREATE_USERROLE_CIPHER = "CREATE_USERROLE_CIPHER"; + + String CREATE_USERROLE_PRIVILEGE = "CREATE_USERROLE_PRIVILEGE"; + + String CREATE_USERROLE_SYSADMIN = "CREATE_USERROLE_SYSADMIN"; + + String CREATE_USERROLE_AUDITADMIN = "CREATE_USERROLE_AUDITADMIN"; + + String CREATE_USERROLE_CREATEDB = "CREATE_USERROLE_CREATEDB"; + + String CREATE_USERROLE_CREATEROLE = "CREATE_USERROLE_CREATEROLE"; + + String CREATE_USERROLE_INHERIT = "CREATE_USERROLE_INHERIT"; + + String CREATE_USERROLE_LOGIN = "CREATE_USERROLE_LOGIN"; + + String CREATE_USERROLE_REPLICATION = "CREATE_USERROLE_REPLICATION"; + + String USER_ROLE_PRIVILEGE_OPTION = "USER_ROLE_PRIVILEGE_OPTION"; + + String CREATE_USERROLE_CONNECT_LIMIT = "CREATE_USERROLE_CONNECT_LIMIT"; + + String CREATE_USERROLE_VALID_BEGIN = "CREATE_USERROLE_VALID_BEGIN"; + + String CREATE_USERROLE_VALID_UNTIL = "CREATE_USERROLE_VALID_UNTIL"; + + String CREATE_USERROLE_RES_POOL = "CREATE_USERROLE_RES_POOL"; + + String CREATE_USERROLE_ROLE_GROUP_MEMBER = "CREATE_USERROLE_ROLE_GROUP_MEMBER"; + + String CREATE_USERROLE_ADMIN_GROUP_MEMBER = "CREATE_USERROLE_ADMIN_GROUP_MEMBER"; + + String CREATE_USERROLE_CREATE_SUCCESS = "CREATE_USERROLE_CREATE_SUCCESS"; + + String DROP_ROLE_DIA_TITLE = "DROP_ROLE_DIA_TITLE"; + + String DROP_ROLE = "DROP_ROLE"; + + String DROP_USERROLE_PROGRESS_NAME = "DROP_USERROLE_PROGRESS_NAME"; + + String DROP_USERROLE_SUCCESS = "DROP_USERROLE_SUCCESS"; + + String CREATE_USERROLE_NO_PRIVILEGE = "CREATE_USERROLE_NO_PRIVILEGE"; + + String CREATE_USERROLE_NO_PRIVILEGE_CREATE = "CREATE_USERROLE_NO_PRIVILEGE_CREATE"; + + String ENTER_ROLE_NAME = "ENTER_ROLE_NAME"; + + String ENTER_CIPHER = "ENTER_CIPHER"; + + String CREATE_USERROLE_PAS_NOT_MATCH = "CREATE_USERROLE_PAS_NOT_MATCH"; + + String ENTER_CIPHER_TWICE = "ENTER_CIPHER_TWICE"; + + String CREATE_USERROLE_ALL = "CREATE_USERROLE_ALL"; + + String CREATE_USERROLE_SSL_NOT_ENABLE = "CREATE_USERROLE_SSL_NOT_ENABLE"; + + String PRIVILEGE_ADVANCED = "PRIVILEGE_ADVANCED"; + + String STATUS_MSG_DROP_ROLE = "STATUS_MSG_DROP_ROLE"; + + String DROP_USERROLE_ERROR = "DROP_USERROLE_ERROR"; + + String DROP_USERROLE_UNABLE = "DROP_USERROLE_UNABLE"; + + String DROP_USERROLE_UNABLE_MSG = "DROP_USERROLE_UNABLE_MSG"; + + String SHOW_USER_ROLE_DDL_ERROR = "SHOW_USER_ROLE_DDL_ERROR"; + + String SHOW_USER_ROLE_DDL_NO_DATABASE = "SHOW_USER_ROLE_DDL_NO_DATABASE"; + + String SHOW_USER_ROLE_DDL_JOB_NAME = "SHOW_USER_ROLE_DDL_JOB_NAME"; + + String EXPORT_ALL_DATA_DISABLE_TOOLTIP = "EXPORT_ALL_DATA_DISABLE_TOOLTIP"; + + String CREATE_USER = "CREATE_USER"; + + String CREATE_ROLE = "CREATE_ROLE"; + + String UNKNOW_CLOB_TYPE = "UNKNOW_CLOB_TYPE"; + + String NO_NEED_TO_REFRESH_EXCEPTION = "NO_NEED_TO_REFRESH"; + + String EXCEL_ROW_LIMIT_REACHED = "EXCEL_ROW_LIMIT_REACHED"; + + String MAXIMUM_EXCEL_ROW_REACHED = "MAXIMUM_EXCEL_ROW_REACHED"; + + String SQL_QUERY_SETTING_ZERO_DATA_HEADER = "SQL_QUERY_SETTING_ZERO_DATA_HEADER"; + + String SQL_QUERY_SETTING_ZERO_DATA_BODY = "SQL_QUERY_SETTING_ZERO_DATA_BODY"; + + String SQL_QUERY_SETTING_COMBO_DATA_BODY = "SQL_QUERY_SETTING_COMBO_DATA_BODY"; + + String CONNECTION_OPTION_DIALOG_TITLE = "CONNECTION_OPTION_DIALOG_TITLE"; + + String DIRTY_TERMINAL_DIALOG_TITLE = "DIRTY_TERMINAL_DIALOG_TITLE"; + + String DIRTY_TERMINAL_DIALOG_SELECT_ALL_BUTTON = "DIRTY_TERMINAL_DIALOG_SELECT_ALL_BUTTON"; + + String DIRTY_TERMINAL_DIALOG_DESELECT_ALL_BUTTON = "DIRTY_TERMINAL_DIALOG_DESELECT_ALL_BUTTON"; + + String DIRTY_TERMINAL_DIALOG_SELECTION_MESSAGE = "DIRTY_TERMINAL_DIALOG_SELECTION_MESSAGE"; + + String FILE_UPDATE_CONFLICT_DIALOG_TITLE = "FILE_UPDATE_CONFLICT_DIALOG_TITLE"; + + String FILE_UPDATE_CONFLICT_DIALOG_DETAIL = "FILE_UPDATE_CONFLICT_DIALOG_DETAIL"; + + String DIRTY_TERMINAL_DIALOG_SAVE_BUTTON = "DIRTY_TERMINAL_DIALOG_SAVE_BUTTON"; + + String DIRTY_TERMINAL_DIALOG_NOT_SAVE_BUTTON = "DIRTY_TERMINAL_DIALOG_NOT_SAVE_BUTTON"; + + String DIRTY_TERMINAL_DIALOG_SAVE_WARNING = "DIRTY_TERMINAL_DIALOG_SAVE_WARNING"; + + String DIRTY_TERMINAL_DIALOG_SAVE_FILE_ERROR = "DIRTY_TERMINAL_DIALOG_SAVE_FILE_ERROR"; + + String OLAP_PROP_COLUMNTAB_DATATYPE = "OLAP_PROP_COLUMNTAB_DATATYPE"; + + String OLAP_PROP_COLUMNTAB_ISNULLABLE = "OLAP_PROP_COLUMNTAB_ISNULLABLE"; + + String OLAP_PROP_KEYTAB_TYPE = "OLAP_PROP_KEYTAB_TYPE"; + + String OLAP_PROP_KEYTAB_COLUMNS = "OLAP_PROP_KEYTAB_COLUMNS"; + + String OLAP_PROP_KEYTAB_REFERENCINGTABLE = "OLAP_PROP_KEYTAB_REFERENCINGTABLE"; + + String OLAP_PROP_KEYTAB_REFERENCINGCOL = "OLAP_PROP_KEYTAB_REFERENCINGCOL"; + + String OLAP_PROP_KEYTAB_ONDELETE = "OLAP_PROP_KEYTAB_ONDELETE"; + + String OLAP_PROP_KEYTAB_DEFERRABLE = "OLAP_PROP_KEYTAB_DEFERRABLE"; + + String OLAP_PROP_KEYTAB_DEFERRED = "OLAP_PROP_KEYTAB_DEFERRED"; + + String OLAP_PROP_KEYTAB_VALIDATED = "OLAP_PROP_KEYTAB_VALIDATED"; + + String OLAP_PROP_INDEXTAB_COLUMNS = "OLAP_PROP_INDEXTAB_COLUMNS"; + + String OLAP_PROP_INDEXTAB_ISUNIQUE = "OLAP_PROP_INDEXTAB_ISUNIQUE"; + + String OLAP_PROP_INDEXTAB_TABLESPACE = "OLAP_PROP_INDEXTAB_TABLESPACE"; + + String OLAP_PROP_CHECKTAB_CONDITION = "OLAP_PROP_CHECKTAB_CONDITION"; + + String OLAP_PROP_CHECKTAB_ENABLED = "OLAP_PROP_CHECKTAB_ENABLED"; + + String OLAP_PROP_CHECKTAB_DEFERRABLE = "OLAP_PROP_CHECKTAB_DEFERRABLE"; + + String OLAP_PROP_CHECKTAB_DEFERRED = "OLAP_PROP_CHECKTAB_DEFERRED"; + + String OLAP_PROP_CHECKTAB_VALIDATED = "OLAP_PROP_CHECKTAB_VALIDATED"; + + String OLAP_PROP_PARTITIONTAB_TYPE = "OLAP_PROP_PARTITIONTAB_TYPE"; + + String OLAP_PROP_PARTITIONTAB_KEYS = "OLAP_PROP_PARTITIONTAB_KEYS"; + + String OLAP_PROP_PARTITIONTAB_PARTITIONVALUE = "OLAP_PROP_PARTITIONTAB_PARTITIONVALUE"; + + String OLAP_PROP_PARTITIONTAB_TABLESPACENAME = "OLAP_PROP_PARTITIONTAB_TABLESPACENAME"; + + String PROPERTIES_CHECKS_TAB = "PROPERTIES_CHECKS_TAB"; + + String PROPERTIES_DISTRIBUTION_TAB = "PROPERTIES_DISTRIBUTION_TAB"; + + String PROPERTIES_KEYS_TAB = "PROPERTIES_KEYS_TAB"; + + // menu in ResultSet + String COPY_TO_EXCEL_RESULT_WINDOW_MENU = "COPY_TO_EXCEL_RESULT_WINDOW_MENU"; + + String COPY_TO_EXCEL_XLS_RESULT_WINDOW_MENUITEM = "COPY_TO_EXCEL_XLS_RESULT_WINDOW_MENUITEM"; + + String COPY_TO_EXCEL_XLSX_RESULT_WINDOW_MENUITEM = "COPY_TO_EXCEL_XLSX_RESULT_WINDOW_MENUITEM"; + + String SEARCH_RESULT_WINDOW_CONTENTS = "SEARCH_RESULT_WINDOW_CONTENTS"; + + String SET_NULL_RESULT_WINDOW_CONTENTS = "SET_NULL_RESULT_WINDOW_CONTENTS"; + + String RIGHT_CLICK_COPY_ADVANCED_RESULT_WINDOW_CONTENTS = "RIGHT_CLICK_COPY_ADVANCED_RESULT_WINDOW_CONTENTS"; + + String RIGHT_CLICK_COPY_RESULT_WINDOW_CONTENTS = "RIGHT_CLICK_COPY_RESULT_WINDOW_CONTENTS"; + + String COPY_TO_EXCEL_RESULT_FILE_NAME = "COPY_TO_EXCEL_RESULT_FILE_NAME"; + + String RIGHT_CLICK_COPY_TO_CLIPBOARD_RESULT_WINDOW_CONTENTS = "RIGHT_CLICK_COPY_TO_CLIPBOARD_RESULT_WINDOW_CONTENTS"; + + String RIGHT_CLICK_EXPORT_RESULT_WINDOW_CONTENTS = "RIGHT_CLICK_EXPORT_RESULT_WINDOW_CONTENTS"; + + String RIGHT_CLICK_EXPORT_CURRENT_PAGE_DATA_RESULT_WINDOW_CONTENTS = "RIGHT_CLICK_EXPORT_CURRENT_PAGE_DATA_RESULT_WINDOW_CONTENTS"; + + String RIGHT_CLICK_EXPORT_ALL_DATA_RESULT_WINDOW_CONTENTS = "RIGHT_CLICK_EXPORT_ALL_DATA_RESULT_WINDOW_CONTENTS"; + + String ERR_OPEN_IN_EXCEL_OPERATION = "ERR_OPEN_IN_EXCEL_OPERATION"; + + String EXPORT_OPEN_IN_EXCEL_PROGRESS_NAME = "EXPORT_OPEN_IN_EXCEL_PROGRESS_NAME"; + + String RIGHT_CLICK_GENERATE_INSERT_RESULT_WINDOW_CONTENTS = "RIGHT_CLICK_GENERATE_INSERT_RESULT_WINDOW_CONTENTS"; + + String RIGHT_CLICK_SELECTED_ROW_INSERT_RESULT_WINDOW_CONTENTS = "RIGHT_CLICK_SELECTED_ROW_INSERT_RESULT_WINDOW_CONTENTS"; + + String RIGHT_CLICK_CURRENT_INSERT_RESULT_WINDOW_CONTENTS = "RIGHT_CLICK_CURRENT_INSERT_RESULT_WINDOW_CONTENTS"; + + String RIGHT_CLICK_ALL_DATA_INSERT_RESULT_WINDOW_CONTENTS = "RIGHT_CLICK_ALL_DATA_INSERT_RESULT_WINDOW_CONTENTS"; + + String GENERATE_INSERT_SQL = "GENERATE_INSERT_SQL"; + + String GENERATE_SQL_SUCCES_DAILOG_TITLE = "GENERATE_SQL_SUCCES_DAILOG_TITLE"; + + String ERR_GENERATE_INSERT_SQL = "ERR_GENERATE_INSERT_SQL"; + + String ERR_GENERATE_INSERT_SQLL_OPERATION = "ERR_GENERATE_INSERT_SQLL_OPERATION"; + + String DIRTY_GENERATE_INSERT_DIALOG_SAVE_FILE_ERROR = "DIRTY_GENERATE_INSERT_DIALOG_SAVE_FILE_ERROR"; + + String GENERATE_INSERT_ERROR = "GENERATE_INSERT_ERROR"; + + String ERR_UI_GENERATE_INSERT_ERROR = "ERR_UI_GENERATE_INSERT_ERROR"; + + String ERR_UI_SEARCH_ERROR = "ERR_UI_SEARCH_ERROR"; + + String GENERATE_INSERT_ALL_RESULTDATA_PROGRESS_NAME = "GENERATE_INSERT_ALL_RESULTDATA_PROGRESS_NAME"; + + /* Multi-COlumn Sort */ + String GRIDDATA_SORT = "GRIDDATA_SORT"; + + String SORT_ERROR_WINDOW_TITLE = "SORT_ERROR_WINDOW_TITLE"; + + String SORT_ERROR_BLANK_COLUMN = "SORT_ERROR_BLANK_COLUMN"; + + String SORT_ERROR_DUPLICATE_COLUMN = "SORT_ERROR_DUPLICATE_COLUMN"; + + String CLEAR_SORT = "CLEAR_SORT"; + + String MULTISORT_POPUP_WINDOW_TITLE = "MULTISORT_POPUP_WINDOW_TITLE"; + + String COLUMN_PRIORITY = "COLUMN_PRIORITY"; + + String COLUMN_COLUMN_NAME = "COLUMN_COLUMN_NAME"; + + String COLUMN_DATATYPE = "COLUMN_DATATYPE"; + + String COLUMN_SORT_ORDER = "COLUMN_SORT_ORDER"; + + String BUTTON_ADD_COLUMN = "BUTTON_ADD_COLUMN"; + + String BUTTON_DELETE_COLUMN = "BUTTON_DELETE_COLUMN"; + + String BUTTON_UP_COLUMN = "BUTTON_UP_COLUMN"; + + String BUTTON_DOWN_COULMN = "BUTTON_DOWN_COULMN"; + + String BUTTON_APPLY_SORT = "BUTTON_APPLY_SORT"; + + String COMBO_TEXT_SORT_COLUMN = "COMBO_TEXT_SORT_COLUMN"; + + String COMBO_TEXT_SORT_OREDER = "COMBO_TEXT_SORT_OREDER"; + + String COMBO_OPTION_ASCENDING = "COMBO_OPTION_ASCENDING"; + + String COMBO_OPTION_DESCENDING = "COMBO_OPTION_DESCENDING"; + + String RESULT_WINDOW_EDITTABLE_COMMIT_NONEXECUTED = "RESULT_WINDOW_EDITTABLE_COMMIT_NONEXECUTED"; + + String EDIT_TABLE_PROPERTIES_DATA_DROPPED_REFRESH_ERROR = "EDIT_TABLE_PROPERTIES_DATA_DROPPED_REFRESH_ERROR"; + + String RESULT_WINDOW_SHOW_GRID = "RESULT_WINDOW_SHOW_GRID"; + + String RESULT_WINDOW_SHOW_TEXT = "RESULT_WINDOW_SHOW_TEXT"; + + String RESULT_WINDOW_TEXT_CELL_VALUE_DIALOG_TITLE = "RESULT_WINDOW_TEXT_CELL_VALUE_DIALOG_TITLE"; + + String RESULT_WINDOW_TEXT_CELL_INVISIBLE_VALUE_TITLE = "RESULT_WINDOW_TEXT_CELL_INVISIBLE_VALUE_TITLE"; + + String RESULT_WINDOW_TEXT_CELL_INVISIBLE_VALUE_BODY = "RESULT_WINDOW_TEXT_CELL_INVISIBLE_VALUE_BODY"; + + String RESULT_WINDOW_SQL_SEARCH_EXECUTE = "RESULT_WINDOW_SQL_SEARCH_EXECUTE"; + + String RESULT_WINDOW_SQL_REFRESH_EXECUTE = "RESULT_WINDOW_SQL_REFRESH_EXECUTE"; + + String RESULT_WINDOW_SQL_LOADING_EXECUTE = "RESULT_WINDOW_SQL_LOADING_EXECUTE"; + + String RESULT_WINDOW_SQL_ENCODING_EXECUTE = "RESULT_WINDOW_SQL_ENCODING_EXECUTE"; + + String DATA_TOO_LARGE_DISPLAY_EDIT = "DATA_TOO_LARGE_DISPLAY_EDIT"; + + String DATA_TOO_LARGE_WARNING = "DATA_TOO_LARGE_WARNING"; + + String NEW_OBJECT_WILL_BE_OPENED = "NEW_OBJECT_WILL_BE_OPENED"; + + String CURSOR_IMPLEMENT_DIALOG_TITLE = "CURSOR_IMPLEMENT_DIALOG_TITLE"; + + String CURSOR_IMPLEMENT_DIALOG_HEADER = "CURSOR_IMPLEMENT_DIALOG_HEADER"; + + String CURSOR_FAILURE_SQL_ERROR = "CURSOR_FAILURE_SQL_ERROR"; + + String COLUMN_DEFAULT_VALUE_EXPRESSION = "COLUMN_DEFAULT_VALUE_EXPRESSION"; + + String REFRESH_TABLE_LABEL_FAILURE = "REFRESH_TABLE_LABEL_FAILURE"; + + String REFRESH_TABLE_LABEL_SUCCESS = "REFRESH_TABLE_LABEL_SUCCESS"; + + String REFRESH_TABLE_LABEL_IN_PROGRESS = "REFRESH_TABLE_LABEL_IN_PROGRESS"; + + String CREATE_TABLE_DDL_TAB = "CREATE_TABLE_DDL_TAB"; + + String MSG_TOTAL_ROWS_EXPORT_INSERT_SQL = "MSG_TOTAL_ROWS_EXPORT_INSERT_SQL"; + + String FAILED_TO_OPEN_FILE_TITLE = "FAILED_TO_OPEN_FILE_TITLE"; + + String FAILED_TO_OPEN_FILE_MESSAGE = "FAILED_TO_OPEN_FILE_MESSAGE"; + + String ENTRE_CLIENTSSLKEY = "ENTRE_CLIENTSSLKEY"; + + String ENTER_CLIENT_SSLPVT_KEYFILE = "ENTER_CLIENT_SSLPVT_KEYFILE"; + + String BTN_CLIENT_PVTKEY = "BTN_CLIENT_PVTKEY"; + + String INVALID_SSL_KEY = "INVALID_SSL_KEY"; + + String RESULT_TAB_CONNECTION_LOST_ERR_MSG = "RESULT_TAB_CONNECTION_LOST_ERR_MSG"; + + String RESULT_TAB_COL_NAME = "RESULT_TAB_COL_NAME"; + + String RESULT_TAB_COL_DATA_TYPE = "RESULT_TAB_COL_DATA_TYPE"; + + String RESULT_TAB_COL_PARAMETER_TYPE = "RESULT_TAB_COL_PARAMETER_TYPE"; + + String RESULT_TAB_COL_VALUE = "RESULT_TAB_COL_VALUE"; + + String CURSOR_TOOLTIP_TEXT = "CURSOR_TOOLTIP_TEXT"; + + String VOID_VALUE_TOOLTIP_TEXT = "VOID_VALUE_TOOLTIP_TEXT"; + + String EDITOR_DATA_TAB = "EDITOR_DATA_TAB"; + + String EDITOR_IMAGE_TAB = "EDITOR_IMAGE_TAB"; + + String EDITOR_IMAGE_NOT_SUPPORTED = "EDITOR_IMAGE_NOT_SUPPORTED"; + + String EDITOR_DATA_INVALID_NUMBER_DIGITS = "EDITOR_DATA_INVALID_NUMBER_DIGITS"; + + String CURSOR_DATA_NODE = "CURSOR_DATA_NODE"; + + String EDIT_TERMINAL_INPUT_VALUE = "EDIT_TERMINAL_INPUT_VALUE"; + + String JOB_EDITOR_INTERVAL_TOOLTIP_INFO = "JOB_EDITOR_INTERVAL_TOOLTIP_INFO"; + + String JOB_EDITOR_INTERVAL_TOOLTIP_EXAMPLE = "JOB_EDITOR_INTERVAL_TOOLTIP_EXAMPLE"; + + String RESTORE_DEFAULTS = "RESTORE_DEFAULTS"; + + String DBMS_JOBS_REOPEN = "DBMS_JOBS_REOPEN"; + + String DBMS_JOBS_OBJECT_MODIFIED_ERROR = "DBMS_JOBS_OBJECT_MODIFIED_ERROR"; + + String DATE_TIME_PREFERENCES = "DATE_TIME_PREFERENCES"; + + String USER_DEFINED = "USER_DEFINED"; + + String SYSTEM_FORMAT = "SYSTEM_FORMAT"; + + String DATE_PREFERENCE = "DATE_PREFERENCE"; + + String TIME_PREFERENCE = "TIME_PREFERENCE"; + + String DATE_FORMAT_ERROR_MSG = "DATE_FORMAT_ERROR_MSG"; + + String TIME_FORMAT_ERROR_MSG = "TIME_FORMAT_ERROR_MSG"; + + String PREF_RS_MAX_RESULT_WINDOW_INPUT_ERR_MSG = "PREF_RS_MAX_RESULT_WINDOW_INPUT_ERR_MSG"; + + String MAX_RESULT_SET_RANGE = "MAX_RESULT_SET_RANGE"; + + String MAX_RESULT_SET_LBL = "MAX_RESULT_SET_LBL"; + + String DATE_FORMAT_EXAMPLE_HINT = "DATE_FORMAT_EXAMPLE_HINT"; + + String TIME_FORMAT_EXAMPLE_HINT = "TIME_FORMAT_EXAMPLE_HINT"; + + String MUTIPLE_MARKERS = "MUTIPLE_MARKERS"; + + String RESULT_MANAGER = "RESULT_MANAGER"; + + String MAX_RESULT_WINDOW_HINT = "MAX_RESULT_WINDOW_HINT"; + + String IMPORT_EXPORT_LIMIT_PREF_TITLE = "IMPORT_EXPORT_LIMIT_PREF_TITLE"; + String IMPORT_EXPORT_LIMIT_PREF_RANGE = "IMPORT_EXPORT_LIMIT_PREF_RANGE"; + String IMPORT_EXPORT_LIMIT_PREF_INFO = "IMPORT_EXPORT_LIMIT_PREF_INFO"; + String IMPORT_EXPORT_LIMIT_MSG_TITLE = "IMPORT_EXPORT_LIMIT_MSG_TITLE"; + String IMPORT_EXPORT_LIMIT_MSG_INFO = "IMPORT_EXPORT_LIMIT_MSG_INFO"; + + String INVALID_LINE_SEPERATOR = "INVALID_LINE_SEPERATOR"; + + String BREAKPOINT_ANNOTATION_LABEL = "BREAKPOINT_ANNOTATION_LABEL"; + String DEBUG_POSITION_LABEL = "DEBUG_POSITION_LABEL"; + + String DEBUG_TABLE_ORDER = "DEBUG_TABLE_ORDER"; + String DEBUG_STACK_INVOKING_LEVEL = "DEBUG_STACK_INVOKING_LEVEL"; + String DEBUG_STACK_FUNCTION_INFO = "DEBUG_STACK_FUNCTION_INFO"; + String DEBUG_STACK_CURRENT_LINE_NUM = "DEBUG_STACK_CURRENT_LINE_NUM"; + String DEBUG_BREAKPOINT_LINE_NUM = "DEBUG_BREAKPOINT_LINE_NUM"; + String DEBUG_BREAKPOINT_STATEMENT = "DEBUG_BREAKPOINT_STATEMENT"; + String DEBUG_BREAKPOINT_ENABLE = "DEBUG_BREAKPOINT_ENABLE"; + String DEBUG_VARIABLE_VARIABLE = "DEBUG_VARIABLE_VARIABLE"; + String DEBUG_VARIABLE_VALUE = "DEBUG_VARIABLE_VALUE"; + String DEBUG_VARIABLE_DATA_TYPE = "DEBUG_VARIABLE_DATA_TYPE"; + String DEBUG_VARIABLE_PARAM_TYPE = "DEBUG_VARIABLE_PARAM_TYPE"; + + String DEBUG_NOT_SUPPORT_WARN = "DEBUG_NOT_SUPPORT_WARN"; + String DEBUG_PREFREENCE_ID = "DEBUG_PREFREENCE_ID"; + String DEBUG_PREFREENCE_WHEN_ROLLBACK = "DEBUG_PREFREENCE_WHEN_ROLLBACK"; + + String CREATE_FUNCTION_UI_CREATE_FUNCTION = "CREATE_FUNCTION_UI_CREATE_FUNCTION"; + String CREATE_FUNCTION_UI_CREATE_PROCEDURE = "CREATE_FUNCTION_UI_CREATE_PROCEDURE"; + String CREATE_FUNCTION_UI_SQL_PREVIEW = "CREATE_FUNCTION_UI_SQL_PREVIEW"; + String CREATE_FUNCTION_UI_SCHEMA = "CREATE_FUNCTION_UI_SCHEMA"; + String CREATE_FUNCTION_UI_FUNCTION_NAME = "CREATE_FUNCTION_UI_FUNCTION_NAME"; + String CREATE_FUNCTION_UI_FUNCTION = "CREATE_FUNCTION_UI_FUNCTION"; + String CREATE_FUNCTION_UI_PROCEDURE = "CREATE_FUNCTION_UI_PROCEDURE"; + String CREATE_FUNCTION_UI_LANGUAGE = "CREATE_FUNCTION_UI_LANGUAGE"; + String CREATE_FUNCTION_UI_RETURN_TYPE = "CREATE_FUNCTION_UI_RETURN_TYPE"; + String CREATE_FUNCTION_UI_PARAM_LIST = "CREATE_FUNCTION_UI_PARAM_LIST"; + String CREATE_FUNCTION_UI_BUTTON_RESET = "CREATE_FUNCTION_UI_BUTTON_RESET"; + String CREATE_FUNCTION_UI_BUTTON_ADD = "CREATE_FUNCTION_UI_BUTTON_ADD"; + String CREATE_FUNCTION_UI_BUTTON_DELETE = "CREATE_FUNCTION_UI_BUTTON_DELETE"; + String CREATE_FUNCTION_UI_FUNCTION_BODY = "CREATE_FUNCTION_UI_FUNCTION_BODY"; + String CREATE_FUNCTION_UI_BUTTON_NEXT = "CREATE_FUNCTION_UI_BUTTON_NEXT"; + String CREATE_FUNCTION_UI_BUTTON_CANCEL = "CREATE_FUNCTION_UI_BUTTON_CANCEL"; + String CREATE_FUNCTION_UI_BUTTON_BACK = "CREATE_FUNCTION_UI_BUTTON_BACK"; + String CREATE_FUNCTION_UI_BUTTON_NO_COMPILE = "CREATE_FUNCTION_UI_BUTTON_NO_COMPILE"; + String CREATE_FUNCTION_UI_BUTTON_COMPILE = "CREATE_FUNCTION_UI_BUTTON_COMPILE"; + String CREATE_FUNCTION_UI_PARAM_NAME = "CREATE_FUNCTION_UI_PARAM_NAME"; + String CREATE_FUNCTION_UI_PARAM_MODE = "CREATE_FUNCTION_UI_PARAM_MODE"; + String CREATE_FUNCTION_UI_PARAM_TYPE = "CREATE_FUNCTION_UI_PARAM_TYPE"; + String CREATE_FUNCTION_UI_PARAM_DEFAULT = "CREATE_FUNCTION_UI_PARAM_DEFAULT"; + String CREATE_FUNCTION_UI_TOOLTIP_NO_COMPILE = "CREATE_FUNCTION_UI_TOOLTIP_NO_COMPILE"; + String CREATE_FUNCTION_UI_TOOLTIP_COMPILE = "CREATE_FUNCTION_UI_TOOLTIP_COMPILE"; + String CREATE_FUNCTION_UI_TRIGGER = "CREATE_FUNCTION_UI_TRIGGER"; + String CREATE_FUNCTION_UI_CREATE = "CREATE_FUNCTION_UI_CREATE"; + String CREATE_FUNCTION_UI_ERR_FUNC_NAME = "CREATE_FUNCTION_UI_ERR_FUNC_NAME"; + String CREATE_FUNCTION_UI_ERR_FUNC_BODY = "CREATE_FUNCTION_UI_ERR_FUNC_BODY"; + + String DROP_TRIGGER = "DROP_TRIGGER"; + String DROP_TRIGGER_TITLE = "DROP_TRIGGER_TITLE"; + String RENAME_TRIGGER = "RENAME_TRIGGER"; + String RENAME_TRIGGER_TITLE = "RENAME_TRIGGER_TITLE"; + + String CREATE_TRIGGER_UI_CREATE_TRIGGER = "CREATE_TRIGGER_UI_CREATE_TRIGGER"; + String CREATE_TRIGGER_UI_EDIT_TRIGGER = "CREATE_TRIGGER_UI_EDIT_TRIGGER"; + String CREATE_TRIGGER_UI_GENERAL_PAGE = "CREATE_TRIGGER_UI_GENERAL_PAGE"; + String CREATE_TRIGGER_UI_TRIGGER_NAME = "CREATE_TRIGGER_UI_TRIGGER_NAME"; + String CREATE_TRIGGER_UI_TRIGGER_TABLE_NAME = "CREATE_TRIGGER_UI_TRIGGER_TABLE_NAME"; + String CREATE_TRIGGER_UI_TIME_TO_TRIGGER = "CREATE_TRIGGER_UI_TIME_TO_TRIGGER"; + String CREATE_TRIGGER_UI_OPERATION_TYPE = "CREATE_TRIGGER_UI_OPERATION_TYPE"; + String CREATE_TRIGGER_UI_COLUMN_NAME = "CREATE_TRIGGER_UI_COLUMN_NAME"; + String CREATE_TRIGGER_UI_DATA_TYPE = "CREATE_TRIGGER_UI_DATA_TYPE"; + String CREATE_TRIGGER_UI_TRIGGER_LEVEL = "CREATE_TRIGGER_UI_TRIGGER_LEVEL"; + String CREATE_TRIGGER_UI_TUPLE_LEVEL_TRIGGER = "CREATE_TRIGGER_UI_TUPLE_LEVEL_TRIGGER"; + String CREATE_TRIGGER_UI_STATEMENT_LEVEL_TRIGGER = "CREATE_TRIGGER_UI_STATEMENT_LEVEL_TRIGGER"; + String CREATE_TRIGGER_UI_TRIGGER_CONDITION = "CREATE_TRIGGER_UI_TRIGGER_CONDITION"; + String CREATE_TRIGGER_UI_TRIGGER_FUNCTION = "CREATE_TRIGGER_UI_TRIGGER_FUNCTION"; + String CREATE_TRIGGER_UI_NEXT = "CREATE_TRIGGER_UI_NEXT"; + String CREATE_TRIGGER_UI_CANCEL = "CREATE_TRIGGER_UI_CANCEL"; + String CREATE_TRIGGER_UI_SQL_PREVIEW = "CREATE_TRIGGER_UI_SQL_PREVIEW"; + String CREATE_TRIGGER_UI_PREVIOUS = "CREATE_TRIGGER_UI_PREVIOUS"; + String CREATE_TRIGGER_UI_FINISH = "CREATE_TRIGGER_UI_FINISH"; + + String EDIT_VIEW_UI_EDIT_VIEW = "EDIT_VIEW_UI_EDIT_VIEW"; + String CREATE_VIEW_UI_CREATE_VIEW = "CREATE_VIEW_UI_CREATE_VIEW"; + String CREATE_VIEW_UI_SCHEMA_NAME = "CREATE_VIEW_UI_SCHEMA_NAME"; + String CREATE_VIEW_UI_VIEW_NAME = "CREATE_VIEW_UI_VIEW_NAME"; + String CREATE_VIEW_UI_TABLE_NAME = "CREATE_VIEW_UI_TABLE_NAME"; + String CREATE_VIEW_UI_TABLE_FULL_NAME = "CREATE_VIEW_UI_TABLE_FULL_NAME"; + String CREATE_VIEW_UI_TABLE_ALIAS_NAME = "CREATE_VIEW_UI_TABLE_ALIAS_NAME"; + String CREATE_VIEW_UI_COLUMN_NAME = "CREATE_VIEW_UI_COLUMN_NAME"; + String CREATE_VIEW_UI_COLUMN_ALIAS_NAME = "CREATE_VIEW_UI_COLUMN_ALIAS_NAME"; + String CREATE_VIEW_UI_COLUMN_1 = "CREATE_VIEW_UI_COLUMN_1"; + String CREATE_VIEW_UI_COLUMN_2 = "CREATE_VIEW_UI_COLUMN_2"; + String CREATE_VIEW_UI_PREVIEW = "CREATE_VIEW_UI_PREVIEW"; + String CREATE_VIEW_UI_NEXT = "CREATE_VIEW_UI_NEXT"; + String CREATE_VIEW_UI_PREVIOUS = "CREATE_VIEW_UI_PREVIOUS"; + String CREATE_VIEW_UI_CANCEL = "CREATE_VIEW_UI_CANCEL"; + String CREATE_VIEW_UI_FINISH = "CREATE_VIEW_UI_FINISH"; + String CREATE_VIEW_UI_WHERE = "CREATE_VIEW_UI_WHERE"; + String CREATE_VIEW_UI_ADD = "CREATE_VIEW_UI_ADD"; + String CREATE_VIEW_UI_DELETE = "CREATE_VIEW_UI_DELETE"; + String CREATE_VIEW_UI_VIEW = "CREATE_VIEW_UI_VIEW"; + String CREATE_VIEW_UI_MATERVIEW = "CREATE_VIEW_UI_MATERVIEW"; + String CREATE_VIEW_UI_NAME_NOT_EMPTY = "CREATE_VIEW_UI_NAME_NOT_EMPTY"; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/IMessagesConstantsOne.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/IMessagesConstantsOne.java new file mode 100644 index 0000000000000000000000000000000000000000..ff57dd80b67f2b4c5efc463d17f0cec2516ce6fe --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/IMessagesConstantsOne.java @@ -0,0 +1,1102 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +/** + * + * Title: interface + * + * Description: The Interface IMessagesConstantsOne. + * + * @since 3.0.0 + */ +public interface IMessagesConstantsOne extends IMessagesConstantsTwo { + String DB_CONN_DIA_TITLE = "DB_CONN_DIA_TITLE"; + String DB_CONN_DIA_MSG = "DB_CONN_DIA_MSG"; + String DB_CONN_DIA_HELP = "DB_CONN_DIA_HELP"; + String DB_CONN_DIA_TO_SERVER = "DB_CONN_DIA_TO_SERVER"; + String DB_CONN_DIA_CONN_NAME = "DB_CONN_DIA_CONN_NAME"; + String DB_CONN_DIA_HOST = "DB_CONN_DIA_HOST"; + String DB_CONN_DIA_HOST_PORT = "DB_CONN_DIA_HOST_PORT"; + String DB_CONN_DIA_MAX_VALUE = "DB_CONN_DIA_MAX_VALUE"; + String DB_CONN_DIA_DB_NAME_OLAP = "DB_CONN_DIA_DB_NAME_OLAP"; + String DB_CONN_DIA_USER_NAME = "DB_CONN_DIA_USER_NAME"; + String DB_CONN_DIA_PSW = "DB_CONN_DIA_PSW"; + String DB_CONN_DIA_SSL = "DB_CONN_DIA_SSL"; + String DB_CONN_DIA_ENABLE_SSL = "DB_CONN_DIA_ENABLE_SSL"; + + String DB_CONN_DIA_T = "DB_CONN_DIA_T"; + + String DB_CONN_DIA_SSL_PROPERTY = "DB_CONN_DIA_SSL_PROPERTY"; + String DB_CONN_DIA_INVALID_SERVER_IP_TITLE = "DB_CONN_DIA_INVALID_SERVER_IP_TITLE"; + String DB_CONN_DIA_INVALID_SERVER_IP_MSG = "DB_CONN_DIA_INVALID_SERVER_IP_MSG"; + String DB_CONN_DIA_VALID_STATUS = "DB_CONN_DIA_VALID_STATUS"; + String DB_CONN_DIA_CONN_PROFILE = "DB_CONN_DIA_CONN_PROFILE"; + String CREATE_SCHEMA_SUCCESS = "CREATE_SCHEMA_SUCCESS"; + String OBJECT_ITEM_REFRESHED = "OBJECT_ITEM_REFRESHED"; + String REMOVE_SERVER = "REMOVE_SERVER"; + + String DB_CONN_DIA_MOM_USAGE = "DB_CONN_DIA_MOM_USAGE"; + String DB_CONN_DIA_MOM_USAGE_MSG = "DB_CONN_DIA_MOM_USAGE_MSG"; + String DB_CONN_DIA_GAUSS_SERVER_ERROR = "DB_CONN_DIA_GAUSS_SERVER_ERROR"; + String DB_CONN_DIA_REASON = "DB_CONN_DIA_REASON"; + String DB_CONN_DIA_GUI_ERROR_MSG = "DB_CONN_DIA_GUI_ERROR_MSG"; + String DB_CONN_DIA_CONN_PROFILE_ERROR = "DB_CONN_DIA_CONN_PROFILE_ERROR"; + String DB_CONN_DIA_FUN_TRI_PROC = "DB_CONN_DIA_FUN_TRI_PROC"; + String DB_CONN_DIA_UPDATE_OBJ_BROW_ERROR = "DB_CONN_DIA_UPDATE_OBJ_BROW_ERROR"; + + /** + * Message: Connection Failure! + */ + String ERR_GUI_SERVER_CONNECTION_FAILED = "ERR_GUI_SERVER_CONNECTION_FAILED"; + + String ERR_GUI_COMPILE_FUN_PROC_TRIG_QUERY_FAILED = "ERR_GUI_COMPILE_FUN_PROC_TRIG_QUERY_FAILED"; + + String ERR_GUI_EXECUTE_FUN_PROC_TRIG_QUERY_FAILED = "ERR_GUI_EXECUTE_FUN_PROC_TRIG_QUERY_FAILED"; + + String ERR_GUI_LOADING_FUN_PROC_TRIG_FAILED = "ERR_GUI_LOADING_FUN_PROC_TRIG_FAILED"; + + /** + * Message: Incompatible version has been loaded. Please check the + * version. + */ + + /** + * Message: Please whether the connection details are valid. + */ + String ERR_GUI_INVALID_CONNECTION_DETAILS = "ERR_GUI_INVALID_CONNECTION_DETAILS"; + + /** + * Message: Result set fetch invalid. + */ + String ERR_GUI_RESULT_SET_INVALID = "ERR_GUI_RESULT_SET_INVALID"; + + /** + * Message: Synonyms not supported for this server. + */ + + String ERR_SYNONYM_NOT_SUPPORTED = "ERR_SYNONYM_NOT_SUPPORTED"; + + /** + * Message: Creating extension required for debugging failed. + */ + + /** + * Message: Source not available. + */ + String ERR_GUI_SOURCE_NOT_AVAILABLE = "ERR_GUI_SOURCE_NOT_AVAILABLE"; + + /** + * Initializing driver failed + */ + String ERR_GUI_DRIVER_INIT_FAILED = "ERR_GUI_DRIVER_INIT_FAILED"; + + /** + * Statement Error + */ + String ERR_GUI_STMT_EXCEPTION = "ERR_GUI_STMT_EXCEPTION"; + + /** + * Message: Unable to Refresh the database object. Error getting tree + * viewer. + */ + + /** + * Message:Creating Connection failed. + */ + + /** + * Message: An error occured while attaching to target session. + */ + String ERR_BL_ATTACH_TARGET_FAILED = "ERR_BL_ATTACH_TARGET_FAILED"; + + /** + * Message: An error occured while detaching session. + */ + String ERR_BL_DETACH_TARGET_FAILED = "ERR_BL_DETACH_TARGET_FAILED"; + + /** + * Message: An error occured while getting the server sync status. + */ + String ERR_BL_GET_SERVER_SYNC_FAILED = "ERR_BL_GET_SERVER_SYNC_FAILED"; + + /** + * Message: An error occured while getting the driver version. + */ + String ERR_BL_GET_DRIVER_VERSION_FAILED = "ERR_BL_GET_DRIVER_VERSION_FAILED"; + + /** + * Message: An error occured while sync. + */ + String ERR_BL_SYNC_FAILED = "ERR_BL_SYNC_FAILED"; + + /** + * Message: Connection failed. + */ + String ERR_BL_CONNECT_FAILED = "ERR_BL_CONNECT_FAILED"; + + String IDE_INTERNAL_ERR = "IDE_INTERNAL_ERR"; + String USER_GUIDE_NAME = "USER_GUIDE_NAME"; + String LOG_SOURCE = "LOG_SOURCE"; + + /** + * Message: Execution failed. + */ + String ERR_BL_EXECUTE_FAILED = "ERR_BL_EXECUTE_FAILED"; + + /** + * Message: Get session failed. + */ + String ERR_BL_GET_SESSION_FAILED = "ERR_BL_GET_SESSION_FAILED"; + + /** + * Message: Get source code failed. + */ + String ERR_BL_GET_SOURCECODE_FAILED = "ERR_BL_GET_SOURCECODE_FAILED"; + + /** + * Message: Refresh object failed. + */ + String ERR_BL_REFRESH_OBJECT_FAILED = "ERR_BL_REFRESH_OBJECT_FAILED"; + + /** + * Message: An error while getting session id. + */ + String ERR_BL_GET_SESSION_ID_FAILED = "ERR_BL_GET_SESSION_ID_FAILED"; + /** + * Message: An error occured while getting raised messages. + */ + + String ERR_BL_REFCUR_EXECUTION_TEMPLATE_FAILURE = "ERR_BL_REFCUR_EXECUTION_TEMPLATE_FAILURE"; + + /** + * Message: Refreshing.... + */ + String MSG_GUI_REFRESH_STATUSBAR = "MSG_GUI_REFRESH_STATUSBAR"; + + /** + * Message: Terminating.... + */ + String MSG_GUI_TERMINATE_STATUSBAR = "MSG_GUI_TERMINATE_STATUSBAR"; + + /** + * Message: Executing SQL... + */ + String MSG_GUI_EXECUTE_STATUSBAR = "MSG_GUI_EXECUTE_STATUSBAR"; + + /** + * Message: Generating Visual Query Plan... + */ + String MSG_GUI_GENERATEQUERYPLAN_STATUSBAR = "MSG_GUI_GENERATEQUERYPLAN_STATUSBAR"; + + String STATUS_MSG_STATUS = "STATUS_MSG_STATUS"; + + /** + * Message: Connection failure. + */ + String ERR_BL_SERVER_CONNECTION_FAILED = "ERR_BL_SERVER_CONNECTION_FAILED"; + + /** + * Message: Invalid state to perform this operation. + */ + String ERR_BL_INVALID_STATE = "ERR_BL_INVALID_STATE"; + + String ERR_BL_LOAD_PROPERTIES = "ERR_BL_LOAD_PROPERTIES"; + + String ERR_UI_EXPORT_FILE_OVERWRITE = "ERR_UI_EXPORT_FILE_OVERWRITE"; + String ERR_UI_NAME_EXIT = "ERR_UI_NAME_EXIT"; + + String ERR_UI_EXPORT_QUERY = "ERR_UI_EXPORT_QUERY"; + + String EXE_BL_CLS = "EXE_BL_CLS"; + + /** + * Message: An unknown internal error occured. Please contact PLSQL + * IDE support team with log file. + */ + String ERR_UI_INTERNAL_FAILURE = "ERR_UI_INTERNAL_FAILURE"; + + /** + * Message: Namespace not available in the cache. + */ + String ERR_BL_NO_NAMESPACE_AVAILABLE = "ERR_BL_NO_NAMESPACE_AVAILABLE"; + + /** + * Message: Error while refreshing the namespace. + */ + + String ERR_BL_SQL_HISTORY_NOT_LOADED = "ERR_BL_SQL_HISTORY_NOT_LOADED"; + + /** + * Message: HINT: Please refresh the object browser and try again. + */ + String MSG_HINT_REFRESH_OBJECTBROWSER = "MSG_HINT_REFRESH_OBJECTBROWSER"; + + /** + * Message: HINT: Try refreshing after sometime. + */ + String MSG_HINT_GETSOURCE = "MSG_HINT_GETSOURCE"; + + /** + * Message: Searched object not available in object browser.\nHINT: + * Please refresh the object browser and search again. + */ + + /** + * Message: Clearing editor contents, as error occured while + * refreshing the object opened in editor. + */ + String MSG_CLEAR_EDITOR_CONTENT_ON_ERROR = "MSG_CLEAR_EDITOR_CONTENT_ON_ERROR"; + + /** + * Message: Object opened in sourceviewer may have been dropped. + */ + String MSG_GUI_OBJECT_MAY_DROPPED = "MSG_GUI_OBJECT_MAY_DROPPED"; + + String MSG_HINT_GUI_CONNECTION_FAIL = "MSG_HINT_GUI_CONNECTION_FAIL"; + + String MSG_HINT_GUI_CONNECTION_FAIL_FOR_SSL = "MSG_HINT_GUI_CONNECTION_FAIL_FOR_SSL"; + + String MSG_HINT_DATABASE_CRITICAL_ERROR = "MSG_HINT_DATABASE_CRITICAL_ERROR"; + + /** + * Message: Advanced search connection is busy. + */ + + String ERR_MSG_OUT_OF_MEMORY_ERROR_OCCURRED = "ERR_MSG_OUT_OF_MEMORY_ERROR_OCCURRED"; + + String ERR_TITLE_DB_CRITICAL_ERROR = "ERR_TITLE_DB_CRITICAL_ERROR"; + + String INFO_MAX_SOURCE_VIEWER = "INFO_MAX_SOURCE_VIEWER"; + + String MAX_SOURCE_VIEWER = "MAX_SOURCE_VIEWER"; + + /** + * Message: Execution Plan and costs for multiple query not avaible + */ + + String ERR_EXE_PLAN_QUERY_PARSE_FAILED = "ERR_EXE_PLAN_QUERY_PARSE_FAILED"; + /** + * Message: Debugging functionality not available. + */ + + String ERR_QUERY_EXECUTION_FAILED = "ERR_QUERY_EXECUTION_FAILED"; + + String ERR_ALREADY_CONNECTION_PROFILE_EXISTS = "ERR_ALREADY_CONNECTION_PROFILE_EXISTS"; + + String ERR_DEFAULT_DATATYPE_NOT_FOUND = "ERR_DEFAULT_DATATYPE_NOT_FOUND"; + + String ERR_CONNECTION_INVALID_STATE = "ERR_CONNECTION_INVALID_STATE"; + + String ERR_FILLFACTOR_LESS_THAN_10 = "ERR_FILLFACTOR_LESS_THAN_10"; + + String ERR_FILLFACTOR_MORE_THAN_100 = "ERR_FILLFACTOR_MORE_THAN_100"; + + String STATUS_MSG_VARIABLE_COLUMN_THREE = "STATUS_MSG_VARIABLE_COLUMN_THREE"; + String STATUS_MSG_PLVIEWER_OPTION_CUT = "STATUS_MSG_PLVIEWER_OPTION_CUT"; + String STATUS_MSG_PLVIEWER_OPTION_COPY = "STATUS_MSG_PLVIEWER_OPTION_COPY"; + String STATUS_MSG_PLVIEWER_OPTION_PASTE = "STATUS_MSG_PLVIEWER_OPTION_PASTE"; + String STATUS_MSG_PLVIEWER_OPTION_SELECTALL = "STATUS_MSG_PLVIEWER_OPTION_SELECTALL"; + String STATUS_MSG_PLVIEWER_OPTION_EXECUTE_DB_OBJECT = "STATUS_MSG_PLVIEWER_OPTION_EXECUTE_DB_OBJECT"; + String STATUS_MSG_PLVIEWER_OPTION_EXECUTE_STATEMENT = "STATUS_MSG_PLVIEWER_OPTION_EXECUTE_STATEMENT"; + String STATUS_MSG_PLVIEWER_OPTION_COMPILE_STATEMENT = "STATUS_MSG_PLVIEWER_OPTION_COMPILE_STATEMENT"; + String ERR_INDEX_NAME_EMPTY = "ERR_INDEX_NAME_EMPTY"; + + String ERR_EXECTION_IN_PROGRESS = "ERR_EXECTION_IN_PROGRESS"; + + String STATUS_MSG_CREATE_DATABASE = "STATUS_MSG_CREATE_DATABASE"; + + String STATUS_MSG_DROP_DATABASE = "STATUS_MSG_DROP_DATABASE"; + + String STATUS_MSG_UPDATE_DATABASE = "STATUS_MSG_UPDATE_DATABASE"; + + String STATUS_MSG_CONNECT_DATABASE = "STATUS_MSG_CONNECT_DATABASE"; + + String STATUS_MSG_CREATE_INDEX = "STATUS_MSG_CREATE_INDEX"; + + String STATUS_MSG_CREATE_SCHEMA = "STATUS_MSG_CREATE_SCHEMA"; + + String STATUS_MSG_CREATE_TABLE = "STATUS_MSG_CREATE_TABLE"; + + String STATUS_MSG_DISCONNECT_ALL_DB = "STATUS_MSG_DISCONNECT_ALL_DB"; + + String STATUS_MSG_DROP_DEBUG_OBJECT = "STATUS_MSG_DROP_DEBUG_OBJECT"; + + String STATUS_MSG_DROP_SCHEMA = "STATUS_MSG_DROP_SCHEMA"; + + String STATUS_MSG_RENAME_SCHEMA = "STATUS_MSG_RENAME_SCHEMA"; + + String STATUS_MSG_ADD_COLUMN = "STATUS_MSG_ADD_COLUMN"; + + String STATUS_MSG_ADD_CONSTRAINT = "STATUS_MSG_ADD_CONSTRAINT"; + + String STATUS_MSG_SET_COLUMN_DEFAULT_VALUE = "STATUS_MSG_SET_COLUMN_DEFAULT_VALUE"; + + String STATUS_MSG_ANALYSE_TABLE = "STATUS_MSG_ANALYSE_TABLE"; + + String STATUS_MSG_CHANGE_DATATYPE = "STATUS_MSG_CHANGE_DATATYPE"; + + String STATUS_MSG_CHANGE_FILLFACTOR = "STATUS_MSG_CHANGE_FILLFACTOR"; + + String STATUS_MSG_CHANGE_INDEX_TBLSPACE = "STATUS_MSG_CHANGE_INDEX_TBLSPACE"; + + String STATUS_MSG_DROP_COLUMN = "STATUS_MSG_DROP_COLUMN"; + + String STATUS_MSG_DROP_CONSTRAINT = "STATUS_MSG_DROP_CONSTRAINT"; + + String STATUS_MSG_DROP_INDEX = "STATUS_MSG_DROP_INDEX"; + + String STATUS_MSG_DROP_TABLE = "STATUS_MSG_DROP_TABLE"; + + String STATUS_MSG_REINDEX_TABLE = "STATUS_MSG_REINDEX_TABLE"; + + String STATUS_MSG_RENAME_COLUMN = "STATUS_MSG_RENAME_COLUMN"; + + String STATUS_MSG_RENAME_CONSTRAINT = "STATUS_MSG_RENAME_CONSTRAINT"; + + String STATUS_MSG_RENAME_INDEX = "STATUS_MSG_RENAME_INDEX"; + + String STATUS_MSG_RENAME_TABLE = "STATUS_MSG_RENAME_TABLE"; + + String STATUS_MSG_SET_COLUMN_NOTNULL = "STATUS_MSG_SET_COLUMN_NOTNULL"; + + String STATUS_MSG_SET_SCHEMA = "STATUS_MSG_SET_SCHEMA"; + + String STATUS_MSG_SET_TBL_DESC = "STATUS_MSG_SET_TBL_DESC"; + + String STATUS_MSG_SET_TBLSPACE = "STATUS_MSG_SET_TBLSPACE"; + + String STATUS_MSG_TRUNCATE_TABLE = "STATUS_MSG_TRUNCATE_TABLE"; + + String STATUS_MSG_VACUUM_TABLE = "STATUS_MSG_VACUUM_TABLE"; + + String STATUS_MSG_VALIDATE_CONSTRAINT = "STATUS_MSG_VALIDATE_CONSTRAINT"; + + String STATUS_MSG_AUTO_SUGGEST = "STATUS_MSG_AUTO_SUGGEST"; + + String ERR_MSG_NO_OTHER_CONNECTION = "ERR_MSG_NO_OTHER_CONNECTION"; + String ERR_EXPORT_TABLE = "ERR_EXPORT_TABLE_TO_CSV"; + String ERR_RENAME_NEED_ANOTHER_CON = "ERR_RENAME_NEED_ANOTHER_CON"; + + String ERR_NO_CONNECTION_AVAILABLE = "ERR_NO_CONNECTION_AVAILABLE"; + + String ERR_DUPLICATE_INDEX_NAME = "ERR_DUPLICATE_INDEX_NAME"; + String ERR_INDEX_COLS_EMPTY = "ERR_INDEX_COLS_EMPTY"; + + String ERR_PARTITION_COLUMN_EMPTY = "ERR_PARTITION_COLUMN_EMPTY"; + String ERR_PARTITION_NAME_EMPTY = "ERR_PARTITION_NAME_EMPTY"; + String ERR_PARTITION_VALUE_EMPTY = "ERR_PARTITION_VALUE_EMPTY"; + String ERR_PARTITION_INTERVAL_VALUE_EMPTY = "ERR_PARTITION_INTERVAL_VALUE_EMPTY"; + String ERR_PARTITION_INTERVAL_COLUMN_TYPE = "ERR_PARTITION_INTERVAL_COLUMN_TYPE"; + String ERR_DUPLICATE_PARTITION_NAME = "ERR_DUPLICATE_PARTITION_NAME"; + String ERR_PREFIX_DB_MESSAGE = "ERR_PREFIX_DB_MESSAGE"; + + String SQL = "SQL"; + + String C_FUN = "C"; + + String PLPGSQL = "PLPGSQL"; + + String PLSQL = "PLSQL"; + + String COPYRIGHT_MSG_HUAWEI = "COPYRIGHT_MSG_HUAWEI"; + String RIGHTS_RESERVRED_MSG_HUAWEI = "RIGHTS_RESERVRED_MSG_HUAWEI"; + String ABOUT_DATA_STUDIO_MSG = "ABOUT_DATA_STUDIO_MSG"; + String VERSION_NO_MSG = "VERSION_NO_MSG"; + String JAVA_VERSION_NO_MSG = "JAVA_VERSION_NO_MSG"; + String JAVA_HOME_MSG = "JAVA_HOME_MSG"; + String JAVA_HOME_NOT_SET = "JAVA_HOME_NOT_SET"; + String WEB_HUAWEI_LINK = "WEB_HUAWEI_LINK"; + + String BREAKPOINT_WINDOW_ERROR_MSG_HEADING = "BREAKPOINT_WINDOW_ERROR_MSG_HEADING"; + String BREAKPOINT_WINDOW_ERROR_MSG = "BREAKPOINT_WINDOW_ERROR_MSG"; + + String CONSOLE_WINDOW_ERROR_MSG = "CONSOLE_WINDOW_ERROR_MSG"; + String CONSOLE_WINDOW_ERROR_SCROLLING_MSG = "CONSOLE_WINDOW_ERROR_SCROLLING_MSG"; + String CONSOLE_WINDOW_MEMORY_MSG = "CONSOLE_WINDOW_MEMORY_MSG"; + String CONSOLE_WINDOW_LINE_NUMBER_MSG = "CONSOLE_WINDOW_LINE_NUMBER_MSG"; + String CONSOLE_WINDOW_OFFSET_MSG = "CONSOLE_WINDOW_OFFSET_MSG"; + String CONSOLE_WINDOW_LENGTH_MSG = "CONSOLE_WINDOW_LENGTH_MSG"; + + String EXECDIALOG_PARAMETER_VALUE = "EXECDIALOG_PARAMETER_VALUE"; + String EXECDIALOG_EXEC_PL_SQL = "EXECDIALOG_EXEC_PL_SQL"; + String EXECDIALOG_PARAMETER = "EXECDIALOG_PARAMETER"; + String EXECDIALOG_TYPE = "EXECDIALOG_TYPE"; + String EXECDIALOG_DATATYPE = "EXECDIALOG_DATATYPE"; + String EXECDIALOG_VALUE = "EXECDIALOG_VALUE"; + String EXECDIALOG_HINT = "EXECDIALOG_HINT"; + + String OBJECT_BROWSER_LABEL_MSG = "OBJECT_BROWSER_LABEL_MSG"; + + String LABEL_VIEW_SOURCE = "LABEL_VIEW_SOURCE"; + + String PL_SOURCE_EDITOR_AT = "PL_SOURCE_EDITOR_AT"; + + String ANALYSE_TABLE_ERROR_MSG = "ANALYSE_TABLE_ERROR_MSG"; + + String CHANGE_INDEX_FILLFACTOR_NEW = "CHANGE_INDEX_FILLFACTOR_NEW"; + String CHANGE_INDEX_FILLFACTOR_MIN = "CHANGE_INDEX_FILLFACTOR_MIN"; + String CHANGE_INDEX_FILLFACTOR_MAX = "CHANGE_INDEX_FILLFACTOR_MAX"; + String CHANGE_INDEX_FILLFACTOR_FOR = "CHANGE_INDEX_FILLFACTOR_FOR"; + + String CHANGE_INDEX_FILLFACTOR_CONN_ERROR = "CHANGE_INDEX_FILLFACTOR_CONN_ERROR"; + + String CHANGE_INDEX_FILLFACTOR_CHANGED = "CHANGE_INDEX_FILLFACTOR_CHANGED"; + + String CHANGE_INDEX_FILLFACTOR_TITLE = "CHANGE_INDEX_FILLFACTOR_TITLE"; + String CHANGE_INDEX_FILLFACTOR_SELECT = "CHANGE_INDEX_FILLFACTOR_SELECT"; + + String CHANGE_INDEX_TABLESPACE_NEW = "CHANGE_INDEX_TABLESPACE_NEW"; + String CHANGE_INDEX_TABLESPACE_FOR = "CHANGE_INDEX_TABLESPACE_FOR"; + String CHANGE_INDEX_TABLESPACE_CONN_ERROR = "CHANGE_INDEX_TABLESPACE_CONN_ERROR"; + String CHANGE_INDEX_TABLESPACE_TO = "CHANGE_INDEX_TABLESPACE_TO"; + String CHANGE_INDEX_TABLESPACE_TITLE = "CHANGE_INDEX_TABLESPACE_TITLE"; + String CHANGE_INDEX_TABLESPACE_SELECT = "CHANGE_INDEX_TABLESPACE_SELECT"; + + String DROP_COLUMN_DIA_TITLE = "DROP_COLUMN_DIA_TITLE"; + String DROP_COLUMN_DIA_MSG = "DROP_COLUMN_DIA_MSG"; + + String DROP_COLUMN_ERROR = "DROP_COLUMN_ERROR"; + String DROP_COLUMN_UNABLE_MSG = "DROP_COLUMN_UNABLE_MSG"; + String DROP_COLUMN_UNABLE = "DROP_COLUMN_UNABLE"; + String DROP_COLUMN_SUCCESS = "DROP_COLUMN_SUCCESS"; + + String DROP_CONSTRAINT_DIA_TITLE = "DROP_CONSTRAINT_DIA_TITLE"; + String DROP_CONSTRAINT_FROM = "DROP_CONSTRAINT_FROM"; + String DROP_CONSTRAINT_DROPPING = "DROP_CONSTRAINT_DROPPING"; + String DROP_CONSTRAINT_ERROR = "DROP_CONSTRAINT_ERROR"; + String DROP_CONSTRAINT_UNABLE_TO_DROP = "DROP_CONSTRAINT_UNABLE_TO_DROP"; + + String DROP_INDEX_DIA_TITLE = "DROP_INDEX_DIA_TITLE"; + String DROP_INDEX = "DROP_INDEX"; + String DROP_INDEX_ERROR_TITLE = "DROP_INDEX_ERROR_TITLE"; + String DROP_INDEX_ERROR_MSG = "DROP_INDEX_ERROR_MSG"; + + String DROP_INDEX_CONN_FAIL = "DROP_INDEX_CONN_FAIL"; + + String DROP_INDEX_SUCCESS = "DROP_INDEX_SUCCESS"; + + String DROP_TABLE_DIA_TITLE = "DROP_TABLE_DIA_TITLE"; + String DROP_TABLE_ERROR = "DROP_TABLE_ERROR"; + String DROP_TABLE_UNABLE = "DROP_TABLE_UNABLE"; + String DROP_TABLE_UNABLE_MSG = "DROP_TABLE_UNABLE_MSG"; + String DROP_TABLE = "DROP_TABLE"; + String DROP_TABLE_SUCCESS = "DROP_TABLE_SUCCESS"; + + String REINDEX_TABLE = "REINDEX_TABLE"; + + String REINDEX_TABLE_ERROR = "REINDEX_TABLE_ERROR"; + String REINDEX_TABLE_CONN_ERROR = "REINDEX_TABLE_CONN_ERROR"; + + String RENAME_COLUMN = "RENAME_COLUMN"; + String RENAME_COLUMN_NEW = "RENAME_COLUMN_NEW"; + + String RENAME_COLUMN_ERROR = "RENAME_COLUMN_ERROR"; + String RENAME_COLUMN_CONN_ERROR = "RENAME_COLUMN_CONN_ERROR"; + + String RENAME_COLUMN_RENAMED = "RENAME_COLUMN_RENAMED"; + + String RENAME_COLUMN_TITLE = "RENAME_COLUMN_TITLE"; + String RENAME_COLUMN_NEW_NAME = "RENAME_COLUMN_NEW_NAME"; + + String RENAME_CONSTRAINT = "RENAME_CONSTRAINT"; + String RENAME_CONSTRAINT_CONN_ERROR = "RENAME_CONSTRAINT_CONN_ERROR"; + + String RENAME_CONSTRAINT_TITLE = "RENAME_CONSTRAINT_TITLE"; + String RENAME_CONSTRAINT_NEW_NAME = "RENAME_CONSTRAINT_NEW_NAME"; + String RENAME_CONSTRAINT_WAIT = "RENAME_CONSTRAINT_WAIT"; + String RENAME_CONSTRAINT_ERROR = "RENAME_CONSTRAINT_ERROR"; + String RENAME_CONSTRAINT_RENAMED = "RENAME_CONSTRAINT_RENAMED"; + + String RENAME_INDEX_NEW_NAME = "RENAME_INDEX_NEW_NAME"; + String RENAME_INDEX_WAIT = "RENAME_INDEX_WAIT"; + String RENAME_INDEX_ERROR = "RENAME_INDEX_ERROR"; + String RENAME_INDEX_CONN_ERROR = "RENAME_INDEX_CONN_ERROR"; + String RENAME_INDEX_TITLE = "RENAME_INDEX_TITLE"; + String RENAME_INDEX_RENAMED = "RENAME_INDEX_RENAMED"; + String RENAME_INDEX_NEW = "RENAME_INDEX_NEW"; + + String RENAME_TABLE_NEW_NAME = "RENAME_TABLE_NEW_NAME"; + String RENAME_TABLE_WAIT = "RENAME_TABLE_WAIT"; + String RENAME_TABLE_ERROR = "RENAME_TABLE_ERROR"; + String RENAME_TABLE_CONN_ERROR = "RENAME_TABLE_CONN_ERROR"; + String RENAME_TABLE_TO = "RENAME_TABLE_TO"; + String RENAME_TABLE_TITLE = "RENAME_TABLE_TITLE"; + + String RENAME_TABLE_NEW = "RENAME_TABLE_NEW"; + + String RENAME_TRIGGER_WAIT = "RENAME_TRIGGER_WAIT"; + + String SET_COLUMN_TOGGLE_TITLE = "SET_COLUMN_TOGGLE_TITLE"; + String SET_COLUMN_TOGGLE_MSG = "SET_COLUMN_TOGGLE_MSG"; + String SET_COLUMN = "SET_COLUMN"; + String SET_COLUMN_ERROR = "SET_COLUMN_ERROR"; + String SET_COLUMN_UNABLE = "SET_COLUMN_UNABLE"; + + String SET_COLUMN_NOT_NULL_SUCCESSFUL = "SET_COLUMN_NOT_NULL_SUCCESSFUL"; + + String SET_SCEMA_SELECT = "SET_SCEMA_SELECT"; + String SET_SCEMA_MOVING = "SET_SCEMA_MOVING"; + + String SET_SCEMA_ERROR = "SET_SCEMA_ERROR"; + String SET_SCEMA = "SET_SCEMA"; + String SET_SCEMA_CONN_ERROR = "SET_SCEMA_CONN_ERROR"; + String SET_SCEMA_MOVED = "SET_SCEMA_MOVED"; + + String SET_SCEMA_TITLE = "SET_SCEMA_TITLE"; + + String SET_SCEMA_SELECT_NEW = "SET_SCEMA_SELECT_NEW"; + + String SET_TABLE_NEW_DESC = "SET_TABLE_NEW_DESC"; + String SET_TABLE_UPDATE_DESC = "SET_TABLE_UPDATE_DESC"; + + String SET_TABLE_UPDATE_ERROR = "SET_TABLE_UPDATE_ERROR"; + String SET_TABLE_CONN_ERROR = "SET_TABLE_CONN_ERROR"; + String SET_TABLE_DESC_SUCCES = "SET_TABLE_DESC_SUCCES"; + + String SET_TABLE_DESC_TITLE = "SET_TABLE_DESC_TITLE"; + String SET_TABLE_NEW_DESC_FOR = "SET_TABLE_NEW_DESC_FOR"; + + String SET_TABLESPACE_NEW = "SET_TABLESPACE_NEW"; + String SET_TABLESPACE_FROM_CURRENT = "SET_TABLESPACE_FROM_CURRENT"; + + String SET_TABLESPACE_ERROR = "SET_TABLESPACE_ERROR"; + String SET_TABLESPACE_CONN_ERROR = "SET_TABLESPACE_CONN_ERROR"; + String SET_TABLESPACE_FROM = "SET_TABLESPACE_FROM"; + String SET_TABLESPACE = "SET_TABLESPACE"; + + String SET_TABLESPACE_TITLE = "SET_TABLESPACE_TITLE"; + String SET_TABLESPACE_IN = "SET_TABLESPACE_IN"; + String SET_TABLE_FROM_TABLESPACE = "SET_TABLE_FROM_TABLESPACE"; + + String TRUNCATE_TABLE_TITLE = "TRUNCATE_TABLE_TITLE"; + String TRUNCATE_TABLE_MSG = "TRUNCATE_TABLE_MSG"; + String TRUNCATE_TABLE_TRUNCATED = "TRUNCATE_TABLE_TRUNCATED"; + String TRUNCATE_TABLE_ERROR = "TRUNCATE_TABLE_ERROR"; + String TRUNCATE_TABLE_CONN_ERROR = "TRUNCATE_TABLE_CONN_ERROR"; + + String VACCUM_TABLE_SUCCESS = "VACCUM_TABLE_SUCCESS"; + String VACCUME_TABLE_ERROR = "VACCUME_TABLE_ERROR"; + String VACCUME_TABLE_CONN_ERROR = "VACCUME_TABLE_CONN_ERROR"; + + String VALIDATE_CONSTRAINT_SUCCESS = "VALIDATE_CONSTRAINT_SUCCESS"; + String VALIDATE_CONSTRAINT_ERROR = "VALIDATE_CONSTRAINT_ERROR"; + String VALIDATE_CONSTRAINT_UNABLE = "VALIDATE_CONSTRAINT_UNABLE"; + + String VIEW_TABALE_DATA_ERROR = "VIEW_TABALE_DATA_ERROR"; + String VIEW_TABALE_DATA_UNABLE = "VIEW_TABALE_DATA_UNABLE"; + String VIEW_TABALE_DATA_UNABLE_VIEW = "VIEW_TABALE_DATA_UNABLE_VIEW"; + + String EXEC_PLAN_TITLE = "EXEC_PLAN_TITLE"; + + String EXEC_PLAN_PARSE_FAIL = "EXEC_PLAN_PARSE_FAIL"; + + String EXEC_PLAN_TEXT = "EXEC_PLAN_TEXT"; + + String EXEC_PLAN_OK = "EXEC_PLAN_OK"; + + String EXEC_PLAN_FAIL_MSG = "EXEC_PLAN_FAIL_MSG"; + + String FIND_REPLACE_TITLE = "FIND_REPLACE_TITLE"; + String FIND_REPLCAE_WHAT = "FIND_REPLCAE_WHAT"; + String FIND_REPLACE_WITH = "FIND_REPLACE_WITH"; + String FIND_REPLACE_BACK = "FIND_REPLACE_BACK"; + String FIND_REPLACE_MATCH = "FIND_REPLACE_MATCH"; + String FIND_REPLACE_WHOLE = "FIND_REPLACE_WHOLE"; + String FIND_REPLACE_WRAP = "FIND_REPLACE_WRAP"; + String FIND_REPLACE_NEXT = "FIND_REPLACE_NEXT"; + String FIND_REPLACE = "FIND_REPLACE"; + String FIND_REPLACE_ALL = "FIND_REPLACE_ALL"; + + String FIND_REPLACE_SEARCH_NOT_FOUND = "FIND_REPLACE_SEARCH_NOT_FOUND"; + + String PL_SOURCE_VIEWER_ERROR = "PL_SOURCE_VIEWER_ERROR"; + String PL_SOURCE_VIEWER_UNABLE = "PL_SOURCE_VIEWER_UNABLE"; + String PL_SOURCE_CODE_ERROR = "PL_SOURCE_CODE_ERROR"; + String PL_SOURCE_DISPLAY_ERROR = "PL_SOURCE_DISPLAY_ERROR"; + + String PROPERTIES_WID_PROPERTY = "PROPERTIES_WID_PROPERTY"; + String PROPERTIES_WID_VALUE = "PROPERTIES_WID_VALUE"; + + String RESULT_WINDOW_REFRESH = "RESULT_WINDOW_REFRESH"; + + String SQL_TERMINAL_CONN = "SQL_TERMINAL_CONN"; + String SQL_TERMINAL_CONNS = "SQL_TERMINAL_CONNS"; + + // Default Schema + String DEFAULT_SCHEMA_INITIAL_MSG = "DEFAULT_SCHEMA_INITIAL_MSG"; + String DEFAULT_SCHEMA_ERROR_TITLE = "DEFAULT_SCHEMA_ERROR_TITLE"; + String DEFAULT_SCHEMA_ERROR_MSG = "DEFAULT_SCHEMA_ERROR_MSG"; + + // Block Root user in Linux + String USER_ROOT_ERROR_TITLE = "USER_ROOT_ERROR_TITLE"; + String USER_ROOT_ERROR_MSG = "USER_ROOT_ERROR_MSG"; + + String MPPDBIDE_DIA_BTN_YES = "MPPDBIDE_DIA_BTN_YES"; + String MPPDBIDE_DIA_BTN_NO = "MPPDBIDE_DIA_BTN_NO"; + String MPPDBIDE_DIA_BTN_CANC = "MPPDBIDE_DIA_BTN_CANC"; + String MPPDBIDE_DIA_BTN_DISCARD = "MPPDBIDE_DIA_BTN_DISCARD"; + + String MPPDB_IDE_MOM_MAX = "MPPDB_IDE_MOM_MAX"; + + String UI_DISPLAY_PERFORMING = "UI_DISPLAY_PERFORMING"; + + String COLUMN_OLD_NAME = "COLUMN_OLD_NAME"; + String DISCONN_IN_PROGRESS = "DISCONN_IN_PROGRESS"; + + String USER_INPUT_PSW_DIA_MSG = "USER_INPUT_PSW_DIA_MSG"; + + String INDEX_UI_NAME = "INDEX_UI_NAME"; + String INDEX_UI_MSG = "INDEX_UI_MSG"; + String INDEX_UI_UNIQUE_INDEX = "INDEX_UI_UNIQUE_INDEX"; + String INDEX_UI_FILLFACTOR = "INDEX_UI_FILLFACTOR"; + String INDEX_UI_PARTIAL_INDEX = "INDEX_UI_PARTIAL_INDEX"; + String INDEX_UI_USER_EXPRESSION = "INDEX_UI_USER_EXPRESSION"; + String INDEX_UI_OR = "INDEX_UI_OR"; + String INDEX_UI_AVA_COLUMNS = "INDEX_UI_AVA_COLUMNS"; + String INDEX_UI_INDEX_CLMS = "INDEX_UI_INDEX_CLMS"; + String INDEX_UI_ADD_TO = "INDEX_UI_ADD_TO"; + String INDEX_UI_REMOVE = "INDEX_UI_REMOVE"; + String INDEX_UI_MOVE_UP = "INDEX_UI_MOVE_UP"; + String INDEX_UI_MOVE_DOWN = "INDEX_UI_MOVE_DOWN"; + String INDEX_UI_TYPE = "INDEX_UI_TYPE"; + String INDEX_UI_ACCESS_METHOD = "INDEX_UI_ACCESS_METHOD"; + String INDEX_UI_TABLESPACE = "INDEX_UI_TABLESPACE"; + + String DATA_DIST_UI_HAST_FUN = "DATA_DIST_UI_HAST_FUN"; + + String DATA_DIST_UI_DEFAULT_DIST = "DATA_DIST_UI_DEFAULT_DIST"; + String DATA_DIST_UI_DIST_TYPE = "DATA_DIST_UI_DIST_TYPE"; + + String DATA_DIST_UI_AVAI_CLMS = "DATA_DIST_UI_AVAI_CLMS"; + String DATA_DIST_UI_NEW_FUN = "DATA_DIST_UI_NEW_FUN"; + String DATA_DIST_UI_HASH_CLMNS = "DATA_DIST_UI_HASH_CLMNS"; + + String CREATE_TABLE_ADD = "CREATE_TABLE_ADD"; + String CREATE_TABLE_CONSTRAINT = "CREATE_TABLE_CONSTRAINT"; + String CREATE_TABLE_DATA_TYPE = "CREATE_TABLE_DATA_TYPE"; + String CREATE_TABLE_CLM_NAME = "CREATE_TABLE_CLM_NAME"; + String CREATE_NEW_TABLE = "CREATE_NEW_TABLE"; + + String CREATE_TABLE_CLM_EDIT = "CREATE_TABLE_CLM_EDIT"; + String CREATE_TABLE_CLM_DELETE = "CREATE_TABLE_CLM_DELETE"; + String CREATE_TABLE_INDEX_DEF = "CREATE_TABLE_INDEX_DEF"; + String CREATE_TABLE_FILL_FACTOR = "CREATE_TABLE_FILL_FACTOR"; + + String CREATE_TABLE_OIDS = "CREATE_TABLE_OIDS"; + String CREATE_TABLE_NOT_EXISTS = "CREATE_TABLE_NOT_EXISTS"; + String CREATE_TABLE_OPTIONS = "CREATE_TABLE_OPTIONS"; + String CREATE_TABLE_TYPE = "CREATE_TABLE_TYPE"; + String CREATE_TABLE_UNLOGGED = "CREATE_TABLE_UNLOGGED"; + String CREATE_TABLE_NORMAL = "CREATE_TABLE_NORMAL"; + String CREATE_TABLE_TEMPORARY = "CREATE_TABLE_TEMPORARY"; + String CREATE_TABLE_CASE = "CREATE_TABLE_CASE"; + String CREATE_TABLE_TABLE_NAME = "CREATE_TABLE_TABLE_NAME"; + String CREATE_TABLE_SCEMA = "CREATE_TABLE_SCEMA"; + String CREATE_TABLE_CREATE_ERROR = "CREATE_TABLE_CREATE_ERROR"; + String CREATE_TABLE_CREATE_SUCCESS = "CREATE_TABLE_CREATE_SUCCESS"; + String CREATE_TABLE_ENTER_TABLE_NM = "CREATE_TABLE_ENTER_TABLE_NM"; + String CREATE_TABLE_BACK_BTN = "CREATE_TABLE_BACK_BTN"; + String CREATE_TABLE_NEXT_BTN = "CREATE_TABLE_NEXT_BTN"; + String CREATE_TABLE_FINISH_BTN = "CREATE_TABLE_FINISH_BTN"; + String CREATE_TABLE_NO_CLM_MSG = "CREATE_TABLE_NO_CLM_MSG"; + String CREATE_TABLE_VALID_NAME = "CREATE_TABLE_VALID_NAME"; + String CREATE_TABLE_CONST_DELETE = "CREATE_TABLE_CONST_DELETE"; + String CREATE_TABLE_CONST_EDIT_MSG = "CREATE_TABLE_CONST_EDIT_MSG"; + String CREATE_TABLE_CONSTRAINT_MSG = "CREATE_TABLE_CONSTRAINT_MSG"; + String CREATE_TABLE_DELETE_MSG = "CREATE_TABLE_DELETE_MSG"; + String CREATE_TABLE_EDIT_MSG = "CREATE_TABLE_EDIT_MSG"; + String CREATE_TABLE_SQL_PREVIEW = "CREATE_TABLE_SQL_PREVIEW"; + + String CREATE_TABLE_COLUMN_EXISTS = "CREATE_TABLE_COLUMN_EXISTS"; + + String CREATE_TABLE_INDEXES = "CREATE_TABLE_INDEXES"; + + String CREATE_TABLE_COLUMNS = "CREATE_TABLE_COLUMNS"; + String CREATE_TABLE_GENERAL = "CREATE_TABLE_GENERAL"; + + String CREATE_TABLE_DELETE = "CREATE_TABLE_DELETE"; + String CREATE_TABLE_EDIT = "CREATE_TABLE_EDIT"; + String ADD_NEW_CONSTRAINT = "ADD_NEW_CONSTRAINT"; + String EDIT_CONSTRAINT = "EDIT_CONSTRAINT"; + String ALTER_COLUMN_SHELL_TEXT = "ALTER_COLUMN_SHELL_TEXT"; + + String EDIT_CONSTRAINT_LABEL = "EDIT_CONSTRAINT_LABEL"; + + String ARRAY_DIMENSIONS = "ARRAY_DIMENSIONS"; + String CHECK_COLUMN_UI = "CHECK_COLUMN_UI"; + String DFLT_CLM_UI = "DFLT_CLM_UI"; + + String CREATE_TABLE_PARTITION_EDIT = "CREATE_TABLE_PARTITION_EDIT"; + String CREATE_TABLE_PARTITION_DELETE = "CREATE_TABLE_PARTITION_DELETE"; + String CREATE_TABLE_NO_PARTITION_MSG = "CREATE_TABLE_NO_PARTITION_MSG"; + + // RenameSchema.java + String NEW_NAME_FOR_SCHEMA_TO_CONTINUE = "NEW_NAME_FOR_SCHEMA_TO_CONTINUE"; + String RENAMING_SCHEMA = "RENAMING_SCHEMA"; + String ENTER_NEW_NAME_FOR = "ENTER_NEW_NAME_FOR"; + + String RENAME_SCHEMA = "RENAME_SCHEMA"; + String DB_RENAME_RENAMED = "DB_RENAME_RENAMED"; + String SCHEMA_TO = "SCHEMA_TO"; + String DB_RENAME_RENAMING = "DB_RENAME_RENAMING"; + + String CONNECTION_ERR_DURING_REMANING = "CONNECTION_ERR_DURING_REMANING"; + + // RenameDatabase + String ENTER_NEW_NAME_FOR_DB = "ENTER_NEW_NAME_FOR_DB"; + String DB_RENAME_RENAMING_DATABASE = "DB_RENAME_RENAMING_DATABASE"; + String DB_RENAME_RENAMED_DATABASE = "DB_RENAME_RENAMED_DATABASE"; + String RENAME_DATABASE = "RENAME_DATABASE"; + String DATABASE = "DATABASE"; + String DATABASE_RENAME_CONFIRMATION = "DATABASE_RENAME_CONFIRMATION"; + + String ERR_WHILE_RENAMING_DATABASE = "ERR_WHILE_RENAMING_DATABASE"; + + String UNABLE_TO_CONNECT_TO_DATABASE = "UNABLE_TO_CONNECT_TO_DATABASE"; + + String UNABLE_TO_CONNECT_TO_DATABASE_DB = "UNABLE_TO_CONNECT_TO_DATABASE_DB"; + + // RemoveServer + String REMOVE_SEVER = "REMOVE_SEVER"; + String REMOVE_SERVER_CONFIRMATION = "REMOVE_SERVER_CONFIRMATION"; + + String SERVER_REMOVED = "SERVER_REMOVED"; + + // RefreshObjectBrowserItem + String REFRESH_IN_PROGRESS = "REFRESH_IN_PROGRESS"; + String MEMORY_USAGE = "MEMORY_USAGE"; + String MEMORY_USAGE_WARNING = "MEMORY_USAGE_WARNING"; + String ERR_WHILE_REFRESHING = "ERR_WHILE_REFRESHING"; + + String PLSQL_ERR = "PLSQL_ERR"; + String UNKNOWN_INTERNAL_ERR = "UNKNOWN_INTERNAL_ERR"; + String ERR_DURING_REFRESHING = "ERR_DURING_REFRESHING"; + + String ERR_DENIED_ACCESS_PRIVILEGE = "ERR_DENIED_ACCESS_PRIVILEGE"; + String EXCEPTION_OCCURED_WHILE_FETCHING_OBJECTS = "EXCEPTION_OCCURED_WHILE_FETCHING_OBJECTS"; + + // PropertiesHandler + String PROP_HANDLER_PROPERTIES = "PROP_HANDLER_PROPERTIES"; + String PROP_HANDLER_PROPERTIES_ERROR = "PROP_HANDLER_PROPERTIES_ERROR"; + String PROPERTIES_WARNING = "PROPERTIES_WARNING"; + + // OpenHelp + String HLP_DOC_NOT_EXIST = "HLP_DOC_NOT_EXIST"; + String UNABLE_TO_FIND_HLP_DOC = "UNABLE_TO_FIND_HLP_DOC"; + + // HandlerUtilities + + String ROWS_AFFECTED = "ROWS_AFFECTED"; + + String DISPLAY_SOURCE_CODE_FAILED = "DISPLAY_SOURCE_CODE_FAILED"; + String ERR_OCCURED_WHILE_DISPLAYING_CODE = "ERR_OCCURED_WHILE_DISPLAYING_CODE"; + String FETCHING_SOURCE_CODE_FAILED = "FETCHING_SOURCE_CODE_FAILED"; + String HANDLER_UTILITIES_CANNOT = "HANDLER_UTILITIES_CANNOT"; + String HANDLER_UTILITIES_CANNOT_PERFORM = "HANDLER_UTILITIES_CANNOT_PERFORM"; + String FUNCTION_PROCEDURE = "FUNCTION_PROCEDURE"; + + String ERR_GUI_SOURCE_NOT_AVAILABLE_HANDLER = "ERR_GUI_SOURCE_NOT_AVAILABLE_HANDLER"; + + // ExportTableHandler + String FILE_OVERWRITE = "FILE_OVERWRITE"; + + String COULD_NOT_SET_READABLE = "COULD_NOT_SET_READABLE"; + String EXPORT_TABLE = "EXPORT_TABLE"; + String DATA_EXPORTED = "DATA_EXPORTED"; + String ERR_EXPORT_TABLE_TO_CSV_HANDLER = "ERR_EXPORT_TABLE_TO_CSV_HANDLER"; + + // ExportResultTable + String DATA_EXPORTED_TO = "DATA_EXPORTED_TO"; + String EXPORT_FILE = "EXPORT_FILE"; + + // ExitApplication + String EXIT_APPLICATION = "EXIT_APPLICATION"; + String EXIT_APPLICATION_CONFIRMATION = "EXIT_APPLICATION_CONFIRMATION"; + + String GRACEFULL_EXIT_DATASTUDIO = "GRACEFULL_EXIT_DATASTUDIO"; + String FORCE_EXIT_DATSTUDIO = "FORCE_EXIT_DATSTUDIO"; + + // ExecuteSQLTerminal + String DATABASE_CONNECTION_ERR = "DATABASE_CONNECTION_ERR"; + + String ERR_QUERY_LENGTH_TOO_BIG = "ERR_QUERY_LENGTH_TOO_BIG"; + + // ExecuteObjectBrowserItem + String OPERATION_CANNOT_BE_PERFOREMD = "OPERATION_CANNOT_BE_PERFOREMD"; + String ERR_WHILE_STARTING_EXECUTE_SQL = "ERR_WHILE_STARTING_EXECUTE_SQL"; + String SOURCE_CODE_CHANGE = "SOURCE_CODE_CHANGE"; + String SOURCE_HAS_BEEN_CHANGED = "SOURCE_HAS_BEEN_CHANGED"; + String EXECUTION_FAILED_ITEM = "EXECUTION_FAILED_ITEM"; + + // ExecuteEditorItem + String ERR_WHILE_STARTING_TO_EXECUTE_SQL_OBJECT = "ERR_WHILE_STARTING_TO_EXECUTE_SQL_OBJECT"; + + // DropSchema + String DROP_SCHEMA = "DROP_SCHEMA"; + String DROP_SCHEMA_CONFIRMATION = "DROP_SCHEMA_CONFIRMATION"; + String SCHEMA_NAME = "SCHEMA_NAME"; + String DB_DROPPED = "DB_DROPPED"; + String DROP_SUCCESS = "DROP_SUCCESS"; + String ERR_WHILE_DROPPING_SCHEMS = "ERR_WHILE_DROPPING_SCHEMS"; + String ERR_WHILE_DROPPING_SCHEMS_MESSAGE = "ERR_WHILE_DROPPING_SCHEMS_MESSAGE"; + + String ERR_WHEN_DROPPING_SCHEMA = "ERR_WHEN_DROPPING_SCHEMA"; + String SERVER_MSG = "SERVER_MSG"; + String CONNECTION_ERR_WHEN_DROPPING_SCHEMA = "CONNECTION_ERR_WHEN_DROPPING_SCHEMA"; + + // Drop Function/Procedure + String DROP_FUNC_PROC = "DROP_FUNC_PROC"; + String DROP_FUNC_PROC_CONFIRMATION = "DROP_FUNC_PROC_CONFIRMATION"; + String FUNC_PROC_DROPPED = "FUNC_PROC_DROPPED"; + + String ERR_DROP_FUNC_PROC = "ERR_DROP_FUNC_PROC"; + String EXECUTION_FAILED = "EXECUTION_FAILED"; + + // Drop Package + + // DropDatabase + String DB_DROPPED_DATABASE = "DB_DROPPED_DATABASE"; + String DROP_DATABASE = "DROP_DATABASE"; + String DROP_DATABASE_ALERT = "DROP_DATABASE_ALERT"; + + String DATABASE_SUCCESSFULLY = "DATABASE_SUCCESSFULLY"; + String ERR_WHEN_DROPPING_DB = "ERR_WHEN_DROPPING_DB"; + String UNABLE_TO_DROP_DB = "UNABLE_TO_DROP_DB"; + + String UNABLE_TO_DROP = "UNABLE_TO_DROP"; + + String ERROR_DURING_SCHEMA_CREATION = "ERROR_DURING_SCHEMA_CREATION"; + + // DisconnectDatabase + String DATABASE_DISCONNECT = "DATABASE_DISCONNECT"; + String DISCONNECT_CONFIRMATION = "DISCONNECT_CONFIRMATION"; + + String DISCONNECTED_FROM_SERVER = "DISCONNECTED_FROM_SERVER"; + + // DisconnectALLdb + + String DISCONNECT_ALL_DB = "DISCONNECT_ALL_DB"; + + // CreateSchema + String ENTER_SCHEMA_NAME_TO_CONTINUE = "ENTER_SCHEMA_NAME_TO_CONTINUE"; + String STATUS_CREATING_SCHEMA = "STATUS_CREATING_SCHEMA"; + String ERROR_WHILE_CREATING_SCHEMA = "ERROR_WHILE_CREATING_SCHEMA"; + String CONNECTION_ERROR_DURING_SCHEMA_CREATION = "CONNECTION_ERROR_DURING_SCHEMA_CREATION"; + + String CREATE_SCHEMA = "CREATE_SCHEMA"; + String ENTER_SCHMEA_NAME = "ENTER_SCHMEA_NAME"; + + // CreateDatabase + String ENTER_DATABASE_NAME_TO_CREATE = "ENTER_DATABASE_NAME_TO_CREATE"; + String CREATING_DATABASE = "CREATING_DATABASE"; + String ERROR_WHILE_CREATING_DATABASE = "ERROR_WHILE_CREATING_DATABASE"; + + String NAME_OF_THE_DATABASE = "NAME_OF_THE_DATABASE"; + String CREATE_DATABASE = "CREATE_DATABASE"; + String CURRENT_USER_CIPHER_TO_CONNECT_TO_DB = "CURRENT_USER_CIPHER_TO_CONNECT_TO_DB"; + + // ConnectToDB + String SUCCESSFULLY_CONNECTED_TO = "SUCCESSFULLY_CONNECTED_TO"; + String CONNECTION_ERR = "CONNECTION_ERR"; + String LOADING_OBJECT_INTO_BROWSER = "LOADING_OBJECT_INTO_BROWSER"; + String OBJECT_SUCCESSFULLY_LOADED = "OBJECT_SUCCESSFULLY_LOADED"; + String ENTRE_CIPHER = "ENTRE_CIPHER"; + String ENTER_CURRENT_USER_CIPHER = "ENTER_CURRENT_USER_CIPHER"; + + // ConfigCheckHandler + String LOGIN_TIMEOUT_CHECKED_FAILED = "LOGIN_TIMEOUT_CHECKED_FAILED"; + String TIMEOUT_VALUE_CHECK_FAILED = "TIMEOUT_VALUE_CHECK_FAILED"; + String ENTER_VALID_TIMEOUT_VALUE = "ENTER_VALID_TIMEOUT_VALUE"; + + String JDK_VERSION_CHECK_FAILED = "JDK_VERSION_CHECK_FAILED"; + String IDE_JDK_VERSION_CHECK_FAILED = "IDE_JDK_VERSION_CHECK_FAILED"; + String ENTER_VALID_JDK_VERSION = "ENTER_VALID_JDK_VERSION"; + + String EXE_TERMINAL_EXC_TIME_MSG = "EXE_TERMINAL_EXC_TIME_MSG"; + String EXE_TERMINAL_EXC_TIME_MSG_RESULT = "EXE_TERMINAL_EXC_TIME_MSG_RESULT"; + + String DS_DEFAULT_ENCODING = "DS_DEFAULT_ENCODING"; + + String DS_DEFAULT_CONSOLE_LINE_COUNT = "DS_DEFAULT_CONSOLE_LINE_COUNT"; + + String DS_INVALID_ENABLE_SECURITY_WARNING = "DS_INVALID_ENABLE_SECURITY_WARNING"; + + // AnalyzeTableHandler + String TABLE_ANALYZED = "TABLE_ANALYZED"; + String TABLE_ANALYZED_ERROR = "TABLE_ANALYZED_ERROR"; + String TABLE_ANALYZED_CONNECTION_ERROR = "TABLE_ANALYZED_CONNECTION_ERROR"; + + String ADD_COLUMN = "ADD_COLUMN"; + String ERR_WHILE_ADDING_COL = "ERR_WHILE_ADDING_COL"; + String UNABLE_TO_ADD_COL = "UNABLE_TO_ADD_COL"; + + String PLS_ENTER_COL_NAME = "PLS_ENTER_COL_NAME"; + String PLS_SELECT_DATA_TYPE = "PLS_SELECT_DATA_TYPE"; + + // CreateIndexDialog + String CREATE_INDEX = "CREATE_INDEX"; + String CREATE_INDEX_SET_TEXT = "CREATE_INDEX_SET_TEXT"; + String CREATE_INDEX_GENERATE_QUERY = "CREATE_INDEX_GENERATE_QUERY"; + String CREATE_INDEX_PREVIEW = "CREATE_INDEX_PREVIEW"; + String CREATE_INDEX_BTN = "CREATE_INDEX_BTN"; + String CREATE_INDEX_SUCCESS = "CREATE_INDEX_SUCCESS"; + String CREATE_INDEX_ERROR = "CREATE_INDEX_ERROR"; + String CREATE_INDEX_CONN_ERROR = "CREATE_INDEX_CONN_ERROR"; + + // ConstraintUI + String CONSTRAINT_TYPE = "CONSTRAINT_TYPE"; + String CONSTRAINT_NAME = "CONSTRAINT_NAME"; + String CONSTRAINT_DESC = "CONSTRAINT_DESC"; + String CONSTRAINT_SELECTED_COLUMNS = "CONSTRAINT_SELECTED_COLUMNS"; + String CONSTRAINT_AVAILABLE_COLUMNS = "CONSTRAINT_AVAILABLE_COLUMNS"; + String CONSTRAINT_NEW_BTN = "CONSTRAINT_NEW_BTN"; + String CONSTRAINT_ON_TABLESPACE = "CONSTRAINT_ON_TABLESPACE"; + String CONSTRAINT_DEFERABLE = "CONSTRAINT_DEFERABLE"; + String CONSTRAINT_INITIALLY_DEFERRED = "CONSTRAINT_INITIALLY_DEFERRED"; + String CONSTRAINT_FILL_FACTOR = "CONSTRAINT_FILL_FACTOR"; + String CONSTRAINT_COLUMN_NAME = "CONSTRAINT_COLUMN_NAME"; + String CONSTRAINT_DATA_TYPE = "CONSTRAINT_DATA_TYPE"; + String CONSTRAINT_EXPRESSION = "CONSTRAINT_EXPRESSION"; + String CONSTRAINT_CHECK_EXPRESSION = "CONSTRAINT_CHECK_EXPRESSION"; + + String CONSTRAINT_FOREIGN_NAMESPACE = "CONSTRAINT_FOREIGN_NAMESPACE"; + String CONSTRAINT_FOREIGE_TABLENAME = "CONSTRAINT_FOREIGE_TABLENAME"; + String CONSTRAINT_FOREIGE_COLUMNNAME = "CONSTRAINT_FOREIGE_COLUMNNAME"; + + String DATA_TYPE = "DATA_TYPE"; + + String SIZE = "SIZE"; + String SCALE_MSG = "SCALE_MSG"; + String COL_NAME = "COL_NAME"; + String COL_CONS = "COL_CONS"; + String NOT_NULL = "NOT_NULL"; + String UNIQUE_MSG = "UNIQUE_MSG"; + String CASE_MSG = "CASE_MSG"; + + String AVL_COL = "AVL_COL"; + + String ON_DELETE = "ON_DELETE"; + + String REF_COL = "REF_COL"; + String INITIALLY_DEFERRED = "INITIALLY_DEFERRED"; + + // logger + String DRIVER_INIT = "DRIVER_INIT"; + + String SUCCESSFULLY_CONNECTED = "SUCCESSFULLY_CONNECTED"; + + String CANCEL_QUERY = "CANCEL_QUERY"; + + String DELETED = "DELETED"; + + String ENABL_ING = "ENABL_ING"; + String DISABL_ING = "DISABL_ING"; + String REMOVE_BP = "REMOVE_BP"; + + String GUI_PLSOURCEEDITORCORE_SOURCE_EDITOR_CLEARED = "GUI_PLSOURCEEDITORCORE_SOURCE_EDITOR_CLEARED"; + String GUI_PLSOURCEEDITORCORE_ADD_ANNOTATION = "GUI_PLSOURCEEDITORCORE_ADD_ANNOTATION"; + String GUI_PLSOURCEEDITORCORE_REMOVE_ANNOTATION = "GUI_PLSOURCEEDITORCORE_REMOVE_ANNOTATION"; + + String CLEARED_CONSOLE_CONTENTS = "CLEARED_CONSOLE_CONTENTS"; + String GUI_FORMATTING_SQL_QUERY_STATEMENTS_FROM_FORMAT_MENU = "GUI_FORMATTING_SQL_QUERY_STATEMENTS_FROM_FORMAT_MENU"; + + String GUI_CREATE_FUNCTION = "GUI_CREATE_FUNCTION"; + String GUI_CREATE_PROCEDURE = "GUI_CREATE_PROCEDURE"; + + String DROPPED = "DROPPED"; + + String GUI_DROPDEBUGOBJECT_DROP_DEBUG_OBJECT = "GUI_DROPDEBUGOBJECT_DROP_DEBUG_OBJECT"; + + String GUI_EXECUTEEDITORITEM_EXECUTE_CLICKED = "GUI_EXECUTEEDITORITEM_EXECUTE_CLICKED"; + String GUI_EXECUTEOBJECTBROWSERITEM_EXECUTE_OBJECT_BROWSER_CLICKED = "GUI_EXECUTEOBJECTBROWSERITEM_EXECUTE_OBJECT_BROWSER_CLICKED"; + String GUI_EXECUTED_SQL_TERMINAL_STATEMENT = "GUI_EXECUTED_SQL_TERMINAL_STATEMENT"; + String TIME_BY_TAKEN_APPLICATION_EXECUTE_QUERY = "TIME_BY_TAKEN_APPLICATION_EXECUTE_QUERY"; + + String GUI_EXITAPPLICATION_EXIT_CLICKED = "GUI_EXITAPPLICATION_EXIT_CLICKED"; + String GUI_APPLICATION_EXITED = "GUI_APPLICATION_EXITED"; + + String GUI_NEWDBCONNECTION_OPEN_CONNECTION_WIZARD = "GUI_NEWDBCONNECTION_OPEN_CONNECTION_WIZARD"; + + String MOVING_TABLE_SELECTED_TABLESPACE_SUCCESFULL = "MOVING_TABLE_SELECTED_TABLESPACE_SUCCESFULL"; + + String SUCCESSFULLY = "SUCCESSFULLY"; + String INDEX = "INDEX"; + + String GUI_UIDISPLAYSTATE_CLEANING_UP_UI_ELEMENTS = "GUI_UIDISPLAYSTATE_CLEANING_UP_UI_ELEMENTS"; + String NO_NEED_ANYTHING_JUST_CONTINUE_EXECUTION = "NO_NEED_ANYTHING_JUST_CONTINUE_EXECUTION"; + + String NEW_NONAME_CONSTRAINT_CREATED = "NEW_NONAME_CONSTRAINT_CREATED"; + String NEW_CONSTRAINT_CREATED = "NEW_CONSTRAINT_CREATED"; + String ERR_WHILE_ADDING_CONSTRAINT = "ERR_WHILE_ADDING_CONSTRAINT"; + String UNABLE_TO_ADD_CONS = "UNABLE_TO_ADD_CONS"; + + String PLS_ENTER_TABLE_FOR_CONS = "PLS_ENTER_TABLE_FOR_CONS"; + String CUURENT_DFLT_VAL = "CUURENT_DFLT_VAL"; + String CUURENT_DFLT_VALUE = "CUURENT_DFLT_VALUE"; + String ADD_NEW_COLUMN = "ADD_NEW_COLUMN"; + String ADD_MSG = "ADD_MSG"; + String EDIT_MSG = "EDIT_MSG"; + String DELETE_MSG = "DELETE_MSG"; + String UP_MSG = "UP_MSG"; + String DOWN_MSG = "DOWN_MSG"; + String UPDATE_MSG = "UPDATE_MSG"; + String CANCEL_MSG = "CANCEL_MSG"; + + String SET_COL_VAL_OF_DEFAULT_TYPE = "SET_COL_VAL_OF_DEFAULT_TYPE"; + + String UNABLE_TO_SET_COL_VAL = "UNABLE_TO_SET_COL_VAL"; + String ERR_WHILE_STNG_COL_VAL = "ERR_WHILE_STNG_COL_VAL"; + + String DATA_TYPE_CONVERSION_TIP = "DATA_TYPE_CONVERSION_TIP"; + String UPDATE_DATA_TYPE = "UPDATE_DATA_TYPE"; + String TYPE_DES = "TYPE_DES"; + String CURRENT_DATA_TYPE = "CURRENT_DATA_TYPE"; + String CHANGE_DATA_TYPE_FOR_COL = "CHANGE_DATA_TYPE_FOR_COL"; + String ERR_CHANGE_DTYPE = "ERR_CHANGE_DTYPE"; + String UNABLE_TO_CHANGE_DTYPE_OF = "UNABLE_TO_CHANGE_DTYPE_OF"; + + String DTYPE_SCHEMA = "DTYPE_SCHEMA"; + + String EXEC_DEBUG_DIALOG_OUT_PARA_MSG = "EXEC_DEBUG_DIALOG_OUT_PARA_MSG"; + String EXECUTION_PLAN_DISPLAY = "EXECUTION_PLAN_DISPLAY"; + String GENERAL_MSG = "GENERAL_MSG"; + String COLUMN_MSG = "COLUMN_MSG"; + String DATA_DIST = "DATA_DIST"; + String INDEX_MSG = "INDEX_MSG"; + String IMPORT_CONNECTIONS_PROFILE_INVALID_FORMAT_EXCEPTION = "IMPORT_CONNECTIONS_PROFILE_INVALID_FORMAT_EXCEPTION"; + String IMPORT_TABLE_FILE_INVALID_DATA_LIMIT = "IMPORT_TABLE_FILE_INVALID_DATA_LIMIT"; + String CREATE_CLM_COMMENT = "CREATE_CLM_COMMENT"; + String COMPRESS_FAILED = "COMPRESS_FAILED"; + String FILTER_INTIAL_TEXT = "FILTER_INTIAL_TEXT"; + String FILTER_CLEAR_TOOLTIP = "FILTER_CLEAR_TOOLTIP"; + + String LOCALE_CHANGE_APP_RESTART_NOTE = "LOCALE_CHANGE_APP_RESTART_NOTE"; + String ERR_INVALID_CONNECTION_NAME = "ERR_INVALID_CONNECTION_NAME"; + String MSG_HINT_GUI_CONNECTION_OPEN_SOCKET_FAIL = "MSG_HINT_GUI_CONNECTION_OPEN_SOCKET_FAIL"; + String ERR_TEMPLATE_LOAD_FAILURE_TITLE = "ERR_TEMPLATE_LOAD_FAILURE_TITLE"; + String PREF_LOAD_ERROR_TITLE = "PREF_LOAD_ERROR_TITLE"; + String ERR_PREFERENCE_LOAD_FAILURE_DETAIL = "ERR_PREFERENCE_LOAD_FAILURE_DETAIL"; + + String AUTO_REFRESH_SUCCESS_MSG = "AUTO_REFRESH_SUCCESS_MSG"; + String MAXIMUM_PREF_FILE_SIZE = "MAXIMUM_PREF_FILE_SIZE"; + String COLUMN_LAYOUT_ERROR = "COLUMN_LAYOUT_ERROR"; + String IMPORT_EXPORT_LOGIN_FAILED = "IMPORT_EXPORT_LOGIN_FAILED"; + String ERROR_POSITION_LABEL = "ERROR_POSITION_LABEL"; + + String ERROR_WHILE_FETCHING_OWNER_NAME = "ERROR_WHILE_FETCHING_OWNER_NAME"; + String ERR_WHILE_FETCHING_SEQ_VALUE = "ERR_WHILE_FETCHING_SEQ_VALUE"; +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/IMessagesConstantsTwo.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/IMessagesConstantsTwo.java new file mode 100644 index 0000000000000000000000000000000000000000..9b038f745ba4811cbb28ba9705c2eed813c477e7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/IMessagesConstantsTwo.java @@ -0,0 +1,519 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +/** + * Title: IMessagesConstantsTwo + * + * @since 3.0.0 + */ +public interface IMessagesConstantsTwo { + String EXECUTION_DYANMIC_TIME_LABEL = "EXECUTION_DYANMIC_TIME_LABEL"; + + String EXECUTION_ELAPSED_TIME_LABEL = "EXECUTION_ELAPSED_TIME_LABEL"; + + String PREF_TRANSACTION_SETTING = "PREF_TRANSACTION_SETTING"; + + String PREF_TRANSACTION_AUTOCOMMIT = "PREF_TRANSACTION_AUTOCOMMIT"; + + String AUTOCOMMIT_ENABLE = "AUTOCOMMIT_ENABLE"; + + String AUTOCOMMIT_DISABLE = "AUTOCOMMIT_DISABLE"; + + String TRANSACTION_DIALOG_TITLE = "TRANSACTION_DIALOG_TITLE"; + + String TRANSACTION_DIALOG_BODY = "TRANSACTION_DIALOG_BODY"; + + String TRANSACTION_COMMIT_FEEDBACK = "TRANSACTION_COMMIT_FEEDBACK"; + + String TRANSACTION_ROLLBACK_FEEDBACK = "TRANSACTION_ROLLBACK_FEEDBACK"; + + String TRANSACTION_OPERATION_EXCEPTION_TITLE = "TRANSACTION_OPERATION_EXCEPTION_TITLE"; + + String TRANSACTION_COMMIT_EXCEPTION_BODY = "TRANSACTION_COMMIT_EXCEPTION_BODY"; + + String TRANSACTION_ROLLBACK_EXCEPTION_BODY = "TRANSACTION_ROLLBACK_EXCEPTION_BODY"; + + String TRANSACTION_RESET_BUTTIONS_EXCEPTION = "TRANSACTION_RESET_BUTTIONS_EXCEPTION"; + + String TRANSACTION_OPERATION_TOGGLE_TITLE = "TRANSACTION_OPERATION_TOGGLE_TITLE"; + + String AUTOCOMMIT_ENABLE_DESC = "AUTOCOMMIT_ENABLE_DESC"; + + String AUTOCOMMIT_DISABLE_DESC = "AUTOCOMMIT_DISABLE_DESC"; + + String TRANSACTION_DIALOG_OK_BUTTION = "TRANSACTION_DIALOG_OK_BUTTION"; + + String TRANSACTION_COMMIT_JOB = "TRANSACTION_COMMIT_JOB"; + + String TRANSACTION_ROLLBACK_JOB = "TRANSACTION_ROLLBACK_JOB"; + + String TRANSACTION_COMMIT_TOOL_TIP = "TRANSACTION_COMMIT_TOOL_TIP"; + + String TRANSACTION_ROLLBACK_TOOL_TIP = "TRANSACTION_ROLLBACK_TOOL_TIP"; + + String TRANSACTION_COMMIT_CONFIRMATION = "TRANSACTION_COMMIT_CONFIRMATION"; + + String TRANSACTION_ROLLBACK_CONFIRMATION = "TRANSACTION_ROLLBACK_CONFIRMATION"; + + String NO_TRANSACTION_COMMIT_ROLLBACK_TOGGLE = "NO_TRANSACTION_COMMIT_ROLLBACK_TOGGLE"; + + String ERR_START_TRANSACTION_FAILED = "ERR_START_TRANSACTION_FAILED"; + + String ERR_ROLL_BACK_TRANSACTION_FAILED = "ERR_ROLL_BACK_TRANSACTION_FAILED"; + + String SHOW_SEQUENCE_DDL_CANCELING = "SHOW_SEQUENCE_DDL_CANCELING"; + + String SHOW_SEQUENCE_DDL_PROGRESS_NAME = "SHOW_SEQUENCE_DDL_PROGRESS_NAME"; + + String SHOW_SEQUENCE_DDL_FAILED = "SHOW_SEQUENCE_DDL_FAILED"; + + String BATCH_EXPORT_NO_RELATION_PREVILAGE = "BATCH_EXPORT_NO_RELATION_PREVILAGE"; + + String EXECUTE_DEBUGE = "EXECUTE_DEBUGE"; + + String WRITE_HERE = "WRITE_HERE"; + + String PARAMETER_INPUT_TABLE_PARAM_NAME_COLUMN = "PARAMETER_INPUT_TABLE_PARAM_NAME_COLUMN"; + + String PARAMETER_INPUT_TABLE_PARAM_TYPE_COLUMN = "PARAMETER_INPUT_TABLE_PARAM_TYPE_COLUMN"; + + String PARAMETER_INPUT_TABLE_PARAM_VALUE_COLUMN = "PARAMETER_INPUT_TABLE_PARAM_VALUE_COLUMN"; + + String OPERATION_CANNOT_BE_PERFOREMD_TITLE = "OPERATION_CANNOT_BE_PERFOREMD_TITLE"; + + String ERROR_IMPORTING_CONNECTION_PROFILES = "ERROR_IMPORTING_CONNECTION_PROFILES"; + + String EXPORTING_CONNECTION_PROFILES = "EXPORTING_CONNECTION_PROFILES"; + + String IMPORTING_CONNECTION_PROFILES = "IMPORTING_CONNECTION_PROFILES"; + + String EXPORT_CONNECTION_PROFILE_DIALOG_HEADER = "EXPORT_CONNECTION_PROFILE_DIALOG_HEADER"; + + String EXPORT_CONNECTION_PROFILE_DIALOG_GROUP = "EXPORT_CONNECTION_PROFILE_DIALOG_GROUP"; + + String EXPORT_CONNECTION_PROFILE_SUCCESS_MESSAGE = "EXPORT_CONNECTION_PROFILE_SUCCESS_MESSAGE"; + + String EXPORT_CONNECTION_PROFILE_LOAD_ERR_MSG = "EXPORT_CONNECTION_PROFILE_LOAD_ERR_MSG"; + + String EXPORT_CONNECTION_PROF_LOADING_STATUS_MESSAGE = "EXPORT_CONNECTION_PROF_LOADING_STATUS_MESSAGE"; + + String IMPORT_CONNECTIONS_LOADING_STATUS_MSG = "IMPORT_CONNECTIONS_LOADING_STATUS_MSG"; + + String IMPORT_CONNECTIONS_PROFILE_DIALOG_HEADER = "IMPORT_CONNECTIONS_PROFILE_DIALOG_HEADER"; + + String IMPORT_CONNECTIONS_PROFILE_ERR_MSG = "IMPORT_CONNECTIONS_PROFILE_ERR_MSG"; + + String IMPORT_CONN_PROFILE_REPLACE_LABEL = "IMPORT_CONN_PROFILE_REPLACE_LABEL"; + + String IMPORT_CONN_PROFILE_KEEP_BOTH_FILES_LBL = "IMPORT_CONN_PROFILE_KEEP_BOTH_FILES_LBL"; + + String IMPORT_CONN_PROFILE_DONT_CPY_LBL = "IMPORT_CONN_PROFILE_DONT_CPY_LBL"; + + String IMPORT_CONN_PROFILE_CONFLICTS_LBL = "IMPORT_CONN_PROFILE_CONFLICTS_LBL"; + + String IMPORT_PROFILE_INCORRECT_FILE = "IMPORT_PROFILE_INCORRECT_FILE"; + + String SHORTCUT_KEY_ALREADY_EXIST = "SHORTCUT_KEY_ALREADY_EXIST"; + + String SELECT_SHORTCUT_KEY_AGAIN = "SELECT_SHORTCUT_KEY_AGAIN"; + + String SHORTCUT_KEY_DUPLICATE = "SHORTCUT_KEY_DUPLICATE"; + + String PROCESS_TIMEOUT_ERROR = "PROCESS_TIMEOUT_ERROR"; + + String EXPORT_TIMEOUT = "EXPORT_TIMEOUT"; + + String DEFAULT_TIMEOUT = "DEFAULT_TIMEOUT"; + + String CUSTOM_TIMEOUT = "CUSTOM_TIMEOUT"; + + String SECONDS = "SECONDS"; + + String ROLLBACK_COMPLETED = "ROLLBACK_COMPLETED"; + + String RENAME_TABLESPACE_FAILED_TITLE = "RENAME_TABLESPACE_FAILED"; + + String ERR_FETCH_RESULT_SET_COLUMN_COMMENT = "ERR_FETCH_RESULT_SET_COLUMN_COMMENT"; + + // olap table excell format import + String IMPORT_RESULT_INVALID_CONNECTION = "IMPORT_RESULT_INVALID_CONNECTION"; + + String IMPORT_EXCEL_DATE = "IMPORT_EXCEL_DATE"; + + String FILE_LIMIT_WARNING_MESSAGE = "FILE_LIMIT_WARNING_MESSAGE"; + + String FILE_LIMIT = "FILE_LIMIT"; + + String FILE_LIMIT_HEADER = "FILE_LIMIT_HEADER"; + + String IMPORT_TABLE_DATA_LIMIT = "IMPORT_TABLE_DATA_LIMIT"; + + String IMPORT_FILE_DATA_LIMIT = "IMPORT_FILE_DATA_LIMIT"; + + String IMPORT_BYTEA_DATA_LIMIT = "IMPORT_BYTEA_DATA_LIMIT"; + + String SUFFIX_DATA_LIMIT = "SUFFIX_DATA_LIMIT"; + + String IMPORT_UNLIMITED_NOTE = "IMPORT_UNLIMITED_NOTE"; + + // Object Browser Lazy Rendering + String LAZY_RENDER_PREFERENCE_GROUP_NAME = "LAZY_RENDER_PREFERENCE_GROUP_NAME"; + + String LAZY_RENDER_OBJECT_COUNT_LABEL = "LAZY_RENDER_OBJECT_COUNT_LABEL"; + + String LAZY_RENDER_SUFFIX_LABEL = "LAZY_RENDER_SUFFIX_LABEL"; + + String LAZY_RENDERING_ERROR_MSG = "LAZY_RENDERING_ERROR_MSG"; + + String INVALID_EXTENSION_HEADER = "INVALID_EXTENSION_HEADER"; + + String INVALID_EXTENSION_MESSAGE = "INVALID_EXTENSION_MESSAGE"; + + String VALIDATE_CIPHER_FAIL = "VALIDATE_CIPHER_FAIL"; + + // openGauss excel format of table data import + + String ENCODING_NOTE = "ENCODING_NOTE"; + + String OPTION_ZIP = "OPTION_ZIP"; + + String COMPRESS_FAIL_DAILOG_TITLE = "COMPRESS_FAIL_DAILOG_TITLE"; + + String SQL_DDL_EXPORT_WINDOW_TITLE = "SQL_DDL_EXPORT_WINDOW_TITLE"; + + String SQL_DDL_DATA_EXPORT_WINDOW_TITLE = "SQL_DDL_DATA_EXPORT_WINDOW_TITLE"; + + String GENERATE_SQL_EXPORT_WINDOW_TITLE = "GENERATE_SQL_EXPORT_WINDOW_TITLE"; + + String INVALID_TEMP_ENVIRONMENT_VARIABLE = "INVALID_TEMP_ENVIRONMENT_VARIABLE"; + + String ERR_ZIP_EXPORT_DAILOG_TITLE = "ERR_ZIP_EXPORT_DAILOG_TITLE"; + + String ERR_ZIP_EXPORT_DAILOG_DESC = "ERR_ZIP_EXPORT_DAILOG_DESC"; + + String ENTER_COL_DESCRIPTIONS_TEXT = "ENTER_COL_DESCRIPTIONS_TEXT"; + + String ERR_REMOVE_TARGET_SESSION_FAILED = "ERR_REMOVE_TARGET_SESSION_FAILED"; + + String ERR_ATTACH_TARGET_SESSION_FAILED = "ERR_ATTACH_TARGET_SESSION_FAILED"; + + String ERR_BL_QUERY_EXEC_STATUS_FAILED = "ERR_BL_QUERY_EXEC_STATUS_FAILED"; + + String LOAD_MORE_RECORD_TOOL_ITEM = "LOAD_MORE_RECORD_TOOL_ITEM"; + + String RESULT_WINDOW = "RESULT_WINDOW"; + + String RESULT_TAB_GENERATE_NEW = "RESULT_TAB_GENERATE_NEW"; + + String RESULT_TAB_RETAIN_CURRENT = "RESULT_TAB_RETAIN_CURRENT"; + + String RESULT_TAB_GENERATE_NEW_HINT = "RESULT_TAB_GENERATE_NEW_HINT"; + + String RESULT_TAB_RETAIN_CURRENT_HINT = "RESULT_TAB_RETAIN_CURRENT_HINT"; + + String BUTTON_OVERWRITE_RESULTSET_TOOLTIP = "BUTTON_OVERWRITE_RESULTSET_TOOLTIP"; + + String PREPARED_QUERY_RELATED_TABLE_FAILED = "PREPARED_QUERY_RELATED_TABLE_FAILED"; + + String PREPARED_QUERY_RELATED_SEQUENCE_FAILED = "PREPARED_QUERY_RELATED_SEQUENCE_FAILED"; + + String ERR_WRITE_FILE = "ERR_WRITE_FILE"; + + String ERR_IMPORT_TABLE_TO_EXCEL = "ERR_IMPORT_TABLE_TO_EXCEL"; + + String AUTO_COMPLETE_SETTING = "AUTO_COMPLETE_SETTING"; + + String AUTO_COMPLETE_MIN_SIZE = "AUTO_COMPLETE_MIN_SIZE"; + + String AUTO_COMPLETE_MIN_SIZE_DESC = "AUTO_COMPLETE_MIN_SIZE_DESC"; + + String AUTO_SUGGEST_ERROR_MSG = "AUTO_SUGGEST_ERROR_MSG"; + + String MPPDBIDE_DIA_BTN_DISCARD_All = "MPPDBIDE_DIA_BTN_DISCARD_ALL"; + + String PREF_FOLDING_SETTING = "PREF_FOLDING_SETTING"; + + String PREF_FOLDING_ENABLE_DESC = "PREF_FOLDING_ENABLE_DESC"; + + String PREF_FOLDING_DISABLE_DESC = "PREF_FOLDING_DISABLE_DESC"; + + String PREF_FOLDING_DESC = "PREF_FOLDING_DESC"; + + String PREF_FONT_SETTING = "PREF_FONT_SETTING"; + + String PREF_FONT_STYLE = "PREF_FONT_STYLE"; + + String PREF_FONT_STYLE_SIZE = "PREF_FONT_STYLE_SIZE"; + + String PREF_FONT_STYLE_SIZE_EXPLANATION = "PREF_FONT_STYLE_SIZE_EXPLANATION"; + + String DESCRIBE_IMPACT_OF_COLUMN_SEQUENCE = "DESCRIBE_IMPACT_OF_COLUMN_SEQUENCE"; + + String ERR_DELETE_FILE_MSG = "ERR_DELETE_FILE_MSG"; + + String ERR_IMPORT_DATE_FORMAT = "ERR_IMPORT_DATE_FORMAT"; + + String ERR_IMPORT_DATA_FILE = "ERR_IMPORT_DATA_FILE"; + + String ERR_IMPORT_DIFF_FILE_FORMAT = "ERR_IMPORT_DIFF_FILE_FORMAT"; + + String LOCALE_CHANGE_APP_EXIT_MSG = "LOCALE_CHANGE_APP_EXIT_MSG"; + + String LOCAL_CHANGE_EXIT_NOTE_YES = "LOCAL_CHANGE_EXIT_NOTE_YES"; + + String LOCALE_CHANGE_APP_RESTART_NOTE_NO = "LOCALE_CHANGE_APP_RESTART_NOTE_NO"; + + String LOADING_DATA = "LOADING_DATA"; + + String LOADED_DATA = "LOADED_DATA"; + + String FILE_SIZE_EXCEEDED_FOUR = "FILE_SIZE_EXCEEDED_FOUR"; + + // for ER --start + String ER_JOB_DETAILS = "ER_JOB_DETAILS"; + + String ER_ERROR_POPUP_HEADER = "ER_ERROR_POPUP_HEADER"; + + String ER_DESC_PRIMARYKEY = "ER_DESC_PRIMARYKEY"; + + String ER_DESC_FOREIGNKEY = "ER_DESC_FOREIGNKEY"; + + String ER_DESC_CURRENT_COLOR = "ER_DESC_CURRENT_COLOR"; + + String ER_DESC_RELATED_COLOR = "ER_DESC_RELATED_COLOR"; + + String ER_VIEW_FAILED = "ER_VIEW_FAILED"; + + String ER_VIEW_FAILED_MSG = "ER_VIEW_FAILED_MSG"; + + String ER_VIEW_INSUFFICIENT_PRIVILEGES_MSG = "ER_VIEW_INSUFFICIENT_PRIVILEGES_MSG"; + + String VIEW_STYLES = "VIEW_STYLES"; + + String SHOW_ICONS = "SHOW_ICONS"; + + String SHOW_DATA_TYPES = "SHOW_DATA_TYPES"; + + String SHOW_NULLABILITY = "SHOW_NULLABILITY"; + + String SHOW_COMMENTS = "SHOW_COMMENTS"; + + String SHOW_FULLY_QUALIFIED_NAMES = "SHOW_FULLY_QUALIFIED_NAMES"; + + String SHOW_ATTRIBUTES = "SHOW_ATTRIBUTES"; + + String ATTRIBUTE_VIS_ALL = "ATTRIBUTE_VIS_ALL"; + + String ATTRIBUTE_VIS_ANY_KEY = "ATTRIBUTE_VIS_ANY_KEY"; + + String ATTRIBUTE_VIS_PRIMARY_KEY = "ATTRIBUTE_VIS_PRIMARY_KEY"; + + String ATTRIBUTE_VIS_NONE = "ATTRIBUTE_VIS_NONE"; + + // for ER --end + + // SYNONYMS Start + String SYNONYM_GROUP_NAME = "SYNONYM_GROUP_NAME"; + + String TRIGGER_GROUP_NAME = "TRIGGER_GROUP_NAME"; + + String CREATE_NEW_SYNONYM = "CREATE_NEW_SYNONYM"; + + String SYNONYM_NAME = "SYNONYM_NAME"; + + String OBJECT_OWNER = "OBJECT_OWNER"; + + String OBJECT_TYPE = "OBJECT_TYPE"; + + String OBJECT_NAME = "OBJECT_NAME"; + + String REPLACE_IF_EXIST = "REPLACE_IF_EXIST"; + + String SYNONYM_NAME_ENTER_NM = "SYNONYM_NAME_ENTER_NM"; + + String SYNONYM_NAME_EXCEED_MAX = "SYNONYM_NAME_EXCEED_MAX"; + + String OBJECT_OWNER_SELECT_NM = "OBJECT_OWNER_SELECT_NM"; + + String OBJECT_TYPE_SELECT_NM = "OBJECT_TYPE_SELECT_NM"; + + String OBJECT_NAME_SELECT_NM = "OBJECT_NAME_SELECT_NM"; + + String CREATED_SYNONYM_SUCESS = "CREATED_SYNONYM_SUCESS"; + + String CREATE_SYNONYM_NO_DATABASE = "CREATE_SYNONYM_NO_DATABASE"; + + String CREATE_SYNONYM_ERROR = "CREATE_SYNONYM_ERROR"; + + String DROP_SYNONYM_CONFIRM_MSG = "DROP_SYNONYM_CONFIRM_MSG"; + + String DROP_SYNONYM_TITLE = "DROP_SYNONYM_TITLE"; + + String STATUS_MSG_DROP_SYNONYM = "STATUS_MSG_DROP_SYNONYM"; + + String DROP_SYNONYM_PROGRESS_NAME = "DROP_SYNONYM_PROGRESS_NAME"; + + String DROP_SYNONYM_SUCCESS = "DROP_SYNONYM_SUCCESS"; + + String DROP_SYNONYM_ERROR = "DROP_SYNONYM_ERROR"; + + String DROP_SYNONYM_UNABLE = "DROP_SYNONYM_UNABLE"; + + String PROPERTIES_SYNONYM_NAME = "PROPERTIES_SYNONYM_NAME"; + + String PROPERTIES_SYNONYM_OWNER = "PROPERTIES_SYNONYM_OWNER"; + + String PROPERTIES_OBJECT_OWNER = "PROPERTIES_OBJECT_OWNER"; + + String PROPERTIES_OBJECT_NAME = "PROPERTIES_OBJECT_NAME"; + + // SYNONYMS End + + // DS Commandline parameter support start + String DS_COMMANDLINE_ERROR = "DS_COMMANDLINE_ERROR"; + + String DS_COMMANDLINE_MANDATORY_PARAM_MISSING = "DS_COMMANDLINE_MANDATORY_PARAM_MISSING"; + + String DS_COMMANDLINE_SSL_MODE_NOT_SUPPORTED = "DS_COMMANDLINE_SSL_MODE_NOT_SUPPORTED"; + + String DS_COMMANDLINE_UNIDENTIFIED_PARAM = "DS_COMMANDLINE_UNIDENTIFIED_PARAM"; + + String DS_COMMANDLINE_DB_TYPE_PARAM_MISSING = "DS_COMMANDLINE_DB_TYPE_PARAM_MISSING"; + + String DS_COMMANDLINE_INVALID_CONNECTION_NAME_VALUE = "DS_COMMANDLINE_INVALID_CONNECTION_NAME_VALUE"; + + String DS_COMMANDLINE_INVALID_VALUE_LENGTH = "DS_COMMANDLINE_INVALID_VALUE_LENGTH"; + + String DS_COMMANDLINE_NULL_VALUE_FOR_PARAM = "DS_COMMANDLINE_NULL_VALUE_FOR_PARAM"; + + String DS_COMMANDLINE_INVALID_FILE_PATH = "DS_COMMANDLINE_INVALID_FILE_PATH"; + + String DS_COMMANDLINE_INVALID_HOST_PORT_VALUE = "DS_COMMANDLINE_INVALID_HOST_PORT_VALUE"; + + String DS_COMMANDLINE_INVALID_SAVE_CIPHER_VALUE = "DS_COMMANDLINE_INVALID_SAVE_CIPHER_VALUE"; + + String DS_COMMANDLINE_INVALID_SSL_ENABLE_VALUE = "DS_COMMANDLINE_INVALID_SSL_ENABLE_VALUE"; + + String DS_COMMANDLINE_INVALID_SSL_MODE_VALUE = "DS_COMMANDLINE_INVALID_SSL_MODE_VALUE"; + + String DS_COMMANDLINE_ATTEMPTING_CONNECTION_MSG = "DS_COMMANDLINE_ATTEMPTING_CONNECTION_MSG"; + + String DS_COMMANDLINE_ENTER_CIPHER = "DS_COMMANDLINE_ENTER_CIPHER"; + + String DS_COMMANDLINE_PRESS_ENTER_FOLLOWED_BY_CIPHER = "DS_COMMANDLINE_PRESS_ENTER_FOLLOWED_BY_CIPHER"; + + // DS Commandline parameter support end + + // Formatter preference start + String FORMATTER_PREVIEW = "FORMATTER_PREVIEW"; + + String FORMATTER_RIGHT_MARGIN = "FORMATTER_RIGHT_MARGIN"; + + String FORMATTER_INDENT = "FORMATTER_INDENT"; + + String FORMATTER_USE_TAB_CHAR = "FORMATTER_USE_TAB_CHAR"; + + String FORMATTER_TABS = "FORMATTER_TABS"; + + String FORMATTER_SPACES = "FORMATTER_SPACES"; + + String FORMATTER_TAB_CHAR_SIZE = "FORMATTER_TAB_CHAR_SIZE"; + + String FORMATTER_ALIGN_DECLARATION = "FORMATTER_ALIGN_DECLARATION"; + + String FORMATTER_ALIGN_ASSIGNMENTS = "FORMATTER_ALIGN_ASSIGNMENTS"; + + String FORMATTER_THEN_ON_NEW_LINE = "FORMATTER_THEN_ON_NEW_LINE"; + + String FORMATTER_LOOP_ON_NEW_LINE = "FORMATTER_LOOP_ON_NEW_LINE"; + + String FORMATTER_SPLIT_AND_OR = "FORMATTER_SPLIT_AND_OR"; + + String FORMATTER_AND_OR_AFTER_EXP = "FORMATTER_AND_OR_AFTER_EXP"; + + String FORMATTER_AND_OR_UNDER = "FORMATTER_AND_OR_UNDER"; + + String FORMATTER_DML = "FORMATTER_DML"; + + String FORMATTER_GENERAL = "FORMATTER_GENERAL"; + + String FORMATTER_SELECT = "FORMATTER_SELECT"; + + String FORMATTER_INSERT = "FORMATTER_INSERT"; + + String FORMATTER_UPDATE = "FORMATTER_UPDATE"; + + String FORMATTER_OTHERS = "FORMATTER_OTHERS"; + + String FORMATTER_LEFT_ALIGN_KEYWORDS = "FORMATTER_LEFT_ALIGN_KEYWORDS"; + + String FORMATTER_LEFT_ALIGN_ITEMS = "FORMATTER_LEFT_ALIGN_ITEMS"; + + String FORMATTER_FORMAT = "FORMATTER_FORMAT"; + + String FORMATTER_ON_ONE_LINE = "FORMATTER_ON_ONE_LINE"; + + String FORMATTER_ONE_PARAM_PER_LINE = "FORMATTER_ONE_PARAM_PER_LINE"; + + String FORMATTER_FIT = "FORMATTER_FIT"; + + String FORMATTER_ALIGN = "FORMATTER_ALIGN"; + + String FORMATTER_COMMA_AFTER_ITEM = "FORMATTER_COMMA_AFTER_ITEM"; + + String FORMATTER_PARAMATER = "FORMATTER_PARAMATER"; + + String FORMATTER_ALIGN_DATATYPES = "FORMATTER_ALIGN_DATATYPES"; + + String FORMATTER_COMMA_AFTER_DATATYPE = "FORMATTER_COMMA_AFTER_DATATYPE"; + + String FORMATTER_LIST_AT_LEFT_MARGIN = "FORMATTER_LIST_AT_LEFT_MARGIN"; + + String FORMATTER_IMPORT = "FORMATTER_IMPORT"; + + String FORMATTER_EXPORT = "FORMATTER_EXPORT"; + + String FORMATTER_INVALID_FILE_SELECTED = "FORMATTER_INVALID_FILE_SELECTED"; + + String FORMATTER_SELECT_VALID_JSON = "FORMATTER_SELECT_VALID_JSON"; + + String FORMATTER_FILE_CREATION_ERROR_HEADER = "FORMATTER_FILE_CREATION_ERROR_HEADER"; + + String FORMATTER_FILE_READ_ERROR_HEADER = "FORMATTER_FILE_READ_ERROR_HEADER"; + + String FORMATTER_FILE_CREATION_ERROR = "FORMATTER_FILE_CREATION_ERROR"; + + String FORMATTER_FILE_READ_ERROR = "FORMATTER_FILE_READ_ERROR"; + + String FORMATTER_ERROR_RESIDE_IN_FILE = "FORMATTER_ERROR_RESIDE_IN_FILE"; + + // Formatter preference end + + String FORMATTER_UNABLE_TO_PARSE_STMT = "FORMATTER_UNABLE_TO_PARSE_STMT"; + + String OBJECT_BROWSER = "OBJECT_BROWSER"; + String OBJECT_BROWSER_FILTER_TIMEOUT = "OBJECT_BROWSER_FILTER_TIMEOUT"; + String OBJECT_BROWSER_FILTER_TIMEOUT_INFO = "OBJECT_BROWSER_FILTER_TIMEOUT_INFO"; + String OBJECT_BROWSER_FILTER_TIMEOUT_ERR_MSG = "OBJECT_BROWSER_FILTER_TIMEOUT_ERR_MSG"; + String OBJECT_BROWSER_FILTER_TIMEOUT_ERROR = "OBJECT_BROWSER_FILTER_TIMEOUT_ERROR"; + String OBJECT_BROWSER_FILTER_TIMEOUT_ERROR_TITLE = "OBJECT_BROWSER_FILTER_TIMEOUT_ERROR_TITLE"; + String OBJECT_BROWSER_FILTER_FINISH_MSG = "OBJECT_BROWSER_FILTER_FINISH_MSG"; + String OBJECT_BROWSER_FILTER_TIMEOUT_TOOLTIP_MESSAGE = "OBJECT_BROWSER_FILTER_TIMEOUT_TOOLTIP_MESSAGE"; + + String LABEL_LOAD_CHILD_OBJECT = "LABEL_LOAD_CHILD_OBJECT"; + String FILE_SIZE_EXCEED_WARNING_MSG = "FILE_SIZE_EXCEED_WARNING_MSG"; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/IQuerrySplitter.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/IQuerrySplitter.java new file mode 100644 index 0000000000000000000000000000000000000000..a593fcf6541e47801518a4051da48a4781865e31 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/IQuerrySplitter.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +import java.util.ArrayList; + +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: interface + * + * Description: The Interface IQuerrySplitter. + * + * @since 3.0.0 + */ +public interface IQuerrySplitter { + + /** + * + * splitQuerries. + * + * @param queryArray the query array + * @param query the query + * @param isOLAP the is OLAP + * @throws DatabaseOperationException the database operation exception + */ + void splitQuerries(ArrayList queryArray, String query, boolean isOLAP) throws DatabaseOperationException; + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/JSQLParserUtils.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/JSQLParserUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..9692e845f077d6ddb14ac0c77da0d1fdd4ceaff7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/JSQLParserUtils.java @@ -0,0 +1,566 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +import java.io.StringReader; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.regex.Pattern; + +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +import net.sf.jsqlparser.JSQLParserException; +import net.sf.jsqlparser.expression.Expression; +import net.sf.jsqlparser.parser.CCJSqlParserManager; +import net.sf.jsqlparser.schema.Table; +import net.sf.jsqlparser.statement.Statement; +import net.sf.jsqlparser.statement.alter.Alter; +import net.sf.jsqlparser.statement.create.table.CreateTable; +import net.sf.jsqlparser.statement.create.view.CreateView; +import net.sf.jsqlparser.statement.drop.Drop; +import net.sf.jsqlparser.statement.select.AllColumns; +import net.sf.jsqlparser.statement.select.AllTableColumns; +import net.sf.jsqlparser.statement.select.GroupByElement; +import net.sf.jsqlparser.statement.select.PlainSelect; +import net.sf.jsqlparser.statement.select.Select; +import net.sf.jsqlparser.statement.select.SelectBody; +import net.sf.jsqlparser.statement.select.SelectExpressionItem; +import net.sf.jsqlparser.statement.select.SelectItem; +import net.sf.jsqlparser.statement.select.SetOperationList; +import net.sf.jsqlparser.statement.select.WithItem; + +/** + * + * Title: class + * + * Description: The Class JSQLParserUtils. + * + * @since 3.0.0 + */ +public class JSQLParserUtils { + /* + * Rules For Disabling Editing of Query Results + * + */ + + /** + * Checks if is query result edit supported. + * + * @param query the query + * @return true, if is query result edit supported + * @throws DatabaseCriticalException the database critical exception + */ + public static boolean isQueryResultEditSupported(String query) throws DatabaseCriticalException { + CCJSqlParserManager parserManager = new CCJSqlParserManager(); + Select selectStatement = null; + SelectVisitorWrap selVisitor = new SelectVisitorWrap(); + try { + Statement stmt = parserManager.parse(new StringReader(query)); + if (!(stmt instanceof Select)) { + return false; + } + selectStatement = (Select) stmt; + + PlainSelect ps = null; + if (selectStatement.getSelectBody() instanceof PlainSelect) { + ps = (PlainSelect) selectStatement.getSelectBody(); + } + selectStatement.getSelectBody().accept(selVisitor); + + if (!selVisitor.hasSetOperations() && !isMoreThanOneTableinFrom(ps) && !isGroupByExists(ps)) { + if (!isWithItemExists(selectStatement) && isAllowedSelectItems(ps) && !isHavingExists(ps) + && !isIntoExists(ps)) { + return true; + } + } + } catch (OutOfMemoryError error) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_OUT_OF_MEMORY_OCCURED), + error); + throw new DatabaseCriticalException(IMessagesConstants.ERR_OUT_OF_MEMORY_OCCURED, error); + + } catch (JSQLParserException e1) { + return false; + } catch (Exception e2) { + // Jsql Parser can throw Null pointer exception for unsupported + // syntax such as OVER in select statement,We are handling such + // exception here. + return false; + } catch (Error e3) { + return false; + } + + return false; + } + + /** + * Checks if is copy query. + * + * @param query the query + * @return true if fixed + * @description Is Copy Query + */ + public static boolean isCopyQuery(String query) { + CCJSqlParserManager parserManager = new CCJSqlParserManager(); + Select selectStatement = null; + try { + Statement stmt = parserManager.parse(new StringReader(query)); + if (!(stmt instanceof Select)) { + return false; + } + selectStatement = (Select) stmt; + + PlainSelect ps = null; + if (selectStatement.getSelectBody() instanceof PlainSelect) { + ps = (PlainSelect) selectStatement.getSelectBody(); + } + if (isIntoExists(ps)) { + return true; + } + } catch (JSQLParserException e1) { + return false; + } catch (Exception e2) { + return false; + } + return false; + } + + /** + * Checks if is with item exists. + * + * @param selectStatement the select statement + * @return true, if is with item exists + */ + private static boolean isWithItemExists(Select selectStatement) { + if (selectStatement == null) { + return false; + } + List withItemList = selectStatement.getWithItemsList(); + if (withItemList != null) { + return true; + } else { + return false; + } + } + + /** + * Checks if is more than one tablein from. + * + * @param ps the ps + * @return true, if is more than one tablein from + */ + private static boolean isMoreThanOneTableinFrom(PlainSelect ps) { + if (ps == null) { + return false; + } + TablesNamesFinderAdapter tablesNamesFinder = new TablesNamesFinderAdapter(); + int tableCount = tablesNamesFinder.getTableList(ps).size(); + if ((tableCount != 1) || tablesNamesFinder.isSelectFromFunction() || tablesNamesFinder.isJoinExists()) { + return true; + } else { + return false; + } + } + + /** + * Gets the qualified table name.Get NamespaceName.TableName from query + * + * @param query the query + * @return the qualified table name + */ + public static String getQualifiedTableName(String query) { + CCJSqlParserManager parserManager = new CCJSqlParserManager(); + Select selectStatement = null; + PlainSelect ps = null; + try { + Statement stmt = parserManager.parse(new StringReader(query)); + if (stmt instanceof Select) { + selectStatement = (Select) stmt; + } + + if (selectStatement == null) { + return ""; + } + + if (selectStatement.getSelectBody() instanceof PlainSelect) { + ps = (PlainSelect) selectStatement.getSelectBody(); + } + + if (ps == null) { + return ""; + } + } catch (JSQLParserException e1) { + return ""; + } catch (Exception e2) { + return ""; + } catch (Error e3) { + return ""; + } + + TablesNamesFinderAdapter tablesNamesFinder = new TablesNamesFinderAdapter(); + List tableList = tablesNamesFinder.getTableList(ps); + if (tableList.size() == 1) { + return tableList.get(0); + } + return ""; + } + + /** + * Gets the select query main table name. + * + * @param query the query + * @return the select query main table name + */ + public static String getSelectQueryMainTableName(String query) { + CCJSqlParserManager parserManager = new CCJSqlParserManager(); + Select selectStatement = null; + PlainSelect ps = null; + SetOperationList operationList = null; + try { + Statement stmt = parserManager.parse(new StringReader(query)); + if (stmt instanceof Select) { + selectStatement = (Select) stmt; + } + + if (selectStatement == null) { + return ""; + } + + if (selectStatement.getSelectBody() instanceof PlainSelect) { + ps = (PlainSelect) selectStatement.getSelectBody(); + } else if (selectStatement.getSelectBody() instanceof SetOperationList) { + operationList = (SetOperationList) selectStatement.getSelectBody(); + if (null != operationList.getSelects() && operationList.getSelects().size() > 0) { + List plainSelectsList = operationList.getSelects(); + if (!plainSelectsList.isEmpty()) { + ps = (PlainSelect) plainSelectsList.get(0); + } + } + } + + if (ps == null) { + return ""; + } + } catch (JSQLParserException e11) { + return ""; + } catch (Exception e22) { + return ""; + } catch (Error e33) { + return ""; + } + + TablesNamesFinderAdapter tablesNameFinder = new TablesNamesFinderAdapter(); + List tableList = tablesNameFinder.getTableList(ps); + if (tableList.size() >= 1) { + return tableList.get(0); + } + return ""; + } + + /** + * Gets the split qualified name. + * + * @param name the name + * @param isStripQuote the is strip quote + * @return the split qualified name + */ + public static String[] getSplitQualifiedName(String name, boolean isStripQuote) { + if (name == null) { + return new String[0]; + } + List strList = new ArrayList(1); + int size; + if (name.contains("\"")) { + if (!name.contains(".")) { + strList.add(name); + } else { + String[] splitStr = name.split("\\."); + int[] dQuoteCntr = populateDQuoteCntr(splitStr); + int index = getCorrectSplitPoint(dQuoteCntr); + + if (index != -1) { + StringBuilder str = new StringBuilder(splitStr[0]); + for (int jindex = 1; jindex < index; jindex++) { + str.append('.').append(splitStr[jindex]); + } + + strList.add(str.toString()); + str = new StringBuilder(splitStr[index]); + for (int cnt = index + 1; cnt < splitStr.length; cnt++) { + str.append('.').append(splitStr[cnt]); + } + + strList.add(str.toString()); + } else { + strList.add(name); + } + } + + if (isStripQuote) { + size = strList.size(); + for (int indx = 0; indx < size; indx++) { + String str1 = strList.get(indx); + if (str1.startsWith("\"") && str1.endsWith("\"")) { + str1 = str1.substring(1, str1.length() - 1); + strList.remove(indx); + strList.add(indx, str1); + } + } + } + + return strList.toArray(new String[strList.size()]); + } else if (name.contains(".")) { + return name.split("\\."); + } else { + return new String[] {name}; + } + } + + /** + * Populate D quote cntr. + * + * @param splitStr the split str + * @return the int[] + */ + private static int[] populateDQuoteCntr(String[] splitStr) { + int[] cntr = new int[splitStr.length]; + for (int cnt = 0; cnt < splitStr.length; cnt++) { + cntr[cnt] = 0; + int len = splitStr[cnt].length(); + for (int jindex = 0; jindex < len; jindex++) { + if (splitStr[cnt].charAt(jindex) == '"') { + cntr[cnt]++; + } + } + } + return cntr; + } + + /** + * Gets the correct split point. + * + * @param dQuoteCntr the d quote cntr + * @return the correct split point + */ + private static int getCorrectSplitPoint(int[] dQuoteCntr) { + int leftDQuoteCnt = dQuoteCntr[0]; + int rightDQuoteCnt = 0; + for (int cnt = 1; cnt < dQuoteCntr.length; cnt++) { + rightDQuoteCnt += dQuoteCntr[cnt]; + } + + if (leftDQuoteCnt % 2 == 0 && rightDQuoteCnt % 2 == 0) { + return 1; + } + + for (int index = 1; index < dQuoteCntr.length - 1; index++) { + leftDQuoteCnt += dQuoteCntr[index]; + rightDQuoteCnt -= dQuoteCntr[index]; + if (leftDQuoteCnt % 2 == 0 && rightDQuoteCnt % 2 == 0) { + return index + 1; + } + } + + return -1; + } + + /** + * Checks if is group by exists. + * + * @param ps the ps + * @return true, if is group by exists + */ + private static boolean isGroupByExists(PlainSelect ps) { + if (ps == null) { + return false; + } + GroupByElement groupBy = ps.getGroupBy(); + if (groupBy == null) { + return false; + } else { + return true; + } + } + + /** + * Checks if is allowed select items. + * + * @param ps the ps + * @return true, if is allowed select items + */ + private static boolean isAllowedSelectItems(PlainSelect ps) { + if (ps == null) { + return false; + } + ExpressionVisitorAdapterWrap expVisitor = new ExpressionVisitorAdapterWrap(); + List sel = ps.getSelectItems(); + if (sel != null) { + for (int index = 0; index < sel.size(); index++) { + if (sel.get(index) instanceof AllColumns || sel.get(index) instanceof AllTableColumns) { + continue; + } + + SelectExpressionItem selExpItem = (SelectExpressionItem) sel.get(index); + /* For Aliases */ + if (selExpItem.getAlias() != null) { + return false; + } else { + selExpItem.getExpression().accept(expVisitor); + if (expVisitor.hasNonEditableSelectItem()) { + return false; + } + } + } + } else { + return false; + } + + return true; + } + + /** + * Checks if is having exists. + * + * @param ps the ps + * @return true, if is having exists + */ + private static boolean isHavingExists(PlainSelect ps) { + if (ps == null) { + return false; + } + Expression having = ps.getHaving(); + if (having == null) { + return false; + } else { + return true; + } + } + + private static boolean isIntoExists(PlainSelect ps) { + if (ps == null) { + return false; + } + List into = ps.getIntoTables(); + if (into == null) { + return false; + } else { + return true; + } + } + + /** + * Gets the qualified tbl R view name. + * + * @param query the query + * @return the qualified tbl R view name + */ + public static String getQualifiedTblRViewName(String query) { + CCJSqlParserManager parserManager = new CCJSqlParserManager(); + Alter alterStatement = null; + CreateTable createTable = null; + CreateView createView = null; + Drop drop = null; + Table tableType = null; + StringReader reader = new StringReader(query); + try { + Statement stmt = parserManager.parse(reader); + if (stmt instanceof Alter) { + alterStatement = (Alter) stmt; + tableType = (Table) alterStatement.getTable(); + } else if (stmt instanceof CreateView) { + createView = (CreateView) stmt; + tableType = (Table) createView.getView(); + } else if (stmt instanceof Drop) { + drop = (Drop) stmt; + tableType = (Table) drop.getName(); + } + if (tableType == null) { + return ""; + } + } catch (JSQLParserException e11) { + if (isCreateTrigger(query.toLowerCase(Locale.ENGLISH))) { + return getTriggerName(query); + } + return ""; + } catch (Exception e22) { + return ""; + } catch (Error e33) { + return ""; + } finally { + reader.close(); + } + TablesNamesFinderAdapter tablesNameFinder = new TablesNamesFinderAdapter(); + List tableList = tablesNameFinder.getTableList(tableType); + if (tableList.size() >= 1) { + return tableList.get(0); + } + return ""; + } + + /** + * Sets the object type. + * + * @param query the query + * @return the string + */ + public static String setObjectType(String query) { + CCJSqlParserManager parserManager = new CCJSqlParserManager(); + String objType = null; + StringReader reader = new StringReader(query); + try { + Statement stmt = parserManager.parse(reader); + + if (stmt instanceof Alter) { + objType = MPPDBIDEConstants.ALTER_TABLE; + } else if (stmt instanceof CreateView) { + objType = MPPDBIDEConstants.CREATE_VIEW; + } else if (stmt instanceof Drop) { + if ("view".equalsIgnoreCase(((Drop) stmt).getType())) { + objType = MPPDBIDEConstants.DROP_VIEW; + } else if ("table".equalsIgnoreCase(((Drop) stmt).getType())) { + objType = MPPDBIDEConstants.DROP_TABLE; + } + } + + } catch (JSQLParserException e11) { + if (isCreateTrigger(query.toLowerCase(Locale.ENGLISH))) { + return MPPDBIDEConstants.CREATE_TRIGGER; + } + return ""; + } catch (Exception e22) { + return ""; + } catch (Error e33) { + return ""; + } finally { + reader.close(); + } + return objType; + } + + private static boolean isCreateTrigger(String query) { + String lowerQuery = query.toLowerCase(Locale.ENGLISH).trim(); + String pattern = "create\\s+trigger\\s+"; + Pattern p1 = Pattern.compile(pattern, Pattern.MULTILINE); + return p1.matcher(lowerQuery).find(); + } + + private static String getTriggerName(String query) { + String queryTmp = query.replace("\r", " ").replace("\n", " ").trim(); + return queryTmp.split("\\ +")[2]; + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/MPPDBIDEConstants.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/MPPDBIDEConstants.java new file mode 100644 index 0000000000000000000000000000000000000000..f4d8566b89e4510e16a163988f6d52bc4e9b19c6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/MPPDBIDEConstants.java @@ -0,0 +1,490 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +import java.text.Normalizer; + +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * Title: interface Description: The Interface MPPDBIDEConstants. + * + * @since 3.0.0 + */ +public interface MPPDBIDEConstants { + String JSON_PLAN_DUMP_FILE = "Execution_plan_JSON.txt"; + + int VARIABLE_ARRAY_SIZE = 10; + + int OBJECT_ARRAY_SIZE = 10; + + int RECORD_ARRAY_SIZE = 10; + + int SHOWTOOLTIPAFTER = 100; + + int SHOWTOOLTIPFOR = 5000; + + int FUNC_PROC_COLUMN_COUNT = 4; + + int STR_EXPLAIN_PLAN_SIZE = 6; + + int STR_EXPLAIN_PLAN_ANALYZE_SIZE = 10; + + int LINE_NUMBER_OFFSET = 1; + + String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS z"; + + String DATE_COLLAPSE_FORMAT = "yyyyMMddHHmmssSSS"; + + String CONNECTION_NAME = "New Database Connection"; + + String GMDB = "GMDB"; + + String GAUSS = "GAUSS"; + + String LINE_SEPARATOR = System.lineSeparator(); + + int FIXED_EXECUTOR_THREAD_POOL_COUNT = 1; + + int FIXED_DEBUG_THREAD_POOL_COUNT = 2; + + /** + * The Constant ZER0. + */ + int ZER0 = 0; + + String GUI = "GUI"; + + String BL = "BL"; + + String ADAPTER = "ADAPTER"; + + String UNKNOWN_DATATYPE_STR = ""; + + String DRIVER_NAME = "org.postgresql.Driver"; + + String SWTBOT_KEY = "org.eclipse.swtbot.widget.key"; + + String EXECUTE_PLAN_COST = "EXPLAIN "; + + // AR.Tools.IDE.030.006 + String EXECUTION_PLAN = MessageConfigLoader.getProperty(IMessagesConstants.EXECUTION_PLAN_DISPLAY); + + // AR.Tools.IDE.030.006 + int PRIME_31 = 31; + + String CHINESE_LOCALE = "zh_CN"; + + String CANCELABLEJOB = "DataSdutioCancelable Job"; + + String PLSOURCEVIEWERJOB = "PLSource viewer Job"; + + String ALTER_VIEW_COLUMN_PROPERTIES = "Alter View column property Job"; + + String PROFILE_BASE_PATH = "Profile"; + + String HISTORY_BASE_PATH = "History"; + + String TEMP_FOLDER_PATH = "Temp"; + + String CONNECTION_PROFILE_NAME = "connection.properties"; + + String CONNECTION_PROFILE_META_FILE = "Profiles.txt"; + + String PUBLIC_SCHEMA_NAME = "public"; + + String SPACE_CHAR = " "; + + String SINGLE_QUOTE = "'"; + + String DOUBLE_QUOTE = "\""; + + String ADD_QUOTE = "''"; + + String BINARY = "Binary"; + + String USER_DATA_FOLDER = "UserData"; + + String SECURITY_FOLDER = "security"; + + String SAVE_HISTORY_FILE_NAME = "file_save_history.log"; + + String LOCK_FILE = ".lock"; + + String PREFERENCES_FOLDER = "Preferences"; + + String PREFERENCES_FILE = "Preferences.prefs"; + + String PROTOCOL_VERSION_ERROR = "PROTOCOL_VERSION_ERROR"; + + String PREF_MAINTAIN_RESULT = "resultwindow.maintainrs"; + + String PREF_MAINTAIN_TABLESPACE_OPTIONS = "tablespaceincludeoptions.prefs"; + + String PREF_MAINTAIN_EXPORT_DATA_OPTIONS = "includeexportdataoptions.prefs"; + + String PREF_RESULT_ROWNUMBER = "resultwindow.copyrownumber"; + + String PREF_COLUMN_WIDTH_LENGTH = "resultwindow.columnwidthlength"; + + String TAB_WIDTH_OPTION = "editor.formatter.tabwidth"; + + String PREF_RESULT_IS_COLUMN_LENGTH_BY_VALUE = "resultwindow.iscolumnlengthbyvalue"; + + String PREF_RESULT_IS_RECORD_FETCH_ALL = "resultwindow.isrecordfetchall"; + + String PREF_RESULT_RECORD_FETCH_COUNT = "resultwindow.recordfetchcount"; + + String PREF_RESULT_IS_COPY_COLUMN_HEADER = "resultwindow.iscopycolumnheader"; + + String PREF_RESULT_IS_COPY_ROW_HEADER = "resultwindow.iscopyrowheader"; + + String PREF_RESULT_IS_SHOW_ENCODING = "resultwindow.isshowencoding"; + + String PREF_RESULT_IS_SHOW_TEXTMODE = "resultwindow.isshowtextmode"; + + String PREF_RESULT_WINDOW_GENERATE = "resultwindow.isgeneratenew"; + String PREF_RESULT_WINDOW_COUNT = "resultwindow.resultwindowcount"; + + String IS_DEFAULT_TIMEOUT = "exportpref.isRecordDefaultTimeout"; + + String TIMEOUT_VALUE = "exportpref.recordTimeOut"; + + String STR_TEXT = "txt"; + + String STR_BINARY = "bin"; + + String STR_EXCEL_XLSX = "EXCEL(xlsx)"; + + String STR_EXCEL_XLS = "EXCEL(xls)"; + + String REPLICATION = "REPLICATION"; + + String HASH = "HASH"; + + int FILE_NAME_MAX_LENGTH = 200; + + int RENAME_TERMINAL_MAX_LENGTH = 150; + + String COMMA_SEPARATE = ","; + + String ESCAPE_STRING_UNDERSCORE = "\\_"; + + String ESCAPE_STRING_PERCENTILE = "\\%"; + + String ESCAPE_FORWARDSLASH = "/"; + + String GS_DUMP_ENCODING = "UTF-8"; + + String SEPARATOR = "-"; + + String UNSUPPORTED_SCHEMA = "public"; + + String CANCEL_CONN_ERR_MSG = "Something unusual has occured to cause the driver to fail. Please report this exception."; + + String DISK_FULL_ERR_MSG = "There is not enough space on the disk"; + + String CASCADE = " CASCADE"; + + String SQL_TERMINAL = "SQL_TERMINAL"; + + String PLSQL_EDITOR = "PLSQL_EDITOR"; + + int KEY_CODE_FOR_COPY = 99; + + int RECONNECT_POPUP_LIMIT = 3; + + /** + * The Constant DEFAULT_TREE_NODE_COUNT. + */ + int DEFAULT_TREE_NODE_COUNT = 10000; + + /** + * The Constant TESTDRIVER. + */ + String TESTDRIVER = "FOR_JUNIT"; + + /** + * The Constant OPENGAUSS. + */ + String OPENGAUSS = "OPENGAUSS"; + + /** + * The Constant GAUSS200V1R5DRIVER. + */ + String GAUSS200V1R5DRIVER = "Gauss200V1R5Driver"; + + /** + * The Constant GAUSS200V1R6DRIVER. + */ + String GAUSS200V1R6DRIVER = "Gauss200V1R6Driver"; + + /** + * The Constant GAUSS200V1R7DRIVER. + */ + String GAUSS200V1R7DRIVER = "Gauss200V1R7Driver"; + + String USER_ROLE_DATE_DISPLAY_FORMAT = "yyyy-MM-dd"; + + String PRIVILEGE_GRANTEE_PUBLIC = "PUBLIC"; + + String PRIVILEGE_SELECT = "select"; + + String PRIVILEGE_INSERT = "insert"; + + String PRIVILEGE_WITH_GRANT_OPTION = "with grant option"; + + String PRIVILEGE_GRANT_OPTION_FOR = "only grant privilege"; + + String PRIVILEGE_ALL = "all"; + + String PRIVILEGE_UPDATE = "update"; + + String PRIVILEGE_DELETE = "delete"; + + String PRIVILEGE_TRUNCATE = "truncate"; + + String PRIVILEGE_EXECUTE = "execute"; + + String PRIVILEGE_USAGE = "usage"; + + String PRIVILEGE_REFERENCES = "references"; + + String PRIVILEGE_CREATE = "create"; + + String NEW_LINE_SIGN = "\r\n"; + + String LEFT_PARENTHESIS = "("; + + String RIGHT_PARENTHESIS = ")"; + + String SEMICOLON = ";"; + + String SERVER_ENCODING_KEY = "characterEncoding"; + + String EMPTY_STRING = ""; + + String SINGLE_NODE = "SINGLENODE"; + + String MULTI_NODE = "MULTINODE"; + + String COORDINATOR_NODE = "COORDINATOR"; + + String DATA_NODE = "DATANODE"; + + String RESULT_WINDOW_GRID = "Grid"; + + String RESULT_WINDOW_TEXT = "Text"; + + int TEXT_MODE_LOAD_MAXIMUM = 30000000; + + int TEXT_MODE_CELL_DIALOG_MAXINUM = 4679; + + // used for validating query while splitting queries to dodge DOS attacks on + // Regular Expression + // 2Crore is the limit to number of characters that SQL terminal can hold + // for a query + + int SQL_TERMINAL_LOAD_MAXIMUM = 20000000; + + int STRING_BUILDER_CAPACITY = 128; + + String FILE_SEPARATOR = "\\"; + + String TEMP_FILE_PATH = Normalizer.normalize(System.getProperty("java.io.tmpdir"), Normalizer.Form.NFD); + + int MAX_FILL_FACTOR = 100; + + int MAX_HOST_PORT = 65535; + + int MAX_LOAD_LIMIT = 30000; + + /** + * the FILE_LIMIT_FOR_SYNTAX_COLOR i.e 40MB, this is the safe value chosen based on multiple trials. + */ + double FILE_LIMIT_FOR_SYNTAX_COLOR = 40; + + String FILEENCODING_UTF = "UTF-8"; + + String FILEENCODING_GBK = "GBK"; + + String FILEENCODING_LATIN1 = "LATIN1"; + + String TAB = "\t"; + + // default process timeout which is the maximum time to wait + + int PROCESS_TIMEOUT = 86400; + + // max timeout value user can enter in preference page + + int MAX_PROCESS_TIMEOUT = 86400; + + // min timeout value user can enter in preference page + + int MIN_PROCESS_TIMEOUT = 1; + + String COLUMN_KEY_SIGN = "schemaName-tblName-colName"; + + /** + * The Constant CSV. + */ + String CSV = "CSV"; + + /** + * The Constant FETCH_COUNT. + */ + int FETCH_COUNT = 500; + + // import excel format + + String STR_XLSX = "XLSX"; + + String STR_XLS = "XLS"; + + String STR_CSV = "CSV"; + + String DOT = "."; + + String TEMP_ENVIRONMENT_VARIABLE = "TEMP"; + + String SHOW_SEARCHPATH_QUERY = "SHOW search_path"; + + String BOTTOM_BAR = "_"; + + String PREF_FONT_STYLE_SIZE = "editor.font.size"; + + String INVALID_INSERT = "invalid_insert"; + + int MAX_PREFIX_SEARCH_LENGTH = 500; + + String CHAR_UNIT = "CHAR"; + + String BYTE_UNIT = "BYTE"; + + String COMMENT_KW = "comment"; + + String DESCRIBE_USAGE = "DESCRIBE [schema.]object"; + + String CREATE_KW = "create"; + + String ALTER_INDEX_KW = "alter index"; + + String ALTER_INDEX_IF_EXISTS_KW = "alter if exists index"; + + String ALTER_KW = "alter"; + + String DROP_KW = "drop"; + + String INDEX_KW = "index"; + + String TABLE_KW = "table"; + + String IF_NOT_EXISTS_KW = "if not exists"; + + String IF_EXISTS_KW = "if exists"; + + String RENAME_KW = "rename"; + + String SET_KW = "set"; + + String SCHEMA_KW = "schema"; + + String COLUMN_KW = "column"; + + String ADD_KW = "add"; + + String CONSTRAINT_KW = "constraint"; + + String BLOB = "BLOB"; + + String BLOB_WATERMARK = "[BLOB]"; + + String BYTEA = "bytea"; + + String BYTEA_WATERMARK = "[BYTEA]"; + + String CURSOR_WATERMARK = "..."; + + String FROM_TABLE = "from"; + + String REF_CURSOR = "refcursor"; + + String CURSOR = "CURSOR"; + + String VOID = "void"; + + String RETURN_VOID = "(void)"; + + String RETURN_RESULT_COL_VALUE = "Result"; + + String VAR_CHAR = "varchar"; + + String PARAM = "param"; + + String OUT = "OUT"; + + String INOUT = "INOUT"; + + String RECORD = "record"; + + String EXEC = "exec"; + + String CALL = "call"; + + String QUESTION_MARK = "?"; + + String DWS = "DWS"; + String ALTER_TABLE = "ALTER_TABLE"; + String CREATE_VIEW = "CREATE_VIEW"; + String DROP_VIEW = "DROP_VIEW"; + String DROP_TABLE = "DROP_TABLE"; + String CREATE_TABLE = "CREATE_TABLE"; + String ALTER_VIEW = "ALTER_VIEW"; + String SET_SCHEMA_VIEW = "SET_SCHEMA_VIEW"; + String SET_SCHEMA_TABLE = "SET_SCHEMA_TABLE"; + String CREATE_TRIGGER = "CREATE_TRIGGER"; + String ID_EDIT_TERMINAL_VALUE_BUTTON = "ID_EDIT_TERMINAL_VALUE_BUTTON"; + String PREF_USER_DEFINE_DATE_FORMAT = "userdefineddateformat.prefs"; + String PREF_USER_DEFINE_TIME_FORMAT = "userdefinedtimeformat.prefs"; + String PREF_SYSTEM_DATE_FORMAT = "systemdateformat.prefs"; + String PREF_SYSTEM_TIME_FORMAT = "systemtimeformat.prefs"; + String DATE_FORMAT_VALUE = "dateformatvalue.prefs"; + String TIME_FORMAT_VALUE = "timeformatvalue.prefs"; + String DEFAULT_DATE_FORMAT = "yyyy-MM-dd"; + String DEFAULT_TIME_FORMAT = "HH:mm:ss"; + + String ML_COMMENT_START = "/*"; + String ML_COMMENT_END = "*/"; + + int PBKDF_ITERATIONS = 10000; + int ONE_KB = 1024; + double FILESIZE_PERCENT_TO_XMX_VALUE = 0.008; + + int PARALLEL_IMPORT_EXPORT_DEFAULT = 10; + int PARALLEL_IMPORT_EXPORT_MAX = 20; + String PARALLEL_IMPORT_EXPORT_PREF = "exportpref.parallelimportexportlimitvalue"; + String DO_NOT_DELETE_PART_LABEL = "Do not delete this part"; + String WITH_CLAUSE_REGEX = "(?i)^with.*as\\s*\\(([^()]*|\\(([^()]*|\\([^()]*\\))*\\))*\\)\\s*.?(\\s*)" + + "(select|insert|delete|update)"; + + String BINARY_FILE_FORMAT = "Binary"; + + /** + * this for debug rollback config + */ + String DEBUG_PREFERENCE_IF_ROLLBACK = "debug.rollback"; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/MathUtils.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/MathUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..d30f979e4cdbd19b0e5996a0a59644c02c5988f1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/MathUtils.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +/** + * + * Title: class + * + * Description: The Class MathUtils. + * + * @since 3.0.0 + */ +public class MathUtils { + + /** + * Round double values. + * + * @param value the value + * @param placesParam the places param + * @return the double + */ + public static double roundDoubleValues(double value, int placesParam) { + int places = placesParam; + if (places < 0) { + places = 0; + } + + BigDecimal bd = BigDecimal.valueOf(value); + bd = bd.setScale(places, RoundingMode.HALF_UP); + return bd.doubleValue(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/MaxLineBufferedReader.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/MaxLineBufferedReader.java new file mode 100644 index 0000000000000000000000000000000000000000..852bc44c8a33b58026c7866248cb1cd1687d6953 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/MaxLineBufferedReader.java @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; + +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class MaxLineBufferedReader. + * + * @since 3.0.0 + */ +public class MaxLineBufferedReader extends BufferedReader { + private static final int DEFAULT_MAX_LINE_LENGTH = 8192; + private int maxLineLen; + private boolean wholeLineFlag = true; + private static final int CHAR_CR = 13; + private static final int CHAR_LF = 10; + + /** + * Instantiates a new max line buffered reader. + * + * @param reader the reader + */ + public MaxLineBufferedReader(InputStreamReader reader) { + super(reader); + maxLineLen = DEFAULT_MAX_LINE_LENGTH; + } + + /** + * Instantiates a new max line buffered reader. + * + * @param reader the reader + */ + public MaxLineBufferedReader(Reader reader) { + super(reader); + maxLineLen = DEFAULT_MAX_LINE_LENGTH; + } + + /** + * Checks if is whole line. + * + * @return true, if is whole line + */ + public boolean isWholeLine() { + return this.wholeLineFlag; + } + + /** + * Instantiates a new max line buffered reader. + * + * @param reader the reader + * @param lineLengthLimit the line length limit + */ + public MaxLineBufferedReader(InputStreamReader reader, int lineLengthLimit) { + super(reader); + maxLineLen = lineLengthLimit; + } + + /** + * Read max len line. + * + * @return the string + * @throws DatabaseOperationException the database operation exception + */ + public String readMaxLenLine() throws DatabaseOperationException { + try { + int currentPos = 0; + char[] line = new char[maxLineLen]; + int currentChar; + currentChar = super.read(); + + while ((currentChar != CHAR_CR) && (currentChar != CHAR_LF) && (currentChar >= 0)) { + line[currentPos++] = (char) currentChar; + + if (currentPos < maxLineLen) { + currentChar = super.read(); + } else { + break; + } + } + this.wholeLineFlag = true; + + if (currentChar < 0) { + // End of file + if (currentPos > 0) { + // Return last line + return new String(line, 0, currentPos); + } else { + return null; + } + } else { + // Remove newline characters from the buffer + if (currentChar == CHAR_CR) { + // Check for LF and remove from buffer + super.mark(1); + if (super.read() != CHAR_LF) { + super.reset(); + } + } else if (currentChar != CHAR_LF) { + this.wholeLineFlag = false; + // maxLineLen has been hit, but still need to + // remove newline characters. + super.mark(1); + int nextChar = super.read(); + if (nextChar == CHAR_CR) { + super.mark(1); + if (super.read() != CHAR_LF) { + super.reset(); + } + } else if (nextChar != CHAR_LF) { + super.reset(); + } + } + return new String(line, 0, currentPos); + } + } catch (IOException exp) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERROR_READING_DATA), exp); + throw new DatabaseOperationException(IMessagesConstants.ERROR_READING_DATA); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/MemoryCleaner.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/MemoryCleaner.java new file mode 100644 index 0000000000000000000000000000000000000000..5f231341d8f0e023d46bfd97b9843feb84c8fa79 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/MemoryCleaner.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +/** + * + * Title: class + * + * Description: The Class MemoryCleaner. + * + * @since 3.0.0 + */ +public final class MemoryCleaner { + + /** + * Instantiates a new memory cleaner. + */ + private MemoryCleaner() { + + } + + /** + * Clean up memory. + */ + public static void cleanUpMemory() { + System.gc(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/MultiLineComment.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/MultiLineComment.java new file mode 100644 index 0000000000000000000000000000000000000000..98afacf7fd11a23170894d5d2b0270c118c4bf4b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/MultiLineComment.java @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +/** + * + * Title: class + * + * Description: The Class MultiLineComment. + * + * @since 3.0.0 + */ +public class MultiLineComment { + private String stringToParse; + + /** + * The start sequence. + */ + protected char[] startSequence = "/*".toCharArray(); + + /** + * The end sequence. + */ + protected char[] endSequence = "*/".toCharArray(); + + private int from; + private int to; + + private int startOffset; + private int endOffset; + + /** + * Instantiates a new multi line comment. + * + * @param stringToParse1 the string to parse 1 + */ + public MultiLineComment(String stringToParse1) { + stringToParse = stringToParse1; + from = 0; + to = stringToParse1.length(); + startOffset = -1; + endOffset = -1; + } + + /** + * Sequence detected. + * + * @param startIdx the start idx + * @param sequence the sequence + * @param eofAllowed the eof allowed + * @return true, if successful + */ + protected boolean sequenceDetected(int startIdx, char[] sequence, boolean eofAllowed) { + for (int cnt = 1; cnt < sequence.length; cnt++) { + if (startIdx + cnt < to) { + int val = stringToParse.charAt(startIdx + cnt); + if (val != sequence[cnt]) { + return false; + } + } else { + return eofAllowed; + } + } + + return true; + } + + /** + * Find. + * + * @return true, if successful + */ + public boolean find() { + char character; + int loop = from; + int commentNestingDepth = 0; + while (loop < to) { + character = stringToParse.charAt(loop); + + if (character == startSequence[0]) { + // Check if the nested start sequence has been found. + if (sequenceDetected(loop, startSequence, false)) { + if (commentNestingDepth == 0) { + startOffset = loop; + } + + commentNestingDepth++; + } + } else if (character == endSequence[0]) { + // Check if the specified end sequence has been found. + if (sequenceDetected(loop, endSequence, true)) { + commentNestingDepth--; + + if (commentNestingDepth == 0) { + endOffset = loop + endSequence.length; + from = endOffset; + return true; + } else if (commentNestingDepth < 1) { + from = loop + endSequence.length; + startOffset = -1; + endOffset = -1; + return false; + } + } + } + + loop++; + } + + from = loop; + startOffset = -1; + endOffset = -1; + return false; + } + + /** + * Start. + * + * @return the int + */ + public int start() { + return startOffset; + } + + /** + * End. + * + * @return the int + */ + public int end() { + return endOffset; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/OsCommandExecutor.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/OsCommandExecutor.java new file mode 100644 index 0000000000000000000000000000000000000000..e3a221b82ebb0776ced1295e10afd3b53903a974 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/OsCommandExecutor.java @@ -0,0 +1,477 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.io.Writer; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.io.input.BoundedInputStream; + +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class OsCommandExecutor. + * + * @since 3.0.0 + */ +public class OsCommandExecutor { + private String[] command; + private File workingDir; + private boolean isFinished; + private boolean isCancel; + private Process process; + private String[] processEnvironment; + private String errorMessage; + private String inputMessage; + private static final String PERMISSION_ERROR = "permission denied for relation"; + private int processTimeout; + private volatile boolean isStopThread = false; + private OutputStreamGobbler outputGobbler; + private InputStreamGobbler inputGobbler; + private ErrorStreamGobbler errorGobbler; + private InputStream inputStream; + private OutputStream outputStream; + private final AtomicReference thExceptionInSGobbler = new AtomicReference(); + private final AtomicReference thExceptionErrSGobbler = new AtomicReference(); + + /** + * Instantiates a new os command executor. + * + * @param commands the commands + * @param en the en + * @param trackOutStream the track out stream + * @param trackErrStream the track err stream + * @param workingDir the working dir + */ + public OsCommandExecutor(String[] commands, String[] en, File workingDir, int processTimeout) { + this.command = commands.clone(); + if (en != null) { + this.processEnvironment = en.clone(); + } else { + this.processEnvironment = new String[0]; + } + this.isFinished = false; + process = null; + this.workingDir = workingDir; + this.processTimeout = processTimeout; + } + + /** + * + * Title: class + * + * Description: The Class InputStreamGobbler. This class captures error + * messages of the new process (gs_dump), and handles accordingly in DS code + */ + class InputStreamGobbler extends Thread { + InputStream is; + + public InputStreamGobbler(InputStream is) { + this.is = is; + } + + /** + * Run. + */ + public void run() { + + StringBuilder strBuilder = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + MPPDBIDELoggerUtility.trace("handleInputStream Start"); + try { + while (false == isStopThread) { + + strBuilder.append(readInputMsg()); + inputMessage = strBuilder.toString(); + + try { + Thread.sleep(3000); + } catch (InterruptedException interruptedException) { + MPPDBIDELoggerUtility.error("Sleep InterruptedException", interruptedException); + } + } + + } catch (Exception exception) { + MPPDBIDELoggerUtility.error("GS_DUMP_LOG : IO Exception while Reading gs dump", exception); + + } finally { + MPPDBIDELoggerUtility.trace("handleInputStream Exit"); + } + MPPDBIDELoggerUtility.info("GS_DUMP Received data: " + inputMessage); + } + + private String readInputMsg() { + StringBuilder strBlder = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + BoundedInputStream bips = null; + try { + bips = new BoundedInputStream(this.is, 8192); + bips.setPropagateClose(false); + checkForInputStream(strBlder, bips); + } catch (IOException ioException) { + thExceptionErrSGobbler.set(ioException); + } finally { + try { + if (bips != null) { + bips.close(); + } + } catch (IOException ioException) { + MPPDBIDELoggerUtility.error("Error while reading input stream", ioException); + } + } + return strBlder.toString(); + } + + private void checkForInputStream(StringBuilder strBuilder, BoundedInputStream bis) throws IOException { + List lines = IOUtils.readLines(bis, MPPDBIDEConstants.GS_DUMP_ENCODING); + if (lines.size() != 0) { + for (String line : lines) { + strBuilder.append(MPPDBIDEConstants.LINE_SEPARATOR).append(line); + } + } + } + } + + /** + * + * Title: class + * + * Description: The Class InputStreamGobbler. This class works to provide + * user input to gs_dump, which it expects from DS For DS, it is handled by + * an OutputStream + */ + class OutputStreamGobbler extends Thread { + char[] param; + OutputStream os; + + public OutputStreamGobbler(OutputStream os, char[] cs) { + this.os = os; + this.param = cs; + } + + /** + * Sends output to process + * + * @return void + */ + public void run() { + PrintWriter pw = null; + Writer outwriter = null; + if (os != null) { + try { + outwriter = new OutputStreamWriter(os, MPPDBIDEConstants.GS_DUMP_ENCODING); + } catch (UnsupportedEncodingException exception) { + MPPDBIDELoggerUtility.error("encoding is not supported", exception); + thExceptionInSGobbler.set(exception); + return; + } + pw = new PrintWriter(outwriter); + } + if (pw != null) { + pw.println(param); // passed to the process + pw.flush(); + pw.close(); + } + MPPDBIDELoggerUtility.info("GS_DUMP Sent data"); + } + } + + class ErrorStreamGobbler extends Thread { + InputStream is; + + public ErrorStreamGobbler(InputStream is) { + this.is = is; + } + + /** + * Run. + */ + public void run() { + + StringBuilder strBuilder = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + MPPDBIDELoggerUtility.trace("handleErrorStream Start"); + try { + while (false == isStopThread) { + + strBuilder.append(readErrorMsg()); + errorMessage = strBuilder.toString(); + + try { + Thread.sleep(3000); + } catch (InterruptedException interruptedException) { + MPPDBIDELoggerUtility.error("Sleep InterruptedException", interruptedException); + } + } + + } catch (Exception exception) { + MPPDBIDELoggerUtility.error("GS_DUMP_LOG : IO Exception while Reading gs dump", exception); + + } finally { + MPPDBIDELoggerUtility.trace("handleErrorStream Exit"); + } + MPPDBIDELoggerUtility.error("GS_DUMP Received data: " + errorMessage); + } + + private String readErrorMsg() { + StringBuilder strBuilder = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + BoundedInputStream bis = null; + try { + bis = new BoundedInputStream(this.is, 8192); + bis.setPropagateClose(false); + checkForInputStream(strBuilder, bis); + } catch (IOException ioException) { + thExceptionErrSGobbler.set(ioException); + } finally { + try { + if (bis != null) { + bis.close(); + } + } catch (IOException ioException) { + MPPDBIDELoggerUtility.error("Error while reading error stream", ioException); + } + } + return strBuilder.toString(); + } + + private void checkForInputStream(StringBuilder strBuilder, BoundedInputStream bis) throws IOException { + List lines = IOUtils.readLines(bis, MPPDBIDEConstants.GS_DUMP_ENCODING); + if (lines.size() != 0) { + for (String line : lines) { + strBuilder.append(MPPDBIDEConstants.LINE_SEPARATOR).append(line); + } + } + } + } + + /** + * Gets the error message. + * + * @return the error message + */ + public String getErrorMessage() { + return this.errorMessage; + } + + /** + * Start. + * + * @param cs the cs + * @throws DatabaseOperationException the database operation exception + */ + public void start(char[] cs) throws DatabaseOperationException { + try { + process = Runtime.getRuntime().exec(command, processEnvironment, workingDir); + } catch (IOException ioException) { + setFinished(true); + if (ioException.getMessage().equalsIgnoreCase("permission denied")) { + MPPDBIDELoggerUtility.error("external utility gs_dump is not executable", ioException); + } + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_FAIL_DISK_WRITE_ERROR), ioException); + throw new DatabaseOperationException(IMessagesConstants.EXPORT_FAIL_DISK_WRITE_ERROR); + } + + inputStream = process.getInputStream(); + outputStream = process.getOutputStream(); + + /* Start stream threads */ + captureStreams(cs); + + try { + boolean processTimedout = process.waitFor(processTimeout, TimeUnit.SECONDS); + + isStopThread = true; + + // if exitValue is true then process is terminated, else it is + // timeout + if (processTimedout) { + int exitValue = process.exitValue(); + + // If returnValue is 0 then normal termination + if (exitValue != 0) { + + MPPDBIDELoggerUtility.info("GS_DUMP process exited abnormally"); + + if (null != errorMessage && errorMessage.contains("is not super or sysadmin role")) { + errorMessage = MessageConfigLoader + .getProperty(IMessagesConstants.BATCH_EXPORT_NO_USER_PREVILAGE); + } + + if (null != errorMessage && errorMessage.contains(PERMISSION_ERROR)) { + errorMessage = MessageConfigLoader + .getProperty(IMessagesConstants.BATCH_EXPORT_NO_RELATION_PREVILAGE); + } + throwThreadException(); + throwIntruptException(); + } + } else { + MPPDBIDELoggerUtility.info("GS_DUMP process timed out"); + errorMessage = MessageConfigLoader.getProperty(IMessagesConstants.PROCESS_TIMEOUT_ERROR); + destroyProcess(); + + throw new DatabaseOperationException(IMessagesConstants.PROCESS_TIMEOUT_ERROR); + } + + } catch (InterruptedException iException) { + errorMessage = iException.getMessage(); + throwIntruptException(); + } finally { + stopCapturingStreams(); + setFinished(true); + IOUtils.closeQuietly(inputStream); + IOUtils.closeQuietly(outputStream); + } + } + + private void throwThreadException() throws DatabaseOperationException { + Exception exception = thExceptionErrSGobbler.get(); + if (exception != null) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_FAIL_DISK_WRITE_ERROR)); + throw new DatabaseOperationException(IMessagesConstants.EXPORT_FAIL_DISK_WRITE_ERROR); + } + exception = thExceptionInSGobbler.get(); + if (exception != null) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_FAIL_DISK_WRITE_ERROR)); + throw new DatabaseOperationException(IMessagesConstants.EXPORT_FAIL_DISK_WRITE_ERROR); + } + } + + private void captureStreams(char[] cs) { + this.outputGobbler = new OutputStreamGobbler(process.getOutputStream(), cs); + this.outputGobbler.start(); + + /* + * due to some reason, error prints from gs_dump is not appearing in + * errorstream, it is coming in DS input pipe/new process outputstream. + * And output prints from gs_dump is appearing in errorstream. So, to + * read error messages, process errorstream is not redirected. + */ + /* + * gs_dump behaviour of input and error streams is different in both + * windows and linux + */ + + this.inputGobbler = new InputStreamGobbler(this.process.getInputStream()); + this.errorGobbler = new ErrorStreamGobbler(this.process.getErrorStream()); + + this.inputGobbler.start(); + this.errorGobbler.start(); + } + + private void stopCapturingStreams() { + if (this.outputGobbler != null && this.outputGobbler.isAlive()) { + try { + this.outputGobbler.join(); + } catch (InterruptedException exception) { + MPPDBIDELoggerUtility.error("error while stopping thread", exception); + } + } + if (this.inputGobbler != null && this.inputGobbler.isAlive()) { + try { + this.inputGobbler.join(); + } catch (InterruptedException exception) { + MPPDBIDELoggerUtility.error("error while stopping thread", exception); + } + } + if (this.errorGobbler != null && this.errorGobbler.isAlive()) { + try { + this.errorGobbler.join(); + } catch (InterruptedException exception) { + MPPDBIDELoggerUtility.error("error while stopping thread", exception); + } + } + } + + /** + * Destroy Process. + */ + private void destroyProcess() { + process.destroy(); + if (process.isAlive()) { + process.destroyForcibly(); + } + } + + /** + * Throw intrupt exception. + * + * @throws DatabaseOperationException the database operation exception + */ + private void throwIntruptException() throws DatabaseOperationException { + if (!isCancel()) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_FAIL_PROCESS_INTRUPTED)); + throw new DatabaseOperationException(IMessagesConstants.EXPORT_FAIL_PROCESS_INTRUPTED); + } else { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_CANCEL_ON_USER_REQUEST)); + throw new DatabaseOperationException(IMessagesConstants.EXPORT_CANCEL_ON_USER_REQUEST); + } + } + + /** + * Checks if is finished. + * + * @return true, if is finished + */ + public boolean isFinished() { + return isFinished; + } + + /** + * Sets the finished. + * + * @param isFinishd the new finished + */ + public void setFinished(boolean isFinishd) { + this.isFinished = isFinishd; + } + + /** + * Checks if is cancel. + * + * @return true, if is cancel + */ + public boolean isCancel() { + return isCancel; + } + + /** + * Cancel. + */ + public void cancel() { + this.isCancel = true; + if (!isFinished() && null != process) { + process.destroy(); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/QueryResultType.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/QueryResultType.java new file mode 100644 index 0000000000000000000000000000000000000000..7f00be8110dfbb9f0980114cfd9eab7617b80fe2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/QueryResultType.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +/** + * + * Title: enum + * + * Description: The Enum QueryResultType. + * + * @since 3.0.0 + */ +public enum QueryResultType { + RESULTTYPE_RESULTSET, RESULTTYPE_DML, RESULTTYPE_OTHERS, RESULTTYPE_BUTT +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/ResultSetDatatypeMapping.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/ResultSetDatatypeMapping.java new file mode 100644 index 0000000000000000000000000000000000000000..be1ea348a5c60c334bd7d0c9d67add32098e2403 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/ResultSetDatatypeMapping.java @@ -0,0 +1,586 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +import java.io.IOException; +import java.io.Reader; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Types; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class ResultSetDatatypeMapping. + * + * @since 3.0.0 + */ +public final class ResultSetDatatypeMapping { + private static boolean isIncludeEncoding; + + /** + * The Constant INTERVAL_DAY_TO_SECOND. + */ + public static final int INTERVAL_DAY_TO_SECOND = -104; + + /** + * The Constant INTERVAL_YEAR_TO_MONTH. + */ + public static final int INTERVAL_YEAR_TO_MONTH = -103; + + /** + * The Constant ZERO. + */ + public static final int ZERO = 0; + + /** + * The Constant TWO. + */ + public static final int TWO = 2; + + /** + * The Constant THREE. + */ + public static final int THREE = 3; + + /** + * The Constant SIX. + */ + public static final int SIX = 6; + + /** + * Instantiates a new result set datatype mapping. + */ + + private static List> cursorResultVisitedValues; + + private ResultSetDatatypeMapping() { + } + + /** + * sets the cursor resultset values + * + * @param cursorResultValues the cursorResultValues + */ + private static void setCursorResultValues(List> cursorResultValues) { + cursorResultVisitedValues = cursorResultValues; + } + + /** + * gets the cursor resultset values + * + * @return cursorResultVisitedValues the cursorResultVisitedValues + */ + public static List> getCursorResultValues() { + return cursorResultVisitedValues; + } + + private static boolean isReturnTypeVoid(ResultSet rs) throws SQLException { + if (MPPDBIDEConstants.VOID.equals(rs.getMetaData().getColumnTypeName(rs.getMetaData().getColumnCount()))) { + return true; + } + return false; + } + + /** + * return true, if is ReturnType Cursor + * + * @param rs the rs + * @return return true, if is ReturnType Cursor + * @throws SQLException the SQLException + */ + public static boolean isReturnTypeCursor(ResultSet rs) throws SQLException { + if (MPPDBIDEConstants.REF_CURSOR + .equals(rs.getMetaData().getColumnTypeName(rs.getMetaData().getColumnCount()))) { + return true; + } + return false; + } + + /** + * return true, if is ReturnType Record + * + * @param rs the rs + * @return return true, if is ReturnType Record + * @throws SQLException the SQLException + */ + public static boolean isReturnTypeRecord(ResultSet rs) throws SQLException { + if (MPPDBIDEConstants.RECORD.equals(rs.getMetaData().getColumnTypeName(rs.getMetaData().getColumnCount()))) { + return true; + } + return false; + } + + /** + * gets the Read Column Value Object + * + * @param rs the rs + * @param columnIndex the columnIndex + * @return the object value + * @throws NumberFormatException the NumberFormatException + * @throws SQLException the SQLException + * @throws DatabaseOperationException the DatabaseOperationException + */ + public static Object getReadColumnValueObject(ResultSet rs, int columnIndex) + throws NumberFormatException, SQLException, DatabaseOperationException { + if (rs.getMetaData() != null) { + switch (rs.getMetaData().getColumnType(columnIndex)) { + case Types.TINYINT: + case Types.SMALLINT: + case Types.INTEGER: + case Types.BIGINT: + case Types.FLOAT: + case Types.REAL: + case Types.DOUBLE: { + return handleDoubleDataTypeValue(rs, columnIndex); + } + case Types.BOOLEAN: + case Types.BIT: { + return getBitValue(rs, columnIndex); + } + case Types.NUMERIC: { + return rs.getBigDecimal(columnIndex); + } + case Types.DATE: { + return rs.getDate(columnIndex); + } + case Types.TIME: + case Types.TIME_WITH_TIMEZONE: + case Types.TIMESTAMP: + case Types.TIMESTAMP_WITH_TIMEZONE: { + String typeName = rs.getMetaData().getColumnTypeName(columnIndex); + if ("timetz".equals(typeName) || "timestamptz".equals(typeName)) { + return rs.getString(columnIndex); + } else { + return rs.getTimestamp(columnIndex); + } + } + case INTERVAL_DAY_TO_SECOND: + case INTERVAL_YEAR_TO_MONTH: { + return convertToInterval(rs, columnIndex); + } + case Types.CLOB: { + return getCLOBValue(rs, columnIndex); + } + case Types.BLOB: { + return getBLOBValue(rs, columnIndex); + } + case Types.OTHER: { + return handleOtherDataTypeValue(rs, columnIndex); + } + case Types.BINARY: { + return getByteAValue(rs, columnIndex); + } + default: { + return resultSetDataTypeMapDefaultAction(rs, columnIndex); + } + } + } + return ""; + } + + private static Object handleDoubleDataTypeValue(ResultSet rs, int columnIndex) throws SQLException { + return rs.getObject(columnIndex); + } + + private static Object handleOtherDataTypeValue(ResultSet rs, int columnIndex) throws SQLException { + if (isReturnTypeCursor(rs) || isReturnTypeRecord(rs)) { + return convertResultSetToObject(rs, columnIndex, false, true); + } + if (isReturnTypeVoid(rs)) { + return MPPDBIDEConstants.RETURN_VOID; + } + return resultSetDataTypeMapDefaultAction(rs, columnIndex); + } + + /** + * converts resultSet values into object + * + * @param rs the rs + * @param columnIndex the columnIndex + * @param isCallableStmt the isCallableStmt + * @param isResultSetVisited the isResultSetVisited + * @return the list of cursor objects + */ + public static List> convertResultSetToObject(ResultSet rs, int columnIndex, boolean isCallableStmt, + boolean isResultSetVisited) { + List> cursorRowsValue = new ArrayList>(); + int visited = 0; + try { + ResultSet rsCursorType = null; + if (isCallableStmt || isReturnTypeRecord(rs)) { + rsCursorType = rs; + } else { + rsCursorType = (ResultSet) rs.getObject(columnIndex); + } + int columnCount = rsCursorType.getMetaData().getColumnCount(); + List colHeaderValue = new ArrayList(); + for (int col = 0; col < columnCount; col++) { + colHeaderValue.add(rsCursorType.getMetaData().getColumnLabel(col + 1)); + } + + cursorRowsValue.add(colHeaderValue); + if (isReturnTypeRecord(rs)) { + visited = addCursorRowValueToList(cursorRowsValue, visited, rsCursorType, columnCount); + } + while (rsCursorType.next()) { + visited = addCursorRowValueToList(cursorRowsValue, visited, rsCursorType, columnCount); + } + + if (!isResultSetVisited) { + cursorRowsValue = getCursorResultValues(); + } + + } catch (SQLException exe) { + MPPDBIDELoggerUtility.error("Error occured while getting result set values", exe); + } + + if (isResultSetVisited) { + setCursorResultValues(cursorRowsValue); + } + + return cursorRowsValue; + + } + + private static int addCursorRowValueToList(List> cursorRowsValue, int visited, ResultSet rsCursorType, + int columnCount) throws SQLException { + List colValue = new ArrayList(); + for (int col = 0; col < columnCount; col++) { + colValue.add(rsCursorType.getObject(col + 1)); + } + cursorRowsValue.add(colValue); + visited++; + return visited; + } + + /** + * the result SetDataType Map Default Action + * + * @param rs the rs + * @param columnIndex the columnIndex + * @return the result set + * @throws SQLException the SQLException + */ + public static Object resultSetDataTypeMapDefaultAction(ResultSet rs, int columnIndex) throws SQLException { + if (ResultSetDatatypeMapping.isIncludeEncoding) { + return rs.getBytes(columnIndex); + } + return rs.getString(columnIndex); + } + + private static Object getBLOBValue(ResultSet rs, int columnIndex) throws SQLException { + switch (rs.getMetaData().getColumnTypeName(columnIndex)) { + case MPPDBIDEConstants.BLOB: { + try { + byte[] retBytes = null; + Blob blob = rs.getBlob(columnIndex); + if (null == blob) { + return null; + } + retBytes = blob.getBytes(1, (int) blob.length()); + blob.free(); + return retBytes; + } catch (SQLException exp) { + MPPDBIDELoggerUtility.error("error occured when converting to BLOB", exp); + return resultSetDataTypeMapDefaultAction(rs, columnIndex); + } + } + default: { + return resultSetDataTypeMapDefaultAction(rs, columnIndex); + } + } + } + + private static Object getByteAValue(ResultSet rs, int columnIndex) throws SQLException { + switch (rs.getMetaData().getColumnTypeName(columnIndex)) { + case MPPDBIDEConstants.BYTEA: { + try { + byte[] retBytes = rs.getBytes(columnIndex); + return retBytes; + } catch (SQLException exp) { + MPPDBIDELoggerUtility.error("error while getting bytes", exp); + return resultSetDataTypeMapDefaultAction(rs, columnIndex); + } + } + default: { + return resultSetDataTypeMapDefaultAction(rs, columnIndex); + } + } + } + + /** + * Gets the CLOB value. + * + * @param rs the rs + * @param columnIndex the column index + * @return the CLOB value + * @throws DatabaseOperationException the database operation exception + */ + private static Object getCLOBValue(ResultSet rs, int columnIndex) throws DatabaseOperationException { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + Reader reader = null; + MaxLineBufferedReader br = null; + try { + Clob clobValue = rs.getClob(columnIndex); + if (null == clobValue) { + return null; + } + reader = clobValue.getCharacterStream(); + br = new MaxLineBufferedReader(reader); + int length = 0; + String line = br.readMaxLenLine(); + while (null != line && length < 5000) { + sb.append(line); + length = sb.length(); + line = br.readMaxLenLine(); + } + } catch (SQLException exp) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.UNKNOW_CLOB_TYPE), exp); + throw new DatabaseOperationException(IMessagesConstants.UNKNOW_CLOB_TYPE, exp); + } finally { + try { + if (null != br) { + br.close(); + } + if (null != reader) { + reader.close(); + } + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("Error while closing readers", exception); + } + + } + return sb.toString(); + } + + /** + * Convert to interval. + * + * @param rs the rs + * @param columnIndex the column index + * @return the string builder + * @throws SQLException the SQL exception + */ + private static String convertToInterval(ResultSet rs, int columnIndex) throws SQLException { + Object obj = null; + obj = rs.getObject(columnIndex); + if (obj == null) { + return null; + } + String objToString = obj.toString(); + String[] interval = objToString.split(" ", TWO); + if (interval.length < 2) { + return getIntervalYrToMonthValue(interval[0]); + } + StringBuilder intervalDS = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + try { + if (Integer.parseInt(interval[0]) >= 0) { + if ("-0".equals(interval[0])) { + intervalDS.append("-"); + } else { + intervalDS.append("+"); + } + } + intervalDS.append(String.format(Locale.ENGLISH, "%07d", Integer.parseInt(interval[0])) + " "); + String[] time = interval[1].split("\\.", TWO); + if (time.length < 2) { + return null; + } + String[] timeUnit = time[0].split(":", THREE); + for (int i = 0; i < timeUnit.length; i++) { + intervalDS.append(String.format(Locale.ENGLISH, "%02d", Integer.parseInt(timeUnit[i]))); + if (i != timeUnit.length - 1) { + intervalDS.append(":"); + } + } + intervalDS.append("."); + if (Integer.parseInt(time[1]) == 0) { + intervalDS.append(String.format(Locale.ENGLISH, "%06d", ZERO)); + } else { + intervalDS.append(time[1].substring(ZERO, SIX)); + } + + } catch (NumberFormatException exception) { + MPPDBIDELoggerUtility.error("Error occured while converting to Time Intervals", exception); + return null; + } + return intervalDS.toString(); + } + + /** + * returns Interval Year to Month value. + * + * @param interval the interval + * @return String + */ + private static String getIntervalYrToMonthValue(String interval) { + StringBuilder intervalDS = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + if ('-' == interval.charAt(0)) { + interval = interval.substring(1); + intervalDS.append("-"); + } + String[] period = interval.split("-"); + if (period.length < 2) { + return null; + } + + if (Integer.parseInt(period[0]) >= 0 && intervalDS.length() < 1) { + intervalDS.append("+"); + } + for (int i = 0; i < period.length; i++) { + if (period[i].length() <= 2) { + intervalDS.append(String.format(Locale.ENGLISH, "%02d", Integer.parseInt(period[i]))); + } else { + intervalDS.append(String.format(Locale.ENGLISH, "%d", Integer.parseInt(period[i]))); + } + if (i != period.length - 1) { + intervalDS.append("-"); + } + } + return intervalDS.toString(); + } + + /** + * Gets the bit value. + * + * @param resultSet the result set + * @param colIndex the col index + * @return the bit value + * @throws SQLException the SQL exception + */ + private static Object getBitValue(ResultSet resultSet, int colIndex) throws SQLException { + ResultSetMetaData metaData = resultSet.getMetaData(); + if (null != metaData && metaData.getPrecision(colIndex) > 1) { + return resultSetDataTypeMapDefaultAction(resultSet, colIndex); + } + return resultSet.getObject(colIndex); + } + + /** + * Convert string to value. + * + * @param rs the rs + * @param i the i + * @return the string + * @throws SQLException the SQL exception + */ + public static String convertStringToValue(ResultSet rs, int i) throws SQLException { + String value = rs.getString(i); + if (null != value && rs.getMetaData() != null) { + switch (rs.getMetaData().getColumnType(i)) { + case Types.TINYINT: + case Types.SMALLINT: { + return String.valueOf(Short.parseShort(value)); + } + case Types.INTEGER: { + return String.valueOf(Integer.parseInt(value)); + } + case Types.BIGINT: { + return String.valueOf(Long.parseLong(value)); + } + case Types.FLOAT: + case Types.REAL: { + return String.valueOf(Float.parseFloat(value)); + } + case Types.DOUBLE: { + return String.valueOf(Double.parseDouble(value)); + } + default: { + return value; + } + } + } else { + return value; + } + } + + /** + * Sets the include encoding. + * + * @param isDSIncludeEncoding the new include encoding + */ + public static void setIncludeEncoding(boolean isDSIncludeEncoding) { + ResultSetDatatypeMapping.isIncludeEncoding = isDSIncludeEncoding; + } + + /** + * gets the data type of column + * + * @param rs the rs + * @return the column data type + * @throws SQLException the SQLException + */ + public static Object getColumnDataTypeName(ResultSet rs) throws SQLException { + Object colDataTypeName = ""; + if (rs.getMetaData() != null) { + colDataTypeName = rs.getMetaData().getColumnTypeName(rs.getMetaData().getColumnCount()); + } + return colDataTypeName; + } + + /** + * gets the FuncProcColObjectExceptValue + * + * @param rs the rs + * @param columnIndex the columnIndex + * @param isCursorTypeResult the isCursorTypeResult + * @return the column value object + * @throws NumberFormatException the NumberFormatException + * @throws DatabaseOperationException the DatabaseOperationException + */ + public static Object getFuncProcColObjectExceptValue(ResultSet rs, int columnIndex, boolean isCursorTypeResult) + throws NumberFormatException, DatabaseOperationException { + try { + if (rs.getMetaData() != null) { + switch (columnIndex) { + case 1: { + if (isCursorTypeResult) { + return MPPDBIDEConstants.RETURN_RESULT_COL_VALUE; + } + return rs.getMetaData().getColumnName(columnIndex); + } + case 2: { + if (isCursorTypeResult) { + return MPPDBIDEConstants.CURSOR; + } + return getColumnDataTypeName(rs); + } + case 3: { + return MPPDBIDEConstants.OUT; + } + default: { + return ""; + } + } + } + } catch (SQLException exe) { + MPPDBIDELoggerUtility.error("Error occured while getting result set values", exe); + } + return ""; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/SQLKeywords.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/SQLKeywords.java new file mode 100644 index 0000000000000000000000000000000000000000..f534344f5f749f3c5825d712fa84b073982c8292 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/SQLKeywords.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +import java.util.HashMap; +import java.util.Locale; + +/** + * + * Title: class + * + * Description: The Class SQLKeywords. + * + * @since 3.0.0 + */ +public class SQLKeywords { + + private static final HashMap KEYWORDSMAPPER = new HashMap<>(); + private static final int CONSTVALUE = 1; + + private static final String[] RESERVEDWORDS = {"ALL", "ANALYSE", "ANALYZE", "AND", "ANY", "ARRAY", "AS", "ASC", + "ASYMMETRIC", "AUTHID", "BOTH", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "CONSTRAINT", "CREATE", + "CURRENT_CATALOG", "CURRENT_DATE", "CURRENT_ROLE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER", + "DEFAULT", "DEFERRABLE", "DESC", "DISTINCT", "DO", "ELSE", "END", "EXCEPT", "FALSE", "FETCH", "FOR", "FOREIGN", + "FROM", "FUNCTION", "GRANT", "GROUP", "HAVING", "IN", "INITIALLY", "INTERSECT", "INTO", "IS", "LEADING", "LESS", + "LIMIT", "LOCALTIME", "LOCALTIMESTAMP", "MINUS", "MODIFY", "NLSSORT", "NOT", "NULL", "OFFSET", "ON", "ONLY", + "OR", "ORDER", "PERFORMANCE", "PLACING", "PRIMARY", "PROCEDURE", "REFERENCES", "RETURN", "RETURNING", "SELECT", + "SESSION_USER", "SOME", "SPLIT", "SYMMETRIC", "SYSDATE", "TABLE", "THEN", "TO", "TRAILING", "TRUE", "UNION", + "UNIQUE", "USER", "USING", "VARIADIC", "WHEN", "WHERE", "WINDOW", "WITH", "DIAGNOSTICS", "ELSEIF", "ELSIF", + "EXCEPTION", "EXIT", "FORALL", "FOREACH", "GET", "OPEN", "PERFORM", "RAISE", "WHILE", "BUCKETS", "REJECT", + "ADD", "ALTER", "BEGIN", "BETWEEN", "BY", "COLLATION", "COMPRESS", "CONCURRENTLY", "CONNECT", "CROSS", + "CURRENT", "DELETE", "DROP", "FREEZE", "FULL", "IDENTIFIED", "ILIKE", "INCREMENT", "INDEX", "INNER", "INSERT", + "ISNULL", "JOIN", "LEFT", "LEVEL", "LIKE", "LOCK", "NATURAL", "NOTNULL", "NOWAIT", "OF", "OUTER", "OVER", + "OVERLAPS", "PRIVILEGES", "RAW", "RENAME", "RIGHT", "ROWS", "SESSION", "SET", "SIMILAR", "START", "TRIGGER", + "UNTIL", "UPDATE", "VERBOSE", "VIEW"}; + + /** + * Gets the reservedwords.To be accessible only to SQL Syntax + * + * @return the reservedwords + */ + public static final String[] getRESERVEDWORDS() { + + return RESERVEDWORDS.clone(); + } + + /** + * Inits the map. + */ + public static void initMap() { + final int length = RESERVEDWORDS.length; + if (KEYWORDSMAPPER.isEmpty()) { + for (int i = 0; i < length; i++) { + KEYWORDSMAPPER.put(RESERVEDWORDS[i].toLowerCase(Locale.ENGLISH), CONSTVALUE); + } + } + + } + + /** + * Gets the keywords. + * + * @return the keywords + */ + public static HashMap getKeywords() { + + return KEYWORDSMAPPER; + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/SQLTerminalQuerySplit.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/SQLTerminalQuerySplit.java new file mode 100644 index 0000000000000000000000000000000000000000..84fd1597dff1ffc9ddf54c95e07fe9234f7c4da1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/SQLTerminalQuerySplit.java @@ -0,0 +1,368 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.StringUtils; + +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: class Description: The Class SQLTerminalQuerySplit. + * + * @since 3.0.0 + */ +public class SQLTerminalQuerySplit implements IQuerrySplitter { + + private static Map allMatches = new HashMap(1); + + @Override + public void splitQuerries(ArrayList queryArray, String query, boolean isOLAP) + throws DatabaseOperationException { + createSplitQueries(queryArray, query, isOLAP); + + } + + /** + * Gets the replace tag. + * + * @param allMatchMap the all match map + * @param substring the substring + * @return the replace tag + */ + private static String getReplaceTag(Map allMatchMap, String substring) { + String tag = "#S#" + (allMatchMap.size() + 1) + "#E#"; + allMatchMap.put(tag, substring); + return tag; + } + + private static String getInQuoteBack(String qryParam) { + String qry = qryParam; + String grp = null; + Matcher tagMatcher = Pattern.compile("(#Q#\\d+#Q#)").matcher(qryParam); + + while (tagMatcher.find()) { + grp = tagMatcher.group(0); + qry = qry.replace(grp, allMatches.get(grp)); + } + + return qry; + } + + /** + * Gets the comments and quotes back. + * + * @param qryParam the qry param + * @return the comments and quotes back + */ + private static String getCommentsAndQuotesBack(String qryParam) { + String qry = qryParam; + Pattern commantTagPattern = null; + Matcher tagMatcher = null; + String grp = null; + // Modified below taging that will have quotes tag also + + commantTagPattern = Pattern.compile("(#S#\\d+#E#|#Q#\\d+#Q#)"); + tagMatcher = commantTagPattern.matcher(qry); + + boolean isFound = tagMatcher.find(); + while (isFound) { + grp = tagMatcher.group(0); + qry = qry.replace(grp, allMatches.get(grp)); + isFound = tagMatcher.find(); + } + + // Pass 2: To handle Single-line comment within Multi-line comment + tagMatcher = commantTagPattern.matcher(qry); + isFound = tagMatcher.find(); + if (!isFound) { + return qry; + } + // Still more items to match. + // As per design only 2 level comments handling is possible. + while (isFound) { + grp = tagMatcher.group(0); + qry = qry.replace(grp, allMatches.get(grp)); + isFound = tagMatcher.find(); + } + // Pass 3: to hand nested quotes + tagMatcher = commantTagPattern.matcher(qry); + isFound = tagMatcher.find(); + // Still more item to match + // As per design only 3 level quotes handling is possible. + while (isFound) { + grp = tagMatcher.group(0); + qry = qry.replace(grp, allMatches.get(grp)); + isFound = tagMatcher.find(); + } + + return qry; + } + + /** + * Adds the token to qry arr. + * + * @param tokenStr the token str + * @param queryArray the query array + */ + private static void addTokenToQryArr(String tokenStr, ArrayList queryArray) { + if (!(MPPDBIDEConstants.LINE_SEPARATOR.equals(tokenStr))) { + if (!("".equals(tokenStr))) { + if (!(" ".equals(tokenStr))) { + queryArray.add(getCommentsAndQuotesBack(tokenStr)); + } + } + } + } + + /** + * Seperate SQL and PLSQL. + * + * @param queryArray the query array + * @param splitArray the split array + */ + private static void seperateSQLAndPLSQL(ArrayList queryArray, String[] splitArray) { + Pattern pattern1 = Pattern + .compile("(?i)CREATE\\s+FUNCTION|CREATE\\s+OR\\s+REPLACE\\s+FUNCTION|CREATE\\s+PROCEDURE|" + + "CREATE\\s+PACKAGE|CREATE\\s+OR\\s+REPLACE\\s+PACKAGE|" + + "CREATE\\s+OR\\s+REPLACE\\s+PROCEDURE|CREATE\\s+TRIGGER|" + + "CREATE\\s+OR\\s+REPLACE\\s+TRIGGER|(? queryArray, String[] splitArray, StringBuffer strBuffer, + int cnt) { + int count = cnt; + int index = count; + if (splitArray.length > 1) { + do { + count++; + if (count != splitArray.length - 1 || !splitArray[splitArray.length - 1].trim().isEmpty()) { + strBuffer.append(splitArray[count]).append(";"); + } + index++; + + } while (index < splitArray.length - 1); + } + if (strBuffer.toString().trim().endsWith(';' + MPPDBIDEConstants.LINE_SEPARATOR + ';')) { + strBuffer.deleteCharAt(strBuffer.length() - 1); + } + queryArray.add(getCommentsAndQuotesBack(strBuffer.toString())); + return count; + } + + private static boolean isAllTextCommented(String tokenStr) { + String[] eachLineArr = tokenStr.split(EnvirnmentVariableValidator.validateAndGetLineSeperator()); + + boolean isAllCommented = true; + + String eachLineTrim = null; + + for (String eachLine : eachLineArr) { + + eachLineTrim = StringUtils.trimToEmpty(eachLine); + + if (!StringUtils.isBlank(eachLineTrim) && !eachLineTrim.startsWith("--")) { + isAllCommented = false; + break; + } + } + return isAllCommented; + } + + /** + * Creates the split queries. + * + * @param queryArray the query array + * @param query the query + * @throws DatabaseOperationException the database operation exception + */ + private static void createSplitQueries(ArrayList queryArray, String query, boolean isOLAP) + throws DatabaseOperationException { + if (query.length() > MPPDBIDEConstants.SQL_TERMINAL_LOAD_MAXIMUM) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_QUERY_LENGTH_TOO_BIG)); + throw new DatabaseOperationException( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_QUERY_LENGTH_TOO_BIG)); + } + allMatches.clear(); + String[] splitBySlash = query.split("\\s*\\t*" + MPPDBIDEConstants.LINE_SEPARATOR + "\\/\\s*\\t*" + + MPPDBIDEConstants.LINE_SEPARATOR + "(?=([^\"]*\"[^\"]*\")*[^\"]*$)"); + + int length = splitBySlash.length; + String replacedString = null; + for (int jindex = 0; jindex < length; jindex++) { + String[] splitArray = null; + // Patter to check whether line starts from create function or + // procedure + Pattern pattern1 = Pattern + .compile("(?i)CREATE\\s+FUNCTION|CREATE\\s+OR\\s+REPLACE\\s+FUNCTION|CREATE\\s+PROCEDURE|" + + "CREATE\\s+PACKAGE|CREATE\\s+OR\\s+REPLACE\\s+PACKAGE|" + + "CREATE\\s+OR\\s+REPLACE\\s+PROCEDURE|CREATE\\s+TRIGGER|" + + "CREATE\\s+OR\\s+REPLACE\\s+TRIGGER|DECLARE|BEGIN"); + + splitQueryForCommentsOLAP(splitBySlash, jindex); + + StringBuffer quotesBuffer = splitQueryForquotes(splitBySlash[jindex]); + splitBySlash[jindex] = quotesBuffer.toString(); + + // modified below code for quotes + StringBuffer nestedBuffer = splitQueryForMultipleComments(splitBySlash, jindex); + splitBySlash[jindex] = nestedBuffer.toString(); + replacedString = splitBySlash[jindex]; + if (replacedString.startsWith(pattern1.pattern())) { + queryArray.add(getCommentsAndQuotesBack(splitBySlash[jindex])); + } else { + splitArray = replacedString.split(";"); + seperateSQLAndPLSQL(queryArray, splitArray); + } + } + } + + private static StringBuffer splitQueryForComments(StringBuffer commentInQuoteBuffer) { + /* + * Modified to address below issue for comment regular expression -- -- + * Name: test123 Type: TABLE Schema: public Owner: - -- * + */ + Matcher matcher = Pattern.compile("(?m)(--.*?(" + MPPDBIDEConstants.LINE_SEPARATOR + "|$)|\\/\\*.*?\\*\\/)") + .matcher(commentInQuoteBuffer); + StringBuffer commentBuffer = new StringBuffer(commentInQuoteBuffer.toString()); + int commentOffset = 0; + while (matcher.find()) { + String originalStr = commentInQuoteBuffer.substring(matcher.start(), matcher.end()); + String replaceTag = getReplaceTag(allMatches, originalStr); + commentBuffer.replace(matcher.start() + commentOffset, matcher.end() + commentOffset, replaceTag); + commentOffset = commentOffset + (replaceTag.length() - originalStr.length()); + } + return commentBuffer; + } + + private static void splitQueryForCommentsOLAP(String[] splitBySlash, int jindex) { + + /* + * Added to address below issue for combating SQL injection through + * column level comments COMMENT ON COLUMN emp0066.mgrno IS 'This column + * ' '; drop table dsuser.tab4; --'; + */ + Matcher m1 = Pattern + .compile("('(.*?)--(.*?)(? allMatchMap, String substring) { + String tag = "#Q#" + (allMatchMap.size() + 1) + "#Q#"; + allMatchMap.put(tag, substring); + return tag; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/SSLUtility.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/SSLUtility.java new file mode 100644 index 0000000000000000000000000000000000000000..08ee3dd964243be48a5b53cff20e4635cc19eb0e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/SSLUtility.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +import java.util.HashMap; +import java.util.Map; + +/** + * + * Title: class + * + * Description: The Class SSLUtility. + * + * @since 3.0.0 + */ +public final class SSLUtility { + private static Map sslConnectionMap = new HashMap( + MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + + /** + * Instantiates a new SSL utility. + */ + private SSLUtility() { + + } + + /** + * Put SSL login status. + * + * @param key the key + * @param value the value + */ + public static void putSSLLoginStatus(String key, Boolean value) { + sslConnectionMap.put(key, value); + } + + /** + * Gets the status. + * + * @param key the key + * @return the status + */ + public static boolean getStatus(String key) { + if (!sslConnectionMap.containsKey(key)) { + return false; + } + return sslConnectionMap.get(key); + } + + /** + * Removes the SSL login status. + * + * @param key the key + * @return true, if successful + */ + public static boolean removeSSLLoginStatus(String key) { + + if (sslConnectionMap.containsKey(key)) { + return sslConnectionMap.remove(key); + } + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/SelectVisitorWrap.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/SelectVisitorWrap.java new file mode 100644 index 0000000000000000000000000000000000000000..2928335167665c1513ee12d25400451549306d5e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/SelectVisitorWrap.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +import net.sf.jsqlparser.statement.select.PlainSelect; +import net.sf.jsqlparser.statement.select.SelectVisitor; +import net.sf.jsqlparser.statement.select.SetOperationList; +import net.sf.jsqlparser.statement.select.WithItem; +import net.sf.jsqlparser.statement.values.ValuesStatement; + +/** + * + * Title: class + * + * Description: The Class SelectVisitorWrap. + * + * @since 3.0.0 + */ +public class SelectVisitorWrap implements SelectVisitor { + + private boolean hasSetOperations = false; + + /** + * Checks for set operations. + * + * @return true, if successful + */ + public boolean hasSetOperations() { + return this.hasSetOperations; + } + + @Override + public void visit(PlainSelect arg0) { + } + + @Override + public void visit(SetOperationList arg0) { + this.hasSetOperations = true; + } + + @Override + public void visit(WithItem arg0) { + } + + @Override + public void visit(ValuesStatement aThis) { + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/SynonymConstants.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/SynonymConstants.java new file mode 100644 index 0000000000000000000000000000000000000000..81e83e830d972608ace594ce5e6784df6bf2f7e9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/SynonymConstants.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +/** + * + * Title: Class + * + * Description: The Class SynonymConstants. + * + * @since 3.0.0 + */ +public interface SynonymConstants { + String OWNER = "OWNER"; + String SYNONYM_NAME = "SYNONYM_NAME"; + String TABLE_OWNER = "TABLE_OWNER"; + String TABLE_NAME = "TABLE_NAME"; + String SYN_NAME = "synonym_name"; + String OWN_NAME = "table_owner"; + String SCHEMA_NAME = "schema_name"; + String TAB_NAME = "table_name"; + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/TablesNamesFinderAdapter.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/TablesNamesFinderAdapter.java new file mode 100644 index 0000000000000000000000000000000000000000..2315c8d46c6df453cf141f25abfb7aff8720416e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/TablesNamesFinderAdapter.java @@ -0,0 +1,1061 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import net.sf.jsqlparser.expression.AllComparisonExpression; +import net.sf.jsqlparser.expression.AnalyticExpression; +import net.sf.jsqlparser.expression.AnyComparisonExpression; +import net.sf.jsqlparser.expression.ArrayExpression; +import net.sf.jsqlparser.expression.BinaryExpression; +import net.sf.jsqlparser.expression.CaseExpression; +import net.sf.jsqlparser.expression.CastExpression; +import net.sf.jsqlparser.expression.CollateExpression; +import net.sf.jsqlparser.expression.DateTimeLiteralExpression; +import net.sf.jsqlparser.expression.DateValue; +import net.sf.jsqlparser.expression.DoubleValue; +import net.sf.jsqlparser.expression.Expression; +import net.sf.jsqlparser.expression.ExpressionVisitor; +import net.sf.jsqlparser.expression.ExtractExpression; +import net.sf.jsqlparser.expression.Function; +import net.sf.jsqlparser.expression.HexValue; +import net.sf.jsqlparser.expression.IntervalExpression; +import net.sf.jsqlparser.expression.JdbcNamedParameter; +import net.sf.jsqlparser.expression.JdbcParameter; +import net.sf.jsqlparser.expression.JsonExpression; +import net.sf.jsqlparser.expression.KeepExpression; +import net.sf.jsqlparser.expression.LongValue; +import net.sf.jsqlparser.expression.MySQLGroupConcat; +import net.sf.jsqlparser.expression.NextValExpression; +import net.sf.jsqlparser.expression.NotExpression; +import net.sf.jsqlparser.expression.NullValue; +import net.sf.jsqlparser.expression.NumericBind; +import net.sf.jsqlparser.expression.OracleHierarchicalExpression; +import net.sf.jsqlparser.expression.OracleHint; +import net.sf.jsqlparser.expression.Parenthesis; +import net.sf.jsqlparser.expression.RowConstructor; +import net.sf.jsqlparser.expression.SignedExpression; +import net.sf.jsqlparser.expression.StringValue; +import net.sf.jsqlparser.expression.TimeKeyExpression; +import net.sf.jsqlparser.expression.TimeValue; +import net.sf.jsqlparser.expression.TimestampValue; +import net.sf.jsqlparser.expression.UserVariable; +import net.sf.jsqlparser.expression.ValueListExpression; +import net.sf.jsqlparser.expression.WhenClause; +import net.sf.jsqlparser.expression.operators.arithmetic.Addition; +import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseAnd; +import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseLeftShift; +import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseOr; +import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseRightShift; +import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseXor; +import net.sf.jsqlparser.expression.operators.arithmetic.Concat; +import net.sf.jsqlparser.expression.operators.arithmetic.Division; +import net.sf.jsqlparser.expression.operators.arithmetic.IntegerDivision; +import net.sf.jsqlparser.expression.operators.arithmetic.Modulo; +import net.sf.jsqlparser.expression.operators.arithmetic.Multiplication; +import net.sf.jsqlparser.expression.operators.arithmetic.Subtraction; +import net.sf.jsqlparser.expression.operators.conditional.AndExpression; +import net.sf.jsqlparser.expression.operators.conditional.OrExpression; +import net.sf.jsqlparser.expression.operators.relational.Between; +import net.sf.jsqlparser.expression.operators.relational.EqualsTo; +import net.sf.jsqlparser.expression.operators.relational.ExistsExpression; +import net.sf.jsqlparser.expression.operators.relational.ExpressionList; +import net.sf.jsqlparser.expression.operators.relational.FullTextSearch; +import net.sf.jsqlparser.expression.operators.relational.GreaterThan; +import net.sf.jsqlparser.expression.operators.relational.GreaterThanEquals; +import net.sf.jsqlparser.expression.operators.relational.InExpression; +import net.sf.jsqlparser.expression.operators.relational.IsBooleanExpression; +import net.sf.jsqlparser.expression.operators.relational.IsNullExpression; +import net.sf.jsqlparser.expression.operators.relational.ItemsListVisitor; +import net.sf.jsqlparser.expression.operators.relational.JsonOperator; +import net.sf.jsqlparser.expression.operators.relational.LikeExpression; +import net.sf.jsqlparser.expression.operators.relational.Matches; +import net.sf.jsqlparser.expression.operators.relational.MinorThan; +import net.sf.jsqlparser.expression.operators.relational.MinorThanEquals; +import net.sf.jsqlparser.expression.operators.relational.MultiExpressionList; +import net.sf.jsqlparser.expression.operators.relational.NamedExpressionList; +import net.sf.jsqlparser.expression.operators.relational.NotEqualsTo; +import net.sf.jsqlparser.expression.operators.relational.RegExpMatchOperator; +import net.sf.jsqlparser.expression.operators.relational.RegExpMySQLOperator; +import net.sf.jsqlparser.expression.operators.relational.SimilarToExpression; +import net.sf.jsqlparser.schema.Column; +import net.sf.jsqlparser.schema.Table; +import net.sf.jsqlparser.statement.Block; +import net.sf.jsqlparser.statement.Commit; +import net.sf.jsqlparser.statement.CreateFunctionalStatement; +import net.sf.jsqlparser.statement.DeclareStatement; +import net.sf.jsqlparser.statement.DescribeStatement; +import net.sf.jsqlparser.statement.ExplainStatement; +import net.sf.jsqlparser.statement.SetStatement; +import net.sf.jsqlparser.statement.ShowColumnsStatement; +import net.sf.jsqlparser.statement.ShowStatement; +import net.sf.jsqlparser.statement.Statement; +import net.sf.jsqlparser.statement.StatementVisitor; +import net.sf.jsqlparser.statement.Statements; +import net.sf.jsqlparser.statement.UseStatement; +import net.sf.jsqlparser.statement.alter.Alter; +import net.sf.jsqlparser.statement.alter.sequence.AlterSequence; +import net.sf.jsqlparser.statement.comment.Comment; +import net.sf.jsqlparser.statement.create.index.CreateIndex; +import net.sf.jsqlparser.statement.create.schema.CreateSchema; +import net.sf.jsqlparser.statement.create.sequence.CreateSequence; +import net.sf.jsqlparser.statement.create.table.CreateTable; +import net.sf.jsqlparser.statement.create.view.AlterView; +import net.sf.jsqlparser.statement.create.view.CreateView; +import net.sf.jsqlparser.statement.delete.Delete; +import net.sf.jsqlparser.statement.drop.Drop; +import net.sf.jsqlparser.statement.execute.Execute; +import net.sf.jsqlparser.statement.grant.Grant; +import net.sf.jsqlparser.statement.insert.Insert; +import net.sf.jsqlparser.statement.merge.Merge; +import net.sf.jsqlparser.statement.replace.Replace; +import net.sf.jsqlparser.statement.select.AllColumns; +import net.sf.jsqlparser.statement.select.AllTableColumns; +import net.sf.jsqlparser.statement.select.FromItemVisitor; +import net.sf.jsqlparser.statement.select.Join; +import net.sf.jsqlparser.statement.select.LateralSubSelect; +import net.sf.jsqlparser.statement.select.ParenthesisFromItem; +import net.sf.jsqlparser.statement.select.PlainSelect; +import net.sf.jsqlparser.statement.select.Select; +import net.sf.jsqlparser.statement.select.SelectBody; +import net.sf.jsqlparser.statement.select.SelectExpressionItem; +import net.sf.jsqlparser.statement.select.SelectItem; +import net.sf.jsqlparser.statement.select.SelectItemVisitor; +import net.sf.jsqlparser.statement.select.SelectVisitor; +import net.sf.jsqlparser.statement.select.SetOperationList; +import net.sf.jsqlparser.statement.select.SubJoin; +import net.sf.jsqlparser.statement.select.SubSelect; +import net.sf.jsqlparser.statement.select.TableFunction; +import net.sf.jsqlparser.statement.select.ValuesList; +import net.sf.jsqlparser.statement.select.WithItem; +import net.sf.jsqlparser.statement.truncate.Truncate; +import net.sf.jsqlparser.statement.update.Update; +import net.sf.jsqlparser.statement.upsert.Upsert; +import net.sf.jsqlparser.statement.values.ValuesStatement; + +/** + * + * Title: class + * + * Description: The Class TablesNamesFinderAdapter. + * + * @since 3.0.0 + */ +public class TablesNamesFinderAdapter implements SelectVisitor, FromItemVisitor, ExpressionVisitor, ItemsListVisitor, + SelectItemVisitor, StatementVisitor { + + private List tablesList; + private boolean allowColumnProcessing = false; + private boolean isSelectFromFunction = false; + private boolean isJoinExists = false; + + /** + * There are some special names which are not tables but parsed as + * tables.Those names will be collected here and excluded from tablesList + * -names anymore + */ + private List otherItemNamesList; + + /** + * Gets the table list. + * + * @param ps the ps + * @return the table list + */ + public List getTableList(PlainSelect ps) { + collectTables(ps); + return tablesList; + } + + /** + * Gets the table list. + * + * @param statement the statement + * @return the table list + */ + public List getTableList(Statement statement) { + init(false); + statement.accept(this); + return tablesList; + } + + /** + * Collect tables. + * + * @param ps the ps + */ + private void collectTables(PlainSelect ps) { + init(false); + if (checkForObjectNull(ps.getFromItem())) { + ps.getFromItem().accept(this); + } + List joins = ps.getJoins(); + if (joins != null) { + this.isJoinExists = true; + for (Join j : joins) { + j.getRightItem().accept(this); + } + } + } + + /** + * Check for object null. + * + * @param obj the obj + * @return true, if successful + */ + private boolean checkForObjectNull(Object obj) { + return obj != null; + } + + /** + * Checks if is select from function. + * + * @return true, if is select from function + */ + public boolean isSelectFromFunction() { + return this.isSelectFromFunction; + } + + /** + * Checks if is join exists. + * + * @return true, if is join exists + */ + public boolean isJoinExists() { + return this.isJoinExists; + } + + @Override + public void visit(WithItem withItm) { + otherItemNamesList.add(withItm.getName().toLowerCase(Locale.ENGLISH)); + withItm.getSelectBody().accept(this); + } + + @Override + public void visit(PlainSelect plnSelect) { + if (checkForObjectNull(plnSelect.getSelectItems())) { + for (SelectItem selectedItem : plnSelect.getSelectItems()) { + selectedItem.accept(this); + } + } + + if (checkForObjectNull(plnSelect.getFromItem())) { + plnSelect.getFromItem().accept(this); + } + + if (checkForObjectNull(plnSelect.getJoins())) { + getJoinItem(plnSelect); + } + if (checkForObjectNull(plnSelect.getWhere())) { + plnSelect.getWhere().accept(this); + } + + if (checkForObjectNull(plnSelect.getHaving())) { + plnSelect.getHaving().accept(this); + } + + if (checkForObjectNull(plnSelect.getOracleHierarchical())) { + plnSelect.getOracleHierarchical().accept(this); + } + } + + /** + * Gets the join item. + * + * @param plnSelect the pln select + * @return the join item + */ + private void getJoinItem(PlainSelect plnSelect) { + for (Join joinItm : plnSelect.getJoins()) { + joinItm.getRightItem().accept(this); + } + } + + /** + * Override to adapt the tableName generation (e.g. with / without schema). + * + * @param table the table + * @return the string + */ + protected String extractTableName(Table table) { + return table.getFullyQualifiedName(); + } + + @Override + public void visit(Table tableNme) { + String tableCompleteName = extractTableName(tableNme); + if (validateTable(tableCompleteName)) { + tablesList.add(tableCompleteName); + } + } + + /** + * Validate table. + * + * @param tableCompleteName the table complete name + * @return true, if successful + */ + private boolean validateTable(String tableCompleteName) { + return !otherItemNamesList.contains(tableCompleteName.toLowerCase(Locale.ENGLISH)) + && !tablesList.contains(tableCompleteName); + } + + @Override + public void visit(SubSelect subSelect) { + if (subSelect.getWithItemsList() != null) { + getWithItem(subSelect); + } + subSelect.getSelectBody().accept(this); + } + + /** + * Gets the with item. + * + * @param subSelect the sub select + * @return the with item + */ + private void getWithItem(SubSelect subSelect) { + for (WithItem withItm : subSelect.getWithItemsList()) { + withItm.accept(this); + } + } + + @Override + public void visit(Addition addition) { + visitBinaryExpression(addition); + } + + @Override + public void visit(AndExpression andExpression) { + visitBinaryExpression(andExpression); + } + + @Override + public void visit(Between betn) { + betn.getLeftExpression().accept(this); + betn.getBetweenExpressionStart().accept(this); + betn.getBetweenExpressionEnd().accept(this); + } + + @Override + public void visit(Column tblColumn) { + if (validateColumn(tblColumn)) { + visit(tblColumn.getTable()); + } + } + + /** + * Validate column. + * + * @param tblColumn the tbl column + * @return true, if successful + */ + private boolean validateColumn(Column tblColumn) { + return allowColumnProcessing && tblColumn.getTable() != null && tblColumn.getTable().getName() != null; + } + + @Override + public void visit(Division divn) { + visitBinaryExpression(divn); + } + + @Override + public void visit(DoubleValue doubleValue) { + } + + @Override + public void visit(EqualsTo equalsTo) { + visitBinaryExpression(equalsTo); + } + + @Override + public void visit(Function func) { + ExpressionList expressionList = func.getParameters(); + if (expressionList != null) { + visit(expressionList); + } + } + + @Override + public void visit(GreaterThan greaterThan) { + visitBinaryExpression(greaterThan); + } + + @Override + public void visit(GreaterThanEquals greaterThanEquals) { + visitBinaryExpression(greaterThanEquals); + } + + @Override + public void visit(InExpression inExpressn) { + visitLeftExpression(inExpressn); + inExpressn.getRightItemsList().accept(this); + } + + /** + * Visit left expression. + * + * @param inExpressn the in expressn + */ + private void visitLeftExpression(InExpression inExpressn) { + if (inExpressn.getLeftExpression() != null) { + inExpressn.getLeftExpression().accept(this); + } else if (inExpressn.getLeftItemsList() != null) { + inExpressn.getLeftItemsList().accept(this); + } + } + + @Override + public void visit(SignedExpression signedExpression) { + signedExpression.getExpression().accept(this); + } + + @Override + public void visit(IsNullExpression isNullExpression) { + return; + } + + @Override + public void visit(JdbcParameter jdbcParameter) { + return; + } + + @Override + public void visit(LikeExpression likeExpression) { + visitBinaryExpression(likeExpression); + } + + @Override + public void visit(ExistsExpression existsExpression) { + existsExpression.getRightExpression().accept(this); + } + + @Override + public void visit(LongValue longValue) { + return; + } + + @Override + public void visit(MinorThan minorThan) { + visitBinaryExpression(minorThan); + } + + @Override + public void visit(MinorThanEquals minorThanEquals) { + visitBinaryExpression(minorThanEquals); + } + + @Override + public void visit(Multiplication multiplication) { + visitBinaryExpression(multiplication); + } + + @Override + public void visit(NotEqualsTo notEqualsTo) { + visitBinaryExpression(notEqualsTo); + } + + @Override + public void visit(NullValue nullValue) { + return; + } + + @Override + public void visit(OrExpression orExpression) { + visitBinaryExpression(orExpression); + } + + @Override + public void visit(Parenthesis parenthesis) { + parenthesis.getExpression().accept(this); + } + + @Override + public void visit(StringValue stringValue) { + return; + } + + @Override + public void visit(Subtraction subtraction) { + visitBinaryExpression(subtraction); + } + + @Override + public void visit(NotExpression notExpr) { + notExpr.getExpression().accept(this); + } + + /** + * Visit binary expression. + * + * @param binaryExpressn the binary expressn + */ + public void visitBinaryExpression(BinaryExpression binaryExpressn) { + binaryExpressn.getLeftExpression().accept(this); + binaryExpressn.getRightExpression().accept(this); + } + + @Override + public void visit(ExpressionList expressnList) { + for (Expression expressn : expressnList.getExpressions()) { + expressn.accept(this); + } + } + + @Override + public void visit(DateValue dateValue) { + return; + } + + @Override + public void visit(TimestampValue timestampValue) { + return; + } + + @Override + public void visit(TimeValue timeValue) { + return; + } + + /** + * Visit. + * + * @param caseExpressn the case expressn + */ + @Override + public void visit(CaseExpression caseExpressn) { + visitSwitchExpression(caseExpressn); + visitWhenClauseExpression(caseExpressn); + visitCaseExpression(caseExpressn); + } + + /** + * Visit case expression. + * + * @param caseExpressn the case expressn + */ + private void visitCaseExpression(CaseExpression caseExpressn) { + if (caseExpressn.getElseExpression() != null) { + caseExpressn.getElseExpression().accept(this); + } + } + + /** + * Visit when clause expression. + * + * @param caseExpressn the case expressn + */ + private void visitWhenClauseExpression(CaseExpression caseExpressn) { + if (caseExpressn.getWhenClauses() != null) { + for (Expression when : caseExpressn.getWhenClauses()) { + when.accept(this); + } + } + } + + /** + * Visit switch expression. + * + * @param caseExpressn the case expressn + */ + private void visitSwitchExpression(CaseExpression caseExpressn) { + if (caseExpressn.getSwitchExpression() != null) { + caseExpressn.getSwitchExpression().accept(this); + } + } + + /** + * Visit. + * + * @param whenClause the when clause + * net.sf.jsqlparser.expression.ExpressionVisitor#visit(net.sf.jsqlparser. + * expression.WhenClause) + */ + @Override + public void visit(WhenClause whenClause) { + if (whenClause.getWhenExpression() != null) { + whenClause.getWhenExpression().accept(this); + } + if (whenClause.getThenExpression() != null) { + whenClause.getThenExpression().accept(this); + } + } + + @Override + public void visit(AllComparisonExpression allComparisonExpression) { + allComparisonExpression.getSubSelect().getSelectBody().accept(this); + } + + @Override + public void visit(AnyComparisonExpression anyComparisonExpression) { + anyComparisonExpression.getSubSelect().getSelectBody().accept(this); + } + + @Override + public void visit(SubJoin subjoin) { + subjoin.getLeft().accept(this); + this.isJoinExists = true; + } + + @Override + public void visit(Concat concat) { + visitBinaryExpression(concat); + } + + @Override + public void visit(Matches matches) { + visitBinaryExpression(matches); + } + + @Override + public void visit(BitwiseAnd bitwiseAnd) { + visitBinaryExpression(bitwiseAnd); + } + + @Override + public void visit(BitwiseOr bitwiseOr) { + visitBinaryExpression(bitwiseOr); + } + + @Override + public void visit(BitwiseXor bitwiseXor) { + visitBinaryExpression(bitwiseXor); + } + + @Override + public void visit(CastExpression cast) { + cast.getLeftExpression().accept(this); + } + + @Override + public void visit(Modulo modulo) { + visitBinaryExpression(modulo); + } + + @Override + public void visit(AnalyticExpression analytic) { + return; + } + + @Override + public void visit(SetOperationList opernlist) { + for (SelectBody plnSelect : opernlist.getSelects()) { + plnSelect.accept(this); + } + } + + @Override + public void visit(ExtractExpression eexpr) { + return; + } + + @Override + public void visit(LateralSubSelect lateralSubSelect) { + lateralSubSelect.getSubSelect().getSelectBody().accept(this); + } + + @Override + public void visit(MultiExpressionList multiExprnList) { + for (ExpressionList exprnList : multiExprnList.getExprList()) { + exprnList.accept(this); + } + } + + @Override + public void visit(ValuesList valuesList) { + return; + } + + /** + * Initializes table names collector. Important is the usage of Column + * instances to find table names. This is only allowed for expression + * parsing, where a better place for tablenames could not be there. For + * complete statements only from items are used to avoid some alias as + * tablenames. + * + * @param allowColProcessing the allow col processing + */ + protected void init(boolean allowColProcessing) { + otherItemNamesList = new ArrayList(); + tablesList = new ArrayList(); + this.allowColumnProcessing = allowColProcessing; + } + + @Override + public void visit(IntervalExpression iexpr) { + return; + } + + @Override + public void visit(JdbcNamedParameter jdbcNamedParameter) { + return; + } + + @Override + public void visit(OracleHierarchicalExpression oracleexpr) { + if (oracleexpr.getStartExpression() != null) { + oracleexpr.getStartExpression().accept(this); + } + + if (oracleexpr.getConnectExpression() != null) { + oracleexpr.getConnectExpression().accept(this); + } + } + + @Override + public void visit(RegExpMatchOperator regexpr) { + visitBinaryExpression(regexpr); + } + + @Override + public void visit(RegExpMySQLOperator regexpr) { + visitBinaryExpression(regexpr); + } + + @Override + public void visit(JsonExpression jsonExpr) { + return; + } + + @Override + public void visit(JsonOperator jsonExpr) { + return; + } + + @Override + public void visit(AllColumns allColumns) { + return; + } + + @Override + public void visit(AllTableColumns allTableColumns) { + } + + @Override + public void visit(SelectExpressionItem expressionItem) { + expressionItem.getExpression().accept(this); + } + + @Override + public void visit(UserVariable var) { + return; + } + + @Override + public void visit(NumericBind bind) { + return; + } + + @Override + public void visit(KeepExpression aexpr) { + return; + } + + @Override + public void visit(MySQLGroupConcat groupConcat) { + } + + @Override + public void visit(RowConstructor rowConstructor) { + for (Expression expression : rowConstructor.getExprList().getExpressions()) { + expression.accept(this); + } + } + + @Override + public void visit(HexValue hexValue) { + return; + } + + @Override + public void visit(OracleHint hint) { + } + + @Override + public void visit(TableFunction valuesList) { + this.isSelectFromFunction = true; + } + + @Override + public void visit(TimeKeyExpression arg0) { + return; + } + + @Override + public void visit(DateTimeLiteralExpression arg0) { + return; + } + + @Override + public void visit(BitwiseRightShift arg0) { + return; + } + + @Override + public void visit(BitwiseLeftShift arg0) { + return; + } + + @Override + public void visit(ValueListExpression arg0) { + return; + } + + @Override + public void visit(ParenthesisFromItem arg0) { + return; + } + + @Override + public void visit(Commit arg0) { + return; + } + + @Override + public void visit(Delete delete) { + tablesList.add(delete.getTable().getName()); + if (delete.getWhere() != null) { + delete.getWhere().accept(this); + } + } + + @Override + public void visit(Update update) { + + tablesList.add(update.getTable().getName()); + if (update.getExpressions() != null) { + for (Expression expression : update.getExpressions()) { + expression.accept(this); + } + } + + if (update.getFromItem() != null) { + update.getFromItem().accept(this); + } + + if (update.getJoins() != null) { + for (Join join : update.getJoins()) { + join.getRightItem().accept(this); + } + } + + if (update.getWhere() != null) { + update.getWhere().accept(this); + } + + } + + @Override + public void visit(Insert insert) { + + tablesList.add(insert.getTable().getName()); + if (insert.getItemsList() != null) { + insert.getItemsList().accept(this); + } + if (insert.getSelect() != null) { + visit(insert.getSelect()); + } + + } + + @Override + public void visit(Replace replace) { + tablesList.add(replace.getTable().getName()); + if (replace.getExpressions() != null) { + for (Expression expression : replace.getExpressions()) { + expression.accept(this); + } + } + if (replace.getItemsList() != null) { + replace.getItemsList().accept(this); + } + + } + + @Override + public void visit(Drop arg0) { + return; + } + + @Override + public void visit(Truncate arg0) { + return; + } + + @Override + public void visit(CreateIndex arg0) { + return; + } + + @Override + public void visit(CreateTable create) { + tablesList.add(create.getTable().getFullyQualifiedName()); + if (create.getSelect() != null) { + create.getSelect().accept(this); + } + + } + + @Override + public void visit(CreateView arg0) { + return; + } + + @Override + public void visit(AlterView arg0) { + return; + } + + @Override + public void visit(Alter arg0) { + return; + } + + @Override + public void visit(Statements arg0) { + return; + } + + @Override + public void visit(Execute arg0) { + return; + } + + @Override + public void visit(SetStatement arg0) { + return; + } + + @Override + public void visit(Merge arg0) { + return; + } + + @Override + public void visit(Select arg0) { + return; + } + + @Override + public void visit(Upsert arg0) { + return; + } + + @Override + public void visit(UseStatement arg0) { + return; + } + + /** + * . + * + * @param ps the ps + * @return the table list + */ + public List getTableList(Table ps) { + init(false); + ps.accept(this); + return tablesList; + } + + @Override + public void visit(Comment comment) { + } + + @Override + public void visit(CreateSchema aThis) { + } + + @Override + public void visit(ShowColumnsStatement set) { + } + + @Override + public void visit(Block block) { + } + + @Override + public void visit(DescribeStatement describe) { + } + + @Override + public void visit(ExplainStatement aThis) { + } + + @Override + public void visit(ShowStatement aThis) { + } + + @Override + public void visit(DeclareStatement aThis) { + } + + @Override + public void visit(Grant grant) { + } + + @Override + public void visit(CreateSequence createSequence) { + } + + @Override + public void visit(AlterSequence alterSequence) { + } + + @Override + public void visit(CreateFunctionalStatement createFunctionalStatement) { + } + + @Override + public void visit(NamedExpressionList namedExpressionList) { + } + + @Override + public void visit(IntegerDivision division) { + } + + @Override + public void visit(FullTextSearch fullTextSearch) { + } + + @Override + public void visit(IsBooleanExpression isBooleanExpression) { + } + + @Override + public void visit(NextValExpression aThis) { + } + + @Override + public void visit(CollateExpression aThis) { + } + + @Override + public void visit(SimilarToExpression aThis) { + } + + @Override + public void visit(ArrayExpression aThis) { + } + + @Override + public void visit(ValuesStatement aThis) { + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/connectionprofileversion/IConnectionProfileVersions.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/connectionprofileversion/IConnectionProfileVersions.java new file mode 100644 index 0000000000000000000000000000000000000000..00ba111c6e65fbe5dbbefbf38597545100fabcf3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/connectionprofileversion/IConnectionProfileVersions.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.connectionprofileversion; + +/** + * Title: IConnectionProfileVersions + * + * Description: The Interface IConnectionProfileVersions + * + * @since 3.0.0 + */ +public interface IConnectionProfileVersions { + + /** + * The connection profile first version. + */ + String CONNECTION_PROFILE_FIRST_VERSION = "1.00"; + + /** + * The connection profile second version. Restructuring of the json + * structure of all the profiles that was used in version 1.00.Each tab + * information is now under the tab root element + */ + String CONNECTION_PROFILE_SECOND_VERSION = "2.00"; + + /** + * The connection profile current version. + */ + String CONNECTION_PROFILE_CURRENT_VERSION = CONNECTION_PROFILE_SECOND_VERSION; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/DataStudioSecurityException.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/DataStudioSecurityException.java new file mode 100644 index 0000000000000000000000000000000000000000..fe689fce2ad39e24f8b2f9ea2e99d4be741dbd82 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/DataStudioSecurityException.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.exceptions; + +/** + * + * Title: class + * + * Description: The Class DataStudioSecurityException. + * + * @since 3.0.0 + */ +public class DataStudioSecurityException extends MPPDBIDEException { + + private static final long serialVersionUID = 1252806867923069413L; + + /** + * Instantiates a new data studio security exception. + * + * @param dbErrorMessageCode the db error message code + * @param exception the exception + */ + public DataStudioSecurityException(String dbErrorMessageCode, Exception exception) { + super(dbErrorMessageCode, exception); + } + + /** + * Instantiates a new data studio security exception. + * + * @param dbErrorMessageCode the db error message code + */ + public DataStudioSecurityException(String dbErrorMessageCode) { + super(dbErrorMessageCode); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/DatabaseCriticalException.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/DatabaseCriticalException.java new file mode 100644 index 0000000000000000000000000000000000000000..86d60273ba5164a41162975fb96e7a217144074a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/DatabaseCriticalException.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.exceptions; + +/** + * + * Title: class + * + * Description: The Class DatabaseCriticalException. + * + * @since 3.0.0 + */ +public class DatabaseCriticalException extends MPPDBIDEException { + + private static final long serialVersionUID = -3171277120266665426L; + + /** + * Instantiates a new database critical exception. + * + * @param dbErrorMessageCode the db error message code + * @param exception the exception + */ + public DatabaseCriticalException(String dbErrorMessageCode, Exception exception) { + super(dbErrorMessageCode, exception); + } + + /** + * Instantiates a new database critical exception. + * + * @param dbErrorMessageCode the db error message code + */ + public DatabaseCriticalException(String dbErrorMessageCode) { + super(dbErrorMessageCode); + setServerMessage(dbErrorMessageCode); + } + + /** + * Instantiates a new database critical exception. + * + * @param dbErrorMessageCode the db error message code + * @param errorOutOfMemory the errorOutOfMemory + */ + public DatabaseCriticalException(String dbErrorMessageCode, OutOfMemoryError errorOutOfMemory) { + super(dbErrorMessageCode, errorOutOfMemory.getCause()); + super.setServerMessage(errorOutOfMemory.getMessage()); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/DatabaseOperationException.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/DatabaseOperationException.java new file mode 100644 index 0000000000000000000000000000000000000000..50c2fb84df77ae04250c7b4c957a779dc3a84ec8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/DatabaseOperationException.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.exceptions; + +/** + * + * Title: class + * + * Description: The Class DatabaseOperationException. + * + * @since 3.0.0 + */ +public class DatabaseOperationException extends MPPDBIDEException { + private static final long serialVersionUID = 1252806867923069413L; + + /** + * Instantiates a new database operation exception. + * + * @param dbErrorMessageCode the db error message code + * @param exception the exception + */ + public DatabaseOperationException(String dbErrorMessageCode, Exception exception) { + super(dbErrorMessageCode, exception); + } + + /** + * Instantiates a new database operation exception. + * + * @param dbErrorMessageCode the db error message code + */ + public DatabaseOperationException(String dbErrorMessageCode) { + super(dbErrorMessageCode); + } + + /** + * Instantiates a new database operation exception. + * + * @param dbErrorMessageCode the db error message code + * @param params the params + */ + public DatabaseOperationException(String dbErrorMessageCode, Object... params) { + super(dbErrorMessageCode, params); + } + + /** + * Instantiates a new database operation exception. + * + * @param dbErrorMessageCode the db error message code + * @param parsedMessage the parsed message + * @param exception the exception + */ + public DatabaseOperationException(String dbErrorMessageCode, String parsedMessage, Exception exception) { + super(dbErrorMessageCode, parsedMessage, exception); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/FileCompressException.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/FileCompressException.java new file mode 100644 index 0000000000000000000000000000000000000000..3f692fa54f27d52b223989b5c5e4cd3a00db6f47 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/FileCompressException.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.exceptions; + +/** + * Title: FileCompressException + * + * @since 3.0.0 + */ +public class FileCompressException extends MPPDBIDEException { + private static final long serialVersionUID = 1026899581597045271L; + + public FileCompressException(String dbErrorMessageCode, String parsedErrorMessage, Exception exception) { + super(dbErrorMessageCode, parsedErrorMessage, exception); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/FileOperationException.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/FileOperationException.java new file mode 100644 index 0000000000000000000000000000000000000000..0a550d530b9b981fef4acc9edba44e9e4225f56c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/FileOperationException.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.exceptions; + +/** + * + * Title: class + * + * Description: The Class FileOperationException. + * + * @since 3.0.0 + */ +public class FileOperationException extends MPPDBIDEException { + + private static final long serialVersionUID = 1026999581597045273L; + + /** + * Instantiates a new file operation exception. + * + * @param fileErrorMessageCode the file error message code + */ + public FileOperationException(String fileErrorMessageCode) { + super(fileErrorMessageCode); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/InvalidDataException.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/InvalidDataException.java new file mode 100644 index 0000000000000000000000000000000000000000..d86889bf641393cb2be9eb39dffc7563b333b175 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/InvalidDataException.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.exceptions; + +/** + * Title: InvalidDataException + * + * @since 3.0.0 + */ +public class InvalidDataException extends MPPDBIDEException { + private static final long serialVersionUID = 1L; + + /** + * InvalidDataException exception + * + * @param dbErrorMessageCode error message + */ + public InvalidDataException(String dbErrorMessageCode) { + super(dbErrorMessageCode); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/MPPDBIDEException.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/MPPDBIDEException.java new file mode 100644 index 0000000000000000000000000000000000000000..6ed54df4e861079cad8e5427ea6b0d893d6c8759 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/MPPDBIDEException.java @@ -0,0 +1,226 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.exceptions; + +import java.io.IOException; +import java.sql.SQLException; +import java.text.Normalizer; +import java.text.Normalizer.Form; +import java.util.Arrays; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class MPPDBIDEException. + * + * @since 3.0.0 + */ +public class MPPDBIDEException extends Exception { + + private static final long serialVersionUID = 2835532651963396147L; + + private final String dbErrorMessage; + + private String serverMessage; + + private String serverStackTrace; + + private final int errorCode; + + /** + * Class of the exception generator. This can be used if no exception is + * passed to the constructor. + */ + private final Object clazz; + + /** + * Copy the server exception to new exception class. This enables the + * propagation of SQLException error message to UI. + * + * @param exception the new server message + */ + private void setServerMessage(Exception exception) { + if (exception instanceof SQLException) { + SQLException sqlException = (SQLException) exception; + this.serverMessage = (sqlException.getErrorCode() > 0 + ? "[SQLErrorCode : " + sqlException.getErrorCode() + ']' + : "") + sqlException.getMessage(); + this.serverStackTrace = Arrays.toString(sqlException.getStackTrace()); + } else if (exception instanceof IOException) { + IOException ioException = (IOException) exception; + this.serverMessage = ioException.getMessage(); + + this.serverStackTrace = Arrays.toString(ioException.getStackTrace()); + } else if (exception instanceof MPPDBIDEException) { + MPPDBIDEException plsqlException = (MPPDBIDEException) exception; + this.serverMessage = plsqlException.getServerMessage(); + this.serverStackTrace = plsqlException.getServerStackTrace(); + } else { + this.serverMessage = MessageConfigLoader.getProperty(IMessagesConstants.IDE_INTERNAL_ERR) + + exception.getMessage(); + } + } + + private void setParsedServerMessage(String parsedErrorMessage, Exception exception) { + if (exception instanceof SQLException) { + SQLException sqlException = (SQLException) exception; + this.serverMessage = parsedErrorMessage; + this.serverStackTrace = Arrays.toString(sqlException.getStackTrace()); + } + } + + /** + * Sets the server message. + * + * @param serverMsg the new server message + */ + public void setServerMessage(String serverMsg) { + StringBuilder msg = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + msg.append("[SERVER]"); + msg.append(serverMsg); + this.serverMessage = msg.toString(); + } + + /** + * Clear server message. + */ + public void clearServerMessage() { + this.serverMessage = ""; + } + + /** + * Gets the server message. + * + * @return the server message + */ + public String getServerMessage() { + String msg = this.serverMessage; + if (msg != null) { + msg = Normalizer.normalize(msg, Form.NFKC); + return (msg.contains(MPPDBIDEConstants.LINE_SEPARATOR + " ")) + ? msg.replaceAll(MPPDBIDEConstants.LINE_SEPARATOR + " +", MPPDBIDEConstants.LINE_SEPARATOR) + : msg; + } + return msg; + } + + /** + * Gets the server stack trace. + * + * @return the server stack trace + */ + public String getServerStackTrace() { + return this.serverStackTrace; + } + + /** + * Instantiates a new MPPDBIDE exception. + * + * @param dbErrorMessageCode the db error message code + * @param excption the e + */ + public MPPDBIDEException(String dbErrorMessageCode, Exception excption) { + super(MessageConfigLoader.getProperty(dbErrorMessageCode), excption); + dbErrorMessage = MessageConfigLoader.getProperty(dbErrorMessageCode); + errorCode = 0; + this.clazz = null; + setServerMessage(excption); + } + + /** + * Instantiates a new MPPDBIDE exception. + * + * @param dbErrorMessageCode the db error message code + * @param parsedErrorMessage the parsed error message + * @param exception the e + */ + public MPPDBIDEException(String dbErrorMessageCode, String parsedErrorMessage, Exception exception) { + super(MessageConfigLoader.getProperty(dbErrorMessageCode), exception); + dbErrorMessage = MessageConfigLoader.getProperty(dbErrorMessageCode); + errorCode = 0; + this.clazz = null; + setParsedServerMessage(parsedErrorMessage, exception); + } + + /** + * Instantiates a new MPPDBIDE exception. + * + * @param dbErrorMessageCode the db error message code + */ + public MPPDBIDEException(String dbErrorMessageCode) { + super(MessageConfigLoader.getProperty(dbErrorMessageCode)); + dbErrorMessage = MessageConfigLoader.getProperty(dbErrorMessageCode); + errorCode = 0; + this.clazz = null; + this.serverMessage = MessageConfigLoader.getProperty(dbErrorMessageCode); + } + + /** + * Instantiates a new MPPDBIDE exception. + * + * @param dbErrorMessageCode the db error message code + * @param params the params + */ + public MPPDBIDEException(String dbErrorMessageCode, Object... params) { + super(MessageConfigLoader.getProperty(dbErrorMessageCode, params)); + dbErrorMessage = MessageConfigLoader.getProperty(dbErrorMessageCode, params); + errorCode = 0; + this.clazz = null; + this.serverMessage = dbErrorMessage; + } + + /** + * Instantiates a new MPPDBIDE exception. + * + * @param dbErrorMessageCode the db error message code + * @param throwable the e + */ + public MPPDBIDEException(String dbErrorMessageCode, Throwable throwable) { + super(MessageConfigLoader.getProperty(dbErrorMessageCode), throwable); + dbErrorMessage = MessageConfigLoader.getProperty(dbErrorMessageCode); + + errorCode = 0; + this.clazz = null; + } + + + /** + * Gets the DB error message. + * + * @return the DB error message + */ + public String getDBErrorMessage() { + if (null == clazz) { + return dbErrorMessage; + } else { + return dbErrorMessage + "in the class:" + clazz.getClass().getName(); + } + } + + /** + * Gets the error code. + * + * @return the error code + */ + public int getErrorCode() { + return errorCode; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/NoNeedToRefreshException.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/NoNeedToRefreshException.java new file mode 100644 index 0000000000000000000000000000000000000000..02ad6c4c32ea52613cc712475de9969ff7508746 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/NoNeedToRefreshException.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.exceptions; + +/** + * + * Title: class + * + * Description: The Class NoNeedToRefreshException. + * + * @since 3.0.0 + */ +public class NoNeedToRefreshException extends MPPDBIDEException { + private static final long serialVersionUID = 5816189949561990799L; + + /** + * Instantiates a new no need to refresh exception. + * + * @param dbErrorMessageCode the db error message code + */ + public NoNeedToRefreshException(String dbErrorMessageCode) { + super(dbErrorMessageCode); + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/PasswordExpiryException.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/PasswordExpiryException.java new file mode 100644 index 0000000000000000000000000000000000000000..3432afe3494c475fe31533a12ee5cf4f8ae2846d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/PasswordExpiryException.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.exceptions; + +/** + * + * Title: class + * + * Description: The Class PasswordExpiryException. + * + * @since 3.0.0 + */ +public class PasswordExpiryException extends Exception { + + private static final long serialVersionUID = 1L; + + /** + * Instantiates a new password expiry exception. + * + * @param exception the exception + */ + public PasswordExpiryException(String exception) { + super(exception); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/TableImporExportException.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/TableImporExportException.java new file mode 100644 index 0000000000000000000000000000000000000000..a80816a2b6d646de3845bfc7786f2f15f1a3067b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/TableImporExportException.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.exceptions; + +/** + * + * Title: class + * + * Description: The Class TableImporExportException. + * + * @since 3.0.0 + */ +public class TableImporExportException extends MPPDBIDEException { + + private static final long serialVersionUID = 6331637509114059067L; + + /** + * Instantiates a new table impor export exception. + * + * @param dbErrorMessageCode the db error message code + */ + public TableImporExportException(String dbErrorMessageCode) { + super(dbErrorMessageCode); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/UnknownException.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/UnknownException.java new file mode 100644 index 0000000000000000000000000000000000000000..1fc5412ed4fe2d2c5945822a5bf962600463f9d3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/UnknownException.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.exceptions; + +/** + * + * Title: class + * + * Description: The Class UnknownException. + * + * @since 3.0.0 + */ +public class UnknownException extends MPPDBIDEException { + + private static final long serialVersionUID = -7056743612593978712L; + + /** + * Instantiates a new unknown exception. + * + * @param dbErrorMessageCode the db error message code + * @param exception the exception + */ + public UnknownException(String dbErrorMessageCode, Exception exception) { + super(dbErrorMessageCode, exception); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/UserOperationCancelException.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/UserOperationCancelException.java new file mode 100644 index 0000000000000000000000000000000000000000..6d4b309363061adb6898b31e19cac3e251c8b7e7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/exceptions/UserOperationCancelException.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.exceptions; + +/** + * + * Title: class + * + * Description: The Class UserOperationCancelException. + * + * @since 3.0.0 + */ +public class UserOperationCancelException extends MPPDBIDEException { + + /** + * Instantiates a new user operation cancel exception. + * + * @param dbErrorMessageCode the db error message code + */ + public UserOperationCancelException(String dbErrorMessageCode) { + super(dbErrorMessageCode); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/DSFileAttributes.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/DSFileAttributes.java new file mode 100644 index 0000000000000000000000000000000000000000..4cb8c9366b37059114231371ca91fd20cdea73f7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/DSFileAttributes.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.files; + +import java.io.IOException; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.attribute.AclEntry; +import java.nio.file.attribute.AclEntry.Builder; +import java.nio.file.attribute.AclEntryFlag; +import java.nio.file.attribute.AclEntryPermission; +import java.nio.file.attribute.AclEntryType; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.UserPrincipal; +import java.nio.file.attribute.UserPrincipalLookupService; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.opengauss.mppdbide.utils.EnvirnmentVariableValidator; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class DSFileAttributes. + * + * @since 3.0.0 + */ +public class DSFileAttributes implements FileAttribute> { + private Set userChosenPermissions; + + /** + * Instantiates a new DS file attributes. + * + * @param userChosenPermissions the user chosen permissions + */ + public DSFileAttributes(Set userChosenPermissions) { + Set currentUserChosenPermissions = userChosenPermissions; + if (currentUserChosenPermissions == null) { + currentUserChosenPermissions = new HashSet(); + } + this.userChosenPermissions = currentUserChosenPermissions; + } + + @Override + public List value() { + // lookup user principal + FileSystem fileSystem = FileSystems.getDefault(); + UserPrincipalLookupService userPrincipalLookupService = fileSystem.getUserPrincipalLookupService(); + UserPrincipal userPrincipal = null; + try { + if (userPrincipalLookupService != null) { + // Choose current operating system user principal + userPrincipal = userPrincipalLookupService + .lookupPrincipalByName(EnvirnmentVariableValidator.validateAndGetUserName()); + } + } catch (IOException exception) { + // No need to throw the exception because ACLbuilder is taken care + // of the exception if the userprincipal is empty/null + MPPDBIDELoggerUtility.error("Exception occured while fetching the userprincipal", exception); + } + + // select ACL flags + // Can be placed on a directory and indicates that the ACL entry should + // be added to each new non-directory file created. + Set flags = EnumSet.of(AclEntryFlag.FILE_INHERIT, AclEntryFlag.DIRECTORY_INHERIT); + // Can be placed / on a directory and indicates that the ACL entry + // should be added to each new directory created. + // build ACL entry + Builder builder = AclEntry.newBuilder(); + builder.setFlags(flags); + + if (userChosenPermissions != null && userChosenPermissions.size() > 0) { + // set user chosen permissions to the file + builder.setPermissions(userChosenPermissions); + } else { + // set default list of permissions + builder.setPermissions(DSFilePermission.getDefaultPermission()); + } + + if (userPrincipal != null) { + builder.setPrincipal(userPrincipal); + } + + // Explicitly grants access to a file or directory for the assigned user + // principle. + builder.setType(AclEntryType.ALLOW); + + AclEntry entry = builder.build(); + List aclEntryList = new ArrayList(1); + aclEntryList.add(entry); + + return aclEntryList; + } + + @Override + public String name() { + return "posix:permissions"; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/DSFilePermission.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/DSFilePermission.java new file mode 100644 index 0000000000000000000000000000000000000000..5bf21b8d5608e44d54cd25cffc0b90b30e008de4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/DSFilePermission.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.files; + +import java.nio.file.attribute.AclEntryPermission; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.Set; + +/** + * + * Title: class + * + * Description: The Class DSFilePermission. + * + * @since 3.0.0 + */ +public class DSFilePermission { + // select ACL permissions + // Permission to delete the file. + private static final Set DEFAULT_PERMISSIONS = EnumSet.of(AclEntryPermission.DELETE, + // Permission to delete a file or directory within a directory. + AclEntryPermission.DELETE_CHILD, + // Permission to modify the file's data. + AclEntryPermission.WRITE_DATA, + // The ability to write (non-acl) file attributes. + AclEntryPermission.WRITE_ATTRIBUTES, + // Permission to write the named attributes of a file. + AclEntryPermission.WRITE_NAMED_ATTRS, + // Permission to append data to a file. + AclEntryPermission.APPEND_DATA, + // Permission to access file locally at the server with synchronous + // reads and writes. + AclEntryPermission.SYNCHRONIZE, + // The ability to read (non-acl)file attributes. + AclEntryPermission.READ_ATTRIBUTES, + // Permission to read the data of the file. + AclEntryPermission.READ_DATA, + // Permission to read the named attributes of a file. + AclEntryPermission.READ_NAMED_ATTRS, + // Permission to read the ACL attribute. + AclEntryPermission.READ_ACL); + + /** + * gets the Default file Permission + * + * @return DEFAULT_PERMISSIONS the DEFAULT_PERMISSIONS + */ + public static Set getDefaultPermission() { + return new HashSet(DEFAULT_PERMISSIONS); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/DSFilesWrapper.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/DSFilesWrapper.java new file mode 100644 index 0000000000000000000000000000000000000000..f54e5d32b09059054ac6a0ec74e9c4c9b7f79eee --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/DSFilesWrapper.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.files; + +import java.io.File; +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.AclEntry; +import java.nio.file.attribute.AclEntryPermission; +import java.nio.file.attribute.AclEntryType; +import java.nio.file.attribute.AclFileAttributeView; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.UserPrincipal; +import java.nio.file.attribute.UserPrincipalLookupService; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.utils.EnvirnmentVariableValidator; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.FileOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class DSFilesWrapper. + * + * @since 3.0.0 + */ +public class DSFilesWrapper { + /** + * Creates the directory. + * + * @param folderPath the folder path + * @param fileAttributes the file attributes + * @return the path + * @throws FileOperationException the file operation exception + */ + public static Path createDirectory(Path folderPath, FileAttribute> fileAttributes) + throws FileOperationException { + Path directoryName = folderPath.getFileName(); + Path parent = folderPath.getParent(); + if (null != parent && parent.toAbsolutePath() != null && parent.toAbsolutePath().normalize() != null) { + String workingDir = null; + try { + workingDir = new File(parent.toAbsolutePath().normalize().toString()).getCanonicalPath(); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("Exception when trying to access the file", exception); + throw new FileOperationException(IMessagesConstants.CREATE_FOLDER_FAIL_ERR); + } + if (null != workingDir && directoryName != null) { + Path folder = Paths.get(workingDir, directoryName.normalize().toString()); + + if (!Files.exists(folder)) { + Set supportedAttr = folder.getFileSystem().supportedFileAttributeViews(); + try { + Files.createDirectory(folderPath); + if (supportedAttr.contains("acl")) { + setWindowsPermissions(folderPath); + } + } catch (IOException e) { + throw new FileOperationException(IMessagesConstants.CREATE_FOLDER_FAIL_ERR); + } + } + } + } + return folderPath; + } + + /** + * Sets the windows permissions. + * + * @param path the new windows permissions + * @throws IOException Signals that an I/O exception has occurred. + */ + public static void setWindowsPermissions(Path path) throws IOException { + AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class); + UserPrincipal owner = view.getOwner(); + List acl = view.getAcl(); + ListIterator it = acl.listIterator(); + while (it.hasNext()) { + AclEntry entry = it.next(); + if ("BUILTIN\\Administrators".equals(entry.principal().getName()) + || "NT AUTHORITY\\SYSTEM".equals(entry.principal().getName())) { + continue; + } + it.remove(); + } + AclEntry entry = AclEntry.newBuilder().setType(AclEntryType.ALLOW).setPrincipal(owner) + .setPermissions(AclEntryPermission.READ_DATA, AclEntryPermission.WRITE_DATA, + AclEntryPermission.APPEND_DATA, AclEntryPermission.READ_NAMED_ATTRS, + AclEntryPermission.WRITE_NAMED_ATTRS, AclEntryPermission.EXECUTE, + AclEntryPermission.READ_ATTRIBUTES, AclEntryPermission.WRITE_ATTRIBUTES, + AclEntryPermission.DELETE, AclEntryPermission.READ_ACL, AclEntryPermission.SYNCHRONIZE) + .build(); + acl.add(entry); + view.setAcl(acl); + } + + /** + * Creates the file. + * + * @param propFileAbsolute the prop file absolute + * @param fileAttributes the file attributes + * @return the path + * @throws FileOperationException the file operation exception + */ + public static Path createFile(Path propFileAbsolute, FileAttribute> fileAttributes) + throws FileOperationException { + Path fileName = propFileAbsolute.getFileName(); + Path parent = propFileAbsolute.getParent(); + if (null != parent && parent.toAbsolutePath() != null && parent.toAbsolutePath().normalize() != null) { + File workingDir = new File(parent.toAbsolutePath().normalize().toString()); + if (fileName != null) { + Path file = Paths.get(workingDir.toString(), fileName.toString()); + + if (!Files.exists(file)) { + Set supportedAttr = file.getFileSystem().supportedFileAttributeViews(); + try { + Files.createFile(file); + if (supportedAttr.contains("acl")) { + setWindowsPermissions(file); + } + } catch (IOException exp) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FOLDER_FAIL_ERR), exp); + throw new FileOperationException(IMessagesConstants.CREATE_FOLDER_FAIL_ERR); + } + } + } + } + return propFileAbsolute; + } + + /** + * Checks if is existing directory. + * + * @param directoryPath the directory path + * @return return true if the path is a existing directory; otherwise return + * false. + * @Title: isExistingDirectory + * @Description: validate the directory if is existing + */ + public static boolean isExistingDirectory(String directoryPath) { + if (directoryPath == null) { + return false; + } + File filePath = null; + if (FileValidationUtils.validateFilePathName(directoryPath)) { + filePath = new File(directoryPath); + } + return filePath != null && filePath.exists() && filePath.isDirectory(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/DSFolderDeleteUtility.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/DSFolderDeleteUtility.java new file mode 100644 index 0000000000000000000000000000000000000000..c56d392580f68dc23aa68064401c25cfc889bc08 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/DSFolderDeleteUtility.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.files; + +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.FileVisitor; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.BasicFileAttributes; + +/** + * + * Title: class + * + * Description: The Class DSFolderDeleteUtility. + * + * @since 3.0.0 + */ +public class DSFolderDeleteUtility implements FileVisitor { + private FileVisitResult proceedAhead = FileVisitResult.CONTINUE; + + @Override + public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { + return proceedAhead; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Files.delete(file); + return proceedAhead; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { + Files.delete(dir); + return proceedAhead; + } + + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { + return proceedAhead; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/FilePermissionFactory.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/FilePermissionFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..129f28b1b9a20697dfc17c9e544150d89e34ae55 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/FilePermissionFactory.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.files; + + +/** + * Title: FilePermissionFactory + * + * @since 3.0.0 + */ +public class FilePermissionFactory { + private static volatile ISetFilePermission INSTANCE = null; + private static final Object MUTEX = new Object(); + + /** + * Gets the file permission instance. + * + * @return the file permission instance + */ + public static ISetFilePermission getFilePermissionInstance() { + if (INSTANCE == null) { + synchronized (MUTEX) { + if (INSTANCE == null) { + INSTANCE = new SetFilePermission(); + } + } + } + return INSTANCE; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/FileValidationUtils.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/FileValidationUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..c1327ca16b35d95167145eb85990ad4fc6f728aa --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/FileValidationUtils.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.files; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * + * Title: class + * + * Description: The Class FileValidationUtils. + * + * @since 3.0.0 + */ +public class FileValidationUtils { + /** + * validateFileName the validateFileName + * + * @param fileName the filename + * @return true, if valid file + */ + public static boolean validateFileName(String fileName) { + Pattern patternWinFile = Pattern.compile("\\[|\\]|\\:|\\||\\*|\\?|\\<|\\>|\\/|\\\\|\\\""); + Matcher matcher = patternWinFile.matcher(fileName); + if (matcher.find()) { + return false; + } + return true; + } + + /** + * the validateFilePathName + * + * @param filePath the filePath + * @return true, if filePath is valid + */ + public static boolean validateFilePathName(String filePath) { + Pattern patternPath = Pattern.compile("(([a-zA-Z]:)?(\\\\[a-zA-Z0-9_.-])|\\\\+)+\\\\?"); + Matcher matcher = patternPath.matcher(filePath); + if (matcher.find()) { + return true; + } + return false; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/ISetFilePermission.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/ISetFilePermission.java new file mode 100644 index 0000000000000000000000000000000000000000..80b1eb6a8cf6ed79511990f0fe6dfb0b2bd309f2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/ISetFilePermission.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.files; + +import java.nio.file.Path; +import java.nio.file.attribute.AclEntryPermission; +import java.util.EnumSet; +import java.util.Set; + +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; + +/** + * + * Title: interface + * + * Description: The Interface ISetFilePermission. + * + * @since 3.0.0 + */ +public interface ISetFilePermission { + /** + * Creates the file with permission. + * + * @param path the path + * @param isDir the is dir + * @param userChosenPermissions the user chosen permissions + * @param setDefaultOnNull the set default on null + * @return the path + * @throws DatabaseOperationException the database operation exception + */ + Path createFileWithPermission(String path, boolean isDir, Set userChosenPermissions, + boolean setDefaultOnNull) throws DatabaseOperationException; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/SetFilePermission.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/SetFilePermission.java new file mode 100644 index 0000000000000000000000000000000000000000..85119995c39885016b35c8f582cb4e0363cd848a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/files/SetFilePermission.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.files; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.AclEntry; +import java.nio.file.attribute.AclEntryPermission; +import java.nio.file.attribute.FileAttribute; +import java.util.List; +import java.util.Set; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.FileOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class SetFilePermission. + * + * @since 3.0.0 + */ +public class SetFilePermission implements ISetFilePermission { + + /** + * Creates the file with permission. + * + * @param path the path + * @param isDir the is dir + * @param userChosenPermissions the user chosen permissions + * @param setDefaultOnNull the set default on null + * @return the path + * @throws DatabaseOperationException the database operation exception * + * org.opengauss.mppdbide.utils.files.ISetFilePermission# + * createFileWithPermission(java.lang.String, boolean, java.util.Set, + * boolean) + */ + @Override + public final Path createFileWithPermission(String path, boolean isDir, + final Set userChosenPermissions, boolean setDefaultOnNull) + throws DatabaseOperationException { + + // Convert string to nio path object + Path newPath = Paths.get(path); + + // Check if file already exists + boolean fileExists = false; + if (newPath != null) { + fileExists = Files.exists(newPath); + } + + // Create file attribute with security permission + FileAttribute> fileAttributes = new DSFileAttributes(userChosenPermissions); + try { + if (isDir) { + // If create log directory and logs folder does not exist, + // create it with security permissions. + if (!fileExists) { + if (setDefaultOnNull) { + try { + newPath = DSFilesWrapper.createDirectory(newPath, fileAttributes); + } catch (FileOperationException e) { + newPath = Files.createDirectory(newPath); + } + } else { + newPath = Files.createDirectory(newPath); + } + } + } else { + // Create file with security permissions. + if (!fileExists) { + if (setDefaultOnNull) { + newPath = DSFilesWrapper.createFile(newPath, fileAttributes); + } else { + newPath = Files.createFile(newPath); + } + } + } + + } catch (IOException | FileOperationException exception) { + try { + Files.deleteIfExists(newPath); + } catch (IOException e1) { + MPPDBIDELoggerUtility.error("Error while deleting file in exception.", e1); + throw new DatabaseOperationException("Error while deleting file in exception."); + } + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.FILE_PERMISSION_ERROR), + exception); + throw new DatabaseOperationException(IMessagesConstants.FILE_PERMISSION_ERROR, exception); + } + return newPath; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/loader/MessageConfigLoader.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/loader/MessageConfigLoader.java new file mode 100644 index 0000000000000000000000000000000000000000..ffb005f5d65044955116a9c11b7af6cd3d61382e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/loader/MessageConfigLoader.java @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.loader; + +import java.io.IOException; +import java.net.URL; +import java.util.Locale; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class MessageConfigLoader. + * + * @since 3.0.0 + */ +public class MessageConfigLoader { + /** + * The Constant UNKNOWN_ERROR. + */ + public static final String UNKNOWN_ERROR = "Unknown error."; + private static MessagePropertiesLoader messagePropertiesLoader = null; + private static final Object LOCK = new Object(); + + /** + * Static block to load the resource bundle file. This will be loaded once + * in a session. + * + * MPPDBIDELoggerUtility MessageConfigLoader + */ + static { + try { + MessageConfigLoader.load("messages.properties"); + } catch (Exception exception) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_BL_LOAD_PROPERTIES), + exception); + } + } + + /** + * Load. + * + * @param propertiesFileName the properties file name + * @throws IOException Signals that an I/O exception has occurred. + */ + public static void load(String propertiesFileName) throws IOException { + synchronized (LOCK) { + // get the URL of the property file + ClassLoader classLoader = MessagePropertiesLoader.class.getClassLoader(); + + String messageFileName = propertiesFileName; + + StringBuffer msgFileCon = new StringBuffer("messages_"); + + if (null != classLoader) { + + String locale = Locale.getDefault().toString(); + + if (locale.equals(MPPDBIDEConstants.CHINESE_LOCALE)) { + messageFileName = msgFileCon.append(locale).append(".properties").toString(); + } + + URL propertiesURL = classLoader.getResource(messageFileName); + if (null != propertiesURL) { + messagePropertiesLoader = new MessagePropertiesLoader(propertiesURL); + } + } + } + + } + + /** + * Gets the property. + * + * @param key the key + * @return the property + */ + public static String getProperty(String key) { + if (null != messagePropertiesLoader) { + String message = messagePropertiesLoader.getProperty(key); + + if (null == message) { + return UNKNOWN_ERROR; + } else if (key.equalsIgnoreCase(message)) { + return UNKNOWN_ERROR; + } + + return message; + } else { + return ""; + } + + } + + /** + * Gets the property. + * + * @param key the key + * @param params the params + * @return the property + */ + public static String getProperty(String key, Object... params) { + if (null != messagePropertiesLoader) { + String message = messagePropertiesLoader.getProperty(key, params); + + if (null == message || key.equalsIgnoreCase(message)) { + return UNKNOWN_ERROR; + } + + return message; + } else { + return ""; + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/loader/MessagePropertiesLoader.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/loader/MessagePropertiesLoader.java new file mode 100644 index 0000000000000000000000000000000000000000..6bea1c23b2e54ba841d6623a837c3ceee2553e2e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/loader/MessagePropertiesLoader.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.loader; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.text.MessageFormat; +import java.util.Properties; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loggerutil.LoggerUtils; + +/** + * + * Title: class + * + * Description: The Class MessagePropertiesLoader. + * + * @since 3.0.0 + */ +public class MessagePropertiesLoader { + + private Properties dbProperties; + + /** + * Instantiates a new message properties loader. + * + * @param propertiesURL the properties URL + * @throws IOException Signals that an I/O exception has occurred. + */ + public MessagePropertiesLoader(URL propertiesURL) throws IOException { + + // get the URL of the property file + InputStream propertiesFileStream = null; + try { + propertiesFileStream = propertiesURL.openStream(); + dbProperties = new Properties(); + dbProperties.load(propertiesFileStream); + } + // closing the stream in finally block + finally { + if (null != propertiesFileStream) { + try { + propertiesFileStream.close(); + } catch (IOException e) { + LoggerUtils.error(MessageConfigLoader.getProperty(IMessagesConstants.EXE_BL_CLS)); + } + } + } + + } + + /** + * Gets the property. + * + * @param key the key + * @return the property + */ + public String getProperty(String key) { + return dbProperties.getProperty(key, key); + } + + /** + * Gets the property. + * + * @param key the key + * @param params the params + * @return the property + */ + public String getProperty(String key, Object... params) { + return MessageFormat.format(dbProperties.getProperty(key, key), params); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/logger/ILogger.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/logger/ILogger.java new file mode 100644 index 0000000000000000000000000000000000000000..b7fc29592a170b57d96c005cdbbf408c37f3bb20 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/logger/ILogger.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.logger; + +/** + * + * Title: interface + * + * Description: The Interface ILogger. + * + * @since 3.0.0 + */ +public interface ILogger { + + String PERF_CON = "CON"; + String PERF_DISCON = "DISCON"; + String PERF_OBJBRWSR_POPULATE = "PERF_OBJBRWSR_POPULATE"; + String PERF_SYNC_ACK = "SYNC_ACK"; + String PERF_EXECUTE_DBOBJECT = "EXEC_DBOBJECT"; + String PERF_DISPLAY_RESULTS = "DISPLAY_RESULTS"; + String PERF_EXECUTE_SQLTERMINAL_QUERY = "EXEC_SQLTRMINLQUERY"; + String PERF_FETCH_SRC_CODE = "FETCH_SRC_CODE"; + String PERF_REFRESH_CONNPROF = "REFRESH_CONNPROF"; + String PERF_REFRESH_NAMESPACE = "REFRESH_NAMESPACE"; + String PERF_REFRESH_OBJECT_GROUP = "REFRESH_OBJECT_GROUP"; + String PERF_REFRESH_OBJECT = "REFRESH_OBJECT"; + String PERF_ADVANCED_SEARCH = "ADVANCED_SEARCH"; + String PERF_EXECUTE_STMT = "EXECUTE_STATEMENT"; + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/logger/ISensitiveExceptionsFilter.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/logger/ISensitiveExceptionsFilter.java new file mode 100644 index 0000000000000000000000000000000000000000..f437f170f353cf130090dca9b7f6a41dc7f0059f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/logger/ISensitiveExceptionsFilter.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.logger; + +import java.io.FileNotFoundException; +import java.net.BindException; +import java.security.acl.NotOwnerException; +import java.util.ConcurrentModificationException; +import java.util.MissingResourceException; +import java.util.jar.JarException; + +import javax.naming.InsufficientResourcesException; + +/** + * + * Title: interface + * + * Description: The Interface ISensitiveExceptionsFilter. + * + * @since 3.0.0 + */ +public interface ISensitiveExceptionsFilter { + /* + * SQLException is not considered as sensitive exception because DS is a + * database client tool and, masking SQL exception would make the logs + * useless for debugging + */ + /** + * isSensitiveException + * + * @param throwable the throwable + * @return is sensitive exception or not + */ + static boolean isSensitiveException(Throwable throwable) { + if (throwable instanceof FileNotFoundException || throwable instanceof JarException + || throwable instanceof MissingResourceException || throwable instanceof NotOwnerException + || throwable instanceof ConcurrentModificationException + || throwable instanceof InsufficientResourcesException || throwable instanceof BindException + || throwable instanceof OutOfMemoryError || throwable instanceof StackOverflowError) { + return true; + } + return false; + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/logger/MPPDBIDELoggerUtility.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/logger/MPPDBIDELoggerUtility.java new file mode 100644 index 0000000000000000000000000000000000000000..cbd888b49fedd030311f38d3f69a5a12b7071d1a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/logger/MPPDBIDELoggerUtility.java @@ -0,0 +1,447 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.logger; + +import java.net.URL; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.config.Configurator; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.loggerif.ErrorLogWriterIf; +import org.opengauss.mppdbide.utils.loggerutil.LoggerUtils; + +/** + * + * Title: class + * + * Description: The Class MPPDBIDELoggerUtility. + * + * @since 3.0.0 + */ +public class MPPDBIDELoggerUtility implements ILogger { + + private static Logger LOGGER; + + private static Logger SECURITY; + + private static Logger OPERATION; + + private static boolean isDetailLog = false; + + private static boolean isLoggerInitialized = false; + + private static String loglevel; + + private static boolean validatLevel = true; + + private static ErrorLogWriterIf errorLogWrapper = new ErrorLogWriter(); + + private static final String REGEX_HOST_IPADDRESS = "\\d+\\.\\d+\\.\\d+\\.\\d+\\:\\d+|\\d+\\.\\d+\\.\\d+\\.\\d+"; + + private static final String MASK_TEXT_FOR_IPADDRESS = "XX.XX.XX.XX"; + + private final static Object Lock; + + static { + LoggerUtils.setErrorLogWriter(errorLogWrapper); + } + + static { + ClassLoader classLoader = MPPDBIDELoggerUtility.class.getClassLoader(); + if (null != classLoader) { + URL url = classLoader.getResource("log4j2.xml"); + if (null != url) { + System.setProperty("log4j.configurationFile", url.getPath()); + } + } + Lock = new Object(); + } + + /** + * Gets the parameter. + * + * @param argument the argument + * @return the parameter + */ + public static String getParameter(String argument) { + if (argument.split("=").length > 1) { + return argument.split("=")[1].trim(); + } else { + return null; + } + } + + /** + * Sets the args. + * + * @param arguments the new args + */ + public static void setArgs(String[] arguments) { + String[] args = arguments; + if (null != args) { + int len = args.length; + for (int i = 0; i < len; i++) { + if (args[i] != null) { + if (args[i].startsWith("-detailLogging")) { + String detailLogValue = getParameter(args[i]); + + if ("true".equalsIgnoreCase(detailLogValue)) { + isDetailLog = true; + } + } + if (args[i].startsWith("-logginglevel")) { + loglevel = getParameter(args[i]); + } + } + } + + } + checkAndCreateLogger(true); + + } + + /** + * Checks if is debug enabled. + * + * @return true, if is debug enabled + */ + public static boolean isDebugEnabled() { + return LOGGER.isDebugEnabled(); + } + + /** + * Checks if is info enabled. + * + * @return true, if is info enabled + */ + public static boolean isInfoEnabled() { + return LOGGER.isInfoEnabled(); + } + + /** + * Checks if is trace enabled. + * + * @return true, if is trace enabled + */ + public static boolean isTraceEnabled() { + return LOGGER.isTraceEnabled(); + } + + /** + * Validate log level. + * + * @return true, if successful + */ + public static boolean validateLogLevel() { + return validatLevel; + + } + + /** + * Check and create logger. + */ + private static void checkAndCreateLogger() { + checkAndCreateLogger(false); + + } + + /** + * Check and create logger. + * + * @param isReinit the is reinit + */ + public static void checkAndCreateLogger(boolean isReinit) { + synchronized (Lock) { + if (!isLoggerInitialized) { + LOGGER = LogManager.getLogger("dslogger"); + SECURITY = LogManager.getLogger("security"); + OPERATION = LogManager.getLogger("operation"); + changeLevelAndReconfigure(); + isLoggerInitialized = true; + } else if (isReinit) { + changeLevelAndReconfigure(); + } + } + } + + private static void changeLevelAndReconfigure() { + if (null != loglevel) { + Level level = null; + Configurator.setLevel(LOGGER.getName(), Level.toLevel(loglevel)); + if (!LOGGER.getLevel().toString().equalsIgnoreCase(loglevel)) { + level = Level.WARN; + validatLevel = false; + } else { + level = Level.toLevel(loglevel); + } + Configurator.setLevel(LOGGER.getName(), level); + } + } + + /** + * Trace. + * + * @param msgParam the msg param + */ + public static void trace(String msgParam) { + String msg = msgParam; + StackTraceElement[] traceElementArr = Thread.currentThread().getStackTrace(); + if (null != traceElementArr && traceElementArr.length > 2 && null != traceElementArr[2]) { + StackTraceElement traceElement = traceElementArr[2]; + msg = " [" + traceElement.getClassName() + "] " + msg; + } + checkAndCreateLogger(); + LOGGER.trace(msg); + } + + /** + * Info. + * + * @param msgParam the msg param + */ + public static void info(String msgParam) { + String msg = msgParam; + StackTraceElement[] traceElementArr = Thread.currentThread().getStackTrace(); + if (null != traceElementArr && traceElementArr.length > 2 && null != traceElementArr[2]) { + StackTraceElement traceElement = traceElementArr[2]; + msg = " [" + traceElement.getClassName() + "] " + msg; + } + checkAndCreateLogger(); + LOGGER.info(msg); + } + + /** + * Warn. + * + * @param msgParam the msg param + */ + public static void warn(String msgParam) { + String msg = msgParam; + StackTraceElement[] traceElementArr = Thread.currentThread().getStackTrace(); + if (null != traceElementArr && traceElementArr.length > 2 && null != traceElementArr[2]) { + StackTraceElement traceElement = traceElementArr[2]; + msg = " [" + traceElement.getClassName() + "] " + msg; + } + checkAndCreateLogger(); + LOGGER.warn(msg); + } + + /** + * Debug. + * + * @param msgParam the msg param + */ + public static void debug(String msgParam) { + String msg = msgParam; + StackTraceElement[] traceElementArr = Thread.currentThread().getStackTrace(); + if (null != traceElementArr && traceElementArr.length > 2 && null != traceElementArr[2]) { + StackTraceElement traceElement = traceElementArr[2]; + msg = " [" + traceElement.getClassName() + "] " + msg; + } + checkAndCreateLogger(); + LOGGER.debug(msg); + } + + /** + * Error. + * + * @param msgParam the msg param + */ + public static void error(String msgParam) { + String msg = msgParam; + StackTraceElement[] traceElementArr = Thread.currentThread().getStackTrace(); + if (null != traceElementArr && traceElementArr.length > 2 && null != traceElementArr[2]) { + StackTraceElement traceElement = traceElementArr[2]; + msg = " [" + traceElement.getClassName() + "] " + msg; + } + checkAndCreateLogger(); + LOGGER.error(msg); + } + + /** + * Error. + * + * @param msgParam the msg param + */ + public static void error(String msgParam, Throwable throwable) { + String msg = msgParam; + StackTraceElement[] traceElementArr = Thread.currentThread().getStackTrace(); + if (null != traceElementArr && traceElementArr.length > 2 && null != traceElementArr[2]) { + StackTraceElement traceElement = traceElementArr[2]; + msg = " [" + traceElement.getClassName() + "] " + msg; + } + checkAndCreateLogger(); + + if (isDetailLog) { + filterSensitiveExceptionsAndLogError(throwable, msg); + } else { + LOGGER.error(msg); + } + } + + private static String maskIPInExceptionMessage(String message, Throwable exp) { + StringBuffer messageBuilder = new StringBuffer(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + messageBuilder.append(message); + messageBuilder.append(MPPDBIDEConstants.LINE_SEPARATOR); + messageBuilder.append(ExceptionUtils.getStackTrace(exp)); + + Pattern pattern = Pattern.compile(REGEX_HOST_IPADDRESS); + Matcher matcher = pattern.matcher(messageBuilder.toString()); + if (matcher.find()) { + return matcher.replaceAll(MASK_TEXT_FOR_IPADDRESS); + } + return messageBuilder.toString(); + } + + private static void filterSensitiveExceptionsAndLogError(Throwable throwable, String msg) { + if (ISensitiveExceptionsFilter.isSensitiveException(throwable) + || ISensitiveExceptionsFilter.isSensitiveException(throwable.getCause())) { + LOGGER.error(msg); + } else { + LOGGER.error(maskIPInExceptionMessage(msg, throwable)); + } + } + + private static void filterSensitiveExceptionsAndLogFatal(Throwable throwable, String msg) { + if (ISensitiveExceptionsFilter.isSensitiveException(throwable) + || ISensitiveExceptionsFilter.isSensitiveException(throwable.getCause())) { + LOGGER.fatal(msg); + } else { + LOGGER.fatal(maskIPInExceptionMessage(msg, throwable)); + } + } + + /** + * Fatal. + * + * @param msgParam the msg param + */ + public static void fatal(String msgParam, Throwable throwable) { + String msg = msgParam; + StackTraceElement[] traceElementArr = Thread.currentThread().getStackTrace(); + checkAndCreateLogger(); + if (null != traceElementArr && traceElementArr.length > 2 && null != traceElementArr[2]) { + StackTraceElement traceElement = traceElementArr[2]; + msg = " [" + traceElement.getClassName() + "] " + msg; + } + if (isDetailLog) { + filterSensitiveExceptionsAndLogFatal(throwable, msg); + } else { + LOGGER.fatal(msg); + } + } + + /** + * Perf. + * + * @param module the module + * @param operation the operation + * @param isStart the is start + */ + public static void perf(String module, String operation, boolean isStart) { + StringBuilder message = new StringBuilder("[PERF]["); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(MPPDBIDEConstants.DATE_FORMAT); + message.append(operation).append("][").append(isStart ? "START" : "STOP").append("][").append(module) + .append("]<<").append(simpleDateFormat.format(new Date())).append(">>"); + trace(message.toString()); + } + + /** + * None. + * + * @param msg the msg + */ + public static void none(String msg) { + // donot log anything here. This implementation is for + // explicit dummy log, to fool static tools. + } + + /** + * Perf. + * + * @param msg the msg + */ + public static void perf(String msg) { + StringBuilder message = new StringBuilder("[PERF]["); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(MPPDBIDEConstants.DATE_FORMAT); + message.append(simpleDateFormat.format(new Date())).append(" ] ").append(msg); + trace(message.toString()); + } + + /** + * + * Title: class + * + * Description: The Class ErrorLogWriter. + */ + private static class ErrorLogWriter implements ErrorLogWriterIf { + + @Override + public void errorLog(String msg) { + error(msg); + + } + + } + + /** + * Info. + * + * @param msgParam the msg param + */ + public static void securityInfo(String msgParam) { + checkAndCreateLogger(); + SECURITY.info(msgParam); + } + + /** + * Info. + * + * @param msgParam the msg param + */ + public static void operationInfo(String msgParam) { + String msg = msgParam; + StackTraceElement[] traceElementArr = Thread.currentThread().getStackTrace(); + if (null != traceElementArr && traceElementArr.length > 2 && null != traceElementArr[2]) { + StackTraceElement traceElement = traceElementArr[2]; + msg = " [" + traceElement.getClassName() + "] " + msg; + } + checkAndCreateLogger(); + OPERATION.info(msg); + } + + /** + * Info. + * + * @param msgParam the msg param + */ + public static void securityError(String msgParam) { + checkAndCreateLogger(); + SECURITY.error(msgParam); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/loggerif/ErrorLogWriterIf.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/loggerif/ErrorLogWriterIf.java new file mode 100644 index 0000000000000000000000000000000000000000..4da7e00a3e6057d5f87653b963273ce70f8ba3dc --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/loggerif/ErrorLogWriterIf.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.loggerif; + +/** + * + * Title: interface + * + * Description: The Interface ErrorLogWriterIf. + * + * @since 3.0.0 + */ +public interface ErrorLogWriterIf { + + /** + * Error log. + * + * @param msg the msg + */ + void errorLog(String msg); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/loggerutil/LoggerUtils.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/loggerutil/LoggerUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..0bbae661065677b2b59290dba8979fc1d0632cf0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/loggerutil/LoggerUtils.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.loggerutil; + +import org.opengauss.mppdbide.utils.loggerif.ErrorLogWriterIf; + +/** + * + * Title: class + * + * Description: The Class LoggerUtils. + * + * @since 3.0.0 + */ +public abstract class LoggerUtils { + private static ErrorLogWriterIf errorLogIf = null; + + /** + * Sets the error log writer. + * + * @param lErrorLogWriter the new error log writer + */ + public static void setErrorLogWriter(ErrorLogWriterIf lErrorLogWriter) { + errorLogIf = lErrorLogWriter; + } + + /** + * Error. + * + * @param msg the msg + */ + public static void error(String msg) { + if (null != errorLogIf) { + errorLogIf.errorLog(msg); + } + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/GlobaMessageQueueUtil.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/GlobaMessageQueueUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..d5993ca092b70042e38631411e215375157b1af4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/GlobaMessageQueueUtil.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.messaging; + +/** + * + * Title: class + * + * Description: The Class GlobaMessageQueueUtil. + * + * @since 3.0.0 + */ +public final class GlobaMessageQueueUtil { + private MessageQueue messageQueue; + + /** + * Gets the message queue. + * + * @return the message queue + */ + public MessageQueue getMessageQueue() { + return messageQueue; + } + + private static volatile GlobaMessageQueueUtil instance; + private static final Object LOCK = new Object(); + + /** + * Instantiates a new globa message queue util. + */ + private GlobaMessageQueueUtil() { + + messageQueue = new MessageQueue(); + } + + /** + * Gets the single instance of GlobaMessageQueueUtil. + * + * @return single instance of GlobaMessageQueueUtil + */ + public static GlobaMessageQueueUtil getInstance() { + if (instance == null) { + synchronized (LOCK) { + if (instance == null) { + instance = new GlobaMessageQueueUtil(); + } + } + } + + return instance; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/IMessageQueue.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/IMessageQueue.java new file mode 100644 index 0000000000000000000000000000000000000000..90173dd457e709ce5db65dbf435311d618993eaf --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/IMessageQueue.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.messaging; + +/** + * + * Title: interface + * + * Description: The Interface IMessageQueue. + * + * @since 3.0.0 + */ +public interface IMessageQueue { + + /** + * Push. + * + * @param msg the msg + */ + void push(Message msg); + + /** + * Pop. + * + * @return the message + */ + Message pop(); + + /** + * Checks if is empty. + * + * @return true, if is empty + */ + boolean isEmpty(); + + /** + * Size. + * + * @return the int + */ + /* + * Returns the current size of the queue + */ + int size(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/IStatusMessageList.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/IStatusMessageList.java new file mode 100644 index 0000000000000000000000000000000000000000..ccc2a2025eb945b6eb1b5dab899ec1f7e359f886 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/IStatusMessageList.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.messaging; + +/** + * + * Title: interface + * + * Description: The Interface IStatusMessageList. + * + * @since 3.0.0 + */ +public interface IStatusMessageList { + + /** + * Push. + * + * @param msg the msg + */ + void push(StatusMessage msg); + + /** + * Pop. + * + * @return the status message + */ + StatusMessage pop(); + + /** + * Pop. + * + * @param message the message + * @return true, if successful + */ + boolean pop(StatusMessage message); + + /** + * Checks if is empty. + * + * @return true, if is empty + */ + boolean isEmpty(); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/Message.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/Message.java new file mode 100644 index 0000000000000000000000000000000000000000..2349324bf0fdde95e474b0cc7a13c4d87aade5b3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/Message.java @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.messaging; + +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class Message. + * + * @since 3.0.0 + */ +public class Message { + private MessageType type; + private String message; + + /** + * Instantiates a new message. + * + * @param type the type + * @param message the message + */ + public Message(MessageType type, String message) { + super(); + this.type = type; + this.message = message; + } + + /** + * Gets the type. + * + * @return the type + */ + public MessageType getType() { + return type; + } + + /** + * Gets the message. + * + * @return the message + */ + public String getMessage() { + return message; + } + + /** + * Gets the info. + * + * @param msg the msg + * @return the info + */ + public static Message getInfo(String msg) { + return new Message(MessageType.INFO, msg); + } + + /** + * Gets the warn. + * + * @param msg the msg + * @return the warn + */ + public static Message getWarn(String msg) { + return new Message(MessageType.WARN, msg); + } + + /** + * Gets the error. + * + * @param msg the msg + * @return the error + */ + public static Message getError(String msg) { + return new Message(MessageType.ERROR, msg); + } + + /** + * Gets the info from const. + * + * @param msgConst the msg const + * @return the info from const + */ + public static Message getInfoFromConst(String msgConst) { + return getInfo(MessageConfigLoader.getProperty(msgConst)); + } + + /** + * Gets the warn from const. + * + * @param msgConst the msg const + * @return the warn from const + */ + public static Message getWarnFromConst(String msgConst) { + return getWarn(MessageConfigLoader.getProperty(msgConst)); + } + + /** + * Gets the error from const. + * + * @param msgConst the msg const + * @return the error from const + */ + public static Message getErrorFromConst(String msgConst) { + return getError(MessageConfigLoader.getProperty(msgConst)); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/MessageQueue.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/MessageQueue.java new file mode 100644 index 0000000000000000000000000000000000000000..d22427e1807415b68bedac651ff188ebe5f1c1e0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/MessageQueue.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.messaging; + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; + +/** + * + * Title: class + * + * Description: The Class MessageQueue. + * + * @since 3.0.0 + */ +public final class MessageQueue implements IMessageQueue { + private BlockingQueue messages; + + /** + * Instantiates a new message queue. + */ + public MessageQueue() { + messages = new LinkedBlockingQueue(); + } + + /** + * Push. + * + * @param msg the msg + * org.opengauss.mppdbide.utils.messaging.IMessageQueue#push(org.opengauss. + * mppdbide.utils.messaging.Message) + */ + @Override + public void push(Message msg) { + messages.add(msg); + } + + /** + * Pop. + * + * @return the message * + * org.opengauss.mppdbide.utils.messaging.IMessageQueue#pop() + * + */ + @Override + public Message pop() { + return messages.poll(); + } + + /** + * Checks if is empty. + * + * @return true, if is empty * + * org.opengauss.mppdbide.utils.messaging.IMessageQueue#isEmpty() + */ + @Override + public boolean isEmpty() { + return messages.isEmpty(); + } + + @Override + public int size() { + return messages.size(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/MessageType.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/MessageType.java new file mode 100644 index 0000000000000000000000000000000000000000..d1d1a72699d7a91e20cc7b8f696da952bb14e142 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/MessageType.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.messaging; + +/** + * + * Title: enum + * + * Description: The Enum MessageType. + * + * @since 3.0.0 + */ +public enum MessageType { + NOTICE, + INFO, WARN, ERROR +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/ProgressBarLabelFormatter.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/ProgressBarLabelFormatter.java new file mode 100644 index 0000000000000000000000000000000000000000..4d8ac36e3684e2efae790ef2c9d6a31d29dcf4ba --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/ProgressBarLabelFormatter.java @@ -0,0 +1,219 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.messaging; + +import java.text.MessageFormat; + +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class ProgressBarLabelFormatter. + * + * @since 3.0.0 + */ +public class ProgressBarLabelFormatter { + + /** + * Gets the progress label for table with msg. + * + * @param tableName the table name + * @param schemaName the schema name + * @param databaseName the database name + * @param serverName the server name + * @param message the message + * @return the progress label for table with msg + */ + public static String getProgressLabelForTableWithMsg(String tableName, String schemaName, String databaseName, + String serverName, String message) { + String msgParam = tableName + '.' + schemaName + '.' + databaseName + '@' + serverName; + String progressLabel = MessageConfigLoader.getProperty(message, msgParam); + return progressLabel; + + } + + /** + * Gets the progress label for table without msg. + * + * @param tableName the table name + * @param schemaName the schema name + * @param databaseName the database name + * @param serverName the server name + * @return the progress label for table without msg + */ + public static String getProgressLabelForTableWithoutMsg(String tableName, String schemaName, String databaseName, + String serverName) { + String msgParam = tableName + '.' + schemaName + '.' + databaseName + '@' + serverName; + return msgParam; + + } + + /** + * Gets the progress label for database. + * + * @param databaseName the database name + * @param serverName the server name + * @param message the message + * @return the progress label for database + */ + public static String getProgressLabelForDatabase(String databaseName, String serverName, String message) { + String msgParam = databaseName + '@' + serverName; + String progressLabel = MessageConfigLoader.getProperty(message, msgParam); + return progressLabel; + + } + + /** + * Gets the progress label for schema. + * + * @param schemaName the schema name + * @param databaseName the database name + * @param serverName the server name + * @param message the message + * @return the progress label for schema + */ + public static String getProgressLabelForSchema(String schemaName, String databaseName, String serverName, + String message) { + String msgParam = schemaName + '.' + databaseName + '@' + serverName; + String progressLabel = MessageConfigLoader.getProperty(message, msgParam); + return progressLabel; + + } + + /** + * Gets the progress label for column. + * + * @param columnName the column name + * @param tableName the table name + * @param schemaName the schema name + * @param databaseName the database name + * @param serverName the server name + * @param message the message + * @return the progress label for column + */ + public static String getProgressLabelForColumn(String columnName, String tableName, String schemaName, + String databaseName, String serverName, String message) { + String msgParam = columnName + '.' + tableName + '.' + schemaName + '.' + databaseName + '@' + serverName; + String progressLabel = MessageConfigLoader.getProperty(message, msgParam); + return progressLabel; + + } + + /** + * Gets the progress label for view. + * + * @param viewName the view name + * @param schemaName the schema name + * @param databaseName the database name + * @param serverName the server name + * @param message the message + * @return the progress label for view + */ + public static String getProgressLabelForView(String viewName, String schemaName, String databaseName, + String serverName, String message) { + String msgParam = viewName + '.' + schemaName + '.' + databaseName + '@' + serverName; + String progressLabel = MessageConfigLoader.getProperty(message, msgParam); + return progressLabel; + + } + + /** + * Gets the progress label for batch export. + * + * @param exportProp the export prop + * @param currentExportCount the current export count + * @param totalExportCount the total export count + * @param objName the obj name + * @param dbName the db name + * @param serverName the server name + * @return the progress label for batch export + */ + public static String getProgressLabelForBatchExport(String exportProp, int currentExportCount, int totalExportCount, + String objName, String dbName, String serverName) { + StringBuilder builder = new StringBuilder(" (" + currentExportCount + "/" + totalExportCount + "): "); + builder.append(objName + "." + dbName + "@" + serverName); + String details = builder.toString(); + + String label = MessageConfigLoader.getProperty(exportProp, details); + return label; + } + + /** + * Gets the progress label for user role. + * + * @param userRoleName the user role name + * @param serverName the server name + * @return the progress label for user role + */ + public static String getProgressLabelForUserRole(String userRoleName, String serverName) { + return MessageFormat.format("{0}@{1}", userRoleName, serverName); + } + + /** + * Gets the progress label for Synonym Objects with msg. + * + * @param childObjectName the child object name + * @param namespaceName the namespace name + * @param serverName the server name + * @param message the message + * @return the progress label for Synonym Objects with msg + */ + public static String getProgressLabelForSynonymObjectsWithMsg(String childObjectName, String namespaceName, + String serverName, String message) { + String msgParam = childObjectName + '.' + namespaceName + '@' + serverName; + String progressLabel = MessageConfigLoader.getProperty(message, msgParam); + return progressLabel; + } + + /** + * Gets the progress label for text mode loading. + * + * @param databaseName the database name + * @param serverName the server name + * @param sqlTerminalPartLabel the sql terminal part label + * @param message the message + * @return the progress label for text mode loading + */ + public static String getProgressLabelForTextModeLoading(String databaseName, String serverName, + String sqlTerminalPartLabel, String message) { + String msgParam = databaseName + '@' + serverName; + if (!sqlTerminalPartLabel.trim().isEmpty()) { + msgParam = sqlTerminalPartLabel + "." + msgParam; + } + return MessageConfigLoader.getProperty(message, msgParam); + + } + + /** + * Gets the progress label for sequence with msg. + * + * @param sequenceName the sequence name + * @param schemaName the schema name + * @param databaseName the database name + * @param serverName the server name + * @param message the message + * @return the progress label for sequence with msg + */ + public static String getProgressLabelForSequenceWithMsg(String sequenceName, String schemaName, String databaseName, + String serverName, String message) { + String msgParam = sequenceName + '.' + schemaName + '.' + databaseName + '@' + serverName; + String progressLabel = MessageConfigLoader.getProperty(message, msgParam); + return progressLabel; + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/StatusMessage.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/StatusMessage.java new file mode 100644 index 0000000000000000000000000000000000000000..81a71afc0e9525372367bba1d83737255a3a4480 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/StatusMessage.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.messaging; + + +/** + * + * Title: class + * + * Description: The Class StatusMessage. + * + * @since 3.0.0 + */ +public class StatusMessage { + private String message; + + /** + * Instantiates a new status message. + * + * @param message the message + * @param isExecutionInProgress the is execution in progress + * @param manager the manager + */ + public StatusMessage(String message) { + this.message = message; + } + + /** + * Gets the message. + * + * @return the message + */ + public String getMessage() { + return message; + } + + /** + * Sets the message. + * + * @param message the new message + */ + public void setMessage(String message) { + this.message = message; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/StatusMessageList.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/StatusMessageList.java new file mode 100644 index 0000000000000000000000000000000000000000..e15f27f25d7d65a93597b380a327e9c9a85d3d47 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/messaging/StatusMessageList.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.messaging; + +import java.util.LinkedList; +import java.util.Queue; + +/** + * + * Title: class + * + * Description: The Class StatusMessageList. + * + * @since 3.0.0 + */ +public final class StatusMessageList implements IStatusMessageList { + private Queue messages; + private static volatile IStatusMessageList instance = null; + private static final Object INSTANCE_LOCK = new Object(); + + /** + * Instantiates a new status message list. + */ + private StatusMessageList() { + messages = new LinkedList(); + } + + /** + * Gets the single instance of StatusMessageList. + * + * @return single instance of StatusMessageList + */ + public static IStatusMessageList getInstance() { + if (null == instance) { + synchronized (INSTANCE_LOCK) { + if (null == instance) { + instance = new StatusMessageList(); + } + } + } + return instance; + } + + /** + * Push. + * + * @param msg the msg + * org.opengauss.mppdbide.utils.messaging.IStatusMessageList#push(org.opengauss. + * mppdbide.utils.messaging.StatusMessage) + */ + @Override + public void push(StatusMessage msg) { + messages.add(msg); + } + + /** + * Pop. + * + * @return the status message + * org.opengauss.mppdbide.utils.messaging.IStatusMessageList#pop() + */ + @Override + public StatusMessage pop() { + return messages.remove(); + } + + /** + * Pop. + * + * @param message the message + * @return true, if successful + * org.opengauss.mppdbide.utils.messaging.IStatusMessageList#pop(org.opengauss. + * mppdbide.utils.messaging.StatusMessage) + */ + @Override + public boolean pop(StatusMessage message) { + return messages.remove(message); + } + + /** + * Checks if is empty. + * + * @return true, if is empty * + * org.opengauss.mppdbide.utils.messaging.IStatusMessageList#isEmpty() + */ + @Override + public boolean isEmpty() { + return messages.isEmpty(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/observer/DSEvent.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/observer/DSEvent.java new file mode 100644 index 0000000000000000000000000000000000000000..8329d519570356edd9e81be769a71a5a3cff63c9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/observer/DSEvent.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.observer; + +/** + * + * Title: class + * + * Description: The Class DSEvent. + * + * @since 3.0.0 + */ +public class DSEvent { + private int type; + private Object object; + + /** + * Instantiates a new DS event. + * + * @param eventType the event type + * @param obj the obj + */ + public DSEvent(int eventType, Object obj) { + this.type = eventType; + this.object = obj; + } + + /** + * Gets the type. + * + * @return the type + */ + public int getType() { + return type; + } + + /** + * Gets the object. + * + * @return the object + */ + public Object getObject() { + return object; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/observer/DSEventTable.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/observer/DSEventTable.java new file mode 100644 index 0000000000000000000000000000000000000000..38c144b7245da96e872cdd577d7cbc16e7308083 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/observer/DSEventTable.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.observer; + +import java.util.ArrayList; + +/** + * + * Title: class + * + * Description: The Class DSEventTable. + * + * @since 3.0.0 + */ +public class DSEventTable { + private ArrayList types; + private ArrayList listener; + private static final int INITIAL_SIZE = 5; + + /** + * Instantiates a new DS event table. + */ + public DSEventTable() { + this.types = new ArrayList(INITIAL_SIZE); + this.listener = new ArrayList(INITIAL_SIZE); + } + + /** + * Hook. + * + * @param eventType the event type + * @param newListener the new listener + */ + public void hook(int eventType, IDSListener newListener) { + types.add(eventType); + listener.add(newListener); + } + + /** + * Unhook. + * + * @param eventType the event type + * @param listner the listner + */ + public void unhook(int eventType, IDSListener listner) { + int size = types.size(); + for (int i = 0; i < size; i++) { + if (this.types.get(i).equals(eventType) && this.listener.get(i).equals(listner)) { + this.types.remove(i); + this.listener.remove(i); + i--; + } + } + } + + /** + * Send event. + * + * @param event the event + */ + public void sendEvent(DSEvent event) { + int size = types.size(); + for (int i = 0; i < size; i++) { + if (this.types.get(i).equals(event.getType())) { + IDSListener listnr = this.listener.get(i); + listnr.handleEvent(event); + } + } + } + + /** + * Unhookall. + */ + public void unhookall() { + int size = types.size(); + while (size > 0) { + this.types.remove(0); + this.listener.remove(0); + size = types.size(); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/observer/DSEventWithCount.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/observer/DSEventWithCount.java new file mode 100644 index 0000000000000000000000000000000000000000..e9250c513748a48ee471029ea2adccd81fcb2e1f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/observer/DSEventWithCount.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.observer; + +/** + * + * Title: class + * + * Description: The Class DSEventWithCount. + * + * @since 3.0.0 + */ +public class DSEventWithCount extends DSEvent { + private int count; + + /** + * Instantiates a new DS event with count. + * + * @param eventType the event type + * @param obj the obj + */ + public DSEventWithCount(int eventType, Object obj) { + super(eventType, obj); + count = 1; + } + + /** + * Instantiates a new DS event with count. + * + * @param eventType the event type + * @param obj the obj + * @param count the count + */ + public DSEventWithCount(int eventType, Object obj, int count) { + super(eventType, obj); + this.count = count; + } + + /** + * Gets the count. + * + * @return the count + */ + public int getCount() { + return count; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/observer/IDSGridUIListenable.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/observer/IDSGridUIListenable.java new file mode 100644 index 0000000000000000000000000000000000000000..80016857e6c46256352ef26ff5fa95668e901dd9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/observer/IDSGridUIListenable.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.observer; + +/** + * + * Title: interface + * + * Description: The Interface IDSGridUIListenable. + * + * @since 3.0.0 + */ +public interface IDSGridUIListenable extends IDSListenable { + int LISTEN_TYPE_PRE_GRID_DATA_LOAD = 1; + int LISTEN_TYPE_POST_GRID_DATA_LOAD = 2; + int LISTEN_TYPE_ON_ERROR = 3; + int LISTEN_TYPE_ON_REEXECUTE_QUERY = 4; + int LISTEN_TYPE_GRID_DATA_CHANGED = 5; + int LISTEN_TYPE_EXPORT_CURR_PAGE_DATA = 6; + int LISTEN_TYPE_EXPORT_ALL_DATA = 7; + int LISTEN_TYPE_GRID_DATA_EDITED = 8; + int LISTEN_EDITTABLE_COMMIT_DATA = 9; + int LISTEN_EDITTABLE_COMMIT_STATUS = 10; + int LISTEN_DATABASE_CONNECT_DISCONNECT_STATUS = 11; + int LISTEN_EDITTABLE_USER_FORGET_OPTION = 12; + int LISTEN_EDITTABLE_REMEMBERED_USER_OPTION = 13; + int LISTEN_TYPE_ON_GRID_CREATION = 14; + int LISTEN_EDITTABLE_COMMIT_DATA_COMPLETE = 15; + int LISTEN_TYPE_SEARCH_DONE = 16; + int LISTEN_TYPE_SEARCH_CLEARED = 17; + int LISTEN_BATCHDROP_ATOMIC_OPTION = 18; + int LISTEN_BATCHDROP_CASCADE_OPTION = 19; + int LISTEN_BATCHDROP_START_OPTION = 20; + int LISTEN_BATCHDROP_STOP_OPTION = 21; + int LISTEN_BATCHDROP_DROP_SUCCESS = 22; + int LISTEN_BATCHDROP_DROP_FAILED = 23; + int LISTEN_BATCHDROP_OP_COMPLETE = 24; + int LISTEN_BATCHDROP_GRID_INPUT_CHANGED = 25; + int LISTEN_BATCHDROP_OP_ROLLBACK = 26; + int LISTEN_BATCHDROP_JOB_CANCEL = 27; + int LISTEN_BATCHDROP_DROP_REVERTED = 28; + int LISTEN_BATCHDROP_DROP_FAIL_REVERTED = 29; + int LISTEN_BATCHDROP_CONN_FAILED = 30; + int LISTEN_EDITTABLE_ROLLBACK_DATA = 31; + int LISTEN_TYPE_ON_REFRESH_QUERY = 32; + int LISTEN_TYPE_PROPERITES_COMMIT_DATA = 33; + int LISTEN_DATA_CHANGE_ENCODING = 34; + int LISTEN_EDITTABLE_ROLLBACK_DATA_COMPLETE = 35; + int LISTEN_BATCHEXPORT_DDL_SUCCESS = 36; + int LISTEN_EXEC_PLAN_WINDOW_REFRESH = 39; + int LISTEN_EXEC_PLAN_WINDOW_TREE_VIEW = 40; + int LISTEN_EXEC_PLAN_WINDOW_TEXT_VIEW = 41; + int LISTEN_EXEC_PLAN_WINDOW_SAVE_PLAN = 42; + int LISTEN_TYPE_ROW_UPDATED = 43; + int LISTEN_TYPE_ROW_DELETED = 44; + int LISTEN_TYPE_CREATE_TABLESPACE_COMMITED_SUCCESS = 45; + int LISTEN_TYPE_GRID_ROW_SELECTED = 46; + int LISTEN_ROW_SELECTED = 47; + int LIRTEN_ROLLBACK_PROPERTIES = 48; + int LISTEN_EDITZPROPERTIES_POST_COMMIT = 49; + int LISTEN_EDITZPROPERTIES_COMMIT_STATUS = 50; + int LISTEN_TYPE_CREATE_TABLE_COMMITED_SUCCESS = 51; + int LISTEN_CASESENSITIVITY_SELECTION = 52; + int LISTEN_COPY_TO_EXCEL_XLSX_RESULT_WINDOW_MENUITEM = 53; + int LISTEN_COPY_TO_EXCEL_XLS_RESULT_WINDOW_MENUITEM = 54; + int LISTEN_TYPE_ON_RESULT_WINDOW_MENUITEM_SEARCH = 55; + int LISTEN_TYPE_ON_RESULT_MENUITEM_GERERATE_SELECT_LINE_INSERT = 56; + int LISTEN_TYPE_ON_RESULT_MENUITEM_GERERATE_CURRENT_PAGE_INSERT = 57; + int LISTEN_TYPE_ON_RESULT_MENUITEM_GERERATE_ALL_INSERT = 58; + int LISTEN_CREATE_TABLE_DDL_GENERATION = 59; + int LISTEN_TYPE_ON_CANCEL_PASSWORD = 60; + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/observer/IDSListenable.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/observer/IDSListenable.java new file mode 100644 index 0000000000000000000000000000000000000000..9fc70a6389bd5423097450d225569d5be6a3224c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/observer/IDSListenable.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.observer; + +/** + * + * Title: interface + * + * Description: The Interface IDSListenable. + * + * @since 3.0.0 + */ +public interface IDSListenable { + + /** + * Adds the listener. + * + * @param type the type + * @param listener the listener + */ + default void addListener(int type, IDSListener listener) { + + } + + /** + * Removes the listener. + * + * @param type the type + * @param listener the listener + */ + default void removeListener(int type, IDSListener listener) { + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/observer/IDSListener.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/observer/IDSListener.java new file mode 100644 index 0000000000000000000000000000000000000000..d4c37ae238f596cfcad967584d357467f0773d01 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/observer/IDSListener.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.observer; + +/** + * Title: IDSListener + * + * Description:The listener interface for receiving IDS events. The class that + * is interested in processing a IDS event implements this interface, and the + * object created with that class is registered with a component using the + * component's addIDSListener method. When the IDS event occurs, + * that object's appropriate method is invoked. + * + * @since 3.0.0 + */ +public interface IDSListener { + + /** + * Handle event. + * + * @param event the event + */ + void handleEvent(DSEvent event); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/security/AESAlgorithmUtility.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/security/AESAlgorithmUtility.java new file mode 100644 index 0000000000000000000000000000000000000000..f7c36f391a252ccdb6b3c7cf4979ff92e26d1994 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/security/AESAlgorithmUtility.java @@ -0,0 +1,567 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.security; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.math.BigInteger; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.spec.InvalidKeySpecException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Locale; + +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.SecretKeySpec; + +import org.apache.commons.io.input.BoundedInputStream; + +import org.opengauss.mppdbide.utils.EnvirnmentVariableValidator; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DataStudioSecurityException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.files.DSFolderDeleteUtility; +import org.opengauss.mppdbide.utils.files.FilePermissionFactory; +import org.opengauss.mppdbide.utils.files.ISetFilePermission; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class AESAlgorithmUtility. + * + * @since 3.0.0 + */ +public class AESAlgorithmUtility { + /** + * The Constant PBKDF2_ALGORITHM. + */ + public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1"; + + private static final String ENVIRON_FILE = EnvirnmentVariableValidator.validateAndGetFileSeperator() + + "environ.txt"; + private static final String LOCALFILE = EnvirnmentVariableValidator.validateAndGetFileSeperator() + "local.txt"; + private static final String TEMP_FILE = EnvirnmentVariableValidator.validateAndGetFileSeperator() + "temp.txt"; + private static final String TEMP_WORKSPACE = EnvirnmentVariableValidator.validateAndGetFileSeperator() + "temp" + + EnvirnmentVariableValidator.validateAndGetFileSeperator() + "workspace"; + private static final String DROPIN_USER = EnvirnmentVariableValidator.validateAndGetFileSeperator() + "dropin" + + EnvirnmentVariableValidator.validateAndGetFileSeperator() + "user"; + private static final String PROFILE_DUMMY = EnvirnmentVariableValidator.validateAndGetFileSeperator() + "profile" + + EnvirnmentVariableValidator.validateAndGetFileSeperator() + "dummy"; + private static final String CHARSET_NAME = "UTF-8"; + + private static String keyPart3 = "18634072297704355082300964104946051172"; + + private String pbkdf2Salt = null; + private SecureUtil secureUtil; + private ISetFilePermission withPermission = FilePermissionFactory.getFilePermissionInstance(); + + public void setPbkdf2Salt(String pbkdf2Salt) { + this.pbkdf2Salt = pbkdf2Salt; + } + + /** + * + * Title: enum + * + * Description: The Enum KeyPartFileCreateOption. + */ + public enum KeyPartFileCreateOption { + + /** + * The created. + */ + CREATED, + /** + * The not created. + */ + NOT_CREATED, + /** + * The exception. + */ + EXCEPTION + } + + /** + * Instantiates a new AES algorithm utility. + * + * @param encryptionDecryption the encryption decryption + */ + public AESAlgorithmUtility(SecureUtil encryptionDecryption) { + this.secureUtil = encryptionDecryption; + } + + /** + * Creates the security folder. + * + * @param path the path + * @return the key part file create option + * @throws IOException Signals that an I/O exception has occurred. + * @throws DatabaseOperationException the database operation exception + */ + public final KeyPartFileCreateOption createSecurityFolder(String path) + throws IOException, DatabaseOperationException { + + KeyPartFileCreateOption keyPartFileCreate = KeyPartFileCreateOption.NOT_CREATED; + String strFileName = null; + String secPath = ""; + int counter = 0; + + if (Files.exists(Paths.get(secPath))) { + for (int count = 1; count <= 2; count++) { + secPath = getSecPath(path, count); + strFileName = getSecFileName(count); + if (Files.exists(Paths.get(String.format(Locale.ENGLISH, "%s%s%s", secPath, '/', strFileName)))) { + counter++; + } + } + if (Files.exists(Paths.get(String.format(Locale.ENGLISH, "%s%s%s", + path, PROFILE_DUMMY, TEMP_FILE)))) { + counter++; + } + + // If files inside security folder is not equal to 3 (key part) + 1 + // (working key) delete the folder + if (counter != 3) { + deleteSecurityFolder(path); + } + } + + for (int count = 1; count <= 2; count++) { + secPath = getSecPath(path, count); + withPermission.createFileWithPermission(secPath, true, null, true); + } + + counter = 0; + for (int count = 1; count <= 2; count++) { + try { + setKey(this.generatePBKDF(keyPart3, false)); + String encryptedBigRandomNumberStr = secureUtil.encryptString(getRandom().toString(), + CHARSET_NAME); + if (count == 1) { + encryptedBigRandomNumberStr = encryptedBigRandomNumberStr + pbkdf2Salt; + } + secPath = getSecPath(path, count); + strFileName = getSecFileName(count); + boolean isFileCreated = writeValueInFile(secPath, strFileName, encryptedBigRandomNumberStr); + if (isFileCreated) { + counter++; + } + } catch (DataStudioSecurityException | IllegalArgumentException | NoSuchAlgorithmException + | InvalidKeySpecException e) { + MPPDBIDELoggerUtility.error("Error encrypting "); + } + } + + if (counter == 2) { + keyPartFileCreate = KeyPartFileCreateOption.CREATED; + } + + return keyPartFileCreate; + } + + private String getSecFileName(int count) { + String secFileName = null; + switch (count) { + case 1: { + secFileName = "environ.txt"; + break; + } + case 2: { + secFileName = "local.txt"; + break; + } + case 3: { + secFileName = "temp.txt"; + break; + } + default: { + break; + } + } + return secFileName; + } + + /** + * the deleteSecurityFolder + * + * @param path the path + * @throws IOException the IOException + */ + public void deleteSecurityFolder(String path) throws IOException { + String secPath = ""; + for (int count = 1; count <= 3; count++) { + secPath = getSecPath(path, count); + Files.walkFileTree(Paths.get(secPath), new DSFolderDeleteUtility()); + } + } + + private String getSecPath(String secPath, int count) { + String lSecPath = null; + switch (count) { + case 1: { + lSecPath = String.format(Locale.ENGLISH, "%s%s", secPath, TEMP_WORKSPACE); + break; + } + case 2: { + lSecPath = String.format(Locale.ENGLISH, "%s%s", secPath, DROPIN_USER); + break; + } + case 3: { + lSecPath = String.format(Locale.ENGLISH, "%s%s", secPath, PROFILE_DUMMY); + break; + } + default: { + break; + } + } + return lSecPath; + } + + /** + * Write value in file. + * + * @param fileDirectory the file directory + * @param strFileName the str file name + * @param strMaskData the str mask data + * @return true, if successful + * @throws DatabaseOperationException the database operation exception + * @throws IOException Signals that an I/O exception has occurred. + */ + public final boolean writeValueInFile(String fileDirectory, String strFileName, String strMaskData) + throws DatabaseOperationException, IOException { + + File createRandomFile = new File(fileDirectory, strFileName); + BufferedWriter bw = null; + FileOutputStream fos = null; + OutputStreamWriter filewriter = null; + boolean isFileCreated = false; + try { + if (Files.notExists(createRandomFile.toPath())) { + Path securePath = withPermission.createFileWithPermission(createRandomFile.getCanonicalPath(), false, + null, true); + + fos = new FileOutputStream(securePath.toFile(), true); + filewriter = new OutputStreamWriter(fos, CHARSET_NAME); + bw = new BufferedWriter(filewriter); + bw.write(strMaskData); + isFileCreated = true; + } + return isFileCreated; + } finally { + try { + if (bw != null) { + bw.close(); + bw = null; + } + } catch (IOException ioException) { + bw = null; + } + try { + if (filewriter != null) { + filewriter.close(); + filewriter = null; + } + } catch (IOException ioExceptione) { + filewriter = null; + } + try { + if (fos != null) { + fos.close(); + fos = null; + } + } catch (IOException ioException) { + fos = null; + } + } + } + + /** + * Gets the random. + * + * @return the random + */ + public BigInteger getRandom() { + byte[] byteRandomArray = SecureRandomGenerator.getRandomNumber(); + BigInteger generatedRandom = new BigInteger(byteRandomArray); + return generatedRandom.abs(); + } + + /** + * Generate XOR result. + * + * @param strDMHome the str DM home + * @return the string + * @throws IOException Signals that an I/O exception has occurred. + * @throws NoSuchAlgorithmException the no such algorithm exception + * @throws InvalidKeySpecException the invalid key spec exception + * @throws DataStudioSecurityException the data studio security exception + */ + public final String generateXORResult(String strDMHome) + throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, DataStudioSecurityException { + File createRandomFile = null; + BigInteger xorResult = null; + ArrayList arrList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + String strFileName = null; + String strSecHome = null; + try { + for (int count = 1; count <= 2; count++) { + strSecHome = getSecPath(strDMHome, count); + strFileName = getSecFileName(count); + createRandomFile = new File(strSecHome, strFileName); + long sizeOfFile = Files.size(createRandomFile.toPath()); + if (sizeOfFile > MPPDBIDEConstants.ONE_KB) { + throw new IOException("Failed to load key. File size exceeded"); + } + String fileContent = new String(Files.readAllBytes(createRandomFile.toPath()), CHARSET_NAME); + String key = ""; + if (fileContent.length() >= 64) { + key = fileContent.substring(0, 64); + } else { + throw new IOException("Failed to load key. Illegal key size"); + } + setKey(this.generatePBKDF(keyPart3, false)); + String decryptedBigRandomNumberStr = secureUtil.decryptString(key, CHARSET_NAME); + arrList.add(decryptedBigRandomNumberStr); + } + } catch (IllegalArgumentException | IndexOutOfBoundsException | IOException ex) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), ex); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, ex); + } + // All 3 file Content is ready for Use to Calculate the XOR + try { + xorResult = new BigInteger(String.valueOf(keyPart3)).xor( + new BigInteger(String.valueOf(arrList.get(0))).xor(new BigInteger(String.valueOf(arrList.get(1))))); + } catch (NumberFormatException numberFormatException) { + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, numberFormatException); + } + MPPDBIDELoggerUtility.securityInfo("Root key generated"); + return generatePBKDF(xorResult.toString(), false); + } + + /** + * Close file. + * + * @param brParam the br param + * @param frParam the fr param + * @param fiParam the fi param + * @param fiParam the bi param + */ + private void closeFile(BufferedReader brParam, InputStreamReader frParam, FileInputStream fiParam, + BoundedInputStream biParam) { + BufferedReader br = brParam; + InputStreamReader fr = frParam; + FileInputStream fi = fiParam; + BoundedInputStream bi = biParam; + try { + if (br != null) { + br.close(); + } + } catch (IOException ex) { + br = null; + } + try { + if (fr != null) { + fr.close(); + } + } catch (IOException ex) { + fr = null; + } + try { + if (fi != null) { + fi.close(); + } + } catch (IOException ex) { + fi = null; + } + try { + if (null != bi) { + bi.close(); + } + } catch (IOException ioException) { + bi = null; + } + } + + /** + * Read WK result. + * + * @param fileDirectory the file directory + * @param strFileName the str file name + * @return the string + * @throws IOException Signals that an I/O exception has occurred. + */ + public final String readWKResult(File fileDirectory, String strFileName) throws IOException { + + BufferedReader br = null; + InputStreamReader fr = null; + BoundedInputStream bi = null; + FileInputStream fi = null; + File createRandomFile = null; + String wkSalt = ""; + try { + String currentLine = null; + createRandomFile = new File(fileDirectory, strFileName); + long fileSize = Files.size(createRandomFile.toPath()); + if (fileSize > MPPDBIDEConstants.ONE_KB) { + throw new IOException("Failed to load key. File size exceeded"); + } + fi = new FileInputStream(createRandomFile.getCanonicalFile()); + bi = new BoundedInputStream(fi, 1024); + fr = new InputStreamReader(bi, CHARSET_NAME); + br = new BufferedReader(fr, 1024); + currentLine = br.readLine(); + while (currentLine != null) { + wkSalt = wkSalt.concat(currentLine); + currentLine = br.readLine(); + } + + } finally { + closeFile(br, fr, fi, bi); + } + return wkSalt; + } + + /** + * Sets the key. + * + * @param rootKey the new key + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + public void setKey(String rootKey) throws UnsupportedEncodingException { + + secureUtil.setKey(rootKey.getBytes(CHARSET_NAME)); + + secureUtil.setKey(Arrays.copyOf(secureUtil.getKey(), 16)); + + secureUtil.setRandomKey(new SecretKeySpec(secureUtil.getKey(), "AES")); + + } + + /** + * Generate PBKDF. + * + * @param password the password + * @return the string + * @throws NoSuchAlgorithmException the no such algorithm exception + * @throws InvalidKeySpecException the invalid key spec exception + * @throws IOException Signals that an I/O exception has occurred. + */ + public final String generatePBKDF(String pwdString, boolean isGenWorkingKeyFlow) + throws NoSuchAlgorithmException, InvalidKeySpecException, IOException { + int iterations = MPPDBIDEConstants.PBKDF_ITERATIONS; + char[] chars = pwdString.toCharArray(); + byte[] salt = isGenWorkingKeyFlow ? SecureRandomGenerator.getRandomNumber() : getSalt(); + + PBEKeySpec spec = new PBEKeySpec(chars, salt, iterations, 64 * 8); + SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); + byte[] hash = skf.generateSecret(spec).getEncoded(); + Arrays.fill(chars, (char) 0x00); + return toHex(hash); + } + + /** + * Gets the salt. + * + * @return the salt + * @throws IOException Signals that an I/O exception has occurred. + */ + private byte[] getSalt() throws IOException { + String securityFolderPath = secureUtil.getSecurityFolder(); + String saltPath = securityFolderPath + TEMP_WORKSPACE; + + File createRandomsalt = null; + String defaultSalt = ""; + try { + String fileContent = null; + createRandomsalt = new File(saltPath, ENVIRON_FILE); + long sizeOfFile = Files.size(createRandomsalt.toPath()); + if (sizeOfFile > MPPDBIDEConstants.ONE_KB) { + throw new IOException("Failed to load Salt. File size exceeded"); + } + fileContent = new String(Files.readAllBytes(createRandomsalt.toPath()), CHARSET_NAME); + if (fileContent.length() > 64) { + String salt = fileContent.substring(64, fileContent.length()); + defaultSalt = defaultSalt.concat(salt); + } else { + throw new IOException("Failed to load Salt. Illegal salt size"); + } + + pbkdf2Salt = defaultSalt; + } catch (FileNotFoundException | NoSuchFileException excep) { + if (pbkdf2Salt != null) { + return pbkdf2Salt.getBytes(CHARSET_NAME); + } else { + return new byte[0]; + } + } + + return pbkdf2Salt.getBytes(CHARSET_NAME); + } + + /** + * To hex. + * + * @param array the array + * @return the string + * @throws NoSuchAlgorithmException the no such algorithm exception + */ + private String toHex(byte[] array) throws NoSuchAlgorithmException { + BigInteger bi = new BigInteger(1, array); + String hex = bi.toString(16); + int paddingLength = (array.length * 2) - hex.length(); + if (paddingLength > 0) { + return String.format(Locale.ENGLISH, "%0" + paddingLength + 'd', 0) + hex; + } else { + return hex; + } + } + + /** + * Gets the IV salt. + * + * @return the IV salt + */ + public final byte[] getIVSalt() { + try { + return toHex(this.getSalt()).substring(0, 16).getBytes(CHARSET_NAME); + } catch (UnsupportedEncodingException exception) { + return null; + } catch (NoSuchAlgorithmException exception) { + return null; + } catch (IOException exception) { + return null; + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/security/DecryptionUtil.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/security/DecryptionUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..ba513bc15c15833f0f42055b3c1fff42235fec19 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/security/DecryptionUtil.java @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.security; + +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.spec.IvParameterSpec; + +import org.apache.commons.codec.binary.Base64; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DataStudioSecurityException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class DecryptionUtil. + * + * @since 3.0.0 + */ +public class DecryptionUtil { + private SecureUtil encryptionDecryption; + + /** + * Instantiates a new decryption util. + * + * @param encryptionDecryption the encryption decryption + */ + public DecryptionUtil(SecureUtil encryptionDecryption) { + this.encryptionDecryption = encryptionDecryption; + } + + /** + * Gets the decrypted string. + * + * @return the decrypted string + */ + public String getDecryptedString() { + return encryptionDecryption.getDecryptedString(); + } + + /** + * Sets the decrypted string. + * + * @param decryptedString the new decrypted string + */ + public void setDecryptedString(String decryptedString) { + encryptionDecryption.setDecryptedString(decryptedString); + } + + /** + * Decrypt. + * + * @param strToDecrypt the str to decrypt + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws IllegalBlockSizeException the illegal block size exception + * @throws BadPaddingException the bad padding exception + * @throws DataStudioSecurityException the data studio security exception + */ + public final void decrypt(String strToDecrypt) throws UnsupportedEncodingException, IllegalBlockSizeException, + BadPaddingException, DataStudioSecurityException { + setDecryptedString(decryptString(strToDecrypt, StandardCharsets.UTF_8.name())); + } + + /** + * Decrypt string. returns decrypted string + * + * @param strToDecrypt the str to decrypt + * @param charSet the char set + * @return the string + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws IllegalBlockSizeException the illegal block size exception + * @throws BadPaddingException the bad padding exception + * @throws DataStudioSecurityException the data studio security exception + */ + public final String decryptString(String strToDecrypt, String charSet) throws UnsupportedEncodingException, + IllegalBlockSizeException, BadPaddingException, DataStudioSecurityException { + return new String(decryptByteArray(getBase4DecodeBase(strToDecrypt)), charSet); + } + + private byte[] getBase4DecodeBase(String strToDecrypt) { + return Base64.decodeBase64(strToDecrypt); + } + + /** + * Decrypt byte array. + * + * @param bytesToDecrypt the bytes to decrypt + * @return the byte[] + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws IllegalBlockSizeException the illegal block size exception + * @throws BadPaddingException the bad padding exception + * @throws DataStudioSecurityException the data studio security exception + */ + public final byte[] decryptByteArray(byte[] bytesToDecrypt) throws UnsupportedEncodingException, + IllegalBlockSizeException, BadPaddingException, DataStudioSecurityException { + byte[] ivByts = encryptionDecryption.getIVSalt(); + IvParameterSpec ivParam; + if (null != ivByts) { + ivParam = new IvParameterSpec(ivByts); + } else { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR)); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR); + } + + Cipher ciphr; + try { + ciphr = Cipher.getInstance("AES/CBC/PKCS5PADDING"); + } catch (NoSuchAlgorithmException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), exe); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, exe); + } catch (NoSuchPaddingException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), exe); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, exe); + } + + try { + ciphr.init(Cipher.DECRYPT_MODE, encryptionDecryption.getRandomKey(), ivParam); + } catch (InvalidKeyException e) { + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, e); + } catch (InvalidAlgorithmParameterException e) { + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, e); + } + return ciphr.doFinal(bytesToDecrypt); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/security/EncryptionUtil.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/security/EncryptionUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..a511a9f9a8e9c169936e3bc2de8caae078aa159d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/security/EncryptionUtil.java @@ -0,0 +1,244 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.security; + +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.Charset; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.spec.IvParameterSpec; + +import org.apache.commons.codec.binary.Base64; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DataStudioSecurityException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class EncryptionUtil. + * + * @since 3.0.0 + */ +public class EncryptionUtil { + private SecureUtil encryptionDecryption; + + /** + * Instantiates a new encryption util. + * + * @param encryptionDecryption the encryption decryption + */ + public EncryptionUtil(SecureUtil encryptionDecryption) { + this.encryptionDecryption = encryptionDecryption; + } + + /** + * Gets the encrypted string. + * + * @return the encrypted string + */ + public String getEncryptedString() { + return encryptionDecryption.getEncryptedString(); + } + + /** + * Sets the encrypted string. + * + * @param encryptedString the new encrypted string + */ + public void setEncryptedString(String encryptedString) { + encryptionDecryption.setEncryptedString(encryptedString); + } + + /** + * Encrypt. + * + * @param strToEncrypt the str to encrypt + * @return boolean true if success + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws IllegalBlockSizeException the illegal block size exception + * @throws BadPaddingException the bad padding exception + * @throws DataStudioSecurityException the data studio security exception + */ + public final boolean encrypt(String strToEncrypt) throws UnsupportedEncodingException, IllegalBlockSizeException, + BadPaddingException, DataStudioSecurityException { + setEncryptedString(encryptString(strToEncrypt, "UTF-8")); + return true; // return for tests + } + + /** + * Encrypt. + * + * @param strToEncrypt the str to encrypt + * @return boolean true if success + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws IllegalBlockSizeException the illegal block size exception + * @throws BadPaddingException the bad padding exception + * @throws DataStudioSecurityException the data studio security exception + */ + public final boolean encrypt(char[] strToEncrypt) throws UnsupportedEncodingException, IllegalBlockSizeException, + BadPaddingException, DataStudioSecurityException { + setEncryptedString(encryptString(strToEncrypt, "UTF-8")); + return true; // return for tests + } + + /** + * Encrypt string. + * + * @param strToEncrypt the str to encrypt + * @param encodingCharSet the encoding char set + * @return String encrypted string + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws IllegalBlockSizeException the illegal block size exception + * @throws BadPaddingException the bad padding exception + * @throws DataStudioSecurityException the data studio security exception + */ + public final String encryptString(String strToEncrypt, String encodingCharSet) throws UnsupportedEncodingException, + IllegalBlockSizeException, BadPaddingException, DataStudioSecurityException { + return Base64.encodeBase64String(encryptByteArray(strToEncrypt.getBytes(encodingCharSet))); + } + + /** + * Encrypt string. + * + * @param strToEncrypt the str to encrypt + * @param encodingCharSet the encoding char set + * @return String encrypted string + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws IllegalBlockSizeException the illegal block size exception + * @throws BadPaddingException the bad padding exception + * @throws DataStudioSecurityException the data studio security exception + */ + public final String encryptString(char[] strToEncrypt, String encodingCharSet) throws UnsupportedEncodingException, + IllegalBlockSizeException, BadPaddingException, DataStudioSecurityException { + String result = Base64.encodeBase64String(encryptByteArray(getBytes(strToEncrypt, encodingCharSet))); + return result; + } + + /** + * Encrypt byte array. + * + * @param bytesToEncrypt the bytes to encrypt + * @return byte[] then byte[] + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws IllegalBlockSizeException the illegal block size exception + * @throws BadPaddingException the bad padding exception + * @throws DataStudioSecurityException the data studio security exception + */ + public final byte[] encryptByteArray(byte[] bytesToEncrypt) throws UnsupportedEncodingException, + IllegalBlockSizeException, BadPaddingException, DataStudioSecurityException { + byte[] ivBytes = encryptionDecryption.getIVSalt(); + IvParameterSpec iv; + if (null != ivBytes) { + iv = new IvParameterSpec(ivBytes); + } else { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR)); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR); + } + Cipher cipher; + try { + cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); + } catch (NoSuchAlgorithmException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), exe); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, exe); + } catch (NoSuchPaddingException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), exe); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, exe); + } + + try { + cipher.init(Cipher.ENCRYPT_MODE, encryptionDecryption.getRandomKey(), iv); + } catch (InvalidKeyException e) { + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, e); + } catch (InvalidAlgorithmParameterException e) { + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, e); + } + + return cipher.doFinal(bytesToEncrypt); + } + + /** + * description: convert char[] to bytes[] + * + * @param chars the input chars + * @param encodeCharSet the convert charset + * @return byte[] the byte array + */ + public static byte[] getBytes(char[] chars, String encodeCharSet) { + Charset cs = Charset.forName(encodeCharSet); + CharBuffer cb = CharBuffer.allocate(chars.length); + cb.put(chars); + cb.flip(); + ByteBuffer bb = cs.encode(cb); + byte[] result = new byte[bb.limit()]; + bb.get(result, 0, result.length); + return result; + } + + /** + * description: convert byte[] to char[] + * + * @param bytes the input bytes + * @param encodeCharSet the convert charset + * @return char[] the char array + */ + public static char[] getChars(byte[] bytes, String encodeCharset) { + Charset cs = Charset.forName(encodeCharset); + ByteBuffer bb = ByteBuffer.allocate(bytes.length); + bb.put(bytes); + bb.flip(); + CharBuffer cb = cs.decode(bb); + return cb.array(); + } + + /** + * description: remove space from chars + * + * @param chars the char array to dispose + * @return char[] remove space array + */ + public static char[] trimChars(char[] chars) { + int startPos = 0; + int endPos = chars.length - 1; + for (; startPos < chars.length ; startPos ++) { + if (!Character.isSpaceChar(chars[startPos])) { + break; + } + } + for (; endPos > startPos; endPos -= 1) { + if (!Character.isSpaceChar(chars[startPos])) { + break; + } + } + if (endPos <= startPos) { + return new char[0]; + } + char[] results = new char[endPos - startPos + 1]; + System.arraycopy(chars, startPos, results, 0, results.length); + return results; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/security/SecureRandomGenerator.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/security/SecureRandomGenerator.java new file mode 100644 index 0000000000000000000000000000000000000000..b1dec377e46bf8c1a1724a684d7573c7b367bf22 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/security/SecureRandomGenerator.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.security; + +import java.security.SecureRandom; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * + * Title: class + * + * Description: The Class SecureRandomGenerator. + * + * @since 3.0.0 + */ +public class SecureRandomGenerator { + private static final AtomicInteger CNT_VAL = new AtomicInteger(0); + + private static void setSeed(SecureRandom random) { + if (CNT_VAL.incrementAndGet() > 100) { + CNT_VAL.set(0); + byte[] seed = new byte[64]; + SecureRandom seedRnd = new SecureRandom(); + seedRnd.nextBytes(seed); + random.setSeed(seed); + } + } + + /** + * Get random number + * + * @return the byte [ ] + */ + public static byte[] getRandomNumber() { + byte[] iv = new byte[16]; + SecureRandom random = new SecureRandom(); + setSeed(random); + random.nextBytes(iv); + return iv; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/security/SecureUtil.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/security/SecureUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..3c05d86be4d15ce24e6a3eebd6929b5a8856da02 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/security/SecureUtil.java @@ -0,0 +1,565 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.security; + +import java.io.File; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Field; +import java.math.BigInteger; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.NoSuchAlgorithmException; +import java.security.spec.InvalidKeySpecException; +import java.util.Locale; + +import javax.crypto.BadPaddingException; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.spec.SecretKeySpec; + +import org.opengauss.mppdbide.utils.EnvirnmentVariableValidator; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.MemoryCleaner; +import org.opengauss.mppdbide.utils.exceptions.DataStudioSecurityException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.files.DSFolderDeleteUtility; +import org.opengauss.mppdbide.utils.files.FilePermissionFactory; +import org.opengauss.mppdbide.utils.files.ISetFilePermission; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.AESAlgorithmUtility.KeyPartFileCreateOption; + +/** + * + * Title: class + * + * Description: The Class SecureUtil. + * + * @since 3.0.0 + */ +public final class SecureUtil { + + private static final String TEMP_FILE = "temp.txt"; + private static final String CONFIG = String.format(Locale.ENGLISH, "%s%s", + EnvirnmentVariableValidator.validateAndGetFileSeperator(), "config"); + private static final String PROFILE_DUMMY = EnvirnmentVariableValidator.validateAndGetFileSeperator() + "profile" + + EnvirnmentVariableValidator.validateAndGetFileSeperator() + "dummy"; + private ISetFilePermission withPermission = FilePermissionFactory.getFilePermissionInstance(); + + private SecretKeySpec randomKey; + + private byte[] key; + + private String decryptedString; + + private String encryptedString; + + private EncryptionUtil encryption; + private DecryptionUtil decryption; + private AESAlgorithmUtility aesAlgorithmUtil; + + private String packagePath; + private String strRootKey; + + private String strWorkKey; + private static final Object INSTANCE_LOCK = new Object(); + + /** + * Sets the package path. + * + * @param path the new package path + */ + public void setPackagePath(String path) { + this.packagePath = path; + } + + /** + * Gets the security folder. + * + * @return the security folder + */ + public String getSecurityFolder() { + return packagePath + CONFIG; + } + + /** + * Instantiates a new secure util. + */ + public SecureUtil() { + // Making this class singleton. + this.encryption = new EncryptionUtil(this); + this.decryption = new DecryptionUtil(this); + this.aesAlgorithmUtil = new AESAlgorithmUtility(this); + } + + /** + * Gets the aes algorithm util. + * + * @return the aes algorithm util + */ + public AESAlgorithmUtility getAesAlgorithmUtil() { + return this.aesAlgorithmUtil; + } + + /** + * Sets the aes algorithm util. + * + * @param aesAlgorithmUtil the new aes algorithm util + */ + public void setAesAlgorithmUtil(AESAlgorithmUtility aesAlgorithmUtil) { + this.aesAlgorithmUtil = aesAlgorithmUtil; + } + + /** + * Sets the str root key. + * + * @param strRootKey the new str root key + */ + public void setStrRootKey(String strRootKey) { + this.strRootKey = strRootKey; + } + + /** + * Sets the str work key. + * + * @param strWorkKey the new str work key + */ + public void setStrWorkKey(String strWorkKey) { + this.strWorkKey = strWorkKey; + } + + /** + * Creates the secure salt. + * + * @throws DataStudioSecurityException the data studio security exception + * @throws DatabaseOperationException the database operation exception + * @throws IOException Signals that an I/O exception has occurred. + */ + protected String createSecureSalt() throws DataStudioSecurityException, DatabaseOperationException, IOException { + BigInteger bigRandomNumber = getAesAlgorithmUtil().getRandom(); + return bigRandomNumber.toString(); + } + + /** + * Run pre encryption task. + * + * @throws DataStudioSecurityException the data studio security exception + */ + public void runPreEncryptionTask() throws DataStudioSecurityException { + File file = new File(packagePath); + + // Check if folder has write permission + boolean canWrite = Files.isWritable(file.toPath()); + if (!canWrite) { + return; + } + + try { + ISetFilePermission set = FilePermissionFactory.getFilePermissionInstance(); + set.createFileWithPermission(getSecurityFolder(), true, null, true); + set.createFileWithPermission(getSecurityFolder() + + EnvirnmentVariableValidator.validateAndGetFileSeperator() + "temp", true, null, true); + set.createFileWithPermission(getSecurityFolder() + + EnvirnmentVariableValidator.validateAndGetFileSeperator() + "dropin", true, null, true); + set.createFileWithPermission(getSecurityFolder() + + EnvirnmentVariableValidator.validateAndGetFileSeperator() + "profile", true, null, true); + String salt = createSecureSalt(); + aesAlgorithmUtil.setPbkdf2Salt(salt); + KeyPartFileCreateOption keyPartFileCreate = getAesAlgorithmUtil() + .createSecurityFolder(getSecurityFolder()); + if (keyPartFileCreate.equals(KeyPartFileCreateOption.CREATED)) { + genarateRootKey(); + } + } catch (IOException ex) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), ex); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, ex); + } catch (IllegalArgumentException ex) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), ex); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, ex); + } catch (DatabaseOperationException ex) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), ex); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, ex); + } + } + + private void genarateRootKey() + throws IOException, DataStudioSecurityException, DatabaseOperationException { + // RootKey based on XOR operation from the Different SEC_PART + try { + setStrRootKey(getAesAlgorithmUtil().generateXORResult(getSecurityFolder())); + getAesAlgorithmUtil().setKey(this.strRootKey); + // Get the Working Key and write in 4th Key File + String strWorkingKeyRandom = getAesAlgorithmUtil().getRandom().toString(); + String strWorkingKey = null; + strWorkingKey = getAesAlgorithmUtil().generatePBKDF(strWorkingKeyRandom, true); + encryption.encrypt(strWorkingKey); + } catch (NoSuchAlgorithmException | InvalidKeySpecException | IllegalBlockSizeException + | BadPaddingException ex) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), ex); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, ex); + } + + withPermission.createFileWithPermission(String.format(Locale.ENGLISH, "%s%s", + getSecurityFolder(), PROFILE_DUMMY), true, null, true); + getAesAlgorithmUtil().writeValueInFile(String.format(Locale.ENGLISH, "%s%s", + getSecurityFolder(), PROFILE_DUMMY), TEMP_FILE, encryption.getEncryptedString()); + setStrWorkKey(encryption.getEncryptedString()); + } + + /** + * Encrypt prd. + * + * @param prd the prd + * @return the string + * @throws DataStudioSecurityException the data studio security exception + */ + public String encryptPrd(char[] prd) throws DataStudioSecurityException { + + MPPDBIDELoggerUtility.securityInfo("Encrypting password to be saved"); + File keyDir = new File(String.format(Locale.ENGLISH, "%s%s", getSecurityFolder(), PROFILE_DUMMY)); + // Read the Folder Name where user wants to create the All KEY Files + + try { + setStrWorkKey(getAesAlgorithmUtil().readWKResult(keyDir, TEMP_FILE)); + setStrRootKey(getAesAlgorithmUtil().generateXORResult(getSecurityFolder())); + + getAesAlgorithmUtil().setKey(this.strRootKey); + decryption.decrypt(this.strWorkKey); + + // Set the WK for prd Encryption + getAesAlgorithmUtil().setKey(decryption.getDecryptedString()); + char[] trimChars = EncryptionUtil.trimChars(prd); + encryption.encrypt(trimChars); + clearPassword(trimChars); + } catch (IOException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), exe); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, exe); + } catch (NoSuchAlgorithmException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), exe); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, exe); + } catch (InvalidKeySpecException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), exe); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, exe); + } catch (IllegalBlockSizeException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), exe); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, exe); + } catch (BadPaddingException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), exe); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, exe); + } + return encryption.getEncryptedString(); + + } + + /** + * Decrypt prd. + * + * @param string the string + * @return the char[] + * @throws DataStudioSecurityException the data studio security exception + */ + public char[] decryptPrd(String string) throws DataStudioSecurityException { + try { + return decryptPswdHandleError(string); + } catch (DataStudioSecurityException exe) { + resetSecurityDetails(); + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), exe); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, exe); + } + } + + /** + * Decrypt pswd handle error. + * + * @param string the string + * @return the char[] + * @throws DataStudioSecurityException the data studio security exception + */ + private char[] decryptPswdHandleError(String string) throws DataStudioSecurityException { + MPPDBIDELoggerUtility.securityInfo("Decrypting saved password"); + File keyDir = new File(String.format(Locale.ENGLISH, "%s%s", getSecurityFolder(), PROFILE_DUMMY)); + try { + + this.strWorkKey = this.aesAlgorithmUtil.readWKResult(keyDir, TEMP_FILE); + + this.strRootKey = this.aesAlgorithmUtil.generateXORResult(getSecurityFolder()); + getAesAlgorithmUtil().setKey(this.strRootKey); + decryption.decrypt(this.strWorkKey); + + // Set the WK for prd Encryption + getAesAlgorithmUtil().setKey(decryption.getDecryptedString()); + + decryption.decrypt(string); + } catch (IOException exe) { + MPPDBIDELoggerUtility + .securityError(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR)); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, exe); + } catch (NoSuchAlgorithmException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), exe); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, exe); + } catch (IllegalBlockSizeException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), exe); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, exe); + } catch (BadPaddingException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), exe); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, exe); + } catch (InvalidKeySpecException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), exe); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, exe); + } catch (Exception exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), exe); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, exe); + } + + return decryption.getDecryptedString().toCharArray(); + } + + /** + * Reset security details. + * + * @throws DataStudioSecurityException the data studio security exception + */ + private void resetSecurityDetails() throws DataStudioSecurityException { + deleteSecurityFolder(); + runPreEncryptionTask(); + } + + /** + * Delete security folder. + */ + public void deleteSecurityFolder() { + Path securityFolderPath = Paths.get(getSecurityFolder()); + if (!Files.exists(securityFolderPath)) { + return; + } + try { + Files.walkFileTree(securityFolderPath, new DSFolderDeleteUtility()); + } catch (IOException exception) { + MPPDBIDELoggerUtility + .securityError(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR)); + } + } + + /** + * Gets the random key. + * + * @return the random key + */ + public SecretKeySpec getRandomKey() { + return this.randomKey; + } + + /** + * Sets the random key. + * + * @param randomKey the new random key + */ + public void setRandomKey(SecretKeySpec randomKey) { + this.randomKey = randomKey; + } + + /** + * Gets the key. + * + * @return the key + */ + public byte[] getKey() { + if (this.key == null) { + return new byte[0]; + } + return (byte[]) this.key.clone(); + } + + /** + * Sets the key. + * + * @param key the new key + */ + public void setKey(byte[] key) { + this.key = (byte[]) key.clone(); + } + + /** + * Gets the decrypted string. + * + * @return the decrypted string + */ + public String getDecryptedString() { + return this.decryptedString; + } + + /** + * Sets the decrypted string. + * + * @param decryptedString the new decrypted string + */ + public void setDecryptedString(String decryptedString) { + this.decryptedString = decryptedString; + } + + /** + * Gets the encrypted string. + * + * @return the encrypted string + */ + public String getEncryptedString() { + return this.encryptedString; + } + + /** + * Sets the encrypted string. + * + * @param encryptedString the new encrypted string + */ + public void setEncryptedString(String encryptedString) { + this.encryptedString = encryptedString; + } + + /** + * Encrypt byte array. + * + * @param bytesToEncrypt the bytes to encrypt + * @return the byte[] + * @throws DataStudioSecurityException the data studio security exception + */ + public byte[] encryptByteArray(byte[] bytesToEncrypt) throws DataStudioSecurityException { + try { + MPPDBIDELoggerUtility.securityInfo("Encrypting files to be autosaved"); + File keyDir = new File(String.format(Locale.ENGLISH, "%s%s", getSecurityFolder(), PROFILE_DUMMY)); + setStrWorkKey(getAesAlgorithmUtil().readWKResult(keyDir, TEMP_FILE)); + setStrRootKey(getAesAlgorithmUtil().generateXORResult(getSecurityFolder())); + + getAesAlgorithmUtil().setKey(this.strRootKey); + decryption.decrypt(this.strWorkKey); + + getAesAlgorithmUtil().setKey(decryption.getDecryptedString()); + + return this.encryption.encryptByteArray(bytesToEncrypt); + } catch (IllegalBlockSizeException | BadPaddingException | InvalidKeySpecException | NoSuchAlgorithmException + | IOException exe) { + resetSecurityDetails(); + MPPDBIDELoggerUtility + .securityError(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR)); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, exe); + } catch (DataStudioSecurityException exe) { + resetSecurityDetails(); + throw exe; + } + } + + /** + * Decrypt byte array. + * + * @param bytesToDecrypt the bytes to decrypt + * @return the byte[] + * @throws DataStudioSecurityException the data studio security exception + */ + public byte[] decryptByteArray(byte[] bytesToDecrypt) throws DataStudioSecurityException { + MPPDBIDELoggerUtility.securityInfo("Decrypting autosaved files"); + try { + File keyDir = null; + keyDir = new File(String.format(Locale.ENGLISH, "%s%s", getSecurityFolder(), PROFILE_DUMMY)); + this.strWorkKey = this.aesAlgorithmUtil.readWKResult(keyDir, TEMP_FILE); + this.strRootKey = this.aesAlgorithmUtil.generateXORResult(getSecurityFolder()); + + this.aesAlgorithmUtil.setKey(this.strRootKey); + decryption.decrypt(this.strWorkKey); + + this.aesAlgorithmUtil.setKey(decryption.getDecryptedString()); + + return this.decryption.decryptByteArray(bytesToDecrypt); + } catch (IllegalBlockSizeException | BadPaddingException | InvalidKeySpecException | NoSuchAlgorithmException + | IOException exe) { + resetSecurityDetails(); + MPPDBIDELoggerUtility + .securityError(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR)); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, exe); + } + } + + /** + * Encrypt string. + * + * @param str the str + * @param charSet the char set + * @return the string + * @throws DataStudioSecurityException the data studio security exception + */ + public String encryptString(String str, String charSet) throws DataStudioSecurityException { + try { + return this.encryption.encryptString(str, charSet); + } catch (UnsupportedEncodingException | IllegalBlockSizeException | BadPaddingException exe) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), exe); + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, exe); + } + } + + /** + * Decrypt string. + * + * @param str the str + * @param charSet the char set + * @return the string + * @throws DataStudioSecurityException the data studio security exception + */ + public String decryptString(String str, String charSet) throws DataStudioSecurityException { + try { + return this.decryption.decryptString(str, charSet); + } catch (UnsupportedEncodingException | IllegalBlockSizeException | BadPaddingException e) { + throw new DataStudioSecurityException(IMessagesConstants.ERR_DS_SECURITY_ERROR, e); + } + } + + /** + * Gets the IV salt. + * + * @return the IV salt + */ + public byte[] getIVSalt() { + return this.aesAlgorithmUtil.getIVSalt(); + } + + /** + * Clear password. + * + * @param clearProfilePrd the clear profile prd + */ + public static void clearPassword(char[] clearProfilePrd) { + if (null == clearProfilePrd) { + return; + } + + for (int i = 0; i < clearProfilePrd.length; i++) { + clearProfilePrd[i] = 0; + } + MemoryCleaner.cleanUpMemory(); + } + + /** + * description: clean key of string info + * + * @param key then clean String key + */ + public static void cleanKeyString(String key) { + if (key == null || "".equals(key)) { + return; + } + return; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/stringparse/IServerMessageParseUtils.java b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/stringparse/IServerMessageParseUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..d305027eab07fe87054c5e64935f265bbfff71cc --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.utils/src/org/opengauss/mppdbide/utils/stringparse/IServerMessageParseUtils.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.utils.stringparse; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Title: IServerMessageParseUtils + * + * @since 3.0.0 + */ +public interface IServerMessageParseUtils { + /** + * String constant ioClient + */ + String IO_CLIENT = "ioClient"; + + /** + * utility class to extract query from server error message + * + * @param errorMessage : error msg + * @return query query + */ + static String extractQueryFromErrorMessage(String errorMessage) { + Pattern pattern = Pattern.compile("sql\\s*=\\s*((.|\\r?\\n)*?)(sessionId)"); + Matcher matcher = pattern.matcher(errorMessage); + + if (matcher.find()) { + String matchedText = matcher.group(1); + if (null != matchedText) { + return matchedText.trim(); + } + } + return ""; + } + + /** + * utility class to extract query without comments from query + * + * @param query : input query + * @return query without comments + */ + static String extractQueryWithoutComments(String query) { + Pattern pattern = Pattern.compile("(\\/\\*(.|\\s)*?\\*\\/)?((.|\\s)*)"); + Matcher matcher = pattern.matcher(query); + + if (matcher.find()) { + String matchedText = matcher.group(3); + if (null != matchedText) { + return matchedText.trim(); + } + } + return ""; + } + + /** + * the isQuerySelectFunction + * + * @param query the query + * @return true, if is select query + */ + static boolean isQuerySelectFunction(String query) { + Pattern pattern = Pattern.compile("^\\s*SELECT\\s*(.|\\s)*\\((.|\\s)*\\)", Pattern.CASE_INSENSITIVE); + Matcher matcher = pattern.matcher(query); + + if (matcher.find()) { + return true; + } + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/.classpath b/code/datastudio/src/org.opengauss.mppdbide.view/.classpath new file mode 100644 index 0000000000000000000000000000000000000000..71b0e34b9c650e5852f4eba94bb4a1ad37ea4dd0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/.classpath @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/.gitignore b/code/datastudio/src/org.opengauss.mppdbide.view/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ddc25c7fcd00a3a38f67eabde7efb88c26a8c3a8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/.gitignore @@ -0,0 +1,3 @@ +/bin/ +/.settings/ +/target/ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/.project b/code/datastudio/src/org.opengauss.mppdbide.view/.project new file mode 100644 index 0000000000000000000000000000000000000000..46aebff853cdaef7f497ae1f533da134d745335c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/.project @@ -0,0 +1,40 @@ + + + org.opengauss.mppdbide.view + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.pde.api.tools.apiAnalysisBuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + org.eclipse.pde.api.tools.apiAnalysisNature + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/Application.e4xmi b/code/datastudio/src/org.opengauss.mppdbide.view/Application.e4xmi new file mode 100644 index 0000000000000000000000000000000000000000..26da7d5e56fd0dc252a3103b2a4e804d53ebaa40 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/Application.e4xmi @@ -0,0 +1,1045 @@ + + + + shellMaximized + + + NoMove + + NoMove + + + + + + + NoMove + + NoMove + + + + + + + + + + + + + + + + + + + + NoMove + + NoMove + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + removeOnHide + + + + + + + + + + + + + + + + + NoMove + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + type:user + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + type:user + + + + type:user + + + + type:user + + + type:user + + + type:user + + + type:user + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/META-INF/MANIFEST.MF b/code/datastudio/src/org.opengauss.mppdbide.view/META-INF/MANIFEST.MF new file mode 100644 index 0000000000000000000000000000000000000000..9263a8b234ba818aa6d310452a324e68dbc9a5e6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/META-INF/MANIFEST.MF @@ -0,0 +1,101 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: MPPDBIDE_View +Bundle-SymbolicName: org.opengauss.mppdbide.view;singleton:=true +Bundle-Version: 1.0.0.qualifier +Bundle-ClassPath: ., + gson-2.8.6.jar, + guava-30.1.1-jre.jar +Bundle-Activator: org.opengauss.mppdbide.view.Activator +Bundle-Vendor: Huawei Technologies +Export-Package: org.opengauss.mppdbide.view.utils +Require-Bundle: org.eclipse.core.runtime;bundle-version="3.15.300", + org.eclipse.swt;bundle-version="3.108.0", + javax.inject;bundle-version="1.0.0", + org.eclipse.e4.core.di;bundle-version="1.7.200", + org.eclipse.e4.ui.workbench;bundle-version="1.10.0", + org.eclipse.e4.ui.di;bundle-version="1.2.600", + org.eclipse.jface;bundle-version="3.14.100", + org.eclipse.jface.text;bundle-version="3.15.200", + org.eclipse.ui;bundle-version="3.113.0", + org.opengauss.mppdbide.util;bundle-version="1.0.0", + org.opengauss.mppdbide.debuger;bundle-version="1.0.0", + org.eclipse.e4.core.contexts;bundle-version="1.8.100", + org.eclipse.e4.ui.workbench.swt;bundle-version="0.14.600", + org.eclipse.core.expressions;bundle-version="3.6.400", + org.eclipse.ui.editors;bundle-version="3.11.500", + org.eclipse.e4.core.commands;bundle-version="0.12.600", + org.eclipse.core.resources;bundle-version="3.13.400", + org.eclipse.e4.core.di.extensions;bundle-version="0.15.300", + org.eclipse.e4.ui.model.workbench;bundle-version="2.1.400", + org.eclipse.equinox.launcher;bundle-version="1.5.400", + javax.annotation;bundle-version="1.2.0", + org.eclipse.osgi.services;bundle-version="3.8.0", + org.eclipse.e4.core.services;bundle-version="2.1.400", + commons-csv;bundle-version="1.0.0", + org.opengauss.mppdbide.adapter.gauss;bundle-version="1.0.0", + org.eclipse.e4.ui.bindings;bundle-version="0.12.500", + org.eclipse.e4.ui.services;bundle-version="1.3.500", + org.eclipse.nebula.widgets.nattable.core;bundle-version="1.6.0", + org.eclipse.nebula.widgets.nattable.extension.e4;bundle-version="1.2.0", + org.eclipse.nebula.widgets.nattable.extension.glazedlists;bundle-version="1.6.0", + org.eclipse.nebula.widgets.nattable.extension.nebula;bundle-version="1.2.0", + org.eclipse.e4.ui.workbench.renderers.swt;bundle-version="0.14.700", + org.eclipse.mylyn.commons.ui;bundle-version="3.24.2", + ca.odell.glazedlists;bundle-version="1.9.0", + org.eclipse.ui.views;bundle-version="3.9.400", + org.eclipse.nebula.widgets.richtext;bundle-version="1.3.0", + org.opengauss.mppdbide.presentation;bundle-version="1.0.0", + org.eclipse.nebula.widgets.cdatetime;bundle-version="1.4.0", + org.apache.commons.lang;bundle-version="2.6.0", + org.apache.commons.io;bundle-version="2.6.0", + org.opengauss.mppdbide.explainplan, + org.opengauss.mppdbide.bl;bundle-version="1.0.0", + Common-collection;bundle-version="1.0.0", + org.eclipse.gef.geometry;bundle-version="5.0.0", + org.eclipse.gef.mvc.fx;bundle-version="5.1.0", + org.eclipse.gef.graph;bundle-version="5.1.0", + org.eclipse.gef.common;bundle-version="5.0.0", + org.eclipse.gef.layout;bundle-version="5.0.0", + org.eclipse.gef.fx;bundle-version="5.0.2", + org.eclipse.gef.zest.fx;bundle-version="5.1.0", + org.eclipse.gef.fx.swt;bundle-version="5.0.2", + org.eclipse.osgi, + com.google.inject;bundle-version="3.0.0", + org.eclipse.gef.geometry.convert.fx;bundle-version="5.0.0", + org.eclipse.gef.geometry.convert.swt;bundle-version="5.0.2", + org.eclipse.gef.fx.jface;bundle-version="5.0.2", + org.apache.commons.lang3;bundle-version="3.1.0", + openjfx.base;bundle-version="17.0.1", + openjfx.controls;bundle-version="17.0.1", + openjfx.graphics.win32_64;bundle-version="17.0.1", + openjfx.swing;bundle-version="17.0.1", + openjfx.swt;bundle-version="17.0.1" +Bundle-RequiredExecutionEnvironment: JavaSE-11 +Bundle-ActivationPolicy: lazy +Import-Package: com.google.common.collect;version="15.0.0", + com.google.inject;version="1.3.0", + com.google.inject.binder;version="1.3.0", + com.google.inject.util;version="1.3.0", + org.opengauss.mppdbide.editor.extension.nameparser, + org.opengauss.mppdbide.explainplan.ui.model, + org.opengauss.mppdbide.parser.alias, + org.opengauss.mppdbide.parser.runtimehandler, + org.opengauss.mppdbide.presentation, + org.opengauss.mppdbide.presentation.contentassistprocesser, + org.opengauss.mppdbide.presentation.edittabledata, + org.opengauss.mppdbide.presentation.exportdata, + org.opengauss.mppdbide.presentation.grid, + org.opengauss.mppdbide.presentation.grid.resultset, + org.opengauss.mppdbide.presentation.objectbrowser, + org.opengauss.mppdbide.presentation.objectproperties, + org.opengauss.mppdbide.presentation.resultset, + org.opengauss.mppdbide.presentation.resultsetif, + org.opengauss.mppdbide.presentation.search, + org.opengauss.mppdbide.presentation.visualexplainplan, + javax.annotation;version="1.0.0";resolution:=optional, + javax.inject;version="1.0.0", + org.apache.commons.collections4.trie, + org.apache.commons.csv, + org.eclipse.ui.editors.text, + org.postgresql diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/OSGI-INF/l10n/bundle.properties b/code/datastudio/src/org.opengauss.mppdbide.view/OSGI-INF/l10n/bundle.properties new file mode 100644 index 0000000000000000000000000000000000000000..519a6f4557055c466d8b997494f4068cbb180031 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/OSGI-INF/l10n/bundle.properties @@ -0,0 +1,1320 @@ +#Handlers +handler.id.refreshdbobject = org.opengauss.mppdbide.handler.id.refreshdbobject +handler.id.disconnectconnectionprofile = org.opengauss.mppdbide.handler.id.disconnectconnectionprofile +handler.id.executedbobject = org.opengauss.mppdbide.handler.id.executedbobject +handler.id.debugdbobject = org.opengauss.mppdbide.handler.id.debugdbobject +handler.newdbconnection = org.opengauss.mppdbide.handler.id.newdbconnection +handler.toggleconsole = org.opengauss.mppdbide.handler.id.toggleconsole +handler.execute = org.opengauss.mppdbide.handler.id.execute + +#Commands + +#Command new DB connection +command.id.newdbconnection = org.opengauss.mppdbide.command.id.newdbconnection +command.name.newdbConnection = New DB Connection +command.description.newdbconnection = New DB Connection + +#Command and handler for new DB connection commandline +command.id.newdbconnectioncommandline = org.opengauss.mppdbide.view.command.newdbconnectioncommandline +command.name.newdbconnectioncommandline = New DB Connection Commandline +command.description.newdbconnectioncommandline = New DB Connection Commandline +handler.newdbconnectioncommandline = org.opengauss.mppdbide.view.handler.newdbconnectioncommandline + +#command export connections +#command.exportconnections =org.opengauss.mppdbide.view.command.exportconnections +#command.name.exportconnections=Export Connections +#command.description.exportconnections= Export Connections + + + +#Command toggle Console +command.id.toggleconsole = org.opengauss.mppdbide.command.id.toggleconsole +command.name.toggleconsole = Console +command.description.toggleconsole = Console + +#Command refresh connection profile +#command.id.refreshconnectionprfofile = org.opengauss.mppdbide.command.id.refreshconnectionprfofile +#command.name.refreshconnectionprfofile = Refresh connection profile +#command.description.refreshconnectionprfofile = Refresh connection profile + +#Command refresh database object group +#command.id.refreshdbobjectgroup = org.opengauss.mppdbide.command.id.refreshdbobjectgroup +#command.name.refreshdbobjectgroup = Refresh DB object group +#command.description.refreshdbobjectgroup = Refresh DB object group + +#Command refresh database object +command.id.refreshdbobject = org.opengauss.mppdbide.command.id.refreshdbobject +command.name.refreshdbobject = Refresh +command.description.refreshdbobject = Refresh the Database object + +#Command disconnect connection profile +command.id.disconnectconnectionprofile = org.opengauss.mppdbide.command.id.disconnectconnectionprofile +command.name.disconnectconnectionprofile = Disconnect profile +command.description.disconnectconnectionprofile = Disconnect profile + +#Command execute database object +command.id.executedbobject = org.opengauss.mppdbide.command.id.executedbobject +command.name.executedbobject = Execute DB object +command.description.executedbobject = Execute DB object + +#Command About dialog +command.id.about = org.opengauss.mppdbide.command.id.aboutdialog +command.name.about = About +command.description.about = About Data Studio + +#Windows +window.id.mainwindow = org.opengauss.mppdbide.window.id.mainwindow + +#Menus +#Main menu +menu.id.mainmenu = org.opengauss.mppdbide.menu.id.main + +#File Menu +menu.id.filemenu = org.opengauss.mppdbide.menu.id.file +menu.label.filemenu = &File +menu.mnemonics.filemenu = F + +#Settings Menu +menu.id.settingsmenu = org.opengauss.mppdbide.view.menu.settings +menu.label.settingsmenu = Settin&gs +menu.mnemonics.settingsmenu = G + +#Language Menu +menu.id.filelanguagemenu = org.opengauss.mppdbide.view.menu.language +menu.label.filelanguagemenu = &Language +menu.mnemonics.filelanguagemenu = L + +#English Language +filelanguagemenu.id.englishlanguage = org.opengauss.mppdbide.view.handledmenuitem.englishlanguage +filelanguagemenu.label.englishlanguage =(en_US) &English (E) +filelanguagemenu.mnemonics.englishlanguage = E +filelanguagemenu.tooltip.englishlanguage = English + +#Chinese Language +filelanguagemenu.id.chineselanguage = org.opengauss.mppdbide.view.handledmenuitem.chineselanguage +filelanguagemenu.label.chineselanguage =(zh_CN) \u4E2D\u6587\uFF08\u7B80\u4F53\uFF09(&C) +filelanguagemenu.mnemonics.chineselanguage = C +filelanguagemenu.tooltip.chineselanguage = \u4E2D\u6587 + +#Preferences +filelanguagemenu.id.preferences = org.opengauss.mppdbide.view.handledmenuitem.preferences +filelanguagemenu.label.preferences =&Preferences +filelanguagemenu.mnemonics.preferences =P +filelanguagemenu.tooltip.preferences = Preferences + +#New connection +filemenu.id.newconnection = org.opengauss.filemenu.id.newconnection +filemenu.label.newconnection = &New Connection +filemenu.mnemonics.newconnection = N +filemenu.tooltip.newconnection = New Connection + + + +#Export connection +filemenu.id.exportconnections = org.opengauss.filemenu.id.exportconnections +filemenu.label.exportconnections = &Export Connections +filemenu.mnemonics.exportconnections = E +filemenu.tooltip.exportconnections = Export Connections + + +#import connection +filemenu.id.importconnections = org.opengauss.filemenu.id.importconnections +filemenu.label.importconnections = &Import Connections +filemenu.mnemonics.importconnections = I +filemenu.tooltip.importconnections = Import Connections + +#Remove connection +filemenu.id.removeconnection = org.opengauss.filemenu.id.removeconnection +filemenu.label.removeconnection = &Remove Connection +filemenu.mnemonics.removeconnection = R +filemenu.tooltip.removeconnection = Remove Connection + +#Connect to db +filemenu.id.connecttodb = org.opengauss.filemenu.id.connecttodb +filemenu.label.connecttodb = &Connect to DB +filemenu.mnemonics.connecttodb = C +filemenu.tooltip.connecttodb = Connect to DB + +#Edit Menu +menu.id.editmenu = org.opengauss.mppdbide.menu.id.edit +menu.label.editmenu = &Edit +menu.mnemonics.editmenu = E + +#View Menu +menu.id.viewmenu = org.opengauss.mppdbide.menu.id.view +menu.label.viewmenu = &View +menu.mnemonics.viewmenu = V + +#Console window +viewmenu.id.console = org.opengauss.viewmenu.id.console +viewmenu.label.console = Messages +viewmenu.mnemonics.console = M +viewmenu.tooltip.console = Messages + + + +#Open New Terminal Menu +editmenu.id.opennewterminal = org.opengauss.edimenu.id.opennewterminal +editmenu.label.opennewterminal = Open Terminal +editmenu.mnemonics.opennewterminal = O +editmenu.tooltip.opennewterminal = Open Terminal + +#console text menu +view.popupmenu.id.console =org.opengauss.mppdbide.view.popupmenu.id.console +view.popupmenu.label.console=Console context menu +view.popupmenu.mnemonics.console= C +view.popupmenu.tooltip.console= Console context menu + +#filterresultwindowcontent +viewmenu.id.filterresultwindowcontent=org.opengauss.mppdbide.view.directtoolitem.id.resultfilter +viewmenu.label.filterresultwindowcontent= +viewmenu.mnemonics.filterresultwindowcontent=F +viewmenu.tooltip.filterresultwindowcontent=Result Data Filtered + + +#edit table +dataviewer.toolbar.edit.id.edittablewizard=org.opengauss.mppdbide.view.handledtoolitem.id.editableflag +dataviewer.toolbar.edit.label.edittablewizard=Edit Table +dataviewer.toolbar.edit.mnemonics.edittablewizard= +dataviewer.toolbar.edit.tooltip.edittablewizard=Edit Table + +#view filter +view.directtoolitem.id.viewfilter=org.opengauss.mppdbide.view.directtoolitem.id.viewfilter +view.directtoolitem.label.viewfilter= +view.directtoolitem.mnemonics.viewfilter= +view.directtoolitem.tooltip.viewfilter=Varibale Data Filtered + + +#SQL Terminal Window +viewmenu.id.sqlterminal = org.opengauss.viewmenu.id.sqlterminal +viewmenu.label.sqlterminal = SQLTerminal +viewmenu.mnemonics.sqlterminal = T +viewmenu.tooltip.sqlterminal = SQLTerminal + +#Object Browser Window +viewmenu.id.objectbrowser = org.opengauss.viewmenu.id.objectbrowser +viewmenu.label.objectbrowser = Object Browser +viewmenu.mnemonics.objectbrowser = O +viewmenu.tooltip.objectbrowser = Object Browser + +#Object Browser Window +viewmenu.id.advancedsearch = org.opengauss.viewmenu.id.advancedsearch +viewmenu.label.advancedsearch = &Advanced Search +viewmenu.mnemonics.advancedsearch = A +viewmenu.tooltip.advancedsearch = Advanced Search + +#Edit Table Data window +viewmenu.id.edittabledata = org.opengauss.viewmenu.id.edittabledata +viewmenu.label.edittabledata = Edit Table Data +viewmenu.mnemonics.edittabledata = E +viewmenu.tooltip.edittabledata = Edit Table Data + +#Result window +viewmenu.id.result = org.opengauss.viewmenu.id.result +viewmenu.label.result = &Result +viewmenu.mnemonics.result = R +viewmenu.tooltip.result = Result + +#CopyResult Menu +viewmenu.id.copyresultwindowcontent = org.opengauss.viewmenu.id.result +viewmenu.label.copyresultwindowcontent = Copy Result window content +viewmenu.mnemonics.copyresultwindowcontent = P +viewmenu.tooltip.copyresultwindowcontent = Copy Result window content + +#ExportResult Menu +viewmenu.id.exportresulttocsv = org.opengauss.viewmenu.id.result +viewmenu.label.exportresulttocsv = Export All Results To CSV +viewmenu.mnemonics.exportresulttocsv = S +viewmenu.tooltip.exportresulttocsv = Export All Results To CSV + +#ExportCurrentResult Menu +viewmenu.id.exportcurrentresulttocsv = org.opengauss.viewmenu.id.result +viewmenu.label.exportcurrentresulttocsv = Export Current Page to CSV +viewmenu.tooltip.exportcurrentresulttocsv = Export Current Page to CSV + +#Breakpoint window +viewmenu.id.breakpoint = org.opengauss.viewmenu.id.breakpoint +viewmenu.label.breakpoint = Breakpoints +viewmenu.mnemonics.breakpoint = B +viewmenu.tooltip.breakpoint = Breakpoints + +#Stack window +viewmenu.id.stack = org.opengauss.viewmenu.id.stack +viewmenu.label.stack = Callstack +viewmenu.mnemonics.stack = S +viewmenu.tooltip.stack = Callstack + +#Variable window +viewmenu.id.variable = org.opengauss.viewmenu.id.variable +viewmenu.label.variable = Variables +viewmenu.mnemonics.variable = V +viewmenu.tooltip.variable = Variables + +#Monitor window +viewmenu.id.monitor = org.opengauss.viewmenu.id.monitor +viewmenu.label.monitor = Monitor +viewmenu.mnemonics.monitor = M +viewmenu.tooltip.monitor = Monitor + +#Run Menu +menu.id.runmenu = org.opengauss.mppdbide.menu.id.run +menu.label.runmenu = &Run +menu.mnemonics.runmenu = R + +#Run Debug +menu.id.debugmenu = org.opengauss.mppdbide.menu.id.debugmenu +menu.label.debugmenu = De&bug +menu.mnemonics.debugmenu = B + +executemenu.id.debug = org.opengauss.executemenu.id.debug +executemenu.label.debug = Start Debugging(&S) +executemenu.mnemonics.debug = S +executemenu.tooltip.debug = Start Debugging + +executemenu.id.terminate = org.opengauss.executemenu.id.terminate +executemenu.label.terminate = Stop Debugging(&T) +executemenu.mnemonics.terminate = T +executemenu.tooltip.terminate = Stop Debugging + +executemenu.id.continue = org.opengauss.executemenu.id.continue +executemenu.label.continue = Continue(&C) +executemenu.mnemonics.continue = C +executemenu.tooltip.continue = Continue + +executemenu.id.stepin = org.opengauss.executemenu.id.stepin +executemenu.label.stepin = Step In(&I) +executemenu.mnemonics.stepin = I +executemenu.tooltip.stepin = Step In + +executemenu.id.stepover = org.opengauss.executemenu.id.stepover +executemenu.label.stepover = Step Over(&O) +executemenu.mnemonics.stepover = O +executemenu.tooltip.stepover = Step Over + +executemenu.id.stepout = org.opengauss.executemenu.id.stepout +executemenu.label.stepout = Step Out(&R) +executemenu.mnemonics.stepout = R +executemenu.tooltip.stepout = Step Out + +#Execute +executemenu.id.execute = org.opengauss.executemenu.id.execute +executemenu.label.execute = &Execute DB Object +executemenu.mnemonics.execute = E +executemenu.tooltip.execute = Execute DB Object + +#Execute SQL Terminal +executemenu.id.executeterminal = org.opengauss.executemenu.id.executeterminal +executemenu.label.executeterminal = Compile/E&xecute Statement +executemenu.mnemonics.executeterminal = X +executemenu.tooltip.executeterminal = Execute Statement + +#Execute SQL Terminal New Tab +executemenu.id.executesqlnewterminal = org.opengauss.executemenu.id.executesqlnewterminal +executemenu.label.executesqlnewterminal = Compile/Execute Statement in New Tab +executemenu.tooltip.executesqlnewterminal = Execute Statement in New Tab + +#For execute sql terminal alone +executemenu.label.executeterminal.alone = E&xecute Statement + +#Compile Function +executemenu.id.compilefunction = org.opengauss.mppdbide.trimbar.id.compilefunction.toolbar.handler +executemenu.label.compilefunction = Co&mpile +executemenu.mnemonics.compilefunction = M +executemenu.tooltip.compilefunction = Compile + +#Cancel Executing SQL Query +executemenu.id.cancelquery = org.opengauss.executemenu.id.cancelquery +executemenu.label.cancelquery = Cancel +executemenu.mnemonics.cancelquery = X +executemenu.tooltip.cancelquery = Cancel +#Disconnect +filemenu.id.disconnect = org.opengauss.filemenu.id.disconnect +filemenu.label.disconnect = &Disconnect from DB +filemenu.mnemonics.disconnect = D +filemenu.tooltip.disconnect = Disconnect from DB + +#Disconnect All +filemenu.id.disconnectall = org.opengauss.filemenu.id.disconnect +filemenu.label.disconnectall = Disconnect A&ll +filemenu.mnemonics.disconnectall = L +filemenu.tooltip.disconnectall = Disconnect All + +#Open New Instance +filemenu.id.opennewinstance = org.opengauss.filemenu.id.opennewinstance +filemenu.label.opennewinstance = Open In New &Window +filemenu.mnemonics.opennewinstance = W +filemenu.tooltip.opennewinstance = Open In New Window + +#Exit +filemenu.id.exit = org.opengauss.filemenu.id.exit +filemenu.label.exit = E&xit +filemenu.mnemonics.exit = X +filemenu.tooltip.exit = Exit Application + + +#Help Menu +menu.id.helpmenu = org.opengauss.mppdbide.menu.id.help +menu.label.helpmenu = &Help +menu.mnemonics.helpmenu = H + +#Cut Menu +editmenu.id.cut = org.opengauss.editmenu.id.cut +editmenu.label.cut = Cu&t +editmenu.mnemonics.cut = T +editmenu.tooltip.cut = Cut + +#Execution Plan Cost +executemenu.id.executionplan = org.opengauss.executemenu.id.executionplan +executemenu.label.executionplan = E&xecution Plan +executemenu.mnemonics.executionplan = E +executemenu.tooltip.executionplan = Execution Plan and Cost + +#Visual Explain Plan +executemenu.id.visualexplainplan = org.opengauss.executemenu.id.visualexplainplan +executemenu.label.visualexplainplan = Visual Explain &Plan +executemenu.mnemonics.visualexplainplan = P +executemenu.tooltip.visualexplainplan = Visual Explain Plan + +#Change to Upper Case +editmenu.label.touppercase = UPP&ERCASE +editmenu.tooltip.touppercase = UPPERCASE + +#Change to Lower Case +editmenu.label.tolowercase = &lowercase +editmenu.tooltip.tolowercase = lowercase + +#Change to indent +editmenu.label.indent=Indent +editmenu.tooltip.indent=Indent + +#Change to unindent +editmenu.label.unindent=Unindent +editmenu.tooltip.unindent=Unindent + + + + +#Go To Line +editmenu.label.gotoline = &Go To Line +editmenu.tooltip.gotoline = Go To Line + +#Copy Menu +editmenu.id.copy = org.opengauss.editmenu.id.copy +editmenu.label.copy = &Copy +editmenu.mnemonics.copy = C +editmenu.tooltip.copy = Copy + +#PasteMenu +editmenu.id.paste = org.opengauss.editmenu.id.paste +editmenu.label.paste = &Paste +editmenu.mnemonics.paste = P +editmenu.tooltip.paste = Paste + +#format Menu +editmenu.id.format = org.opengauss.editmenu.id.format +editmenu.label.format = &Format +editmenu.mnemonics.format = F +editmenu.tooltip.format = Format + +#format Menu +editmenu.id.newinstance = org.opengauss.editmenu.id.newinstance +editmenu.label.newinstance = Open In New &Window +editmenu.mnemonics.newinstance = W +editmenu.tooltip.newinstance = Open In New Window + +#Save Menu +editmenu.id.savesql = org.opengauss.editmenu.id.savesql +editmenu.label.savesql = &Save +editmenu.mnemonics.savesql = S +editmenu.tooltip.savesql = Save + +#Open Terminal +editmenu.id.opennewterminal = org.opengauss.editmenu.id.opennewterminal +editmenu.label.opennewterminal = &Open Terminal +editmenu.mnemonics.opennewterminal = O +editmenu.tooltip.opennewterminal = Open Terminal + +#Open Menu +editmenu.id.opensql = org.opengauss.editmenu.id.opensql +editmenu.label.opensql = &Open +editmenu.mnemonics.opensql = O +editmenu.tooltip.opensql = Open + +#Selectall menu +editmenu.id.selectall = org.opengauss.editmenu.id.selectall +editmenu.label.selectall = Select &All +editmenu.mnemonics.selectall = A +editmenu.tooltip.selectall = Select All + +#Find menu +editmenu.id.find = org.opengauss.editmenu.id.findreplace +editmenu.label.find = F&ind and Replace +editmenu.mnemonics.find = i +editmenu.tooltip.find = find and replace + +#Search menu +editmenu.id.search = org.opengauss.mppdbide.view.handledmenuitem.search +editmenu.label.search = &Search Objects +editmenu.mnemonics.search = s +editmenu.tooltip.search = Search Objects + +#Undo menu +editmenu.id.undo = org.opengauss.editmenu.id.undo +editmenu.label.undo = &Undo +editmenu.mnemonics.undo = u +editmenu.tooltip.undo = Undo + +#Redo menu +editmenu.id.redo = org.opengauss.editmenu.id.redo +editmenu.label.redo = &Redo +editmenu.mnemonics.redo = r +editmenu.tooltip.redo = redo + +#Execute DB Object menu +executemenu.id.executedbobjectineditor = org.opengauss.executemenu.id.execute +executemenu.label.executedbobjectineditor = Execute &DB Object in Editor +executemenu.mnemonics.executedbobjectineditor = E +executemenu.tooltip.executedbobjectineditor = Execute DB Object + +#User Guide menu +helpmenu.id.userguide = org.opengauss.mppdbide.menu.id.help.userguid +helpmenu.label.userguide = &User Manual +helpmenu.mnemonics.userguide = U +helpmenu.tooltip.userguide = User Manual + +#About menu +helpmenu.id.about = org.opengauss.mppdbide.menu.id.help.about +helpmenu.label.about = &About Data Studio +helpmenu.mnemonics.about = A +helpmenu.tooltip.about = About Data Studio + +#Parts +partsashcontainer.id.main = org.opengauss.mppdbide.partsashcontainer.id.main + +#Object browser partstack +partstack.id.objectbrowser = org.opengauss.mppdbide.partstack.id.objectbrowser + +#Object browser part +part.id.objectbrowser=org.opengauss.mppdbide.part.id.objectbrowser +part.label.objectbrowser=Object browser + +#Object browser pop up menu +part.menu.id.objectbrowser = org.opengauss.mppdbide.part.menu.id.objectbrowser +part.menu.label.objectbrowser = Object browser popup menu + +#Refresh popup menu for objectbrowser +objectbrowser.popupmenu.id.refresh = org.opengauss.objectbrowser.popupmenu.id.refresh +objectbrowser.popupmenu.label.refresh = Refresh +objectbrowser.popupmenu.mnemonics.refresh = R +objectbrowser.popupmenu.tooltip.refresh = Refresh database Object + +#View Data pop up menu +objectbrowser.popupmenu.id.viewdata = org.opengauss.objectbrowser.popupmenu.id.viewdata +objectbrowser.popupmenu.label.viewdata = View Data +objectbrowser.popupmenu.mnemonics.viewdata = V +objectbrowser.popupmenu.tooltip.viewdata = View data for the view object + +#Execute popup menu for objectbrowser +objectbrowser.popupmenu.id.execute = org.opengauss.objectbrowser.popupmenu.id.execute +objectbrowser.popupmenu.label.execute = Execute +objectbrowser.popupmenu.mnemonics.execute = X +objectbrowser.popupmenu.tooltip.execute = Execute DB Object + +#View Source popup menu for objectbrowser +objectbrowser.popupmenu.id.viewsource = org.opengauss.objectbrowser.popupmenu.id.viewsource +objectbrowser.popupmenu.label.viewsource = View Source +objectbrowser.popupmenu.mnemonics.viewsource = w +objectbrowser.popupmenu.tooltip.viewsource = View Source + +#Disconnect popup menu for objectbrowser +objectbrowser.popupmenu.id.connect = org.opengauss.objectbrowser.popupmenu.id.connect +objectbrowser.popupmenu.label.connect = Connect to DB +objectbrowser.popupmenu.mnemonics.connect = C +objectbrowser.popupmenu.tooltip.connect = Connect to DB + +#Disconnect popup menu for objectbrowser +objectbrowser.popupmenu.id.disconnect = org.opengauss.objectbrowser.popupmenu.id.disconnect +objectbrowser.popupmenu.label.disconnect = Disconnect from DB +objectbrowser.popupmenu.mnemonics.disconnect = D +objectbrowser.popupmenu.tooltip.disconnect = Disconnect from DB + +objectbrowser.popupmenu.id.properties = org.opengauss.objectbrowser.popupmenu.id.properties +objectbrowser.popupmenu.label.properties = Properties +objectbrowser.popupmenu.mnemonics.properties = P +objectbrowser.popupmenu.tooltip.properties = Server Properties + +objectbrowser.popupmenu.id.datatypedetails = org.opengauss.objectbrowser.popupmenu.id.datatypedetails +objectbrowser.popupmenu.label.datatypedetails = Data Type Details +objectbrowser.popupmenu.mnemonics.datatypedetails = D +objectbrowser.popupmenu.tooltip.datatypedetails = Data Details + +#Clear console window +consolepopupmenu.id.clear = org.opengauss.mppdbide.view.consolemenu.clear +consolepopupmenu.label.clear = Clear +consolepopupmenu.mnemonics.clear = L +consolepopupmenu.tooltip.clear = Clear + +#Expression for disconnect popup menu in objectbrowse +objectbrowser.popupmenu.disconnect.id.expression = org.opengauss.objectbrowser.popupmenu.disconnect.id.expression + +#Partsash container sub(editor, console, stack, breakpoint & variable) +partsashcontainer.id.sub = org.opengauss.mppdbide.partsashcontainer.id.sub + +#Partsash container sub(editor, console, stack, breakpoint & variable) +partsashcontainer.id.sub.editor.console = org.opengauss.mppdbide.partsashcontainer.id.sub.editor.console + +#Editor partstack +partstack.id.editor = org.opengauss.mppdbide.partstack.id.editor + +#Editor part +part.id.editor = org.opengauss.mppdbide.part.id.editor +part.label.editor = PLSQL Viewer + +part.id.sqlterminal = org.opengauss.mppdbide.part.id.sqlterminal +part.label.sqlterminal = SQL Terminal + +#Console partstack +partstack.id.console = org.opengauss.mppdbide.partstack.id.console + +#AdvancedSearch partstack +partstack.id.advancedsearch = org.opengauss.mppdbide.part.id.advsearch + +#console part +part.id.console = org.opengauss.mppdbide.part.id.console +part.label.console = Console + +part.id.result = org.opengauss.mppdbide.part.id.console +part.label.result = Results + +#Trimbar +trimbar.id.maintrimbar = org.opengauss.mppdbide.trimbar.id.maintrimbar + +#Toolbar +trimbar.id.maintrimbar.toolbar = org.opengauss.mppdbide.trimbar.id.maintrimbar.toolbar + +#handlers +trimbar.id.newconnection.toolbar.handler = org.opengauss.mppdbide.trimbar.id.newconnection.toolbar.handler + +#Create PLSQL function popup menu for objectbrowser +objectbrowser.popupmenu.id.createfunction= org.opengauss.objectbrowser.popupmenu.id.createfunction +objectbrowser.popupmenu.label.createfunction = Create Function +objectbrowser.popupmenu.mnemonics.createfunction = c +objectbrowser.popupmenu.tooltip.createfunction = Create Function + +#Create SQL function popup menu for objectbrowser +objectbrowser.popupmenu.id.createsqlfunction= org.opengauss.mppdbide.view.handledmenuitem.createsqlfunction +objectbrowser.popupmenu.label.createsqlfunction = Create SQL Function +objectbrowser.popupmenu.mnemonics.createsqlfunction = c +objectbrowser.popupmenu.tooltip.createsqlfunction = Create SQL Function + +#Create PLSQL procedure popup menu for objectbrowser +objectbrowser.popupmenu.id.createprocedure= org.opengauss.objectbrowser.popupmenu.id.createprocedure +objectbrowser.popupmenu.label.createprocedure = Create Procedure +objectbrowser.popupmenu.mnemonics.createprocedure = c +objectbrowser.popupmenu.tooltip.createprocedure = Create Procedure + +#Create PLSQL package popup menu for objectbrowser +objectbrowser.popupmenu.id.createpackage= org.opengauss.objectbrowser.popupmenu.id.createpackage +objectbrowser.popupmenu.label.createpackage = Create Package +objectbrowser.popupmenu.mnemonics.createpackage = c +objectbrowser.popupmenu.tooltip.createpackage = Create Package + +#Create trigger popup menu for objectbrowser +objectbrowser.popupmenu.id.createtrigger= org.opengauss.objectbrowser.popupmenu.id.createtrigger +objectbrowser.popupmenu.label.createtrigger = Create Trigger Function +objectbrowser.popupmenu.mnemonics.createtrigger = t +objectbrowser.popupmenu.tooltip.createtrigger = Create Trigger Function + +#Drop debug object popup menu for objectbrowser +objectbrowser.popupmenu.id.dropdebugobject= org.opengauss.objectbrowser.popupmenu.id.dropdebugobject +objectbrowser.popupmenu.label.dropdebugobject = Drop Object +objectbrowser.popupmenu.mnemonics.dropdebugobject = t +objectbrowser.popupmenu.tooltip.dropdebugobject = Drop Object + +#Create db popup menu for object browser +objectbrowser.popupmenu.id.createdb = objectbrowser.popupmenu.id.createdb +objectbrowser.popupmenu.label.createdb = Create Database +objectbrowser.popupmenu.mnemonics.createdb = r +objectbrowser.popupmenu.tooltip.createdb = Create new database + +#Create db rename connection for object browser +objectbrowser.popupmenu.id.renameconnection = objectbrowser.popupmenu.id.renameconnection +objectbrowser.popupmenu.label.renameconnection = Rename Connection +objectbrowser.popupmenu.mnemonics.renameconnection = r +objectbrowser.popupmenu.tooltip.renameconnection = Rename Connection + +#Create db edit connection for object browser +objectbrowser.popupmenu.id.editconnection = objectbrowser.popupmenu.id.editconnection +objectbrowser.popupmenu.label.editconnection = Edit Connection +objectbrowser.popupmenu.mnemonics.editconnection = r +objectbrowser.popupmenu.tooltip.editconnection = Edit Connection + +#rename db popup menu for object browser +objectbrowser.popupmenu.id.renamedb = objectbrowser.popupmenu.id.renamedb +objectbrowser.popupmenu.label.renamedb = Rename Database +objectbrowser.popupmenu.mnemonics.renamedb = e +objectbrowser.popupmenu.tooltip.renamedb = Rename database + +#open new terminal popup menu for object browser +objectbrowser.popupmenu.id.opennewterminal = objectbrowser.popupmenu.id.opennewterminal +objectbrowser.popupmenu.label.opennewterminal = Open Terminal +objectbrowser.popupmenu.mnemonics.opennewterminal = O +objectbrowser.popupmenu.tooltip.opennewterminal = Open Terminal + +#Drop db popup menu for object browser +objectbrowser.popupmenu.id.dropdb = objectbrowser.popupmenu.id.dropdb +objectbrowser.popupmenu.label.dropdb = Drop Database +objectbrowser.popupmenu.mnemonics.dropdb = e +objectbrowser.popupmenu.tooltip.dropdb = Drop the database + +#Create schema db popup menu for object browser +objectbrowser.popupmenu.id.createschema = objectbrowser.popupmenu.id.createschema +objectbrowser.popupmenu.label.createschema = Create Schema +objectbrowser.popupmenu.mnemonics.createschema = s +objectbrowser.popupmenu.tooltip.createschema = Create Schema + +#Rename schema schema popup menu for object browser +objectbrowser.popupmenu.id.renameschema = objectbrowser.popupmenu.id.renameschema +objectbrowser.popupmenu.label.renameschema = Rename Schema +objectbrowser.popupmenu.mnemonics.renameschema = r +objectbrowser.popupmenu.tooltip.renameschema = Rename Schema + +#Drop schema schema popup menu for object browser +objectbrowser.popupmenu.id.dropschema = objectbrowser.popupmenu.id.dropschema +objectbrowser.popupmenu.label.dropschema = Drop Schema +objectbrowser.popupmenu.mnemonics.dropschema = d +objectbrowser.popupmenu.tooltip.dropschema = Drop Schema + +#Drop objects popup menu for object browser +objectbrowser.popupmenu.id.dropobjects = objectbrowser.popupmenu.id.dropobjects +objectbrowser.popupmenu.label.dropobjects = Drop Objects +objectbrowser.popupmenu.mnemonics.dropobjects = d +objectbrowser.popupmenu.tooltip.dropobjects = Drop Objects + +#Create table popup menu for object browser +#objectbrowser.popupmenu.id.createtable = objectbrowser.popupmenu.id.createtable +#objectbrowser.popupmenu.label.createtable = Create Table +#objectbrowser.popupmenu.mnemonics.createtable = b +#objectbrowser.popupmenu.tooltip.createtable = Create new table + + +#Rename table popup menu for object browser +#objectbrowser.popupmenu.id.renametable = objectbrowser.popupmenu.id.renametable +#objectbrowser.popupmenu.label.renametable = Rename Table +#objectbrowser.popupmenu.mnemonics.renametable = r +#objectbrowser.popupmenu.tooltip.renametable = Rename Existing Table + +#Create table pop-up menu for object browser +objectbrowser.popupmenu.id.createtable = org.opengauss.mppdbide.command.id.createtable +objectbrowser.popupmenu.label.createtable = Create Regular Table +objectbrowser.popupmenu.mnemonics.createtable = b +objectbrowser.popupmenu.tooltip.createtable = Create Regular table + +#Rename Table pop-up menu for object browser +objectbrowser.popupmenu.id.renametable = org.opengauss.mppdbide.command.id.renametable +objectbrowser.popupmenu.label.renametable = Rename Table +objectbrowser.popupmenu.mnemonics.renametable = r +objectbrowser.popupmenu.tooltip.renametable = Change the name of a table + +#Drop Table pop-up menu for object browser +objectbrowser.popupmenu.id.droptable = org.opengauss.mppdbide.command.id.droptable +objectbrowser.popupmenu.label.droptable = Drop Table + +objectbrowser.popupmenu.mnemonics.droptable = d +objectbrowser.popupmenu.tooltip.droptable = Drop the table + + +#Create Partition table pop-up menu for object browser +objectbrowser.popupmenu.id.createpartitiontable = org.opengauss.mppdbide.command.id.createpartitiontable +objectbrowser.popupmenu.label.createpartitiontable = Create Partition Table +objectbrowser.popupmenu.mnemonics.createpartitiontable = p +objectbrowser.popupmenu.tooltip.createpartitiontable = Create a new partition table + +#Create Partition pop-up menu for object browser +objectbrowser.popupmenu.id.addpartition = org.opengauss.objectbrowser.popupmenu.id.addpartition +objectbrowser.popupmenu.label.addpartition = Add Partition +objectbrowser.popupmenu.mnemonics.addpartition = p +objectbrowser.popupmenu.tooltip.addpartition = Add a new partition + +#Move Partition pop-up menu for object browser +objectbrowser.popupmenu.id.movepartition = org.opengauss.objectbrowser.popupmenu.id.movepartition +objectbrowser.popupmenu.label.movepartition = Move Partition +objectbrowser.popupmenu.mnemonics.movepartition = p +objectbrowser.popupmenu.tooltip.movepartition = Move partition + +#Exchange Partition pop-up menu for object browser +objectbrowser.popupmenu.id.exchangepartition = org.opengauss.objectbrowser.popupmenu.id.exchangepartition +objectbrowser.popupmenu.label.exchangepartition = Exchange Partition +objectbrowser.popupmenu.mnemonics.exchangepartition = p +objectbrowser.popupmenu.tooltip.exchangepartition = Exchange partition + +#Merge Partition pop-up menu for object browser +objectbrowser.popupmenu.id.mergepartition = org.opengauss.objectbrowser.popupmenu.id.mergepartition +objectbrowser.popupmenu.label.mergepartition = Merge Partition +objectbrowser.popupmenu.mnemonics.mergepartition = p +objectbrowser.popupmenu.tooltip.mergepartition = Merge partition + +#Split Partition pop-up menu for object browser +objectbrowser.popupmenu.id.splitpartition = org.opengauss.objectbrowser.popupmenu.id.splitpartition +objectbrowser.popupmenu.label.splitpartition = Split Partition +objectbrowser.popupmenu.mnemonics.splitpartition = p +objectbrowser.popupmenu.tooltip.splitpartition = Split partition + +#Modify Partition pop-up menu for object browser +objectbrowser.popupmenu.id.modifypartition = org.opengauss.objectbrowser.popupmenu.id.modifypartition +objectbrowser.popupmenu.label.modifypartition = Modify Partition +objectbrowser.popupmenu.mnemonics.modifypartition = p +objectbrowser.popupmenu.tooltip.modifypartition = Modify partition + +#Row Movement pop-up menu for object browser +objectbrowser.popupmenu.id.rowmovement = org.opengauss.objectbrowser.popupmenu.id.rowmovement +objectbrowser.popupmenu.label.rowmovement = Row Movement +objectbrowser.popupmenu.mnemonics.rowmovement = p +objectbrowser.popupmenu.tooltip.rowmovement = Row Movement + +#Drop Partition pop-up menu for object browser +objectbrowser.popupmenu.id.droppartition = org.opengauss.objectbrowser.popupmenu.id.droppartition +objectbrowser.popupmenu.label.droppartition = Drop Partition +objectbrowser.popupmenu.mnemonics.droppartition = p +objectbrowser.popupmenu.tooltip.droppartition = Drop Partition + +#View Partition Data pop-up menu for object browser +objectbrowser.popupmenu.id.viewpartition = org.opengauss.objectbrowser.popupmenu.id.viewpartition +objectbrowser.popupmenu.label.viewpartition = View Partition Data +objectbrowser.popupmenu.mnemonics.viewpartition = p +objectbrowser.popupmenu.tooltip.viewpartition = View Partition Data + +#Rename Partition pop-up menu for object browser +objectbrowser.popupmenu.id.renamepartition = org.opengauss.objectbrowser.popupmenu.id.renamepartition +objectbrowser.popupmenu.label.renamepartition = Rename Partition +objectbrowser.popupmenu.mnemonics.renamepartition = p +objectbrowser.popupmenu.tooltip.renamepartition = Rename Partition + + +#vacuum delta range pop-up menu for object browser +objectbrowser.popupmenu.id.vacuumdeltarange =org.opengauss.objectbrowser.popupmenu.id.vacuumdeltarange +objectbrowser.popupmenu.label.vacuumdeltarange = Vacuum Delta Range +objectbrowser.popupmenu.mnemonics.vacuumdeltarange = p +objectbrowser.popupmenu.tooltip.vacuumdeltarange = Vacuum Delta Range + +#vacuum HDFS directory pop-up menu for object browser +objectbrowser.popupmenu.id.vacuumhdfsdirectory =org.opengauss.objectbrowser.popupmenu.id.vacuumhdfsdirectory +objectbrowser.popupmenu.label.vacuumhdfsdirectory =Vacuum HDFS Directory +objectbrowser.popupmenu.mnemonics.vacuumhdfsdirectory = p +objectbrowser.popupmenu.tooltip.vacuumhdfsdirectory = Vacuum HDFS Directory + + +#Create Sequence pop-up menu for object browser +objectbrowser.popupmenu.id.createsequence = org.opengauss.mppdbide.command.id.createsequence +objectbrowser.popupmenu.label.createsequence = Create Sequence +objectbrowser.popupmenu.mnemonics.createsequence = q +objectbrowser.popupmenu.tooltip.createsequence = Create a new Sequence + +#Truncate Table pop-up menu for object browser +objectbrowser.popupmenu.id.truncatetable = org.opengauss.mppdbide.command.id.truncatetable +objectbrowser.popupmenu.label.truncatetable = Truncate Table +objectbrowser.popupmenu.mnemonics.truncatetable = t +objectbrowser.popupmenu.tooltip.truncatetable = Truncate the table + +#Reindex Table pop-up menu for object browser +objectbrowser.popupmenu.id.reindextable = org.opengauss.mppdbide.command.id.reindextable +objectbrowser.popupmenu.label.reindextable = Reindex Table +objectbrowser.popupmenu.mnemonics.reindextable = i +objectbrowser.popupmenu.tooltip.reindextable = Reindex all the indices of table including toast index + +#Analyze Table popup menu for object browser +objectbrowser.popupmenu.id.analyzetable = org.opengauss.mppdbide.command.id.analyzetable +objectbrowser.popupmenu.label.analyzetable = Analyze Table +objectbrowser.popupmenu.mnemonics.analyzetable = a +objectbrowser.popupmenu.tooltip.analyzetable = Analyze the table + +#Vacuum Table pop-up menu for object browser +objectbrowser.popupmenu.id.vacuumtable = org.opengauss.mppdbide.command.id.vacuumtable +objectbrowser.popupmenu.label.vacuumtable = Vacuum Table +objectbrowser.popupmenu.mnemonics.vacuumtable = v +objectbrowser.popupmenu.tooltip.vacuumtable = Vacuum the table + +#Set table description pop-up menu for object browser +objectbrowser.popupmenu.id.settabledescription = org.opengauss.mppdbide.command.id.settabledescription +objectbrowser.popupmenu.label.settabledescription = Set Table Description +objectbrowser.popupmenu.mnemonics.settabledescription = D +objectbrowser.popupmenu.tooltip.settabledescription = Brief description about table + +#Set Tablespace pop-up menu for object browser +objectbrowser.popupmenu.id.settablespace = org.opengauss.mppdbide.command.id.settablespace +objectbrowser.popupmenu.label.settablespace = Set Tablespace +objectbrowser.popupmenu.mnemonics.settablespace = s +objectbrowser.popupmenu.tooltip.settablespace = Changes the tablespace to the specified tablespace + +#Set Schema pop-up menu for object browser +objectbrowser.popupmenu.id.setschema = org.opengauss.mppdbide.command.id.setschema +objectbrowser.popupmenu.label.setschema = Set Schema +objectbrowser.popupmenu.mnemonics.setschema = S +objectbrowser.popupmenu.tooltip.setschema = Moves the table into another schema + +#Edit table properties pop-up menu for object browser +objectbrowser.popupmenu.id.editpropeties = org.opengauss.mppdbide.command.id.editpropeties +objectbrowser.popupmenu.label.editpropeties = Edit Table Properties +objectbrowser.popupmenu.mnemonics.editpropeties = p +objectbrowser.popupmenu.tooltip.editpropeties = Edit the table properties + +#Edit Data Distribution pop-up menu for object browser +objectbrowser.popupmenu.id.changedatadistribution = org.opengauss.mppdbide.command.id.changedatadistribution +objectbrowser.popupmenu.label.changedatadistribution = Edit Data Distribution +objectbrowser.popupmenu.mnemonics.changedatadistribution = b +objectbrowser.popupmenu.tooltip.changedatadistribution = Change how the table to be distributed or replicated among datanodes + +#Create Column pop-up menu for object browser +objectbrowser.popupmenu.id.createcolumn = org.opengauss.mppdbide.command.id.createcolumn +objectbrowser.popupmenu.label.createcolumn = Create column +objectbrowser.popupmenu.mnemonics.createcolumn = c +objectbrowser.popupmenu.tooltip.createcolumn = Create the column + +#Drop Column pop-up menu for object browser +objectbrowser.popupmenu.id.dropcolumn = org.opengauss.mppdbide.command.id.dropcolumn +objectbrowser.popupmenu.label.dropcolumn = Drop Column +objectbrowser.popupmenu.mnemonics.dropcolumn = d +objectbrowser.popupmenu.tooltip.dropcolumn = Drop the column + +#Edit column properties pop-up menu for object browser +objectbrowser.popupmenu.id.editcolumnproperties = org.opengauss.mppdbide.command.id.editcolumnproperties +objectbrowser.popupmenu.label.editcolumnproperties = Edit column properties +objectbrowser.popupmenu.mnemonics.editcolumnproperties = p +objectbrowser.popupmenu.tooltip.editcolumnproperties = Change default expression, data type, set/remove not null property + +#Edit column properties pop-up menu for object browser +objectbrowser.popupmenu.id.renamecolumn = org.opengauss.mppdbide.command.id.renamecolumn +objectbrowser.popupmenu.label.renamecolumn = Rename Column +objectbrowser.popupmenu.mnemonics.renamecolumn = r +objectbrowser.popupmenu.tooltip.renamecolumn = Change the name of a column + +#Create Constraint pop-up menu for object browser +objectbrowser.popupmenu.id.createconstraint = org.opengauss.mppdbide.command.id.createconstraint +objectbrowser.popupmenu.label.createconstraint = Create constraint +objectbrowser.popupmenu.mnemonics.createconstraint = c +objectbrowser.popupmenu.tooltip.createconstraint = Create new constraint + +#Rename Constraint pop-up menu for object browser +objectbrowser.popupmenu.id.renameconstraint = org.opengauss.mppdbide.command.id.renameconstraint +objectbrowser.popupmenu.label.renameconstraint = Rename Constraint +objectbrowser.popupmenu.mnemonics.renameconstraint = r +objectbrowser.popupmenu.tooltip.renameconstraint = Change the name of a constraint + +#Validate Constraint pop-up menu for object browser +objectbrowser.popupmenu.id.validateconstraint = org.opengauss.mppdbide.command.id.validateconstraint +objectbrowser.popupmenu.label.validateconstraint = Validate Constraint +objectbrowser.popupmenu.mnemonics.validateconstraint = v +objectbrowser.popupmenu.tooltip.validateconstraint = Validates the constraint + +#Drop Constraint pop-up menu for object browser +objectbrowser.popupmenu.id.dropconstraint = org.opengauss.mppdbide.command.id.dropconstraint +objectbrowser.popupmenu.label.dropconstraint = Drop Constraint +objectbrowser.popupmenu.mnemonics.dropconstraint = d +objectbrowser.popupmenu.tooltip.dropconstraint = Drop the constraint + +#Edit Constraint Properties pop-up menu for object browser +objectbrowser.popupmenu.id.editconstraint = org.opengauss.mppdbide.command.id.editconstraint +objectbrowser.popupmenu.label.editconstraint = Edit Constraint +objectbrowser.popupmenu.mnemonics.editconstraints = p +objectbrowser.popupmenu.tooltip.editconstraint = Edit Constraint + +#Edit Constraint Properties pop-up menu for object browser +objectbrowser.popupmenu.id.createindex = org.opengauss.mppdbide.command.id.createindex +objectbrowser.popupmenu.label.createindex = Create index +objectbrowser.popupmenu.mnemonics.createindex = i +objectbrowser.popupmenu.tooltip.createindex = Create Index + +#Export table data pop-up menu for object browser +objectbrowser.popupmenu.id.exporttabledata = org.opengauss.mppdbide.command.id.exporttabledata +objectbrowser.popupmenu.label.exporttabledata = Export Table Data +objectbrowser.popupmenu.mnemonics.exporttabledata = X +objectbrowser.popupmenu.tooltip.exporttabledata = Export Table Data + +#Import table data pop-up menu for object browser +objectbrowser.popupmenu.id.importtabledata = org.opengauss.mppdbide.command.id.importtabledata +objectbrowser.popupmenu.label.importtabledata = Import Table Data +objectbrowser.popupmenu.mnemonics.importtabledata = I +objectbrowser.popupmenu.tooltip.importtabledata = Import Table Data + +#View table data pop-up menu for object browser +objectbrowser.popupmenu.id.viewtabledata = org.opengauss.mppdbide.command.id.viewtabledata +objectbrowser.popupmenu.label.viewtabledata = View Table Data +objectbrowser.popupmenu.mnemonics.viewtabledata = W +objectbrowser.popupmenu.tooltip.viewtabledata = View Table Data + +#Show Related Sequence pop-up menu for object browser +objectbrowser.popupmenu.id.showRelatedSequence = org.opengauss.mppdbide.command.id.showRelatedSequence +objectbrowser.popupmenu.label.showRelatedSequence = Show Related Sequence +objectbrowser.popupmenu.mnemonics.showRelatedSequence = S +objectbrowser.popupmenu.tooltip.showRelatedSequence = Show Related Sequence + +#Drop index pop-up menu for object browser +objectbrowser.popupmenu.id.dropindex = org.opengauss.mppdbide.command.id.dropindex +objectbrowser.popupmenu.label.dropindex = Drop Index +objectbrowser.popupmenu.mnemonics.dropindex = I +objectbrowser.popupmenu.tooltip.dropindex = Drop Index + +#Rename index pop-up menu for object browser +objectbrowser.popupmenu.id.renameindex = org.opengauss.mppdbide.command.id.renameindex +objectbrowser.popupmenu.label.renameindex = Rename Index +objectbrowser.popupmenu.mnemonics.renameindex = r +objectbrowser.popupmenu.tooltip.renameindex = Rename Index + +#Change index tablespace pop-up menu for object browser +objectbrowser.popupmenu.id.changeindextablespace = org.opengauss.mppdbide.command.id.changeindextablespace +objectbrowser.popupmenu.label.changeindextablespace = Change Tablespace +objectbrowser.popupmenu.mnemonics.changeindextablespace = t +objectbrowser.popupmenu.tooltip.changeindextablespace = Change tablespace of the index + +#Change index fill factor pop-up menu for object browser +objectbrowser.popupmenu.id.changeindexfillfactor = org.opengauss.mppdbide.command.id.changeindexfillfactor +objectbrowser.popupmenu.label.changeindexfillfactor = Change Fill Factor +objectbrowser.popupmenu.mnemonics.changeindexfillfactor = t +objectbrowser.popupmenu.tooltip.changeindexfillfactor = Change fill factor of the index + +#Disconnect all dbs pop-up menu for object browser +objectbrowser.popupmenu.id.disconnectalldbs = org.opengauss.mppdbide.command.id.disconnectalldbs +objectbrowser.popupmenu.label.disconnectalldbs = Disconnect All +objectbrowser.popupmenu.mnemonics.disconnectalldbs = a +objectbrowser.popupmenu.tooltip.disconnectalldbs = Disconnect all dbs of the server + +#Remove server from list pop-up menu for object browser +objectbrowser.popupmenu.id.removeserver = org.opengauss.mppdbide.command.id.removeserver +objectbrowser.popupmenu.label.removeserver = Remove Connection +objectbrowser.popupmenu.mnemonics.removeserver = r +objectbrowser.popupmenu.tooltip.removeserver = Remove connection from view + +#Column not null property pop-up menu for object browser +objectbrowser.popupmenu.id.columnnotnull = org.opengauss.mppdbide.command.id.columnnotnull +objectbrowser.popupmenu.label.columnnotnull = Toggle Not Null +objectbrowser.popupmenu.mnemonics.columnnotnull = u +objectbrowser.popupmenu.tooltip.columnnotnull = Set Column Not Null Property + +#Column default value property pop-up menu for object browser +objectbrowser.popupmenu.id.columndefaultvalue = org.opengauss.mppdbide.command.id.columndefaultvalue +objectbrowser.popupmenu.label.columndefaultvalue = Set Column Default Value +objectbrowser.popupmenu.mnemonics.columndefaultvalue = V +objectbrowser.popupmenu.tooltip.columndefaultvalue = Set Column Default Value + +#Column change data type property pop-up menu for object browser +objectbrowser.popupmenu.id.changedatatype = org.opengauss.mppdbide.command.id.changedatatype +objectbrowser.popupmenu.label.changedatatype = Change Data Type +objectbrowser.popupmenu.mnemonics.changedatatype = T +objectbrowser.popupmenu.tooltip.changedatatype = Change Data Type + +#Properties pop-up menu for object browser +objectbrowser.popupmenu.id.properties = org.opengauss.mppdbide.command.id.properties +objectbrowser.popupmenu.label.properties = Properties +objectbrowser.popupmenu.mnemonics.properties = p +objectbrowser.popupmenu.tooltip.properties = Properties + +#Create Tablespace pop-up menu for object browser +objectbrowser.popupmenu.id.createtablespace = org.opengauss.mppdbide.command.id.createtablespace +objectbrowser.popupmenu.label.createtablespace = Create Tablespace +objectbrowser.popupmenu.mnemonics.createtablespace = C +objectbrowser.popupmenu.tooltip.createtablespace = Create Tablespace + +#Rename Tablespace pop-up menu for object browser +objectbrowser.popupmenu.id.renametablespace = org.opengauss.mppdbide.command.id.renametablespace +objectbrowser.popupmenu.label.renametablespace = Rename Tablespace +objectbrowser.popupmenu.mnemonics.renametablespace = R +objectbrowser.popupmenu.tooltip.renametablespace = Rename Tablespace + +#Set Tablespace Option pop-up menu for object browser +objectbrowser.popupmenu.id.settablespaceoption = org.opengauss.mppdbide.command.id.settablespaceoption +objectbrowser.popupmenu.label.settablespaceoption = Set Tablespace Option +objectbrowser.popupmenu.mnemonics.settablespaceoption = S +objectbrowser.popupmenu.tooltip.settablespaceoption = Set Tablespace Option + +#Set Tablespace Size pop-up menu for object browser +objectbrowser.popupmenu.id.settablespacesize = org.opengauss.mppdbide.command.id.settablespacesize +objectbrowser.popupmenu.label.settablespacesize = Set Tablespace MaxSize +objectbrowser.popupmenu.mnemonics.settablespacesize = S +objectbrowser.popupmenu.tooltip.settablespacesize = Set Tablespace MaxSize + +#Drop Tablespace pop-up menu for object browser +objectbrowser.popupmenu.id.droptablespace = org.opengauss.mppdbide.command.id.droptablespace +objectbrowser.popupmenu.label.droptablespace = Drop Tablespace +objectbrowser.popupmenu.mnemonics.droptablespace = D +objectbrowser.popupmenu.tooltip.droptablespace = Drop Tablespace + +#Show DDL Tablespace pop-up menu for object browser +objectbrowser.popupmenu.id.showddl = org.opengauss.mppdbide.command.id.showddl +objectbrowser.popupmenu.label.showddl = Show DDL +objectbrowser.popupmenu.mnemonics.showddl = S +objectbrowser.popupmenu.tooltip.showddl = Show DDL + +#Show DDL for table pop-up menu for object browser +objectbrowser.popupmenu.id.showddlfortable = org.opengauss.mppdbide.command.id.showddlfortable +objectbrowser.popupmenu.label.showddlfortable = Show DDL +objectbrowser.popupmenu.mnemonics.showddlfortable = S +objectbrowser.popupmenu.tooltip.showddlfortable = Show DDL + +#Edit table data pop_up menu for table +objectbrowser.popupmenu.id.edittablewizard = org.opengauss.mppdbide.command.id.edittablewizard +objectbrowser.popupmenu.label.edittablewizard = Edit Table Data +objectbrowser.popupmenu.mnemonics.edittablewizard = E +objectbrowser.popupmenu.tooltip.edittablewizard = Edit Table Data + +#Edit table data viewer toolbar menu for table +dataviewer.toolbar.id.edittablewizard = org.opengauss.mppdbide.view.handledtoolitem.add +dataviewer.toolbar.add.label.edittablewizard = Insert +dataviewer.toolbar.add.mnemonics.edittablewizard = I +dataviewer.toolbar.add.tooltip.edittablewizard = Insert + +dataviewer.toolbar.id.edittablewizard = org.opengauss.mppdbide.view.handledtoolitem.Delete +dataviewer.toolbar.delete.label.edittablewizard = Delete +dataviewer.toolbar.delete.mnemonics.edittablewizard = E +dataviewer.toolbar.delete.tooltip.edittablewizard = Delete + +dataviewer.toolbar.id.edittablewizard = org.opengauss.mppdbide.view.handledtoolitem.paste +dataviewer.toolbar.paste.label.edittablewizard = Paste +dataviewer.toolbar.paste.mnemonics.edittablewizard = E +dataviewer.toolbar.paste.tooltip.edittablewizard = Paste + +dataviewer.toolbar.id.edittablewizard = org.opengauss.mppdbide.view.handledtoolitem.post +dataviewer.toolbar.post.label.edittablewizard = Post +dataviewer.toolbar.post.mnemonics.edittablewizard = E +dataviewer.toolbar.post.tooltip.edittablewizard = Post + +dataviewer.toolbar.id.edittablewizard =org.opengauss.mppdbide.view.handledtoolitem.rollback +dataviewer.toolbar.rollback.label.edittablewizard=Rollback +dataviewer.toolbar.rollback.tooltip.edittablewizard=Rollback + +dataviewer.toolbar.id.edittablewizard =org.opengauss.mppdbide.view.handledtoolitem.Commitchanges +dataviewer.toolbar.commit.label.edittablewizard=Commit +dataviewer.toolbar.commit.tooltip.edittablewizard=Commit +#Progress Bar Window +progressview.id.showrprogress = org.opengauss.mppdbide.part.id.showrprogress +progressview.label.showrprogress = Show Progress Bar +progressview.mnemonics.showrprogress = P +progressview.tooltip.showrprogress = Show Progress Bar + +objectbrowser.popupmenu.id.createview = org.opengauss.mppdbide.command.id.createviewobject +objectbrowser.popupmenu.label.createview = Create View +objectbrowser.popupmenu.mnemonics.createview = C +objectbrowser.popupmenu.tooltip.createview = Create new view object + +objectbrowser.popupmenu.id.dropview = org.opengauss.mppdbide.command.id.dropviewobject +objectbrowser.popupmenu.label.dropview = Drop View +objectbrowser.popupmenu.mnemonics.dropview = D +objectbrowser.popupmenu.tooltip.dropview = Drop the view object + +objectbrowser.popupmenu.id.renameview = org.opengauss.mppdbide.command.id.renameviewobject +objectbrowser.popupmenu.label.renameview = Rename View +objectbrowser.popupmenu.mnemonics.renameview = R +objectbrowser.popupmenu.tooltip.renameview = Rename the view object + +objectbrowser.popupmenu.id.setviewschema = org.opengauss.mppdbide.command.id.setviewschema +objectbrowser.popupmenu.label.setviewschema = Set Schema +objectbrowser.popupmenu.mnemonics.setviewschema = S +objectbrowser.popupmenu.tooltip.setviewschema = Set schema for the view object + +objectbrowser.popupmenu.id.showviewddl = org.opengauss.mppdbide.command.id.setviewddl +objectbrowser.popupmenu.label.showviewddl = Show DDL +objectbrowser.popupmenu.mnemonics.showviewddl = w +objectbrowser.popupmenu.tooltip.showviewddl = Show the DDL for the view + +objectbrowser.popupmenu.id.viewcolumn.defaultvalue = org.opengauss.mppdbide.command.id.viewcolumn.defaultvalue +objectbrowser.popupmenu.label.viewcolumn.defaultvalue = Set View Column Default Value +objectbrowser.popupmenu.mnemonics.viewcolumn.defaultvalue = D +objectbrowser.popupmenu.tooltip.viewcolumn.defaultvalue = Set View Column Default Value + +objectbrowser.popupmenu.id.exportddl = org.opengauss.mppdbide.command.id.exportddl +objectbrowser.popupmenu.label.exportddl = Export DDL +objectbrowser.popupmenu.mnemonics.exportddl = L +objectbrowser.popupmenu.tooltip.exportddl = Export DDL + +objectbrowser.popupmenu.id.exportddldata = org.opengauss.mppdbide.command.id.exportddldata +objectbrowser.popupmenu.label.exportddldata = Export DDL and Data +objectbrowser.popupmenu.mnemonics.exportddldata = T +objectbrowser.popupmenu.tooltip.exportddldata = Export DDL and Data + +objectbrowser.popupmenu.id.batchexportddl = org.opengauss.mppdbide.view.id.batchexportddl +objectbrowser.popupmenu.label.batchexportddl = Export DDL +objectbrowser.popupmenu.mnemonics.batchexportddl = L +objectbrowser.popupmenu.tooltip.batchexportddl = Export DDL + +objectbrowser.popupmenu.id.batchexportddldata = org.opengauss.mppdbide.view.id.batchexportddldata +objectbrowser.popupmenu.label.batchexportddldata = Export DDL and Data +objectbrowser.popupmenu.mnemonics.batchexportddldata = T +objectbrowser.popupmenu.tooltip.batchexportddldata = Export DDL and Data + +objectbrowser.popupmenu.id.dropviewcascade = org.opengauss.mppdbide.command.id.dropviewobjectcascade +objectbrowser.popupmenu.label.dropviewcascade = Drop View Cascade +objectbrowser.popupmenu.mnemonics.dropviewcascade = C +objectbrowser.popupmenu.tooltip.dropviewcascade =Drop the view object with cascade option ON + + ++#Open New Terminal Menu ++editmenu.id.opennewterminal = org.opengauss.edimenu.id.opennewterminal ++editmenu.label.opennewterminal = New Terminal Window ++editmenu.mnemonics.opennewterminal = O ++editmenu.tooltip.opennewterminal = New Terminal Window ++ + +#console text menu +view.popupmenu.id.console =org.opengauss.mppdbide.view.popupmenu.id.console +view.popupmenu.label.console=Console context menu +view.popupmenu.mnemonics.console= C +view.popupmenu.tooltip.console= + + +#filterresultwindowcontent +viewmenu.id.filterresultwindowcontent=org.opengauss.mppdbide.view.directtoolitem.id.resultfilter +viewmenu.label.filterresultwindowcontent= +viewmenu.mnemonics.filterresultwindowcontent=F +viewmenu.tooltip.filterresultwindowcontent=Result Data Filtered + + +#edit table +dataviewer.toolbar.edit.id.edittablewizard=org.opengauss.mppdbide.view.handledtoolitem.id.editableflag +dataviewer.toolbar.edit.label.edittablewizard=Edit Table +dataviewer.toolbar.edit.mnemonics.edittablewizard=E +dataviewer.toolbar.edit.tooltip.edittablewizard=Edit Table + + +#view filter +view.directtoolitem.id.viewfilter=org.opengauss.mppdbide.view.directtoolitem.id.viewfilter +view.directtoolitem.label.viewfilter= +view.directtoolitem.mnemonics.viewfilter= +view.directtoolitem.tooltip.viewfilter=Varibale Data Filtered + +#Create Sequence pop-up menu for object browser +objectbrowser.popupmenu.id.createsequence = org.opengauss.mppdbide.command.id.createsequence +objectbrowser.popupmenu.label.createsequence = Create Sequence +objectbrowser.popupmenu.mnemonics.createsequence = q +objectbrowser.popupmenu.tooltip.createsequence = Create a new Sequence + +#Sequence Drop +objectbrowser.popupmenu.id.dropsequence = org.opengauss.mppdbide.command.id.dropsequenceobject +objectbrowser.popupmenu.label.dropsequence = Drop Sequence +objectbrowser.popupmenu.mnemonics.dropsequence = D +objectbrowser.popupmenu.tooltip.dropsequence = Drop the sequence object + +#show Table By Sequence +objectbrowser.popupmenu.id.showTableBySequence = org.opengauss.mppdbide.command.id.showTableBySequence +objectbrowser.popupmenu.label.showTableBySequence = Show Related Table +objectbrowser.popupmenu.mnemonics.showTableBySequence = S +objectbrowser.popupmenu.tooltip.showTableBySequence = Show Related Table + +#Sequence Drop cascade +objectbrowser.popupmenu.id.dropsequence = org.opengauss.mppdbide.command.id.dropsequenceobjectcascade +objectbrowser.popupmenu.label.dropsequencecascade = Drop Sequence Cascade +objectbrowser.popupmenu.mnemonics.dropsequencecascade = D +objectbrowser.popupmenu.tooltip.dropsequencecascade = Drop the sequence object cascade + +#DB Assistant +view.db.assistant.title=SQL Assistant +view.db.assistant.open=Open SQL Assistant + +#Toggle Line Comment +editmenu.label.togglelinecomments = Comme&nt/Uncomment Lines +objectbrowser.popupmenu.mnemonics.togglelinecomments = N +editmenu.tooltip.togglelinecomments = Comment/Uncomment Lines +editmenu.tooltip.togglelinecomments1 = Comment/Uncomment Line1 + +#Toggle Block Comment +editmenu.label.toggleblockcomments = Comment/Uncomment &Block +objectbrowser.popupmenu.mnemonics.toggleblockcomments = B +editmenu.tooltip.toggleblockcomments = Comment/Uncomment Block + +#Grant/Revoke +objectbrowser.popupmenu.id.grantrevokewizard = org.opengauss.objectbrowser.popupmenu.id.grantrevokewizard +objectbrowser.popupmenu.label.grantrevokewizard = Grant/Revoke +objectbrowser.popupmenu.tooltip.grantrevokewizard = Grant/Revoke +objectbrowser.popupmenu.mnemonics.grantrevokewizard = P + +#tablespace properties +objectbrowser.popupmenu.label.tablespaceproperties=Properties +objectbrowser.popupmenu.mnemonics.tablespaceproperties=Properties +objectbrowser.popupmenu.tooltip.tablespaceproperties=Properties +#Create User/Role Wizard +org.opengauss.objectbrowser.popupmenu.id.createrole = org.opengauss.objectbrowser.popupmenu.id.createrole +objectbrowser.popupmenu.label.createrole = Create User/Role +objectbrowser.popupmenu.tooltip.createrole = Create User/Role +objectbrowser.popupmenu.mnemonics.createrole = P + +#Drop User/Role +org.opengauss.objectbrowser.popupmenu.id.dropuserrole = org.opengauss.objectbrowser.popupmenu.id.dropuserrole +objectbrowser.popupmenu.label.dropuserrole = Drop User/Role +objectbrowser.popupmenu.tooltip.dropuserrole = Drop User/Role +objectbrowser.popupmenu.mnemonics.dropuserrole = P + +#Create C Function +org.opengauss.objectbrowser.popupmenu.id.createcfunction = org.opengauss.objectbrowser.popupmenu.id.createcfunction +objectbrowser.popupmenu.label.createcfunction = Create C Function +objectbrowser.popupmenu.tooltip.createcfunction = Create C Function +objectbrowser.popupmenu.mnemonics.createcfunction = Cobjectbrowser.popupmenu.mnemonics.dropuserrole = P + +#Save As Menu +editmenu.id.savesqlas = org.opengauss.editmenu.id.savesqlas +editmenu.label.savesqlas = Save As +editmenu.mnemonics.savesqlas = S +editmenu.tooltip.savesqlas = Save As + +#Show DDL of sequence +objectbrowser.popupmenu.id.showsequenceddl = org.opengauss.mppdbide.command.id.showsequenceddl +objectbrowser.popupmenu.label.showsequenceddl = Show DDL +objectbrowser.popupmenu.mnemonics.showsequenceddl = S +objectbrowser.popupmenu.tooltip.showsequenceddl = Show the DDL for the sequence + +#Edit ERD pop-up menu for object browser +objectbrowser.popupmenu.id.viewerd = org.opengauss.mppdbide.command.id.viewerd +objectbrowser.popupmenu.label.viewerd = View ER Diagram +objectbrowser.popupmenu.mnemonics.viewerd = v +objectbrowser.popupmenu.tooltip.viewerd = View the ER Diagram + +#Create Synonym +org.opengauss.objectbrowser.popupmenu.id.createsynonym =org.opengauss.objectbrowser.popupmenu.id.createsynonym +objectbrowser.popupmenu.label.createsynonym = Create Synonym +objectbrowser.popupmenu.tooltip.createsynonym = Create Synonym +objectbrowser.popupmenu.mnemonics.createsynonym = P + +#Dop Synonym +org.opengauss.objectbrowser.popupmenu.id.dropsynonym =org.opengauss.objectbrowser.popupmenu.id.dropsynonym +objectbrowser.popupmenu.label.dropsynonym = Drop Synonym +objectbrowser.popupmenu.tooltip.dropsynonym = Drop Synonym +objectbrowser.popupmenu.mnemonics.dropsynonym = D + +#Start Debugging +org.opengauss.objectbrowser.popupmenu.id.startdebug = org.opengauss.objectbrowser.popupmenu.id.startdebug +objectbrowser.popupmenu.label.startdebug = Start Debugging +objectbrowser.popupmenu.tooltip.startdebug = Start Debugging +objectbrowser.popupmenu.mnemonics.startdebug = S + +#Trigger Create +org.opengauss.objectbrowser.popupmenu.id.triggergroup.create = org.opengauss.objectbrowser.popupmenu.id.triggergroup.create +objectbrowser.popupmenu.label.triggergroup.create = Trigger Create +objectbrowser.popupmenu.mnemonics.triggergroup.create = c +objectbrowser.popupmenu.tooltip.triggergroup.create = Trigger Create +#Trigger Drop +org.opengauss.objectbrowser.popupmenu.id.trigger.drop = org.opengauss.objectbrowser.popupmenu.id.trigger.drop +objectbrowser.popupmenu.label.trigger.drop = Trigger Drop +objectbrowser.popupmenu.mnemonics.trigger.drop = d +objectbrowser.popupmenu.tooltip.trigger.drop = Trigger Drop +#Trigger Edit +org.opengauss.objectbrowser.popupmenu.id.trigger.edit = org.opengauss.objectbrowser.popupmenu.id.trigger.edit +objectbrowser.popupmenu.label.trigger.edit = Trigger Edit +objectbrowser.popupmenu.mnemonics.trigger.edit = i +objectbrowser.popupmenu.tooltip.trigger.edit = Trigger Edit +#Trigger Enable +org.opengauss.objectbrowser.popupmenu.id.trigger.enable = org.opengauss.objectbrowser.popupmenu.id.trigger.enable +objectbrowser.popupmenu.label.trigger.enable = Trigger Enable +objectbrowser.popupmenu.mnemonics.trigger.enable = e +objectbrowser.popupmenu.tooltip.trigger.enable = Trigger Enable +#Trigger Disable +org.opengauss.objectbrowser.popupmenu.id.trigger.disable = org.opengauss.objectbrowser.popupmenu.id.trigger.disable +objectbrowser.popupmenu.label.trigger.disable = Trigger Disable +objectbrowser.popupmenu.mnemonics.trigger.disable = i +objectbrowser.popupmenu.tooltip.trigger.disable = Trigger Disable +#Trigger Rename +org.opengauss.objectbrowser.popupmenu.id.trigger.rename = org.opengauss.objectbrowser.popupmenu.id.trigger.rename +objectbrowser.popupmenu.label.trigger.rename = Trigger Rename +objectbrowser.popupmenu.mnemonics.trigger.rename = r +objectbrowser.popupmenu.tooltip.trigger.rename = Trigger Rename +#Edit View +org.opengauss.objectbrowser.popupmenu.id.view.editview = org.opengauss.objectbrowser.popupmenu.id.view.editview +objectbrowser.popupmenu.label.editview = Edit View +objectbrowser.popupmenu.mnemonics.editview = e +objectbrowser.popupmenu.tooltip.editview = Edit View \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/OSGI-INF/l10n/bundle_zh_CN.properties b/code/datastudio/src/org.opengauss.mppdbide.view/OSGI-INF/l10n/bundle_zh_CN.properties new file mode 100644 index 0000000000000000000000000000000000000000..31c510a263422049183e0214bbe87d2fd709e1be --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/OSGI-INF/l10n/bundle_zh_CN.properties @@ -0,0 +1,1221 @@ +#Handlers +handler.id.refreshdbobject = org.opengauss.mppdbide.handler.id.refreshdbobject +handler.id.disconnectconnectionprofile = org.opengauss.mppdbide.handler.id.disconnectconnectionprofile +handler.id.executedbobject = org.opengauss.mppdbide.handler.id.executedbobject +handler.id.debugdbobject = org.opengauss.mppdbide.handler.id.debugdbobject +handler.newdbconnection = org.opengauss.mppdbide.handler.id.newdbconnection +handler.toggleconsole = org.opengauss.mppdbide.handler.id.toggleconsole +handler.execute = org.opengauss.mppdbide.handler.id.execute + +#Commands + +#Command new DB connection +command.id.newdbconnection = org.opengauss.mppdbide.command.id.newdbconnection +command.name.newdbConnection = \u65B0\u7684\u6570\u636E\u5E93\u8FDE\u63A5 +command.description.newdbconnection = \u65B0\u7684\u6570\u636E\u5E93\u8FDE\u63A5 + +#Command and handler for new DB connection commandline +command.id.newdbconnectioncommandline = org.opengauss.mppdbide.view.command.newdbconnectioncommandline +command.name.newdbconnectioncommandline = \u65B0\u7684\u6570\u636E\u5E93\u8FDE\u63A5\u547D\u4EE4\u884C +command.description.newdbconnectioncommandline = \u65B0\u7684\u6570\u636E\u5E93\u8FDE\u63A5\u547D\u4EE4\u884C +handler.newdbconnectioncommandline = org.opengauss.mppdbide.view.handler.newdbconnectioncommandline + +#Command toggle Console +command.id.toggleconsole = org.opengauss.mppdbide.command.id.toggleconsole +command.name.toggleconsole = \u63A7\u5236\u53F0 +command.description.toggleconsole = \u63A7\u5236\u53F0 + +#Command refresh connection profile +#command.id.refreshconnectionprfofile = org.opengauss.mppdbide.command.id.refreshconnectionprfofile +#command.name.refreshconnectionprfofile = \u5237\u65B0\u8FDE\u63A5\u914D\u7F6E\u6587\u4EF6 +#command.description.refreshconnectionprfofile = \u5237\u65B0\u8FDE\u63A5\u914D\u7F6E\u6587\u4EF6 + +#Command refresh database object group +#command.id.refreshdbobjectgroup = org.opengauss.mppdbide.command.id.refreshdbobjectgroup +#command.name.refreshdbobjectgroup = \u5237\u65B0\u6570\u636E\u5E93\u5BF9\u8C61\u7EC4 +#command.description.refreshdbobjectgroup = \u5237\u65B0\u6570\u636E\u5E93\u5BF9\u8C61\u7EC4 + +#Command refresh database object +command.id.refreshdbobject = org.opengauss.mppdbide.command.id.refreshdbobject +command.name.refreshdbobject = \u5237\u65B0 +command.description.refreshdbobject = \u5237\u65B0\u6570\u636E\u5E93\u5BF9\u8C61 + +#Command disconnect connection profile +command.id.disconnectconnectionprofile = org.opengauss.mppdbide.command.id.disconnectconnectionprofile +command.name.disconnectconnectionprofile = \u5237\u65B0\u6570\u636E\u5E93\u5BF9\u8C61 +command.description.disconnectconnectionprofile = \u65AD\u5F00\u914D\u7F6E\u6587\u4EF6 + +#Command execute database object +command.id.executedbobject = org.opengauss.mppdbide.command.id.executedbobject +command.name.executedbobject = \u6267\u884C\u6570\u636E\u5E93\u5BF9\u8C61 +command.description.executedbobject = \u6267\u884C\u6570\u636E\u5E93\u5BF9\u8C61 + +#Command About dialog +command.id.about = org.opengauss.mppdbide.command.id.aboutdialog +command.name.about = \u5173\u4E8E +command.description.about = \u5173\u4E8E Data Studio + +#Windows +window.id.mainwindow = org.opengauss.mppdbide.window.id.mainwindow + +#Menus +#Main menu +menu.id.mainmenu = org.opengauss.mppdbide.menu.id.main + +#File Menu +menu.id.filemenu = org.opengauss.mppdbide.menu.id.file +menu.label.filemenu = \u6587\u4EF6(&F) +menu.mnemonics.filemenu = F + +#Settings Menu +menu.id.settingsmenu = org.opengauss.mppdbide.view.menu.settings +menu.label.settingsmenu = \u8BBE\u7F6E(&G) +menu.mnemonics.settingsmenu = G + +#Language Menu +menu.id.filelanguagemenu = org.opengauss.mppdbide.view.menu.language +menu.label.filelanguagemenu =\u8BED\u8A00(&L) +menu.mnemonics.filelanguagemenu = L + +#English Language +filelanguagemenu.id.englishlanguage = org.opengauss.mppdbide.view.handledmenuitem.englishlanguage +filelanguagemenu.label.englishlanguage =(en_US) &English (E) +filelanguagemenu.mnemonics.englishlanguage = E +filelanguagemenu.tooltip.englishlanguage = English + +#Chinese Language +filelanguagemenu.id.chineselanguage = org.opengauss.mppdbide.view.handledmenuitem.chineselanguage +filelanguagemenu.label.chineselanguage =(zh_CN)\u4E2D\u6587\uFF08\u7B80\u4F53\uFF09(&C) +filelanguagemenu.mnemonics.chineselanguage = C +filelanguagemenu.tooltip.chineselanguage = \u4E2D\u6587 + + +#Preferences +filelanguagemenu.id.preferences = org.opengauss.mppdbide.view.handledmenuitem.preferences +filelanguagemenu.label.preferences =\u9996\u9009\u9879(&P) +filelanguagemenu.mnemonics.preferences =P +filelanguagemenu.tooltip.preferences = \u9996\u9009\u9879 + +#New connection +filemenu.id.newconnection = org.opengauss.filemenu.id.newconnection +filemenu.label.newconnection = \u65B0\u5EFA\u8FDE\u63A5(&N) +filemenu.mnemonics.newconnection = N +filemenu.tooltip.newconnection = \u65B0\u5EFA\u8FDE\u63A5 + +#Export connection +filemenu.id.exportconnections = org.opengauss.filemenu.id.exportconnections +filemenu.label.exportconnections = \u5BFC\u51FA\u8FDE\u63A5\u914D\u7F6E\u6587\u4EF6(&E) +filemenu.mnemonics.exportconnections = E +filemenu.tooltip.exportconnections = \u5BFC\u51FA\u8FDE\u63A5\u914D\u7F6E\u6587\u4EF6 + + +#import connection +filemenu.id.importconnections = org.opengauss.filemenu.id.importconnections +filemenu.label.importconnections = \u5BFC\u5165\u8FDE\u63A5\u914D\u7F6E\u6587\u4EF6(&I) +filemenu.mnemonics.importconnections = I +filemenu.tooltip.importconnections = \u5BFC\u5165\u8FDE\u63A5\u914D\u7F6E\u6587\u4EF6 + +#Remove connection +filemenu.id.removeconnection = org.opengauss.filemenu.id.removeconnection +filemenu.label.removeconnection = \u5220\u9664\u8FDE\u63A5(&R) +filemenu.mnemonics.removeconnection = R +filemenu.tooltip.removeconnection = \u5220\u9664\u8FDE\u63A5 + +#Connect to db +filemenu.id.connecttodb = org.opengauss.filemenu.id.connecttodb +filemenu.label.connecttodb =\u6253\u5F00\u8FDE\u63A5(&C) +filemenu.mnemonics.connecttodb = C +filemenu.tooltip.connecttodb = \u6253\u5F00\u8FDE\u63A5 + +#Edit Menu +menu.id.editmenu = org.opengauss.mppdbide.menu.id.edit +menu.label.editmenu = \u7F16\u8F91(&E) +menu.mnemonics.editmenu = E + +#View Menu +menu.id.viewmenu = org.opengauss.mppdbide.menu.id.view +menu.label.viewmenu =\u67E5\u770B(&V) +menu.mnemonics.viewmenu = V + +#Console window +viewmenu.id.console = org.opengauss.viewmenu.id.console +viewmenu.label.console = \u6D88\u606F +viewmenu.mnemonics.console = M +viewmenu.tooltip.console = \u6D88\u606F + +#SQL Terminal Window +viewmenu.id.sqlterminal = org.opengauss.viewmenu.id.sqlterminal +viewmenu.label.sqlterminal = SQL \u7EC8\u7AEF +viewmenu.mnemonics.sqlterminal = T +viewmenu.tooltip.sqlterminal = SQL \u7EC8\u7AEF + +#Object Browser Window +viewmenu.id.objectbrowser = org.opengauss.viewmenu.id.objectbrowser +viewmenu.label.objectbrowser = \u5BF9\u8C61\u6D4F\u89C8\u5668 +viewmenu.mnemonics.objectbrowser = O +viewmenu.tooltip.objectbrowser = \u5BF9\u8C61\u6D4F\u89C8\u5668 + +#Object Browser Window +viewmenu.id.advancedsearch = org.opengauss.viewmenu.id.advancedsearch +viewmenu.label.advancedsearch = \u9AD8\u7EA7\u641C\u7D22 +viewmenu.mnemonics.advancedsearch = A +viewmenu.tooltip.advancedsearch = \u9AD8\u7EA7\u641C\u7D22 + +#Edit Table Data window +viewmenu.id.edittabledata = org.opengauss.viewmenu.id.edittabledata +viewmenu.label.edittabledata = \u7F16\u8F91\u8868\u6570\u636E +viewmenu.mnemonics.edittabledata = E +viewmenu.tooltip.edittabledata = \u7F16\u8F91\u8868\u6570\u636E + +#Result window +viewmenu.id.result = org.opengauss.viewmenu.id.result +viewmenu.label.result = \u7ED3\u679C(&R) +viewmenu.mnemonics.result = R +viewmenu.tooltip.result = \u7ED3\u679C + +#CopyResult Menu +viewmenu.id.copyresultwindowcontent = org.opengauss.viewmenu.id.result +viewmenu.label.copyresultwindowcontent = \u590D\u5236\u7A97\u53E3\u7ED3\u679C\u5185\u5BB9 +viewmenu.mnemonics.copyresultwindowcontent = P +viewmenu.tooltip.copyresultwindowcontent = \u590D\u5236\u7A97\u53E3\u7ED3\u679C\u5185\u5BB9 + +#ExportResult Menu +viewmenu.id.exportresulttocsv = org.opengauss.viewmenu.id.result +viewmenu.label.exportresulttocsv = \u5BFC\u51FA\u6240\u6709\u7ED3\u679C\u4E3ACSV +viewmenu.mnemonics.exportresulttocsv = S +viewmenu.tooltip.exportresulttocsv = \u5BFC\u51FA\u6240\u6709\u7ED3\u679C\u4E3ACSV + +#ExportCurrentResult Menu +viewmenu.id.exportcurrentresulttocsv = org.opengauss.viewmenu.id.result +viewmenu.label.exportcurrentresulttocsv = \u5BFC\u51FA\u5F53\u524D\u9875\u5230CSV +viewmenu.tooltip.exportcurrentresulttocsv = \u5BFC\u51FA\u5F53\u524D\u9875\u5230CSV + +#Breakpoint window +viewmenu.id.breakpoint = org.opengauss.viewmenu.id.breakpoint +viewmenu.label.breakpoint = \u65AD\u70B9 +viewmenu.mnemonics.breakpoint = B +viewmenu.tooltip.breakpoint = \u65AD\u70B9 + +#Stack window +viewmenu.id.stack = org.opengauss.viewmenu.id.stack +viewmenu.label.stack = \u8C03\u7528\u5806\u6808 +viewmenu.mnemonics.stack = S +viewmenu.tooltip.stack = \u8C03\u7528\u5806\u6808 + +#Variable window +viewmenu.id.variable = org.opengauss.viewmenu.id.variable +viewmenu.label.variable = \u53D8\u91CF +viewmenu.mnemonics.variable = V +viewmenu.tooltip.variable = \u53D8\u91CF + +#Monitor window +viewmenu.id.monitor = org.opengauss.viewmenu.id.monitor +viewmenu.label.monitor = \u76d1\u89c6\u5668 +viewmenu.mnemonics.monitor = M +viewmenu.tooltip.monitor = \u76d1\u89c6\u5668 + +#Run Menu +menu.id.runmenu = org.opengauss.mppdbide.menu.id.run +menu.label.runmenu = \u8FD0\u884C(&R) +menu.mnemonics.runmenu = R + +#Run Debug +menu.id.debugmenu = org.opengauss.mppdbide.menu.id.debugmenu +menu.label.debugmenu = \u8c03\u8bd5(&B) +menu.mnemonics.debugmenu = B + +executemenu.id.debug = org.opengauss.executemenu.id.debug +executemenu.label.debug = \u542f\u52a8\u8c03\u8bd5(&S) +executemenu.mnemonics.debug = S +executemenu.tooltip.debug = \u542f\u52a8\u8c03\u8bd5 + +executemenu.id.terminate = org.opengauss.executemenu.id.terminate +executemenu.label.terminate = \u505c\u6b62\u8c03\u8bd5(&T) +executemenu.mnemonics.terminate = T +executemenu.tooltip.terminate = \u505c\u6b62\u8c03\u8bd5 + +executemenu.id.continue = org.opengauss.executemenu.id.continue +executemenu.label.continue = \u7ee7\u7eed(&C) +executemenu.mnemonics.continue = C +executemenu.tooltip.continue = \u7ee7\u7eed + +executemenu.id.stepin = org.opengauss.executemenu.id.stepin +executemenu.label.stepin = \u6b65\u5165(&I) +executemenu.mnemonics.stepin = I +executemenu.tooltip.stepin = \u6b65\u5165 + +executemenu.id.stepover = org.opengauss.executemenu.id.stepover +executemenu.label.stepover = \u6b65\u8fdb(&O) +executemenu.mnemonics.stepover = O +executemenu.tooltip.stepover = \u6b65\u8fdb + +executemenu.id.stepout = org.opengauss.executemenu.id.stepout +executemenu.label.stepout = \u6b65\u51fa(&R) +executemenu.mnemonics.stepout = R +executemenu.tooltip.stepout = \u6b65\u51fa + +#Compile +executemenu.id.compile = org.opengauss.executemenu.id.compile +executemenu.label.compile = \u7F16\u8BD1 +executemenu.mnemonics.compile = M +executemenu.tooltip.compile = \u7F16\u8BD1 + +#Execute +executemenu.id.execute = org.opengauss.executemenu.id.execute +executemenu.label.execute = \u6267\u884C(&E) +executemenu.mnemonics.execute = E +executemenu.tooltip.execute = \u6267\u884C + +#Execute SQL Terminal +executemenu.id.executeterminal = org.opengauss.executemenu.id.executeterminal +executemenu.label.executeterminal = \u7F16\u8BD1/\u6267\u884C(&X) +executemenu.mnemonics.executeterminal = X +executemenu.tooltip.executeterminal = \u6267\u884C\u58F0\u660E + +#Execute SQL Terminal New Tab +executemenu.id.executesqlnewterminal = org.opengauss.executemenu.id.executesqlnewterminal +executemenu.label.executesqlnewterminal = \u65B0\u589E\u9875\u7B7E\u7F16\u8BD1/\u6267\u884C\u8BED\u53E5 +executemenu.tooltip.executesqlnewterminal = \u65B0\u589E\u9875\u7B7E\u6267\u884C\u8BED\u53E5 + + +#For execute sql terminal alone +executemenu.label.executeterminal.alone = \u6267\u884C\u58F0\u660E(&X) + +#Compile Function +executemenu.id.compilefunction = org.opengauss.mppdbide.trimbar.id.compilefunction.toolbar.handler +executemenu.label.compilefunction = \u7F16\u8BD1 +executemenu.mnemonics.compilefunction = M +executemenu.tooltip.compilefunction = \u7F16\u8BD1 + +#Cancel Executing SQL Query +executemenu.id.cancelquery = org.opengauss.executemenu.id.cancelquery +executemenu.label.cancelquery = \u7EC8\u6B62 +executemenu.mnemonics.cancelquery = X +executemenu.tooltip.cancelquery = \u7EC8\u6B62 + +#Disconnect +filemenu.id.disconnect = org.opengauss.filemenu.id.disconnect +filemenu.label.disconnect = \u65AD\u5F00\u8FDE\u63A5(&D) +filemenu.mnemonics.disconnect = D +filemenu.tooltip.disconnect = \u65AD\u5F00\u8FDE\u63A5 + +#Disconnect All +filemenu.id.disconnectall = org.opengauss.filemenu.id.disconnect +filemenu.label.disconnectall = \u65AD\u5F00\u6240\u6709\u8FDE\u63A5(&L) +filemenu.mnemonics.disconnectall = L +filemenu.tooltip.disconnectall = \u65AD\u5F00\u6240\u6709\u8FDE\u63A5 + +#Open New Instance +filemenu.id.opennewinstance = org.opengauss.filemenu.id.opennewinstance +filemenu.label.opennewinstance = \u5728\u65B0\u7A97\u53E3\u4E2D\u6253\u5F00 (&W) +filemenu.mnemonics.opennewinstance = W +filemenu.tooltip.opennewinstance = \u5728\u65B0\u7A97\u53E3\u4E2D\u6253\u5F00 +#Open New Terminal Menu +editmenu.id.opennewterminal = org.opengauss.edimenu.id.opennewterminal +editmenu.label.opennewterminal = \u65B0\u7EC8\u7AEF\u7A97\u53E3 +editmenu.mnemonics.opennewterminal = O +editmenu.tooltip.opennewterminal = \u65B0\u7EC8\u7AEF\u7A97\u53E3 + +#Exit +filemenu.id.exit = org.opengauss.filemenu.id.exit +filemenu.label.exit = \u9000\u51FA(&X) +filemenu.mnemonics.exit = X +filemenu.tooltip.exit = \u9000\u51FA\u5E94\u7528\u7A0B\u5E8F + +#Help Menu +menu.id.helpmenu = org.opengauss.mppdbide.menu.id.help +menu.label.helpmenu = \u5E2E\u52A9(&H) +menu.mnemonics.helpmenu = H + +#Cut Menu +editmenu.id.cut = org.opengauss.editmenu.id.cut +editmenu.label.cut = \u526A\u5207(&T) +editmenu.mnemonics.cut = T +editmenu.tooltip.cut = \u526A\u5207 + +#Execution Plan Cost +executemenu.id.executionplan = org.opengauss.executemenu.id.executionplan +executemenu.label.executionplan = \u6267\u884C\u8BA1\u5212 +executemenu.mnemonics.executionplan = E +executemenu.tooltip.executionplan =\u6267\u884C\u8BA1\u5212 + +#Visual Explain Plan +executemenu.id.visualexplainplan = org.opengauss.executemenu.id.visualexplainplan +executemenu.label.visualexplainplan = \u53EF\u89C6\u5316\u89E3\u91CA\u8BA1\u5212(&P) +executemenu.mnemonics.visualexplainplan = P +executemenu.tooltip.visualexplainplan = \u53EF\u89C6\u5316\u89E3\u91CA\u8BA1\u5212 + +#Copy Menu +editmenu.id.copy = org.opengauss.editmenu.id.copy +editmenu.label.copy = \u590D\u5236(&C) +editmenu.mnemonics.copy = C +editmenu.tooltip.copy = \u590D\u5236 + +#PasteMenu +editmenu.id.paste = org.opengauss.editmenu.id.paste +editmenu.label.paste = \u7C98\u8D34(&P) +editmenu.mnemonics.paste = P +editmenu.tooltip.paste = \u7C98\u8D34 + +#format Menu +editmenu.id.format = org.opengauss.editmenu.id.format +editmenu.label.format =\u683C\u5F0F\u5316(&F) +editmenu.mnemonics.format = F +editmenu.tooltip.format = \u683C\u5F0F\u5316 + +#format Menu +editmenu.id.newinstance = org.opengauss.editmenu.id.newinstance +editmenu.label.newinstance = \u5728\u65B0\u7A97\u53E3\u4E2D\u6253\u5F00 (&W) +editmenu.mnemonics.newinstance = W +editmenu.tooltip.newinstance = \u5728\u65B0\u7A97\u53E3\u4E2D\u6253\u5F00 + +#Save Menu +editmenu.id.savesql = org.opengauss.editmenu.id.savesql +editmenu.label.savesql = \u4FDD\u5B58(&S) +editmenu.mnemonics.savesql = S +editmenu.tooltip.savesql = \u4FDD\u5B58 + + +#Open Terminal +editmenu.id.opennewterminal = org.opengauss.editmenu.id.opennewterminal +editmenu.label.opennewterminal = \u6253\u5F00\u65B0\u7684\u7EC8\u7AEF(&O) +editmenu.mnemonics.opennewterminal = O +editmenu.tooltip.opennewterminal = \u6253\u5F00\u65B0\u7684\u7EC8\u7AEF + +#Open Menu +editmenu.id.opensql = org.opengauss.editmenu.id.opensql +editmenu.label.opensql = \u6253\u5F00(&O) +editmenu.mnemonics.opensql = O +editmenu.tooltip.opensql = \u6253\u5F00 + +#Selectall menu +editmenu.id.selectall = org.opengauss.editmenu.id.selectall +editmenu.label.selectall = \u5168\u9009(&A) +editmenu.mnemonics.selectall = A +editmenu.tooltip.selectall = \u5168\u9009 + +#Find menu +editmenu.id.find = org.opengauss.editmenu.id.findreplace +editmenu.label.find = \u67E5\u627E\u548C\u66FF\u6362(&I) +editmenu.mnemonics.find = i +editmenu.tooltip.find = \u67E5\u627E\u548C\u66FF\u6362 + +#Search menu +editmenu.id.search = org.opengauss.mppdbide.view.handledmenuitem.search +editmenu.label.search =\u641C\u7D22\u5BF9\u8C61(&S) +editmenu.mnemonics.search = s +editmenu.tooltip.search = \u641C\u7D22\u5BF9\u8C61 + +#Undo menu +editmenu.id.undo = org.opengauss.editmenu.id.undo +editmenu.label.undo = \u64A4\u9500(&U) +editmenu.mnemonics.undo = u +editmenu.tooltip.undo = \u64A4\u9500 + +#Redo menu +editmenu.id.redo = org.opengauss.editmenu.id.redo +editmenu.label.redo = \u91CD\u505A(&R) +editmenu.mnemonics.redo = r +editmenu.tooltip.redo = \u91CD\u505A + +#Execute DB Object menu +executemenu.id.executedbobjectineditor = org.opengauss.executemenu.id.execute +executemenu.label.executedbobjectineditor = \u6267\u884C(&D) +executemenu.mnemonics.executedbobjectineditor = E +executemenu.tooltip.executedbobjectineditor = \u6267\u884C + +#User Guide menu +helpmenu.id.userguide = org.opengauss.mppdbide.menu.id.help.userguid +helpmenu.label.userguide =\u7528\u6237\u624B\u518C(&U) +helpmenu.mnemonics.userguide = U +helpmenu.tooltip.userguide =\u7528\u6237\u624B\u518C + +#About menu +helpmenu.id.about = org.opengauss.mppdbide.menu.id.help.about +helpmenu.label.about = \u5173\u4E8E(&A) +helpmenu.mnemonics.about = A +helpmenu.tooltip.about = \u5173\u4E8EData Studio + +#Parts +partsashcontainer.id.main = org.opengauss.mppdbide.partsashcontainer.id.main + +#Object browser partstack +partstack.id.objectbrowser = org.opengauss.mppdbide.partstack.id.objectbrowser + +#Object browser part +part.id.objectbrowser=org.opengauss.mppdbide.part.id.objectbrowser +part.label.objectbrowser=\u5BF9\u8C61\u6D4F\u89C8\u5668 + +#Object browser pop up menu +part.menu.id.objectbrowser = org.opengauss.mppdbide.part.menu.id.objectbrowser +part.menu.label.objectbrowser = \u5BF9\u8C61\u6D4F\u89C8\u5668\u5F39\u51FA\u83DC\u5355 + +#Refresh popup menu for objectbrowser +objectbrowser.popupmenu.id.refresh = org.opengauss.objectbrowser.popupmenu.id.refresh +objectbrowser.popupmenu.label.refresh = \u5237\u65B0 +objectbrowser.popupmenu.mnemonics.refresh = R +objectbrowser.popupmenu.tooltip.refresh = \u5237\u65B0\u6570\u636E\u5BF9\u8C61 + +#View Data pop up menu +objectbrowser.popupmenu.id.viewdata = org.opengauss.objectbrowser.popupmenu.id.viewdata +objectbrowser.popupmenu.label.viewdata = \u67E5\u770B\u6570\u636E +objectbrowser.popupmenu.mnemonics.viewdata = V +objectbrowser.popupmenu.tooltip.viewdata = \u67E5\u770B\u89C6\u56FE\u6570\u636E + +#Execute popup menu for objectbrowser +objectbrowser.popupmenu.id.execute = org.opengauss.objectbrowser.popupmenu.id.execute +objectbrowser.popupmenu.label.execute = \u6267\u884C +objectbrowser.popupmenu.mnemonics.execute = X +objectbrowser.popupmenu.tooltip.execute = \u6267\u884C\u6570\u636E\u5E93\u5BF9\u8C61 + + + + + +#View Source popup menu for objectbrowser +objectbrowser.popupmenu.id.viewsource = org.opengauss.objectbrowser.popupmenu.id.viewsource +objectbrowser.popupmenu.label.viewsource = \u67E5\u770B\u6E90 +objectbrowser.popupmenu.mnemonics.viewsource = w +objectbrowser.popupmenu.tooltip.viewsource = \u67E5\u770B\u6E90 + +#Expression for debug popup menu in objectbrowse +objectbrowser.popupmenu.debug.id.expression = org.opengauss.objectbrowser.popupmenu.debug.id.expression + +#Disconnect popup menu for objectbrowser +objectbrowser.popupmenu.id.connect = org.opengauss.objectbrowser.popupmenu.id.connect +objectbrowser.popupmenu.label.connect = \u6253\u5F00\u8FDE\u63A5 +objectbrowser.popupmenu.mnemonics.connect = C +objectbrowser.popupmenu.tooltip.connect = \u8FDE\u63A5\u5230\u6570\u636E\u5E93 + +#Disconnect popup menu for objectbrowser +objectbrowser.popupmenu.id.disconnect = org.opengauss.objectbrowser.popupmenu.id.disconnect +objectbrowser.popupmenu.label.disconnect =\u65AD\u5F00\u8FDE\u63A5 +objectbrowser.popupmenu.mnemonics.disconnect = D +objectbrowser.popupmenu.tooltip.disconnect = \u65AD\u5F00\u6570\u636E\u5E93 + +objectbrowser.popupmenu.id.properties = org.opengauss.objectbrowser.popupmenu.id.properties +objectbrowser.popupmenu.label.properties = \u5C5E\u6027 +objectbrowser.popupmenu.mnemonics.properties = P +objectbrowser.popupmenu.tooltip.properties = \u670D\u52A1\u5668\u5C5E\u6027 + +objectbrowser.popupmenu.id.datatypedetails = org.opengauss.objectbrowser.popupmenu.id.datatypedetails +objectbrowser.popupmenu.label.datatypedetails = \u6570\u636E\u7C7B\u578B\u8BE6\u7EC6\u4FE1\u606F +objectbrowser.popupmenu.mnemonics.datatypedetails = D +objectbrowser.popupmenu.tooltip.datatypedetails = \u8BE6\u7EC6\u6570\u636E + +#Clear console window +consolepopupmenu.id.clear = org.opengauss.mppdbide.view.consolemenu.clear +consolepopupmenu.label.clear = \u6E05\u9664 +consolepopupmenu.mnemonics.clear = L +consolepopupmenu.tooltip.clear = \u6E05\u9664 + +#Expression for disconnect popup menu in objectbrowse +objectbrowser.popupmenu.disconnect.id.expression = org.opengauss.objectbrowser.popupmenu.disconnect.id.expression + +#Partsash container sub(editor, console, stack, breakpoint & variable +partsashcontainer.id.sub = org.opengauss.mppdbide.partsashcontainer.id.sub + +#Partsash container sub(editor, console, stack, breakpoint & variable +partsashcontainer.id.sub.editor.console = org.opengauss.mppdbide.partsashcontainer.id.sub.editor.console + +#Editor partstack +partstack.id.editor = org.opengauss.mppdbide.partstack.id.editor + +#Editor part +part.id.editor = org.opengauss.mppdbide.part.id.editor +part.label.editor = PLSQL \u6D4F\u89C8\u5668 + +part.id.sqlterminal = org.opengauss.mppdbide.part.id.sqlterminal +part.label.sqlterminal = SQL \u7EC8\u7AEF + +#Console partstack +partstack.id.console = org.opengauss.mppdbide.partstack.id.console + +#AdvancedSearch partstack +partstack.id.advancedsearch = org.opengauss.mppdbide.part.id.advsearch + +#console part +part.id.console = org.opengauss.mppdbide.part.id.console +part.label.console = \u63A7\u5236\u53F0 + +part.id.result = org.opengauss.mppdbide.part.id.console +part.label.result = \u7ED3\u679C + + +#Trimbar +trimbar.id.maintrimbar = org.opengauss.mppdbide.trimbar.id.maintrimbar + +#Toolbar +trimbar.id.maintrimbar.toolbar = org.opengauss.mppdbide.trimbar.id.maintrimbar.toolbar + +#handlers +trimbar.id.newconnection.toolbar.handler = org.opengauss.mppdbide.trimbar.id.newconnection.toolbar.handler + +#Create PLSQLfunction popup menu for objectbrowser +objectbrowser.popupmenu.id.createfunction= org.opengauss.objectbrowser.popupmenu.id.createfunction +objectbrowser.popupmenu.label.createfunction = \u521B\u5EFA\u51FD\u6570 +objectbrowser.popupmenu.mnemonics.createfunction = c +objectbrowser.popupmenu.tooltip.createfunction = \u521B\u5EFA\u51FD\u6570 + +#Create SQL function popup menu for objectbrowser +objectbrowser.popupmenu.id.createsqlfunction= org.opengauss.mppdbide.view.handledmenuitem.createsqlfunction +objectbrowser.popupmenu.label.createsqlfunction = \u521B\u5EFASQL\u51FD\u6570 +objectbrowser.popupmenu.mnemonics.createsqlfunction = c +objectbrowser.popupmenu.tooltip.createsqlfunction = \u521B\u5EFASQL\u51FD\u6570 + +#Create PLSQL procedure popup menu for objectbrowser +objectbrowser.popupmenu.id.createprocedure= org.opengauss.objectbrowser.popupmenu.id.createprocedure +objectbrowser.popupmenu.label.createprocedure = \u521B\u5EFA\u8FC7\u7A0B +objectbrowser.popupmenu.mnemonics.createprocedure = c +objectbrowser.popupmenu.tooltip.createprocedure = \u521B\u5EFA\u8FC7\u7A0B + +#Create PLSQL package popup menu for objectbrowser +objectbrowser.popupmenu.id.createpackage= org.opengauss.objectbrowser.popupmenu.id.createpackage +objectbrowser.popupmenu.label.createpackage = \u521B\u5EFA\u5957\u9910 +objectbrowser.popupmenu.mnemonics.createpackage = c +objectbrowser.popupmenu.tooltip.createpackage = \u521B\u5EFA\u5957\u9910 + +#Create trigger popup menu for objectbrowser +objectbrowser.popupmenu.id.createtrigger= org.opengauss.objectbrowser.popupmenu.id.createtrigger +objectbrowser.popupmenu.label.createtrigger = \u521B\u5EFA\u89E6\u53D1\u5668\u51FD\u6570 +objectbrowser.popupmenu.mnemonics.createtrigger = t +objectbrowser.popupmenu.tooltip.createtrigger = \u521B\u5EFA\u89E6\u53D1\u5668\u51FD\u6570 + +#Drop debug object popup menu for objectbrowser +objectbrowser.popupmenu.id.dropdebugobject= org.opengauss.objectbrowser.popupmenu.id.dropdebugobject +objectbrowser.popupmenu.label.dropdebugobject = \u5220\u9664\u51FD\u6570/\u8FC7\u7A0B +objectbrowser.popupmenu.mnemonics.dropdebugobject = t +objectbrowser.popupmenu.tooltip.dropdebugobject = \u5220\u9664\u51FD\u6570/\u8FC7\u7A0B + +#Create db popup menu for object browser +objectbrowser.popupmenu.id.createdb = objectbrowser.popupmenu.id.createdb +objectbrowser.popupmenu.label.createdb = \u521B\u5EFA\u6570\u636E\u5E93 +objectbrowser.popupmenu.mnemonics.createdb = r +objectbrowser.popupmenu.tooltip.createdb = \u65B0\u5EFA\u6570\u636E\u5E93 + +#Create db rename connection for object browser +objectbrowser.popupmenu.id.renameconnection = objectbrowser.popupmenu.id.renameconnection +objectbrowser.popupmenu.label.renameconnection = \u91CD\u547D\u540D\u8FDE\u63A5 +objectbrowser.popupmenu.mnemonics.renameconnection = r +objectbrowser.popupmenu.tooltip.renameconnection = \u91CD\u547D\u540D\u8FDE\u63A5 + +#Create db edit connection for object browser +objectbrowser.popupmenu.id.editconnection = objectbrowser.popupmenu.id.editconnection +objectbrowser.popupmenu.label.editconnection = \u7F16\u8F91\u8FDE\u63A5 +objectbrowser.popupmenu.mnemonics.editconnection = r +objectbrowser.popupmenu.tooltip.editconnection = \u7F16\u8F91\u8FDE\u63A5 + + +#rename db popup menu for object browser +objectbrowser.popupmenu.id.renamedb = objectbrowser.popupmenu.id.renamedb +objectbrowser.popupmenu.label.renamedb = \u91CD\u547D\u540D +objectbrowser.popupmenu.mnemonics.renamedb = e +objectbrowser.popupmenu.tooltip.renamedb = \u91CD\u547D\u540D\u6570\u636E\u5E93 + +#open new terminal popup menu for object browser +objectbrowser.popupmenu.id.opennewterminal = objectbrowser.popupmenu.id.opennewterminal +objectbrowser.popupmenu.label.opennewterminal = \u6253\u5F00\u65B0\u7684\u7EC8\u7AEF +objectbrowser.popupmenu.mnemonics.opennewterminal = O +objectbrowser.popupmenu.tooltip.opennewterminal = \u6253\u5F00\u65B0\u7684\u7EC8\u7AEF + +#Drop db popup menu for object browser +objectbrowser.popupmenu.id.dropdb = objectbrowser.popupmenu.id.dropdb +objectbrowser.popupmenu.label.dropdb = \u5220\u9664 +objectbrowser.popupmenu.mnemonics.dropdb = e +objectbrowser.popupmenu.tooltip.dropdb =\u5220\u9664\u6570\u636E\u5E93 + +#Create schema db popup menu for object browser +objectbrowser.popupmenu.id.createschema = objectbrowser.popupmenu.id.createschema +objectbrowser.popupmenu.label.createschema = \u521B\u5EFA\u6A21\u5F0F +objectbrowser.popupmenu.mnemonics.createschema = s +objectbrowser.popupmenu.tooltip.createschema = \u521B\u5EFA\u6A21\u5F0F + +#Rename schema schema popup menu for object browser +objectbrowser.popupmenu.id.renameschema = objectbrowser.popupmenu.id.renameschema +objectbrowser.popupmenu.label.renameschema = \u91CD\u547D\u540D +objectbrowser.popupmenu.mnemonics.renameschema = r +objectbrowser.popupmenu.tooltip.renameschema = \u91CD\u547D\u540D\u6A21\u5F0F + +#Drop schema schema popup menu for object browser +objectbrowser.popupmenu.id.dropschema = objectbrowser.popupmenu.id.dropschema +objectbrowser.popupmenu.label.dropschema = \u5220\u9664 +objectbrowser.popupmenu.mnemonics.dropschema = d +objectbrowser.popupmenu.tooltip.dropschema = \u5220\u9664\u6A21\u5F0F + +#Drop objects popup menu for object browser +objectbrowser.popupmenu.id.dropobjects = objectbrowser.popupmenu.id.dropobjects +objectbrowser.popupmenu.label.dropobjects = \u5220\u9664\u5BF9\u8C61 +objectbrowser.popupmenu.mnemonics.dropobjects = d +objectbrowser.popupmenu.tooltip.dropobjects = \u5220\u9664\u5BF9\u8C61 + +#Create table popup menu for object browser +objectbrowser.popupmenu.id.createtable = objectbrowser.popupmenu.id.createtable +objectbrowser.popupmenu.label.createtable = \u521B\u5EFA\u666E\u901A\u8868 +objectbrowser.popupmenu.mnemonics.createtable = b +objectbrowser.popupmenu.tooltip.createtable = \u521B\u5EFA\u666E\u901A\u8868 + + +#Rename table popup menu for object browser +objectbrowser.popupmenu.id.renametable = objectbrowser.popupmenu.id.renametable +objectbrowser.popupmenu.label.renametable = \u91CD\u547D\u540D +objectbrowser.popupmenu.mnemonics.renametable = r +objectbrowser.popupmenu.tooltip.renametable = \u91CD\u547D\u540D + +#Create table pop-up menu for object browser +objectbrowser.popupmenu.id.createtable = org.opengauss.mppdbide.command.id.createtable +objectbrowser.popupmenu.label.createtable = \u521B\u5EFA\u666E\u901A\u8868 +objectbrowser.popupmenu.mnemonics.createtable = b +objectbrowser.popupmenu.tooltip.createtable = \u521B\u5EFA\u666E\u901A\u8868 + + + +#Create Partition table pop-up menu for object browser +objectbrowser.popupmenu.id.createpartitiontable = org.opengauss.mppdbide.command.id.createpartitiontable +objectbrowser.popupmenu.label.createpartitiontable = \u521B\u5EFA\u5206\u533A\u8868 +objectbrowser.popupmenu.mnemonics.createpartitiontable = p +objectbrowser.popupmenu.tooltip.createpartitiontable = \u521B\u5EFA\u666E\u901A\u8868 + +#Drop Partition pop-up menu for object browser +objectbrowser.popupmenu.id.droppartition = org.opengauss.objectbrowser.popupmenu.id.droppartition +objectbrowser.popupmenu.label.droppartition = \u5220\u9664\u5206\u533A +objectbrowser.popupmenu.mnemonics.droppartition = p +objectbrowser.popupmenu.tooltip.droppartition = \u5220\u9664\u5206\u533A + +#View Partition Data pop-up menu for object browser +objectbrowser.popupmenu.id.viewpartition = org.opengauss.objectbrowser.popupmenu.id.viewpartition +objectbrowser.popupmenu.label.viewpartition = \u67e5\u770b\u5206\u533a\u6570\u636e +objectbrowser.popupmenu.mnemonics.viewpartition = p +objectbrowser.popupmenu.tooltip.viewpartition = \u67e5\u770b\u5206\u533a\u6570\u636e + +#Rename Partition pop-up menu for object browser +objectbrowser.popupmenu.id.renamepartition = org.opengauss.objectbrowser.popupmenu.id.renamepartition +objectbrowser.popupmenu.label.renamepartition = \u91CD\u547D\u540D\u5206\u533A +objectbrowser.popupmenu.mnemonics.renamepartition = p +objectbrowser.popupmenu.tooltip.renamepartition =\u91CD\u547D\u540D\u5206\u533A + +#Rename Table pop-up menu for object browser +objectbrowser.popupmenu.id.renametable = org.opengauss.mppdbide.command.id.renametable +objectbrowser.popupmenu.label.renametable = \u91CD\u547D\u540D +objectbrowser.popupmenu.mnemonics.renametable = r +objectbrowser.popupmenu.tooltip.renametable = \u66F4\u6539\u8868\u7684\u540D\u79F0 + +#Drop Table pop-up menu for object browser +objectbrowser.popupmenu.id.droptable = org.opengauss.mppdbide.command.id.droptable +objectbrowser.popupmenu.label.droptable = \u5220\u9664 +objectbrowser.popupmenu.mnemonics.droptable = d +objectbrowser.popupmenu.tooltip.droptable = \u5220\u6389\u8868 + +#Truncate Table pop-up menu for object browser +objectbrowser.popupmenu.id.truncatetable = org.opengauss.mppdbide.command.id.truncatetable +objectbrowser.popupmenu.label.truncatetable = \u622A\u65AD +objectbrowser.popupmenu.mnemonics.truncatetable = t +objectbrowser.popupmenu.tooltip.truncatetable = \u622A\u65AD + +#Reindex Table pop-up menu for object browser +objectbrowser.popupmenu.id.reindextable = org.opengauss.mppdbide.command.id.reindextable +objectbrowser.popupmenu.label.reindextable = \u91CD\u5EFA\u7D22\u5F15 +objectbrowser.popupmenu.mnemonics.reindextable = i +objectbrowser.popupmenu.tooltip.reindextable = \u91CD\u65B0\u7D22\u5F15\u8868\u7684\u6240\u6709\u6307\u6807\u5305\u62EC\u8D85\u5927\u7D22\u5F15 + +#Analyze Table popup menu for object browser +objectbrowser.popupmenu.id.analyzetable = org.opengauss.mppdbide.command.id.analyzetable +objectbrowser.popupmenu.label.analyzetable = \u5206\u6790 +objectbrowser.popupmenu.mnemonics.analyzetable = a +objectbrowser.popupmenu.tooltip.analyzetable = \u5206\u6790 + +#Vacuum Table pop-up menu for object browser +objectbrowser.popupmenu.id.vacuumtable = org.opengauss.mppdbide.command.id.vacuumtable +objectbrowser.popupmenu.label.vacuumtable = \u6E05\u7406 +objectbrowser.popupmenu.mnemonics.vacuumtable = v +objectbrowser.popupmenu.tooltip.vacuumtable = \u6E05\u7406 + +#Set table description pop-up menu for object browser +objectbrowser.popupmenu.id.settabledescription = org.opengauss.mppdbide.command.id.settabledescription +objectbrowser.popupmenu.label.settabledescription = \u8BBE\u7F6E\u8868\u63CF\u8FF0 +objectbrowser.popupmenu.mnemonics.settabledescription = D +objectbrowser.popupmenu.tooltip.settabledescription = \u8BBE\u7F6E\u63CF\u8FF0 + +#Set Tablespace pop-up menu for object browser +objectbrowser.popupmenu.id.settablespace = org.opengauss.mppdbide.command.id.settablespace +objectbrowser.popupmenu.label.settablespace = \u8BBE\u7F6E\u8868\u7A7A\u95F4 +objectbrowser.popupmenu.mnemonics.settablespace = s +objectbrowser.popupmenu.tooltip.settablespace = \u8BBE\u7F6E\u8868\u7A7A\u95F4 + +#Set Schema pop-up menu for object browser +objectbrowser.popupmenu.id.setschema = org.opengauss.mppdbide.command.id.setschema(\u8868\u7A7A\u95F4\u66F4\u6539\u4E3A\u6307\u5B9A\u8868\u7A7A\u95F4 +objectbrowser.popupmenu.label.setschema = \u8BBE\u7F6E\u8868\u6A21\u5F0F +objectbrowser.popupmenu.mnemonics.setschema = S +objectbrowser.popupmenu.tooltip.setschema = \u79FB\u52A8\u8868\u5230\u53E6\u4E00\u4E2A\u6A21\u5F0F + + +#Edit table properties pop-up menu for object browser +objectbrowser.popupmenu.id.editpropeties = org.opengauss.mppdbide.command.id.editpropeties +objectbrowser.popupmenu.label.editpropeties = \u7F16\u8F91\u8868\u5C5E\u6027 +objectbrowser.popupmenu.mnemonics.editpropeties = p +objectbrowser.popupmenu.tooltip.editpropeties = \u7F16\u8F91\u8868\u5C5E\u6027 + +#Edit Data Distribution pop-up menu for object browser +objectbrowser.popupmenu.id.changedatadistribution = org.opengauss.mppdbide.command.id.changedatadistribution +objectbrowser.popupmenu.label.changedatadistribution = \u7F16\u8F91\u6570\u636E\u5206\u914D +objectbrowser.popupmenu.mnemonics.changedatadistribution = b +objectbrowser.popupmenu.tooltip.changedatadistribution = \u5982\u4F55\u66F4\u6539\u8868\u80FD\u591F\u4F7F\u5206\u5E03\u6570\u636E\u8282\u70B9\u4E4B\u95F4\u590D\u5236 + +#Create Column pop-up menu for object browser +objectbrowser.popupmenu.id.createcolumn = org.opengauss.mppdbide.command.id.createcolumn +objectbrowser.popupmenu.label.createcolumn = \u6DFB\u52A0\u5217 +objectbrowser.popupmenu.mnemonics.createcolumn = c +objectbrowser.popupmenu.tooltip.createcolumn =\u6DFB\u52A0\u5217 + +#Drop Column pop-up menu for object browser +objectbrowser.popupmenu.id.dropcolumn = org.opengauss.mppdbide.command.id.dropcolumn +objectbrowser.popupmenu.label.dropcolumn = \u5220\u9664 +objectbrowser.popupmenu.mnemonics.dropcolumn = d +objectbrowser.popupmenu.tooltip.dropcolumn = \u5220\u9664\u5217 + +#Edit column properties pop-up menu for object browser +objectbrowser.popupmenu.id.editcolumnproperties = org.opengauss.mppdbide.command.id.editcolumnproperties +objectbrowser.popupmenu.label.editcolumnproperties = \u7F16\u8F91\u5217\u5C5E\u6027 +objectbrowser.popupmenu.mnemonics.editcolumnproperties = p +objectbrowser.popupmenu.tooltip.editcolumnproperties = \u66F4\u6539\u7F3A\u7701\u8868\u8FBE\u5F0F\uFF0C\u6570\u636E\u7C7B\u578B\uFF0C\u8BBE\u7F6E/\u5220\u9664\u4E0D\u4E3A\u7A7A\u5C5E\u6027 + +#Edit column properties pop-up menu for object browser +objectbrowser.popupmenu.id.renamecolumn = org.opengauss.mppdbide.command.id.renamecolumn +objectbrowser.popupmenu.label.renamecolumn = \u91CD\u547D\u540D +objectbrowser.popupmenu.mnemonics.renamecolumn = r +objectbrowser.popupmenu.tooltip.renamecolumn = \u91CD\u547D\u540D + +#Create Constraint pop-up menu for object browser +objectbrowser.popupmenu.id.createconstraint = org.opengauss.mppdbide.command.id.createconstraint +objectbrowser.popupmenu.label.createconstraint = \u6DFB\u52A0\u7EA6\u675F +objectbrowser.popupmenu.mnemonics.createconstraint = c +objectbrowser.popupmenu.tooltip.createconstraint = \u521B\u5EFA\u65B0\u7684\u7EA6\u675F + +#Rename Constraint pop-up menu for object browser +objectbrowser.popupmenu.id.renameconstraint = org.opengauss.mppdbide.command.id.renameconstraint +objectbrowser.popupmenu.label.renameconstraint = \u91CD\u547D\u540D +objectbrowser.popupmenu.mnemonics.renameconstraint = r +objectbrowser.popupmenu.tooltip.renameconstraint = \u66F4\u6539\u7EA6\u675F\u540D + +#Validate Constraint pop-up menu for object browser +objectbrowser.popupmenu.id.validateconstraint = org.opengauss.mppdbide.command.id.validateconstraint +objectbrowser.popupmenu.label.validateconstraint = \u9A8C\u8BC1 +objectbrowser.popupmenu.mnemonics.validateconstraint = v +objectbrowser.popupmenu.tooltip.validateconstraint = \u9A8C\u8BC1\u7EA6\u675F + +#Drop Constraint pop-up menu for object browser +objectbrowser.popupmenu.id.dropconstraint = org.opengauss.mppdbide.command.id.dropconstraint +objectbrowser.popupmenu.label.dropconstraint =\u5220\u9664 +objectbrowser.popupmenu.mnemonics.dropconstraint = d +objectbrowser.popupmenu.tooltip.dropconstraint = \u5220\u9664 + +#Edit Constraint Properties pop-up menu for object browser +objectbrowser.popupmenu.id.editconstraint = org.opengauss.mppdbide.command.id.editconstraint +objectbrowser.popupmenu.label.editconstraint = \u7F16\u8F91\u7EA6\u675F +objectbrowser.popupmenu.mnemonics.editconstraint = p +objectbrowser.popupmenu.tooltip.editconstraint = \u7F16\u8F91\u7EA6\u675F +#Edit Constraint Properties pop-up menu for object browser +objectbrowser.popupmenu.id.createindex = org.opengauss.mppdbide.command.id.createindex +objectbrowser.popupmenu.label.createindex = \u521B\u5EFA\u7D22\u5F15 +objectbrowser.popupmenu.mnemonics.createindex = i +objectbrowser.popupmenu.tooltip.createindex = \u521B\u5EFA\u7D22\u5F15 + +#Export table data pop-up menu for object browser +objectbrowser.popupmenu.id.exporttabledata = org.opengauss.mppdbide.command.id.exporttabledata +objectbrowser.popupmenu.label.exporttabledata = \u5BFC\u51FA\u8868\u6570\u636E +objectbrowser.popupmenu.mnemonics.exporttabledata = X +objectbrowser.popupmenu.tooltip.exporttabledata = \u5BFC\u51FA\u8868\u6570\u636E + +#Import table data pop-up menu for object browser +objectbrowser.popupmenu.id.importtabledata = org.opengauss.mppdbide.command.id.importtabledata +objectbrowser.popupmenu.label.importtabledata = \u5BFC\u5165\u8868\u6570\u636E +objectbrowser.popupmenu.mnemonics.importtabledata = I +objectbrowser.popupmenu.tooltip.importtabledata = \u5BFC\u5165\u8868\u6570\u636E + +#View table data pop-up menu for object browser +objectbrowser.popupmenu.id.viewtabledata = org.opengauss.mppdbide.command.id.viewtabledata +objectbrowser.popupmenu.label.viewtabledata = \u67E5\u770B\u6570\u636E +objectbrowser.popupmenu.mnemonics.viewtabledata = W +objectbrowser.popupmenu.tooltip.viewtabledata = \u67E5\u770B\u8868\u6570\u636E + +#Show Related Sequence pop-up menu for object browser +objectbrowser.popupmenu.id.showRelatedSequence = org.opengauss.mppdbide.command.id.showRelatedSequence +objectbrowser.popupmenu.label.showRelatedSequence = \u67E5\u8BE2\u76F8\u5173\u5E8F\u5217 +objectbrowser.popupmenu.mnemonics.showRelatedSequence = S +objectbrowser.popupmenu.tooltip.showRelatedSequence = \u67E5\u8BE2\u76F8\u5173\u5E8F\u5217 + +#Drop index pop-up menu for object browser +objectbrowser.popupmenu.id.dropindex = org.opengauss.mppdbide.command.id.dropindex +objectbrowser.popupmenu.label.dropindex = \u5220\u9664 +objectbrowser.popupmenu.mnemonics.dropindex = I +objectbrowser.popupmenu.tooltip.dropindex = \u5220\u9664\u7D22\u5F15 + +#Rename index pop-up menu for object browser +objectbrowser.popupmenu.id.renameindex = org.opengauss.mppdbide.command.id.renameindex +objectbrowser.popupmenu.label.renameindex = \u91CD\u547D\u540D +objectbrowser.popupmenu.mnemonics.renameindex = r +objectbrowser.popupmenu.tooltip.renameindex = \u91CD\u547D\u540D\u7D22\u5F15 + +#Change index tablespace pop-up menu for object browser +objectbrowser.popupmenu.id.changeindextablespace = org.opengauss.mppdbide.command.id.changeindextablespace +objectbrowser.popupmenu.label.changeindextablespace =\u66F4\u6539\u8868\u7A7A\u95F4 +objectbrowser.popupmenu.mnemonics.changeindextablespace = t +objectbrowser.popupmenu.tooltip.changeindextablespace = \u66F4\u6539\u7D22\u5F15\u8868\u7A7A\u95F4 + +#Change index fill factor pop-up menu for object browser +objectbrowser.popupmenu.id.changeindexfillfactor = org.opengauss.mppdbide.command.id.changeindexfillfactor +objectbrowser.popupmenu.label.changeindexfillfactor = \u66F4\u6539\u586B\u5145\u56E0\u5B50 +objectbrowser.popupmenu.mnemonics.changeindexfillfactor = t +objectbrowser.popupmenu.tooltip.changeindexfillfactor = \u6539\u53D8\u7D22\u5F15\u586B\u5145\u56E0\u5B50 + +#Disconnect all dbs pop-up menu for object browser +objectbrowser.popupmenu.id.disconnectalldbs = org.opengauss.mppdbide.command.id.disconnectalldbs +objectbrowser.popupmenu.label.disconnectalldbs = \u65AD\u5F00\u6240\u6709\u8FDE\u63A5 +objectbrowser.popupmenu.mnemonics.disconnectalldbs = a +objectbrowser.popupmenu.tooltip.disconnectalldbs = \u65AD\u5F00\u670D\u52A1\u5668\u7684\u6240\u6709DBS + +#Remove server from list pop-up menu for object browser +objectbrowser.popupmenu.id.removeserver = org.opengauss.mppdbide.command.id.removeserver +objectbrowser.popupmenu.label.removeserver = \u5220\u9664\u8FDE\u63A5 +objectbrowser.popupmenu.mnemonics.removeserver = r +objectbrowser.popupmenu.tooltip.removeserver = \u4ECE\u89C6\u56FE\u4E2D\u5220\u9664\u8FDE\u63A5 + +#Column not null property pop-up menu for object browser +objectbrowser.popupmenu.id.columnnotnull = org.opengauss.mppdbide.command.id.columnnotnull +objectbrowser.popupmenu.label.columnnotnull = \u8F6C\u6362\u4E3A\u975E\u7A7A\u503C +objectbrowser.popupmenu.mnemonics.columnnotnull = u +objectbrowser.popupmenu.tooltip.columnnotnull = \u8F6C\u6362\u4E3A\u975E\u7A7A\u503C + +#Column default value property pop-up menu for object browser +objectbrowser.popupmenu.id.columndefaultvalue = org.opengauss.mppdbide.command.id.columndefaultvalue +objectbrowser.popupmenu.label.columndefaultvalue = \u8BBE\u7F6E\u5217\u7F3A\u7701\u503C +objectbrowser.popupmenu.mnemonics.columndefaultvalue = V +objectbrowser.popupmenu.tooltip.columndefaultvalue = \u8BBE\u7F6E\u5217\u7F3A\u7701\u503C + +#Column change data type property pop-up menu for object browser +objectbrowser.popupmenu.id.changedatatype = org.opengauss.mppdbide.command.id.changedatatype +objectbrowser.popupmenu.label.changedatatype = \u66F4\u6539\u6570\u636E\u7C7B\u578B +objectbrowser.popupmenu.mnemonics.changedatatype = T +objectbrowser.popupmenu.tooltip.changedatatype = \u66F4\u6539\u6570\u636E\u7C7B\u578B + +#Properties pop-up menu for object browser +objectbrowser.popupmenu.id.properties = org.opengauss.mppdbide.command.id.properties +objectbrowser.popupmenu.label.properties = \u5C5E\u6027 +objectbrowser.popupmenu.mnemonics.properties = p +objectbrowser.popupmenu.tooltip.properties = \u5C5E\u6027 + +#Create Tablespace pop-up menu for object browser +objectbrowser.popupmenu.id.createtablespace = org.opengauss.mppdbide.command.id.createtablespace +objectbrowser.popupmenu.label.createtablespace = \u521B\u5EFA\u8868\u7A7A\u95F4 +objectbrowser.popupmenu.mnemonics.createtablespace = C +objectbrowser.popupmenu.tooltip.createtablespace = \u521B\u5EFA\u8868\u7A7A\u95F4 + +#Rename Tablespace pop-up menu for object browser +objectbrowser.popupmenu.id.renametablespace = org.opengauss.mppdbide.command.id.renametablespace +objectbrowser.popupmenu.label.renametablespace = \u91CD\u547D\u540D +objectbrowser.popupmenu.mnemonics.renametablespace = R +objectbrowser.popupmenu.tooltip.renametablespace = \u91CD\u547D\u540D\u8868\u7A7A\u95F4 + +#Set Tablespace Option pop-up menu for object browser +objectbrowser.popupmenu.id.settablespaceoption = org.opengauss.mppdbide.command.id.settablespaceoption +objectbrowser.popupmenu.label.settablespaceoption = \u8BBE\u7F6E\u9009\u9879 +objectbrowser.popupmenu.mnemonics.settablespaceoption = S +objectbrowser.popupmenu.tooltip.settablespaceoption = \u8BBE\u7F6E\u8868\u7A7A\u95F4\u9009\u9879 + +#Set Tablespace Size pop-up menu for object browser +objectbrowser.popupmenu.id.settablespacesize = org.opengauss.mppdbide.command.id.settablespacesize +objectbrowser.popupmenu.label.settablespacesize = \u8BBE\u7F6E\u5927\u5C0F +objectbrowser.popupmenu.mnemonics.settablespacesize = S +objectbrowser.popupmenu.tooltip.settablespacesize = \u8BBE\u7F6E\u8868\u7A7A\u95F4\u5927\u5C0F + +#Drop Tablespace pop-up menu for object browser +objectbrowser.popupmenu.id.droptablespace = org.opengauss.mppdbide.command.id.droptablespace +objectbrowser.popupmenu.label.droptablespace = \u5220\u9664 +objectbrowser.popupmenu.mnemonics.droptablespace = D +objectbrowser.popupmenu.tooltip.droptablespace = \u5220\u9664\u8868\u7A7A\u95F4 + +#Show DDL Tablespace pop-up menu for object browser +objectbrowser.popupmenu.id.showddl = org.opengauss.mppdbide.command.id.showddl +objectbrowser.popupmenu.label.showddl = \u663E\u793ADDL +objectbrowser.popupmenu.mnemonics.showddl = S +objectbrowser.popupmenu.tooltip.showddl = \u663E\u793ADDL + +#Show DDL for table pop-up menu for object browser +objectbrowser.popupmenu.id.showddlfortable = org.opengauss.mppdbide.command.id.showddlfortable +objectbrowser.popupmenu.label.showddlfortable = \u663E\u793ADDL +objectbrowser.popupmenu.mnemonics.showddlfortable = S +objectbrowser.popupmenu.tooltip.showddlfortable = \u663E\u793ADDL + +#Edit table data pop_up menu for table +objectbrowser.popupmenu.id.edittablewizard = org.opengauss.mppdbide.command.id.edittablewizard +objectbrowser.popupmenu.label.edittablewizard = \u7F16\u8F91\u6570\u636E +objectbrowser.popupmenu.mnemonics.edittablewizard = E +objectbrowser.popupmenu.tooltip.edittablewizard = \u7F16\u8F91\u8868\u6570\u636E + +#Edit table data viewer toolbar menu for table +dataviewer.toolbar.id.edittablewizard = org.opengauss.mppdbide.view.handledtoolitem.add +dataviewer.toolbar.add.label.edittablewizard = \u63D2\u5165 +dataviewer.toolbar.add.mnemonics.edittablewizard = I +dataviewer.toolbar.add.tooltip.edittablewizard = \u63D2\u5165 + +dataviewer.toolbar.id.edittablewizard = org.opengauss.mppdbide.view.handledtoolitem.Delete +dataviewer.toolbar.delete.label.edittablewizard = \u5220\u9664 +dataviewer.toolbar.delete.mnemonics.edittablewizard = E +dataviewer.toolbar.delete.tooltip.edittablewizard = \u5220\u9664 + +dataviewer.toolbar.id.edittablewizard = org.opengauss.mppdbide.view.handledtoolitem.paste +dataviewer.toolbar.paste.label.edittablewizard = \u7C98\u8D34 +dataviewer.toolbar.paste.mnemonics.edittablewizard = E +dataviewer.toolbar.paste.tooltip.edittablewizard = \u7C98\u8D34 + +dataviewer.toolbar.id.edittablewizard = org.opengauss.mppdbide.view.handledtoolitem.post +dataviewer.toolbar.post.label.edittablewizard = \u53D1\u9001 +dataviewer.toolbar.post.mnemonics.edittablewizard = E +dataviewer.toolbar.post.tooltip.edittablewizard = \u53D1\u9001 + +dataviewer.toolbar.id.edittablewizard =org.opengauss.mppdbide.view.handledtoolitem.rollback +dataviewer.toolbar.rollback.label.edittablewizard=\u56DE\u6EDA +dataviewer.toolbar.rollback.tooltip.edittablewizard=\u56DE\u6EDA + +dataviewer.toolbar.id.edittablewizard =org.opengauss.mppdbide.view.handledtoolitem.Commitchanges +dataviewer.toolbar.commit.label.edittablewizard=\u63D0\u4EA4 +dataviewer.toolbar.commit.tooltip.edittablewizard=\u63D0\u4EA4 +#Progress Bar Window +progressview.id.showrprogress = org.opengauss.mppdbide.part.id.showrprogress +progressview.label.showrprogress = \u663E\u793A\u8FDB\u5EA6\u6761 +progressview.mnemonics.showrprogress = P +progressview.tooltip.showrprogress = \u663E\u793A\u8FDB\u5EA6\u6761 + +objectbrowser.popupmenu.id.createview = org.opengauss.mppdbide.command.id.createviewobject +objectbrowser.popupmenu.label.createview = \u521B\u5EFA\u89C6\u56FE +objectbrowser.popupmenu.mnemonics.createview = C +objectbrowser.popupmenu.tooltip.createview = \u521B\u5EFA\u65B0\u7684\u89C6\u56FE\u5BF9\u8C61 + +objectbrowser.popupmenu.id.dropview = org.opengauss.mppdbide.command.id.dropviewobject +objectbrowser.popupmenu.label.dropview = \u5220\u9664 +objectbrowser.popupmenu.mnemonics.dropview = D +objectbrowser.popupmenu.tooltip.dropview = \u5220\u9664\u89C6\u56FE\u5BF9\u8C61 + +objectbrowser.popupmenu.id.renameview = org.opengauss.mppdbide.command.id.renameviewobject +objectbrowser.popupmenu.label.renameview = \u91CD\u547D\u540D +objectbrowser.popupmenu.mnemonics.renameview = R +objectbrowser.popupmenu.tooltip.renameview = \u91CD\u547D\u540D\u89C6\u56FE\u5BF9\u8C61 + +objectbrowser.popupmenu.id.setviewschema = org.opengauss.mppdbide.command.id.setviewschema +objectbrowser.popupmenu.label.setviewschema = \u8BBE\u7F6E\u6A21\u5F0F +objectbrowser.popupmenu.mnemonics.setviewschema = S +objectbrowser.popupmenu.tooltip.setviewschema = \u7ED9\u89C6\u56FE\u5BF9\u8C61\u8BBE\u7F6E\u6A21\u5F0F + +objectbrowser.popupmenu.id.showviewddl = org.opengauss.mppdbide.command.id.setviewddl +objectbrowser.popupmenu.label.showviewddl = \u67E5\u770BDDL +objectbrowser.popupmenu.mnemonics.showviewddl = w +objectbrowser.popupmenu.tooltip.showviewddl = \u663E\u793A\u89C6\u56FE\u5B9A\u4E49 + +objectbrowser.popupmenu.id.viewcolumn.defaultvalue = org.opengauss.mppdbide.command.id.viewcolumn.defaultvalue +objectbrowser.popupmenu.label.viewcolumn.defaultvalue = \u8bbe\u7f6e\u89c6\u56fe\u5217\u7f3a\u7701\u503c +objectbrowser.popupmenu.mnemonics.viewcolumn.defaultvalue = D +objectbrowser.popupmenu.tooltip.viewcolumn.defaultvalue = \u8bbe\u7f6e\u89c6\u56fe\u5217\u7f3a\u7701\u503c + + +objectbrowser.popupmenu.id.exportddl = org.opengauss.mppdbide.command.id.exportddl +objectbrowser.popupmenu.label.exportddl = \u5BFC\u51FADDL +objectbrowser.popupmenu.mnemonics.exportddl = L +objectbrowser.popupmenu.tooltip.exportddl = \u5BFC\u51FA\u5B9A\u4E49 + +objectbrowser.popupmenu.id.exportddldata = org.opengauss.mppdbide.command.id.exportddldata +objectbrowser.popupmenu.label.exportddldata = \u5BFC\u51FADDL\u548C\u6570\u636E +objectbrowser.popupmenu.mnemonics.exportddldata = T +objectbrowser.popupmenu.tooltip.exportddldata = \u5BFC\u51FA\u5B9A\u4E49\u548C\u6570\u636E + +objectbrowser.popupmenu.id.batchexportddl = org.opengauss.mppdbide.view.id.batchexportddl +objectbrowser.popupmenu.label.batchexportddl = \u5BFC\u51FADDL +objectbrowser.popupmenu.mnemonics.batchexportddl = L +objectbrowser.popupmenu.tooltip.batchexportddl = \u5BFC\u51FA\u5B9A\u4E49 + +objectbrowser.popupmenu.id.batchexportddldata = org.opengauss.mppdbide.view.id.batchexportddldata +objectbrowser.popupmenu.label.batchexportddldata = \u5BFC\u51FADDL\u548C\u6570\u636E +objectbrowser.popupmenu.mnemonics.batchexportddldata = T +objectbrowser.popupmenu.tooltip.batchexportddldata = \u5BFC\u51FA\u5B9A\u4E49\u548C\u6570\u636E + +objectbrowser.popupmenu.id.dropviewcascade = org.opengauss.mppdbide.command.id.dropviewobjectcascade +objectbrowser.popupmenu.label.dropviewcascade = \u7EA7\u8054\u5220\u9664 +objectbrowser.popupmenu.mnemonics.dropviewcascade = C +objectbrowser.popupmenu.tooltip.dropviewcascade = \u6253\u5F00\u5220\u9664\u7EA7\u8054\u89C6\u56FE\u9009\u9879 + +#view filter +view.directtoolitem.id.viewfilter=org.opengauss.mppdbide.view.directtoolitem.id.viewfilter +view.directtoolitem.label.viewfilter=\u53D8\u91CF\u6570\u636E\u7B5B\u9009 +view.directtoolitem.mnemonics.viewfilter=V +view.directtoolitem.tooltip.viewfilter=\u53D8\u91CF\u6570\u636E\u7B5B\u9009 + +#edit table +dataviewer.toolbar.edit.id.edittablewizard=org.opengauss.mppdbide.view.handledtoolitem.id.editableflag +dataviewer.toolbar.edit.label.edittablewizard=\u7F16\u8F91\u8868 +dataviewer.toolbar.edit.mnemonics.edittablewizard=E +dataviewer.toolbar.edit.tooltip.edittablewizard=\u7F16\u8F91\u8868 + +#filter result window content +viewmenu.id.filterresultwindowcontent=org.opengauss.mppdbide.view.directtoolitem.id.resultfilter +viewmenu.label.filterresultwindowcontent=\u7ED3\u675F\u6570\u636E\u7B5B\u9009 +viewmenu.mnemonics.filterresultwindowcontent=F +viewmenu.tooltip.filterresultwindowcontent=\u7ED3\u675F\u6570\u636E\u7B5B\u9009 + +#console text menu +view.popupmenu.id.console =org.opengauss.mppdbide.view.popupmenu.id.console +view.popupmenu.label.console=\u63A7\u5236\u53F0\u53F3\u952E\u83DC\u5355 +view.popupmenu.mnemonics.console= C +view.popupmenu.tooltip.console=\u63A7\u5236\u53F0\u53F3\u952E\u83DC\u5355 + +#Change to Upper Case +editmenu.label.touppercase = \u5927\u5199(&E) +editmenu.tooltip.touppercase = \u5927\u5199 + +#Change to Lower Case +editmenu.label.tolowercase = \u5C0F\u5199(&L) +editmenu.tooltip.tolowercase = \u5C0F\u5199 + + +#Change to indent +editmenu.label.indent=\u7F29\u8FDB +editmenu.tooltip.indent=\u7F29\u8FDB + +#Change to unindent +editmenu.label.unindent=\u51CF\u5C11\u7F29\u8FDB +editmenu.tooltip.unindent=\u51CF\u5C11\u7F29\u8FDB + +#Go To Line +editmenu.label.gotoline = \u8F6C\u5230\u884C(&G) +editmenu.tooltip.gotoline = \u8F6C\u5230\u884C + +#Create Sequence pop-up menu for object browser +objectbrowser.popupmenu.id.createsequence = org.opengauss.mppdbide.command.id.createsequence +objectbrowser.popupmenu.label.createsequence = \u521B\u5EFA\u5E8F\u5217 +objectbrowser.popupmenu.mnemonics.createsequence = q +objectbrowser.popupmenu.tooltip.createsequence = \u521B\u5EFA\u5E8F\u5217 +#Sequence Drop +objectbrowser.popupmenu.id.dropsequence = org.opengauss.mppdbide.command.id.dropsequenceobject +objectbrowser.popupmenu.label.dropsequence = \u5220\u9664\u5E8F\u5217 +objectbrowser.popupmenu.mnemonics.dropsequence = D +objectbrowser.popupmenu.tooltip.dropsequence = \u5220\u9664\u5E8F\u5217\u5BF9\u8C61 +#show Table By Sequence +objectbrowser.popupmenu.id.showTableBySequence = org.opengauss.mppdbide.command.id.showTableBySequence +objectbrowser.popupmenu.label.showTableBySequence = \u67E5\u8BE2\u76F8\u5173\u8868 +objectbrowser.popupmenu.mnemonics.showTableBySequence = S +objectbrowser.popupmenu.tooltip.showTableBySequence = \u67E5\u8BE2\u76F8\u5173\u8868 +#Sequence Drop cascade +objectbrowser.popupmenu.id.dropsequence = org.opengauss.mppdbide.command.id.dropsequenceobjectcascade +objectbrowser.popupmenu.label.dropsequencecascade = \u7EA7\u8054\u5220\u9664\u5E8F\u5217 +objectbrowser.popupmenu.mnemonics.dropsequencecascade = D +objectbrowser.popupmenu.tooltip.dropsequencecascade = \u7EA7\u8054\u5220\u9664\u5E8F\u5217\u5BF9\u8C61 + +#DB Assistant +view.db.assistant.title=SQL\u52a9\u624b +view.db.assistant.open=\u6253\u5f00SQL\u52a9\u624b + +#Toggle Line Comment +editmenu.label.togglelinecomments = \u884C\u6CE8\u91CA/\u53D6\u6D88\u884C\u6CE8\u91CA(&N) +objectbrowser.popupmenu.mnemonics.togglelinecomments = N +editmenu.tooltip.togglelinecomments = \u884C\u6CE8\u91CA/\u53D6\u6D88\u884C\u6CE8\u91CA + +#Toggle Block Comment +editmenu.label.toggleblockcomments = \u5757\u6CE8\u91CA/\u53D6\u6D88\u5757\u6CE8\u91CA(&B) +objectbrowser.popupmenu.mnemonics.toggleblockcomments = B +editmenu.tooltip.toggleblockcomments = \u5757\u6CE8\u91CA/\u53D6\u6D88\u5757\u6CE8\u91CA +#User/Role Menu +objectbrowser.popupmenu.label.createrole = \u521b\u5efa\u7528\u6237\u002f\u89d2\u8272 +objectbrowser.popupmenu.tooltip.createrole = \u521b\u5efa\u7528\u6237\u002f\u89d2\u8272 + +objectbrowser.popupmenu.label.dropuserrole = \u5220\u9664\u7528\u6237\u002f\u89d2\u8272 +objectbrowser.popupmenu.tooltip.dropuserrole = \u5220\u9664\u7528\u6237\u002f\u89d2\u8272 + +#Grant/Revoke +objectbrowser.popupmenu.label.grantrevokewizard = \u6388\u6743/\u64A4\u9500\u6743\u9650 +objectbrowser.popupmenu.tooltip.grantrevokewizard = \u6388\u6743/\u64A4\u9500\u6743\u9650 + +#tablespace properties +objectbrowser.popupmenu.label.tablespaceproperties=\u5C5E\u6027 +objectbrowser.popupmenu.mnemonics.tablespaceproperties=P +objectbrowser.popupmenu.tooltip.tablespaceproperties=\u670D\u52A1\u5668\u5C5E\u6027 + +#Create C function popup menu for objectbrowser +objectbrowser.popupmenu.id.createcfunction= org.opengauss.objectbrowser.popupmenu.id.createcfunction +objectbrowser.popupmenu.label.createcfunction = \u521b\u5efa\u0043\u51fd\u6570 +objectbrowser.popupmenu.mnemonics.createcfunction = c +objectbrowser.popupmenu.tooltip.createcfunction = \u521b\u5efa\u0043\u51fd\u6570objectbrowser.popupmenu.tooltip.tablespaceproperties=\u670D\u52A1\u5668\u5C5E\u6027 + +#Save As Menu +editmenu.id.savesqlas = org.opengauss.editmenu.id.savesqlas +editmenu.label.savesqlas = \u53E6\u5B58\u4E3A +editmenu.mnemonics.savesqlas = S +editmenu.tooltip.savesqlas = \u53E6\u5B58\u4E3A + +#Show DDL of sequence +objectbrowser.popupmenu.id.showsequenceddl = org.opengauss.mppdbide.command.id.showsequenceddl +objectbrowser.popupmenu.label.showsequenceddl = \u663E\u793ADDL +objectbrowser.popupmenu.mnemonics.showsequenceddl = S +objectbrowser.popupmenu.tooltip.showsequenceddl = \u663E\u793ADDL + +#Edit Table data +objectbrowser.popupmenu.id.edittabledata = org.opengauss.mppdbide.command.id.edittabledata +objectbrowser.popupmenu.label.edittabledata = \u7F16\u8F91\u8868\u6570\u636E +objectbrowser.popupmenu.mnemonics.edittabledata = S +objectbrowser.popupmenu.tooltip.edittabledata = \u7F16\u8F91\u8868\u6570\u636E + +#Edit ERD pop-up menu for object browser +objectbrowser.popupmenu.id.viewerd = org.opengauss.mppdbide.command.id.viewerd +objectbrowser.popupmenu.label.viewerd = \u0045\u0052\u56fe +objectbrowser.popupmenu.mnemonics.viewerd = v +objectbrowser.popupmenu.tooltip.viewerd = \u67e5\u770b\u0045\u0052\u56fe + +#Create Synonym +org.opengauss.objectbrowser.popupmenu.id.createsynonym =org.opengauss.objectbrowser.popupmenu.id.createsynonym +objectbrowser.popupmenu.label.createsynonym = \u521B\u5EFA\u540C\u4E49\u8BCD +objectbrowser.popupmenu.tooltip.createsynonym = \u521B\u5EFA\u540C\u4E49\u8BCD +objectbrowser.popupmenu.mnemonics.createsynonym = P + +#Dop Synonym +org.opengauss.objectbrowser.popupmenu.id.dropsynonym =org.opengauss.objectbrowser.popupmenu.id.dropsynonym +objectbrowser.popupmenu.label.dropsynonym = \u5220\u9664\u540C\u4E49\u8BCD +objectbrowser.popupmenu.tooltip.dropsynonym = \u5220\u9664\u540C\u4E49\u8BCD +objectbrowser.popupmenu.mnemonics.dropsynonym = D + +#Start Debugging +org.opengauss.objectbrowser.popupmenu.id.startdebug = org.opengauss.objectbrowser.popupmenu.id.startdebug +objectbrowser.popupmenu.label.startdebug = \u542f\u52a8\u8c03\u8bd5 +objectbrowser.popupmenu.tooltip.startdebug = \u542f\u52a8\u8c03\u8bd5 +objectbrowser.popupmenu.mnemonics.startdebug = S + +#Trigger Create +org.opengauss.objectbrowser.popupmenu.id.triggergroup.create = org.opengauss.objectbrowser.popupmenu.id.triggergroup.create +objectbrowser.popupmenu.label.triggergroup.create = \u521b\u5efa\u89e6\u53d1\u5668 +objectbrowser.popupmenu.mnemonics.triggergroup.create = c +objectbrowser.popupmenu.tooltip.triggergroup.create = \u521b\u5efa\u89e6\u53d1\u5668 +#Trigger Drop +org.opengauss.objectbrowser.popupmenu.id.trigger.drop = org.opengauss.objectbrowser.popupmenu.id.trigger.drop +objectbrowser.popupmenu.label.trigger.drop = \u5220\u9664\u89e6\u53d1\u5668 +objectbrowser.popupmenu.mnemonics.trigger.drop = d +objectbrowser.popupmenu.tooltip.trigger.drop = \u5220\u9664\u89e6\u53d1\u5668 +#Trigger Edit +org.opengauss.objectbrowser.popupmenu.id.trigger.edit = org.opengauss.objectbrowser.popupmenu.id.trigger.edit +objectbrowser.popupmenu.label.trigger.edit = \u7F16\u8F91\u89E6\u53D1\u5668 +objectbrowser.popupmenu.mnemonics.trigger.edit = i +objectbrowser.popupmenu.tooltip.trigger.edit = \u7F16\u8F91\u89E6\u53D1\u5668 +#Trigger Enable +org.opengauss.objectbrowser.popupmenu.id.trigger.enable = org.opengauss.objectbrowser.popupmenu.id.trigger.enable +objectbrowser.popupmenu.label.trigger.enable = \u542f\u7528\u89e6\u53d1\u5668 +objectbrowser.popupmenu.mnemonics.trigger.enable = e +objectbrowser.popupmenu.tooltip.trigger.enable = \u542f\u7528\u89e6\u53d1\u5668 +#Trigger Disable +org.opengauss.objectbrowser.popupmenu.id.trigger.disable = org.opengauss.objectbrowser.popupmenu.id.trigger.disable +objectbrowser.popupmenu.label.trigger.disable = \u7981\u7528\u89e6\u53d1\u5668 +objectbrowser.popupmenu.mnemonics.trigger.disable = i +objectbrowser.popupmenu.tooltip.trigger.disable = \u7981\u7528\u89e6\u53d1\u5668 +#Trigger Rename +org.opengauss.objectbrowser.popupmenu.id.trigger.rename = org.opengauss.objectbrowser.popupmenu.id.trigger.rename +objectbrowser.popupmenu.label.trigger.rename = \u91cd\u547d\u540d +objectbrowser.popupmenu.mnemonics.trigger.rename = r +objectbrowser.popupmenu.tooltip.trigger.rename = \u91cd\u547d\u540d +#Edit View +org.opengauss.objectbrowser.popupmenu.id.view.editview = org.opengauss.objectbrowser.popupmenu.id.view.editview +objectbrowser.popupmenu.label.editview = \u7f16\u8f91\u89c6\u56fe +objectbrowser.popupmenu.mnemonics.editview = e +objectbrowser.popupmenu.tooltip.editview = \u7f16\u8f91\u89c6\u56fe \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/build.properties b/code/datastudio/src/org.opengauss.mppdbide.view/build.properties new file mode 100644 index 0000000000000000000000000000000000000000..ecda4b3d6d20bf14b470722a2cf1f95c23346d62 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/build.properties @@ -0,0 +1,12 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + plugin.xml,\ + OSGI-INF/,\ + Application.e4xmi,\ + icons/,\ + build.properties,\ + gson-2.8.6.jar,\ + guava-30.1.1-jre.jar + diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/compile_plsqlide.view.xml b/code/datastudio/src/org.opengauss.mppdbide.view/compile_plsqlide.view.xml new file mode 100644 index 0000000000000000000000000000000000000000..ff4f79238ff91f80931241808cba7ea27ceb734a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/compile_plsqlide.view.xml @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/css/plsqlide_style.css b/code/datastudio/src/org.opengauss.mppdbide.view/css/plsqlide_style.css new file mode 100644 index 0000000000000000000000000000000000000000..93aebda723eb3156122f7c35b98677dabddc259a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/css/plsqlide_style.css @@ -0,0 +1,29 @@ +Label { + font: Verdana 8px; + color: black; +} +Composite Label { + color: black; +} +Text { + font: Verdana 8px; +} +/* Identifies only those SWT Text elements +appearing within a Composite */ +Composite Text { + background-color: white; + color: black; +} +SashForm { + background-color: #c1d5ef; +} +/* background uses a gradient */ +.MTrimBar Button { + background-color: #e3efff #c1d5ef; + color: white; + font: Verdana 8px; +} + +Shell { + background-color: #e3efff #c1d5ef 60%; +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/About-Data-Studio-Header-EN-US.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/About-Data-Studio-Header-EN-US.png new file mode 100644 index 0000000000000000000000000000000000000000..59c56f69395de4acf374e7e8b7756c3b52d1ed6a Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/About-Data-Studio-Header-EN-US.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Add_Records.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Add_Records.png new file mode 100644 index 0000000000000000000000000000000000000000..054a8fcefd72f54e9fee58ca13066c8074b381da Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Add_Records.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/CaseInsensitive.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/CaseInsensitive.png new file mode 100644 index 0000000000000000000000000000000000000000..4c56775dc9b1016ac997dd6c8ee4b5bd78169c61 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/CaseInsensitive.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Commit_Records.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Commit_Records.png new file mode 100644 index 0000000000000000000000000000000000000000..babdacd367dbb8b676531f9bde8e31b5999d889b Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Commit_Records.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Compile.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Compile.png new file mode 100644 index 0000000000000000000000000000000000000000..2ff1a3c59d7cc53544800a3be8d238e99f82359d Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Compile.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Delete.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Delete.png new file mode 100644 index 0000000000000000000000000000000000000000..734717134d645e765645ea29928874a69c371e10 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Delete.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Delete_Records.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Delete_Records.png new file mode 100644 index 0000000000000000000000000000000000000000..812ede37811599632fdbe4ca2c20ba0cdd957f94 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Delete_Records.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Disable.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Disable.png new file mode 100644 index 0000000000000000000000000000000000000000..73e5d8344fe606c9816908470f3356145ad18f55 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Disable.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Enable.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Enable.png new file mode 100644 index 0000000000000000000000000000000000000000..fa6162611a5599d7676a1eae68b95d7ecc608c03 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Enable.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Export-CSV-Star.jpg b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Export-CSV-Star.jpg new file mode 100644 index 0000000000000000000000000000000000000000..174cbbf81084fdc450e3cd38144707832256c3ad Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Export-CSV-Star.jpg differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/ExportAllData.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/ExportAllData.png new file mode 100644 index 0000000000000000000000000000000000000000..4af41080f2b9174a3451654843b6da9f2cdabc87 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/ExportAllData.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/ExportCurrentPage.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/ExportCurrentPage.png new file mode 100644 index 0000000000000000000000000000000000000000..973d23a1fa3c3ca64c0e9b0e1d441e4931a7f1b4 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/ExportCurrentPage.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/ForeignTable.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/ForeignTable.png new file mode 100644 index 0000000000000000000000000000000000000000..cbaa29ed6db9d2078188fc9b2b95adeff4f433cf Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/ForeignTable.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/ForeignTableGroup.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/ForeignTableGroup.png new file mode 100644 index 0000000000000000000000000000000000000000..fa755f5417b3f7b6e61b530f8b0a3effab6b9c05 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/ForeignTableGroup.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Function_folder.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Function_folder.png new file mode 100644 index 0000000000000000000000000000000000000000..83c457e1529ab35910d6f6024de4efd251eb48d3 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Function_folder.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/HDFSTable.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/HDFSTable.png new file mode 100644 index 0000000000000000000000000000000000000000..1405c145bae43a020ac42ff996514cb04b523a14 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/HDFSTable.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Help.jpg b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Help.jpg new file mode 100644 index 0000000000000000000000000000000000000000..257a1c3c9f5c91e18451b4aa28d3bd7de3712b20 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Help.jpg differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Icon_TableExport.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Icon_TableExport.png new file mode 100644 index 0000000000000000000000000000000000000000..0a4b7170725d0606715f78fd04a2902c263f3c60 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Icon_TableExport.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Icon_TableImport.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Icon_TableImport.png new file mode 100644 index 0000000000000000000000000000000000000000..25e41acbe7a26ea1461cd120db0f52be59772e5d Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Icon_TableImport.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Left_IndentNew.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Left_IndentNew.png new file mode 100644 index 0000000000000000000000000000000000000000..35c49c8e4b924df81a5ce4d545e82f32df5176ae Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Left_IndentNew.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Load-Query-to-SQL-&-close.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Load-Query-to-SQL-&-close.png new file mode 100644 index 0000000000000000000000000000000000000000..e7fa358482e7f02f1e81388a5bc4918b7ba992db Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Load-Query-to-SQL-&-close.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Load-Query-to-SQL.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Load-Query-to-SQL.png new file mode 100644 index 0000000000000000000000000000000000000000..5185bd2d44aaaf9dae6b34525d595ee26e592d4a Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Load-Query-to-SQL.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/LowerCase.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/LowerCase.png new file mode 100644 index 0000000000000000000000000000000000000000..43aab0454b763e151f34b7d18474637c1a95ade2 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/LowerCase.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/PartitionTable.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/PartitionTable.png new file mode 100644 index 0000000000000000000000000000000000000000..f8515b1f96b344cd1154a6fd8f66d75d212b7a75 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/PartitionTable.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/PartitionTableGroup.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/PartitionTableGroup.png new file mode 100644 index 0000000000000000000000000000000000000000..627d569da4a49ece8311800cbe9182fbe4546625 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/PartitionTableGroup.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Pin-SQL-green.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Pin-SQL-green.png new file mode 100644 index 0000000000000000000000000000000000000000..8692489cad31bbb273a5be398be2206a55758be5 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Pin-SQL-green.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Pin-SQL.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Pin-SQL.png new file mode 100644 index 0000000000000000000000000000000000000000..34b717d4d425a7e3fd2131b27891e2fce2047842 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Pin-SQL.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Right_IndentNew.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Right_IndentNew.png new file mode 100644 index 0000000000000000000000000000000000000000..7d1e44636c66428db423bb01b7f0d90cc461e031 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Right_IndentNew.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Rollback_Changes.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Rollback_Changes.png new file mode 100644 index 0000000000000000000000000000000000000000..c632fd24e2f97cfa86227fc81f347d7b1f38c40c Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Rollback_Changes.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/SQL-history.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/SQL-history.png new file mode 100644 index 0000000000000000000000000000000000000000..3c02082012192d6108f2c23e2c2be8ce64bd14cd Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/SQL-history.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/SQL-history1.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/SQL-history1.png new file mode 100644 index 0000000000000000000000000000000000000000..a6a46a3013e261225fafb6b519bba43e865dcf14 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/SQL-history1.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/SequenceGroup.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/SequenceGroup.png new file mode 100644 index 0000000000000000000000000000000000000000..ce152f3415c68eeb95a8a2b8507a137ce9f80a96 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/SequenceGroup.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Table.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Table.png new file mode 100644 index 0000000000000000000000000000000000000000..8a9eca6875fdbe2a400ac570338f5c134ddc075b Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Table.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Table_Space-folder.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Table_Space-folder.png new file mode 100644 index 0000000000000000000000000000000000000000..5a94eea8b55b54417b835da66e5b212ba1e36b84 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Table_Space-folder.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Table_Space1.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Table_Space1.png new file mode 100644 index 0000000000000000000000000000000000000000..cbd170f8cbbfedf2e1b927c09eef249a4d5b7ee3 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Table_Space1.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Tables.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Tables.png new file mode 100644 index 0000000000000000000000000000000000000000..3b3dca7e2d357f48e55137c7e4bd8c57efd49a6b Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Tables.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/ToolIcons/128x128.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/ToolIcons/128x128.png new file mode 100644 index 0000000000000000000000000000000000000000..973a86c9176f20ff31abbb9e3b2f4d6b49d22ea3 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/ToolIcons/128x128.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/ToolIcons/32x32(32).png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/ToolIcons/32x32(32).png new file mode 100644 index 0000000000000000000000000000000000000000..c3010367acf5294f68c1e97ba44074374a7c9566 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/ToolIcons/32x32(32).png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/ToolIcons/64x64.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/ToolIcons/64x64.png new file mode 100644 index 0000000000000000000000000000000000000000..ccdfdadc5bbe63a71af3a0dce8a34e32633741c5 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/ToolIcons/64x64.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/Trigger_folder.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Trigger_folder.png new file mode 100644 index 0000000000000000000000000000000000000000..4752740472a284f27959efcb7dc1e0179980bde2 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/Trigger_folder.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/UnPin-SQL.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/UnPin-SQL.png new file mode 100644 index 0000000000000000000000000000000000000000..34b717d4d425a7e3fd2131b27891e2fce2047842 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/UnPin-SQL.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/UpperCase.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/UpperCase.png new file mode 100644 index 0000000000000000000000000000000000000000..2697b6c95d9299f43b16a509f72b0cc3c8cf247f Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/UpperCase.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/View-group.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/View-group.png new file mode 100644 index 0000000000000000000000000000000000000000..b1c0c9599f8ac9052a74f3f6fa7f2527bb0808b8 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/View-group.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/View1.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/View1.png new file mode 100644 index 0000000000000000000000000000000000000000..483615c58f8adbca5cf9c579380540b1b33e2d6a Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/View1.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/accept_database.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/accept_database.png new file mode 100644 index 0000000000000000000000000000000000000000..de57414e4562a7d0f968d3cf174a1e56f8f9971f Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/accept_database.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/add-row.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/add-row.png new file mode 100644 index 0000000000000000000000000000000000000000..d452b96a99eb302fb03df363fc14bd108cc9f3bc Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/add-row.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/add_run_terminal.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/add_run_terminal.png new file mode 100644 index 0000000000000000000000000000000000000000..dfaa4240793957692c16e8b15daf698e4c999d0e Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/add_run_terminal.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/autocommitoff.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/autocommitoff.png new file mode 100644 index 0000000000000000000000000000000000000000..4a7aa77cf8310718e9df910e1baad1cf355ee850 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/autocommitoff.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/autocommiton.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/autocommiton.png new file mode 100644 index 0000000000000000000000000000000000000000..6b91b79a4672c948e0313dd74129241ff4347e74 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/autocommiton.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/boolean.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/boolean.png new file mode 100644 index 0000000000000000000000000000000000000000..3ce9a7927b7472dd191fd6976249bb8570fcf5e6 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/boolean.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/checked.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/checked.png new file mode 100644 index 0000000000000000000000000000000000000000..2ad611b27221611b3a724f62426d729034b39cb8 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/checked.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/clear_sort.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/clear_sort.png new file mode 100644 index 0000000000000000000000000000000000000000..7cdb7ad62793bccac272c90949721c3eeb9ae4a3 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/clear_sort.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/closeQuery.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/closeQuery.png new file mode 100644 index 0000000000000000000000000000000000000000..61425f503ccace3cdb4ce697f0d797e0ad875339 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/closeQuery.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/cloud_node.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/cloud_node.png new file mode 100644 index 0000000000000000000000000000000000000000..c9a5ccb184344de24664ca65b7087cd7e56c1947 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/cloud_node.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/cloud_node_.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/cloud_node_.png new file mode 100644 index 0000000000000000000000000000000000000000..c9a5ccb184344de24664ca65b7087cd7e56c1947 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/cloud_node_.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/cloud_nodes.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/cloud_nodes.png new file mode 100644 index 0000000000000000000000000000000000000000..9cf515d215ce4c8cbcb257bffd25d8a1870106b9 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/cloud_nodes.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/commit.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/commit.png new file mode 100644 index 0000000000000000000000000000000000000000..20cad4033150db510cdd5b58077a39a2ee6db8df Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/commit.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/connected.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/connected.png new file mode 100644 index 0000000000000000000000000000000000000000..bd4cdc0705ac4b1b8ae0e8ba506ef8fc8dbeb266 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/connected.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/data-type.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/data-type.png new file mode 100644 index 0000000000000000000000000000000000000000..0d9940bb7f9307e98fbe5b6e862de6cd8e099582 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/data-type.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/database_group.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/database_group.png new file mode 100644 index 0000000000000000000000000000000000000000..3306755e59c66483f5d579c430a8a910a01b88d3 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/database_group.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/datetime.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/datetime.png new file mode 100644 index 0000000000000000000000000000000000000000..ba92c8e27d3668ad78f93c6b0f21e3293eefbcf5 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/datetime.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/db_assistant16x16.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/db_assistant16x16.png new file mode 100644 index 0000000000000000000000000000000000000000..61bfffdc33ffafa8ab016e918ecfe7dddff3dbf1 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/db_assistant16x16.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/breakpoint_indicate.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/breakpoint_indicate.png new file mode 100644 index 0000000000000000000000000000000000000000..bf1501cf404360d9719e0a90cd2b3dd9c48efe46 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/breakpoint_indicate.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/debug.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/debug.png new file mode 100644 index 0000000000000000000000000000000000000000..3fd4820477b7584b6f6a96954705e1cdc7f9aed3 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/debug.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/debugarrows.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/debugarrows.png new file mode 100644 index 0000000000000000000000000000000000000000..e06775f0297de6f6717264c6d51365033169406b Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/debugarrows.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/icon_breakpoint-delete.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/icon_breakpoint-delete.png new file mode 100644 index 0000000000000000000000000000000000000000..d30c2ef695685838c9f11602e3ef6c4e415c9502 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/icon_breakpoint-delete.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/icon_breakpoint-delete_all.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/icon_breakpoint-delete_all.png new file mode 100644 index 0000000000000000000000000000000000000000..e540cc34d4f59e424a083dd6e1ba0c2487bd64cc Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/icon_breakpoint-delete_all.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/icon_breakpoint-disabled.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/icon_breakpoint-disabled.png new file mode 100644 index 0000000000000000000000000000000000000000..fdfaa58f0048b60cb1566c7a56ddf74a6ab7de5f Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/icon_breakpoint-disabled.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/icon_breakpoint-enabled.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/icon_breakpoint-enabled.png new file mode 100644 index 0000000000000000000000000000000000000000..c147eb7450785aa6e17d14890bf06b9173b9f491 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/icon_breakpoint-enabled.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/resume.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/resume.png new file mode 100644 index 0000000000000000000000000000000000000000..6fe1e3d14be544cf80998ff347b36c3c1d5abcd6 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/resume.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/step-in.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/step-in.png new file mode 100644 index 0000000000000000000000000000000000000000..689364861aee76ebfbb37a5020e410a97e5080e6 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/step-in.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/step-out.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/step-out.png new file mode 100644 index 0000000000000000000000000000000000000000..3e7aa61dd6d408974e6c380059e2a2512d2802b1 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/step-out.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/step-over.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/step-over.png new file mode 100644 index 0000000000000000000000000000000000000000..b3624724503776ea146456739297b911d7848463 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/step-over.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/terminateExecution.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/terminateExecution.png new file mode 100644 index 0000000000000000000000000000000000000000..79ea170b2b306f65436b29ed296c63484934fb3b Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/debug/terminateExecution.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/delete-all-history-item.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/delete-all-history-item.png new file mode 100644 index 0000000000000000000000000000000000000000..3676e7325becdc808df119436079738091cee8cb Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/delete-all-history-item.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/delete-selected-history-item.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/delete-selected-history-item.png new file mode 100644 index 0000000000000000000000000000000000000000..710943bf38b523d5b43cc7e63035c27ee97e0aac Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/delete-selected-history-item.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/delete_row.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/delete_row.png new file mode 100644 index 0000000000000000000000000000000000000000..545d9fffc97904b755f90519c09e29b489284eab Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/delete_row.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/dsgrid_selectall_corner_dark.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/dsgrid_selectall_corner_dark.png new file mode 100644 index 0000000000000000000000000000000000000000..0de36fa4510b25964c18b7d2d668b2f9b4eb0554 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/dsgrid_selectall_corner_dark.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/edit-partition-table.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/edit-partition-table.png new file mode 100644 index 0000000000000000000000000000000000000000..05563cfdcb8b690a05d6f43f94cea00d763f917f Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/edit-partition-table.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/edit-table.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/edit-table.png new file mode 100644 index 0000000000000000000000000000000000000000..ac576f41b31a89cb370b06c7de82ec73e7f48da8 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/edit-table.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/edit.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/edit.png new file mode 100644 index 0000000000000000000000000000000000000000..ad41c84b3d7e13bfad5d7662947f36999dd315a9 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/edit.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/er_current_color.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/er_current_color.png new file mode 100644 index 0000000000000000000000000000000000000000..bfe7c1a2f406bfc69b71b3fa69a0b8f6ec40f73a Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/er_current_color.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/er_foreign_key.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/er_foreign_key.png new file mode 100644 index 0000000000000000000000000000000000000000..2e58af8f1168010ed9fadf0fbf99bc9f862fbd4a Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/er_foreign_key.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/er_primary_key.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/er_primary_key.png new file mode 100644 index 0000000000000000000000000000000000000000..f58c1e975b7402dafa0b19fb1de48b898d5bfe71 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/er_primary_key.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/er_related_color.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/er_related_color.png new file mode 100644 index 0000000000000000000000000000000000000000..b8de30e02cb52814307f70d5d4cd6ccd1052b4c0 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/er_related_color.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/execution-plan.02.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/execution-plan.02.png new file mode 100644 index 0000000000000000000000000000000000000000..65c537cd12748d720a9aaa4fa9eb7d2ee0704659 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/execution-plan.02.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/exportconnection.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/exportconnection.png new file mode 100644 index 0000000000000000000000000000000000000000..5e0f5dbd49e4b56185b374af8ceaad6724a6a494 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/exportconnection.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/filter.bmp b/code/datastudio/src/org.opengauss.mppdbide.view/icons/filter.bmp new file mode 100644 index 0000000000000000000000000000000000000000..a63e74152c6d5c295cb3daf7887b0cc7598d1fa0 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/filter.bmp differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/find.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/find.png new file mode 100644 index 0000000000000000000000000000000000000000..92fd9bd37d4fa7e152d5cc30080bac0010ccd445 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/find.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/find_replace.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/find_replace.png new file mode 100644 index 0000000000000000000000000000000000000000..5eee68b5e91dec20f39bd292958f4df8aedca262 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/find_replace.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/format.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/format.png new file mode 100644 index 0000000000000000000000000000000000000000..ba3fbcb74640a66590b16fa307a737c33847be3f Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/format.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/function.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/function.png new file mode 100644 index 0000000000000000000000000000000000000000..67dbbdb3ce94d1f5c186be42218aa70b066044a1 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/function.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionC.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionC.png new file mode 100644 index 0000000000000000000000000000000000000000..f9d5f77334458b9001bfaf3abb84fda59110a4bc Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionC.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionC_Disconnected.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionC_Disconnected.png new file mode 100644 index 0000000000000000000000000000000000000000..1519b06e9c9e7053c27fe583362e794b4ee7292e Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionC_Disconnected.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionPLSQL.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionPLSQL.png new file mode 100644 index 0000000000000000000000000000000000000000..609964075446b3a1122781aa8f0dd1ed91c9a328 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionPLSQL.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionPLSQL_Disconnected.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionPLSQL_Disconnected.png new file mode 100644 index 0000000000000000000000000000000000000000..7e96a488c8fd2e01726569942549b27acdb12fab Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionPLSQL_Disconnected.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionPLSQL_invalid.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionPLSQL_invalid.png new file mode 100644 index 0000000000000000000000000000000000000000..526d0321716ad92f0b47d2ea9988ecdc292f9ec7 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionPLSQL_invalid.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionSQL.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionSQL.png new file mode 100644 index 0000000000000000000000000000000000000000..72b7f5a8903531d219da3ee219fb0b4b865282e3 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionSQL.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionSQL_Disconnected.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionSQL_Disconnected.png new file mode 100644 index 0000000000000000000000000000000000000000..ff3280dacee9ed806c0f69910e50f8362cec43bb Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionSQL_Disconnected.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionSQL_invalid.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionSQL_invalid.png new file mode 100644 index 0000000000000000000000000000000000000000..64afcbf20285981dd95ef25b319c4c7fb9389811 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/functionSQL_invalid.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/function_invalid.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/function_invalid.png new file mode 100644 index 0000000000000000000000000000000000000000..999f11e36e98d2ec31c66d469208d8d8cfe6997f Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/function_invalid.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/hdfs_foreign_partition_table.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/hdfs_foreign_partition_table.png new file mode 100644 index 0000000000000000000000000000000000000000..1215d0b4aee14f8fa208295293c9fd6471ea33d4 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/hdfs_foreign_partition_table.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/ico-mandatory.jpg b/code/datastudio/src/org.opengauss.mppdbide.view/icons/ico-mandatory.jpg new file mode 100644 index 0000000000000000000000000000000000000000..54492975393963975f8829fd9e512c036d4829c9 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/ico-mandatory.jpg differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-AddMultiLineComment.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-AddMultiLineComment.png new file mode 100644 index 0000000000000000000000000000000000000000..aec12784571dbcd123a0157d6f07bcc5e10d5491 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-AddMultiLineComment.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-AddSingleLineComment.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-AddSingleLineComment.png new file mode 100644 index 0000000000000000000000000000000000000000..c9f65ad71e4f5c49eca5590ee7cf8166ae3ceaf0 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-AddSingleLineComment.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-UsersAndRoles-00-NoAccess.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-UsersAndRoles-00-NoAccess.png new file mode 100644 index 0000000000000000000000000000000000000000..d3b16b765a3323ee57ff9476e5b192dae47df283 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-UsersAndRoles-00-NoAccess.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-UsersAndRoles-01-Access.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-UsersAndRoles-01-Access.png new file mode 100644 index 0000000000000000000000000000000000000000..f211bbab036c20a2e492df924e136f2905d80805 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-UsersAndRoles-01-Access.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-UsersAndRoles.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-UsersAndRoles.png new file mode 100644 index 0000000000000000000000000000000000000000..b044dbdb622492f60e6d86e4aba885533993bbf4 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-UsersAndRoles.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-VEP-GenDetailsTab.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-VEP-GenDetailsTab.png new file mode 100644 index 0000000000000000000000000000000000000000..30b4489a9c45d9e6e50ceb46befdf03e27560a70 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-VEP-GenDetailsTab.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-VEP-Node-Properties-01.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-VEP-Node-Properties-01.png new file mode 100644 index 0000000000000000000000000000000000000000..12c539e68ab4adba85b2d7fc8cac4553ce4fe1dd Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-VEP-Node-Properties-01.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-VEP-Properties-01.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-VEP-Properties-01.png new file mode 100644 index 0000000000000000000000000000000000000000..71a8ad560cbbd50a8be6d2e130e814839ebb4519 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-VEP-Properties-01.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-VEP-Reset.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-VEP-Reset.png new file mode 100644 index 0000000000000000000000000000000000000000..c14704364a0724d98e52178a82de9041662fa1f6 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-VEP-Reset.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-VEP-VisDetailedTab.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-VEP-VisDetailedTab.png new file mode 100644 index 0000000000000000000000000000000000000000..1f6b59a32ecd35a3e97438f410f7692c027bafb9 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-VEP-VisDetailedTab.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-VEP-VisQuickTab.png.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-VEP-VisQuickTab.png.png new file mode 100644 index 0000000000000000000000000000000000000000..207c9137a88792d3d043e61f3f0b30e895c17483 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-VEP-VisQuickTab.png.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-VEP-VisualExplain-Detailed.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-VEP-VisualExplain-Detailed.png new file mode 100644 index 0000000000000000000000000000000000000000..f8515b1f96b344cd1154a6fd8f66d75d212b7a75 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-VEP-VisualExplain-Detailed.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-alias.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-alias.png new file mode 100644 index 0000000000000000000000000000000000000000..cbad0fb59498433ebc1e050b4669bf9b730a8fcd Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-alias.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-clear.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-clear.png new file mode 100644 index 0000000000000000000000000000000000000000..5a3c36471365a69dddb897258b4750c227a1a27c Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-clear.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-column.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-column.png new file mode 100644 index 0000000000000000000000000000000000000000..12383f0e5860bc72ac8cee13819b748368d06bf1 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-column.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-columns.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-columns.png new file mode 100644 index 0000000000000000000000000000000000000000..b22300a808cc88b1eef7f26f352e4e621ec61335 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-columns.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-constraints.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-constraints.png new file mode 100644 index 0000000000000000000000000000000000000000..20fee66af05f9c0a2da8cf28d86ad5cb074f7403 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-constraints.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-copy-advanced.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-copy-advanced.png new file mode 100644 index 0000000000000000000000000000000000000000..00116a44626856c67b355d2c668e6ac0b441f012 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-copy-advanced.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-copy.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-copy.png new file mode 100644 index 0000000000000000000000000000000000000000..ae7c278fe4a710210ae2c04ad5c8c4ef72dc93ae Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-copy.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-cut.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-cut.png new file mode 100644 index 0000000000000000000000000000000000000000..cc26c7c239c07e2cc43cd0b5cca1fa93c61618f5 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-cut.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-database-CloseAll.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-database-CloseAll.png new file mode 100644 index 0000000000000000000000000000000000000000..10dab3fc7c19493941a3188b42f850a7682411ed Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-database-CloseAll.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-database-active.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-database-active.png new file mode 100644 index 0000000000000000000000000000000000000000..3a6d539b43e3e23eeea844e1c3c1bda0848ccd6e Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-database-active.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-database-not-active.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-database-not-active.png new file mode 100644 index 0000000000000000000000000000000000000000..207c9137a88792d3d043e61f3f0b30e895c17483 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-database-not-active.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-grid.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-grid.png new file mode 100644 index 0000000000000000000000000000000000000000..84778ea5bd0ddf10ee8afb1f2d48d1e1fc3a0ecc Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-grid.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-index.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-index.png new file mode 100644 index 0000000000000000000000000000000000000000..4f417bdebcb8fffb0ab2cd7e9fa33f0dc57dac6a Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-index.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-indexes.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-indexes.png new file mode 100644 index 0000000000000000000000000000000000000000..a7245e04338bfb6fa2a29f9f2458f5f561624957 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-indexes.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-load-more-record.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-load-more-record.png new file mode 100644 index 0000000000000000000000000000000000000000..1e503f6f320ba7fc347384ea7a21bdd4e958a4a4 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-load-more-record.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-newTerminalConnection.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-newTerminalConnection.png new file mode 100644 index 0000000000000000000000000000000000000000..903a7b2009d3ac2ea390fdc42654ca0a89fc02c6 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-newTerminalConnection.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-01-Aggregate.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-01-Aggregate.png new file mode 100644 index 0000000000000000000000000000000000000000..2da684824ff017fe747402ff2278b22cbe4051a4 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-01-Aggregate.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-02-AggregateGroup.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-02-AggregateGroup.png new file mode 100644 index 0000000000000000000000000000000000000000..3e08c852bd74d41dec146116e022e6e6426d473b Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-02-AggregateGroup.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-03-Function.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-03-Function.png new file mode 100644 index 0000000000000000000000000000000000000000..ac8c9bd450b3c203e4f6c44d79973bd865cf7ab4 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-03-Function.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-04-Hash.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-04-Hash.png new file mode 100644 index 0000000000000000000000000000000000000000..6d254aea7cf0657771502076201adef3baef4a05 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-04-Hash.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-05-HashJoin.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-05-HashJoin.png new file mode 100644 index 0000000000000000000000000000000000000000..22eaebceb9a88abf67589571db9845dd0b2bff3c Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-05-HashJoin.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-06-NestedLoop.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-06-NestedLoop.png new file mode 100644 index 0000000000000000000000000000000000000000..45207b7350db38b77e2923df0a2e330a01d02cba Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-06-NestedLoop.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-07-NestedLoopJoin.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-07-NestedLoopJoin.png new file mode 100644 index 0000000000000000000000000000000000000000..c3cc501b0ffe49a403c1533b039d9bfde66f89d0 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-07-NestedLoopJoin.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-08-ModifyTable.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-08-ModifyTable.png new file mode 100644 index 0000000000000000000000000000000000000000..fa7dcd256162f15c432371732524eed9bc83f63c Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-08-ModifyTable.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-09-PartitionIterator.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-09-PartitionIterator.png new file mode 100644 index 0000000000000000000000000000000000000000..0ad96d45c7931f74bf61f0f03bdc2fd0ad1a17ce Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-09-PartitionIterator.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-10-RowAdapter.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-10-RowAdapter.png new file mode 100644 index 0000000000000000000000000000000000000000..500c86a66c2d4a8b81f0af4df17e6978886eda85 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-10-RowAdapter.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-11-Scan.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-11-Scan.png new file mode 100644 index 0000000000000000000000000000000000000000..904774dc5a2188e9394e1fdc60865215f67e65fc Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-11-Scan.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-12-SetOperator.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-12-SetOperator.png new file mode 100644 index 0000000000000000000000000000000000000000..6e7b15aa14541f0500aed50bf3c0eb902d89d5d6 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-12-SetOperator.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-13-Sort.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-13-Sort.png new file mode 100644 index 0000000000000000000000000000000000000000..f437e508df5414adb321f019f9ec3fb5cb4fe3c8 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-13-Sort.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-14-Stream.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-14-Stream.png new file mode 100644 index 0000000000000000000000000000000000000000..13669d103e4942c41ca4e9bd5720a1009befaa7f Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-14-Stream.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-15-Union.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-15-Union.png new file mode 100644 index 0000000000000000000000000000000000000000..19c75e41631016448630d5853f866c4065b4da96 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-15-Union.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-16-Unknown.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-16-Unknown.png new file mode 100644 index 0000000000000000000000000000000000000000..8835c233b81976d20205cde1e9789fd2cc87c09e Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-nodeType-16-Unknown.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-paste.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-paste.png new file mode 100644 index 0000000000000000000000000000000000000000..10c8e8c0b125b40768278e25761882a5e6f7a1fc Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-paste.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-planTextView.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-planTextView.png new file mode 100644 index 0000000000000000000000000000000000000000..213ab980eaab067696304f8cb243de3c41b818c5 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-planTextView.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-planTreeView.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-planTreeView.png new file mode 100644 index 0000000000000000000000000000000000000000..b92eb5c1dfb5502f22d1219394d739dd984b1b9d Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-planTreeView.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-redo-01.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-redo-01.png new file mode 100644 index 0000000000000000000000000000000000000000..6ea2d7877df14b9d0f4be14f512be9bbfecfbd91 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-redo-01.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-reuseTerminalConnection.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-reuseTerminalConnection.png new file mode 100644 index 0000000000000000000000000000000000000000..f3cba969dd18e6c7086297871d04a26c6e6d0b53 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-reuseTerminalConnection.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-server.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-server.png new file mode 100644 index 0000000000000000000000000000000000000000..1b09a45c29918a53cd2c7a22e710bd423d7ba664 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-server.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-tables.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-tables.png new file mode 100644 index 0000000000000000000000000000000000000000..95261becbbfdb5e2761c4d83afe208a4f9f93fd3 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-tables.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-text.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-text.png new file mode 100644 index 0000000000000000000000000000000000000000..3e13ba1c09fd3d1d3464f7dacd520a04cfe6c933 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-text.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-undo-01.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-undo-01.png new file mode 100644 index 0000000000000000000000000000000000000000..30d9503fcec166c95fd5326d49df12d3b0c4a17e Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon-undo-01.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_PLSQLviewer.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_PLSQLviewer.png new file mode 100644 index 0000000000000000000000000000000000000000..56fac9b8fe6eb0e31302c316dd5647c553c2efae Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_PLSQLviewer.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_Procedure_PL.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_Procedure_PL.png new file mode 100644 index 0000000000000000000000000000000000000000..34cdfa2781e26fa76702d69d5ab218296577415a Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_Procedure_PL.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_Procedure_PL_Disconnected.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_Procedure_PL_Disconnected.png new file mode 100644 index 0000000000000000000000000000000000000000..59c63117f78788fc561b70a0c4b3963f4b6d5a87 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_Procedure_PL_Disconnected.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_SQLterminal.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_SQLterminal.png new file mode 100644 index 0000000000000000000000000000000000000000..51f221c91ce5023d737682f1cf8ab31e4b9d73cc Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_SQLterminal.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_SQLterminal_Disconnected.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_SQLterminal_Disconnected.png new file mode 100644 index 0000000000000000000000000000000000000000..d51bddbd74b0c0765e5799afb9f22653bdd2893c Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_SQLterminal_Disconnected.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_arrow_right.gif b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_arrow_right.gif new file mode 100644 index 0000000000000000000000000000000000000000..4d3b012864da6f726acd460602200b81547ffd43 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_arrow_right.gif differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_batchdrop_completed.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_batchdrop_completed.png new file mode 100644 index 0000000000000000000000000000000000000000..6e1dab9c6873c46265359dcb3141b689cbcc2539 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_batchdrop_completed.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_batchdrop_error.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_batchdrop_error.png new file mode 100644 index 0000000000000000000000000000000000000000..d1ba950d31b79ecf4ae14077e992f1799f056b70 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_batchdrop_error.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_batchdrop_errorcount.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_batchdrop_errorcount.png new file mode 100644 index 0000000000000000000000000000000000000000..11fe3bf9358c3e004d28a21aaa9b414e8dd19231 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_batchdrop_errorcount.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_batchdrop_inprogress.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_batchdrop_inprogress.png new file mode 100644 index 0000000000000000000000000000000000000000..3cf8089af55c3119a61f07ee7e743e5f71e2ba8a Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_batchdrop_inprogress.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_batchdrop_runcount.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_batchdrop_runcount.png new file mode 100644 index 0000000000000000000000000000000000000000..62ae8e395bae10eb395b9ee495525eec308abe75 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_batchdrop_runcount.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_batchdrop_tostart.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_batchdrop_tostart.png new file mode 100644 index 0000000000000000000000000000000000000000..9dbaa309539955b69a75ef74cdd5c2ec72ed3edd Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_batchdrop_tostart.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_batchdrop_window_01.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_batchdrop_window_01.png new file mode 100644 index 0000000000000000000000000000000000000000..ef238bbf0a9042cfa72711d67f0d365554da3594 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_batchdrop_window_01.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_columnLock_04.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_columnLock_04.png new file mode 100644 index 0000000000000000000000000000000000000000..dc4c4898c2b0f472a8448629356a1b8c35b0f864 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_columnLock_04.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_console.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_console.png new file mode 100644 index 0000000000000000000000000000000000000000..32f19d82bb85e1ef807d05a3dc286fc70c73d6a8 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_console.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_edit_table_forget_diable.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_edit_table_forget_diable.png new file mode 100644 index 0000000000000000000000000000000000000000..b51b55a7d889a0aa37d50ab8555f1c2f819af5c8 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_edit_table_forget_diable.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_edit_table_forget_enable.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_edit_table_forget_enable.png new file mode 100644 index 0000000000000000000000000000000000000000..579ad98e08a79d924fbb8f178a392f6c7a0f7a32 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_edit_table_forget_enable.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_file_terminal-disconnected.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_file_terminal-disconnected.png new file mode 100644 index 0000000000000000000000000000000000000000..c5d53e27fc88bb88697b79de5b19e231b2689e29 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_file_terminal-disconnected.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_file_terminal.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_file_terminal.png new file mode 100644 index 0000000000000000000000000000000000000000..ac655778189164fbc6a4fd7890f29221673fce02 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_file_terminal.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_namespace_N(16x16).PNG b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_namespace_N(16x16).PNG new file mode 100644 index 0000000000000000000000000000000000000000..63f608647e9a66952034c1c7805eb48ba165d5a3 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_namespace_N(16x16).PNG differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_namespace_S(16x16).PNG b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_namespace_S(16x16).PNG new file mode 100644 index 0000000000000000000000000000000000000000..1748eb38c236c0cd917deedededf94434dc4a5cc Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_namespace_S(16x16).PNG differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_objBrowser.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_objBrowser.png new file mode 100644 index 0000000000000000000000000000000000000000..99860adb8ff1a49b3db0b7c90bad5dad82e02dc0 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_objBrowser.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_obrefresh.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_obrefresh.png new file mode 100644 index 0000000000000000000000000000000000000000..4e8c46989e75663f2f4655cb472c81004db374d4 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_obrefresh.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_resultWindow.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_resultWindow.png new file mode 100644 index 0000000000000000000000000000000000000000..be56969b6f3274f210986a53180edbe48a01fc53 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_resultWindow.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_search.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_search.png new file mode 100644 index 0000000000000000000000000000000000000000..b500b1772fca171528d29a3b0781dc327eb21747 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_search.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_search_bar_disabled.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_search_bar_disabled.png new file mode 100644 index 0000000000000000000000000000000000000000..f3872d6528eb8bdb56e65ee233142f4e60688d20 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_search_bar_disabled.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_search_bar_enabled.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_search_bar_enabled.png new file mode 100644 index 0000000000000000000000000000000000000000..28c4278ec4c7b44ab3ddf8cb915de841d8bb8a43 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_search_bar_enabled.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_search_text_clear.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_search_text_clear.png new file mode 100644 index 0000000000000000000000000000000000000000..35801000fbebc52c1034a18daeee97de2bcc2b16 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_search_text_clear.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_sequence_object.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_sequence_object.png new file mode 100644 index 0000000000000000000000000000000000000000..1a81e22bded2d68b3ea647418ff4cf171f11ae6f Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_sequence_object.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_sql_bar_disabled.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_sql_bar_disabled.png new file mode 100644 index 0000000000000000000000000000000000000000..0de915c50ef3764a0ad83f828b2cee32545a607f Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_sql_bar_disabled.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_sql_bar_enabled.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_sql_bar_enabled.png new file mode 100644 index 0000000000000000000000000000000000000000..6a120d9dcf43b2c4af87cb3c232231ad08f490df Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_sql_bar_enabled.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_system_schemas.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_system_schemas.png new file mode 100644 index 0000000000000000000000000000000000000000..a2b3dd479f83d2d97b5977ce8c5e40798352b66c Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_system_schemas.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_user_schemas.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_user_schemas.png new file mode 100644 index 0000000000000000000000000000000000000000..6b0b6433c307c735c16dbf7d0d5496c7ebb7faee Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/icon_user_schemas.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/importconnection.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/importconnection.png new file mode 100644 index 0000000000000000000000000000000000000000..317c3c944f7194bf6abbdc83c16850a0e5e94ddc Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/importconnection.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/keywords.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/keywords.png new file mode 100644 index 0000000000000000000000000000000000000000..53f16e562d793fea27ad2a200ac4010521489c8a Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/keywords.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/loading_namespace.gif b/code/datastudio/src/org.opengauss.mppdbide.view/icons/loading_namespace.gif new file mode 100644 index 0000000000000000000000000000000000000000..939dae8eff16be00a8fbbaacb94fb64d03b9f07d Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/loading_namespace.gif differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/lob.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/lob.png new file mode 100644 index 0000000000000000000000000000000000000000..f1ffa00138cad9d97dccd722c7bd7567a65d79b2 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/lob.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/message_error.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/message_error.png new file mode 100644 index 0000000000000000000000000000000000000000..317f8afa3f999bdcfab8a47ca46a86551b700aa8 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/message_error.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/multi_sort.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/multi_sort.png new file mode 100644 index 0000000000000000000000000000000000000000..d8c409ba3acc86bbf9cd6ebaaca7b49e39f629aa Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/multi_sort.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/newConnection.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/newConnection.png new file mode 100644 index 0000000000000000000000000000000000000000..c305163cb29ca93a8c93b39c53aa57049b17d83b Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/newConnection.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/noConnection.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/noConnection.png new file mode 100644 index 0000000000000000000000000000000000000000..ebd3dac81acebe7321482b37d19b378962f5123a Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/noConnection.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/number.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/number.png new file mode 100644 index 0000000000000000000000000000000000000000..7e0adf510ec1e18bdc12a96de248c16e947b4b18 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/number.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/openConnection.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/openConnection.png new file mode 100644 index 0000000000000000000000000000000000000000..dfcff913337475a29ecb47d4da31da7379736739 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/openConnection.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/open_SQL.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/open_SQL.png new file mode 100644 index 0000000000000000000000000000000000000000..c97f4c920368f6c9b69644c0bfe58145ddffde34 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/open_SQL.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/procedure.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/procedure.png new file mode 100644 index 0000000000000000000000000000000000000000..0b9984d278acec771f741b79c48400c427fc3fe9 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/procedure.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/progress-window.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/progress-window.png new file mode 100644 index 0000000000000000000000000000000000000000..78376e7e7f91abed8355ded11c931d28c91b522d Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/progress-window.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/progressclose_14X14.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/progressclose_14X14.png new file mode 100644 index 0000000000000000000000000000000000000000..a5de20257aca30c95525d1f81ca6fbfe40499ee4 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/progressclose_14X14.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/resume.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/resume.png new file mode 100644 index 0000000000000000000000000000000000000000..6fe1e3d14be544cf80998ff347b36c3c1d5abcd6 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/resume.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/run.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/run.png new file mode 100644 index 0000000000000000000000000000000000000000..e0d0c2fe1bc94a4c8068fc0619b5cd60c89291c0 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/run.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/run_terminal.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/run_terminal.png new file mode 100644 index 0000000000000000000000000000000000000000..045ac953f65b48435c422bebf9a659a1b006ede0 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/run_terminal.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/save-SQL.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/save-SQL.png new file mode 100644 index 0000000000000000000000000000000000000000..6db49d0a4346603ec8e75673355dce9ae07d31ec Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/save-SQL.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/save-SQL_.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/save-SQL_.png new file mode 100644 index 0000000000000000000000000000000000000000..6db49d0a4346603ec8e75673355dce9ae07d31ec Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/save-SQL_.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/save_SQL_.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/save_SQL_.png new file mode 100644 index 0000000000000000000000000000000000000000..6db49d0a4346603ec8e75673355dce9ae07d31ec Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/save_SQL_.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/save_SQL_as_.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/save_SQL_as_.png new file mode 100644 index 0000000000000000000000000000000000000000..0c349ecd7cc8503b2265193f250db99224667a6f Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/save_SQL_as_.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/sort_ascending.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/sort_ascending.png new file mode 100644 index 0000000000000000000000000000000000000000..09fcbf0e10fbed7e67dafed32b67a1e0e260f942 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/sort_ascending.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/sort_ascending_smaller.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/sort_ascending_smaller.png new file mode 100644 index 0000000000000000000000000000000000000000..297b7c4670c20b06f6c73350a72599b7a86fbef1 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/sort_ascending_smaller.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/sort_ascending_smallest.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/sort_ascending_smallest.png new file mode 100644 index 0000000000000000000000000000000000000000..93231609ed2027705d7b3db86796d57ba003004c Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/sort_ascending_smallest.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/sort_descending.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/sort_descending.png new file mode 100644 index 0000000000000000000000000000000000000000..329786e59ed19aeddcf1b25d47338039c5d815a4 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/sort_descending.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/sort_descending_smaller.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/sort_descending_smaller.png new file mode 100644 index 0000000000000000000000000000000000000000..540da488a4764ba834686ef431efda54883dd8e9 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/sort_descending_smaller.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/sort_descending_smallest.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/sort_descending_smallest.png new file mode 100644 index 0000000000000000000000000000000000000000..4c5871fd44d94e8bf1391748f6bd00755d958131 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/sort_descending_smallest.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/sort_none.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/sort_none.png new file mode 100644 index 0000000000000000000000000000000000000000..b88ddfa742dcd8ffaf3e564c6581645d15f9cb86 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/sort_none.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/string.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/string.png new file mode 100644 index 0000000000000000000000000000000000000000..b4d32bec61f5d274e4a12a0ae1f599c9548ff226 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/string.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/synonym.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/synonym.png new file mode 100644 index 0000000000000000000000000000000000000000..167536795fa32fe572ac0cb4f412630d759a1a30 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/synonym.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/synonymGroup.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/synonymGroup.png new file mode 100644 index 0000000000000000000000000000000000000000..377c033502686027d79a5b05a216ac1323aef9f9 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/synonymGroup.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/toggle_autocommit_disabled.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/toggle_autocommit_disabled.png new file mode 100644 index 0000000000000000000000000000000000000000..0a3441d53ac88815a8ce46633c0ad346004f11dc Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/toggle_autocommit_disabled.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/toggle_autocommit_off.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/toggle_autocommit_off.png new file mode 100644 index 0000000000000000000000000000000000000000..23aa6471cbd395fca7f6556d2b9cd3d11bbd5a60 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/toggle_autocommit_off.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/toggle_autocommit_on.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/toggle_autocommit_on.png new file mode 100644 index 0000000000000000000000000000000000000000..9a1c9d2f98a58f73c0d08275b99710f40368f62c Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/toggle_autocommit_on.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/transaction-commit.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/transaction-commit.png new file mode 100644 index 0000000000000000000000000000000000000000..48ec0dd676fbbb7976de1ef6ebeb05be918c1d25 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/transaction-commit.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/transaction-rollback.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/transaction-rollback.png new file mode 100644 index 0000000000000000000000000000000000000000..601f71c8f51c10ea1fd6cfd185bcffd2eeb99b97 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/transaction-rollback.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/trigger-disable.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/trigger-disable.png new file mode 100644 index 0000000000000000000000000000000000000000..ecd2ce70df123f813685f35447cf71763910bcfb Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/trigger-disable.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/trigger.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/trigger.png new file mode 100644 index 0000000000000000000000000000000000000000..79df60413a8ca414291747286a9ddaebf3ea783d Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/trigger.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/unchecked.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/unchecked.png new file mode 100644 index 0000000000000000000000000000000000000000..be3546fabf49e81e5fb08ded5d6d9c40afb2d0b6 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/unchecked.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/unknow.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/unknow.png new file mode 100644 index 0000000000000000000000000000000000000000..8823e56e21b48a3afc5f38187779dc80e3c7b63f Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/unknow.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/view_er_icon.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/view_er_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..4178fc6c873e85fd31af14f33e8856ad44a2975a Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/view_er_icon.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/visual_explain_disable.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/visual_explain_disable.png new file mode 100644 index 0000000000000000000000000000000000000000..f3db68b295f11f0735504c41a37fc38914d889df Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/visual_explain_disable.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/visual_explain_enable.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/visual_explain_enable.png new file mode 100644 index 0000000000000000000000000000000000000000..ad040f8b2319354431ee1324bf56b8eb8ec0080a Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/visual_explain_enable.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/warning.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/warning.png new file mode 100644 index 0000000000000000000000000000000000000000..50b6619b3dc35d17537466dc8a3733a83ae41f07 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/warning.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/icons/window_add.png b/code/datastudio/src/org.opengauss.mppdbide.view/icons/window_add.png new file mode 100644 index 0000000000000000000000000000000000000000..c985213f7fbe7e5dc089c775757b5a65c8e25830 Binary files /dev/null and b/code/datastudio/src/org.opengauss.mppdbide.view/icons/window_add.png differ diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/plugin.xml b/code/datastudio/src/org.opengauss.mppdbide.view/plugin.xml new file mode 100644 index 0000000000000000000000000000000000000000..16fa4d5e96929e426f400ef56ca750e90425458d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/plugin.xml @@ -0,0 +1,1493 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/pom.xml b/code/datastudio/src/org.opengauss.mppdbide.view/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..942dd2ad89dde592ff05b0172208ec73608ae961 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + + org.opengauss.plide.build + GAUSS_MPP_DB_IDE + 1.0.0-SNAPSHOT + + + ${maven.build.timestamp} + yyyy-MM-dd HH:mm + + + org.opengauss.mppdbide.view + eclipse-plugin + + + + maven-resources-plugin + + + copy-resource-for-build-timestamp + prepare-package + + copy-resources + + + true + target/classes + + + src/resources + true + + + + + + + + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/schema/editorextension.exsd b/code/datastudio/src/org.opengauss.mppdbide.view/schema/editorextension.exsd new file mode 100644 index 0000000000000000000000000000000000000000..937b473d65f61bdd826ca849666cc54ca6b04de9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/schema/editorextension.exsd @@ -0,0 +1,102 @@ + + + + + + + + + [Enter description of this extension point.] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + [Enter the first release in which this extension point appears.] + + + + + + + + + [Enter extension point usage example here.] + + + + + + + + + [Enter API information here.] + + + + + + + + + [Enter information about supplied implementation of this extension point.] + + + + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/default_templates.json b/code/datastudio/src/org.opengauss.mppdbide.view/src/default_templates.json new file mode 100644 index 0000000000000000000000000000000000000000..3c1e2e3871d7ac3d0f29ba8c168cc4843a305455 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/default_templates.json @@ -0,0 +1,61 @@ +{ + "version": "1.0.0", + "encoding": "utf8", + "templates": [{ + "deleted": "false", + "description": "select", + "enabled": "true", + "name": "sl", + "pattern": "select", + "id": "sl" + }, + { + "deleted": "false", + "description": "order by", + "enabled": "true", + "name": "o", + "pattern": "order by", + "id": "o" + }, + { + "deleted": "false", + "description": "select from", + "enabled": "true", + "name": "sf", + "pattern": "select * from", + "id": "sf" + }, + { + "deleted": "false", + "description": "delete from", + "enabled": "true", + "name": "df", + "pattern": "delete from", + "id": "df" + }, + { + "deleted": "false", + "description": "insert into", + "enabled": "true", + "name": "is", + "pattern": "insert into select", + "id": "is" + }, + { + "deleted": "false", + "description": "select row count", + "enabled": "true", + "name": "sc", + "pattern": "select count(*) from", + "id": "sc" + }, + { + "deleted": "false", + "description": "select from", + "enabled": "true", + "name": "s*", + "pattern": "select * from", + "id": "s*" + } + ] +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/formatter_template.json b/code/datastudio/src/org.opengauss.mppdbide.view/src/formatter_template.json new file mode 100644 index 0000000000000000000000000000000000000000..c6a99f7ad4367c918997dde3739c810b16d65576 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/formatter_template.json @@ -0,0 +1,49 @@ +{ + "general": "create or replace function insertStudent(studentName varchar, sectionId integer) +returns integer +AS $$ + studentNo integer; + i integer; +begin + studentNo := null; + i := 1; + if studentName is null then + studentNo := null; + else + insert into student + (studentName, sectionId) + values + (studentName, sectionId); + end if; + + for student_cursor in( select studentNo, studentName, sectionId + from student) loop + if student_cursor.studentName = studentName and student_cursor.sectionId = sectionId then + studentNo :=emp_cursor.studentNo; + end if; + end loop; + begin +-- Select + + select stuId as student_number, stuName as student_name, secName as section_name + from student, section + where student.secId = section.secId + and student.classId = section.classId; + + -- Insert + + insert into student + (stuId, stuName, secId) + values + (1, 'A Student', 101); + + -- Update + + update student + set stuName = 'B Student', secId = 102 + where stuId = 1; + end; + return studentNo; +end; $$ +" +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/keybinding.xml b/code/datastudio/src/org.opengauss.mppdbide.view/src/keybinding.xml new file mode 100644 index 0000000000000000000000000000000000000000..3f53d373f9573cc1125618992d2d5dde3aba8412 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/keybinding.xml @@ -0,0 +1,218 @@ + + + + org.opengauss.mppdbide.command.id.newdbconnection + PREFERENCE_COMMAND_NEW_NODE_CONNECTION + editor.shortcutmapper.newprofileconnection + DES_NEW_CONN + CTRL+N + + + org.opengauss.mppdbide.command.id.disconnectconnectionprofile + + PREFERENCE_SHORTCUT_DISSCONN_FRM_DB + editor.shortcutmapper.disconnectdatabase + DISSCONN_FRM_DB + CTRL+SHIFT+D + + + org.opengauss.mppdbide.command.id.executeeditoritem + + PREFERENCE_SHORTCUT_EXE_DB_OBJECT + editor.shortcutmapper.execute + EXE_DB_OBJECT + CTRL+E + + + org.opengauss.mppdbide.view.command.closeactivesourceviewer + PREFERENCE_SHORTCUT_CLOSE_ACTIVE_VIEWER + editor.shortcutmapper.closeactiveviewer + CLOSE_ACTIVE_VIEWER + SHIFT+F4 + + + org.opengauss.mppdbide.command.id.opennewterminal + PREFERENCE_COMMAND_OPEN_NEW_TERMINAL + editor.shortcutmapper.opennewterminal + OPEN_NEW_TERMINAL + CTRL+T + + + org.opengauss.mppdbide.command.id.executeobjectbrowseritemfromtoolbar + PREFERENCE_SHORTCUT_EXE_SQL_TERMINAL + editor.shortcutmapper.executesqlterminal + EXE_SQL_TERMINAL + CTRL+ENTER + + + org.opengauss.mppdbide.command.id.executeobjectbrowseritemfromtoolbarnewtab + PREFERENCE_SHORTCUT_KEY_OVERWRITE_RESULTSET + editor.shortcutmapper.executesqlterminalnewtab + PREFERENCE_SHORTCUT_KEY_OVERWRITE_RESULTSET_DESC + CTRL+ALT+ENTER + + + org.opengauss.mppdbide.command.id.cancelSql + PREFERENCE_SHORTCUT_CANCEL_SQL_STETEMNT + editor.shortcutmapper.cancelquery + CANCEL_SQL_STETEMNT + SHIFT+ESC + + + org.opengauss.mppdbide.command.id.executionplanandcost + PREFERENCE_SHORTCUT_EXECUTION_PLAN_AND_COST + editor.shortcutmapper.explainplanandcost + EXECUTION_PLAN_AND_COST + CTRL+SHIFT+X + + + org.opengauss.mppdbide.view.command.visualexplainplan + PREFERENCE_SHORTCUT_VISUAL_EXPLAIN_PLAN + editor.shortcutmapper.visualexplainplan + VISUAL_EXPLAIN_PLAN + ALT+CTRL+X + + + Auto Suggest + PREFERENCE_SHORTCUT_AUTO_SUGGEST + editor.shortcutmapper.autosuggest + SHOW_LIST_OF_OBJECTS + CTRL+SPACE + + + org.opengauss.mppdbide.editor.shortcutmapper.codetemplate + PREFERENCE_SHORTCUT_CODE_TEMPLATE + editor.shortcutmapper.codetemplate + SHOW_MATCHING_PATTERN + ALT+CTRL+SPACE + + + org.opengauss.mppdbide.command.id.format + PREFERENCE_SHORTCUT_FORMAT_SQL_STATEMENT + editor.shortcutmapper.format + FORMAT_SQL_STATEMENT + CTRL+SHIFT+F + + + org.opengauss.mppdbide.command.id.opensql + PREFERENCE_SHORTCUT_OPEN_SAVED_FILE + editor.shortcutmapper.open + OPEN_SAVED_FILE + CTRL+O + + + org.opengauss.mppdbide.command.id.savesql + PREFERENCE_SHORTCUT_TO_SAVE_FILE + editor.shortcutmapper.save + TO_SAVE_FILE + CTRL+S + + + org.opengauss.mppdbide.command.id.savesqlas + PREFERENCE_SHORTCUT_TO_SAVE_FILE_AS + editor.shortcutmapper.saveas + TO_SAVE_FILE_AS + CTRL+ALT+S + + + org.opengauss.mppdbide.view.command.collapseopenobjects + + PREFERENCE_SHORTCUT_COLAPSE_ALL_OBJECTS + editor.shortcutmapper.collapseopenobjs + COLAPSE_ALL_OBJECTS + ALT+Q + + + org.opengauss.mppdbide.command.id.refreshserverobject + + PREFERENCE_SHORTCUT_REF_SREVER_OBJECT + editor.shortcutmapper.refresh + REF_SREVER_OBJECT + F5 + + + org.opengauss.mppdbide.view.command.search + PREFERENCE_SHORTCUT_KEY_BINDING_SEARCH_DESC + editor.shortcutmapper.search + KEY_BINDING_SEARCH_DESC + CTRL+SHIFT+S + + + org.opengauss.mppdbide.view.command.UpperCase + PREFERENCE_SHORTCUT_TO_UPPER_CASE + editor.shortcutmapper.uppercase + TO_UPPER_CASE + CTRL+SHIFT+U + + + org.opengauss.mppdbide.view.command.LowerCase + PREFERENCE_SHORTCUT_TO_LOWER_CASE + editor.shortcutmapper.lowercase + TO_LOWER_CASE + CTRL+SHIFT+L + + + org.opengauss.mppdbide.view.command.gotoline + PREFERENCE_SHORTCUT_GO_TO_LINE + editor.shortcutmapper.gotoline + GO_TO_LINE + CTRL+G + + + org.opengauss.mppdbide.view.command.ForwardSearch + PREFERENCE_SHORTCUT_FORWARD_SEARCH + editor.shortcutmapper.ForwardSearch + FORWARD_SEARCH + F3 + + + org.opengauss.mppdbide.view.command.BackwardSearch + PREFERENCE_SHORTCUT_BACKWARD_SEARCH + editor.shortcutmapper.BackwardSearch + BACKWARD_SEARCH + SHIFT+F3 + + + org.opengauss.mppdbide.view.command.ToggleLineComment + PREFERENCE_SHORTCUT_KEY_BINDING_TOGGLE_LINE_COMMENTS + editor.shortcutmapper.toggleLineComment + KEY_BINDING_TOGGLE_LINE_COMMENTS_DESC + CTRL+/ + + + org.opengauss.mppdbide.view.command.ToggleBlockComment + PREFERENCE_SHORTCUT_KEY_BINDING_TOGGLE_BLOCK_COMMENTS + editor.shortcutmapper.toggleBlockComment + KEY_BINDING_TOGGLE_BLOCK_COMMENTS_DESC + CTRL+SHIFT+/ + + + + org.opengauss.mppdbide.command.id.startdebug + PREFERENCE_SHORTCUT_KEY_BINDING_START_DEBUG + editor.shortcutmapper.startdebug + KEY_BINDING_COMMENTS_DESC_START_DEBUG + F11 + + + org.opengauss.mppdbide.command.id.terminate + PREFERENCE_SHORTCUT_KEY_BINDING_TERNIMATE_DEBUG + editor.shortcutmapper.stopdebug + KEY_BINDING_COMMENTS_DESC_TERNIMATE_DEBUG + CTRL+F2 + + + org.opengauss.mppdbide.command.id.continue + PREFERENCE_SHORTCUT_KEY_BINDING_CONTINUE_DEBUG + editor.shortcutmapper.continue + KEY_BINDING_COMMENTS_DESC_CONTINUE_DEBUG + F8 + + + org.opengauss.mppdbide.command.id.stepover + PREFERENCE_SHORTCUT_KEY_BINDING_STEPOVER_DEBUG + editor.shortcutmapper.stepover + KEY_BINDING_COMMENTS_DESC_STEPOVER_DEBUG + F6 + + diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/eclipse/dependent/EclipseContextDSKeys.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/eclipse/dependent/EclipseContextDSKeys.java new file mode 100644 index 0000000000000000000000000000000000000000..2083323e79ec98ed5e4eb8866071f96c462b53d8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/eclipse/dependent/EclipseContextDSKeys.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.eclipse.dependent; + +/** + * + * Title: interface + * + * Description: The Interface EclipseContextDSKeys. + * + * @since 3.0.0 + */ +public interface EclipseContextDSKeys { + + /** + * The server object.for Object browser + */ + String SERVER_OBJECT = "SERVER_OBJECT"; + + /** + * The debug console window.Console for Debug Operation + */ + String DEBUG_CONSOLE_WINDOW = "DEBUG_CONSOLE_WINDOW"; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/eclipse/dependent/EclipseInjections.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/eclipse/dependent/EclipseInjections.java new file mode 100644 index 0000000000000000000000000000000000000000..b392532ffc50997be0807b957ea9ce457d4d610f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/eclipse/dependent/EclipseInjections.java @@ -0,0 +1,222 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.eclipse.dependent; + +import org.eclipse.e4.core.commands.ECommandService; +import org.eclipse.e4.core.commands.EHandlerService; +import org.eclipse.e4.core.contexts.IEclipseContext; +import org.eclipse.e4.ui.bindings.EBindingService; +import org.eclipse.e4.ui.model.application.MApplication; +import org.eclipse.e4.ui.workbench.IWorkbench; +import org.eclipse.e4.ui.workbench.modeling.EModelService; +import org.eclipse.e4.ui.workbench.modeling.EPartService; + +/** + * + * Title: class + * + * Description: The Class EclipseInjections. + * + * @since 3.0.0 + */ +public class EclipseInjections { + + /** + * The eclipse context. + */ + IEclipseContext eclipseContext; + + /** + * The workbench. + */ + IWorkbench workbench; + private ECommandService commandService; + private EHandlerService handlerService; + private EBindingService bindingService; + private EPartService partService; + private EModelService modelService; + private MApplication application; + + /** + * The my self. + */ + static EclipseInjections mySelf; + + private EclipseInjections() { + + } + + static { + mySelf = new EclipseInjections(); + } + + /** + * Sets the eclipse context. + * + * @param eclipseContext the new eclipse context + */ + public void setEclipseContext(IEclipseContext eclipseContext) { + this.eclipseContext = eclipseContext; + } + + /** + * Sets the command service. + * + * @param commService the new command service + */ + public void setCommandService(ECommandService commService) { + this.commandService = commService; + } + + /** + * Sets the handler service. + * + * @param handService the new handler service + */ + public void setHandlerService(EHandlerService handService) { + this.handlerService = handService; + } + + /** + * Sets the work bench. + * + * @param wb the new work bench + */ + public void setWorkBench(IWorkbench wb) { + this.workbench = wb; + } + + /** + * Sets the binding service. + * + * @param bs the new binding service + */ + public void setBindingService(EBindingService bs) { + this.bindingService = bs; + } + + /** + * Sets the part service. + * + * @param ps the new part service + */ + public void setPartService(EPartService ps) { + this.partService = ps; + + } + + /** + * Sets the model service. + * + * @param ms the new model service + */ + public void setModelService(EModelService ms) { + this.modelService = ms; + + } + + /** + * Sets the application. + * + * @param app the new application + */ + public void setApplication(MApplication app) { + this.application = app; + + } + + /** + * Gets the single instance of EclipseInjections. + * + * @return single instance of EclipseInjections + */ + public static EclipseInjections getInstance() { + return mySelf; + } + + /** + * Gets the command service. + * + * @return the command service + */ + public ECommandService getCommandService() { + return commandService; + } + + /** + * Gets the handler service. + * + * @return the handler service + */ + public EHandlerService getHandlerService() { + return handlerService; + } + + /** + * Gets the binding service. + * + * @return the binding service + */ + public EBindingService getBindingService() { + return this.bindingService; + } + + /** + * Gets the work bench. + * + * @return the work bench + */ + public IWorkbench getWorkBench() { + return workbench; + } + + /** + * Gets the eclipse context. + * + * @return the eclipse context + */ + public IEclipseContext getEclipseContext() { + return this.eclipseContext; + } + + /** + * Gets the ps. + * + * @return the ps + */ + public EPartService getPS() { + return partService; + } + + /** + * Gets the ms. + * + * @return the ms + */ + public EModelService getMS() { + return modelService; + } + + /** + * Gets the app. + * + * @return the app + */ + public MApplication getApp() { + return application; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/consts/EmptyLinesEnum.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/consts/EmptyLinesEnum.java new file mode 100644 index 0000000000000000000000000000000000000000..0e48255d48fda4c408c6c3e7a3bfdf339358332f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/consts/EmptyLinesEnum.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.consts; + +/** + * Title: EmptyLinesEnum + * + * @since 3.0.0 + */ +public enum EmptyLinesEnum { + REMOVE, MERGE, PRESERVE +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/consts/FormatItemsType.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/consts/FormatItemsType.java new file mode 100644 index 0000000000000000000000000000000000000000..446f7c41909effbc81fd0ef7bd3abcb2b5bac944 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/consts/FormatItemsType.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.consts; + +/** + * Title: FormatItemsType + * + * @since 3.0.0 + */ +public enum FormatItemsType { + SELECT, INSERT, UPDATE, DML, CONTROL_STRUCTURE, PARAMETER, RECORD_TYPE, UNKNOWN, FIXED_ONEITEMPERLINE +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/consts/FormatPaddingEnum.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/consts/FormatPaddingEnum.java new file mode 100644 index 0000000000000000000000000000000000000000..fa274744ab5615201cb15132d4dff932d956ae32 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/consts/FormatPaddingEnum.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.consts; + +/** + * + * Title: FormatPaddingEnum + * + * @since 3.0.0 + */ +public enum FormatPaddingEnum { + LPAD, RPAD, NOPAD +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/consts/ListItemOptionsEnum.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/consts/ListItemOptionsEnum.java new file mode 100644 index 0000000000000000000000000000000000000000..fc6f79c4419a27c56c8ee6c1411a727cc029d3e1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/consts/ListItemOptionsEnum.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.consts; + +/** + * Title: ListItemOptionsEnum + * + * @since 3.0.0 + */ +public enum ListItemOptionsEnum { + ONELINE, ONLINEIFPOSSIBLE, ONEITEMPERLINE, FIT +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/option/FmtOptions.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/option/FmtOptions.java new file mode 100644 index 0000000000000000000000000000000000000000..6cbe3b40bf836ad0a13e1659085c4808b1d33825 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/option/FmtOptions.java @@ -0,0 +1,378 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.option; + +import org.eclipse.jface.preference.PreferenceStore; + +import org.opengauss.mppdbide.gauss.format.consts.EmptyLinesEnum; +import org.opengauss.mppdbide.gauss.format.consts.FormatItemsType; +import org.opengauss.mppdbide.gauss.format.consts.ListItemOptionsEnum; +import org.opengauss.mppdbide.view.formatpref.FormatterPreferenceKeys; + +/** + * Title: FmtOptions + * + * @since 3.0.0 + */ +public class FmtOptions implements FmtOptionsIf { + private PreferenceStore prefStore = null; + + /** + * get preference store + * + * @return get preference store + */ + @Override + public PreferenceStore getPrefStore() { + return prefStore; + } + + /** + * set preference store + * + * @param prefStore set preference store + */ + @Override + public void setPrefStore(PreferenceStore prefStore) { + this.prefStore = prefStore; + } + + /** + * return true if keywords are left align + * + * @return true if keywords are left align + */ + @Override + public boolean leftAlignKeywords() { + return prefStore.getBoolean(FormatterPreferenceKeys.DML_LEFT_ALIGN_KEYWORDS); + } + + /** + * return true if items are left align + * + * @return return true if items are left align + */ + @Override + public boolean leftAlignItems() { + return prefStore.getBoolean(FormatterPreferenceKeys.DML_LEFT_ALIGN_ITEMS); + } + + /** + * return the list of Item options + * + * @param formatItemsType formatItemsType for which need ListItemOptionsEnum + * @return return the list of Item options + */ + @Override + public ListItemOptionsEnum getItemOption(FormatItemsType formatItemsType) { + return getFormatOptionByType(formatItemsType); + } + + private ListItemOptionsEnum getFormatOptionByType(FormatItemsType formatItemsType) { + switch (formatItemsType) { + case SELECT: { + return getFormatOption(prefStore.getInt(FormatterPreferenceKeys.DML_SELECT_FORMAT)); + } + case INSERT: { + return getFormatOption(prefStore.getInt(FormatterPreferenceKeys.DML_INSERT_FORMAT)); + } + case UPDATE: { + return getFormatOption(prefStore.getInt(FormatterPreferenceKeys.DML_UPDATE_FORMAT)); + } + default: { + return getFormatOptionByTypeSecond(formatItemsType); + } + } + } + + private ListItemOptionsEnum getFormatOptionByTypeSecond(FormatItemsType formatItemsType) { + switch (formatItemsType) { + case PARAMETER: { + return getFormatOption(prefStore.getInt(FormatterPreferenceKeys.PARAM_FORMAT)); + } + case FIXED_ONEITEMPERLINE: { + return ListItemOptionsEnum.ONEITEMPERLINE; + } + default: { + return getFormatOption(prefStore.getInt(FormatterPreferenceKeys.GEN_ITEMLIST_FORMAT)); + } + } + } + + private ListItemOptionsEnum getFormatOption(int option) { + switch (option) { + case 0: { + return ListItemOptionsEnum.ONEITEMPERLINE; + } + case 1: { + return ListItemOptionsEnum.ONELINE; + } + case 2: { + return ListItemOptionsEnum.FIT; + } + default: { + return ListItemOptionsEnum.ONLINEIFPOSSIBLE; + } + } + } + + /** + * return right margin + * + * @return return right margin + */ + @Override + public int getRightMargin() { + return prefStore.getInt(FormatterPreferenceKeys.GEN_RIGHT_MARGIN); + } + + /** + * return true if comma is there after format item + * + * @param formatItemsType FormatItemsType of the statement + * @return true if comma is there after format item + */ + @Override + public boolean getCommaAfteritem(FormatItemsType formatItemsType) { + switch (formatItemsType) { + case SELECT: { + return prefStore.getBoolean(FormatterPreferenceKeys.DML_SELECT_COMMA_AFTER); + } + case INSERT: { + return prefStore.getBoolean(FormatterPreferenceKeys.DML_INSERT_COMMA_AFTER); + } + default: { + return getCommaAfteritemSecond(formatItemsType); + } + } + } + + private boolean getCommaAfteritemSecond(FormatItemsType formatItemsType) { + switch (formatItemsType) { + case UPDATE: { + return prefStore.getBoolean(FormatterPreferenceKeys.DML_UPDATE_COMMA_AFTER); + } + case PARAMETER: { + return prefStore.getBoolean(FormatterPreferenceKeys.PARAM_COMMA_AFTER); + } + case RECORD_TYPE: { + return prefStore.getBoolean(FormatterPreferenceKeys.RECORD_TYPE_COMMA_AFTER); + } + default: { + return prefStore.getBoolean(FormatterPreferenceKeys.GEN_ITEMLIST_COMMA_AFTER); + } + } + } + + /** + * return true if Tab char is used + * + * @return return true if Tab char is used + */ + @Override + public boolean useTabChar() { + return prefStore.getBoolean(FormatterPreferenceKeys.GEN_TAB_CHAR); + } + + /** + * return the size of tab char + * + * @return return the size of tab char + */ + @Override + public int getTabCharSize() { + return prefStore.getInt(FormatterPreferenceKeys.GEN_CHAR_SIZE); + } + + /** + * return true if item is aligned + * + * @param formatItemsType FormatItemsType of the statement + * @return return true if item is aligned + */ + @Override + public boolean isAlign(FormatItemsType formatItemsType) { + switch (formatItemsType) { + case SELECT: { + return prefStore.getBoolean(FormatterPreferenceKeys.DML_SELECT_ALIGN); + } + case INSERT: { + return false; + } + case UPDATE: { + return prefStore.getBoolean(FormatterPreferenceKeys.DML_UPDATE_ALIGN); + } + case PARAMETER: { + return prefStore.getBoolean(FormatterPreferenceKeys.PARAM_ALIGN); + } + case RECORD_TYPE: { + return prefStore.getBoolean(FormatterPreferenceKeys.RECORD_TYPE_ALIGN); + } + default: { + return prefStore.getBoolean(FormatterPreferenceKeys.GEN_ITEMLIST_ALIGN); + } + } + } + + /** + * return true is item can be split at zero level + * + * @param formatItemsType FormatItemsType of the statement + * @return true is item can be split at zero level + */ + @Override + public boolean splitAtZeroLevel(FormatItemsType formatItemsType) { + switch (formatItemsType) { + case CONTROL_STRUCTURE: { + return prefStore.getBoolean(FormatterPreferenceKeys.CTRL_STRUCT_SPLIT_AND_OR); + } + default: { + return prefStore.getBoolean(FormatterPreferenceKeys.DML_SPLIT_AND_OR); + } + } + } + + /** + * return true if AND/OR is there after expr + * + * @param formatItemsType FormatItemsType of the statement + * @return return true if AND/OR is there after expr + */ + @Override + public boolean andOrAfterExp(FormatItemsType formatItemsType) { + switch (formatItemsType) { + case CONTROL_STRUCTURE: { + return prefStore.getBoolean(FormatterPreferenceKeys.CTRL_STRUCT_AND_OR_AFTER_EXP); + } + default: { + return prefStore.getBoolean(FormatterPreferenceKeys.DML_AND_OR_AFTER_EXP); + } + } + } + + /** + * return true if AND/OR is there under Where + * + * @return return true if AND/OR is there under Where + */ + @Override + public boolean andOrUnderWhere() { + return prefStore.getBoolean(FormatterPreferenceKeys.DML_AND_OR_UDER_WHERE); + } + + /** + * return Indendent space + * + * @return return Indendent space + */ + @Override + public int getIndend() { + return prefStore.getInt(FormatterPreferenceKeys.GEN_INDENT); + } + + /** + * return true if join can be split before on + * + * @return return true if join can be split before on + */ + @Override + public boolean splitJoinBeforeOn() { + return prefStore.getBoolean(FormatterPreferenceKeys.DML_JOIN_SPLIT_BEFORE_ON); + } + + /** + * return statement style + * + * @return return statement style + */ + @Override + public boolean getStatementStyle() { + return prefStore.getBoolean(FormatterPreferenceKeys.DML_ON_ONE_LINE_IFPOSSIBLE); + } + + /** + * return true if list is there after left margin + * + * @return return true if list is there after left margin + */ + @Override + public boolean isListAtLeftMargin() { + return prefStore.getBoolean(FormatterPreferenceKeys.PARAM_AT_LEFT_MARGIN); + } + + /** + * return true id declaration stmt is aligned + * + * @return return true id declaration stmt is aligned + */ + @Override + public boolean isAlignDeclaration() { + return prefStore.getBoolean(FormatterPreferenceKeys.GEN_ALIGN_DECLARATION); + } + + /** + * return true if assignment stmt is aligned + * + * @return return true if assignment stmt is aligned + */ + @Override + public boolean isAlignAssignment() { + return prefStore.getBoolean(FormatterPreferenceKeys.GEN_ALIGN_ASSIGNMENT); + } + + /** + * return empty lines + * + * @return return empty lines + */ + @Override + public EmptyLinesEnum getEmptyLines() { + switch (prefStore.getInt(FormatterPreferenceKeys.GEN_EMPTY_LINES)) { + case 1: { + return EmptyLinesEnum.REMOVE; + } + case 2: { + return EmptyLinesEnum.MERGE; + } + case 3: { + return EmptyLinesEnum.PRESERVE; + } + default: { + return EmptyLinesEnum.PRESERVE; + } + } + } + + /** + * check whether Then is there on NewLine + * + * @return return true when new line on control structure + */ + @Override + public boolean isThenOnNewLine() { + return prefStore.getBoolean(FormatterPreferenceKeys.CTRL_STRUCT_THEN_ON_NEW_LINE); + } + + /** + * check whether Loop is there on NewLine + * + * @return return true when LOOP on newline + */ + @Override + public boolean isLoopOnNewLine() { + return prefStore.getBoolean(FormatterPreferenceKeys.CTRL_STRUCT_LOOP_ONE_NEW_LINE); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/option/FmtOptionsIf.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/option/FmtOptionsIf.java new file mode 100644 index 0000000000000000000000000000000000000000..ee77d14fde2c62b651017a15873f41b1e3835b42 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/option/FmtOptionsIf.java @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.option; + +import org.eclipse.jface.preference.PreferenceStore; + +import org.opengauss.mppdbide.gauss.format.consts.EmptyLinesEnum; +import org.opengauss.mppdbide.gauss.format.consts.FormatItemsType; +import org.opengauss.mppdbide.gauss.format.consts.ListItemOptionsEnum; + +/** + * Title: FmtOptions + * + * @since 3.0.0 + */ +public interface FmtOptionsIf { + /** + * get preference store + * + * @return get preference store + */ + PreferenceStore getPrefStore(); + + /** + * set preference store + * + * @param prefStore set preference store + */ + void setPrefStore(PreferenceStore prefStore); + + /** + * return true if keywords are left align + * + * @return true if keywords are left align + */ + boolean leftAlignKeywords(); + + /** + * return true if items are left align + * + * @return return true if items are left align + */ + boolean leftAlignItems(); + + /** + * return the list of Item options + * + * @param formatItemsType formatItemsType for which need ListItemOptionsEnum + * @return return the list of Item options + */ + ListItemOptionsEnum getItemOption(FormatItemsType formatItemsType); + + /** + * return right margin + * + * @return return right margin + */ + int getRightMargin(); + + /** + * return true if comma is there after format item + * + * @param formatItemsType FormatItemsType of the statement + * @return true if comma is there after format item + */ + boolean getCommaAfteritem(FormatItemsType formatItemsType); + + /** + * return true if Tab char is used + * + * @return return true if Tab char is used + */ + boolean useTabChar(); + + /** + * return the size of tab char + * + * @return return the size of tab char + */ + int getTabCharSize(); + + /** + * return true if item is aligned + * + * @param formatItemsType FormatItemsType of the statement + * @return return true if item is aligned + */ + boolean isAlign(FormatItemsType formatItemsType); + + /** + * return true is item can be split at zero level + * + * @param formatItemsType FormatItemsType of the statement + * @return true is item can be split at zero level + */ + boolean splitAtZeroLevel(FormatItemsType formatItemsType); + + /** + * return true if AND/OR is there after expr + * + * @param formatItemsType FormatItemsType of the statement + * @return return true if AND/OR is there after expr + */ + boolean andOrAfterExp(FormatItemsType formatItemsType); + + /** + * return true if AND/OR is there under Where + * + * @return return true if AND/OR is there under Where + */ + boolean andOrUnderWhere(); + + /** + * return Indendent space + * + * @return return Indendent space + */ + int getIndend(); + + /** + * return true if join can be split before on + * + * @return return true if join can be split before on + */ + boolean splitJoinBeforeOn(); + + /** + * return statement style + * + * @return return statement style + */ + boolean getStatementStyle(); + + /** + * return true if list is there after left margin + * + * @return return true if list is there after left margin + */ + boolean isListAtLeftMargin(); + + /** + * return true id declaration stmt is aligned + * + * @return return true id declaration stmt is aligned + */ + boolean isAlignDeclaration(); + + /** + * return true if assignment stmt is aligned + * + * @return return true if assignment stmt is aligned + */ + boolean isAlignAssignment(); + + /** + * return empty lines + * + * @return return empty lines + */ + EmptyLinesEnum getEmptyLines(); + + /** + * check whether Then is there on NewLine + * + * @return return true when new line on control structure + */ + boolean isThenOnNewLine(); + + /** + * check whether Loop is there on NewLine + * + * @return return true when LOOP on newline + */ + boolean isLoopOnNewLine(); + +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/option/OptionsProcessData.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/option/OptionsProcessData.java new file mode 100644 index 0000000000000000000000000000000000000000..abae2d9f7d97631f569a03ea64fa05c759614c39 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/option/OptionsProcessData.java @@ -0,0 +1,212 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.option; + +import org.opengauss.mppdbide.gauss.format.consts.FormatItemsType; + +/** + * Title: OptionsProcessData + * + * @since 3.0.0 + */ +public class OptionsProcessData implements Cloneable { + + private int offSet = 0; + + private int parentOffSet = 0; + + private int maxKeywordLength = 0; + + private int preIndentOffSet = 0; + + private boolean putStmtNewLine = true; + + private FormatItemsType formatItemsType = FormatItemsType.UNKNOWN; + + private OptionsProcessData parentData = null; + + private int lastFormatType = 0; + + /** + * return offset value. + * + * @return the off set + */ + public int getOffSet() { + return offSet; + } + + /** + * set offset value. + * + * @param offSet the new off set + */ + public void setOffSet(int offSet) { + this.offSet = offSet; + } + + /** + * add offset value. + * + * @param addedOffSet the added off set + */ + public void addOffSet(int addedOffSet) { + this.offSet += addedOffSet; + } + + /** + * return parent offset value. + * + * @return the parent off set + */ + public int getParentOffSet() { + return parentOffSet; + } + + /** + * set parent offset value. + * + * @param parentOffSet the new parent off set + */ + public void setParentOffSet(int parentOffSet) { + this.parentOffSet = parentOffSet; + } + + /** + * return max keyword length. + * + * @return the max keyword length + */ + public int getMaxKeywordLength() { + return maxKeywordLength; + } + + /** + * set max keyword length. + * + * @param maxKeywordLength the new max keyword length + */ + public void setMaxKeywordLength(int maxKeywordLength) { + this.maxKeywordLength = maxKeywordLength; + } + + /** + * return pre indend offset value. + * + * @return the pre indent off set + */ + public int getPreIndentOffSet() { + return preIndentOffSet; + } + + /** + * set pre indend offset value. + * + * @param preIndentOffSet the new pre indent off set + */ + public void setPreIndentOffSet(int preIndentOffSet) { + this.preIndentOffSet = preIndentOffSet; + } + + /** + * return ParentData object. + * + * @return the parent data + */ + public OptionsProcessData getParentData() { + return parentData; + } + + /** + * set ParentData object. + * + * @param parentData the new parent data + */ + public void setParentData(OptionsProcessData parentData) { + this.parentData = parentData; + } + + /** + * return formatItemsType. + * + * @return the format items type + */ + public FormatItemsType getFormatItemsType() { + return formatItemsType; + } + + /** + * set formatItemsType. + * + * @param formatItemsType the new format items type + */ + public void setFormatItemsType(FormatItemsType formatItemsType) { + this.formatItemsType = formatItemsType; + } + + /** + * return putStmtNewLine value. + * + * @return true, if is put stmt new line + */ + public boolean isPutStmtNewLine() { + return putStmtNewLine; + } + + /** + * set putStmtNewLine value. + * + * @param putStmtNewLine the new put stmt new line + */ + public void setPutStmtNewLine(boolean putStmtNewLine) { + this.putStmtNewLine = putStmtNewLine; + } + + /** + * Gets the last format type. + * + * @return the last format type + */ + public int getLastFormatType() { + return lastFormatType; + } + + /** + * Sets the last format type. + * + * @param lastFormatType the new last format type + */ + public void setLastFormatType(int lastFormatType) { + this.lastFormatType = lastFormatType; + } + + /** + * clone the data. + * + * @return the options process data + */ + public OptionsProcessData clone() { + + OptionsProcessData optData = new OptionsProcessData(); + optData.setOffSet(offSet); + optData.setParentOffSet(parentOffSet); + optData.setMaxKeywordLength(maxKeywordLength); + optData.setFormatItemsType(formatItemsType); + optData.setPutStmtNewLine(putStmtNewLine); + return optData; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/AbstractListProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/AbstractListProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..346eb07c63400d209c3585f4b3f3e88a4963d397 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/AbstractListProcessor.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TAbstractListItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; + +/** + * Title: AbstractListProcessor + * + * @since 3.0.0 + */ +public class AbstractListProcessor extends AbstractProcessor> { + + /** + * process + */ + public void process(TParseTreeNodeList columns, FmtOptionsIf options, OptionsProcessData pData) { + // in one line if possible need to find the + OptionsProcessData listParentData = pData.clone(); + + listParentData.setParentData(pData); + + // for single line + int itemsSize = columns.getResultList().size(); + + // for fit layout need to maintain running count + + for (int itemIndex = 0; itemIndex < itemsSize; itemIndex++) { + + beforeItemProcess(pData, listParentData); + + TAbstractListItem tAbstractListItem = (TAbstractListItem) columns.getResultList().get(itemIndex); + + addListItemListener(tAbstractListItem); + + TParseTreeNode startNode = tAbstractListItem.getStartNode(); + + iterateAndParseNodes(options, listParentData, startNode); + + } + + // set the current run data to parent from child + pData.setOffSet(listParentData.getOffSet()); + + } + + /** + * process before item + * + * @param pData options data to process + * @param currentData current options data to process + */ + protected void beforeItemProcess(OptionsProcessData pData, OptionsProcessData currentData) { + + } + + /** + * add listener + * + * @param tAbstractListItem list item to which listeners to be added + */ + protected void addListItemListener(TAbstractListItem tAbstractListItem) { + + } + + @Override + public TParseTreeNode getStartNode(TParseTreeNodeList selectAstNode) { + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/AbstractProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/AbstractProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..c807cf1bc340219c14b49e0253df86afb8676e43 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/AbstractProcessor.java @@ -0,0 +1,216 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.utils.StmtKeywordAlignUtil; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * Title: AbstractProcessor + * + * @param the element type + * @since 3.0.0 + */ +public abstract class AbstractProcessor { + + private FmtOptionsIf options = null; + + /** + * before process. + * + * @param node node to format + */ + public void beforeProcess(E node) { + } + + /** + * after process. + * + * @param node node to be formatted + * @param clonedOptData options data to format + */ + public void afterProcess(E node, OptionsProcessData clonedOptData) { + } + + /** + * return formatter options. + * + * @return formatter options + */ + public FmtOptionsIf getOptions() { + return options; + } + + /** + * set formatter options. + * + * @param options formatter options + */ + public void setOptions(FmtOptionsIf options) { + this.options = options; + } + + /** + * process the data. + * + * @param selectAstNode selected node to process + * @param options for process + * @param pData options data while process + */ + public void process(E selectAstNode, FmtOptionsIf options, OptionsProcessData pData) { + process(selectAstNode, options, pData, true); + } + + /** + * process the data. + * + * @param selectAstNode selected node to process + * @param options for process + * @param pData options data while process + * @param addPreSpace add prespace before process + */ + public void process(E selectAstNode, FmtOptionsIf options, OptionsProcessData pData, boolean addPreSpace) { + OptionsProcessData clonedOptData = getOptionsProcessData(selectAstNode, pData, options); + + TParseTreeNode nextNode = getStartNode(selectAstNode); + + iterateAndParseNodes(options, clonedOptData, nextNode, addPreSpace); + } + + /** + * iterate parseTree node and do parsing. + * + * @param options for process + * @param clonedOptData options data while process + * @param startNode to process + */ + protected void iterateAndParseNodes(FmtOptionsIf options, OptionsProcessData clonedOptData, + TParseTreeNode startNode) { + iterateAndParseNodes(options, clonedOptData, startNode, true); + } + + /** + * iterate parseTree node and do parsing. + * + * @param options for process + * @param clonedOptData options data while process + * @param startNode selected node to process + * @param addPreSpace add prespace before process + */ + protected void iterateAndParseNodes(FmtOptionsIf options, OptionsProcessData clonedOptData, + TParseTreeNode startNode, boolean addPreSpace) { + TParseTreeNode nextNode = startNode; + while (null != nextNode) { + // process the node + if (null != nextNode.getFormatListener()) { + + nextNode.getFormatListener().formatProcess(nextNode, options, + isCloneData() ? clonedOptData.clone() : clonedOptData); + + } else { + AbstractProcessorUtils.processParseTreeNode(nextNode, options, + isCloneData() ? clonedOptData.clone() : clonedOptData, addPreSpace); + + } + + nextNode = nextNode.getNextNode(); + } + + } + + /** + * return true is data is cloned. + * + * @return true, if is clone data + */ + public boolean isCloneData() { + return false; + } + + /** + * return options of proceesed data. + * + * @param selectAstNode selected node to process + * @param pData options data while process + * @param options options for format + * @return returns the options data + */ + public OptionsProcessData getOptionsProcessData(E selectAstNode, OptionsProcessData pData, FmtOptionsIf options) { + return pData; + } + + /** + * return start node. + * + * @param selectAstNode the select ast node + * @return the start node + */ + public abstract TParseTreeNode getStartNode(E selectAstNode); + + /** + * add listener to format process. + * + * @param parseNode node to process + * @param processListener listers to add to prase node + */ + protected void addFormatProcessListener(TParseTreeNode parseNode, IFormarProcessorListener processListener) { + if (null != parseNode) { + parseNode.setFormatListener(processListener); + } + } + + /** + * return keyword with max length. + * + * @param selectAstNode node to process + * @param options otpions for format + * @return the max keyword width + */ + protected int getMaxKeywordWidth(TCustomSqlStatement selectAstNode, FmtOptionsIf options) { + return StmtKeywordAlignUtil.getMaxKeywordWidth(selectAstNode, options); + } + + /** + * process data. + * + * @param pData options data while process + * @param maxKeywordWidth max width to format + * @return the new options data bean + */ + protected OptionsProcessData getNewOptionsDataBean(OptionsProcessData pData, int maxKeywordWidth) { + OptionsProcessData lOptionsProcessData = new OptionsProcessData(); + + lOptionsProcessData.setMaxKeywordLength(maxKeywordWidth); + lOptionsProcessData.setOffSet(pData.getOffSet()); + lOptionsProcessData.setParentOffSet(pData.getParentOffSet()); + lOptionsProcessData.setPutStmtNewLine(pData.isPutStmtNewLine()); + return lOptionsProcessData; + } + + /** + * set option process data. + * + * @param clonedOptData options data while process + */ + protected void setOptionsProcessData(OptionsProcessData clonedOptData) { + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/AbstractProcessorUtils.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/AbstractProcessorUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..78c4d9d4eb90bfa9c8f071dac8438e30b5cc4d07 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/AbstractProcessorUtils.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * Title: ProcessorUtils + * + * @since 3.0.0 + */ +public class AbstractProcessorUtils { + + /** + * process parseTree node. + * + * @param nextNode the next node + * @param options the options + * @param clonedOptData the cloned opt data + */ + public static void processParseTreeNode(TParseTreeNode nextNode, FmtOptionsIf options, + OptionsProcessData clonedOptData) { + processParseTreeNode(nextNode, options, clonedOptData, true); + } + + /** + * process parseTree node. + * + * @param nextNode the next node + * @param options the options + * @param clonedOptData the cloned opt data + * @param addPreSpace the add pre space + */ + public static void processParseTreeNode(TParseTreeNode nextNode, FmtOptionsIf options, + OptionsProcessData clonedOptData, boolean addPreSpace) { + AbstractProcessor processor = ProcessorFactory.getProcessor(nextNode); + if (null != processor) { + processor.setOptions(options); + processor.setOptionsProcessData(clonedOptData); + processor.beforeProcess(nextNode); + processor.process(nextNode, options, clonedOptData, addPreSpace); + processor.afterProcess(nextNode, clonedOptData); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/AlignColumnsParameter.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/AlignColumnsParameter.java new file mode 100644 index 0000000000000000000000000000000000000000..29255f4487094ff239e93674d7df2736523d9211 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/AlignColumnsParameter.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor; + +/** + * Title: AlignColumnsParameter + * + * @since 3.0.0 + */ +public class AlignColumnsParameter { + private boolean expContainStmt; + + private int runningSize; + + private int itemsSize; + + public AlignColumnsParameter(boolean expContainStmt, int runningSize, int itemsSize) { + this.expContainStmt = expContainStmt; + this.runningSize = runningSize; + this.itemsSize = itemsSize; + } + + public boolean isExpContainStmt() { + return expContainStmt; + } + + public void setExpContainStmt(boolean expContainStmt) { + this.expContainStmt = expContainStmt; + } + + public int getRunningSize() { + return runningSize; + } + + public void setRunningSize(int runningSize) { + this.runningSize = runningSize; + } + + public int getItemsSize() { + return itemsSize; + } + + public void setItemsSize(int itemsSize) { + this.itemsSize = itemsSize; + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/ColumnlistColonProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/ColumnlistColonProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..234f5ce0e989a692259d690ef237b692305ddd34 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/ColumnlistColonProcessor.java @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor; + +import java.util.List; + +import org.opengauss.mppdbide.gauss.format.consts.ListItemOptionsEnum; +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpressionNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TListItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; + +/** + * Title: ColumnlistColonProcessor + * + * @since 3.0.0 + */ +public class ColumnlistColonProcessor extends ColumnlistCommaProcessor { + /** + * handle one item per line + */ + protected int handleOneItemPerLine(FmtOptionsIf options, HandleOneItemPerLineParameter parameterObject, + TListItem parseTreeNode) { + int runningSize = parameterObject.getRunningSize(); + if (null != getSeperator(parseTreeNode) && !parameterObject.isLastIndex()) { + ProcessorUtils.addNewLineAfter(getSeperator(parseTreeNode), parameterObject.getOffset() + 1, options); + runningSize = parameterObject.getOffset() + 1; + + } + return runningSize; + } + + /** + * return seperator for parseTree node + * + * @param parseTreeNode list item to which seperatoe to handle + * @return returns the node which is seperator + */ + protected TParseTreeNode getSeperator(TListItem parseTreeNode) { + return null != parseTreeNode.getSeperator() ? parseTreeNode.getSeperator() + : (null != parseTreeNode.getEndNode() ? parseTreeNode.getEndNode() : parseTreeNode.getItemListNode()); + } + + /** + * return true if there is only one item per line + */ + protected boolean isOneItemPerLine(ListItemOptionsEnum itemOption, TListItem parseTreeNode) { + return ListItemOptionsEnum.ONEITEMPERLINE == itemOption; + } + + /** + * Gets the item option. + * + * @param columns the columns + * @param options the options + * @param pData the data + * @param expContainStmt the exp contain stmt + * @return the item option + */ + protected ListItemOptionsEnum getItemOption(TParseTreeNodeList columns, FmtOptionsIf options, + OptionsProcessData pData, boolean expContainStmt) { + return ListItemOptionsEnum.ONEITEMPERLINE; + } + + /** + * return true is columns are aligned + * + * @param options the options + * @param pData the data + * @param parameterObject combined object to pass the parameters + * @param itemOption the item option + * @return true is columns are aligned + */ + protected boolean isAlignColumns(FmtOptionsIf options, OptionsProcessData pData, + AlignColumnsParameter parameterObject, ListItemOptionsEnum itemOption) { + return options.isAlignDeclaration(); + } + + /** + * Gets the item size. + * + * @param runningSize the running size + * @param pDataClone the data clone + * @param expContainStmt the exp contain stmt + * @param parseNode the parse node + * @return the item size + */ + protected int getItemSize(int runningSize, OptionsProcessData pDataClone, boolean expContainStmt, + TParseTreeNode parseNode) { + if (expContainStmt) { + if (parseNode instanceof TExpression) { + TExpression stmtExpression = (TExpression) parseNode; + List expList = stmtExpression.getExpList(); + for (TExpressionNode expNode : expList) { + TParseTreeNode customStmt = expNode.getCustomStmt(); + if (null != customStmt && customStmt instanceof TCustomSqlStatement) { + return 0; + } + } + } + } + return pDataClone.getOffSet() - runningSize; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/ColumnlistCommaProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/ColumnlistCommaProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..14355885393cc97bb5a9092df378d77eab985767 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/ColumnlistCommaProcessor.java @@ -0,0 +1,423 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor; + +import org.opengauss.mppdbide.gauss.format.consts.FormatItemsType; +import org.opengauss.mppdbide.gauss.format.consts.ListItemOptionsEnum; +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.format.utils.FormatterUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TListItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; + +/** + * Title: ColumnlistCommaProcessor + * + * @since 3.0.0 + */ +public class ColumnlistCommaProcessor extends AbstractProcessor> { + + private boolean addPreSpace = true; + private boolean semiColonList = false; + + /** + * return true if SemiColonList is there. + * + * @return true, if SemiColonList is there. + */ + public boolean isSemiColonList() { + return semiColonList; + } + + /** + * sets the SemiColonList + * + * @param semiColonList the semicolon list + */ + public void setSemiColonList(boolean semiColonList) { + this.semiColonList = semiColonList; + } + + /** + * return true if pre added space are there. + * + * @return true, if is adds the pre space + */ + public boolean isAddPreSpace() { + return addPreSpace; + } + + /** + * set prePreSpace flag. + * + * @param addPreSpace the new adds the pre space + */ + public void setAddPreSpace(boolean addPreSpace) { + this.addPreSpace = addPreSpace; + } + + /** + * process data. + * + * @param columns the columns + * @param options the options + * @param pData the data + */ + @Override + public void process(TParseTreeNodeList columns, FmtOptionsIf options, OptionsProcessData pData) { + // in one line if possible need to find the + int offset = pData.getOffSet(); + boolean expContainStmt = columns.isExpContainStmt(); + + ListItemOptionsEnum itemOption = getItemOption(columns, options, pData, expContainStmt); + + int maxNodeItemLength = 0; + + boolean commaAfterItem = getCommanAfterItem(itemOption, pData.getFormatItemsType()); + + // for single line + + int itemsSize = columns.getResultList().size(); + + offset -= (addPreSpace == false ? 1 : 0); + // for fit layout need to maintain running count + int runningSize = offset; + + OptionsProcessData pDataClone = pData.clone(); + + for (int itemIndex = 0; itemIndex < itemsSize; itemIndex++) { + + TListItem parseTreeNode = columns.getResultList().get(itemIndex); + boolean isLastIndex = itemIndex == itemsSize - 1; + + runningSize += getStartIndexSize(itemIndex); + + if (isAddPreEmptySpace(commaAfterItem, itemIndex)) { + parseTreeNode.getItemListNode().addPreText(" "); + runningSize++; + } + + pDataClone.setOffSet(runningSize); + + TParseTreeNode parseNode = parseTreeNode.getItemListNode(); + + checkAndProcessExpression(options, pDataClone, parseNode); + + int itemSize = getItemSize(runningSize, pDataClone, expContainStmt, parseNode); + + if (maxNodeItemLength < itemSize) { + maxNodeItemLength = itemSize; + } + + runningSize = processAsAndEndNode(options, runningSize, pDataClone, parseTreeNode, offset); + + // add new line char + if (ListItemOptionsEnum.FIT == itemOption) { + runningSize = handleFitOption(options, offset, runningSize, parseTreeNode, itemSize); + } else if (isOneItemPerLine(itemOption, parseTreeNode)) { + runningSize = handleOneItemPerLine(options, + new HandleOneItemPerLineParameter(offset, commaAfterItem, runningSize, isLastIndex), + parseTreeNode); + } else { + runningSize = addSeparatorLength(runningSize, parseTreeNode); + } + } + + handleOneItemPerLine(columns, options, + new OneItemPerLineParameter(offset, commaAfterItem, itemsSize, runningSize), itemOption); + + if (isAlignColumns(options, pData, new AlignColumnsParameter(expContainStmt, runningSize, itemsSize), + itemOption)) { + for (int itemIndex = 0; itemIndex < itemsSize; itemIndex++) { + TListItem parseTreeNode = columns.getResultList().get(itemIndex); + + if (null == parseTreeNode.getAs() && null == parseTreeNode.getEndNode()) { + continue; + } + addPostTextAlignColumn(options, maxNodeItemLength, commaAfterItem, itemIndex, parseTreeNode); + } + } + } + + /** + * Gets the item size. + * + * @param runningSize current size of the process + * @param pDataClone options data while process + * @param expContainStmt to know that expression contain stmt or nor + * @param parseNode node to process + * @return the item size + * @apiNote getItemSize + */ + protected int getItemSize(int runningSize, OptionsProcessData pDataClone, boolean expContainStmt, + TParseTreeNode parseNode) { + return pDataClone.getOffSet() - runningSize; + } + + private void addPostTextAlignColumn(FmtOptionsIf options, int maxNodeItemLength, boolean commaAfterItem, + int itemIndex, TListItem parseTreeNode) { + StringBuilder lsb = new StringBuilder(10); + ProcessorUtils.fillSBWithIndendationChars( + getIndendChars(maxNodeItemLength, commaAfterItem, itemIndex, parseTreeNode, options), lsb, options); + + parseTreeNode.getItemListNode().addPostText(lsb.toString()); + } + + private int handleFitOption(FmtOptionsIf options, int offset, int runningSize, TListItem parseTreeNode, + int itemSize) { + if (runningSize >= getOptions().getRightMargin()) { + // REMOVE last character which is there as part ofr + // isAddPreEmpty space + ProcessorUtils.addNewLineBefore(parseTreeNode.getItemListNode(), offset + 1, options); + runningSize = offset + 1 + itemSize; + } + runningSize = addSeparatorLength(runningSize, parseTreeNode); + return runningSize; + } + + /** + * handle one item per line. + * + * @param options the options + * @param parameterObject combined parameter object to pass + * @param parseTreeNode the parse tree node + * @return the int + */ + protected int handleOneItemPerLine(FmtOptionsIf options, HandleOneItemPerLineParameter parameterObject, + TListItem parseTreeNode) { + int runningSize = parameterObject.getRunningSize(); + if (null != parseTreeNode.getSeperator()) { + if (!parameterObject.isCommaAfterItem()) { + ProcessorUtils.addNewLineBefore(parseTreeNode.getSeperator(), parameterObject.getOffset(), options); + runningSize = parameterObject.getOffset() + getNodeTextLength(parseTreeNode); + } else { + ProcessorUtils.addNewLineAfter(parseTreeNode.getSeperator(), parameterObject.getOffset(), options); + runningSize = parameterObject.getOffset(); + } + } + return runningSize; + } + + private int getStartIndexSize(int itemIndex) { + return itemIndex == 0 && !addPreSpace ? 1 : 0; + } + + private int addSeparatorLength(int runningSize, TListItem parseTreeNode) { + if (null != parseTreeNode.getSeperator()) { + runningSize += getNodeTextLength(parseTreeNode); + } + return runningSize; + } + + /** + * return length of Node text. + * + * @param parseTreeNode the parse tree node + * @return the node text length + */ + protected int getNodeTextLength(TListItem parseTreeNode) { + return parseTreeNode.getSeperator().getNodeText().length(); + } + + /** + * return true is columns are aligned. + * + * @param options the options + * @param pData the data + * @param parameterObject combined object to pass the parameters + * @param itemOption the item option + * @return true is columns are aligned + */ + protected boolean isAlignColumns(FmtOptionsIf options, OptionsProcessData pData, + AlignColumnsParameter parameterObject, ListItemOptionsEnum itemOption) { + return !parameterObject.isExpContainStmt() && options.isAlign(pData.getFormatItemsType()) + && (ListItemOptionsEnum.ONEITEMPERLINE == itemOption + || (ListItemOptionsEnum.ONLINEIFPOSSIBLE == itemOption && isOneLineIfPossible(itemOption, + parameterObject.getRunningSize(), parameterObject.getItemsSize()))); + } + + private void handleOneItemPerLine(TParseTreeNodeList columns, FmtOptionsIf options, + OneItemPerLineParameter parameterObject, ListItemOptionsEnum itemOption) { + if (ListItemOptionsEnum.ONLINEIFPOSSIBLE == itemOption) { + if (isOneLineIfPossible(itemOption, parameterObject.getRunningSize(), parameterObject.getItemsSize())) { + for (int itemIndex = 0; itemIndex < parameterObject.getItemsSize(); itemIndex++) { + TListItem parseTreeNode = columns.getResultList().get(itemIndex); + if (null != parseTreeNode.getSeperator()) { + if (!parameterObject.isCommaAfterItem()) { + ProcessorUtils.addNewLineBefore(parseTreeNode.getSeperator(), parameterObject.getOffset(), + options); + } else { + ProcessorUtils.addNewLineAfter(parseTreeNode.getSeperator(), parameterObject.getOffset(), + options); + } + } + } + } else { + if (!parameterObject.isCommaAfterItem()) { + for (int itemIndex = 0; itemIndex < parameterObject.getItemsSize(); itemIndex++) { + TListItem parseTreeNode = columns.getResultList().get(itemIndex); + if (0 != itemIndex) { + parseTreeNode.getItemListNode().addPreText(" "); + } + } + } + } + } + + } + + private int getIndendChars(int maxNodeItemLength, boolean commaAfterItem, int itemIndex, TListItem parseTreeNode, + FmtOptionsIf options) { + return maxNodeItemLength + (isAddPreEmptySpace(commaAfterItem, itemIndex) ? 1 : 0) + - FormatterUtils.getFormatString(parseTreeNode.getItemListNode(), options).length(); + } + + private boolean isOneLineIfPossible(ListItemOptionsEnum itemOption, int runningSize, int itemsSize) { + + return Math.max(itemsSize - 1, 0) + runningSize >= getOptions().getRightMargin(); + } + + /** + * return true if there is only one item per line. + * + * @param itemOption the item option + * @param parseTreeNode the parse tree node + * @return true, if is one item per line + */ + protected boolean isOneItemPerLine(ListItemOptionsEnum itemOption, TListItem parseTreeNode) { + return ListItemOptionsEnum.ONEITEMPERLINE == itemOption && null != parseTreeNode.getSeperator(); + } + + private boolean isAddPreEmptySpace(boolean commaAfterItem, int itemIndex) { + // for first item + // case 1 : addPreSpace is true + + // for other items + // case 1 : commaAfterItem is true and one item per line + + if (semiColonList) { + return false; + } + + if (itemIndex == 0) { + if (this.addPreSpace) { + return true; + } + } else if (commaAfterItem) { + return true; + } + return false; + } + + /** + * process As and End node. + * + * @param options format configured options + * @param runningSize for process + * @param pDataClone data for options + * @param parseTreeNode node to process + * @param offset to process + * @return returns the runningSize + */ + protected int processAsAndEndNode(FmtOptionsIf options, int runningSize, OptionsProcessData pDataClone, + TListItem parseTreeNode, int offset) { + int retRunningSize = runningSize; + retRunningSize = pDataClone.getOffSet(); + if (null != parseTreeNode.getAs()) { + parseTreeNode.getAs().addPreText(" "); + retRunningSize += parseTreeNode.getAs().getNodeText().length() + 1; + } + + retRunningSize = processEndNode(options, retRunningSize, pDataClone, parseTreeNode, offset); + return retRunningSize; + } + + /** + * process End node. + * + * @param options format configured options + * @param runningSize for process + * @param pDataClone data for options + * @param parseTreeNode node to process + * @param offset to process + * @return the int + */ + protected int processEndNode(FmtOptionsIf options, int runningSize, OptionsProcessData pDataClone, + TListItem parseTreeNode, int offset) { + if (null != parseTreeNode.getEndNode()) { + parseTreeNode.getEndNode().addPreText(" "); + runningSize++; + pDataClone.setOffSet(runningSize); + ExpressionProcessor lExpressionProcessor = new ExpressionProcessor(); + lExpressionProcessor.process((TExpression) parseTreeNode.getEndNode(), options, pDataClone); + + runningSize = pDataClone.getOffSet(); + } + return runningSize; + } + + private void checkAndProcessExpression(FmtOptionsIf options, OptionsProcessData pDataClone, + TParseTreeNode parseNode) { + ExpressionProcessor lExpressionProcessor = new ExpressionProcessor(); + if (parseNode instanceof TExpression) { + lExpressionProcessor.process((TExpression) parseNode, options, pDataClone); + } + } + + /** + * Gets the item option. + * + * @param columns the columns + * @param options the options + * @param pData the data + * @param expContainStmt the exp contain stmt + * @return the item option + */ + protected ListItemOptionsEnum getItemOption(TParseTreeNodeList columns, FmtOptionsIf options, + OptionsProcessData pData, boolean expContainStmt) { + ListItemOptionsEnum itemOption = options.getItemOption(pData.getFormatItemsType()); + + if (expContainStmt) { + itemOption = ListItemOptionsEnum.ONEITEMPERLINE; + } + return itemOption; + } + + private boolean getCommanAfterItem(ListItemOptionsEnum itemOption, FormatItemsType formatOptType) { + boolean commaAfterItem = getOptions().getCommaAfteritem(formatOptType); + + if (itemOption == ListItemOptionsEnum.FIT || itemOption == ListItemOptionsEnum.ONELINE) { + commaAfterItem = true; + } + + return commaAfterItem; + } + + /** + * return start node. + * + * @param selectAstNode the select ast node + * @return the start node + */ + @Override + public TParseTreeNode getStartNode(TParseTreeNodeList selectAstNode) { + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/ExpressionProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/ExpressionProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..41c772392a7329841dcbe7a20786a989c0045f31 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/ExpressionProcessor.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor; + +import java.util.List; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpressionNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * Title: ExpressionProcessor + * + * @since 3.0.0 + */ +public class ExpressionProcessor extends AbstractProcessor { + + /** + * process. + * + * @param selectAstNode the select ast node + * @param options the options + * @param pData the data + */ + @Override + public void process(TExpression selectAstNode, FmtOptionsIf options, OptionsProcessData pData) { + process(selectAstNode, options, pData, true); + } + + /** + * process. + * + * @param selectAstNode the select ast node + * @param options the options + * @param pData the data + * @param addPreSpace the add pre space + */ + @Override + public void process(TExpression selectAstNode, FmtOptionsIf options, OptionsProcessData pData, + boolean addPreSpace) { + List expList = selectAstNode.getExpList(); + int itemsSize = expList.size(); + + String prePreText = null; + String pretext = null; + String currenttext = null; + + for (int itemIndex = 0; itemIndex < itemsSize; itemIndex++) { + + TExpressionNode expNode = expList.get(itemIndex); + + if (null == expNode.getCustomStmt()) { + if (expNode.getExpNode().getNodeText() == null) { + continue; + } + + currenttext = expNode.getExpNode().getNodeText(); + + if (itemIndex == 0) { + prePreText = pretext; + pretext = expNode.getExpNode().getNodeText(); + pData.addOffSet(expNode.getExpNode().getNodeText().length()); + continue; + } + + handleExprNodeFormat(pData, prePreText, pretext, currenttext, expNode, options); + + prePreText = pretext; + pretext = expNode.getExpNode().getNodeText(); + + } else { + + boolean putStmtNewLine = pData.isPutStmtNewLine(); + if (selectAstNode.isDirectExpression()) { + pData.setPutStmtNewLine(true); + } else { + pData.setPutStmtNewLine(false); + if (selectAstNode.getAddSpaceForCustomStmt()) { + pData.addOffSet(1); + expNode.addPreText(" "); + } + } + + processExpressionCustomStmt(options, pData, expNode); + + pData.setPutStmtNewLine(putStmtNewLine); + + pretext = null; + prePreText = null; + } + + } + + } + + /** + * handle each ExprNode Format + * + * @param pData the data + * @param prePreText previous previous text + * @param pretext previous text + * @param currenttext current text + * @param expNode the exp node + * @param options the options + */ + protected void handleExprNodeFormat(OptionsProcessData pData, String prePreText, String pretext, String currenttext, + TExpressionNode expNode, FmtOptionsIf options) { + pData.addOffSet(expNode.getExpNode().getNodeText().length()); + if (!(ExpressionProcessorUtil.isAppendNoPreTextSpace(currenttext, pretext, prePreText))) { + ProcessorUtils.addPreEmptyText(expNode.getExpNode(), pData); + } + } + + /** + * process expression for custom statement. + * + * @param options the options + * @param pData the data + * @param expNode the exp node + */ + protected void processExpressionCustomStmt(FmtOptionsIf options, OptionsProcessData pData, + TExpressionNode expNode) { + AbstractProcessorUtils.processParseTreeNode(expNode.getCustomStmt(), options, pData); + } + + /** + * return start node. + * + * @param selectAstNode the select ast node + * @return the start node + */ + @Override + public TParseTreeNode getStartNode(TExpression selectAstNode) { + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/ExpressionProcessorUtil.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/ExpressionProcessorUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..1f30fd24b55d77bbd8f60d188ce71ab642ceecbe --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/ExpressionProcessorUtil.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.lang.math.NumberUtils; + +/** + * Title: ExpressionProcessorUtil + * + * @since 3.0.0 + */ +public class ExpressionProcessorUtil { + + private static Set currentTextSet = new HashSet<>(Arrays.asList(".", "(", ",", ")", ";", "|")); + + private static Set preTextSet = new HashSet<>(Arrays.asList(".", "(", "|")); + + private static Set relationoperator = new HashSet<>(Arrays.asList("<", ">", "=")); + + private static Map> currentPreTextMap = new HashMap<>(10); + + static { + currentPreTextMap.put("=", Arrays.asList(":", ">", "<")); + currentPreTextMap.put("<", Arrays.asList("=", ">")); + currentPreTextMap.put(">", Arrays.asList("=", "<")); + currentPreTextMap.put("!", Arrays.asList("=")); + currentPreTextMap.put(":", Arrays.asList("=", ":")); + currentPreTextMap.put("|", Arrays.asList("|")); + + } + + /** + * return true if no space appended + * + * @param currenttext current text to compare + * @param preText pretext to compare + * @param prePreText prePretext to compare + * @return true if no space appended + */ + public static boolean isAppendNoPreTextSpace(String currenttext, String preText, String prePreText) { + if (isCurrentTextNoSapce(currenttext) || isPreTextNoSapce(preText)) { + return true; + } else { + List crrMap = currentPreTextMap.get(currenttext); + if (null != crrMap) { + return crrMap.contains(preText); + } + + // check for pre pre text + if ("$".equals(preText)) { + return true; + } + + if (("-".equals(preText) || "+".equals(preText)) && NumberUtils.isNumber(currenttext) + && relationoperator.contains(prePreText)) { + return true; + } + } + return false; + } + + private static boolean isCurrentTextNoSapce(String currenttext) { + if (currentTextSet.contains(currenttext)) { + return true; + } + return false; + } + + private static boolean isPreTextNoSapce(String preText) { + if (preTextSet.contains(preText)) { + return true; + } + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/FullStatementProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/FullStatementProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..e1154ec8e2b3ea16a014d890a365b3db56ae3e47 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/FullStatementProcessor.java @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor; + +import java.util.List; +import java.util.ListIterator; + +import org.apache.commons.lang3.StringUtils; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.utils.FullNodeExpressionType; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.fullstmt.TFullListNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.fullstmt.TFullStmt; +import org.opengauss.mppdbide.gauss.sqlparser.stmtbeanif.StatementBeanIf; + +/** + * Title: ExpressionProcessor + * + * @since 3.0.0 + */ +public class FullStatementProcessor extends AbstractProcessor { + + @Override + public void process(TFullStmt selectAstNode, FmtOptionsIf options, OptionsProcessData pData) { + process(selectAstNode, options, pData, true); + } + + @Override + public void process(TFullStmt selectAstNode, FmtOptionsIf options, OptionsProcessData pData, boolean addPreSpace) { + List stmtList = selectAstNode.getStmtList(); + + // iterate all the assignment variables and find the offset for + // alignment + + processAssignmentStmt(stmtList, options); + + int itemsSize = stmtList.size(); + for (int itemIndex = 0; itemIndex < itemsSize; itemIndex++) { + TParseTreeNode fullStmtNode = stmtList.get(itemIndex); + + OptionsProcessData optionsCloneData = pData.clone(); + optionsCloneData.setOffSet(pData.getParentOffSet() + options.getIndend()); + if (fullStmtNode instanceof TCustomSqlStatement) { + AbstractProcessorUtils.processParseTreeNode((TCustomSqlStatement) fullStmtNode, options, + optionsCloneData); + } else if (fullStmtNode instanceof TFullStmt) { + AbstractProcessorUtils.processParseTreeNode((TFullStmt) fullStmtNode, options, optionsCloneData); + } else if (fullStmtNode instanceof TFullListNode) { + TFullListNode lTFullListNode = (TFullListNode) fullStmtNode; + + // remove blank new line from backwards direction + + handleLastEmptyNewlineCharacters(lTFullListNode, lTFullListNode.getSqlTokenDataList().size()); + + if (lTFullListNode.getExpressionType() != FullNodeExpressionType.NEWLINES) { + ProcessorUtils.addNewLineBefore(lTFullListNode, optionsCloneData.getOffSet(), options); + } + + ListIterator listItems = lTFullListNode.getSqlTokenDataList().listIterator(); + + while (listItems.hasNext()) { + StatementBeanIf stmtBean = listItems.next(); + // calculate the offset and set to the TCustomSqlStatement + boolean putStmtNewLine = optionsCloneData.isPutStmtNewLine(); + if (stmtBean instanceof TCustomSqlStatement) { + // remove the above first newline character from the + removeTillLastNewLineBlankDataCustom(listItems, stmtBean); + + AbstractProcessorUtils.processParseTreeNode((TCustomSqlStatement) stmtBean, options, + optionsCloneData); + } else if (stmtBean instanceof TFullStmt) { + AbstractProcessorUtils.processParseTreeNode((TFullStmt) stmtBean, options, optionsCloneData); + } else { + // do nothing + } + optionsCloneData.setPutStmtNewLine(putStmtNewLine); + + } + } + } + } + + private void processAssignmentStmt(List stmtList, FmtOptionsIf options) { + if (!options.isAlignAssignment()) { + return; + } + int itemsSize = stmtList.size(); + int maxNodeItemLength = 0; + for (int itemIndex = 0; itemIndex < itemsSize; itemIndex++) { + TParseTreeNode fullStmtNode = stmtList.get(itemIndex); + if (fullStmtNode instanceof TFullListNode) { + TFullListNode lTFullListNode = (TFullListNode) fullStmtNode; + if (FullNodeExpressionType.ASSIGNMENTS == lTFullListNode.getExpressionType()) { + List sqlTokenDataList = lTFullListNode.getSqlTokenDataList(); + ListIterator listIterator = sqlTokenDataList.listIterator(); + + boolean firstNonEmpty = false; + while (listIterator.hasNext()) { + StatementBeanIf lastElement = listIterator.next(); + if (lastElement instanceof ISQLTokenData) { + String tokenStr = ((ISQLTokenData) lastElement).getTokenStr(); + if (StringUtils.isBlank(tokenStr)) { + listIterator.remove(); + continue; + } + if (!firstNonEmpty && !StringUtils.isBlank(tokenStr)) { + if (maxNodeItemLength < tokenStr.length()) { + maxNodeItemLength = tokenStr.length(); + } + firstNonEmpty = true; + } + if ("=".equals(tokenStr)) { + break; + } + } + } + } + } + } + alignAssignmentKeyWords(stmtList, options, itemsSize, maxNodeItemLength); + } + + private void alignAssignmentKeyWords(List stmtList, FmtOptionsIf options, int itemsSize, + int maxNodeItemLength) { + for (int itemIndex = 0; itemIndex < itemsSize; itemIndex++) { + TParseTreeNode fullStmtNode = stmtList.get(itemIndex); + if (fullStmtNode instanceof TFullListNode) { + TFullListNode lTFullListNode = (TFullListNode) fullStmtNode; + if (FullNodeExpressionType.ASSIGNMENTS == lTFullListNode.getExpressionType()) { + ListIterator listIterator = lTFullListNode.getSqlTokenDataList().listIterator(); + while (listIterator.hasNext()) { + StatementBeanIf lastElement = listIterator.next(); + if (lastElement instanceof ISQLTokenData) { + String tokenStr = ((ISQLTokenData) lastElement).getTokenStr(); + int paddingLength = tokenStr.length() < maxNodeItemLength + ? maxNodeItemLength - tokenStr.length() + : 0; + StringBuilder lsb = new StringBuilder(10); + ProcessorUtils.fillSBWithIndendationChars(paddingLength + 1, lsb, options); + ((ISQLTokenData) lastElement).setTokenStr(tokenStr + lsb.toString()); + break; + } + } + } + } + } + } + + private void removeTillLastNewLineBlankDataCustom(ListIterator listItems, + StatementBeanIf stmtBean) { + listItems.previous(); + removeTillLastNewLineBlankData(listItems); + while (listItems.hasNext()) { + if (stmtBean.equals(listItems.next())) { + break; + } + } + + } + + private void handleLastEmptyNewlineCharacters(TFullListNode lTFullListNode, int size) { + ListIterator listItems = lTFullListNode.getSqlTokenDataList().listIterator(size); + removeTillLastNewLineBlankData(listItems); + } + + private void removeTillLastNewLineBlankData(ListIterator listItems) { + while (listItems.hasPrevious()) { + StatementBeanIf lastElement = listItems.previous(); + if (lastElement instanceof ISQLTokenData) { + String tokenStr = ((ISQLTokenData) lastElement).getTokenStr(); + if (StringUtils.isBlank(tokenStr)) { + if (isLineSeparator(tokenStr)) { + // remove all the elements from here to end + removeAllElementsTillEnd(listItems); + break; + } + + } else { + break; + } + + } else { + break; + } + } + } + + private boolean isLineSeparator(String tokenStr) { + return null != tokenStr && (System.lineSeparator().equals(tokenStr) || tokenStr.equals("\n")); + } + + private void removeAllElementsTillEnd(ListIterator listItems) { + listItems.remove(); + while (listItems.hasNext()) { + StatementBeanIf next = listItems.next(); + if (next instanceof TCustomSqlStatement) { + listItems.previous(); + break; + } + + listItems.remove(); + } + } + + @Override + public TParseTreeNode getStartNode(TFullStmt selectAstNode) { + return null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/FullStmtCTEExpressionProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/FullStmtCTEExpressionProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..f013e1d5bb6b873b348e9e6841bfee438a1317ff --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/FullStmtCTEExpressionProcessor.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.debugobj.TCreateSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpressionNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * Title: FullStmtCTEExpressionProcessor + * + * @since 3.0.0 + */ +public class FullStmtCTEExpressionProcessor extends ExpressionProcessor { + /** + * process expression with custom statement + */ + protected void processExpressionCustomStmt(FmtOptionsIf options, OptionsProcessData pData, + TExpressionNode expNode) { + OptionsProcessData clone = pData.clone(); + TParseTreeNode customStmt = expNode.getCustomStmt(); + if (customStmt instanceof TCreateSqlStatement) { + clone.addOffSet(pData.getParentOffSet() + options.getIndend()); + } else { + clone.addOffSet(pData.getParentOffSet()); + } + AbstractProcessorUtils.processParseTreeNode(customStmt, options, clone); + } + + /** + * handle each ExprNode Format + * + * @param pData the data + * @param prePreText previous previous text + * @param pretext previous text + * @param currenttext current text + * @param expNode the exp node + * @param options the options + */ + protected void handleExprNodeFormat(OptionsProcessData pData, String prePreText, String pretext, String currenttext, + TExpressionNode expNode, FmtOptionsIf options) { + if ("end".equalsIgnoreCase(currenttext)) { + ProcessorUtils.addNewLineBefore(expNode, pData.getParentOffSet(), options); + } else { + super.handleExprNodeFormat(pData, prePreText, pretext, currenttext, expNode, options); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/HandleOneItemPerLineParameter.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/HandleOneItemPerLineParameter.java new file mode 100644 index 0000000000000000000000000000000000000000..4017e3d6fff1a812034e3f4e4d702690160cfc5a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/HandleOneItemPerLineParameter.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor; + +/** + * Title: HandleOneItemPerLineParameter + * + * @since 3.0.0 + */ +public class HandleOneItemPerLineParameter { + private int offset; + + private boolean commaAfterItem; + + private int runningSize; + + private boolean isLastIndex; + + public HandleOneItemPerLineParameter(int offset, boolean commaAfterItem, int runningSize, boolean isLastIndex) { + this.offset = offset; + this.commaAfterItem = commaAfterItem; + this.runningSize = runningSize; + this.isLastIndex = isLastIndex; + } + + public int getOffset() { + return offset; + } + + public void setOffset(int offset) { + this.offset = offset; + } + + public boolean isCommaAfterItem() { + return commaAfterItem; + } + + public void setCommaAfterItem(boolean commaAfterItem) { + this.commaAfterItem = commaAfterItem; + } + + public int getRunningSize() { + return runningSize; + } + + public void setRunningSize(int runningSize) { + this.runningSize = runningSize; + } + + public boolean isLastIndex() { + return isLastIndex; + } + + public void setLastIndex(boolean isLastIndex) { + this.isLastIndex = isLastIndex; + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/IfStmtConditionClauseProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/IfStmtConditionClauseProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..bff5f890e4972f1e5a335fbb1c2ba134dde1f798 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/IfStmtConditionClauseProcessor.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor; + +import org.opengauss.mppdbide.gauss.format.consts.FormatItemsType; +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; + +/** + * + * Title: WhereListOnClauseProcessor + * + * @since 3.0.0 + */ +public class IfStmtConditionClauseProcessor extends WhereListCommaProcessor { + + /** + * return true if and/or are under where + */ + protected boolean andOrUnderWhere(FmtOptionsIf options) { + return false; + } + + /** + * return true if and/or are after expr + */ + protected boolean andOrAfterExp(FmtOptionsIf options, OptionsProcessData pData) { + return options.andOrAfterExp(FormatItemsType.CONTROL_STRUCTURE); + } + + /** + * return true if can be split at zero level + */ + protected boolean splitAtZeroLevel(FmtOptionsIf options, OptionsProcessData pData) { + return options.splitAtZeroLevel(FormatItemsType.CONTROL_STRUCTURE); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/OneItemPerLineParameter.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/OneItemPerLineParameter.java new file mode 100644 index 0000000000000000000000000000000000000000..2b033ca1b8fb5c485eda613c0ebe1683c5b5c47e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/OneItemPerLineParameter.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor; + +/** + * Title: OneItemPerLineParameter + * + * @since 3.0.0 + */ +public class OneItemPerLineParameter { + private int offset; + + private boolean commaAfterItem; + + private int itemsSize; + + private int runningSize; + + public OneItemPerLineParameter(int offset, boolean commaAfterItem, int itemsSize, int runningSize) { + this.offset = offset; + this.commaAfterItem = commaAfterItem; + this.itemsSize = itemsSize; + this.runningSize = runningSize; + } + + public int getOffset() { + return offset; + } + + public void setOffset(int offset) { + this.offset = offset; + } + + public boolean isCommaAfterItem() { + return commaAfterItem; + } + + public void setCommaAfterItem(boolean commaAfterItem) { + this.commaAfterItem = commaAfterItem; + } + + public int getItemsSize() { + return itemsSize; + } + + public void setItemsSize(int itemsSize) { + this.itemsSize = itemsSize; + } + + public int getRunningSize() { + return runningSize; + } + + public void setRunningSize(int runningSize) { + this.runningSize = runningSize; + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/ProcessorFactory.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/ProcessorFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..64b0f62c2995deb861e12067e073acd0a38e2011 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/ProcessorFactory.java @@ -0,0 +1,246 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor; + +import java.util.HashMap; +import java.util.Map; + +import org.opengauss.mppdbide.gauss.format.processor.begin.BeginFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.begin.DeclareFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.begin.ast.BeginASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.begin.ast.DeclareASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.casestmt.CaseASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.casestmt.CaseStmtFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.common.CTEASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.common.ReturningASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.create.CreateFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.create.ast.AsASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.create.ast.CreateASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.create.ast.LanguageASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.create.ast.ReturnsASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.cursor.CursorStmtFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.cursor.ast.CursorStmtASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.delete.DeleteStmtFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.delete.ast.DeleteFromASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.delete.ast.DeleteUsingASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.forloop.ForLoopFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.forloop.ast.ForLoopASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.ifstmt.IfStmtFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.ifstmt.ast.IfStmtASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.insert.InsertStmtFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.insert.ast.InsertIntoASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.insert.ast.InsertValuesListASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.loop.LoopFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.loop.ast.LoopASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.merge.MergeStmtFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.merge.ast.MergeASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.merge.ast.MergeWithASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.node.SqlNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.select.FromASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.select.GroupByASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.select.HavingASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.select.LimitASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.select.OrderByASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.select.SelectASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.select.SelectStmtFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.select.WhereASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.select.WindowASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.union.UnionFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.union.ast.UnionASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.update.UpdateStmtFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.update.ast.UpdateIntoASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.update.ast.UpdateSetASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.with.WithASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.with.WithStmtFormatProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.begin.TBeginASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.begin.TDeclareASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.casestmt.TCaseASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.common.TCTEASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.common.TFromASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.common.TOrderByASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.common.TReturningASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.common.TWhereASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.create.TAsASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.create.TCreateASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.create.TLaungageASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.create.TReturnASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.cursor.TCursorASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.delete.TDeleteFromASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.delete.TDeleteUsingASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.forloop.TForLoopASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.ifstmt.TIfElseASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.insert.TInsertDefaultASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.insert.TInsertIntoASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.insert.TInsertValuesASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.limit.TLimitASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.limit.TOffsetASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.loop.TLoopASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.merge.TMergeASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.merge.TMergeWhenASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select.TFetchASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select.TForASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select.TGroupByASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select.THavingASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select.TSelectASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select.TWindowASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.union.TUnionASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.update.TUpdateIntoASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.update.TUpdateSetASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.with.TWithASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.block.TBeginSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.block.TDeclareSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.common.TUnionSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.condition.TCaseSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.condition.TIfElseSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.debugobj.TCreateSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.debugobj.TCursorSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml.TDeleteSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml.TInsertSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml.TMergeSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml.TSelectSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml.TUpdateSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml.TWithSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.loop.TForLoopSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.loop.TLoopSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TCTEExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.fullstmt.TFullStmt; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: ProcessorFactory + * + * @since 3.0.0 + */ +public class ProcessorFactory { + + private static Map processorMap = new HashMap<>(); + + static { + + processorMap.put(TSelectSqlStatement.class, SelectStmtFormatProcessor.class); + processorMap.put(TSelectASTNode.class, SelectASTNodeFormatProcessor.class); + processorMap.put(TLimitASTNode.class, LimitASTNodeFormatProcessor.class); + processorMap.put(TOrderByASTNode.class, OrderByASTNodeFormatProcessor.class); + processorMap.put(TGroupByASTNode.class, GroupByASTNodeFormatProcessor.class); + processorMap.put(THavingASTNode.class, HavingASTNodeFormatProcessor.class); + processorMap.put(TForASTNode.class, LimitASTNodeFormatProcessor.class); + processorMap.put(TOffsetASTNode.class, LimitASTNodeFormatProcessor.class); + processorMap.put(TFetchASTNode.class, LimitASTNodeFormatProcessor.class); + processorMap.put(TWindowASTNode.class, WindowASTNodeFormatProcessor.class); + + // insert process rules + processorMap.put(TInsertSqlStatement.class, InsertStmtFormatProcessor.class); + processorMap.put(TInsertIntoASTNode.class, InsertIntoASTNodeFormatProcessor.class); + processorMap.put(TInsertDefaultASTNode.class, AbstractASTNodeFormatProcessor.class); + processorMap.put(TInsertValuesASTNode.class, InsertValuesListASTNodeFormatProcessor.class); + + // delete process rules + processorMap.put(TDeleteSqlStatement.class, DeleteStmtFormatProcessor.class); + processorMap.put(TDeleteFromASTNode.class, DeleteFromASTNodeFormatProcessor.class); + processorMap.put(TDeleteUsingASTNode.class, DeleteUsingASTNodeFormatProcessor.class); + + // update process rules + processorMap.put(TUpdateSqlStatement.class, UpdateStmtFormatProcessor.class); + processorMap.put(TUpdateIntoASTNode.class, UpdateIntoASTNodeFormatProcessor.class); + processorMap.put(TUpdateSetASTNode.class, UpdateSetASTNodeFormatProcessor.class); + + // with process rules + processorMap.put(TWithSqlStatement.class, WithStmtFormatProcessor.class); + processorMap.put(TWithASTNode.class, WithASTNodeFormatProcessor.class); + + // case process rules + processorMap.put(TCaseSqlStatement.class, CaseStmtFormatProcessor.class); + processorMap.put(TCaseASTNode.class, CaseASTNodeFormatProcessor.class); + + // if stmt rules + processorMap.put(TIfElseSqlStatement.class, IfStmtFormatProcessor.class); + processorMap.put(TIfElseASTNode.class, IfStmtASTNodeFormatProcessor.class); + + // Loop rules + processorMap.put(TLoopSqlStatement.class, LoopFormatProcessor.class); + processorMap.put(TLoopASTNode.class, LoopASTNodeFormatProcessor.class); + + // Begin rules + processorMap.put(TBeginSqlStatement.class, BeginFormatProcessor.class); + processorMap.put(TBeginASTNode.class, BeginASTNodeFormatProcessor.class); + + processorMap.put(TDeclareSqlStatement.class, DeclareFormatProcessor.class); + processorMap.put(TDeclareASTNode.class, DeclareASTNodeFormatProcessor.class); + + // create stmt + processorMap.put(TCreateSqlStatement.class, CreateFormatProcessor.class); + processorMap.put(TCreateASTNode.class, CreateASTNodeFormatProcessor.class); + processorMap.put(TAsASTNode.class, AsASTNodeFormatProcessor.class); + processorMap.put(TLaungageASTNode.class, LanguageASTNodeFormatProcessor.class); + processorMap.put(TReturnASTNode.class, ReturnsASTNodeFormatProcessor.class); + + // loop stmt + processorMap.put(TForLoopSqlStatement.class, ForLoopFormatProcessor.class); + processorMap.put(TForLoopASTNode.class, ForLoopASTNodeFormatProcessor.class); + + // cursor stmt + processorMap.put(TCursorSqlStatement.class, CursorStmtFormatProcessor.class); + processorMap.put(TCursorASTNode.class, CursorStmtASTNodeFormatProcessor.class); + + // union stmt + processorMap.put(TUnionSqlStatement.class, UnionFormatProcessor.class); + processorMap.put(TUnionASTNode.class, UnionASTNodeFormatProcessor.class); + + // merge stmt + processorMap.put(TMergeSqlStatement.class, MergeStmtFormatProcessor.class); + processorMap.put(TMergeASTNode.class, MergeASTNodeFormatProcessor.class); + processorMap.put(TMergeWhenASTNode.class, MergeWithASTNodeFormatProcessor.class); + + // common sql rules + processorMap.put(TSqlNode.class, SqlNodeFormatProcessor.class); + processorMap.put(TExpression.class, ExpressionProcessor.class); + processorMap.put(TCTEExpression.class, FullStmtCTEExpressionProcessor.class); + processorMap.put(TCTEASTNode.class, CTEASTNodeFormatProcessor.class); + processorMap.put(TFromASTNode.class, FromASTNodeFormatProcessor.class); + processorMap.put(TWhereASTNode.class, WhereASTNodeFormatProcessor.class); + processorMap.put(TReturningASTNode.class, ReturningASTNodeFormatProcessor.class); + processorMap.put(TFullStmt.class, FullStatementProcessor.class); + + } + + /** + * abstract processor. + * + * @param startNode the start node + * @return the processor + */ + public static AbstractProcessor getProcessor(TParseTreeNode startNode) { + Class parseNodeClass = processorMap.get(startNode.getClass()); + + if (null == parseNodeClass) { + return null; + } + + AbstractProcessor processor = null; + try { + processor = (AbstractProcessor) parseNodeClass.newInstance(); + } catch (InstantiationException | IllegalAccessException e) { + MPPDBIDELoggerUtility.error("Exception occured while getting instance of parseNode class" + startNode); + + } + return processor; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/WhereListCommaProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/WhereListCommaProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..62cd5e66df3de14f02804820861f94c7f7e5255b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/WhereListCommaProcessor.java @@ -0,0 +1,214 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpressionNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TWhereListItem; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * Title: WhereListCommaProcessor + * + * @since 3.0.0 + */ +public class WhereListCommaProcessor extends AbstractProcessor> { + + /** + * process. + * + * @param columns the columns + * @param options the options + * @param pData the data + */ + @Override + public void process(TParseTreeNodeList columns, FmtOptionsIf options, OptionsProcessData pData) { + // in one line if possible need to find the + int offset = pData.getOffSet(); + int poffset = pData.getParentOffSet(); + + boolean spliAtZeroLevel = splitAtZeroLevel(options, pData); + + boolean andOrAfterExp = andOrAfterExp(options, pData); + + boolean andOrUnderWhere = andOrUnderWhere(options); + + boolean expContainStmt = isContainExpression(columns); + + if (expContainStmt) { + spliAtZeroLevel = true; + } + + // for single line + + int itemsSize = columns.getResultList().size(); + + ExpressionProcessor lExpressionProcessor = new ExpressionProcessor(); + + OptionsProcessData pDataClone = pData.clone(); + + // for fit layout need to maintain running count + int runningSize = offset; + + for (int itemIndex = 0; itemIndex < itemsSize; itemIndex++) { + + runningSize = processWhereList(columns, options, offset, poffset, spliAtZeroLevel, andOrAfterExp, + andOrUnderWhere, lExpressionProcessor, pDataClone, runningSize, itemIndex); + } + } + + private int processWhereList(TParseTreeNodeList columns, FmtOptionsIf options, int offset, + int poffset, boolean spliAtZeroLevel, boolean andOrAfterExp, boolean andOrUnderWhere, + ExpressionProcessor lExpressionProcessor, OptionsProcessData pDataClone, int runningSizeParam, + int itemIndex) { + int runningSize = runningSizeParam; + TWhereListItem parseTreeNode = columns.getResultList().get(itemIndex); + + parseTreeNode.getItemListNode().addPreText(" "); + runningSize++; + + pDataClone.setOffSet(runningSize); + + lExpressionProcessor.process((TExpression) parseTreeNode.getItemListNode(), options, pDataClone); + + runningSize = pDataClone.getOffSet(); + + TSqlNode conSep = parseTreeNode.getConSep(); + + if (spliAtZeroLevel && null != conSep) { + runningSize = splitAtZeroLevel(options, offset, poffset, andOrAfterExp, andOrUnderWhere, conSep); + } else { + if (null != conSep) { + conSep.addPreText(" "); + runningSize += offset + 1 + conSep.getNodeText().length(); + } + if (runningSize >= getOptions().getRightMargin()) { + ProcessorUtils.addNewLineAfter(parseTreeNode, offset, options); + runningSize = offset + 1; + } + } + return runningSize; + } + + private int splitAtZeroLevel(FmtOptionsIf options, int offset, int poffset, boolean andOrAfterExp, + boolean andOrUnderWhere, TSqlNode conSep) { + int runningSize; + if (andOrAfterExp) { + conSep.addPreText(" "); + ProcessorUtils.addNewLineAfter(conSep, offset, options); + runningSize = offset; + + } else { + conSep.addPreText(System.lineSeparator()); + + if (andOrUnderWhere) { + handleAndOrUnderWhere(options, offset, poffset, conSep); + runningSize = offset - poffset; + } else { + StringBuilder lsb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + ProcessorUtils.fillSBWithIndendationChars(offset, lsb, options); + conSep.addPreText(lsb.toString()); + conSep.addPreText(" "); + runningSize = offset + 1 + conSep.getNodeText().length(); + } + + } + return runningSize; + } + + /** + * handles and/or under where clause. + * + * @param options the options + * @param offset the offset + * @param poffset the poffset + * @param conSep the con sep + */ + protected void handleAndOrUnderWhere(FmtOptionsIf options, int offset, int poffset, TSqlNode conSep) { + int whereConOffSet = offset - poffset; + StringBuilder lsb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + ProcessorUtils.fillSBWithIndendationChars(poffset, lsb, options); + conSep.addPreText(lsb.toString()); + ProcessorUtils.formatStartNode(conSep, options, whereConOffSet); + } + + /** + * return true if and/or is under where. + * + * @param options the options + * @return true, if successful + */ + protected boolean andOrUnderWhere(FmtOptionsIf options) { + return options.andOrUnderWhere(); + } + + /** + * return true if and/or after expr. + * + * @param options the options + * @param pData the data + * @return true, if successful + */ + protected boolean andOrAfterExp(FmtOptionsIf options, OptionsProcessData pData) { + return options.andOrAfterExp(pData.getFormatItemsType()); + } + + /** + * return true if can be split at zero level. + * + * @param options the options + * @param pData the data + * @return true, if successful + */ + protected boolean splitAtZeroLevel(FmtOptionsIf options, OptionsProcessData pData) { + return options.splitAtZeroLevel(pData.getFormatItemsType()); + } + + private boolean isContainExpression(TParseTreeNodeList columns) { + boolean expContainStmt = false; + + for (TWhereListItem parseTreeNode : columns.getResultList()) { + + TParseTreeNode itemListNode = parseTreeNode.getItemListNode(); + if (itemListNode instanceof TExpression) { + + TExpression expr = (TExpression) itemListNode; + for (TExpressionNode expNode : expr.getExpList()) { + if (null != expNode.getCustomStmt()) { + return true; + } + } + } + + } + return expContainStmt; + } + + /** + * return start node + */ + @Override + public TParseTreeNode getStartNode(TParseTreeNodeList selectAstNode) { + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/WhereListOnClauseProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/WhereListOnClauseProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..520c0cf97ff33dcc8746af941c4bca6c08fd4413 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/WhereListOnClauseProcessor.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: WhereListOnClauseProcessor + * + * @since 3.0.0 + */ +public class WhereListOnClauseProcessor extends WhereListCommaProcessor { + + /** + * return true if and/or is under where + */ + protected boolean andOrUnderWhere(FmtOptionsIf options) { + return true; + } + + /** + * return true if and/or is after expr + */ + protected boolean andOrAfterExp(FmtOptionsIf options, OptionsProcessData pData) { + return false; + } + + /** + * return true if can be splited at zero level + */ + protected boolean splitAtZeroLevel(FmtOptionsIf options, OptionsProcessData pData) { + return true; + } + + /** + * handles and/or under where clause + */ + protected void handleAndOrUnderWhere(FmtOptionsIf options, int offset, int poffset, TSqlNode conSep) { + int whereConOffSet = poffset + offset - conSep.getNodeText().length(); + StringBuilder lsb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + ProcessorUtils.fillSBWithIndendationChars(whereConOffSet, lsb, options); + conSep.addPreText(lsb.toString()); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/WithColumnlistCommaProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/WithColumnlistCommaProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..71f67b6a4bdf1bf1b393e60c1ce00ddb57d8a744 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/WithColumnlistCommaProcessor.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor; + +import org.opengauss.mppdbide.gauss.format.consts.ListItemOptionsEnum; +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TListItem; + +/** + * Title: WithColumnlistCommaProcessor + * + * @since 3.0.0 + */ +public class WithColumnlistCommaProcessor extends ColumnlistCommaProcessor { + /** + * process end node + */ + protected int processEndNode(FmtOptionsIf options, int runningSize, OptionsProcessData pDataClone, + TListItem parseTreeNode, int offset) { + if (null != parseTreeNode.getEndNode()) { + pDataClone.setOffSet(offset + 1); + ProcessorUtils.addNewLineBeforeWithindent(parseTreeNode.getEndNode(), pDataClone, options); + ExpressionProcessor lExpressionProcessor = new ExpressionProcessor(); + lExpressionProcessor.process((TExpression) parseTreeNode.getEndNode(), options, pDataClone); + runningSize = pDataClone.getOffSet(); + } + return runningSize; + } + + /** + * return true if columns are aligned + */ + protected boolean isAlignColumns(FmtOptionsIf options, OptionsProcessData pData, + AlignColumnsParameter parameterObject, ListItemOptionsEnum itemOption) { + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/begin/BeginFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/begin/BeginFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..3356211a5bc286b4f65e22319cca823da4c285e7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/begin/BeginFormatProcessor.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.begin; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.block.TBeginSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * Title: LoopStmtFormatProcessor + * + * @since 3.0.0 + */ +public class BeginFormatProcessor extends AbstractProcessor { + + /** + * return option processData + */ + public OptionsProcessData getOptionsProcessData(TBeginSqlStatement selectAstNode, OptionsProcessData pData, + FmtOptionsIf options) { + OptionsProcessData lOptionsProcessData = getNewOptionsDataBean(pData, 0); + return lOptionsProcessData; + } + + /** + * return start node + */ + @Override + public TParseTreeNode getStartNode(TBeginSqlStatement selectAstNode) { + return selectAstNode.getStartNode(); + } + + /** + * return true if data is cloned + */ + public boolean isCloneData() { + return true; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/begin/DeclareFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/begin/DeclareFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..9ae48871548df26a5ef30e910b11db064668df87 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/begin/DeclareFormatProcessor.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.begin; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.block.TDeclareSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: LoopStmtFormatProcessor + * + * @since 3.0.0 + */ +public class DeclareFormatProcessor extends AbstractProcessor { + + /** + * Gets the options process data. + * + * @param selectAstNode the select ast node + * @param pData the data + * @param options the options + * @return the options process data + */ + public OptionsProcessData getOptionsProcessData(TDeclareSqlStatement selectAstNode, OptionsProcessData pData, + FmtOptionsIf options) { + OptionsProcessData lOptionsProcessData = getNewOptionsDataBean(pData, 0); + return lOptionsProcessData; + } + + /** + * Gets the start node. + * + * @param selectAstNode the select ast node + * @return the start node + */ + @Override + public TParseTreeNode getStartNode(TDeclareSqlStatement selectAstNode) { + return selectAstNode.getStartNode(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/begin/ast/BeginASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/begin/ast/BeginASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..11384ddb8727ede1f839c712fc46ce97835d2281 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/begin/ast/BeginASTNodeFormatProcessor.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.begin.ast; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.AddEmptyPreTextFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.NewlineFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.WhenListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.begin.TBeginASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * Title: LoopASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class BeginASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + TBeginASTNode selectAstNode = (TBeginASTNode) node; + addFormatProcessListener(selectAstNode.getEnd(), getNewlineFormat()); + + addFormatProcessListener(selectAstNode.getException(), getNewlineFormat()); + + addFormatProcessListener(selectAstNode.getExceptionWhenList(), new WhenListFormatProcessorListener()); + + if (null != selectAstNode.getEndExpression() && selectAstNode.getEndExpression().getExpList().size() > 1) { + addFormatProcessListener(selectAstNode.getEndExpression(), new AddEmptyPreTextFormatProcessorListener()); + } + } + + private NewlineFormatProcessorListener getNewlineFormat() { + return new NewlineFormatProcessorListener() { + /** + * format the process for the given node + */ + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + super.formatProcess(nextNode, options, pData); + nextNode.setCheckPreviousNewLine(Boolean.TRUE); + } + }; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/begin/ast/DeclareASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/begin/ast/DeclareASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..df6531e60c86eda7f322175a586cd025ed3f41da --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/begin/ast/DeclareASTNodeFormatProcessor.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.begin.ast; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.DeclareFieldsNewlineWithIndentFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * + * Title: LoopASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class DeclareASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + if (ProcessorUtils.isNodeListAvailable(node.getItemList())) { + addFormatProcessListener(node.getItemList(), new DeclareFieldsNewlineWithIndentFormatProcessorListener()); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/casestmt/CaseASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/casestmt/CaseASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..9538af4a3bea864bdd7c8bfe9752ab1903d87cfc --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/casestmt/CaseASTNodeFormatProcessor.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.casestmt; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.ASTStartNodeNoNewlineFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.AddEmptyPreTextFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.CaseEndNodeFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.CaseListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.casestmt.TCaseASTNode; + +/** + * + * Title: CaseASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class CaseASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + + TCaseASTNode selectAstNode = (TCaseASTNode) node; + + addFormatProcessListener(selectAstNode.getStartNode(), new ASTStartNodeNoNewlineFormatProcessorListener()); + + addFormatProcessListener(selectAstNode.getColExpression(), new AddEmptyPreTextFormatProcessorListener()); + + addFormatProcessListener(selectAstNode.getItemList(), new CaseListFormatProcessorListener()); + + addFormatProcessListener(selectAstNode.getEndNode(), new CaseEndNodeFormatProcessorListener()); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/casestmt/CaseStmtFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/casestmt/CaseStmtFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..f7b22064045d5044f6e3cd328710c80f8a6eb973 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/casestmt/CaseStmtFormatProcessor.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.casestmt; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.condition.TCaseSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: CaseStmtFormatProcessor + * + * @since 3.0.0 + */ +public class CaseStmtFormatProcessor extends AbstractProcessor { + + /** + * Gets the options process data. + * + * @param selectAstNode the select ast node + * @param pData the data + * @param options the options + * @return the options process data + */ + public OptionsProcessData getOptionsProcessData(TCaseSqlStatement selectAstNode, OptionsProcessData pData, + FmtOptionsIf options) { + + OptionsProcessData lOptionsProcessData = getNewOptionsDataBean(pData, 4); + + return lOptionsProcessData; + } + + /** + * Gets the start node. + * + * @param selectAstNode the select ast node + * @return the start node + */ + @Override + public TParseTreeNode getStartNode(TCaseSqlStatement selectAstNode) { + return selectAstNode.getStartNode(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/common/CTEASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/common/CTEASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..694cd6e5e3e05af20cd5c41edf02b094fbe346f2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/common/CTEASTNodeFormatProcessor.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.common; + +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.common.TCTEASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: CTEASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class CTEASTNodeFormatProcessor extends AbstractProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TCTEASTNode node) { + super.beforeProcess(node); + + } + + /** + * Gets the start node. + * + * @param selectAstNode the select ast node + * @return the start node + */ + public TParseTreeNode getStartNode(TCTEASTNode selectAstNode) { + return selectAstNode.getStmtExpression(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/common/ReturningASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/common/ReturningASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..445a9f110fc1c8792090b3b5b08475764e61a60e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/common/ReturningASTNodeFormatProcessor.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.common; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.ResultListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * + * Title: ReturningASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class ReturningASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + addFormatProcessListener(node.getItemList(), new ResultListFormatProcessorListener()); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/create/CreateFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/create/CreateFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..6c02672fae38d5a508bf3ba21503d8a73a02781a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/create/CreateFormatProcessor.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.create; + +import org.opengauss.mppdbide.gauss.format.consts.FormatItemsType; +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.debugobj.TCreateSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: LoopStmtFormatProcessor + * + * @since 3.0.0 + */ +public class CreateFormatProcessor extends AbstractProcessor { + + /** + * Gets the options process data. + * + * @param selectAstNode the select ast node + * @param pData the data + * @param options the options + * @return the options process data + */ + public OptionsProcessData getOptionsProcessData(TCreateSqlStatement selectAstNode, OptionsProcessData pData, + FmtOptionsIf options) { + + OptionsProcessData lOptionsProcessData = getNewOptionsDataBean(pData, 0); + lOptionsProcessData.setFormatItemsType(FormatItemsType.PARAMETER); + return lOptionsProcessData; + } + + /** + * Gets the start node. + * + * @param selectAstNode the select ast node + * @return the start node + */ + @Override + public TParseTreeNode getStartNode(TCreateSqlStatement selectAstNode) { + return selectAstNode.getStartNode(); + } + + /** + * Checks if is clone data. + * + * @return true, if is clone data + */ + public boolean isCloneData() { + return true; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/create/ast/AsASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/create/ast/AsASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..8c52e618a5a9bcb82b95dfbc038b530ae8607e26 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/create/ast/AsASTNodeFormatProcessor.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.create.ast; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.DeclareFieldsNewlineWithIndentFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.NewlineFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.exception.GaussDBSQLParserException; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.create.TAsASTNode; + +/** + * Title: LoopASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class AsASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + TAsASTNode lTAsASTNode = getAstNode(node); + // add listener to the startnode + + if (ProcessorUtils.isNodeListAvailable(node.getItemList())) { + addFormatProcessListener(node.getItemList(), new DeclareFieldsNewlineWithIndentFormatProcessorListener()); + } + + addFormatProcessListener(lTAsASTNode.getEndAs(), new NewlineFormatProcessorListener()); + + } + + private TAsASTNode getAstNode(TBasicASTNode node) { + if (!(node instanceof TAsASTNode)) { + throw new GaussDBSQLParserException("Unable to Cast the AST Node"); + } + return (TAsASTNode) node; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/create/ast/CreateASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/create/ast/CreateASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..498b1c8e4c5a5fc079afd0c7506c1ad56e568ce4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/create/ast/CreateASTNodeFormatProcessor.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.create.ast; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.AddEmptyPreTextFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.CreateParamsNewlineWithIndentFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.NewlineFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.NewlineWithProcessFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.NoPreTextFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.ResultListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.create.TCreateASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpressionNode; + +/** + * + * Title: LoopASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class CreateASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + + TCreateASTNode selectAstNode = (TCreateASTNode) node; + + addFormatProcessListener(selectAstNode.getIntermediateText(), new AddEmptyPreTextFormatProcessorListener()); + + addFormatProcessListener(selectAstNode.getProcOrFuncName(), new AddEmptyPreTextFormatProcessorListener()); + + boolean isNdeListPresent = ProcessorUtils.isNodeListAvailable(selectAstNode.getItemList()); + if (this.getOptions().isListAtLeftMargin() && isNdeListPresent) { + addFormatProcessListener(selectAstNode.getProcStartBracket(), new NewlineFormatProcessorListener()); + addFormatProcessListener(selectAstNode.getItemList(), + new CreateParamsNewlineWithIndentFormatProcessorListener()); + addFormatProcessListener(selectAstNode.getProcEndBracket(), new NewlineFormatProcessorListener()); + } else { + addFormatProcessListener(selectAstNode.getProcStartBracket(), new NoPreTextFormatProcessorListener()); + if (isNdeListPresent) { + addFormatProcessListener(selectAstNode.getItemList(), getListItemProcessListener()); + } + addFormatProcessListener(selectAstNode.getProcEndBracket(), new NoPreTextFormatProcessorListener()); + } + + TExpression commonExpression = selectAstNode.getCommonExpression(); + if (null != commonExpression && commonExpression.getExpList().size() == 1) { + TExpressionNode tExpressionNode = commonExpression.getExpList().get(0); + if (tExpressionNode.getExpNode() != null && !";".equals(tExpressionNode.getExpNode().getNodeText())) { + addFormatProcessListener(commonExpression, new NewlineWithProcessFormatProcessorListener()); + } + + } else { + addFormatProcessListener(commonExpression, new NewlineWithProcessFormatProcessorListener()); + } + } + + private ResultListFormatProcessorListener getListItemProcessListener() { + ResultListFormatProcessorListener lResultListFormatProcessorListener = new ResultListFormatProcessorListener(); + lResultListFormatProcessorListener.setAddPreSpace(false); + return lResultListFormatProcessorListener; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/create/ast/LanguageASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/create/ast/LanguageASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..9e185da14483bab249e4cd6c0c01e26a0d4d2c8b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/create/ast/LanguageASTNodeFormatProcessor.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.create.ast; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.AddEmptyPreTextFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.NewlineWithProcessFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.create.TLaungageASTNode; + +/** + * + * Title: LoopASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class LanguageASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + + TLaungageASTNode selectAstNode = (TLaungageASTNode) node; + + addFormatProcessListener(selectAstNode.getLanguageExpression(), new AddEmptyPreTextFormatProcessorListener()); + + addFormatProcessListener(selectAstNode.getCommonExpression(), new NewlineWithProcessFormatProcessorListener()); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/create/ast/ReturnsASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/create/ast/ReturnsASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..4098aff48c1aab961bff40f3db9e34dca4fdb2bf --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/create/ast/ReturnsASTNodeFormatProcessor.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.create.ast; + +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.AddEmptyPreTextFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.NewlineWithProcessFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.NoPreTextFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.ResultListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.create.TReturnASTNode; + +/** + * + * Title: LoopASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class ReturnsASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + + TReturnASTNode selectAstNode = (TReturnASTNode) node; + + addFormatProcessListener(selectAstNode.getResultExpression(), new AddEmptyPreTextFormatProcessorListener()); + + addFormatProcessListener(selectAstNode.getReturnTableList(), getListFormatProcessor()); + + addFormatProcessListener(selectAstNode.getReturnEndBracket(), new NoPreTextFormatProcessorListener()); + + addFormatProcessListener(selectAstNode.getCommonExpression(), new NewlineWithProcessFormatProcessorListener()); + + } + + private IFormarProcessorListener getListFormatProcessor() { + ResultListFormatProcessorListener lIFormarProcessorListener = new ResultListFormatProcessorListener(); + lIFormarProcessorListener.setAddPreSpace(false); + return lIFormarProcessorListener; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/cursor/CursorStmtFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/cursor/CursorStmtFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..be1e12213b759a15eb6ba566a85423f9e3489a85 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/cursor/CursorStmtFormatProcessor.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.cursor; + +import org.opengauss.mppdbide.gauss.format.consts.FormatItemsType; +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.debugobj.TCursorSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * Title: CursorStmtFormatProcessor + * + * @since 3.0.0 + */ +public class CursorStmtFormatProcessor extends AbstractProcessor { + /** + * Gets the options process data. + * + * @param selectAstNode the select ast node + * @param pData the data + * @param options the options + * @return the options process data + */ + public OptionsProcessData getOptionsProcessData(TCursorSqlStatement selectAstNode, OptionsProcessData pData, + FmtOptionsIf options) { + OptionsProcessData lOptionsProcessData = getNewOptionsDataBean(pData, 0); + lOptionsProcessData.setFormatItemsType(FormatItemsType.PARAMETER); + return lOptionsProcessData; + } + + @Override + public TParseTreeNode getStartNode(TCursorSqlStatement selectAstNode) { + return selectAstNode.getStartNode(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/cursor/ast/CursorStmtASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/cursor/ast/CursorStmtASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..36d40b21899dc1f3bfa227bbabb4d90d7e0788d2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/cursor/ast/CursorStmtASTNodeFormatProcessor.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.cursor.ast; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.ASTStartNodeNoNewlineFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.AddEmptyPreTextFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.CreateParamsNewlineWithIndentFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.NewlineFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.NewlineWithOffsetSqlNodeFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.NoPreTextFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.ResultListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.exception.GaussDBSQLParserException; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.cursor.TCursorASTNode; + +/** + * Title: IfStmtASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class CursorStmtASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + + TCursorASTNode selectAstNode = getAstNode(node); + + addFormatProcessListener(selectAstNode.getKeywordNode(), new ASTStartNodeNoNewlineFormatProcessorListener()); + // add the listener for the if condition + addFormatProcessListener(selectAstNode.getCursorExpression(), new AddEmptyPreTextFormatProcessorListener()); + + if (this.getOptions().isListAtLeftMargin()) { + addFormatProcessListener(selectAstNode.getParamStartBracket(), new NewlineFormatProcessorListener()); + if (ProcessorUtils.isNodeListAvailable(selectAstNode.getItemList())) { + addFormatProcessListener(selectAstNode.getItemList(), + new CreateParamsNewlineWithIndentFormatProcessorListener()); + } + addFormatProcessListener(selectAstNode.getParamEndBracket(), + new NewlineWithOffsetSqlNodeFormatProcessorListener()); + } else { + addFormatProcessListener(selectAstNode.getParamStartBracket(), new NoPreTextFormatProcessorListener()); + if (ProcessorUtils.isNodeListAvailable(selectAstNode.getItemList())) { + addFormatProcessListener(selectAstNode.getItemList(), getListItemProcessListener()); + } + addFormatProcessListener(selectAstNode.getParamEndBracket(), new NoPreTextFormatProcessorListener()); + } + + addFormatProcessListener(selectAstNode.getCursorStmts(), new AddEmptyPreTextFormatProcessorListener()); + } + + private TCursorASTNode getAstNode(TBasicASTNode node) { + if (!(node instanceof TCursorASTNode)) { + throw new GaussDBSQLParserException("Unable to Cast the AST Node"); + } + return (TCursorASTNode) node; + } + + private ResultListFormatProcessorListener getListItemProcessListener() { + ResultListFormatProcessorListener lResultListFormatProcessorListener = new ResultListFormatProcessorListener(); + lResultListFormatProcessorListener.setAddPreSpace(false); + return lResultListFormatProcessorListener; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/delete/DeleteStmtFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/delete/DeleteStmtFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..9380203717c4cf780e603693b3108d43d6c5e015 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/delete/DeleteStmtFormatProcessor.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.delete; + +import org.opengauss.mppdbide.gauss.format.consts.FormatItemsType; +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml.TDeleteSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: DeleteStmtFormatProcessor + * + * @since 3.0.0 + */ +public class DeleteStmtFormatProcessor extends AbstractProcessor { + + /** + * Gets the options process data. + * + * @param selectAstNode the select ast node + * @param pData the data + * @param options the options + * @return the options process data + */ + public OptionsProcessData getOptionsProcessData(TDeleteSqlStatement selectAstNode, OptionsProcessData pData, + FmtOptionsIf options) { + + int maxKeywordWidth = getMaxKeywordWidth(selectAstNode, options); + + OptionsProcessData lOptionsProcessData = getNewOptionsDataBean(pData, maxKeywordWidth); + + lOptionsProcessData.setFormatItemsType(FormatItemsType.SELECT); + + return lOptionsProcessData; + } + + /** + * Gets the start node. + * + * @param selectAstNode the select ast node + * @return the start node + */ + @Override + public TParseTreeNode getStartNode(TDeleteSqlStatement selectAstNode) { + return selectAstNode.getStartNode(); + } + + /** + * Checks if is clone data. + * + * @return true, if is clone data + */ + public boolean isCloneData() { + return true; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/delete/ast/DeleteFromASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/delete/ast/DeleteFromASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..c99a65c452a0d562e4c7c6d4bbd6a14de88d2c06 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/delete/ast/DeleteFromASTNodeFormatProcessor.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.delete.ast; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.ASTStartNodeNoNewlineFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.AddEmptyPreTextFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.delete.TDeleteFromASTNode; + +/** + * + * Title: DeleteFromASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class DeleteFromASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + + TDeleteFromASTNode insertNode = (TDeleteFromASTNode) node; + + addFormatProcessListener(insertNode.getKeywordNode(), new ASTStartNodeNoNewlineFormatProcessorListener()); + + addFormatProcessListener(insertNode.getTableName(), new AddEmptyPreTextFormatProcessorListener()); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/delete/ast/DeleteUsingASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/delete/ast/DeleteUsingASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..1c7360c906097249f63317802cf81dafa77c12a5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/delete/ast/DeleteUsingASTNodeFormatProcessor.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.delete.ast; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.FromListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * + * Title: DeleteUsingASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class DeleteUsingASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + + addFormatProcessListener(node.getItemList(), new FromListFormatProcessorListener()); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/forloop/ForLoopFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/forloop/ForLoopFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..882e33787b5d1b872dfb0907d435978628495ad5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/forloop/ForLoopFormatProcessor.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.forloop; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.loop.TForLoopSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * Title: IfStmtFormatProcessor + * + * @since 3.0.0 + */ +public class ForLoopFormatProcessor extends AbstractProcessor { + /** + * Gets the options process data. + * + * @param selectAstNode the select ast node + * @param pData the data + * @param options the options + * @return the options process data + */ + public OptionsProcessData getOptionsProcessData(TForLoopSqlStatement selectAstNode, OptionsProcessData pData, + FmtOptionsIf options) { + OptionsProcessData lOptionsProcessData = getNewOptionsDataBean(pData, 0); + return lOptionsProcessData; + } + + @Override + public TParseTreeNode getStartNode(TForLoopSqlStatement selectAstNode) { + return selectAstNode.getStartNode(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/forloop/ast/ForLoopASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/forloop/ast/ForLoopASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..c2fa4821926795f0b5b6c4540527d8153a4d0ac6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/forloop/ast/ForLoopASTNodeFormatProcessor.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.forloop.ast; + +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.AddEmptyPreTextFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.IfStmtConditionListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.exception.GaussDBSQLParserException; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.forloop.TForLoopASTNode; + +/** + * Title: IfStmtASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class ForLoopASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + TForLoopASTNode selectAstNode = getAstNode(node); + // add the listener for the if condition + addFormatProcessListener(selectAstNode.getTargetName(), new AddEmptyPreTextFormatProcessorListener()); + addFormatProcessListener(selectAstNode.getItemList(), new IfStmtConditionListFormatProcessorListener()); + } + + private TForLoopASTNode getAstNode(TBasicASTNode node) { + if (!(node instanceof TForLoopASTNode)) { + throw new GaussDBSQLParserException("Unable to Cast the AST Node"); + } + return (TForLoopASTNode) node; + } + + /** + * After process. + * + * @param node the node + * @param clonedOptData the cloned opt data + */ + public void afterProcess(TBasicASTNode node, OptionsProcessData clonedOptData) { + clonedOptData.setOffSet(clonedOptData.getParentOffSet()); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/ifstmt/IfStmtFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/ifstmt/IfStmtFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..6ed9549dc9df3e57b8d27accf4321b8633144460 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/ifstmt/IfStmtFormatProcessor.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.ifstmt; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.condition.TIfElseSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: IfStmtFormatProcessor + * + * @since 3.0.0 + */ +public class IfStmtFormatProcessor extends AbstractProcessor { + + /** + * Gets the options process data. + * + * @param selectAstNode the select ast node + * @param pData the data + * @param options the options + * @return the options process data + */ + public OptionsProcessData getOptionsProcessData(TIfElseSqlStatement selectAstNode, OptionsProcessData pData, + FmtOptionsIf options) { + + OptionsProcessData lOptionsProcessData = getNewOptionsDataBean(pData, 0); + + return lOptionsProcessData; + } + + /** + * Gets the start node. + * + * @param selectAstNode the select ast node + * @return the start node + */ + @Override + public TParseTreeNode getStartNode(TIfElseSqlStatement selectAstNode) { + return selectAstNode.getStartNode(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/ifstmt/ast/IfStmtASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/ifstmt/ast/IfStmtASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..e26ad5eaca752f8db4da0dd16d31b042276edbce --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/ifstmt/ast/IfStmtASTNodeFormatProcessor.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.ifstmt.ast; + +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.AddEmptyPreTextFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.IfStmtConditionListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.NewlineWithProcessFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.ifstmt.TIfElseASTNode; + +/** + * + * Title: IfStmtASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class IfStmtASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + + TIfElseASTNode selectAstNode = (TIfElseASTNode) node; + + // add the listener for the if condition + + addFormatProcessListener(selectAstNode.getThen(), getThenProcessorListener()); + + addFormatProcessListener(selectAstNode.getItemList(), new IfStmtConditionListFormatProcessorListener()); + + addFormatProcessListener(selectAstNode.getEnd(), new NewlineWithProcessFormatProcessorListener()); + + addFormatProcessListener(selectAstNode.getEndNode(), new AddEmptyPreTextFormatProcessorListener()); + + } + + private IFormarProcessorListener getThenProcessorListener() { + return this.getOptions().isThenOnNewLine() ? new NewlineWithProcessFormatProcessorListener() + : new AddEmptyPreTextFormatProcessorListener(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/insert/InsertStmtFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/insert/InsertStmtFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..f135f9d0bb8c5ccf2061a46e23902e0840c00492 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/insert/InsertStmtFormatProcessor.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.insert; + +import org.opengauss.mppdbide.gauss.format.consts.FormatItemsType; +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml.TInsertSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: InsertStmtFormatProcessor + * + * @since 3.0.0 + */ +public class InsertStmtFormatProcessor extends AbstractProcessor { + + /** + * Gets the options process data. + * + * @param selectAstNode the select ast node + * @param pData the data + * @param options the options + * @return the options process data + */ + public OptionsProcessData getOptionsProcessData(TInsertSqlStatement selectAstNode, OptionsProcessData pData, + FmtOptionsIf options) { + + int maxKeywordWidth = getMaxKeywordWidth(selectAstNode, options); + + OptionsProcessData lOptionsProcessData = getNewOptionsDataBean(pData, maxKeywordWidth); + + lOptionsProcessData.setFormatItemsType(FormatItemsType.INSERT); + + return lOptionsProcessData; + } + + /** + * Gets the start node. + * + * @param selectAstNode the select ast node + * @return the start node + */ + @Override + public TParseTreeNode getStartNode(TInsertSqlStatement selectAstNode) { + return selectAstNode.getStartNode(); + } + + /** + * Checks if is clone data. + * + * @return true, if is clone data + */ + public boolean isCloneData() { + return true; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/insert/ast/InsertIntoASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/insert/ast/InsertIntoASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..fe19c2f11959ccdabee69c21c9514f66cdbe6688 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/insert/ast/InsertIntoASTNodeFormatProcessor.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.insert.ast; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.ASTStartNodeNoNewlineFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.AddEmptyPreTextFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.NewlineWithIndentFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.NoPreTextFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.ResultListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.insert.TInsertIntoASTNode; + +/** + * + * Title: InsertIntoASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class InsertIntoASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + + TInsertIntoASTNode insertNode = (TInsertIntoASTNode) node; + + addFormatProcessListener(insertNode.getKeywordNode(), new ASTStartNodeNoNewlineFormatProcessorListener()); + + addFormatProcessListener(insertNode.getTableName(), new AddEmptyPreTextFormatProcessorListener()); + + addFormatProcessListener(insertNode.getStartInsertAstBracket(), new NewlineWithIndentFormatProcessorListener()); + + ResultListFormatProcessorListener processListener = new ResultListFormatProcessorListener(); + processListener.setAddPreSpace(false); + addFormatProcessListener(insertNode.getItemList(), processListener); + + addFormatProcessListener(insertNode.getEndInsertAstBracket(), new NoPreTextFormatProcessorListener()); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/insert/ast/InsertValuesListASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/insert/ast/InsertValuesListASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..1d345c5c9ad255933a5dfcaf7b9a966967887d34 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/insert/ast/InsertValuesListASTNodeFormatProcessor.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.insert.ast; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.InsertValuesNodeItemListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * + * Title: InsertValuesListASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class InsertValuesListASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + addFormatProcessListener(node.getItemList(), new InsertValuesNodeItemListFormatProcessorListener()); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listener/IFormarProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listener/IFormarProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..91964266ac17f8edbb9d4a83462a8e1732a43038 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listener/IFormarProcessorListener.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listener; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: IFormarProcessorListener + * + * @since 3.0.0 + */ +public interface IFormarProcessorListener { + + /** + * Format process. + * + * @param nextNode the next node + * @param options the options + * @param pData the data + */ + void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/ASTStartNodeFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/ASTStartNodeFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..7e3a1dd1941f5082d5348cfe9b1415deae77f8c3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/ASTStartNodeFormatProcessorListener.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: ASTStartNodeFormatProcessorListener + * + * @since 3.0.0 + */ +public class ASTStartNodeFormatProcessorListener implements IFormarProcessorListener { + + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + + int offset = pData.getOffSet(); + pData.setParentOffSet(offset); + + // start node put in the new line and format + TSqlNode where = (TSqlNode) nextNode; + ProcessorUtils.addNewLineBefore(where, offset, options); + ProcessorUtils.formatStartNode(where, options, pData); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/ASTStartNodeNoNewlineFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/ASTStartNodeNoNewlineFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..f68002669d775c01a55c7fba72c1d87cb0425921 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/ASTStartNodeNoNewlineFormatProcessorListener.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: ASTStartNodeNoNewlineFormatProcessorListener + * + * @since 3.0.0 + */ +public class ASTStartNodeNoNewlineFormatProcessorListener implements IFormarProcessorListener { + + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + + int offset = pData.getOffSet(); + pData.setParentOffSet(offset); + + // start node put in the new line and format + TSqlNode where = (TSqlNode) nextNode; + if (pData.isPutStmtNewLine()) { + ProcessorUtils.addNewLineBefore(where, offset, options); + } + ProcessorUtils.formatStartNode(where, options, pData); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/AddEmptyPreTextFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/AddEmptyPreTextFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..dff3310c5a7f458f7ece13ca4de7bbb7c3406976 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/AddEmptyPreTextFormatProcessorListener.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessorUtils; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * Title: AddEmptyPreTextFormatProcessorListener + * + * @since 3.0.0 + */ +public class AddEmptyPreTextFormatProcessorListener implements IFormarProcessorListener { + + /** + * Format process. + * + * @param nextNode the next node + * @param options the options + * @param pData the data + */ + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + + changeOptionsData(pData); + + // start node put in the new line and format + ProcessorUtils.addPreEmptyText(nextNode, pData); + if (!(nextNode instanceof TSqlNode)) { + AbstractProcessorUtils.processParseTreeNode(nextNode, options, pData); + } + + } + + /** + * Change options data. + * + * @param pData the data + */ + protected void changeOptionsData(OptionsProcessData pData) { + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/CaseEndNodeFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/CaseEndNodeFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..cc3af33be91ce07713cb84e52fddc36a86e3f406 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/CaseEndNodeFormatProcessorListener.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: CaseEndNodeFormatProcessorListener + * + * @since 3.0.0 + */ +public class CaseEndNodeFormatProcessorListener implements IFormarProcessorListener { + + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + + // start node put in the new line and format + TSqlNode where = (TSqlNode) nextNode; + ProcessorUtils.addNewLineBefore(where, pData.getParentOffSet(), options); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/CaseExprListProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/CaseExprListProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..3237a88a60e67339cb68587fa4c855721764a6d0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/CaseExprListProcessor.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractListProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TAbstractListItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.casenode.TCaseStmtExpr; + +/** + * + * Title: CaseExprListProcessor + * + * @since 3.0.0 + */ +public class CaseExprListProcessor extends AbstractListProcessor { + + /** + * Adds the list item listener. + * + * @param tAbstractListItem the t abstract list item + */ + protected void addListItemListener(TAbstractListItem tAbstractListItem) { + + TCaseStmtExpr caseStmtExpr = (TCaseStmtExpr) tAbstractListItem; + + addFormatProcessListener(caseStmtExpr.getWhenOrElse(), new NewlineWithIndentFormatProcessorListener()); + + addFormatProcessListener(caseStmtExpr.getEndNode(), new NewlineWithIndentFormatProcessorListener()); + + addFormatProcessListener(caseStmtExpr.getConditionExpr(), new OnConditionListFormatProcessorListener()); + + } + + /** + * Before item process. + * + * @param pData the data + * @param currentData the current data + */ + protected void beforeItemProcess(OptionsProcessData pData, OptionsProcessData currentData) { + + currentData.setOffSet(pData.getOffSet()); + currentData.setParentOffSet(pData.getParentOffSet()); + currentData.setPreIndentOffSet(0); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/CaseListFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/CaseListFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..c110fe91b15dbe7131c8c15374906ac311fa040e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/CaseListFormatProcessorListener.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.casenode.TCaseExprList; + +/** + * + * Title: CaseListFormatProcessorListener + * + * @since 3.0.0 + */ +public class CaseListFormatProcessorListener implements IFormarProcessorListener { + + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + + TCaseExprList expressionList = (TCaseExprList) nextNode; + + // add the expressionList + + CaseExprListProcessor lColumnlistCommaProcessor = new CaseExprListProcessor(); + lColumnlistCommaProcessor.setOptions(options); + + lColumnlistCommaProcessor.process(expressionList, options, pData); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/ColonResultListFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/ColonResultListFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..52f5f3e1126feab85d078ea8c1da8ebc0cab655b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/ColonResultListFormatProcessorListener.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.processor.ColumnlistColonProcessor; +import org.opengauss.mppdbide.gauss.format.processor.ColumnlistCommaProcessor; + +/** + * Title: ColonResultListFormatProcessorListener + * + * @since 3.0.0 + */ +public class ColonResultListFormatProcessorListener extends ResultListFormatProcessorListener { + + /** + * Gets the column list processor. + * + * @return the column list processor + */ + protected ColumnlistCommaProcessor getColumnListProcessor() { + return new ColumnlistColonProcessor(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/CreateParamsNewlineWithIndentFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/CreateParamsNewlineWithIndentFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..c59b30b62d1b36218975c4098521dd46eac03e6a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/CreateParamsNewlineWithIndentFormatProcessorListener.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: NewlineWithIndentFormatProcessorListener + * + * @since 3.0.0 + */ +public class CreateParamsNewlineWithIndentFormatProcessorListener implements IFormarProcessorListener { + + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + + pData.setOffSet(pData.getParentOffSet()); + ProcessorUtils.addNewLineBeforeWithindent(nextNode, pData, options); + + ResultListFormatProcessorListener processListener = new ResultListFormatProcessorListener(); + processListener.setAddPreSpace(false); + + processListener.formatProcess(nextNode, options, pData); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/DeclareFieldsNewlineWithIndentFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/DeclareFieldsNewlineWithIndentFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..4d1c7ca32cb4512e4a51d58d238c4c080edbcf16 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/DeclareFieldsNewlineWithIndentFormatProcessorListener.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.consts.FormatItemsType; +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * Title: DeclareFieldsNewlineWithIndentFormatProcessorListener + * + * @since 3.0.0 + */ +public class DeclareFieldsNewlineWithIndentFormatProcessorListener implements IFormarProcessorListener { + + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + + pData.setOffSet(pData.getParentOffSet()); + ProcessorUtils.addNewLineBeforeWithindent(nextNode, pData, options); + + pData.setFormatItemsType(FormatItemsType.FIXED_ONEITEMPERLINE); + + ResultListFormatProcessorListener processListener = new ColonResultListFormatProcessorListener(); + processListener.setAddPreSpace(false); + processListener.setSemiColonList(true); + processListener.formatProcess(nextNode, options, pData); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/FromJoinListProcessorNew.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/FromJoinListProcessorNew.java new file mode 100644 index 0000000000000000000000000000000000000000..66c738f276a6e514a698fc121ab2df25d7fec5ca --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/FromJoinListProcessorNew.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.processor.AbstractListProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TAbstractListItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.from.TFromItem; + +/** + * + * Title: FromJoinListProcessorNew + * + * @since 3.0.0 + */ +public class FromJoinListProcessorNew extends AbstractListProcessor { + + /** + * Adds the list item listener. + * + * @param tAbstractListItem the t abstract list item + */ + protected void addListItemListener(TAbstractListItem tAbstractListItem) { + + TFromItem fromItem = (TFromItem) tAbstractListItem; + + addFormatProcessListener(fromItem.getTable(), new AddEmptyPreTextFormatProcessorListener()); + + addFormatProcessListener(fromItem.getEndNode(), new AddEmptyPreTextFormatProcessorListener()); + + addFormatProcessListener(fromItem.getJoinType(), new NewlineWithParentOffsetFormatProcessorListener()); + + addFormatProcessListener(fromItem.getJoinCondition(), new OnConditionListFormatProcessorListener()); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/FromListFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/FromListFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..77dd939cbcf260b525d19faeac4152b4867afc39 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/FromListFormatProcessorListener.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.ColumnlistCommaProcessor; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.from.TFromItemList; + +/** + * + * Title: FromListFormatProcessorListener + * + * @since 3.0.0 + */ +public class FromListFormatProcessorListener implements IFormarProcessorListener { + + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + + TFromItemList fromItemList = (TFromItemList) nextNode; + + // add the expressionList + + if (fromItemList.isJoinStmt()) { + FromJoinListProcessorNew lFromJoinListProcessor = new FromJoinListProcessorNew(); + lFromJoinListProcessor.setOptions(options); + lFromJoinListProcessor.process(fromItemList, options, pData); + } else { + ColumnlistCommaProcessor lColumnlistCommaProcessor = new ColumnlistCommaProcessor(); + lColumnlistCommaProcessor.setOptions(options); + lColumnlistCommaProcessor.process((TParseTreeNodeList) fromItemList, options, pData); + } + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/IfStmtConditionListFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/IfStmtConditionListFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..b577b872c6d2cf075f16546a636b055285e690e5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/IfStmtConditionListFormatProcessorListener.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.IfStmtConditionClauseProcessor; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TWhereClause; + +/** + * + * Title: IfStmtConditionListFormatProcessorListener + * + * @since 3.0.0 + */ +public class IfStmtConditionListFormatProcessorListener implements IFormarProcessorListener { + + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + + TWhereClause expressionList = (TWhereClause) nextNode; + + // add the expressionList + + IfStmtConditionClauseProcessor lColumnlistCommaProcessor = new IfStmtConditionClauseProcessor(); + lColumnlistCommaProcessor.setOptions(options); + + lColumnlistCommaProcessor.process(expressionList, options, pData); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/InsertValuesItemListProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/InsertValuesItemListProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..5d1076fc6109fd14f3982a3707a9e0837187fc6f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/InsertValuesItemListProcessor.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractListProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.insert.TInsertValuesNodeItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TAbstractListItem; + +/** + * + * Title: InsertValuesItemListProcessor + * + * @since 3.0.0 + */ +public class InsertValuesItemListProcessor extends AbstractListProcessor { + + /** + * Adds the list item listener. + * + * @param tAbstractListItem the t abstract list item + */ + protected void addListItemListener(TAbstractListItem tAbstractListItem) { + + TInsertValuesNodeItem fromItem = (TInsertValuesNodeItem) tAbstractListItem; + + addFormatProcessListener(fromItem.getStartInsertBracket(), new NewlineWithIndentFormatProcessorListener()); + + ResultListFormatProcessorListener processListener = new ResultListFormatProcessorListener(); + processListener.setAddPreSpace(false); + addFormatProcessListener(fromItem.getValueItemList(), processListener); + + addFormatProcessListener(fromItem.getInsertEndBracket(), new NoPreTextFormatProcessorListener()); + + addFormatProcessListener(fromItem.getSeperator(), new NoPreTextFormatProcessorListener()); + + } + + /** + * Before item process. + * + * @param pData the data + * @param currentData the current data + */ + protected void beforeItemProcess(OptionsProcessData pData, OptionsProcessData currentData) { + + currentData.setOffSet(pData.getOffSet()); + currentData.setParentOffSet(pData.getParentOffSet()); + currentData.setPreIndentOffSet(0); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/InsertValuesNodeItemListFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/InsertValuesNodeItemListFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..af073d4b4e98a3d70de90d58d1a5cf89b5a8c903 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/InsertValuesNodeItemListFormatProcessorListener.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.insert.TInsertValuesNodeItemList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: InsertValuesNodeItemListFormatProcessorListener + * + * @since 3.0.0 + */ +public class InsertValuesNodeItemListFormatProcessorListener implements IFormarProcessorListener { + + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + + TInsertValuesNodeItemList expressionList = (TInsertValuesNodeItemList) nextNode; + + // add the expressionList + + InsertValuesItemListProcessor lColumnlistCommaProcessor = new InsertValuesItemListProcessor(); + lColumnlistCommaProcessor.setOptions(options); + + lColumnlistCommaProcessor.process(expressionList, options, pData); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/NewlineFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/NewlineFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..68ad8b80149e923e5db406666df1705142bb2f49 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/NewlineFormatProcessorListener.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: NewlineWithIndentFormatProcessorListener + * + * @since 3.0.0 + */ +public class NewlineFormatProcessorListener implements IFormarProcessorListener { + + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + + pData.setOffSet(pData.getParentOffSet()); + ProcessorUtils.addNewLineBefore(nextNode, pData.getOffSet(), options); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/NewlineWithIndentFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/NewlineWithIndentFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..32c1ad7fc229db43d9b47bd6947873ff3ed9b79c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/NewlineWithIndentFormatProcessorListener.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessorUtils; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: NewlineWithIndentFormatProcessorListener + * + * @since 3.0.0 + */ +public class NewlineWithIndentFormatProcessorListener implements IFormarProcessorListener { + + /** + * Format process. + * + * @param nextNode the next node + * @param options the options + * @param pData the data + */ + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + + changeOptionsData(pData); + ProcessorUtils.addNewLineBeforeWithindent(nextNode, pData, options); + AbstractProcessorUtils.processParseTreeNode(nextNode, options, pData, false); + + } + + /** + * Change options data. + * + * @param pData the data + */ + protected void changeOptionsData(OptionsProcessData pData) { + if (pData.getPreIndentOffSet() == 0) { + pData.setOffSet(pData.getParentOffSet()); + } else { + pData.setOffSet(pData.getPreIndentOffSet()); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/NewlineWithOffsetSqlNodeFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/NewlineWithOffsetSqlNodeFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..297487b8506a82ff986ba137bf4299e957fc127f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/NewlineWithOffsetSqlNodeFormatProcessorListener.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.sqlparser.exception.GaussDBSQLParserException; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * Title: NewlineWithOffsetSqlNodeFormatProcessorListener + * + * @since 3.0.0 + */ +public class NewlineWithOffsetSqlNodeFormatProcessorListener extends NewlineFormatProcessorListener { + /** + * Format process. + * + * @param nextNode the next node + * @param options the options + * @param pData the data + */ + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + super.formatProcess(nextNode, options, pData); + pData.addOffSet(getTSqlNode(nextNode).getNodeText().length()); + } + + private TSqlNode getTSqlNode(TParseTreeNode nextNode) { + if (!(nextNode instanceof TSqlNode)) { + throw new GaussDBSQLParserException("Unable to Cast the AST Node"); + } + return (TSqlNode) nextNode; + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/NewlineWithParentOffsetFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/NewlineWithParentOffsetFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..6695d6188b5745e0b755be5e0a06a0442a5ba7f7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/NewlineWithParentOffsetFormatProcessorListener.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import java.util.List; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessorUtils; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpressionNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: NewlineWithParentOffsetFormatProcessorListener + * + * @since 3.0.0 + */ +public class NewlineWithParentOffsetFormatProcessorListener implements IFormarProcessorListener { + + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + + // this is for join type expression + + TExpression joinTypeExpr = (TExpression) nextNode; + + List expList = joinTypeExpr.getExpList(); + + for (int index = 0; index < expList.size(); index++) { + TExpressionNode tExpressionNode = expList.get(index); + + TSqlNode sqlNode = tExpressionNode.getExpNode(); + if (index == 0) { + + ProcessorUtils.addNewLineBefore(sqlNode, pData.getParentOffSet(), options); + ProcessorUtils.formatStartNode(sqlNode, options, + pData.getParentData().getOffSet() - pData.getParentOffSet()); + pData.setOffSet(pData.getParentData().getOffSet() - pData.getParentOffSet()); + continue; + } + + AbstractProcessorUtils.processParseTreeNode(sqlNode, options, pData); + + } + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/NewlineWithProcessFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/NewlineWithProcessFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..493b6b00a4e71fc749c88bdebc8a215e624defeb --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/NewlineWithProcessFormatProcessorListener.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: NewlineWithIndentFormatProcessorListener + * + * @since 3.0.0 + */ +public class NewlineWithProcessFormatProcessorListener extends NewlineFormatProcessorListener { + + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + + super.formatProcess(nextNode, options, pData); + + AbstractProcessorUtils.processParseTreeNode(nextNode, options, pData, false); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/NoPreTextFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/NoPreTextFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..2d263322cf1446a68827daff16dafc801332d06f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/NoPreTextFormatProcessorListener.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: NoPreTextFormatProcessorListener + * + * @since 3.0.0 + */ +public class NoPreTextFormatProcessorListener implements IFormarProcessorListener { + + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + if (nextNode instanceof TSqlNode) { + pData.addOffSet(((TSqlNode) nextNode).getNodeText().length()); + } + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/OnConditionListFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/OnConditionListFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..639c03ba407939e84a92e601b9586edbe7765498 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/OnConditionListFormatProcessorListener.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.WhereListCommaProcessor; +import org.opengauss.mppdbide.gauss.format.processor.WhereListOnClauseProcessor; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TWhereClause; + +/** + * + * Title: OnConditionListFormatProcessorListener + * + * @since 3.0.0 + */ +public class OnConditionListFormatProcessorListener implements IFormarProcessorListener { + + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + + TWhereClause expressionList = (TWhereClause) nextNode; + + // add the expressionList + + WhereListCommaProcessor lColumnlistCommaProcessor = new WhereListOnClauseProcessor(); + lColumnlistCommaProcessor.setOptions(options); + + lColumnlistCommaProcessor.process(expressionList, options, pData); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/ResultListFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/ResultListFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..6d9693bab39f2f847fdaa8cb75971030630721da --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/ResultListFormatProcessorListener.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.ColumnlistCommaProcessor; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TResultColumnList; + +/** + * + * Title: ResultListFormatProcessorListener + * + * @since 3.0.0 + */ +public class ResultListFormatProcessorListener implements IFormarProcessorListener { + + private boolean addPreSpace = true; + private boolean semiColonList = false; + + /** + * return true is SemiColon List is there + * + * @return isSemiColonList the flag + */ + public boolean isSemiColonList() { + return semiColonList; + } + + /** + * sets the SemiColonList + * + * @param semiColonList the semicolon list + */ + public void setSemiColonList(boolean semiColonList) { + this.semiColonList = semiColonList; + } + + /** + * Format process. + * + * @param nextNode the next node + * @param options the options + * @param pData the data + */ + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + + TResultColumnList expressionList = (TResultColumnList) nextNode; + + // add the expressionList + + ColumnlistCommaProcessor lColumnlistCommaProcessor = getColumnListProcessor(); + lColumnlistCommaProcessor.setOptions(options); + lColumnlistCommaProcessor.setAddPreSpace(addPreSpace); + lColumnlistCommaProcessor.setSemiColonList(semiColonList); + lColumnlistCommaProcessor.process(expressionList, options, pData); + + } + + /** + * Gets the column list processor. + * + * @return the column list processor + */ + protected ColumnlistCommaProcessor getColumnListProcessor() { + return new ColumnlistCommaProcessor(); + } + + /** + * Checks if is adds the pre space. + * + * @return true, if is adds the pre space + */ + public boolean isAddPreSpace() { + return addPreSpace; + } + + /** + * Sets the adds the pre space. + * + * @param addPreSpace the new adds the pre space + */ + public void setAddPreSpace(boolean addPreSpace) { + this.addPreSpace = addPreSpace; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/SqlHintInfoFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/SqlHintInfoFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..e13f7bf4834735de9f4488ac0e3c1dc5c1a786d6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/SqlHintInfoFormatProcessorListener.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessorUtils; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: SqlHintInfoFormatProcessorListener + * + * @since 3.0.0 + */ +public class SqlHintInfoFormatProcessorListener implements IFormarProcessorListener { + + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + + ProcessorUtils.addPreEmptyText(nextNode, pData); + AbstractProcessorUtils.processParseTreeNode(nextNode, options, pData); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/UpdateSetValueBeanFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/UpdateSetValueBeanFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..4bbed9c0ae8915c5076d457a8684ef18fc0a0ad3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/UpdateSetValueBeanFormatProcessorListener.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.ColumnlistCommaProcessor; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.update.TUpdateSetValuesBean; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; + +/** + * + * Title: UpdateSetValueBeanFormatProcessorListener + * + * @since 3.0.0 + */ +public class UpdateSetValueBeanFormatProcessorListener implements IFormarProcessorListener { + + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + + TUpdateSetValuesBean expressionList = (TUpdateSetValuesBean) nextNode; + + // add the expressionList + + ColumnlistCommaProcessor lColumnlistCommaProcessor = new ColumnlistCommaProcessor(); + lColumnlistCommaProcessor.setOptions(options); + lColumnlistCommaProcessor.setAddPreSpace(false); + lColumnlistCommaProcessor.process((TParseTreeNodeList) expressionList.getValueItemList(), options, pData); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/UpdateSetValuesItemListProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/UpdateSetValuesItemListProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..0f7e6513a13863135f256fb68e8fc02df182a502 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/UpdateSetValuesItemListProcessor.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.processor.AbstractListProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.update.TUpdateSetValuesNodeItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TAbstractListItem; + +/** + * + * Title: UpdateSetValuesItemListProcessor + * + * @since 3.0.0 + */ +public class UpdateSetValuesItemListProcessor extends AbstractListProcessor { + + /** + * Adds the list item listener. + * + * @param tAbstractListItem the t abstract list item + */ + protected void addListItemListener(TAbstractListItem tAbstractListItem) { + + TUpdateSetValuesNodeItem fromItem = (TUpdateSetValuesNodeItem) tAbstractListItem; + + addFormatProcessListener(fromItem.getLeftNodeItem(), new UpdateSetValueBeanFormatProcessorListener()); + + addFormatProcessListener(fromItem.getRightNodeItem(), new UpdateSetValueBeanFormatProcessorListener()); + + addFormatProcessListener(fromItem.getSeperator(), new NoPreTextFormatProcessorListener()); + + } + +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/UpdateValuesListFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/UpdateValuesListFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..0267665c7b8ae5dcb2876fd8f2af4cc581bae14a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/UpdateValuesListFormatProcessorListener.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.update.TUpdateSetValuesNodeItemList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: UpdateValuesListFormatProcessorListener + * + * @since 3.0.0 + */ +public class UpdateValuesListFormatProcessorListener implements IFormarProcessorListener { + + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + + TUpdateSetValuesNodeItemList expressionList = (TUpdateSetValuesNodeItemList) nextNode; + + // add the expressionList + + UpdateSetValuesItemListProcessor lColumnlistCommaProcessor = new UpdateSetValuesItemListProcessor(); + lColumnlistCommaProcessor.setOptions(options); + + lColumnlistCommaProcessor.process(expressionList, options, pData); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/WhenListFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/WhenListFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..d2fef594cbaf5eb68ba22734bded2842c65e5b06 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/WhenListFormatProcessorListener.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.sqlparser.exception.GaussDBSQLParserException; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.exceptionwhen.TWhenExprList; + +/** + * Title: WhenListFormatProcessorListener + * + * @since 3.0.0 + */ +public class WhenListFormatProcessorListener implements IFormarProcessorListener { + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + TWhenExprList expressionList = getWhenExprList(nextNode); + + // add the expressionList + + WhenListProcessor lColumnlistCommaProcessor = new WhenListProcessor(); + lColumnlistCommaProcessor.setOptions(options); + + lColumnlistCommaProcessor.process(expressionList, options, pData); + } + + private TWhenExprList getWhenExprList(TParseTreeNode tAbstractListItem) { + if (tAbstractListItem instanceof TWhenExprList) { + return (TWhenExprList) tAbstractListItem; + } + throw new GaussDBSQLParserException("Unable to typecase the statement"); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/WhenListProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/WhenListProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..f23755eec8938f77d9999e7286ffd18543d7f670 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/WhenListProcessor.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractListProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.exception.GaussDBSQLParserException; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TAbstractListItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.exceptionwhen.TWhenStmtExpr; + +/** + * Title: WhenListProcessor + * + * @since 3.0.0 + */ +public class WhenListProcessor extends AbstractListProcessor { + /** + * add listener + * + * @param tAbstractListItem list item to which listeners to be added + */ + protected void addListItemListener(TAbstractListItem tAbstractListItem) { + TWhenStmtExpr caseStmtExpr = getWhenStmtExpr(tAbstractListItem); + + addFormatProcessListener(caseStmtExpr.getWhen(), new NewlineWithIndentFormatProcessorListener()); + + addFormatProcessListener(caseStmtExpr.getExceptionType(), new AddEmptyPreTextFormatProcessorListener()); + } + + private TWhenStmtExpr getWhenStmtExpr(TAbstractListItem tAbstractListItem) { + if (tAbstractListItem instanceof TWhenStmtExpr) { + return (TWhenStmtExpr) tAbstractListItem; + } + throw new GaussDBSQLParserException("Unable to typecase the statement"); + } + + /** + * process before item + * + * @param pData options data to process + * @param currentData current options data to process + */ + protected void beforeItemProcess(OptionsProcessData pData, OptionsProcessData currentData) { + currentData.setOffSet(pData.getOffSet()); + currentData.setParentOffSet(pData.getParentOffSet()); + currentData.setPreIndentOffSet(0); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/WhereListFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/WhereListFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..1b694f2f48a41fc840e97273a85722ece5337736 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/WhereListFormatProcessorListener.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.WhereListCommaProcessor; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TWhereClause; + +/** + * + * Title: WhereListFormatProcessorListener + * + * @since 3.0.0 + */ +public class WhereListFormatProcessorListener implements IFormarProcessorListener { + + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + + TWhereClause expressionList = (TWhereClause) nextNode; + + // add the expressionList + + WhereListCommaProcessor lColumnlistCommaProcessor = new WhereListCommaProcessor(); + lColumnlistCommaProcessor.setOptions(options); + + lColumnlistCommaProcessor.process(expressionList, options, pData); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/WithResultListFormatProcessorListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/WithResultListFormatProcessorListener.java new file mode 100644 index 0000000000000000000000000000000000000000..5203a9685dc4cf5035bf964d8cfea86a29d255cd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/listimpl/WithResultListFormatProcessorListener.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.listimpl; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.WithColumnlistCommaProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TResultColumnList; + +/** + * + * Title: WithResultListFormatProcessorListener + * + * @since 3.0.0 + */ +public class WithResultListFormatProcessorListener extends ResultListFormatProcessorListener { + + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + + TResultColumnList expressionList = (TResultColumnList) nextNode; + + // add the expressionList + + WithColumnlistCommaProcessor lColumnlistCommaProcessor = new WithColumnlistCommaProcessor(); + lColumnlistCommaProcessor.setOptions(options); + lColumnlistCommaProcessor.setAddPreSpace(isAddPreSpace()); + lColumnlistCommaProcessor.process(expressionList, options, pData); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/loop/LoopFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/loop/LoopFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..94f3d8b941a35f5ddc58323c6a815b038b42db40 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/loop/LoopFormatProcessor.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.loop; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.loop.TLoopSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * Title: LoopStmtFormatProcessor + * + * @since 3.0.0 + */ +public class LoopFormatProcessor extends AbstractProcessor { + + /** + * Gets the options process data. + * + * @param selectAstNode the select ast node + * @param pData the data + * @param options the options + * @return the options process data + */ + public OptionsProcessData getOptionsProcessData(TLoopSqlStatement selectAstNode, OptionsProcessData pData, + FmtOptionsIf options) { + + OptionsProcessData lOptionsProcessData = getNewOptionsDataBean(pData, 0); + + return lOptionsProcessData; + } + + /** + * Gets the start node. + * + * @param selectAstNode the select ast node + * @return the start node + */ + @Override + public TParseTreeNode getStartNode(TLoopSqlStatement selectAstNode) { + return selectAstNode.getStartNode(); + } + + /** + * Checks if is clone data. + * + * @return true, if is clone data + */ + public boolean isCloneData() { + return true; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/loop/ast/LoopASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/loop/ast/LoopASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..feb9cd2abe9f04f287dcde5fb7c462824ca5d6d1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/loop/ast/LoopASTNodeFormatProcessor.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.loop.ast; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessorUtils; +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.AddEmptyPreTextFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.loop.TLoopASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: LoopASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class LoopASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * the beforeProcess + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + + TLoopASTNode selectAstNode = (TLoopASTNode) node; + + addFormatProcessListener(selectAstNode.getStartNode(), getLoopProcessorListener()); + + addFormatProcessListener(selectAstNode.getEndLoop(), new IFormarProcessorListener() { + + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + int offset = pData.getParentOffSet(); + ProcessorUtils.addNewLineBefore(nextNode, offset, options); + AbstractProcessorUtils.processParseTreeNode(nextNode, options, pData, false); + } + }); + + } + + private IFormarProcessorListener getLoopProcessorListener() { + return this.getOptions().isLoopOnNewLine() ? new IFormarProcessorListener() { + + @Override + public void formatProcess(TParseTreeNode nextNode, FmtOptionsIf options, OptionsProcessData pData) { + int offset = pData.getOffSet(); + pData.setParentOffSet(offset); + ProcessorUtils.addNewLineBefore(nextNode, offset, options); + AbstractProcessorUtils.processParseTreeNode(nextNode, options, pData, false); + nextNode.setCheckPreviousNewLine(Boolean.TRUE); + } + } : new AddEmptyPreTextFormatProcessorListener() { + /** + * the changeOptionsData + */ + protected void changeOptionsData(OptionsProcessData pData) { + pData.setParentOffSet(pData.getOffSet()); + } + + }; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/merge/MergeStmtFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/merge/MergeStmtFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..0cd92a72508f4f255dbdd4f93454a50eb9dd0f81 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/merge/MergeStmtFormatProcessor.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.merge; + +import org.opengauss.mppdbide.gauss.format.consts.FormatItemsType; +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml.TMergeSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * Title: WithStmtFormatProcessor + * + * @since 3.0.0 + */ +public class MergeStmtFormatProcessor extends AbstractProcessor { + /** + * return options of proceesed data + * + * @param selectAstNode selected node to process + * @param pData options data while process + * @param options options for format + * @return returns the options data + */ + public OptionsProcessData getOptionsProcessData(TMergeSqlStatement selectAstNode, OptionsProcessData pData, + FmtOptionsIf options) { + int maxKeywordWidth = getMaxKeywordWidth(selectAstNode, options); + + OptionsProcessData lOptionsProcessData = super.getNewOptionsDataBean(pData, maxKeywordWidth); + + lOptionsProcessData.setFormatItemsType(FormatItemsType.UNKNOWN); + return lOptionsProcessData; + } + + /** + * return start node + * + * @param selectAstNode node to which startnode to be returned + * @return return start node + */ + @Override + public TParseTreeNode getStartNode(TMergeSqlStatement selectAstNode) { + return selectAstNode.getStartNode(); + } + + /** + * return true is data is cloned + * + * @return return true is data is cloned else false + */ + public boolean isCloneData() { + return true; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/merge/ast/MergeASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/merge/ast/MergeASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..d63642a2506c93526bf7550973df9d857a28768e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/merge/ast/MergeASTNodeFormatProcessor.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.merge.ast; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.AddEmptyPreTextFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.NewlineFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.NewlineWithOffsetSqlNodeFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.NoPreTextFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.WhereListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.exception.GaussDBSQLParserException; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.merge.TMergeASTNode; + +/** + * Title: WithASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class MergeASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + /** + * adds listeners to the node before process + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + TMergeASTNode mergeNode = getMergeAstNode(node); + + addFormatProcessListener(mergeNode.getSrcTable(), new AddEmptyPreTextFormatProcessorListener()); + + addFormatProcessListener(mergeNode.getUsing(), new NewlineWithOffsetSqlNodeFormatProcessorListener()); + + addFormatProcessListener(mergeNode.getDestTable(), new AddEmptyPreTextFormatProcessorListener()); + + addFormatProcessListener(mergeNode.getOn(), new NewlineFormatProcessorListener()); + + addFormatProcessListener(mergeNode.getOnEndBracket(), new NoPreTextFormatProcessorListener()); + + addFormatProcessListener(node.getItemList(), new WhereListFormatProcessorListener()); + } + + private TMergeASTNode getMergeAstNode(TBasicASTNode node) { + if (node instanceof TMergeASTNode) { + return (TMergeASTNode) node; + } + throw new GaussDBSQLParserException("Unable to typecase the statement"); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/merge/ast/MergeWithASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/merge/ast/MergeWithASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..37be4d228445195f39b4d3b6576c54b85e2721bf --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/merge/ast/MergeWithASTNodeFormatProcessor.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.merge.ast; + +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.AddEmptyPreTextFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.NewlineWithIndentFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.NewlineWithProcessFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.exception.GaussDBSQLParserException; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.merge.TMergeWhenASTNode; + +/** + * Title: WithASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class MergeWithASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + /** + * adds listeners to the node before process + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + + TMergeWhenASTNode mergeNode = getMergeWhenASTNode(node); + + addFormatProcessListener(mergeNode.getWhenMatch(), new AddEmptyPreTextFormatProcessorListener()); + + addFormatProcessListener(mergeNode.getMatchDML(), new NewlineWithIndentFormatProcessorListener() { + /** + * options data to change + */ + protected void changeOptionsData(OptionsProcessData pData) { + pData.setOffSet(pData.getParentOffSet()); + } + }); + + addFormatProcessListener(mergeNode.getWhenNotMatch(), new NewlineWithProcessFormatProcessorListener()); + + addFormatProcessListener(mergeNode.getInsertDML(), new NewlineWithIndentFormatProcessorListener() { + /** + * options data to change + */ + protected void changeOptionsData(OptionsProcessData pData) { + pData.setOffSet(pData.getParentOffSet()); + } + }); + } + + private TMergeWhenASTNode getMergeWhenASTNode(TBasicASTNode node) { + if (node instanceof TMergeWhenASTNode) { + return (TMergeWhenASTNode) node; + } + throw new GaussDBSQLParserException("Unable to typecase the statement"); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/node/SqlNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/node/SqlNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..f52f648cc505e463c09de3f63816b8f044c6b5ae --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/node/SqlNodeFormatProcessor.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.node; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessor; +import org.opengauss.mppdbide.gauss.format.processor.utils.ProcessorUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: SqlNodeFormatProcessor + * + * @since 3.0.0 + */ +public class SqlNodeFormatProcessor extends AbstractProcessor { + + @Override + public void process(TSqlNode selectAstNode, FmtOptionsIf options, OptionsProcessData pData, boolean addPreSpace) { + if (addPreSpace) { + ProcessorUtils.addPreEmptyText(selectAstNode, pData); + } + pData.addOffSet(selectAstNode.getNodeText().length()); + } + + @Override + public TParseTreeNode getStartNode(TSqlNode selectAstNode) { + return selectAstNode.getStartNode(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/AbstractASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/AbstractASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..1a26010df7857e5433cea6f1bfc56c52f9942ecf --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/AbstractASTNodeFormatProcessor.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.select; + +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessor; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.ASTStartNodeFormatProcessorListener; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: AbstractASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class AbstractASTNodeFormatProcessor extends AbstractProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + node.getKeywordNode().setFormatListener(new ASTStartNodeFormatProcessorListener()); + + } + + /** + * Gets the start node. + * + * @param selectAstNode the select ast node + * @return the start node + */ + public TParseTreeNode getStartNode(TBasicASTNode selectAstNode) { + return selectAstNode.getKeywordNode(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/FromASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/FromASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..2be9088329395a685ac7692039a32f06c02b0fe7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/FromASTNodeFormatProcessor.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.select; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.FromListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * + * Title: FromASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class FromASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + + addFormatProcessListener(node.getItemList(), new FromListFormatProcessorListener()); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/GroupByASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/GroupByASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..02e730688792140dd904cf21e5134a5c4b87963d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/GroupByASTNodeFormatProcessor.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.select; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.ResultListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * + * Title: GroupByASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class GroupByASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + + node.getItemList().setFormatListener(new ResultListFormatProcessorListener()); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/HavingASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/HavingASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..5adcc2d6cf71879ef9828d1b5a76ea702d6b8535 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/HavingASTNodeFormatProcessor.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.select; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.WhereListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * + * Title: HavingASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class HavingASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + if (node.getItemList() != null) { + node.getItemList().setFormatListener(new WhereListFormatProcessorListener()); + } + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/LimitASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/LimitASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..09ac39b3323c16845fc212e2e9fad50232298db0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/LimitASTNodeFormatProcessor.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.select; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.AddEmptyPreTextFormatProcessorListener; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.limit.TLimitASTNode; + +/** + * + * Title: LimitASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class LimitASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + + TLimitASTNode tLimitASTNode = (TLimitASTNode) node; + // add listener to the startnode + addFormatProcessListener(tLimitASTNode.getLimitExpression(), new AddEmptyPreTextFormatProcessorListener()); + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/OrderByASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/OrderByASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..070550266aad49204ffd5b14dae11649fd386b29 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/OrderByASTNodeFormatProcessor.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.select; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.ResultListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * + * Title: OrderByASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class OrderByASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + node.getItemList().setFormatListener(new ResultListFormatProcessorListener()); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/SelectASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/SelectASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..324602aa5832af06866fa27b66ae633faa6c8ec1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/SelectASTNodeFormatProcessor.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.select; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.ASTStartNodeNoNewlineFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.ResultListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.SqlHintInfoFormatProcessorListener; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select.TSelectASTNode; + +/** + * + * Title: SelectASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class SelectASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + + TSelectASTNode selectAstNode = (TSelectASTNode) node; + + node.getKeywordNode().setFormatListener(new ASTStartNodeNoNewlineFormatProcessorListener()); + + addFormatProcessListener(node.getItemList(), new ResultListFormatProcessorListener()); + + addFormatProcessListener(selectAstNode.getHintInfo(), new SqlHintInfoFormatProcessorListener()); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/SelectStmtFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/SelectStmtFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..9d70d14b915e6d8c21238fe34274089551de0452 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/SelectStmtFormatProcessor.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.select; + +import org.opengauss.mppdbide.gauss.format.consts.FormatItemsType; +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml.TSelectSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * Title: SelectStmtFormatProcessor + * + * @since 3.0.0 + */ +public class SelectStmtFormatProcessor extends AbstractProcessor { + + /** + * Gets the options process data. + * + * @param selectAstNode the select ast node + * @param pData the data + * @param options the options + * @return the options process data + */ + public OptionsProcessData getOptionsProcessData(TSelectSqlStatement selectAstNode, OptionsProcessData pData, + FmtOptionsIf options) { + int maxKeywordWidth = getMaxKeywordWidth(selectAstNode, options); + + if (SQLTokenConstants.T_SQL_KEYWORK_UNION == pData.getLastFormatType()) { + pData.setPutStmtNewLine(true); + pData.setLastFormatType(0); + } + OptionsProcessData lOptionsProcessData = getNewOptionsDataBean(pData, maxKeywordWidth); + lOptionsProcessData.setFormatItemsType(FormatItemsType.SELECT); + return lOptionsProcessData; + } + + /** + * Gets the new options data bean. + * + * @param pData the data + * @param maxKeywordWidth the max keyword width + * @return the new options data bean + */ + protected OptionsProcessData getNewOptionsDataBean(OptionsProcessData pData, int maxKeywordWidth) { + OptionsProcessData lOptionsProcessData = new OptionsProcessData(); + lOptionsProcessData.setMaxKeywordLength(maxKeywordWidth); + lOptionsProcessData.setOffSet(pData.getOffSet()); + lOptionsProcessData.setParentOffSet(pData.getParentOffSet()); + lOptionsProcessData.setPutStmtNewLine(pData.isPutStmtNewLine()); + return lOptionsProcessData; + } + + /** + * Gets the start node. + * + * @param selectAstNode the select ast node + * @return the start node + */ + @Override + public TParseTreeNode getStartNode(TSelectSqlStatement selectAstNode) { + return selectAstNode.getStartNode(); + } + + /** + * Checks if is clone data. + * + * @return true, if is clone data + */ + public boolean isCloneData() { + return true; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/WhereASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/WhereASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..7c2b71f86e806ec39e6fab6ce350cfa4ddf561a2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/WhereASTNodeFormatProcessor.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.select; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.WhereListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * + * Title: WhereASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class WhereASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + node.getItemList().setFormatListener(new WhereListFormatProcessorListener()); + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/WindowASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/WindowASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..da5be1ba403121cee0fdce72603beb3b8576f974 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/select/WindowASTNodeFormatProcessor.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.select; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.ResultListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * + * Title: WindowASTNodeFormatProcessor + * + * Description: The Class WindowASTNodeFormatProcessor. + * + * @since 3.0.0 + */ +public class WindowASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + + super.beforeProcess(node); + + addFormatProcessListener(node.getItemList(), new ResultListFormatProcessorListener()); + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/union/UnionFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/union/UnionFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..8aa7006cb5e549cbde97bae223185b213c5e318a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/union/UnionFormatProcessor.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.union; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.common.TUnionSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * Title: LoopStmtFormatProcessor + * + * @since 3.0.0 + */ +public class UnionFormatProcessor extends AbstractProcessor { + /** + * return options of proceesed data + * + * @param selectAstNode selected node to process + * @param pData options data while process + * @param options options for format + * @return returns the options data + */ + public OptionsProcessData getOptionsProcessData(TUnionSqlStatement selectAstNode, OptionsProcessData pData, + FmtOptionsIf options) { + pData.setLastFormatType(SQLTokenConstants.T_SQL_KEYWORK_UNION); + OptionsProcessData lOptionsProcessData = getNewOptionsDataBean(pData, 0); + return lOptionsProcessData; + } + + /** + * return start node + * + * @param selectAstNode custom select statement + * @return returns the start node + */ + @Override + public TParseTreeNode getStartNode(TUnionSqlStatement selectAstNode) { + return selectAstNode.getStartNode(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/union/ast/UnionASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/union/ast/UnionASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..5df3d7052bc126b6c52dcb8b3afc7fcf72966bc8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/union/ast/UnionASTNodeFormatProcessor.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.union.ast; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.AddEmptyPreTextFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.exception.GaussDBSQLParserException; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.union.TUnionASTNode; + +/** + * Title: WithASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class UnionASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + /** + * before process + * + * @param node node to format + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + TUnionASTNode unionAst = getAstNode(node); + + addFormatProcessListener(unionAst.getRemainingStmt(), new AddEmptyPreTextFormatProcessorListener()); + } + + private TUnionASTNode getAstNode(TBasicASTNode node) { + if (!(node instanceof TUnionASTNode)) { + throw new GaussDBSQLParserException("Unable to Cast the AST Node"); + } + return (TUnionASTNode) node; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/update/UpdateStmtFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/update/UpdateStmtFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..bef60f68ce8ec69385ffe26ca0ca522022bca92e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/update/UpdateStmtFormatProcessor.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.update; + +import org.opengauss.mppdbide.gauss.format.consts.FormatItemsType; +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml.TUpdateSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: UpdateStmtFormatProcessor + * + * @since 3.0.0 + */ +public class UpdateStmtFormatProcessor extends AbstractProcessor { + + /** + * Gets the options process data. + * + * @param selectAstNode the select ast node + * @param pData the data + * @param options the options + * @return the options process data + */ + public OptionsProcessData getOptionsProcessData(TUpdateSqlStatement selectAstNode, OptionsProcessData pData, + FmtOptionsIf options) { + + int maxKeywordWidth = getMaxKeywordWidth(selectAstNode, options); + + OptionsProcessData lOptionsProcessData = getNewOptionsDataBean(pData, maxKeywordWidth); + + lOptionsProcessData.setFormatItemsType(FormatItemsType.UPDATE); + + return lOptionsProcessData; + } + + /** + * Gets the start node. + * + * @param selectAstNode the select ast node + * @return the start node + */ + @Override + public TParseTreeNode getStartNode(TUpdateSqlStatement selectAstNode) { + return selectAstNode.getStartNode(); + } + + /** + * Checks if is clone data. + * + * @return true, if is clone data + */ + public boolean isCloneData() { + return true; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/update/ast/UpdateIntoASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/update/ast/UpdateIntoASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..404226f3661b5c1cdf3feb401afd7dd6c4b5c0bc --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/update/ast/UpdateIntoASTNodeFormatProcessor.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.update.ast; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.ASTStartNodeNoNewlineFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.FromListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * + * Title: UpdateIntoASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class UpdateIntoASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + addFormatProcessListener(node.getKeywordNode(), new ASTStartNodeNoNewlineFormatProcessorListener()); + addFormatProcessListener(node.getItemList(), new FromListFormatProcessorListener()); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/update/ast/UpdateSetASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/update/ast/UpdateSetASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..cdea9f2d60b5c63b53510e8b5737a99533c61862 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/update/ast/UpdateSetASTNodeFormatProcessor.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.update.ast; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.ResultListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * + * Title: UpdateSetASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class UpdateSetASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + addFormatProcessListener(node.getItemList(), new ResultListFormatProcessorListener()); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/utils/ProcessorUtils.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/utils/ProcessorUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..535202aec6043146c1ad406a32191be34b2089a7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/utils/ProcessorUtils.java @@ -0,0 +1,254 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.utils; + +import org.opengauss.mppdbide.gauss.format.consts.FormatPaddingEnum; +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: ProcessorUtils + * + * @since 3.0.0 + */ +public class ProcessorUtils { + + /** + * Adds the pre empty text. + * + * @param node the node + * @param bean the bean + */ + public static void addPreEmptyText(TParseTreeNode node, OptionsProcessData bean) { + addPreText(node, " ", bean); + } + + /** + * Adds the pre text. + * + * @param node the node + * @param preText the pre text + * @param bean the bean + */ + public static void addPreText(TParseTreeNode node, String preText, OptionsProcessData bean) { + node.addPreText(preText); + bean.addOffSet(preText.length()); + } + + /** + * Adds the pre text. + * + * @param node the node + * @param offset the offset + * @param preText the pre text + * @return the int + */ + public static int addPreText(TParseTreeNode node, int offset, String preText) { + int offSetRet = offset; + if (null == node) { + return offSetRet; + } + node.addPreText(preText); + offSetRet += preText.length(); + + return offSetRet; + } + + /** + * Adds the pre text. + * + * @param node the node + * @param offSet the off set + * @param preText the pre text + * @return the int + */ + public static int addPreText(TSqlNode node, int offSet, String preText) { + int offSetRet = offSet; + + if (null == node) { + return offSetRet; + } + + node.addPreText(preText); + offSetRet += preText.length(); + + offSetRet += node.getNodeText().length(); + + return offSetRet; + } + + /** + * Adds the new line before withindent. + * + * @param node the node + * @param pData the data + * @param options the options + */ + public static void addNewLineBeforeWithindent(TParseTreeNode node, OptionsProcessData pData, FmtOptionsIf options) { + addNewLineBefore(node, pData.getOffSet(), options); + addIndentBefore(node, pData, options); + + } + + /** + * Adds the new line before. + * + * @param node the node + * @param offSet the off set + * @param options the options + */ + public static void addNewLineBefore(TParseTreeNode node, int offSet, FmtOptionsIf options) { + + node.addPreText(System.lineSeparator()); + + StringBuilder lsb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + fillSBWithIndendationChars(offSet, lsb, options); + node.addPreText(lsb.toString()); + + } + + /** + * Adds the indent before. + * + * @param node the node + * @param pData the data + * @param options the options + */ + public static void addIndentBefore(TParseTreeNode node, OptionsProcessData pData, FmtOptionsIf options) { + + StringBuilder lsb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + fillSBWithIndendationChars(options.getIndend(), lsb, options); + node.addPreText(lsb.toString()); + + pData.addOffSet(options.getIndend()); + pData.setPreIndentOffSet(pData.getOffSet()); + } + + /** + * Adds the new line after. + * + * @param node the node + * @param offset the offset + * @param options the options + */ + public static void addNewLineAfter(TParseTreeNode node, int offset, FmtOptionsIf options) { + node.addPostText(System.lineSeparator()); + StringBuilder lsb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + fillSBWithIndendationChars(offset, lsb, options); + node.addPostText(lsb.toString()); + } + + /** + * Adds the post text. + * + * @param node the node + * @param pData the data + * @param postText the post text + */ + public static void addPostText(TParseTreeNode node, OptionsProcessData pData, String postText) { + node.addPostText(postText); + pData.addOffSet(postText.length()); + } + + /** + * Format start node. + * + * @param select the select + * @param options the options + * @param pData the data + */ + public static void formatStartNode(TSqlNode select, FmtOptionsIf options, OptionsProcessData pData) { + + int offsetLen = pData.getMaxKeywordLength(); + if (pData.getMaxKeywordLength() == 0) { + offsetLen = select.getNodeText().length(); + } + formatStartNode(select, options, pData.getMaxKeywordLength()); + pData.addOffSet(offsetLen); + + } + + /** + * Format start node. + * + * @param select the select + * @param options the options + * @param maxKeyword the max keyword + */ + public static void formatStartNode(TSqlNode select, FmtOptionsIf options, int maxKeyword) { + + FormatPaddingEnum paddingType = StmtKeywordAlignUtil.getPaddingType(options); + + int paddingLength = select.getNodeText().length() < maxKeyword ? maxKeyword - select.getNodeText().length() : 0; + + if (paddingLength > 0) { + + StringBuilder lsb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + fillSBWithIndendationChars(paddingLength, lsb, options); + + if (FormatPaddingEnum.RPAD == paddingType) { + select.addPostText(lsb.toString()); + } else { + select.addPreText(lsb.toString()); + } + } + } + + /** + * Fill SB with indendation chars. + * + * @param offset the offset + * @param sb the sb + * @param options the options + */ + public static void fillSBWithIndendationChars(int offset, StringBuilder sb, FmtOptionsIf options) { + int actualOffset = offset; + int numTabs = 0; + + int numSpaces = 0; + if (options.useTabChar() && options.getTabCharSize() > 0) { + numTabs = actualOffset / options.getTabCharSize(); + numSpaces = actualOffset % options.getTabCharSize(); + } else { + numSpaces = actualOffset; + } + while (numTabs-- > 0) { + sb.append("\t"); + } + while (numSpaces-- > 0) { + sb.append(" "); + } + } + + /** + * Checks if is node list available. + * + * @param itemList the item list + * @return true, if is node list available + */ + public static boolean isNodeListAvailable(TParseTreeNodeList itemList) { + if (null != itemList && !itemList.getResultList().isEmpty()) { + return true; + } + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/utils/StmtKeywordAlignUtil.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/utils/StmtKeywordAlignUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..7aed90e11f906f0a6246cecacabe0e8298b1b9f5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/utils/StmtKeywordAlignUtil.java @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.utils; + +import java.util.List; + +import org.apache.commons.lang3.StringUtils; + +import org.opengauss.mppdbide.gauss.format.consts.FormatPaddingEnum; +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.common.TCTEASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpressionNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: StmtKeywordAlignUtil + * + * @since 3.0.0 + */ +public abstract class StmtKeywordAlignUtil { + + /** + * Gets the max keyword width. + * + * @param selectStmt the select stmt + * @param fmtOpt the fmt opt + * @return the max keyword width + */ + public static int getMaxKeywordWidth(TCustomSqlStatement selectStmt, FmtOptionsIf fmtOpt) { + + int maxKeywordLength = 0; + int nodeLength = 0; + + FormatPaddingEnum paddingType = getPaddingType(fmtOpt); + + if (FormatPaddingEnum.NOPAD != paddingType) { + + TParseTreeNode nextAstNode = selectStmt.getStartNode(); + + while (null != nextAstNode) { + + if (nextAstNode instanceof TCTEASTNode) { + nodeLength = getMaxKeywordWithOfCTENode((TCTEASTNode) nextAstNode, fmtOpt); + } else { + + TSqlNode startKeyworkNode = (TSqlNode) nextAstNode.getStartNode(); + if (null == startKeyworkNode) { + break; + } + nodeLength = startKeyworkNode.getNodeText().length(); + } + if (maxKeywordLength < nodeLength) { + maxKeywordLength = nodeLength; + } + + nextAstNode = nextAstNode.getNextNode(); + } + } + + return maxKeywordLength; + + } + + private static int getMaxKeywordWithOfCTENode(TCTEASTNode customAstNode, FmtOptionsIf fmtOpt) { + int maxKeywordLength = 0; + + TExpression stmtExpression = customAstNode.getStmtExpression(); + if (null != stmtExpression) { + List expList = stmtExpression.getExpList(); + int nodeLength = 0; + for (TExpressionNode expNode : expList) { + TParseTreeNode customStmt = expNode.getCustomStmt(); + if (null != customStmt && customStmt instanceof TCustomSqlStatement) { + nodeLength = getMaxKeywordWidth((TCustomSqlStatement) customStmt, fmtOpt); + if (maxKeywordLength < nodeLength) { + maxKeywordLength = nodeLength; + } + + } + } + } + + return maxKeywordLength; + + } + + /** + * Gets the padding string. + * + * @param paddingType the padding type + * @param maxKeywordLength the max keyword length + * @param startKeyworkNode the start keywork node + * @return the padding string + */ + public static String getPaddingString(FormatPaddingEnum paddingType, int maxKeywordLength, + TSqlNode startKeyworkNode) { + if (FormatPaddingEnum.RPAD == paddingType) { + return StringUtils.leftPad(startKeyworkNode.getNodeText(), maxKeywordLength, " "); + } + return startKeyworkNode.getNodeText(); + } + + /** + * Gets the padding type. + * + * @param fmtOpt the fmt opt + * @return the padding type + */ + public static FormatPaddingEnum getPaddingType(FmtOptionsIf fmtOpt) { + if (fmtOpt.leftAlignKeywords() && fmtOpt.leftAlignItems()) { + return FormatPaddingEnum.RPAD; + } else if (!fmtOpt.leftAlignKeywords()) { + return FormatPaddingEnum.LPAD; + } + return FormatPaddingEnum.NOPAD; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/with/WithASTNodeFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/with/WithASTNodeFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..310d8f9c5cfdebb4547fa0e618944da833cc18df --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/with/WithASTNodeFormatProcessor.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.with; + +import org.opengauss.mppdbide.gauss.format.processor.listimpl.ASTStartNodeNoNewlineFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.listimpl.WithResultListFormatProcessorListener; +import org.opengauss.mppdbide.gauss.format.processor.select.AbstractASTNodeFormatProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * + * Title: WithASTNodeFormatProcessor + * + * @since 3.0.0 + */ +public class WithASTNodeFormatProcessor extends AbstractASTNodeFormatProcessor { + + /** + * Before process. + * + * @param node the node + */ + public void beforeProcess(TBasicASTNode node) { + super.beforeProcess(node); + // add listener to the startnode + + addFormatProcessListener(node.getKeywordNode(), new ASTStartNodeNoNewlineFormatProcessorListener()); + + addFormatProcessListener(node.getItemList(), new WithResultListFormatProcessorListener()); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/with/WithStmtFormatProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/with/WithStmtFormatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..e8f2e03d709b12297a439bf6f70e4e4f6769d89e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/processor/with/WithStmtFormatProcessor.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.processor.with; + +import org.opengauss.mppdbide.gauss.format.consts.FormatItemsType; +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessor; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml.TWithSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: WithStmtFormatProcessor + * + * @since 3.0.0 + */ +public class WithStmtFormatProcessor extends AbstractProcessor { + + /** + * Gets the options process data. + * + * @param selectAstNode the select ast node + * @param pData the data + * @param options the options + * @return the options process data + */ + public OptionsProcessData getOptionsProcessData(TWithSqlStatement selectAstNode, OptionsProcessData pData, + FmtOptionsIf options) { + + int maxKeywordWidth = getMaxKeywordWidth(selectAstNode, options); + + OptionsProcessData lOptionsProcessData = super.getNewOptionsDataBean(pData, maxKeywordWidth); + + lOptionsProcessData.setFormatItemsType(FormatItemsType.UNKNOWN); + + return lOptionsProcessData; + } + + /** + * Gets the start node. + * + * @param selectAstNode the select ast node + * @return the start node + */ + @Override + public TParseTreeNode getStartNode(TWithSqlStatement selectAstNode) { + return selectAstNode.getStartNode(); + } + + /** + * Checks if is clone data. + * + * @return true, if is clone data + */ + public boolean isCloneData() { + return true; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/stmtformatter/FormatterFactory.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/stmtformatter/FormatterFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..003f74240c3748783c60dcb5e90b2ad27c9cb59e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/stmtformatter/FormatterFactory.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.stmtformatter; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessor; +import org.opengauss.mppdbide.gauss.format.processor.ProcessorFactory; +import org.opengauss.mppdbide.gauss.format.utils.FormatterUtils; +import org.opengauss.mppdbide.gauss.format.utils.wrapper.FormatStringWrapper; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * Title: FormatterFactory + * + * @since 3.0.0 + */ +public class FormatterFactory { + + /** + * Format. + * + * @param sqlStmt the sql stmt + * @param options the options + * @param formatterOffset the formatter offset + * @return the string + */ + public static String format(TCustomSqlStatement sqlStmt, FmtOptionsIf options, int formatterOffset) { + + OptionsProcessData lOptionsProcessData = new OptionsProcessData(); + + lOptionsProcessData.setMaxKeywordLength(0); + lOptionsProcessData.setOffSet(formatterOffset); + lOptionsProcessData.setParentOffSet(0); + + AbstractProcessor proc = ProcessorFactory.getProcessor(sqlStmt); + if (null != proc) { + proc.setOptions(options); + proc.process(sqlStmt, options, lOptionsProcessData); + } + + FormatStringWrapper formatWrapper = new FormatStringWrapper(); + + FormatterUtils.prepareFormatString(sqlStmt, formatWrapper, options); + + return formatWrapper.toString(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/stmtformatter/type/AbstractAllStmtsFormatter.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/stmtformatter/type/AbstractAllStmtsFormatter.java new file mode 100644 index 0000000000000000000000000000000000000000..d4d747d70b2146cf0382a08af158c7c2b9396b38 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/stmtformatter/type/AbstractAllStmtsFormatter.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.stmtformatter.type; + +/** + * Title: AbstractAllStmtsFormatter + * + * @since 3.0.0 + */ +public class AbstractAllStmtsFormatter { +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/stmtformatter/type/AbstractStmtFormatter.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/stmtformatter/type/AbstractStmtFormatter.java new file mode 100644 index 0000000000000000000000000000000000000000..b37b6577b8bb4fce6efc2fa8c37f49b40b317cc7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/stmtformatter/type/AbstractStmtFormatter.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.stmtformatter.type; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; + +/** + * + * Title: AbstractStmtFormatter + * + * @since 3.0.0 + */ +public class AbstractStmtFormatter { + + private FmtOptionsIf options = null; + + public FmtOptionsIf getOptions() { + return options; + } + + public void setOptions(FmtOptionsIf options) { + this.options = options; + } + + /** + * stmt forma + * + * @param stmt stmt to be formatted + * @return returns the statement string + */ + public String format(E stmt) { + return doFormat(stmt); + } + + /** + * before stmt format + * + * @param stmt stmt to be formatted + */ + protected void beforeFormat(E stmt) { + } + + /** + * stmt format + * + * @param stmt stmt to be formatted + * @return returns the statement string + */ + protected String doFormat(E stmt) { + return null; + } + + /** + * after Stmt Format + * + * @param stmt stmt to be formatted + */ + protected void afterFormat(E stmt) { + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/stmtformatter/type/SelectStmtFormatter.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/stmtformatter/type/SelectStmtFormatter.java new file mode 100644 index 0000000000000000000000000000000000000000..3222a9678c26df506a89e76ab6039a7e5f6481c1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/stmtformatter/type/SelectStmtFormatter.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.stmtformatter.type; + +import org.opengauss.mppdbide.gauss.format.option.OptionsProcessData; +import org.opengauss.mppdbide.gauss.format.processor.AbstractProcessor; +import org.opengauss.mppdbide.gauss.format.processor.ProcessorFactory; +import org.opengauss.mppdbide.gauss.format.processor.utils.StmtKeywordAlignUtil; +import org.opengauss.mppdbide.gauss.format.utils.FormatterUtils; +import org.opengauss.mppdbide.gauss.format.utils.wrapper.FormatStringWrapper; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml.TSelectSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * Title: SelectStmtFormatter + * + * @since 3.0.0 + */ +public class SelectStmtFormatter extends AbstractStmtFormatter { + + /** + * Do format. + * + * @param sql the sql + * @return the string + */ + protected String doFormat(TSelectSqlStatement sql) { + + int maxKeywordWidth = StmtKeywordAlignUtil.getMaxKeywordWidth(sql, getOptions()); + + OptionsProcessData lOptionsProcessData = new OptionsProcessData(); + + lOptionsProcessData.setMaxKeywordLength(maxKeywordWidth); + lOptionsProcessData.setOffSet(0); + lOptionsProcessData.setParentOffSet(0); + + AbstractProcessor proc = ProcessorFactory.getProcessor(sql); + if (null != proc) { + proc.setOptions(getOptions()); + proc.process(sql, getOptions(), lOptionsProcessData); + } + + FormatStringWrapper formatWrapper = new FormatStringWrapper(); + + FormatterUtils.prepareFormatString(sql, formatWrapper, getOptions()); + + return formatWrapper.toString(); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/utils/FormatterUtils.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/utils/FormatterUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..270e9d83d4522a9d2466a4d4e886b585be197d6d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/utils/FormatterUtils.java @@ -0,0 +1,244 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.utils; + +import java.util.List; +import java.util.ListIterator; + +import org.opengauss.mppdbide.gauss.format.consts.EmptyLinesEnum; +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.utils.wrapper.FormatStringWrapper; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.utils.FullNodeExpressionType; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TAbstractListItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpressionNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.fullstmt.TFullListNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.fullstmt.TFullStmt; +import org.opengauss.mppdbide.gauss.sqlparser.stmtbeanif.StatementBeanIf; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * Title: FormatterUtils + * + * @since 3.0.0 + */ +public class FormatterUtils { + + /** + * prepareFormatString from the given Parse Object + * + * @param selectAstNode parse object + * @param formatWrapper format string to keep the Format String + */ + public static void prepareFormatString(TParseTreeNode selectAstNode, FormatStringWrapper formatWrapper, + FmtOptionsIf options) { + prepareFormatString(selectAstNode, formatWrapper, true, options); + } + + /** + * prepareFormatString from the given Parse Object + * + * @param selectAstNode parse object + * @param formatWrapper format string to keep the Format String + * @param isAllNodes to iterate all nodes or only current node + */ + public static void prepareFormatString(TParseTreeNode selectAstNode, FormatStringWrapper formatWrapper, + boolean isAllNodes, FmtOptionsIf options) { + TParseTreeNode startKeyworkNode = selectAstNode.getStartNode(); + + while (null != startKeyworkNode) { + addStringToList(formatWrapper, startKeyworkNode.getPreText(), startKeyworkNode); + if (startKeyworkNode instanceof TSqlNode) { + String strNodeText = ((TSqlNode) startKeyworkNode).getNodeText(); + if (MPPDBIDEConstants.ESCAPE_FORWARDSLASH.equals(strNodeText)) { + formatWrapper.append(System.lineSeparator()); + } + formatWrapper.append(strNodeText); + } else if (isInstanceOfTreeParseNodeList(startKeyworkNode)) { + TParseTreeNodeList list = (TParseTreeNodeList) startKeyworkNode; + for (TAbstractListItem lTListItem : list.getResultList()) { + prepareFormatString(lTListItem, formatWrapper, options); + } + } else if (isExpression(startKeyworkNode)) { + TExpression exp = (TExpression) startKeyworkNode; + for (TExpressionNode expNode : exp.getExpList()) { + addStringToList(formatWrapper, expNode.getPreText(), expNode); + prepareFormatString(expNode, formatWrapper, options); + } + } else if (startKeyworkNode instanceof TFullStmt) { + prepareFullStmtFormatString(formatWrapper, startKeyworkNode, options); + } else { + prepareFormatString(startKeyworkNode, formatWrapper, options); + } + + addCommentsAndPostText(formatWrapper, startKeyworkNode, options); + if (isAllNodes) { + startKeyworkNode = startKeyworkNode.getNextNode(); + } else { + startKeyworkNode = null; + } + + } + } + + private static boolean isExpression(TParseTreeNode startKeyworkNode) { + return startKeyworkNode instanceof TExpression; + } + + private static boolean isInstanceOfTreeParseNodeList(TParseTreeNode startKeyworkNode) { + return startKeyworkNode instanceof TParseTreeNodeList; + } + + private static void prepareFullStmtFormatString(FormatStringWrapper formatWrapper, TParseTreeNode startKeyworkNode, + FmtOptionsIf options) { + TFullStmt fullStmt = (TFullStmt) startKeyworkNode; + EmptyLinesEnum emptyLines = options.getEmptyLines(); + for (TParseTreeNode parserFullStmtNode : fullStmt.getStmtList()) { + if (parserFullStmtNode instanceof TFullListNode) { + TFullListNode fullNodeList = (TFullListNode) parserFullStmtNode; + addStringToList(formatWrapper, fullNodeList.getPreText(), fullNodeList); + + if (fullNodeList.getExpressionType() == FullNodeExpressionType.NEWLINES + && fullNodeList.getSqlTokenDataList().size() > 0 && emptyLines != EmptyLinesEnum.PRESERVE) { + if (emptyLines == EmptyLinesEnum.REMOVE) { + addCommentsAndPostText(formatWrapper, startKeyworkNode, options); + continue; + } else if (emptyLines == EmptyLinesEnum.MERGE) { + formatWrapper.append(System.lineSeparator()); + addCommentsAndPostText(formatWrapper, startKeyworkNode, options); + continue; + } + } + + for (StatementBeanIf sqlTokenDataList : fullNodeList.getSqlTokenDataList()) { + if (sqlTokenDataList instanceof ISQLTokenData) { + formatWrapper.append(((ISQLTokenData) sqlTokenDataList).getTokenStr()); + } else if (isFullStmtIns(sqlTokenDataList)) { + prepareFullStmtFormatString(formatWrapper, (TParseTreeNode) sqlTokenDataList, options); + } else { + prepareFormatString((TParseTreeNode) sqlTokenDataList, formatWrapper, options); + } + } + addCommentsAndPostText(formatWrapper, startKeyworkNode, options); + } else { + prepareFormatString(parserFullStmtNode, formatWrapper, options); + } + } + } + + private static boolean isFullStmtIns(StatementBeanIf sqlTokenDataList) { + return sqlTokenDataList instanceof TFullStmt; + } + + private static void addCommentsAndPostText(FormatStringWrapper formatWrapper, TParseTreeNode startKeyworkNode, + FmtOptionsIf options) { + addStringToListComments(formatWrapper, startKeyworkNode.getNextComments(), startKeyworkNode, options); + addStringToList(formatWrapper, startKeyworkNode.getPostText(), startKeyworkNode); + } + + private static void addStringToListComments(FormatStringWrapper formatWrapper, List preText, + TParseTreeNode parseNode, FmtOptionsIf options) { + if (null == preText) { + return; + } + + boolean isFirstLineIgnored = false; + + ListIterator commentsListItr = preText.listIterator(); + EmptyLinesEnum emptyLines = EmptyLinesEnum.REMOVE; + int newLineCount = 0; + + while (commentsListItr.hasNext()) { + String formatStr = commentsListItr.next(); + + String nextFormatStr = getNextCommentsString(commentsListItr); + + if (System.lineSeparator().equals(formatStr)) { + boolean isNextLineCom = isNextLineComment(nextFormatStr); + if (!isFirstLineIgnored && !isNextLineCom) { + isFirstLineIgnored = true; + continue; + } else { + newLineCount++; + } + + if (emptyLines == EmptyLinesEnum.REMOVE && !isNextLineCom) { + commentsListItr.remove(); + continue; + } else if (emptyLines == EmptyLinesEnum.MERGE && newLineCount > 1 && !isNextLineCom) { + commentsListItr.remove(); + continue; + } + + } else { + isFirstLineIgnored = false; + newLineCount = 0; + } + + formatWrapper.append(formatStr); + + } + } + + private static boolean isNextLineComment(String nextFormatStr) { + return null != nextFormatStr && (nextFormatStr.startsWith("--") || nextFormatStr.startsWith("/*")); + } + + private static String getNextCommentsString(ListIterator commentsListItr) { + String retVal = null; + if (commentsListItr.hasNext()) { + retVal = commentsListItr.next(); + commentsListItr.previous(); + } + return retVal; + } + + private static void addStringToList(FormatStringWrapper formatWrapper, List preText, + TParseTreeNode parseNode) { + if (null == preText) { + return; + } + + for (int itemCount = 0; itemCount < preText.size(); itemCount++) { + if (itemCount == 0 && parseNode.getCheckPreviousNewLine()) { + if (System.lineSeparator().equals(formatWrapper.getLastStringAdded()) + && System.lineSeparator().equals(preText.get(itemCount))) { + continue; + } + } + formatWrapper.append(preText.get(itemCount)); + } + } + + /** + * get the format string from parse noew + * + * @param itemListNode parse node + * @return return the parse String + */ + public static String getFormatString(TParseTreeNode itemListNode, FmtOptionsIf options) { + FormatStringWrapper formatWrapper = new FormatStringWrapper(); + + FormatterUtils.prepareFormatString(itemListNode, formatWrapper, false, options); + + return formatWrapper.toString(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/utils/wrapper/FormatStringWrapper.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/utils/wrapper/FormatStringWrapper.java new file mode 100644 index 0000000000000000000000000000000000000000..72323426eee4f933e926933a6fa56a21967c86ba --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/format/utils/wrapper/FormatStringWrapper.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.format.utils.wrapper; + +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: FormatStringWrapper + * + * @since 3.0.0 + */ +public class FormatStringWrapper { + private StringBuilder formatdata = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + private String lastStringAdded = null; + + /** + * returns the StringBuilder + * + * @return returns the StringBuilder which maintain the data + */ + public StringBuilder getFormatdata() { + return formatdata; + } + + /** + * returns the last string added + * + * @return String which is added latest + */ + public String getLastStringAdded() { + return lastStringAdded; + } + + /** + * set the lastStringAdded + * + * @param lastStringAdded set the lastStringAdded + */ + public void setLastStringAdded(String lastStringAdded) { + this.lastStringAdded = lastStringAdded; + } + + /** + * append the give text to the format data + * + * @param nodeText string to be appended + */ + public void append(String nodeText) { + lastStringAdded = nodeText; + formatdata.append(nodeText); + } + + /** + * returns the formatted string + */ + public String toString() { + return formatdata.toString(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLDDLToken.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLDDLToken.java new file mode 100644 index 0000000000000000000000000000000000000000..862e8b671f6e88da6f6773c0e196c34376c1e9db --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLDDLToken.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser; + +/** + * + * Title: SQLDDLToken + * + * @since 3.0.0 + */ +public class SQLDDLToken extends SQLToken { + + /** + * Instantiates a new SQLDDL token. + * + * @param tokenType the token type + * @param data the data + */ + public SQLDDLToken(int tokenType, Object data) { + super(tokenType, data); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLDDLTypeEnum.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLDDLTypeEnum.java new file mode 100644 index 0000000000000000000000000000000000000000..a52b903b60612b1599271a87b0754ae6a539bf88 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLDDLTypeEnum.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser; + +/** + * Title: SQLDDLEnum + * + * @since 3.0.0 + */ +public enum SQLDDLTypeEnum { + + /** + * The procedure. + */ + PROCEDURE, + + /** + * The function. + */ + FUNCTION, + + PACKAGE, + + /** + * The table. + */ + TABLE, + + /** + * The view. + */ + VIEW, + + /** + * The trigger. + */ + TRIGGER, + + /** + * The unknown. + */ + UNKNOWN +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLDMLToken.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLDMLToken.java new file mode 100644 index 0000000000000000000000000000000000000000..36e4981e44f621fba1a1662db0c89f07e8cd8255 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLDMLToken.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser; + +/** + * + * Title: SQLDMLToken + * + * @since 3.0.0 + */ +public class SQLDMLToken extends SQLToken { + + /** + * Instantiates a new SQLDML token. + * + * @param tokenType the token type + * @param data the data + */ + public SQLDMLToken(int tokenType, Object data) { + super(tokenType, data); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLDelimiterRule.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLDelimiterRule.java new file mode 100644 index 0000000000000000000000000000000000000000..7e6cdbe2fdcda3b3d5ce8b4f0848bfa87496c395 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLDelimiterRule.java @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser; + +import java.util.Locale; + +import org.eclipse.jface.text.rules.ICharacterScanner; +import org.eclipse.jface.text.rules.IRule; +import org.eclipse.jface.text.rules.IToken; +import org.eclipse.jface.text.rules.Token; + +/** + * + * Title: SQLDelimiterRule + * + * @since 3.0.0 + */ +public class SQLDelimiterRule implements IRule { + private IToken token = null; + private char[][] delimiters = null; + private char[][] origDelimiters = null; + private char[] buffer = null; + private char[] origBuffer = null; + + /** + * Instantiates a new SQL delimiter rule. + * + * @param delimiters the delimiters + * @param token the token + */ + public SQLDelimiterRule(String[] delimiters, IToken token) { + this.token = token; + this.origDelimiters = this.delimiters = new char[delimiters.length][]; + int index = 0; + int maxLength = 0; + for (String delim : delimiters) { + this.delimiters[index] = delim.toCharArray(); + for (int cnt = 0; cnt < this.delimiters[index].length; cnt++) { + this.delimiters[index][cnt] = Character.toUpperCase(this.delimiters[index][cnt]); + } + maxLength = Math.max(maxLength, this.delimiters[index].length); + index++; + } + this.origBuffer = this.buffer = new char[maxLength]; + } + + /** + * Gets the delimiters. + * + * @return the delimiters + */ + public char[][] getDelimiters() { + return delimiters.clone(); + } + + /** + * Evaluate. + * + * @param scanner the scanner + * @return the i token + */ + @Override + public IToken evaluate(ICharacterScanner scanner) { + for (int cnt = 0;; cnt++) { + int character = scanner.read(); + boolean matches = false; + if (character != ICharacterScanner.EOF) { + character = Character.toUpperCase(character); + for (int kIndex = 0; kIndex < delimiters.length; kIndex++) { + if (cnt < delimiters[kIndex].length && delimiters[kIndex][cnt] == character) { + buffer[cnt] = (char) character; + if (cnt == delimiters[kIndex].length - 1 && equalsBegin(delimiters[kIndex])) { + // Matched. Check next character + if (Character.isLetterOrDigit(character)) { + int cn = scanner.read(); + scanner.unread(); + if (Character.isLetterOrDigit(cn)) { + matches = false; + continue; + } + } + return token; + } + matches = true; + break; + } + } + } + if (!matches) { + for (int indx = 0; indx <= cnt; indx++) { + scanner.unread(); + } + return Token.UNDEFINED; + } + } + } + + private boolean equalsBegin(char[] delimiter) { + for (int index = 0; index < delimiter.length; index++) { + if (buffer[index] != delimiter[index]) { + return false; + } + } + return true; + } + + /** + * Checks if is empty. + * + * @param value the value + * @return true, if is empty + */ + public static boolean isEmpty(String value) { + return value == null || value.length() == 0; + } + + /** + * Change delimiter. + * + * @param newDelimiter the new delimiter + */ + public void changeDelimiter(String newDelimiter) { + if (isEmpty(newDelimiter)) { + this.delimiters = this.origDelimiters; + this.buffer = this.origBuffer; + } else { + for (char[] delim : delimiters) { + String delimStr = String.valueOf(delim); + if (newDelimiter.equals(delimStr)) { + return; + } + if (newDelimiter.endsWith(delimStr)) { + // New delimiter ends with old delimiter (as command + // terminator). Remove it. + newDelimiter = newDelimiter.substring(0, newDelimiter.length() - delimStr.length()).trim(); + } + } + this.delimiters = new char[1][]; + this.delimiters[0] = newDelimiter.toUpperCase(Locale.ENGLISH).toCharArray(); + this.buffer = new char[newDelimiter.length()]; + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLFoldingConstants.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLFoldingConstants.java new file mode 100644 index 0000000000000000000000000000000000000000..3b38fe5b3b4f1f418a03c75e82e46b4e145661e1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLFoldingConstants.java @@ -0,0 +1,378 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser; + +/** + * Title: SQLFoldingConstants + * + * @since 3.0.0 + */ +public interface SQLFoldingConstants { + + /** + * The sql view. + */ + String SQL_VIEW = "view"; + + /** + * The sql procedure. + */ + String SQL_PROCEDURE = "procedure"; + + /** + * The sql procedure. + */ + String SQL_PACKAGE = "package"; + + /** + * The package body. + */ + String SQL_PACKAGE_BODY = "body"; + + /** + * The sql function. + */ + String SQL_FUNCTION = "function"; + + /** + * The sql table. + */ + String SQL_TABLE = "table"; + + /** + * The sql trigger. + */ + String SQL_TRIGGER = "trigger"; + + /** + * The sql create. + */ + String SQL_CREATE = "create"; + + /** + * The sql alter. + */ + String SQL_ALTER = "alter"; + + /** + * The sql drop. + */ + String SQL_DROP = "drop"; + + /** + * The sql grant. + */ + String SQL_GRANT = "grant"; + + /** + * The sql revoke. + */ + String SQL_REVOKE = "revoke"; + + /** + * The sql delim name. + */ + String SQL_DELIM_NAME = "delim"; + + /** + * The sql keyword union. + */ + String SQL_KEYWORD_UNION = "union"; + + /** + * The sql keyword union. + */ + String SQL_KEYWORD_MINUS = "minus"; + + /** + * The sql keyword intersect. + */ + String SQL_KEYWORD_INTERSECT = "intersect"; + + /** + * The sql keyword except. + */ + String SQL_KEYWORD_EXCEPT = "except"; + + /** + * The sql keyword with. + */ + String SQL_KEYWORD_WITH = "with"; + + /** + * The sql keyword if. + */ + String SQL_KEYWORD_IF = "if"; + + /** + * The sql keyword else. + */ + String SQL_KEYWORD_ELSE = "else"; + + /** + * The sql keyword elsif. + */ + String SQL_KEYWORD_ELSIF = "elsif"; + + /** + * The sql keyword elseif. + */ + String SQL_KEYWORD_ELSEIF = "elseif"; + + /** + * The sql keyword loop. + */ + String SQL_KEYWORD_LOOP = "loop"; + + /** + * The sql keyword case. + */ + String SQL_KEYWORD_CASE = "case"; + + /** + * The sql keyword select. + */ + String SQL_KEYWORD_SELECT = "select"; + + /** + * The sql keyword insert. + */ + String SQL_KEYWORD_INSERT = "insert"; + + /** + * The sql keyword delete. + */ + String SQL_KEYWORD_DELETE = "delete"; + + /** + * The sql keyword update. + */ + String SQL_KEYWORD_UPDATE = "update"; + + /** + * The sql keyword truncate. + */ + String SQL_KEYWORD_TRUNCATE = "truncate"; + + /** + * The sql keyword language. + */ + String SQL_KEYWORD_LANGUAGE = "language"; + + /** + * The sql keywork values. + */ + String SQL_KEYWORK_VALUES = "values"; + + /** + * The sql keywork values upper. + */ + String SQL_KEYWORK_VALUES_UPPER = "VALUES"; + + /** + * The sql keywork declare. + */ + String SQL_KEYWORK_DECLARE = "declare"; + + /** + * The sql keywork begin. + */ + String SQL_KEYWORK_BEGIN = "begin"; + + /** + * The sql keywork end. + */ + String SQL_KEYWORK_END = "end"; + + /** + * The sql keywork as. + */ + String SQL_KEYWORK_AS = "as"; + + /** + * The sql keywork is. + */ + String SQL_KEYWORK_IS = "is"; + + /** + * The sql delim semicolon. + */ + String SQL_DELIM_SEMICOLON = ";"; + + /** + * The sql bracket start. + */ + String SQL_BRACKET_START = "("; + + /** + * The sql bracket end. + */ + String SQL_BRACKET_END = ")"; + + /** + * The sql double doller. + */ + String SQL_DOUBLE_DOLLER = "$$"; + + /** + * The sql token unknown. + */ + String SQL_TOKEN_UNKNOWN = "unknown"; + + /** + * The sql comment singleline. + */ + String SQL_COMMENT_SINGLELINE = "--"; + + /** + * The sql comment multiline start. + */ + String SQL_COMMENT_MULTILINE_START = "/*"; + + /** + * The sql comment multiline end. + */ + String SQL_COMMENT_MULTILINE_END = "*/"; + + /** + * The sql literal double quotes. + */ + String SQL_LITERAL_DOUBLE_QUOTES = "\""; + + /** + * The sql literal single quotes. + */ + String SQL_LITERAL_SINGLE_QUOTES = "'"; + + /** + * The sql delim fslash. + */ + String SQL_DELIM_FSLASH = "/"; + + /** + * The sql token dummy. + */ + String SQL_TOKEN_DUMMY = "dummy"; + + /** + * The sql literal double quotes char. + */ + char SQL_LITERAL_DOUBLE_QUOTES_CHAR = '"'; + + /** + * The sql literal single quotes char. + */ + char SQL_LITERAL_SINGLE_QUOTES_CHAR = '\''; + + /** + * The monoreconciler. + */ + String MONORECONCILER = "MonoReconciler"; + + /** + * The sqlreconcilingstrategy. + */ + String SQLRECONCILINGSTRATEGY = "SQLReconcilingStrategy"; + + /** + * The sql keyword from. + */ + String SQL_KEYWORD_FROM = "from"; + + /** + * The sql keyword where. + */ + String SQL_KEYWORD_WHERE = "where"; + + /** + * The sql keyword start. + */ + String SQL_KEYWORD_START = "start"; + + /** + * The sql keyword connect. + */ + String SQL_KEYWORD_CONNECT = "connect"; + + /** + * The sql keyword where. + */ + String SQL_KEYWORD_GROUP = "group"; + + /** + * The sql keyword where. + */ + String SQL_KEYWORD_ORDER = "order"; + + /** + * The sql keyword where. + */ + String SQL_KEYWORD_HAVING = "having"; + + /** + * The sql keyword where. + */ + String SQL_KEYWORD_LIMIT = "limit"; + + String SQL_KEYWORD_OFFSET = "offset"; + + String SQL_KEYWORD_FETCH = "fetch"; + + String SQL_KEYWORD_FOR = "for"; + + String SQL_KEYWORD_WHILE = "while"; + + String SQL_KEYWORD_CURSOR = "cursor"; + + String SQL_KEYWORD_WINDOW = "window"; + + String SQL_KEYWORD_RETURNS = "returns"; + + String SQL_KEYWORD_RETURN = "return"; + + /** + * The sql keyword where. + */ + String SQL_KEYWORD_WHEN = "when"; + + /** + * The sql keyword where. + */ + String SQL_KEYWORD_THEN = "then"; + + /** + * The sql keyword where. + */ + String SQL_KEYWORD_DEFAULT = "default"; + + String SQL_KEYWORD_VALUES = "values"; + + String SQL_KEYWORD_RETURNING = "returning"; + + String SQL_KEYWORD_USING = "using"; + + String SQL_KEYWORD_ONLY = "only"; + + String SQL_KEYWORD_SET = "set"; + + String SQL_KEYWORD_MERGE = "merge"; + + /** + * The sql keywork end. + */ + String SQL_KEYWORK_EXCEPTION = "exception"; + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLToken.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLToken.java new file mode 100644 index 0000000000000000000000000000000000000000..eab682158b13ee1ae517af6f96ee2429e638db3a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLToken.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser; + +import org.eclipse.jface.text.rules.Token; + +/** + * + * Title: SQLToken + * + * @since 3.0.0 + */ +public class SQLToken extends Token { + + private final int type; + + private boolean isNested = true; + + /** + * Instantiates a new SQL token. + * + * @param type the type + * @param data the data + */ + public SQLToken(int type, Object data) { + super(data); + this.type = type; + } + + /** + * Gets the type. + * + * @return the type + */ + public int getType() { + return type; + } + + /** + * Checks if is nested. + * + * @return true, if is nested + */ + public boolean isNested() { + return isNested; + } + + /** + * Sets the nested. + * + * @param isNested the new nested + */ + public void setNested(boolean isNested) { + this.isNested = isNested; + } + +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLTokenConstants.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLTokenConstants.java new file mode 100644 index 0000000000000000000000000000000000000000..3d933f06221f7c09a5e0a57fd7c26ffffd263512 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLTokenConstants.java @@ -0,0 +1,244 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser; + +/** + * + * Title: SQLFoldingConstants + * + * @since 3.0.0 + */ +public interface SQLTokenConstants { + + /** + * The t sql nonexist. + */ + int T_SQL_NONEXIST = -1; + + /** + * The t sql dummy. + */ + int T_SQL_DUMMY = -2; + + /** + * The t sql unknown. + */ + int T_SQL_UNKNOWN = 1000; + + /** + * The t sql block begin. + */ + int T_SQL_BLOCK_BEGIN = 1001; + + /** + * The t sql block end. + */ + int T_SQL_BLOCK_END = 1002; + + /** + * The t sql delimiter. + */ + int T_SQL_DELIMITER = 1007; + + /** + * The t sql dml select. + */ + int T_SQL_DML_SELECT = 1008; + + /** + * The t sql dml insert. + */ + int T_SQL_DML_INSERT = 1009; + + /** + * The t sql dml delete. + */ + int T_SQL_DML_DELETE = 1010; + + /** + * The t sql dml update. + */ + int T_SQL_DML_UPDATE = 1011; + + /** + * The t sql dml truncate. + */ + int T_SQL_DML_TRUNCATE = 1012; + + /** + * The t sql ddl create. + */ + int T_SQL_DDL_CREATE = 1013; + + /** + * The t sql ddl create func. + */ + int T_SQL_DDL_CREATE_FUNC = 1014; + + /** + * The t sql ddl create proc. + */ + int T_SQL_DDL_CREATE_PROC = 1015; + + /** + * The t sql ddl create table. + */ + int T_SQL_DDL_CREATE_TABLE = 1016; + + /** + * The t sql ddl control if. + */ + int T_SQL_DDL_CONTROL_IF = 1017; + + /** + * The t sql ddl control else. + */ + int T_SQL_DDL_CONTROL_ELSE = 1018; + + /** + * The t sql ddl control elsif. + */ + int T_SQL_DDL_CONTROL_ELSIF = 1019; + + /** + * The t sql bracket begin. + */ + int T_SQL_BRACKET_BEGIN = 1020; + + /** + * The t sql bracket end. + */ + int T_SQL_BRACKET_END = 1021; + + /** + * The t sql function end. + */ + int T_SQL_FUNCTION_END = 1022; + + /** + * The t sql dml insert values. + */ + int T_SQL_DML_INSERT_VALUES = 1023; + + /** + * The t sql dml with. + */ + int T_SQL_DML_WITH = 1024; + + /** + * The t sql block declare. + */ + int T_SQL_BLOCK_DECLARE = 1025; + + /** + * The t sql ddl alter. + */ + int T_SQL_DDL_ALTER = 1026; + + /** + * The t sql keywork view. + */ + int T_SQL_KEYWORK_VIEW = 1027; + + /** + * The t sql keywork language. + */ + int T_SQL_KEYWORK_LANGUAGE = 1028; + + /** + * The t sql keywork as. + */ + int T_SQL_KEYWORK_AS = 1029; + + /** + * The t sql keywork union. + */ + int T_SQL_KEYWORK_UNION = 1030; + + /** + * The t sql keywork intersect. + */ + int T_SQL_KEYWORK_INTERSECT = 1031; + + /** + * The t sql keywork except. + */ + int T_SQL_KEYWORK_EXCEPT = 1032; + + /** + * The t sql keywork case. + */ + int T_SQL_KEYWORK_CASE = 1033; + + /** + * The t sql loop. + */ + int T_SQL_LOOP = 1034; + + /** + * The t sql trigger. + */ + int T_SQL_TRIGGER = 1035; + + /** + * The t sql drop. + */ + int T_SQL_DROP = 1036; + + /** + * The t sql grant. + */ + int T_SQL_GRANT = 1037; + + /** + * The t sql revoke. + */ + int T_SQL_REVOKE = 1038; + + /** + * The t sql keywork is. + */ + int T_SQL_KEYWORK_IS = 1039; + + /** + * The t sql delimiter fslash. + */ + int T_SQL_DELIMITER_FSLASH = 1040; + + /** + * The t sql function end. + */ + int T_SQL_NUMBER = 1041; + + int T_SQL_KEYWORD_FOR = 1042; + + int T_SQL_KEYWORD_CURSOR = 1043; + + int T_SQL_MERGE = 1044; + + int T_SQL_WHEN = 1045; + + /** + * The t sql ddl create package. + */ + int T_SQL_DDL_CREATE_PACKAGE = 1046; + + /** + * The t sql ddl create package body. + */ + int T_SQL_DDL_CREATE_PACKAGE_BODY = 1047; + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLWordRule.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLWordRule.java new file mode 100644 index 0000000000000000000000000000000000000000..70b81bc061540476e09ee2b88282ec91f45b17a1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/SQLWordRule.java @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser; + +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +import org.eclipse.jface.text.rules.ICharacterScanner; +import org.eclipse.jface.text.rules.IRule; +import org.eclipse.jface.text.rules.IToken; +import org.eclipse.jface.text.rules.Token; + +/** + * + * Title: SQLWordRule + * + * @since 3.0.0 + */ +public class SQLWordRule implements IRule { + + private SQLDelimiterRule delimRule; + private IToken defaultToken; + private Map fWords = new HashMap<>(); + private StringBuilder fBuffer = new StringBuilder(); + private char[][] delimiters; + + /** + * Instantiates a new SQL word rule. + * + * @param delimRule the delim rule + * @param defaultToken the default token + */ + public SQLWordRule(SQLDelimiterRule delimRule, IToken defaultToken) { + this.delimRule = delimRule; + this.defaultToken = defaultToken; + } + + /** + * Checks for word. + * + * @param word the word + * @return true, if successful + */ + public boolean hasWord(String word) { + return fWords.containsKey(word.toLowerCase(Locale.ENGLISH)); + } + + /** + * Adds the word. + * + * @param word the word + * @param token the token + */ + public void addWord(String word, IToken token) { + fWords.put(word.toLowerCase(Locale.ENGLISH), token); + } + + /** + * Evaluate. + * + * @param scanner the scanner + * @return the i token + */ + @Override + public IToken evaluate(ICharacterScanner scanner) { + int chr = scanner.read(); + if (chr != ICharacterScanner.EOF && Character.isUnicodeIdentifierStart(chr)) { + fBuffer.setLength(0); + delimiters = delimRule.getDelimiters(); + do { + fBuffer.append((char) chr); + chr = scanner.read(); + } while (chr != ICharacterScanner.EOF && isWordPart((char) chr, scanner)); + scanner.unread(); + + String buffer = fBuffer.toString().toLowerCase(Locale.ENGLISH); + IToken token = fWords.get(buffer); + + if (token != null) { + return token; + } + + if (defaultToken.isUndefined()) { + unreadBuffer(scanner); + } + + return defaultToken; + } + + scanner.unread(); + return Token.UNDEFINED; + } + + private boolean isWordPart(char c, ICharacterScanner scanner) { + if (!Character.isUnicodeIdentifierPart(c) && c != '$') { + return false; + } + + if (null == delimiters) { + return false; + } + + // Check for delimiter + for (char[] wordDelimiter : delimiters) { + if (!Character.isLetter(c) && c == wordDelimiter[0]) { + if (wordDelimiter.length == 1) { + return false; + } + int charsRead = 0; + boolean matches = true; + for (int i = 1; i < wordDelimiter.length; i++) { + int c2 = scanner.read(); + charsRead++; + if (c2 == ICharacterScanner.EOF) { + break; + } + if (c2 != wordDelimiter[i]) { + matches = false; + break; + } + } + for (int i = 0; i < charsRead; i++) { + scanner.unread(); + } + if (matches) { + return false; + } + } + } + + return true; + } + + private void unreadBuffer(ICharacterScanner scanner) { + for (int i = fBuffer.length() - 1; i >= 0; i--) { + scanner.unread(); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/DMLParamScriptBlockInfo.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/DMLParamScriptBlockInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..3fa33e4075e3f21fa25caf20c3309c1d587b160a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/DMLParamScriptBlockInfo.java @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.bean; + +import java.util.Locale; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLDDLTypeEnum; +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.handlerif.RuleHandlerIf; + +/** + * Title: DMLParamScriptBlockInfo + * + * @since 3.0.0 + */ +public class DMLParamScriptBlockInfo extends ScriptBlockInfoImpl { + + private boolean plBodyStart = false; + + private boolean endStmtFound = false; + + private String startKeywork = null; + + private boolean langKeywordFound = false; + + private boolean langKeywordFoundBeforeStart = false; + + private SQLDDLTypeEnum ddlType = null; + + /** + * Instantiates a new DML param script block info. + * + * @param parent the parent + * @param token the token + * @param abstractRuleHandler the abstract rule handler + */ + public DMLParamScriptBlockInfo(ScriptBlockInfo parent, IToken token, RuleHandlerIf abstractRuleHandler) { + super(parent, token, abstractRuleHandler); + } + + /** + * Checks if is end stmt found. + * + * @return true, if is end stmt found + */ + public boolean isEndStmtFound() { + return endStmtFound; + } + + /** + * Sets the end stmt found. + * + * @param endStmtFound the new end stmt found + */ + public void setEndStmtFound(boolean endStmtFound) { + this.endStmtFound = endStmtFound; + } + + /** + * Gets the start keywork. + * + * @return the start keywork + */ + public String getStartKeywork() { + return startKeywork; + } + + /** + * Sets the start keywork. + * + * @param startKeywork the new start keywork + */ + public void setStartKeywork(String startKeywork) { + this.startKeywork = startKeywork; + } + + /** + * Checks if is lang keyword found. + * + * @return true, if is lang keyword found + */ + public boolean isLangKeywordFound() { + return langKeywordFound; + } + + /** + * Sets the lang keyword found. + * + * @param langKeywordFound the new lang keyword found + */ + public void setLangKeywordFound(boolean langKeywordFound) { + this.langKeywordFound = langKeywordFound; + } + + /** + * Checks if is lang keyword found before start. + * + * @return true, if is lang keyword found before start + */ + public boolean isLangKeywordFoundBeforeStart() { + return langKeywordFoundBeforeStart; + } + + /** + * Sets the lang keyword found before start. + * + * @param langKeywordFoundBeforeStart the new lang keyword found before + * start + */ + public void setLangKeywordFoundBeforeStart(boolean langKeywordFoundBeforeStart) { + this.langKeywordFoundBeforeStart = langKeywordFoundBeforeStart; + } + + /** + * Checks if is pl body start. + * + * @return true, if is pl body start + */ + public boolean isPlBodyStart() { + return plBodyStart; + } + + /** + * Sets the pl body start. + * + * @param plBodyStart the new pl body start + */ + public void setPlBodyStart(boolean plBodyStart) { + this.plBodyStart = plBodyStart; + } + + /** + * Gets the ddl type. + * + * @return the ddl type + */ + public SQLDDLTypeEnum getDdlType() { + return ddlType; + } + + /** + * Sets the ddl type. + * + * @param ddlType the new ddl type + */ + public void setDdlType(SQLDDLTypeEnum ddlType) { + this.ddlType = ddlType; + } + + /** + * Sets the DDL type. + * + * @param latestkeyword the new DDL type + */ + public void setDDLType(String latestkeyword) { + switch (latestkeyword.toLowerCase(Locale.ENGLISH)) { + case SQLFoldingConstants.SQL_PROCEDURE: { + setDdlType(SQLDDLTypeEnum.PROCEDURE); + break; + } + case SQLFoldingConstants.SQL_FUNCTION: { + setDdlType(SQLDDLTypeEnum.FUNCTION); + break; + } + case SQLFoldingConstants.SQL_TABLE: { + setDdlType(SQLDDLTypeEnum.TABLE); + break; + } + case SQLFoldingConstants.SQL_VIEW: { + setDdlType(SQLDDLTypeEnum.VIEW); + break; + } + case SQLFoldingConstants.SQL_TRIGGER: { + setDdlType(SQLDDLTypeEnum.TRIGGER); + break; + } + case SQLFoldingConstants.SQL_PACKAGE: { + setDdlType(SQLDDLTypeEnum.PACKAGE); + break; + } + default: + } + } + + /** + * Sets the DDL type. + * + * @param latestkeyword the new DDL type + */ + public void setDDLType(int tokenType) { + if (SQLTokenConstants.T_SQL_DDL_CREATE_PROC == tokenType) { + setDdlType(SQLDDLTypeEnum.PROCEDURE); + } else if (SQLTokenConstants.T_SQL_DDL_CREATE_FUNC == tokenType) { + setDdlType(SQLDDLTypeEnum.FUNCTION); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/SQLBracketParamData.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/SQLBracketParamData.java new file mode 100644 index 0000000000000000000000000000000000000000..ef30de648942f6e00cdcec2d0ca1868ac50e66be --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/SQLBracketParamData.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.bean; + +/** + * + * Title: SQLBracketParamData + * + * @since 3.0.0 + */ +public class SQLBracketParamData { + + /** + * The start end token counter. + */ + int startEndTokenCounter = 0; + + /** + * Gets the start end token counter. + * + * @return the start end token counter + */ + public int getStartEndTokenCounter() { + return startEndTokenCounter; + } + + /** + * Incr start end token counter. + */ + public void incrStartEndTokenCounter() { + this.startEndTokenCounter++; + } + + /** + * Decr start end token counter. + */ + public void decrStartEndTokenCounter() { + this.startEndTokenCounter--; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/ScriptBlockInfoImpl.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/ScriptBlockInfoImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..8de7c187a22553cb613e39b527da8b4a5a3116e3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/ScriptBlockInfoImpl.java @@ -0,0 +1,555 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.bean; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.handlerif.RuleHandlerIf; + +/** + * Title: ScriptBlockInfo + * + * @since 3.0.0 + */ +public class ScriptBlockInfoImpl implements ScriptBlockInfo { + + private ScriptBlockInfo parent; + + private int tokenType = SQLTokenConstants.T_SQL_UNKNOWN; + + private int startOffSet; + + private int lenght; + + private boolean isNested = true; + + private boolean invokeParent = false; + + private int lastNonBlankTokenOffSet; + + private int lastNonBlankTokenlenght; + + private int lastKnownTokenOffSet; + + private int lastKnownTokenlenght; + + private int preNewlineTokenOffSet; + + private int preNewlineTokenlenght; + + private int lastAnyTokenOffSet; + + private int lastAnyTokenlenght; + + private String lastNonBlankToken; + + private String currentKnownToken; + + private List lastKnownTokenList = new ArrayList(); + + private RuleHandlerIf abstractRuleHandler = null; + + private SQLBracketParamData bracketParamData = null; + + private SQLBracketParamData caseParamData = null; + + private int allowDMLWithoutBracket = 0; + + private int nextOptTokenToEnd = SQLTokenConstants.T_SQL_UNKNOWN; + + private int nextMiddleOptTokenToEnd = SQLTokenConstants.T_SQL_UNKNOWN; + + private int recentNewLineCount = 0; + + private List tokenDataList = new ArrayList<>(); + + /** + * Instantiates a new script block info impl. + * + * @param parent the parent + * @param token the token + * @param abstractRuleHandler the abstract rule handler + */ + public ScriptBlockInfoImpl(ScriptBlockInfo parent, IToken token, RuleHandlerIf abstractRuleHandler) { + this.parent = parent; + if (token instanceof SQLToken) { + this.tokenType = ((SQLToken) token).getType(); + } + this.abstractRuleHandler = abstractRuleHandler; + } + + public ScriptBlockInfoImpl() { + } + + /** + * Gets the start off set for block. + * + * @return the start off set for block + */ + public int getStartOffSetForBlock() { + return startOffSet; + } + + /** + * Sets the start off set for block. + * + * @param startOffSet the new start off set for block + */ + public void setStartOffSetForBlock(int startOffSet) { + this.startOffSet = startOffSet; + } + + /** + * Gets the lenght. + * + * @return the lenght + */ + public int getLenght() { + return lenght; + } + + /** + * Gets the token type. + * + * @return the token type + */ + public int getTokenType() { + return tokenType; + } + + /** + * Sets the token type. + * + * @param scriptType the new token type + */ + public void setTokenType(int scriptType) { + this.tokenType = scriptType; + } + + /** + * Sets the lenght. + * + * @param lenght the new lenght + */ + public void setLenght(int lenght) { + this.lenght = lenght; + } + + /** + * Gets the abstract rule handler. + * + * @return the abstract rule handler + */ + public RuleHandlerIf getAbstractRuleHandler() { + return abstractRuleHandler; + } + + /** + * Sets the abstract rule handler. + * + * @param abstractRuleHandler the new abstract rule handler + */ + public void setAbstractRuleHandler(RuleHandlerIf abstractRuleHandler) { + this.abstractRuleHandler = abstractRuleHandler; + } + + /** + * Gets the parent. + * + * @return the parent + */ + public ScriptBlockInfo getParent() { + return parent; + } + + /** + * Checks if is nested. + * + * @return true, if is nested + */ + public boolean isNested() { + return isNested; + } + + /** + * Sets the nested. + * + * @param isNested the new nested + */ + public void setNested(boolean isNested) { + this.isNested = isNested; + } + + /** + * Gets the last token off set. + * + * @return the last token off set + */ + public int getLastTokenOffSet() { + return lastNonBlankTokenOffSet; + } + + /** + * Sets the last token off set. + * + * @param lastTokenOffSet the new last token off set + */ + public void setLastTokenOffSet(int lastTokenOffSet) { + this.lastNonBlankTokenOffSet = lastTokenOffSet; + } + + /** + * Gets the last tokenlenght. + * + * @return the last tokenlenght + */ + public int getLastTokenlenght() { + return lastNonBlankTokenlenght; + } + + /** + * Sets the last tokenlenght. + * + * @param lastTokenlenght the new last tokenlenght + */ + public void setLastTokenlenght(int lastTokenlenght) { + this.lastNonBlankTokenlenght = lastTokenlenght; + } + + /** + * Gets the last token. + * + * @return the last token + */ + public String getLastToken() { + return lastNonBlankToken; + } + + /** + * Sets the last token. + * + * @param lastToken the new last token + */ + public void setLastToken(String lastToken) { + this.lastNonBlankToken = lastToken; + } + + /** + * Addlast known token. + * + * @param token the token + */ + public void addlastKnownToken(String token) { + lastKnownTokenList.add(token); + } + + /** + * Gets the last known token list. + * + * @return the last known token list + */ + public List getLastKnownTokenList() { + return lastKnownTokenList; + } + + /** + * Gets the last known token. + * + * @return the last known token + */ + public String getLastKnownToken() { + + if (lastKnownTokenList.size() > 0) { + return lastKnownTokenList.get(lastKnownTokenList.size() - 1); + } + + return null; + + } + + /** + * Gets the current known token. + * + * @return the current known token + */ + public String getCurrentKnownToken() { + return currentKnownToken; + } + + /** + * Sets the current known token. + * + * @param currentKnownToken the new current known token + */ + public void setCurrentKnownToken(String currentKnownToken) { + this.currentKnownToken = currentKnownToken; + } + + /** + * Gets the bracket param data. + * + * @return the bracket param data + */ + public SQLBracketParamData getBracketParamData() { + return bracketParamData; + } + + /** + * Sets the bracket param data. + * + * @param bracketParamData the new bracket param data + */ + public void setBracketParamData(SQLBracketParamData bracketParamData) { + this.bracketParamData = bracketParamData; + } + + /** + * Gets the allow DML without bracket. + * + * @return the allow DML without bracket + */ + public int getAllowDMLWithoutBracket() { + return allowDMLWithoutBracket; + } + + /** + * Incr allow DML without bracket. + */ + public void incrAllowDMLWithoutBracket() { + this.allowDMLWithoutBracket++; + } + + /** + * Checks if is invoke parent. + * + * @return true, if is invoke parent + */ + public boolean isInvokeParent() { + return invokeParent; + } + + /** + * Sets the invoke parent. + * + * @param invokeParent the new invoke parent + */ + public void setInvokeParent(boolean invokeParent) { + this.invokeParent = invokeParent; + } + + /** + * Gets the last known token off set. + * + * @return the last known token off set + */ + public int getLastKnownTokenOffSet() { + return lastKnownTokenOffSet; + } + + /** + * Sets the last known token off set. + * + * @param lastKnownTokenOffSet the new last known token off set + */ + public void setLastKnownTokenOffSet(int lastKnownTokenOffSet) { + this.lastKnownTokenOffSet = lastKnownTokenOffSet; + } + + /** + * Gets the last known tokenlenght. + * + * @return the last known tokenlenght + */ + public int getLastKnownTokenlenght() { + return lastKnownTokenlenght; + } + + /** + * Sets the last known tokenlenght. + * + * @param lastKnownTokenlenght the new last known tokenlenght + */ + public void setLastKnownTokenlenght(int lastKnownTokenlenght) { + this.lastKnownTokenlenght = lastKnownTokenlenght; + } + + /** + * Gets the case param data. + * + * @return the case param data + */ + public SQLBracketParamData getCaseParamData() { + return caseParamData; + } + + /** + * Sets the case param data. + * + * @param caseParamData the new case param data + */ + public void setCaseParamData(SQLBracketParamData caseParamData) { + this.caseParamData = caseParamData; + } + + /** + * Gets the next opt token to end. + * + * @return the next opt token to end + */ + public int getNextOptTokenToEnd() { + return nextOptTokenToEnd; + } + + /** + * Sets the next opt token to end. + * + * @param nextOptTokenToEnd the new next opt token to end + */ + public void setNextOptTokenToEnd(int nextOptTokenToEnd) { + this.nextOptTokenToEnd = nextOptTokenToEnd; + } + + /** + * Gets the recent new line count. + * + * @return the recent new line count + */ + public int getRecentNewLineCount() { + return recentNewLineCount; + } + + /** + * Reset recent new line count. + */ + public void resetRecentNewLineCount() { + this.recentNewLineCount = 0; + } + + /** + * Incr recent new line count. + */ + public void incrRecentNewLineCount() { + this.recentNewLineCount++; + } + + /** + * Gets the pre newline token off set. + * + * @return the pre newline token off set + */ + public int getPreNewlineTokenOffSet() { + return preNewlineTokenOffSet; + } + + /** + * Sets the pre newline token off set. + * + * @param preNewlineTokenOffSet the new pre newline token off set + */ + public void setPreNewlineTokenOffSet(int preNewlineTokenOffSet) { + this.preNewlineTokenOffSet = preNewlineTokenOffSet; + } + + /** + * Gets the pre newline tokenlenght. + * + * @return the pre newline tokenlenght + */ + public int getPreNewlineTokenlenght() { + return preNewlineTokenlenght; + } + + /** + * Sets the pre newline tokenlenght. + * + * @param preNewlineTokenlenght the new pre newline tokenlenght + */ + public void setPreNewlineTokenlenght(int preNewlineTokenlenght) { + this.preNewlineTokenlenght = preNewlineTokenlenght; + } + + /** + * Gets the any token off set. + * + * @return the any token off set + */ + public int getAnyTokenOffSet() { + return lastAnyTokenOffSet; + } + + /** + * Sets the any token off set. + * + * @param anyTokenOffSet the new any token off set + */ + public void setAnyTokenOffSet(int anyTokenOffSet) { + this.lastAnyTokenOffSet = anyTokenOffSet; + } + + /** + * Gets the any tokenlenght. + * + * @return the any tokenlenght + */ + public int getAnyTokenlenght() { + return lastAnyTokenlenght; + } + + /** + * Sets the any tokenlenght. + * + * @param anyTokenlenght the new any tokenlenght + */ + public void setAnyTokenlenght(int anyTokenlenght) { + this.lastAnyTokenlenght = anyTokenlenght; + } + + /** + * Gets the next middle opt token to end. + * + * @return the next middle opt token to end + */ + public int getNextMiddleOptTokenToEnd() { + return nextMiddleOptTokenToEnd; + } + + /** + * Sets the next middle opt token to end. + * + * @param nextMiddleOptTokenToEnd the new next middle opt token to end + */ + public void setNextMiddleOptTokenToEnd(int nextMiddleOptTokenToEnd) { + this.nextMiddleOptTokenToEnd = nextMiddleOptTokenToEnd; + } + + @Override + public List getAllTokenList() { + return tokenDataList; + } + + @Override + public void addSQLTokenData(ISQLTokenData token) { + tokenDataList.add(token); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/SelectSqlParamScriptBlockInfo.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/SelectSqlParamScriptBlockInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..c526be8540766c31ab14b1754ae380adecc4bd71 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/SelectSqlParamScriptBlockInfo.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.bean; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.handlerif.RuleHandlerIf; + +/** + * + * Title: SelectSqlParamScriptBlockInfo + * + * @since 3.0.0 + */ +public class SelectSqlParamScriptBlockInfo extends ScriptBlockInfoImpl { + + /** + * Instantiates a new select sql param script block info. + * + * @param parent the parent + * @param token the token + * @param abstractRuleHandler the abstract rule handler + */ + public SelectSqlParamScriptBlockInfo(ScriptBlockInfo parent, SQLToken token, RuleHandlerIf abstractRuleHandler) { + super(parent, token, abstractRuleHandler); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/pos/RuleBean.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/pos/RuleBean.java new file mode 100644 index 0000000000000000000000000000000000000000..9c6e9e0345c65eee59328811f4ff2fe4febfe8f0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/pos/RuleBean.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.bean.pos; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; + +/** + * Title: RuleBean + * + * @since 3.0.0 + */ +public class RuleBean { + + private ScriptBlockInfo scriptBlockInfo = null; + + private ScriptBlockInfo previousScriptBlock = null; + + private boolean continueLoop = false; + + /** + * Gets the script block info. + * + * @return the script block info + */ + public ScriptBlockInfo getScriptBlockInfo() { + return scriptBlockInfo; + } + + /** + * Sets the script block info. + * + * @param scriptBlockInfo the new script block info + */ + public void setScriptBlockInfo(ScriptBlockInfo scriptBlockInfo) { + this.scriptBlockInfo = scriptBlockInfo; + } + + /** + * Checks if is continue loop. + * + * @return true, if is continue loop + */ + public boolean isContinueLoop() { + return continueLoop; + } + + /** + * Sets the continue loop. + * + * @param continueLoop the new continue loop + */ + public void setContinueLoop(boolean continueLoop) { + this.continueLoop = continueLoop; + } + + /** + * return the previous script block + * + * @return return the previous script block + */ + public ScriptBlockInfo getPreviousScriptBlock() { + return previousScriptBlock; + } + + public void setPreviousScriptBlock(ScriptBlockInfo previousScriptBlock) { + this.previousScriptBlock = previousScriptBlock; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/pos/SQLQueryPosition.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/pos/SQLQueryPosition.java new file mode 100644 index 0000000000000000000000000000000000000000..e83434fe17faf83da6cb43ef40b6eb3a0c2ce047 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/pos/SQLQueryPosition.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.bean.pos; + +/** + * + * Title: SQLQueryPosition + * + * @since 3.0.0 + */ +public class SQLQueryPosition implements SQLScriptElement { + + private int offset; + private int length; + + /** + * Instantiates a new SQL query position. + * + * @param lOffSet the l off set + * @param llength the llength + */ + public SQLQueryPosition(int lOffSet, int llength) { + this.offset = lOffSet; + this.length = llength; + + } + + /** + * Gets the original text. + * + * @return the original text + */ + @Override + public String getOriginalText() { + return null; + } + + /** + * Gets the text. + * + * @return the text + */ + @Override + public String getText() { + return null; + } + + /** + * Gets the offset. + * + * @return the offset + */ + @Override + public int getOffset() { + + return offset; + } + + /** + * Gets the length. + * + * @return the length + */ + @Override + public int getLength() { + return length; + } + + /** + * Gets the data. + * + * @return the data + */ + @Override + public Object getData() { + return null; + } + + /** + * Sets the data. + * + * @param data the new data + */ + @Override + public void setData(Object data) { + + } + + /** + * Reset. + */ + @Override + public void reset() { + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/pos/SQLScriptElement.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/pos/SQLScriptElement.java new file mode 100644 index 0000000000000000000000000000000000000000..7b494f06dd82c3590120df2c415cce9a7bd62db8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/pos/SQLScriptElement.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.bean.pos; + +/** + * + * Title: SQLScriptElement + * + * @since 3.0.0 + */ +public interface SQLScriptElement { + + /** + * Gets the original text. + * + * @return the original text + */ + String getOriginalText(); + + /** + * Gets the text. + * + * @return the text + */ + String getText(); + + /** + * Gets the offset. + * + * @return the offset + */ + int getOffset(); + + /** + * Gets the length. + * + * @return the length + */ + int getLength(); + + /** + * Gets the data. + * + * @return the data + */ + Object getData(); + + /** + * Sets the data. + * + * @param data the new data + */ + void setData(Object data); + + /** + * Reset. + */ + void reset(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/pos/SQLScriptPosition.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/pos/SQLScriptPosition.java new file mode 100644 index 0000000000000000000000000000000000000000..dabaf6cd412a71635b7c2f3d8efa5ca39ead1c68 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/pos/SQLScriptPosition.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.bean.pos; + +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.source.projection.ProjectionAnnotation; + +/** + * + * Title: SQLScriptPosition + * + * @since 3.0.0 + */ +public class SQLScriptPosition extends Position implements Comparable { + + private final ProjectionAnnotation foldingAnnotation; + private final boolean isMultiline; + + /** + * Instantiates a new SQL script position. + * + * @param offset the offset + * @param length the length + * @param isMultiline the is multiline + * @param foldingAnnotation the folding annotation + */ + public SQLScriptPosition(int offset, int length, boolean isMultiline, ProjectionAnnotation foldingAnnotation) { + super(offset, length); + this.foldingAnnotation = foldingAnnotation; + this.isMultiline = isMultiline; + } + + /** + * Gets the folding annotation. + * + * @return the folding annotation + */ + public ProjectionAnnotation getFoldingAnnotation() { + return foldingAnnotation; + } + + /** + * Checks if is multiline. + * + * @return true, if is multiline + */ + public boolean isMultiline() { + return isMultiline; + } + + /** + * Compare to. + * + * @param scriptPosition the o + * @return the int + */ + @Override + public int compareTo(SQLScriptPosition scriptPosition) { + return offset - scriptPosition.offset; + } + + /** + * Hash code. + * + * @return the int + */ + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Equals. + * + * @param obj the obj + * @return true, if successful + */ + @Override + public boolean equals(Object obj) { + + return super.equals(obj); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/scriptif/ScriptBlockInfo.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/scriptif/ScriptBlockInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..deeb4a755470deed8b823ddc0c4e7633a555dbcd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/scriptif/ScriptBlockInfo.java @@ -0,0 +1,381 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif; + +import java.util.List; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.SQLBracketParamData; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.handlerif.RuleHandlerIf; + +/** + * Title: ScriptBlockInfo + * + * @since 3.0.0 + */ +public interface ScriptBlockInfo { + + /** + * Gets the start off set for block. + * + * @return the start off set for block + */ + int getStartOffSetForBlock(); + + /** + * Sets the start off set for block. + * + * @param startOffSet the new start off set for block + */ + void setStartOffSetForBlock(int startOffSet); + + /** + * Gets the lenght. + * + * @return the lenght + */ + int getLenght(); + + /** + * Gets the token type. + * + * @return the token type + */ + int getTokenType(); + + /** + * Sets the token type. + * + * @param scriptType the new token type + */ + void setTokenType(int scriptType); + + /** + * Sets the lenght. + * + * @param lenght the new lenght + */ + void setLenght(int lenght); + + /** + * Gets the abstract rule handler. + * + * @return the abstract rule handler + */ + RuleHandlerIf getAbstractRuleHandler(); + + /** + * Sets the abstract rule handler. + * + * @param abstractRuleHandler the new abstract rule handler + */ + void setAbstractRuleHandler(RuleHandlerIf abstractRuleHandler); + + /** + * Gets the parent. + * + * @return the parent + */ + ScriptBlockInfo getParent(); + + /** + * Checks if is nested. + * + * @return true, if is nested + */ + boolean isNested(); + + /** + * Sets the nested. + * + * @param isNested the new nested + */ + void setNested(boolean isNested); + + /** + * Gets the last token off set. + * + * @return the last token off set + */ + int getLastTokenOffSet(); + + /** + * Sets the last token off set. + * + * @param lastTokenOffSet the new last token off set + */ + void setLastTokenOffSet(int lastTokenOffSet); + + /** + * Gets the last tokenlenght. + * + * @return the last tokenlenght + */ + int getLastTokenlenght(); + + /** + * Sets the last tokenlenght. + * + * @param lastTokenlenght the new last tokenlenght + */ + void setLastTokenlenght(int lastTokenlenght); + + /** + * Gets the last token. + * + * @return the last token + */ + String getLastToken(); + + /** + * Sets the last token. + * + * @param lastToken the new last token + */ + void setLastToken(String lastToken); + + /** + * Addlast known token. + * + * @param token the token + */ + void addlastKnownToken(String token); + + /** + * Gets the last known token list. + * + * @return the last known token list + */ + List getLastKnownTokenList(); + + /** + * Adds the SQL token data. + * + * @param token the token + */ + void addSQLTokenData(ISQLTokenData token); + + /** + * Gets the all token list. + * + * @return the all token list + */ + List getAllTokenList(); + + /** + * Gets the last known token. + * + * @return the last known token + */ + String getLastKnownToken(); + + /** + * Gets the current known token. + * + * @return the current known token + */ + String getCurrentKnownToken(); + + /** + * Sets the current known token. + * + * @param currentKnownToken the new current known token + */ + void setCurrentKnownToken(String currentKnownToken); + + /** + * Gets the bracket param data. + * + * @return the bracket param data + */ + SQLBracketParamData getBracketParamData(); + + /** + * Sets the bracket param data. + * + * @param bracketParamData the new bracket param data + */ + void setBracketParamData(SQLBracketParamData bracketParamData); + + /** + * Gets the allow DML without bracket. + * + * @return the allow DML without bracket + */ + int getAllowDMLWithoutBracket(); + + /** + * Incr allow DML without bracket. + */ + void incrAllowDMLWithoutBracket(); + + /** + * Checks if is invoke parent. + * + * @return true, if is invoke parent + */ + boolean isInvokeParent(); + + /** + * Sets the invoke parent. + * + * @param invokeParent the new invoke parent + */ + void setInvokeParent(boolean invokeParent); + + /** + * Gets the last known token off set. + * + * @return the last known token off set + */ + int getLastKnownTokenOffSet(); + + /** + * Sets the last known token off set. + * + * @param lastKnownTokenOffSet the new last known token off set + */ + void setLastKnownTokenOffSet(int lastKnownTokenOffSet); + + /** + * Gets the last known tokenlenght. + * + * @return the last known tokenlenght + */ + int getLastKnownTokenlenght(); + + /** + * Sets the last known tokenlenght. + * + * @param lastKnownTokenlenght the new last known tokenlenght + */ + void setLastKnownTokenlenght(int lastKnownTokenlenght); + + /** + * Gets the case param data. + * + * @return the case param data + */ + SQLBracketParamData getCaseParamData(); + + /** + * Sets the case param data. + * + * @param caseParamData the new case param data + */ + void setCaseParamData(SQLBracketParamData caseParamData); + + /** + * Gets the next opt token to end. + * + * @return the next opt token to end + */ + int getNextOptTokenToEnd(); + + /** + * Sets the next opt token to end. + * + * @param nextOptTokenToEnd the new next opt token to end + */ + void setNextOptTokenToEnd(int nextOptTokenToEnd); + + /** + * Gets the recent new line count. + * + * @return the recent new line count + */ + int getRecentNewLineCount(); + + /** + * Reset recent new line count. + */ + void resetRecentNewLineCount(); + + /** + * Incr recent new line count. + */ + void incrRecentNewLineCount(); + + /** + * Gets the pre newline token off set. + * + * @return the pre newline token off set + */ + int getPreNewlineTokenOffSet(); + + /** + * Sets the pre newline token off set. + * + * @param preNewlineTokenOffSet the new pre newline token off set + */ + void setPreNewlineTokenOffSet(int preNewlineTokenOffSet); + + /** + * Gets the pre newline tokenlenght. + * + * @return the pre newline tokenlenght + */ + int getPreNewlineTokenlenght(); + + /** + * Sets the pre newline tokenlenght. + * + * @param preNewlineTokenlenght the new pre newline tokenlenght + */ + void setPreNewlineTokenlenght(int preNewlineTokenlenght); + + /** + * Gets the any token off set. + * + * @return the any token off set + */ + int getAnyTokenOffSet(); + + /** + * Sets the any token off set. + * + * @param anyTokenOffSet the new any token off set + */ + void setAnyTokenOffSet(int anyTokenOffSet); + + /** + * Gets the any tokenlenght. + * + * @return the any tokenlenght + */ + int getAnyTokenlenght(); + + /** + * Sets the any tokenlenght. + * + * @param anyTokenlenght the new any tokenlenght + */ + void setAnyTokenlenght(int anyTokenlenght); + + /** + * Gets the next middle opt token to end. + * + * @return the next middle opt token to end + */ + int getNextMiddleOptTokenToEnd(); + + /** + * Sets the next middle opt token to end. + * + * @param nextMiddleOptTokenToEnd the new next middle opt token to end + */ + void setNextMiddleOptTokenToEnd(int nextMiddleOptTokenToEnd); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/tokendata/ISQLTokenData.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/tokendata/ISQLTokenData.java new file mode 100644 index 0000000000000000000000000000000000000000..4d438ccbb428d308fdb63a29f279b64c61de0208 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/tokendata/ISQLTokenData.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.stmtbeanif.StatementBeanIf; + +/** + * Title: ISQLTokenData + * + * @since 3.0.0 + */ +public interface ISQLTokenData extends StatementBeanIf { + /** + * Gets the token. + * + * @return the token + */ + IToken getToken(); + + /** + * Sets the token. + * + * @param token the new token + */ + void setToken(IToken token); + + /** + * Gets the token offset. + * + * @return the token offset + */ + int getTokenOffset(); + + /** + * Sets the token offset. + * + * @param tokenOffset the new token offset + */ + void setTokenOffset(int tokenOffset); + + /** + * Gets the token length. + * + * @return the token length + */ + int getTokenLength(); + + /** + * Sets the token length. + * + * @param tokenLength the new token length + */ + void setTokenLength(int tokenLength); + + /** + * Gets the token str. + * + * @return the token str + */ + String getTokenStr(); + + /** + * Sets the token str. + * + * @param tokenStr the new token str + */ + void setTokenStr(String tokenStr); + + /** + * Gets the sub token bean. + * + * @return the sub token bean + */ + SQLStmtTokenListBean getSubTokenBean(); + + /** + * Sets the sub token bean. + * + * @param subTokenBean the new sub token bean + */ + void setSubTokenBean(SQLStmtTokenListBean subTokenBean); + +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/tokendata/SQLStmtTokenListBean.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/tokendata/SQLStmtTokenListBean.java new file mode 100644 index 0000000000000000000000000000000000000000..f75287fa847b9e446409257f1a875494babcf9ab --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/tokendata/SQLStmtTokenListBean.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata; + +import java.util.List; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLDDLTypeEnum; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; + +/** + * Title: SQLStmtTokenListBean + * + * @since 3.0.0 + */ +public class SQLStmtTokenListBean { + + private List sqlTokenData = null; + + private int statementType = SQLTokenConstants.T_SQL_UNKNOWN; + + private SQLDDLTypeEnum ddlType = SQLDDLTypeEnum.UNKNOWN; + + /** + * Gets the sql token data. + * + * @return the sql token data + */ + public List getSqlTokenData() { + return sqlTokenData; + } + + /** + * Sets the sql token data. + * + * @param sqlTokenData the new sql token data + */ + public void setSqlTokenData(List sqlTokenData) { + this.sqlTokenData = sqlTokenData; + } + + /** + * Gets the statement type. + * + * @return the statement type + */ + public int getStatementType() { + return statementType; + } + + /** + * Sets the statement type. + * + * @param statementType the new statement type + */ + public void setStatementType(int statementType) { + this.statementType = statementType; + } + + /** + * Gets the ddl type. + * + * @return the ddl type + */ + public SQLDDLTypeEnum getDdlType() { + return ddlType; + } + + /** + * Sets the ddl type. + * + * @param ddlType the new ddl type + */ + public void setDdlType(SQLDDLTypeEnum ddlType) { + this.ddlType = ddlType; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/tokendata/SQLStmtTokenManager.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/tokendata/SQLStmtTokenManager.java new file mode 100644 index 0000000000000000000000000000000000000000..403d314307f91eef248405650fa3b811b9563926 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/tokendata/SQLStmtTokenManager.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata; + +import java.util.LinkedList; +import java.util.List; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.DMLParamScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; + +/** + * + * Title: class + * + * Description: The Class SQLStmtTokenManager. + * + * @since 3.0.0 + */ +public class SQLStmtTokenManager { + + private List sqlTokenStmtList = new LinkedList(); + + /** + * Gets the sql token stmt list. + * + * @return the sql token stmt list + */ + public List getSqlTokenStmtList() { + return sqlTokenStmtList; + } + + /** + * Sets the sql token stmt list. + * + * @param sqlTokenStmtList the new sql token stmt list + */ + public void setSqlTokenStmtList(List sqlTokenStmtList) { + this.sqlTokenStmtList = sqlTokenStmtList; + } + + /** + * Adds the SQL stmt token list bean. + * + * @param sqlStmtTokenListBean the sql stmt token list bean + */ + public void addSQLStmtTokenListBean(SQLStmtTokenListBean sqlStmtTokenListBean) { + this.sqlTokenStmtList.add(sqlStmtTokenListBean); + } + + /** + * Adds the SQL stmt token list bean. + * + * @param scriptBlock the script block + */ + public void addSQLStmtTokenListBean(ScriptBlockInfo scriptBlock) { + + List allTokenList = scriptBlock.getAllTokenList(); + if (!allTokenList.isEmpty()) { + SQLStmtTokenListBean lSQLStmtTokenListBean = new SQLStmtTokenListBean(); + lSQLStmtTokenListBean.setSqlTokenData(allTokenList); + lSQLStmtTokenListBean.setStatementType(scriptBlock.getTokenType()); + if (scriptBlock instanceof DMLParamScriptBlockInfo) { + lSQLStmtTokenListBean.setDdlType(((DMLParamScriptBlockInfo) scriptBlock).getDdlType()); + } + + sqlTokenStmtList.add(lSQLStmtTokenListBean); + } + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/tokendata/SQLTokenData.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/tokendata/SQLTokenData.java new file mode 100644 index 0000000000000000000000000000000000000000..a318ac26ba5bb7daaa7dd9a5a7f9a5b67f9b5932 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/tokendata/SQLTokenData.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata; + +import org.eclipse.jface.text.rules.IToken; + +/** + * Title: SQLTokenData + * + * @since 3.0.0 + */ +public class SQLTokenData implements ISQLTokenData { + private IToken token = null; + + private int tokenOffset = 0; + + private int tokenLength = 0; + + private String tokenStr = null; + + private SQLStmtTokenListBean subTokenBean = null; + + /** + * Gets the token. + * + * @return the token + */ + @Override + public IToken getToken() { + return token; + } + + /** + * Sets the token. + * + * @param token the new token + */ + @Override + public void setToken(IToken token) { + this.token = token; + } + + /** + * Gets the token offset. + * + * @return the token offset + */ + @Override + public int getTokenOffset() { + return tokenOffset; + } + + /** + * Sets the token offset. + * + * @param tokenOffset the new token offset + */ + @Override + public void setTokenOffset(int tokenOffset) { + this.tokenOffset = tokenOffset; + } + + /** + * Gets the token length. + * + * @return the token length + */ + @Override + public int getTokenLength() { + return tokenLength; + } + + /** + * Sets the token length. + * + * @param tokenLength the new token length + */ + @Override + public void setTokenLength(int tokenLength) { + this.tokenLength = tokenLength; + } + + @Override + public String getTokenStr() { + return tokenStr; + } + + @Override + public void setTokenStr(String tokenStr) { + this.tokenStr = tokenStr; + } + + @Override + public SQLStmtTokenListBean getSubTokenBean() { + return subTokenBean; + } + + @Override + public void setSubTokenBean(SQLStmtTokenListBean subTokenBean) { + this.subTokenBean = subTokenBean; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/tokendata/SQLTokenFactory.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/tokendata/SQLTokenFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..ae2c4728de90767e775e5a9372b7404c33bc980d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/bean/tokendata/SQLTokenFactory.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata; + +/** + * Title: SQLTokenFactory + * + * @since 3.0.0 + */ +public abstract class SQLTokenFactory { + /** + * factory method to return the token data + * + * @return the sql token data + */ + public static ISQLTokenData getTokenData() { + return new SQLTokenData(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/FastStringBuffer.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/FastStringBuffer.java new file mode 100644 index 0000000000000000000000000000000000000000..3fda847a66ad06f69fa4c213749c28fe8c35ac1f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/FastStringBuffer.java @@ -0,0 +1,880 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.comm; + +import java.nio.charset.Charset; +import java.util.Iterator; + +/** + * + * Title: FastStringBuffer + * + * @since 3.0.0 + */ +public final class FastStringBuffer { + /** + * Holds the actual chars + */ + private char[] value; + + /** + * Count for which chars are actually used + */ + private int count; + + /** + * Initializes with a default initial size (128 chars). + */ + public FastStringBuffer() { + this(128); + } + + /** + * An initial size can be specified (if available and given for no + * allocations it can be more efficient). + * + * @param initialSize the initial size + */ + public FastStringBuffer(int initialSize) { + this.value = new char[initialSize]; + this.count = 0; + } + + /** + * Instantiates a new fast string buffer. + * + * @param internalBuffer the internal buffer + */ + public FastStringBuffer(char[] internalBuffer) { + this.value = internalBuffer; + this.count = internalBuffer.length; + } + + /** + * initializes from a string and the additional size for the buffer. + * + * @param bufferString string with the initial contents + * @param additionalSize the additional size for the buffer + */ + public FastStringBuffer(String bufferString, int additionalSize) { + this.count = bufferString.length(); + if (additionalSize < 0) { + additionalSize = 0; + } + value = new char[this.count + additionalSize]; + bufferString.getChars(0, this.count, value, 0); + } + + /** + * Appends a string to the buffer. Passing a null string will throw an + * exception. + * + * @param string the string + * @return the fast string buffer + */ + public FastStringBuffer append(String string) { + return appendObject(string); + } + + /** + * Appends a string to the buffer. The buffer must have enough pre-allocated + * space for it to succeed. + * + * Passing a null string will throw an exception. Not having a pre-allocated + * internal array big enough will throw an exception. + * + * @param string the string + * @return the fast string buffer + */ + public FastStringBuffer appendNoResize(String string) { + int strLen = string.length(); + string.getChars(0, strLen, value, this.count); + this.count = count + strLen; + return this; + } + + /** + * Appends an int to the buffer. + * + * @param n the n + * @return the fast string buffer + */ + public FastStringBuffer append(int n) { + String string = String.valueOf(n); + return appendObject(string); + } + + /** + * Appends a char to the buffer. + * + * @param n the n + * @return the fast string buffer + */ + public FastStringBuffer append(char chr) { + if (count + 1 > value.length) { + int minimumCapacity = count + 1; + int newCapacity = (value.length + 1) * 2; + if (minimumCapacity > newCapacity) { + newCapacity = minimumCapacity; + } + char[] newValue = new char[newCapacity]; + System.arraycopy(value, 0, newValue, 0, count); + value = newValue; + } + value[count] = chr; + count++; + return this; + } + + /** + * Appends a char to the buffer. Use when the size allocated is usually + * already ok (will only resize on exception instead of doing a size check + * all the time). + * + * @param n the n + */ + public void appendResizeOnExc(char chr) { + try { + value[count] = chr; + } catch (Exception e) { + int minimumCapacity = count + 1; + int newCapacity = (value.length + 1) * 2; + if (minimumCapacity > newCapacity) { + newCapacity = minimumCapacity; + } + char[] newValue = new char[newCapacity]; + System.arraycopy(value, 0, newValue, 0, count); + value = newValue; + value[count] = chr; + } + count++; + } + + /** + * Appends a long to the buffer. + * + * @param n the n + * @return the fast string buffer + */ + public FastStringBuffer append(long n) { + String string = String.valueOf(n); + return appendObject(string); + } + + /** + * Appends a boolean to the buffer. + * + * @param booleanValue the b + * @return the fast string buffer + */ + public FastStringBuffer append(boolean booleanValue) { + String string = String.valueOf(booleanValue); + return appendObject(string); + } + + private FastStringBuffer appendObject(String objStrVal) { + int strLen = objStrVal.length(); + int newCount = count + strLen; + + if (newCount > this.value.length) { + int newCapacity = (value.length + 1) * 2; + if (newCount > newCapacity) { + newCapacity = newCount; + } + char[] newValue = new char[newCapacity]; + System.arraycopy(value, 0, newValue, 0, count); + value = newValue; + } + objStrVal.getChars(0, strLen, value, this.count); + this.count = newCount; + return this; + } + + /** + * Appends a double to the buffer. + * + * @param doubleValue the b + * @return the fast string buffer + */ + public FastStringBuffer append(double doubleValue) { + String string = String.valueOf(doubleValue); + return appendObject(string); + } + + /** + * Appends an array of chars to the buffer. + * + * @param chars the chars + * @return the fast string buffer + */ + public FastStringBuffer append(char[] chars) { + int newCount = count + chars.length; + if (newCount > value.length) { + int newCapacity = (value.length + 1) * 2; + if (newCount > newCapacity) { + newCapacity = newCount; + } + char[] newValue = new char[newCapacity]; + System.arraycopy(value, 0, newValue, 0, count); + value = newValue; + } + System.arraycopy(chars, 0, value, count, chars.length); + count = newCount; + return this; + } + + /** + * Appends another buffer to this buffer. + * + * @param other the other + * @return the fast string buffer + */ + public FastStringBuffer append(FastStringBuffer other) { + int len = other.count; + int newCount = count + len; + if (newCount > value.length) { + int newCapacity = (value.length + 1) * 2; + if (newCount > newCapacity) { + newCapacity = newCount; + } + char[] newValue = new char[newCapacity]; + System.arraycopy(value, 0, newValue, 0, count); + value = newValue; + } + System.arraycopy(other.value, 0, value, count, len); + count = newCount; + return this; + } + + /** + * Appends an array of chars to this buffer, starting at the offset passed + * with the length determined. + * + * @param chars the chars + * @param offset the offset + * @param len the len + * @return the fast string buffer + */ + public FastStringBuffer append(char[] chars, int offset, int len) { + int newCount = count + len; + if (newCount > value.length) { + int newCapacity = (value.length + 1) * 2; + if (newCount > newCapacity) { + newCapacity = newCount; + } + char[] newValue = new char[newCapacity]; + System.arraycopy(value, 0, newValue, 0, count); + value = newValue; + } + System.arraycopy(chars, offset, value, count, len); + count = newCount; + return this; + } + + /** + * Reverses the contents on this buffer. + * + * @return the fast string buffer + */ + public FastStringBuffer reverse() { + final int limit = count / 2; + for (int i = 0; i < limit; ++i) { + char chr = value[i]; + value[i] = value[count - i - 1]; + value[count - i - 1] = chr; + } + return this; + } + + /** + * Clears this buffer. + * + * @return the fast string buffer + */ + public FastStringBuffer clear() { + this.count = 0; + return this; + } + + /** + * Length. + * + * @return the length of this buffer + */ + public int length() { + return this.count; + } + + /** + * Checks if is empty. + * + * @return true, if is empty + */ + public boolean isEmpty() { + return this.count == 0; + } + + /** + * To string. + * + * @return a new string with the contents of this buffer. + */ + @Override + public String toString() { + return new String(value, 0, count); + } + + /** + * To char array. + * + * @return a new char array with the contents of this buffer. + */ + public char[] toCharArray() { + char[] chr = new char[count]; + System.arraycopy(value, 0, chr, 0, count); + return chr; + } + + /** + * Erases the last char in this buffer. + */ + public void deleteLast() { + if (this.count > 0) { + this.count--; + } + } + + /** + * Delete last chars. + * + * @param charsToDelete the chars to delete + */ + public void deleteLastChars(int charsToDelete) { + this.count -= charsToDelete; + if (this.count < 0) { + this.count = 0; + } + } + + /** + * Char at. + * + * @param i the i + * @return the char given at a specific position of the buffer (no bounds + * check) + */ + public char charAt(int i) { + return this.value[i]; + } + + /** + * Inserts a string at a given position in the buffer. + * + * @param offset the offset + * @param str the str + * @return the fast string buffer + */ + public FastStringBuffer insert(int offset, String str) { + int length = str.length(); + int newCountLength = count + length; + if (newCountLength > value.length) { + int newCapacity = (value.length + 1) * 2; + if (newCountLength > newCapacity) { + newCapacity = newCountLength; + } + char[] newValue = new char[newCapacity]; + System.arraycopy(value, 0, newValue, 0, count); + value = newValue; + } + System.arraycopy(value, offset, value, offset + length, count - offset); + str.getChars(0, length, value, offset); + count = newCountLength; + return this; + } + + /** + * Inserts a string at a given position in the buffer. + * + * @param offset the offset + * @param str the str + * @return the fast string buffer + */ + public FastStringBuffer insert(int offset, FastStringBuffer str) { + int len = str.length(); + int newCount = count + len; + if (newCount > value.length) { + int newCapacity = (value.length + 1) * 2; + if (newCount > newCapacity) { + newCapacity = newCount; + } + char[] newValue = new char[newCapacity]; + System.arraycopy(value, 0, newValue, 0, count); + value = newValue; + } + System.arraycopy(value, offset, value, offset + len, count - offset); + System.arraycopy(str.value, 0, value, offset, str.count); + count = newCount; + return this; + } + + /** + * Inserts a char at a given position in the buffer. + * + * @param offset the offset + * @param c the c + * @return the fast string buffer + */ + public FastStringBuffer insert(int offset, char chr) { + int newCount = count + 1; + if (newCount > value.length) { + int newCapacity = (value.length + 1) * 2; + if (newCount > newCapacity) { + newCapacity = newCount; + } + char[] newValue = new char[newCapacity]; + System.arraycopy(value, 0, newValue, 0, count); + value = newValue; + } + System.arraycopy(value, offset, value, offset + 1, count - offset); + value[offset] = chr; + count = newCount; + return this; + } + + /** + * Appends object.toString(). If null, "null" is appended. + * + * @param object the object + * @return the fast string buffer + */ + public FastStringBuffer appendObject(Object object) { + String string = object != null ? object.toString() : "null"; + return appendObject(string); + } + + /** + * Sets the new size of this buffer (warning: use with care: no validation + * is done of the len passed). + * + * @param newLen the new count + */ + public void setCount(int newLen) { + this.count = newLen; + } + + /** + * Delete. + * + * @param start the start + * @param end the end + * @return the fast string buffer + */ + public FastStringBuffer delete(int start, int end) { + if (start < 0) { + throw new StringIndexOutOfBoundsException(start); + } + if (end > count) { + end = count; + } + if (start > end) { + throw new StringIndexOutOfBoundsException(); + } + int len = end - start; + if (len > 0) { + System.arraycopy(value, start + len, value, start, count - end); + count -= len; + } + return this; + } + + /** + * Replace. + * + * @param start the start + * @param end the end + * @param str the str + * @return the fast string buffer + */ + public FastStringBuffer replace(int start, int end, String str) { + if (start < 0) { + throw new StringIndexOutOfBoundsException(start); + } + if (start > count) { + throw new StringIndexOutOfBoundsException("start > length()"); + } + if (start > end) { + throw new StringIndexOutOfBoundsException("start > end"); + } + if (end > count) { + end = count; + } + + int len = str.length(); + int newCount = count + len - (end - start); + if (newCount > value.length) { + int newCapacity = (value.length + 1) * 2; + if (newCount > newCapacity) { + newCapacity = newCount; + } + char[] newValue = new char[newCapacity]; + System.arraycopy(value, 0, newValue, 0, count); + value = newValue; + } + + System.arraycopy(value, end, value, start + len, count - end); + str.getChars(0, len, value, start); + count = newCount; + return this; + } + + /** + * Delete char at. + * + * @param index the index + * @return the fast string buffer + */ + public FastStringBuffer deleteCharAt(int index) { + if ((index < 0) || (index >= count)) { + throw new StringIndexOutOfBoundsException(index); + } + System.arraycopy(value, index + 1, value, index, count - index - 1); + count--; + return this; + } + + /** + * Index of. + * + * @param c the c + * @return the int + */ + public int indexOf(char c) { + for (int i = 0; i < this.count; i++) { + if (c == this.value[i]) { + return i; + } + } + return -1; + } + + /** + * Index of. + * + * @param c the c + * @param fromOffset the from offset + * @return the int + */ + public int indexOf(char c, int fromOffset) { + for (int i = fromOffset; i < this.count; i++) { + if (c == this.value[i]) { + return i; + } + } + return -1; + } + + /** + * First char. + * + * @return the char + */ + public char firstChar() { + return this.value[0]; + } + + /** + * Last char. + * + * @return the char + */ + public char lastChar() { + return this.value[this.count - 1]; + } + + /** + * Right trim. + */ + public void rightTrim() { + char chr; + while (this.count > 0 && ((chr = this.value[this.count - 1]) == ' ' || chr == '\t')) { + this.count--; + } + } + + /** + * Delete first. + * + * @return the char + */ + public char deleteFirst() { + char ret = this.value[0]; + this.deleteCharAt(0); + return ret; + } + + /** + * Append N. + * + * @param val the val + * @param n the n + * @return the fast string buffer + */ + public FastStringBuffer appendN(final String val, int n) { + final int strLen = val.length(); + int min = count + (n * strLen); + if (min > value.length) { + int newCapacity = (value.length + 1) * 2; + if (min > newCapacity) { + newCapacity = min; + } + char[] newValue = new char[newCapacity]; + System.arraycopy(value, 0, newValue, 0, count); + value = newValue; + } + + while (n-- > 0) { + val.getChars(0, strLen, value, this.count); + this.count += strLen; + } + return this; + } + + /** + * Append N. + * + * @param val the val + * @param n the n + * @return the fast string buffer + */ + public FastStringBuffer appendN(char val, int n) { + if (count + n > value.length) { + int minimumCapacity = count + n; + int newCapacity = (value.length + 1) * 2; + if (minimumCapacity > newCapacity) { + newCapacity = minimumCapacity; + } + char[] newValue = new char[newCapacity]; + System.arraycopy(value, 0, newValue, 0, count); + value = newValue; + } + + while (n-- > 0) { + value[count] = val; + count++; + } + return this; + } + + /** + * Ends with. + * + * @param string the string + * @return true, if successful + */ + public boolean endsWith(String string) { + return startsWith(string, count - string.length()); + } + + /** + * Starts with. + * + * @param prefix the prefix + * @return true, if successful + */ + public boolean startsWith(String prefix) { + return startsWith(prefix, 0); + } + + /** + * Starts with. + * + * @param c the c + * @return true, if successful + */ + public boolean startsWith(char c) { + if (this.count < 1) { + return false; + } + return this.value[0] == c; + } + + /** + * Ends with. + * + * @param c the c + * @return true, if successful + */ + public boolean endsWith(char c) { + if (this.count < 1) { + return false; + } + return this.value[this.count - 1] == c; + } + + /** + * Starts with. + * + * @param prefix the prefix + * @param offset the offset + * @return true, if successful + */ + public boolean startsWith(String prefix, int offset) { + char[] ta = value; + int to = offset; + char[] pa = prefix.toCharArray(); + int po = 0; + int pc = pa.length; + // Note: toffset might be near -1>>>1. + if ((offset < 0) || (offset > count - pc)) { + return false; + } + while (--pc >= 0) { + if (ta[to++] != pa[po++]) { + return false; + } + } + return true; + } + + /** + * Sets the char at. + * + * @param pos the pos + * @param chr the chr + */ + public void setCharAt(int pos, char chr) { + this.value[pos] = chr; + } + + /** + * Careful: it doesn't check anything. Just sets the internal length. + * + * @param i the new length + */ + public void setLength(int len) { + this.count = len; + } + + /** + * Gets the bytes. + * + * @return the bytes + */ + public byte[] getBytes() { + return this.toString().getBytes(Charset.forName("UTF-8")); + } + + /** + * Count new lines. + * + * @return the int + */ + public int countNewLines() { + int lines = 0; + + for (int i = 0; i < count; i++) { + char chr = value[i]; + switch (chr) { + case '\n': { + lines += 1; + break; + } + + case '\r': { + lines += 1; + if (i < count - 1) { + if (value[i + 1] == '\n') { + i++; // skip the \n after the \r + } + } + break; + } + default: { + break; + } + } + } + return lines; + } + + /** + * Insert N. + * + * @param pos the pos + * @param charValue the c + * @param repetitions the repetitions + * @return the fast string buffer + */ + public FastStringBuffer insertN(int pos, char charValue, int repetitions) { + FastStringBuffer other = new FastStringBuffer(repetitions); + other.appendN(charValue, repetitions); + insert(pos, other); + return this; + } + + /** + * Gets the last word. + * + * @return the last word + */ + public String getLastWord() { + FastStringBuffer lastWordBuf = new FastStringBuffer(this.count); + int index; + // skip whitespaces in the end + for (index = this.count - 1; index >= 0; index--) { + if (!Character.isWhitespace(this.value[index])) { + break; + } + } + // actual word + for (; index >= 0; index--) { + if (Character.isWhitespace(this.value[index])) { + break; + } + lastWordBuf.append(this.value[index]); + } + lastWordBuf.reverse(); + return lastWordBuf.toString(); + } + + /** + * Removes the whitespaces. + */ + public void removeWhitespaces() { + int length = this.count; + char[] newVal = new char[length]; + + int index = 0; + for (int i = 0; i < length; i++) { + char ch = this.value[i]; + if (!Character.isWhitespace(ch)) { + newVal[index] = ch; + index++; + } + } + this.count = index; + this.value = newVal; + } + + /** + * Gets the internal chars array. + * + * @return the internal chars array + */ + public char[] getInternalCharsArray() { + return this.value; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/ISQLSyntax.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/ISQLSyntax.java new file mode 100644 index 0000000000000000000000000000000000000000..64f6d0148e6f37879ad822a09246774fa1cedd05 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/ISQLSyntax.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.comm; + +/** + * + * Title: interface + * + * Description: The Interface ISQLSyntax. + * + * @since 3.0.0 + */ +public interface ISQLSyntax { + + /** + * The sql comment. + */ + String SQL_COMMENT = "sql_comment"; + + /** + * The sql multiline comment. + */ + String SQL_MULTILINE_COMMENT = "sql_multiline_comment"; + + /** + * The sql code. + */ + String SQL_CODE = "sql_code"; + + /** + * The single line comment. + */ + String SINGLE_LINE_COMMENT = "sql_singleline_comment"; + + /** + * The sql partitioning. + */ + String SQL_PARTITIONING = "___sql_partitioning"; + + /** + * The sql double quotes identifier. + */ + String SQL_DOUBLE_QUOTES_IDENTIFIER = "sql_double_quotes_identifier"; + + /** + * The sql string. + */ + String SQL_STRING = "sql_character"; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/NestedMultipleLineRule.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/NestedMultipleLineRule.java new file mode 100644 index 0000000000000000000000000000000000000000..e2faf14959c26a6caddc6fe467dd5c470947cce0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/NestedMultipleLineRule.java @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.comm; + +import org.eclipse.jface.text.rules.ICharacterScanner; +import org.eclipse.jface.text.rules.IToken; +import org.eclipse.jface.text.rules.MultiLineRule; +import org.eclipse.jface.text.rules.Token; + +/** + * + * Title: class + * + * Description: The Class NestedMultipleLineRule. + * + * @since 3.0.0 + */ +public class NestedMultipleLineRule extends MultiLineRule { + + /** + * The comment nesting depth. + */ + protected int commentNestingDepth = 0; + + /** + * Instantiates a new nested multiple line rule. + * + * @param startSequence the start sequence + * @param endSequence the end sequence + * @param token the token + * @param escapeCharacter the escape character + * @param isBreaksOnEOF the is breaks on EOF + */ + public NestedMultipleLineRule(String startSequence, String endSequence, IToken token, char escapeCharacter, + boolean isBreaksOnEOF) { + super(startSequence, endSequence, token, escapeCharacter, isBreaksOnEOF); + } + + /** + * End sequence detected. + * + * @param characterScanner the character scanner + * @return true, if successful + */ + @Override + protected boolean endSequenceDetected(ICharacterScanner characterScanner) { + int character = characterScanner.read(); + while (character != ICharacterScanner.EOF) { + if (character == fEscapeCharacter) { + // Skip escaped character. + characterScanner.read(); + } else if (verifyStartSequence(character)) { + // Check if nested start sequence has been found. + if (sequenceDetected(characterScanner, fStartSequence, false)) { + commentNestingDepth++; + } + } else if (verifyEndSequence(character)) { + // Check if specified end sequence has been found. + if (sequenceDetected(characterScanner, fEndSequence, true)) { + commentNestingDepth--; + if (commentNestingDepth <= 0) { + return true; + } + } + } + character = characterScanner.read(); + } + if (fBreaksOnEOF) { + return true; + } + characterScanner.unread(); + return false; + } + + /** + * Verify start sequence. + * + * @param chr the c + * @return true, if successful + */ + private boolean verifyStartSequence(int chr) { + return fStartSequence.length > 0 && chr == fStartSequence[0]; + } + + /** + * Verify end sequence. + * + * @param chr the c + * @return true, if successful + */ + private boolean verifyEndSequence(int chr) { + return fEndSequence.length > 0 && chr == fEndSequence[0]; + } + + /** + * Do evaluate. + * + * @param charScanner the char scanner + * @param isResume the is resume + * @return the i token + */ + @Override + protected IToken doEvaluate(ICharacterScanner charScanner, boolean isResume) { + if (isResume) { + commentNestingDepth = 0; + + if (endSequenceDetected(charScanner)) { + return fToken; + } + } else { + int chr = charScanner.read(); + if (chr == fStartSequence[0]) { + if (sequenceDetected(charScanner, fStartSequence, false)) { + commentNestingDepth = 1; + if (endSequenceDetected(charScanner)) { + return fToken; + } + } + } + } + + charScanner.unread(); + return Token.UNDEFINED; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/NestedQuotesRule.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/NestedQuotesRule.java new file mode 100644 index 0000000000000000000000000000000000000000..80bec9fac57e737811200518f78ee82a06cc10cf --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/NestedQuotesRule.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.comm; + +import org.eclipse.jface.text.rules.ICharacterScanner; +import org.eclipse.jface.text.rules.IToken; +import org.eclipse.jface.text.rules.MultiLineRule; +import org.eclipse.jface.text.rules.Token; + +/** + * + * Title: class + * + * Description: The Class NestedQuotesRule. + * + * @since 3.0.0 + */ +public class NestedQuotesRule extends MultiLineRule { + + /** + * The quote nesting depth. + */ + protected int quoteNestingDepth = 0; + + /** + * Instantiates a new nested quotes rule. + * + * @param startSequence the start sequence + * @param endSequence the end sequence + * @param token the token + * @param escapeCharacter the escape character + * @param isBreaksOnEOF the is breaks on EOF + */ + public NestedQuotesRule(String startSequence, String endSequence, IToken token, char escapeCharacter, + boolean isBreaksOnEOF) { + super(startSequence, endSequence, token, escapeCharacter, isBreaksOnEOF); + } + + /** + * End sequence detected. + * + * @param characterScanner the character scanner + * @return true, if successful + */ + @Override + protected boolean endSequenceDetected(ICharacterScanner characterScanner) { + int currChar = characterScanner.read(); + int nextChar = -1; + int nestedDepth = 0; + while (currChar != ICharacterScanner.EOF) { + + if (currChar == fEndSequence[0]) { + nestedDepth++; + nextChar = characterScanner.read(); + if (nextChar == fEndSequence[0]) { + nestedDepth--; + } else if (nestedDepth == 1 && currChar == fEndSequence[0] && nextChar != fEndSequence[0]) { + characterScanner.unread(); + return true; + } + } + currChar = characterScanner.read(); + } + if (fBreaksOnEOF) { + return true; + } + characterScanner.unread(); + return false; + } + + /** + * Do evaluate. + * + * @param charScanner the char scanner + * @param isResume the is resume + * @return the i token + */ + @Override + protected IToken doEvaluate(ICharacterScanner charScanner, boolean isResume) { + if (isResume) { + quoteNestingDepth = 0; + + if (endSequenceDetected(charScanner)) { + return fToken; + } + } else { + int character = charScanner.read(); + if (character == fStartSequence[0]) { + if (sequenceDetected(charScanner, fStartSequence, false)) { + if (endSequenceDetected(charScanner)) { + return fToken; + } + } + } + } + + charScanner.unread(); + return Token.UNDEFINED; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/NumberDetector.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/NumberDetector.java new file mode 100644 index 0000000000000000000000000000000000000000..8d8959e39831f5ef5fe5c8bb1621565538d4c4b1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/NumberDetector.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.comm; + +import org.eclipse.jface.text.rules.IWordDetector; + +/** + * + * Title: NumberDetector + * + * @since 3.0.0 + */ +public class NumberDetector implements IWordDetector { + + /** + * Used to keep the state of the token + */ + private FastStringBuffer buffer = new FastStringBuffer(); + + /** + * Defines if we are at an hexa number + */ + private boolean isInHexa; + + /** + * @see org.eclipse.jface.text.rules.IWordDetector#isWordStart(char) + */ + public boolean isWordStart(char wordStart) { + isInHexa = false; + buffer.clear(); + buffer.append(wordStart); + return Character.isDigit(wordStart); + } + + /** + * Check if we are still in the number + */ + public boolean isWordPart(char wordPart) { + // ok, we have to test for scientific notation e.g.: 10.9e10 + + if ((wordPart == 'x' || wordPart == 'X') && buffer.length() == 1 && buffer.charAt(0) == '0') { + // it is an hexadecimal + buffer.append(wordPart); + isInHexa = true; + return true; + } else { + buffer.append(wordPart); + } + + if (isInHexa) { + return Character.isDigit(wordPart) || wordPart == 'a' || wordPart == 'A' || wordPart == 'b' + || wordPart == 'B' || wordPart == 'c' || wordPart == 'C' || wordPart == 'd' || wordPart == 'D' + || wordPart == 'e' || wordPart == 'E' || wordPart == 'f' || wordPart == 'F'; + + } else { + return Character.isDigit(wordPart) || wordPart == 'e' || wordPart == '.'; + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/SQLEditorParserBase.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/SQLEditorParserBase.java new file mode 100644 index 0000000000000000000000000000000000000000..7171a5970cfad4fd31644a755d7706d145205df6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/SQLEditorParserBase.java @@ -0,0 +1,303 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.comm; + +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.rules.IToken; +import org.eclipse.jface.text.source.projection.ProjectionAnnotationModel; +import org.eclipse.jface.text.source.projection.ProjectionViewer; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.RuleBean; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.SQLScriptElement; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.SQLTokenFactory; +import org.opengauss.mppdbide.gauss.sqlparser.handler.AbstractRuleHandler; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: SQLEditorParserBase + * + * @since 3.0.0 + */ +public class SQLEditorParserBase { + + /** + * The source viewer. + */ + protected ProjectionViewer sourceViewer = null; + + /** + * The rule manager. + */ + protected SQLFoldingRuleManager ruleManager = null; + + /** + * Instantiates a new SQL editor parser. + */ + public SQLEditorParserBase() { + + } + + /** + * Gets the document. + * + * @return the document + */ + public IDocument getDocument() { + return sourceViewer.getDocument(); + } + + /** + * Gets the EOF ret val. + * + * @param curBlock the cur block + * @param lretList the lret list + * @return the EOF ret val + */ + protected List getEOFRetVal(ScriptBlockInfo curBlock, List lretList) { + if (null == curBlock) { + return lretList; + } + + int lastTokenOffSet = curBlock.getLastTokenOffSet(); + int lastTokenLength = curBlock.getLastTokenlenght(); + + while (null != curBlock) { + curBlock.getAbstractRuleHandler().endScriptBlock(curBlock, lretList, lastTokenOffSet, lastTokenLength); + curBlock = curBlock.getParent(); + } + + return lretList; + } + + /** + * Gets the current block handle. + * + * @param lretList the lret list + * @param curBlock the cur block + * @param token the token + * @param ruleHandlarByToken the rule handlar by token + * @param sqlTokenData the sql token data + * @return the current block handle + */ + public ScriptBlockInfo getCurrentBlockHandle(List lretList, ScriptBlockInfo curBlock, + IToken token, AbstractRuleHandler ruleHandlarByToken, ISQLTokenData sqlTokenData) { + RuleBean ruleBean = curBlock.getAbstractRuleHandler().handle(curBlock, lretList, getSQLToken(token), + sqlTokenData, ruleHandlarByToken); + + // is parent propagation is required + + curBlock = ruleBean.getScriptBlockInfo(); + + return curBlock; + } + + /** + * Gets the SQL token. + * + * @param token the token + * @return the SQL token + */ + protected SQLToken getSQLToken(IToken token) { + if (token instanceof SQLToken) { + return (SQLToken) token; + } + return null; + } + + /** + * Gets the current token. + * + * @param tokenOffset the token offset + * @param tokenLength the token length + * @return the current token + */ + public String getCurrentToken(int tokenOffset, int tokenLength) { + String currentToken = null; + try { + currentToken = getDocument().get(tokenOffset, tokenLength); + } catch (BadLocationException e) { + MPPDBIDELoggerUtility.error( + "Exception while Document replace while getting documnet text within specified range, tokenoffset " + + tokenOffset + "token length" + tokenLength); + } + return currentToken; + } + + /** + * Adds the last known token details. + * + * @param curBlock the cur block + * @param tokenOffset the token offset + * @param tokenLength the token length + * @param currentToken the current token + */ + public void addLastKnownTokenDetails(ScriptBlockInfo curBlock, int tokenOffset, int tokenLength, + String currentToken) { + curBlock.setLastKnownTokenlenght(tokenLength); + curBlock.setLastKnownTokenOffSet(tokenOffset); + + curBlock.addlastKnownToken(currentToken); + } + + /** + * Handle last token data. + * + * @param curBlock the cur block + * @param token the token + * @param tokenOffset the token offset + * @param tokenLength the token length + * @param currentToken the current token + */ + public void handleLastTokenData(ScriptBlockInfo curBlock, IToken token, int tokenOffset, int tokenLength, + String currentToken) { + + if (null == currentToken) { + return; + } + + if (null != curBlock) { + if (System.lineSeparator().equalsIgnoreCase(currentToken)) { + curBlock.incrRecentNewLineCount(); + } else if (StringUtils.isNotEmpty(currentToken.trim())) { + curBlock.resetRecentNewLineCount(); + } + } + + if (null != curBlock) { + if (!token.isWhitespace() && !token.isEOF() && !System.lineSeparator().equalsIgnoreCase(currentToken) + && StringUtils.isNotEmpty(currentToken.trim())) { + curBlock.setLastToken(currentToken); + curBlock.setLastTokenlenght(tokenLength); + curBlock.setLastTokenOffSet(tokenOffset); + } + if (System.lineSeparator().equalsIgnoreCase(currentToken)) { + curBlock.setPreNewlineTokenlenght(curBlock.getAnyTokenlenght()); + curBlock.setPreNewlineTokenOffSet(curBlock.getAnyTokenOffSet()); + } + + curBlock.setAnyTokenlenght(tokenLength); + curBlock.setAnyTokenOffSet(tokenOffset); + + if (ISQLSyntax.SQL_COMMENT.equals(token.getData())) { + curBlock.setPreNewlineTokenlenght(curBlock.getAnyTokenlenght() - System.lineSeparator().length()); + curBlock.setPreNewlineTokenOffSet(curBlock.getAnyTokenOffSet()); + } + + } + + } + + /** + * Contains ignore case. + * + * @param array the array + * @param value the value + * @return true, if successful + */ + public boolean containsIgnoreCase(String[] array, String value) { + if (isEmpty(array) || value == null) { + return false; + } + for (int i = 0; i < array.length; i++) { + if (value.equalsIgnoreCase(array[i])) { + return true; + } + } + return false; + } + + /** + * Checks if is empty. + * + * @param arr the arr + * @return true, if is empty + */ + public boolean isEmpty(Object[] arr) { + return arr == null || arr.length == 0; + } + + /** + * Gets the source viewer. + * + * @return the source viewer + */ + public ProjectionViewer getSourceViewer() { + return sourceViewer; + } + + /** + * Sets the source viewer. + * + * @param lSourceViewer the new source viewer + */ + public void setSourceViewer(ProjectionViewer lSourceViewer) { + this.sourceViewer = lSourceViewer; + } + + /** + * Gets the rule manager. + * + * @return the rule manager + */ + public SQLFoldingRuleManager getRuleManager() { + return ruleManager; + } + + /** + * Sets the rule manager. + * + * @param ruleManager the new rule manager + */ + public void setRuleManager(SQLFoldingRuleManager ruleManager) { + this.ruleManager = ruleManager; + } + + /** + * Gets the projection annotation model. + * + * @return the projection annotation model + */ + public ProjectionAnnotationModel getProjectionAnnotationModel() { + return sourceViewer.getProjectionAnnotationModel(); + } + + /** + * + * creates a new SQLToken data and return the same. + * + * @param ruleManager current RuleManager + * @param token current IToken + * @param currentToken current token data + * @return the sql token data + */ + protected ISQLTokenData getSQLTokenData(SQLFoldingRuleManager ruleManager, IToken token, String currentToken) { + ISQLTokenData sqlTokenData = SQLTokenFactory.getTokenData(); + sqlTokenData.setToken(token); + sqlTokenData.setTokenOffset(ruleManager.getTokenOffset()); + sqlTokenData.setTokenLength(ruleManager.getTokenLength()); + sqlTokenData.setTokenStr(currentToken); + return sqlTokenData; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/SQLFoldingRuleManager.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/SQLFoldingRuleManager.java new file mode 100644 index 0000000000000000000000000000000000000000..7679aff6d2ef62aa23149e3eeae27fbe187a4223 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/SQLFoldingRuleManager.java @@ -0,0 +1,369 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.comm; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.eclipse.jface.text.rules.BufferedRuleBasedScanner; +import org.eclipse.jface.text.rules.EndOfLineRule; +import org.eclipse.jface.text.rules.IRule; +import org.eclipse.jface.text.rules.IToken; +import org.eclipse.jface.text.rules.Token; +import org.eclipse.jface.text.rules.WordRule; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLDDLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLDMLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLDelimiterRule; +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.SQLWordRule; + +/** + * Title: SQLFoldingRuleManager + * + * @since 3.0.0 + */ +public class SQLFoldingRuleManager extends BufferedRuleBasedScanner implements ISQLSyntax { + + /** + * The tkn comment. + */ + IToken tknComment = new Token(SQL_COMMENT); + + /** + * The tkn multiline comment. + */ + IToken tknMultilineComment = new Token(SQL_MULTILINE_COMMENT); + + /** + * The tkn sql double quotes identifier. + */ + IToken tknSqlDoubleQuotesIdentifier = new Token(SQL_DOUBLE_QUOTES_IDENTIFIER); + + /** + * The tkn sql string. + */ + IToken tknSqlString = new Token(SQL_STRING); + + /** + * Instantiates a new SQL folding rule manager. + */ + public SQLFoldingRuleManager() { + super(); + } + + /** + * Refresh rules. + */ + public void refreshRules() { + + List rules = new ArrayList(); + + final IToken otherToken = new Token(SQLFoldingConstants.SQL_TOKEN_UNKNOWN); + + final IToken newlineChar = new Token(System.lineSeparator()); + + IToken blockBeginToken = new SQLToken(SQLTokenConstants.T_SQL_BLOCK_BEGIN, + SQLFoldingConstants.SQL_KEYWORK_BEGIN); + + IToken blockEndToken = new SQLToken(SQLTokenConstants.T_SQL_BLOCK_END, SQLFoldingConstants.SQL_KEYWORK_END); + + IToken blockDeclareToken = new SQLToken(SQLTokenConstants.T_SQL_BLOCK_DECLARE, + SQLFoldingConstants.SQL_KEYWORK_DECLARE); + + IToken bracketStartToken = new SQLToken(SQLTokenConstants.T_SQL_BRACKET_BEGIN, + SQLFoldingConstants.SQL_BRACKET_START); + IToken bracketEndToken = new SQLToken(SQLTokenConstants.T_SQL_BRACKET_END, SQLFoldingConstants.SQL_BRACKET_END); + + IToken sqldDelim = new SQLToken(SQLTokenConstants.T_SQL_DELIMITER, SQLFoldingConstants.SQL_DELIM_NAME); + + IToken sqlFunctionDelim = new SQLToken(SQLTokenConstants.T_SQL_FUNCTION_END, + SQLFoldingConstants.SQL_DOUBLE_DOLLER); + + IToken sqlNumberToken = new SQLToken(SQLTokenConstants.T_SQL_NUMBER, SQLTokenConstants.T_SQL_NUMBER); + + IToken sqlDelimForwardSlash = new SQLToken(SQLTokenConstants.T_SQL_DELIMITER_FSLASH, + SQLFoldingConstants.SQL_DELIM_FSLASH); + + String[] delims = {SQLFoldingConstants.SQL_DELIM_SEMICOLON, SQLFoldingConstants.SQL_BRACKET_START, + SQLFoldingConstants.SQL_BRACKET_END}; + + SQLDelimiterRule delimRule = new SQLDelimiterRule(delims, sqldDelim); + + SQLDelimiterRule endDelimRule = getEndDelimRule(sqldDelim); + + SQLDelimiterRule brackerStartRule = getBrackerStartRule(bracketStartToken); + + SQLDelimiterRule brackerEndRule = getBrackerEndRule(bracketEndToken); + + SQLDelimiterRule functionEndRule = getFunEndRule(sqlFunctionDelim); + + SQLDelimiterRule newlineRule = getNewLineEndRule(newlineChar); + + String[] forwardSlash = {SQLFoldingConstants.SQL_DELIM_FSLASH}; + + SQLDelimiterRule forwardSlashRule = new SQLDelimiterRule(forwardSlash, sqlDelimForwardSlash); + + SQLWordRule wordRule = new SQLWordRule(delimRule, otherToken); + + addWordRules(newlineChar, blockBeginToken, blockEndToken, blockDeclareToken, wordRule); + + NumberDetector lDetector = new NumberDetector(); + + WordRule numberRule = new WordRule(lDetector, sqlNumberToken, true); + + addRules(wordRule, getKeywordRules()); + + IRule[] result = addRules(rules, endDelimRule, brackerStartRule, brackerEndRule, functionEndRule, newlineRule, + forwardSlashRule, wordRule, numberRule); + setRules(result); + } + + private SQLDelimiterRule getEndDelimRule(IToken sqldDelim) { + String[] endDelim = {SQLFoldingConstants.SQL_DELIM_SEMICOLON}; + + SQLDelimiterRule endDelimRule = new SQLDelimiterRule(endDelim, sqldDelim); + return endDelimRule; + } + + private SQLDelimiterRule getNewLineEndRule(final IToken newlineChar) { + String[] newlineEnd = {System.lineSeparator()}; + + SQLDelimiterRule newlineRule = new SQLDelimiterRule(newlineEnd, newlineChar); + return newlineRule; + } + + private SQLDelimiterRule getFunEndRule(IToken sqlFunctionDelim) { + String[] funcEnd = {SQLFoldingConstants.SQL_DOUBLE_DOLLER}; + + SQLDelimiterRule functionEndRule = new SQLDelimiterRule(funcEnd, sqlFunctionDelim); + return functionEndRule; + } + + private SQLDelimiterRule getBrackerEndRule(IToken bracketEndToken) { + String[] brackerEnd = {SQLFoldingConstants.SQL_BRACKET_END}; + + SQLDelimiterRule brackerEndRule = new SQLDelimiterRule(brackerEnd, bracketEndToken); + return brackerEndRule; + } + + private SQLDelimiterRule getBrackerStartRule(IToken bracketStartToken) { + String[] brackerStart = {SQLFoldingConstants.SQL_BRACKET_START}; + + SQLDelimiterRule brackerStartRule = new SQLDelimiterRule(brackerStart, bracketStartToken); + return brackerStartRule; + } + + private void addWordRules(final IToken newlineChar, IToken blockBeginToken, IToken blockEndToken, + IToken blockDeclareToken, SQLWordRule wordRule) { + // rules for begin & end + wordRule.addWord(SQLFoldingConstants.SQL_KEYWORK_BEGIN, blockBeginToken); + wordRule.addWord(SQLFoldingConstants.SQL_KEYWORK_END, blockEndToken); + wordRule.addWord(SQLFoldingConstants.SQL_KEYWORK_DECLARE, blockDeclareToken); + wordRule.addWord(System.lineSeparator(), newlineChar); + + // rules for dml + addRules(wordRule, getDMLRules()); + + // rules for create + + addRules(wordRule, getCreateRules()); + + // rules for if then else + + wordRule.addWord(SQLFoldingConstants.SQL_KEYWORD_IF, + new SQLToken(SQLTokenConstants.T_SQL_DDL_CONTROL_IF, SQLFoldingConstants.SQL_KEYWORD_IF)); + + wordRule.addWord(SQLFoldingConstants.SQL_KEYWORD_ELSE, + new SQLToken(SQLTokenConstants.T_SQL_DDL_CONTROL_ELSE, SQLFoldingConstants.SQL_KEYWORD_ELSE)); + + wordRule.addWord(SQLFoldingConstants.SQL_KEYWORD_ELSIF, + new SQLToken(SQLTokenConstants.T_SQL_DDL_CONTROL_ELSIF, SQLFoldingConstants.SQL_KEYWORD_ELSIF)); + + wordRule.addWord(SQLFoldingConstants.SQL_KEYWORD_ELSEIF, + new SQLToken(SQLTokenConstants.T_SQL_DDL_CONTROL_ELSIF, SQLFoldingConstants.SQL_KEYWORD_ELSEIF)); + } + + private IRule[] addRules(List rules, SQLDelimiterRule endDelimRule, SQLDelimiterRule brackerStartRule, + SQLDelimiterRule brackerEndRule, SQLDelimiterRule functionEndRule, SQLDelimiterRule newlineRule, + SQLDelimiterRule forwardSlashRule, SQLWordRule wordRule, WordRule numberRule) { + rules.add(new EndOfLineRule(SQLFoldingConstants.SQL_COMMENT_SINGLELINE, tknComment)); + rules.add(new NestedMultipleLineRule(SQLFoldingConstants.SQL_COMMENT_MULTILINE_START, + SQLFoldingConstants.SQL_COMMENT_MULTILINE_END, tknMultilineComment, (char) 0, true)); + rules.add(new NestedQuotesRule(SQLFoldingConstants.SQL_LITERAL_DOUBLE_QUOTES, + SQLFoldingConstants.SQL_LITERAL_DOUBLE_QUOTES, tknSqlDoubleQuotesIdentifier, + SQLFoldingConstants.SQL_LITERAL_DOUBLE_QUOTES_CHAR, true)); + rules.add(new NestedQuotesRule(SQLFoldingConstants.SQL_LITERAL_SINGLE_QUOTES, + SQLFoldingConstants.SQL_LITERAL_SINGLE_QUOTES, tknSqlString, + SQLFoldingConstants.SQL_LITERAL_SINGLE_QUOTES_CHAR, true)); + + rules.add(forwardSlashRule); + + rules.add(endDelimRule); + + rules.add(brackerStartRule); + + rules.add(brackerEndRule); + + rules.add(functionEndRule); + + rules.add(newlineRule); + + rules.add(wordRule); + + rules.add(numberRule); + + IRule[] result = new IRule[rules.size()]; + rules.toArray(result); + return result; + } + + private void addRules(SQLWordRule wordRule, Map dmlRules) { + for (Entry tokenEntry : dmlRules.entrySet()) { + wordRule.addWord(tokenEntry.getKey(), tokenEntry.getValue()); + } + } + + private Map getKeywordRules() { + + Map retVal = new HashMap(10); + + retVal.put(SQLFoldingConstants.SQL_KEYWORD_LANGUAGE, + new SQLToken(SQLTokenConstants.T_SQL_KEYWORK_LANGUAGE, SQLFoldingConstants.SQL_KEYWORD_LANGUAGE)); + + retVal.put(SQLFoldingConstants.SQL_KEYWORK_AS, + new SQLToken(SQLTokenConstants.T_SQL_KEYWORK_AS, SQLFoldingConstants.SQL_KEYWORK_AS)); + + retVal.put(SQLFoldingConstants.SQL_KEYWORK_IS, + new SQLToken(SQLTokenConstants.T_SQL_KEYWORK_IS, SQLFoldingConstants.SQL_KEYWORK_IS)); + + retVal.put(SQLFoldingConstants.SQL_KEYWORD_UNION, + new SQLToken(SQLTokenConstants.T_SQL_KEYWORK_UNION, SQLFoldingConstants.SQL_KEYWORD_UNION)); + + retVal.put(SQLFoldingConstants.SQL_KEYWORD_INTERSECT, + new SQLToken(SQLTokenConstants.T_SQL_KEYWORK_INTERSECT, SQLFoldingConstants.SQL_KEYWORD_INTERSECT)); + + retVal.put(SQLFoldingConstants.SQL_KEYWORD_EXCEPT, + new SQLToken(SQLTokenConstants.T_SQL_KEYWORK_EXCEPT, SQLFoldingConstants.SQL_KEYWORD_EXCEPT)); + + retVal.put(SQLFoldingConstants.SQL_KEYWORD_CASE, + new SQLToken(SQLTokenConstants.T_SQL_KEYWORK_CASE, SQLFoldingConstants.SQL_KEYWORD_CASE)); + + retVal.put(SQLFoldingConstants.SQL_KEYWORD_LOOP, + new SQLToken(SQLTokenConstants.T_SQL_LOOP, SQLFoldingConstants.SQL_KEYWORD_LOOP)); + + retVal.put(SQLFoldingConstants.SQL_KEYWORD_FOR, + new SQLToken(SQLTokenConstants.T_SQL_KEYWORD_FOR, SQLFoldingConstants.SQL_KEYWORD_FOR)); + + retVal.put(SQLFoldingConstants.SQL_KEYWORD_WHILE, + new SQLToken(SQLTokenConstants.T_SQL_KEYWORD_FOR, SQLFoldingConstants.SQL_KEYWORD_WHILE)); + + retVal.put(SQLFoldingConstants.SQL_KEYWORD_CURSOR, + new SQLToken(SQLTokenConstants.T_SQL_KEYWORD_CURSOR, SQLFoldingConstants.SQL_KEYWORD_CURSOR)); + + retVal.put(SQLFoldingConstants.SQL_KEYWORD_UNION, + new SQLToken(SQLTokenConstants.T_SQL_KEYWORK_UNION, SQLFoldingConstants.SQL_KEYWORD_UNION)); + + retVal.put(SQLFoldingConstants.SQL_KEYWORD_INTERSECT, + new SQLToken(SQLTokenConstants.T_SQL_KEYWORK_UNION, SQLFoldingConstants.SQL_KEYWORD_INTERSECT)); + + retVal.put(SQLFoldingConstants.SQL_KEYWORD_EXCEPT, + new SQLToken(SQLTokenConstants.T_SQL_KEYWORK_UNION, SQLFoldingConstants.SQL_KEYWORD_EXCEPT)); + + retVal.put(SQLFoldingConstants.SQL_KEYWORD_MINUS, + new SQLToken(SQLTokenConstants.T_SQL_KEYWORK_UNION, SQLFoldingConstants.SQL_KEYWORD_MINUS)); + + return retVal; + } + + private Map getCreateRules() { + + Map retVal = new HashMap(10); + + retVal.put(SQLFoldingConstants.SQL_CREATE, + new SQLDDLToken(SQLTokenConstants.T_SQL_DDL_CREATE, SQLFoldingConstants.SQL_CREATE)); + + retVal.put(SQLFoldingConstants.SQL_FUNCTION, + new SQLDDLToken(SQLTokenConstants.T_SQL_DDL_CREATE_FUNC, SQLFoldingConstants.SQL_FUNCTION)); + + retVal.put(SQLFoldingConstants.SQL_PROCEDURE, + new SQLDDLToken(SQLTokenConstants.T_SQL_DDL_CREATE_PROC, SQLFoldingConstants.SQL_PROCEDURE)); + + retVal.put(SQLFoldingConstants.SQL_PACKAGE, + new SQLDDLToken(SQLTokenConstants.T_SQL_DDL_CREATE_PACKAGE, SQLFoldingConstants.SQL_PACKAGE)); + + retVal.put(SQLFoldingConstants.SQL_PACKAGE_BODY, + new SQLDDLToken(SQLTokenConstants.T_SQL_DDL_CREATE_PACKAGE_BODY, SQLFoldingConstants.SQL_PACKAGE_BODY)); + + retVal.put(SQLFoldingConstants.SQL_TABLE, + new SQLDDLToken(SQLTokenConstants.T_SQL_DDL_CREATE_TABLE, SQLFoldingConstants.SQL_TABLE)); + + retVal.put(SQLFoldingConstants.SQL_TRIGGER, + new SQLToken(SQLTokenConstants.T_SQL_TRIGGER, SQLFoldingConstants.SQL_TRIGGER)); + + retVal.put(SQLFoldingConstants.SQL_ALTER, + new SQLToken(SQLTokenConstants.T_SQL_DDL_ALTER, SQLFoldingConstants.SQL_ALTER)); + + retVal.put(SQLFoldingConstants.SQL_VIEW, + new SQLToken(SQLTokenConstants.T_SQL_KEYWORK_VIEW, SQLFoldingConstants.SQL_VIEW)); + + retVal.put(SQLFoldingConstants.SQL_DROP, + new SQLToken(SQLTokenConstants.T_SQL_DROP, SQLFoldingConstants.SQL_DROP)); + + retVal.put(SQLFoldingConstants.SQL_GRANT, + new SQLToken(SQLTokenConstants.T_SQL_GRANT, SQLFoldingConstants.SQL_GRANT)); + + retVal.put(SQLFoldingConstants.SQL_REVOKE, + new SQLToken(SQLTokenConstants.T_SQL_REVOKE, SQLFoldingConstants.SQL_REVOKE)); + + return retVal; + } + + private Map getDMLRules() { + + Map retVal = new HashMap(10); + + retVal.put(SQLFoldingConstants.SQL_KEYWORD_SELECT, + new SQLDMLToken(SQLTokenConstants.T_SQL_DML_SELECT, SQLFoldingConstants.SQL_KEYWORD_SELECT)); + retVal.put(SQLFoldingConstants.SQL_KEYWORD_INSERT, + new SQLDMLToken(SQLTokenConstants.T_SQL_DML_INSERT, SQLFoldingConstants.SQL_KEYWORD_INSERT)); + retVal.put(SQLFoldingConstants.SQL_KEYWORD_DELETE, + new SQLDMLToken(SQLTokenConstants.T_SQL_DML_DELETE, SQLFoldingConstants.SQL_KEYWORD_DELETE)); + retVal.put(SQLFoldingConstants.SQL_KEYWORD_UPDATE, + new SQLDMLToken(SQLTokenConstants.T_SQL_DML_UPDATE, SQLFoldingConstants.SQL_KEYWORD_UPDATE)); + retVal.put(SQLFoldingConstants.SQL_KEYWORD_TRUNCATE, + new SQLDMLToken(SQLTokenConstants.T_SQL_DML_TRUNCATE, SQLFoldingConstants.SQL_KEYWORD_TRUNCATE)); + + retVal.put(SQLFoldingConstants.SQL_KEYWORD_WITH, + new SQLDMLToken(SQLTokenConstants.T_SQL_DML_WITH, SQLFoldingConstants.SQL_KEYWORD_WITH)); + + retVal.put(SQLFoldingConstants.SQL_KEYWORK_VALUES, + new SQLDMLToken(SQLTokenConstants.T_SQL_DML_INSERT_VALUES, SQLFoldingConstants.SQL_KEYWORK_VALUES)); + + retVal.put(SQLFoldingConstants.SQL_KEYWORD_MERGE, + new SQLDMLToken(SQLTokenConstants.T_SQL_MERGE, SQLFoldingConstants.SQL_KEYWORD_MERGE)); + + retVal.put(SQLFoldingConstants.SQL_KEYWORD_WHEN, + new SQLDMLToken(SQLTokenConstants.T_SQL_WHEN, SQLFoldingConstants.SQL_KEYWORD_WHEN)); + + return retVal; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/SQLFormatEditorParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/SQLFormatEditorParser.java new file mode 100644 index 0000000000000000000000000000000000000000..689a02e4c44da8dbe16441d62082b49e8d03f297 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/comm/SQLFormatEditorParser.java @@ -0,0 +1,433 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.comm; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.eclipse.jface.preference.PreferenceStore; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.format.option.FmtOptions; +import org.opengauss.mppdbide.gauss.format.option.FmtOptionsIf; +import org.opengauss.mppdbide.gauss.format.stmtformatter.FormatterFactory; +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.ScriptBlockInfoImpl; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.RuleBean; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.SQLScriptElement; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.SQLStmtTokenListBean; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.SQLStmtTokenManager; +import org.opengauss.mppdbide.gauss.sqlparser.handler.AbstractCreateHandler; +import org.opengauss.mppdbide.gauss.sqlparser.handler.AbstractRuleHandler; +import org.opengauss.mppdbide.gauss.sqlparser.handler.RuleHandlerConfig; +import org.opengauss.mppdbide.gauss.sqlparser.handler.SQLUnionRuleHandler; +import org.opengauss.mppdbide.gauss.sqlparser.handlerif.RuleHandlerIf; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserFactory; +import org.opengauss.mppdbide.gauss.sqlparser.parser.init.ParserInitilizer; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; + +/** + * Title: SQLFormatEditorParser + * + * @since 3.0.0 + */ +public class SQLFormatEditorParser extends SQLEditorParserBase { + + private IDocument sourceViewerDocument = null; + + /** + * Instantiates a new SQL editor parser. + */ + public SQLFormatEditorParser() { + ParserInitilizer.initParser(); + } + + /** + * Gets the document. + * + * @return the document + */ + public IDocument getDocument() { + return sourceViewerDocument; + } + + /** + * Sets the document. + * + * @param sourceDocument the new document + */ + public void setDocument(IDocument sourceDocument) { + this.sourceViewerDocument = sourceDocument; + } + + private AbstractRuleHandler getRuleHandlarByToken(IToken lToken, ScriptBlockInfo curBlock, + SQLStmtTokenManager lSQLStmtTokenManager, RuleBean lRuleBean) { + if (!(lToken instanceof SQLToken)) { + return null; + } + + try { + AbstractRuleHandler ruleHandlarByToken = RuleHandlerConfig.getInstance() + .getNewRuleHandle(((SQLToken) lToken).getType()); + + if (null == ruleHandlarByToken) { + return null; + } + + ruleHandlarByToken.setSqlStmtTokenManager(lSQLStmtTokenManager); + ruleHandlarByToken.setRuleScanner(this.getRuleManager()); + + if (isInvalidRuleHandlar(lRuleBean, ruleHandlarByToken)) { + return null; + } + + if (null == curBlock) { + return ruleHandlarByToken; + } + + RuleHandlerIf currentRuleHandler = curBlock.getAbstractRuleHandler(); + SQLToken lSqlToken = (SQLToken) lToken; + if ((lSqlToken.getType() == SQLTokenConstants.T_SQL_DDL_CREATE_FUNC + || lSqlToken.getType() == SQLTokenConstants.T_SQL_DDL_CREATE_PROC)) { + if (currentRuleHandler instanceof AbstractCreateHandler) { + AbstractCreateHandler createhandlar = (AbstractCreateHandler) currentRuleHandler; + boolean packageStmt = createhandlar.isPackageStmt(currentRuleHandler, curBlock, lSqlToken); + if (packageStmt) { + return ruleHandlarByToken; + } + } + return null; + } + + if (currentRuleHandler.isRuleHandlerValid(ruleHandlarByToken, curBlock, (SQLToken) lToken)) { + return ruleHandlarByToken; + } + } catch (Exception e) { + return null; + } + + return null; + + } + + private boolean isInvalidRuleHandlar(RuleBean lRuleBean, AbstractRuleHandler ruleHandlarByToken) { + return ruleHandlarByToken instanceof SQLUnionRuleHandler && !isPreviousScriptBlockSelect(lRuleBean); + } + + private boolean isPreviousScriptBlockSelect(RuleBean lRuleBean) { + return lRuleBean != null && null != lRuleBean.getPreviousScriptBlock() + && SQLTokenConstants.T_SQL_DML_SELECT == lRuleBean.getPreviousScriptBlock().getTokenType(); + } + + /** + * Parses the SQL docuement. + * + * @param preferenceStore the preference store + * @param startOffset the start offset + * @param endOffset the end offset + * @param formatterOffset the formatter offset + * @return the string + */ + public String parseSQLDocuement(PreferenceStore preferenceStore, int startOffset, int endOffset, + int formatterOffset) { + IDocument document = getDocument(); + + SQLStmtTokenManager parseQuery = parseQuery(document, startOffset, endOffset, 0, true, true); + + List sqlTokenStmtList = parseQuery.getSqlTokenStmtList(); + + StringBuilder lRetBuilder = new StringBuilder(); + + SQLStmtTokenListBean preNode = null; + + for (SQLStmtTokenListBean stmtTokenListBean : sqlTokenStmtList) { + + formatCustomSqlStmt(lRetBuilder, stmtTokenListBean, preferenceStore, formatterOffset, preNode); + preNode = stmtTokenListBean; + } + + return lRetBuilder.toString(); + + } + + private void formatCustomSqlStmt(StringBuilder lRetBuilder, SQLStmtTokenListBean stmtTokenListBean, + PreferenceStore preferenceStore, int formatterOffset, SQLStmtTokenListBean preNode) { + TCustomSqlStatement customSqlStmt = ParserFactory.getCustomSqlStmt(stmtTokenListBean); + + if (null != customSqlStmt) { + FmtOptionsIf options = new FmtOptions(); + options.setPrefStore(preferenceStore); + // format the statement object + String format = FormatterFactory.format(customSqlStmt, options, formatterOffset); + + if (lRetBuilder.length() == 0 && format.startsWith(System.lineSeparator())) { + format = format.replaceFirst(System.lineSeparator(), ""); + } + + if (isStmtTypeUnion(stmtTokenListBean, preNode) || isDeclareBegin(stmtTokenListBean, preNode)) { + lRetBuilder.append(""); + } else if (!isLastCharNewLine(lRetBuilder, true)) { + lRetBuilder.append(System.lineSeparator()); + } + lRetBuilder.append(format); + } else { + // add all the format data + StringBuilder lNoFormatBuilder = new StringBuilder(); + appendUnformattedString(stmtTokenListBean, lNoFormatBuilder, preferenceStore, formatterOffset); + + // trim the lNoFormatBuilder + String fullString = lNoFormatBuilder.toString().trim(); + + if ("/".equals(fullString)) { + lRetBuilder.append(System.lineSeparator()); + } else if (StringUtils.isNotBlank(fullString) && !isLastCharNewLine(lRetBuilder, true)) { + lRetBuilder.append(System.lineSeparator()); + lRetBuilder.append(System.lineSeparator()); + } + + lRetBuilder.append(fullString); + } + } + + private boolean isDeclareBegin(SQLStmtTokenListBean stmtTokenListBean, SQLStmtTokenListBean preNode) { + return preNode != null && (SQLTokenConstants.T_SQL_BLOCK_DECLARE == preNode.getStatementType() + && SQLTokenConstants.T_SQL_BLOCK_BEGIN == stmtTokenListBean.getStatementType()); + } + + private boolean isStmtTypeUnion(SQLStmtTokenListBean stmtTokenListBean, SQLStmtTokenListBean preNode) { + return null != preNode && (SQLTokenConstants.T_SQL_KEYWORK_UNION == preNode.getStatementType() + || SQLTokenConstants.T_SQL_KEYWORK_UNION == stmtTokenListBean.getStatementType()); + } + + private boolean isLastCharNewLine(StringBuilder lRetBuilder, boolean emptyRetVal) { + if (lRetBuilder.length() <= 0) { + return emptyRetVal; + } + return "\n".equals(lRetBuilder.charAt(lRetBuilder.length() - 1) + ""); + } + + private void appendUnformattedString(SQLStmtTokenListBean stmtTokenListBean, StringBuilder lNoFormatBuilder, + PreferenceStore preferenceStore, int formatterOffset) { + List sqlTokenData = stmtTokenListBean.getSqlTokenData(); + for (ISQLTokenData lSQLTokenData : sqlTokenData) { + if (null != lSQLTokenData.getSubTokenBean()) { + String fullData = lNoFormatBuilder.toString(); + lNoFormatBuilder.delete(0, lNoFormatBuilder.length()); + // rtrim the string and then send it + lNoFormatBuilder.append(rtrim(fullData)); + formatCustomSqlStmt(lNoFormatBuilder, lSQLTokenData.getSubTokenBean(), preferenceStore, formatterOffset, + null); + } else { + lNoFormatBuilder.append(lSQLTokenData.getTokenStr()); + } + + } + } + + private String rtrim(String str) { + int pos = str.length() - 1; + while (pos >= 0 && Character.isWhitespace(str.charAt(pos))) { + pos--; + } + return str.substring(0, pos + 1); + } + + /** + * Parses the query. + * + * @param document the document + * @param startPos the start pos + * @param endPos the end pos + * @param currentPos the current pos + * @param scriptMode the script mode + * @param keepDelimiters the keep delimiters + * @return the list + */ + protected SQLStmtTokenManager parseQuery(final IDocument document, final int startPos, final int endPos, + final int currentPos, final boolean scriptMode, final boolean keepDelimiters) { + List lretList = new ArrayList(); + ruleManager.setRange(document, startPos, endPos - startPos); + ScriptBlockInfo curBlock = null; + RuleBean lRuleBean = null; + ScriptBlockInfo unSupportedBlockToken = new ScriptBlockInfoImpl(); + SQLStmtTokenManager lSQLStmtTokenManager = new SQLStmtTokenManager(); + for (;;) { + IToken token = ruleManager.nextToken(); + int tokenOffset = ruleManager.getTokenOffset(); + int tokenLength = ruleManager.getTokenLength(); + String currentToken = getCurrentToken(tokenOffset, tokenLength); + int tokenType = token instanceof SQLToken ? ((SQLToken) token).getType() : SQLTokenConstants.T_SQL_UNKNOWN; + ISQLTokenData sqlTokenData = getSQLTokenData(ruleManager, token, currentToken); + if (tokenOffset < startPos) { + // This may happen with EOF tokens (bug in jface?) + break; + } + // if it is not of the token specified then can return handle + // optional token end + RuleBean optRuleBean = checkBlockEndWithOptionalToken(lretList, curBlock, sqlTokenData, tokenType, + currentToken); + if (null != optRuleBean) { + curBlock = optRuleBean.getScriptBlockInfo(); + if (optRuleBean.isContinueLoop() || null == curBlock) { + continue; + } + } + if (tokenType != SQLTokenConstants.T_SQL_UNKNOWN) { + // 1. if the curBlock is null then get the handler by token + AbstractRuleHandler ruleHandlarByToken = getRuleHandlarByToken(token, curBlock, lSQLStmtTokenManager, + lRuleBean); + if (null == curBlock) { + if (null == ruleHandlarByToken) { + addUnSupportedBlockData(curBlock, unSupportedBlockToken, sqlTokenData); + // some thing went wrong the token is not associated + // with handler the token in not folding token + continue; + } + curBlock = ruleHandlarByToken.createScriptBlock(null, sqlTokenData, tokenOffset); + unSupportedBlockToken = addAndGetUnSupportedBlockToken(unSupportedBlockToken, lSQLStmtTokenManager); + curBlock.addSQLTokenData(sqlTokenData); + } else { + // get rule manager wrapper + addSqlTokenAndCurrentTokenData(curBlock, currentToken, sqlTokenData); + lRuleBean = getCurrentBlockHandleRuleBean(lretList, curBlock, token, ruleHandlarByToken, + sqlTokenData); + curBlock = lRuleBean.getScriptBlockInfo(); + if (null == curBlock) { + continue; + } + addLastKnownTokenDetails(curBlock, tokenOffset, tokenLength, currentToken); + if (curBlock.isInvokeParent()) { + lRuleBean = getCurrentBlockHandleRuleBean(lretList, curBlock, token, ruleHandlarByToken, + sqlTokenData); + curBlock = lRuleBean.getScriptBlockInfo(); + if (null == curBlock) { + continue; + } + } + } + } else if (null != curBlock) { + curBlock.addSQLTokenData(sqlTokenData); + } + addUnSupportedBlockData(curBlock, unSupportedBlockToken, sqlTokenData); + handleLastTokenData(curBlock, token, tokenOffset, tokenLength, currentToken); + if (token.isEOF()) { + getEOFRetVal(curBlock, lretList); + lSQLStmtTokenManager.addSQLStmtTokenListBean(unSupportedBlockToken); + break; + } + } + return lSQLStmtTokenManager; + } + + private ScriptBlockInfo addAndGetUnSupportedBlockToken(ScriptBlockInfo unSupportedBlockToken, + SQLStmtTokenManager lSQLStmtTokenManager) { + lSQLStmtTokenManager.addSQLStmtTokenListBean(unSupportedBlockToken); + unSupportedBlockToken = new ScriptBlockInfoImpl(); + return unSupportedBlockToken; + } + + /** + * Gets the current block handle rule bean. + * + * @param lretList the lret list + * @param curBlock the cur block + * @param token the token + * @param ruleHandlarByToken the rule handlar by token + * @param sqlTokenData the sql token data + * @return the current block handle rule bean + */ + public RuleBean getCurrentBlockHandleRuleBean(List lretList, ScriptBlockInfo curBlock, + IToken token, AbstractRuleHandler ruleHandlarByToken, ISQLTokenData sqlTokenData) { + RuleBean ruleBean = curBlock.getAbstractRuleHandler().handle(curBlock, lretList, getSQLToken(token), + sqlTokenData, ruleHandlarByToken); + return ruleBean; + } + + private void addSqlTokenAndCurrentTokenData(ScriptBlockInfo curBlock, String currentToken, + ISQLTokenData sqlTokenData) { + curBlock.addSQLTokenData(sqlTokenData); + curBlock.setCurrentKnownToken(currentToken); + } + + private void addUnSupportedBlockData(ScriptBlockInfo curBlock, ScriptBlockInfo unSupportedBlockToken, + ISQLTokenData sqlTokenData) { + if (null == curBlock && (null != sqlTokenData.getTokenStr() || null != sqlTokenData.getSubTokenBean())) { + unSupportedBlockToken.addSQLTokenData(sqlTokenData); + } + } + + /** + * Check block end with optional token. + * + * @param lretList the lret list + * @param curBlock the cur block + * @param token the token + * @param tokenType the token type + * @param currentToken the current token + * @return the rule bean + */ + public RuleBean checkBlockEndWithOptionalToken(List lretList, ScriptBlockInfo curBlock, + ISQLTokenData token, int tokenType, String currentToken) { + RuleBean ruleBean = null; + + if (null == currentToken || StringUtils.isEmpty(currentToken.trim())) { + return null; + } + + if (null != curBlock && curBlock.getNextOptTokenToEnd() != SQLTokenConstants.T_SQL_UNKNOWN) { + + if (curBlock.getNextOptTokenToEnd() == tokenType) { + curBlock.addSQLTokenData(token); + ISQLTokenData sqlTokenData = getSQLTokenData(ruleManager, token.getToken(), currentToken); + ruleBean = curBlock.getAbstractRuleHandler().endOptionalScript(curBlock, lretList, + getSQLToken(token.getToken()), sqlTokenData); + + ruleBean.setContinueLoop(true); + + } else if (curBlock.getNextMiddleOptTokenToEnd() == tokenType) { + curBlock.addSQLTokenData(token); + ruleBean = new RuleBean(); + ruleBean.setScriptBlockInfo(curBlock); + ruleBean.setContinueLoop(true); + + } else { + // FORMATPENDING: curBlock.addSQLTokenData(token); is not + // handled here + token.setTokenLength(curBlock.getLastKnownTokenlenght()); + token.setTokenOffset(curBlock.getLastKnownTokenOffSet()); + + SQLToken dummyToken = null; + + if (!(token.getToken() instanceof SQLToken)) { + dummyToken = new SQLToken(SQLTokenConstants.T_SQL_DUMMY, SQLFoldingConstants.SQL_TOKEN_DUMMY); + } else { + dummyToken = (SQLToken) token.getToken(); + } + + ruleBean = curBlock.getAbstractRuleHandler().endOptionalScript(curBlock, lretList, dummyToken, token); + } + + } + return ruleBean; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/exception/GaussDBSQLParserException.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/exception/GaussDBSQLParserException.java new file mode 100644 index 0000000000000000000000000000000000000000..b55e690e2859088c3f45fc78422004220eedf75d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/exception/GaussDBSQLParserException.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.exception; + +/** + * Title: GaussDBSQLParserException + * + * @since 3.0.0 + */ +public class GaussDBSQLParserException extends RuntimeException { + + private static final long serialVersionUID = -2820181785972339647L; + + public GaussDBSQLParserException() { + super(); + } + + public GaussDBSQLParserException(String message) { + super(message); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/AbstractAlterHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/AbstractAlterHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..5e2851fe6b37b5eff7f42b03ccb24e46d97a9ba0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/AbstractAlterHandler.java @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLDDLTypeEnum; +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.bean.DMLParamScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; + +/** + * + * Title: AbstractCreateHandler + * + * @since 3.0.0 + */ +public class AbstractAlterHandler extends AbstractRuleHandler implements IPartialStmt { + + private AbstractAlterStmt abstractAlterStmt = new AbstractAlterStmt(); + + /** + * Instantiates a new abstract alter handler. + */ + public AbstractAlterHandler() { + + } + + /** + * Gets the end token type. + * + * @param curBlock the cur block + * @return the end token type + */ + @Override + public int getEndTokenType(ScriptBlockInfo curBlock) { + + // to be done in the sub classes + return getCreateStmt(getDMLParamScriptBlock(curBlock)).getEndTokenType(); + } + + /** + * Gets the script block. + * + * @param parent the parent + * @param token the token + * @return the script block + */ + protected ScriptBlockInfo getScriptBlock(ScriptBlockInfo parent, ISQLTokenData token) { + return new DMLParamScriptBlockInfo(parent, token.getToken(), this); + } + + /** + * Checks if is stop script block. + * + * @param curBlock the cur block + * @param ruleHandlarByToken the rule handlar by token + * @return true, if is stop script block + */ + @Override + public boolean isStopScriptBlock(ScriptBlockInfo curBlock, AbstractRuleHandler ruleHandlarByToken) { + // to be done in the sub classes + + return false; + } + + /** + * Handle SQL stmt. + * + * @param curScriptBlock the cur script block + */ + @Override + public void handleSQLStmt(ScriptBlockInfo curScriptBlock) { + + DMLParamScriptBlockInfo curBlock = getDMLParamScriptBlock(curScriptBlock); + String latestkeyword = null; + if (curBlock != null) { + latestkeyword = curBlock.getCurrentKnownToken(); + } + + if (curBlock != null && null == curBlock.getDdlType()) { + if (SQLFoldingConstants.SQL_VIEW.equalsIgnoreCase(latestkeyword)) { + curBlock.setDdlType(SQLDDLTypeEnum.VIEW); + } + } + + } + + /** + * Handle partial stmt. + * + * @param curBlock the cur block + */ + public void handlePartialStmt(ScriptBlockInfo curBlock) { + + handleSQLStmt(curBlock); + + } + + /** + * Checks if is stop parent script block. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is stop parent script block + */ + public boolean isStopParentScriptBlock(ScriptBlockInfo curBlock, IToken token) { + + return getCreateStmt(getDMLParamScriptBlock(curBlock)).isStopParentScriptBlock(curBlock, getSQLToken(token)); + } + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(ScriptBlockInfo curBlock, IToken token) { + return getCreateStmt(getDMLParamScriptBlock(curBlock)).isNested(curBlock, (SQLToken) token); + } + + /** + * Checks if is ignore by current block. + * + * @param ruleHandlarByToken the rule handlar by token + * @param curBlock the cur block + * @param token the token + * @return true, if is ignore by current block + */ + public boolean isIgnoreByCurrentBlock(AbstractRuleHandler ruleHandlarByToken, ScriptBlockInfo curBlock, + SQLToken token) { + return getCreateStmt(getDMLParamScriptBlock(curBlock)).isIgnoreByCurrentBlock(ruleHandlarByToken, curBlock, + token); + } + + /** + * Checks if is block end. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is block end + */ + public boolean isBlockEnd(ScriptBlockInfo curBlock, SQLToken token) { + return getCreateStmt(getDMLParamScriptBlock(curBlock)).isBlockEnd(curBlock, token); + } + + private DMLParamScriptBlockInfo getDMLParamScriptBlock(ScriptBlockInfo curBlock) { + if (curBlock instanceof DMLParamScriptBlockInfo) { + return (DMLParamScriptBlockInfo) curBlock; + } + return null; + } + + private AbstractAlterStmt getCreateStmt(DMLParamScriptBlockInfo curScriptBlock) { + + return RuleHandlerConfig.getInstance().getAlterStmt(curScriptBlock, abstractAlterStmt); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/AbstractAlterStmt.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/AbstractAlterStmt.java new file mode 100644 index 0000000000000000000000000000000000000000..a0ae7e111f28da6df1d6c5b1331d31f0198d5e1b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/AbstractAlterStmt.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; + +/** + * + * Title: AbstractCreateStmt + * + * @since 3.0.0 + */ +public class AbstractAlterStmt { + + /** + * Gets the end token type. + * + * @return the end token type + */ + public int getEndTokenType() { + return SQLTokenConstants.T_SQL_DELIMITER; + } + + /** + * Checks if is stop parent script block. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is stop parent script block + */ + public boolean isStopParentScriptBlock(ScriptBlockInfo curBlock, SQLToken token) { + + return false; + } + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(ScriptBlockInfo curBlock, SQLToken token) { + return false; + } + + /** + * Checks if is block end. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is block end + */ + public boolean isBlockEnd(ScriptBlockInfo curBlock, SQLToken token) { + return null != curBlock && token.getType() == getEndTokenType(); + } + + /** + * Checks if is ignore by current block. + * + * @param ruleHandlarByToken the rule handlar by token + * @param curBlock the cur block + * @param token the token + * @return true, if is ignore by current block + */ + public boolean isIgnoreByCurrentBlock(AbstractRuleHandler ruleHandlarByToken, ScriptBlockInfo curBlock, + SQLToken token) { + return SQLTokenConstants.T_SQL_DDL_CONTROL_IF == token.getType() + || SQLTokenConstants.T_SQL_DML_WITH == token.getType(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/AbstractCreateHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/AbstractCreateHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..9fab89cdfa69811123fbcb5f821ae23cc1d87f58 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/AbstractCreateHandler.java @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.bean.DMLParamScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; + +/** + * Title: AbstractCreateHandler + * + * @since 3.0.0 + */ +public class AbstractCreateHandler extends BaseCreatehandler { + + /** + * Instantiates a new abstract create handler. + */ + public AbstractCreateHandler() { + + } + + /** + * Gets the end token type. + * + * @param curBlock the cur block + * @return the end token type + */ + @Override + public int getEndTokenType(ScriptBlockInfo curBlock) { + DMLParamScriptBlockInfo dmlParamScriptBlock = getDMLParamScriptBlock(curBlock); + // to be done in the sub classes + return getCreateStmt(dmlParamScriptBlock).getEndTokenType(); + } + + /** + * Checks if is stop script block. + * + * @param curBlock the cur block + * @param ruleHandlarByToken the rule handlar by token + * @return true, if is stop script block + */ + @Override + public boolean isStopScriptBlock(ScriptBlockInfo curBlock, AbstractRuleHandler ruleHandlarByToken) { + // to be done in the sub classes + + return false; + } + + /** + * Handle SQL stmt. + * + * @param curScriptBlock the cur script block + */ + @Override + public void handleSQLStmt(ScriptBlockInfo curScriptBlock) { + + DMLParamScriptBlockInfo curBlock = getDMLParamScriptBlock(curScriptBlock); + if (null != curBlock) { + String latestkeyword = curBlock.getCurrentKnownToken(); + + if (null == curBlock.getDdlType()) { + if (null == latestkeyword) { + curBlock.setDDLType(curBlock.getTokenType()); + } else { + curBlock.setDDLType(latestkeyword); + } + } + } + + } + + /** + * Handle partial stmt. + * + * @param curBlock the cur block + */ + public void handlePartialStmt(ScriptBlockInfo curBlock) { + + handleSQLStmt(curBlock); + + } + + /** + * Checks if is ignore by current block. + * + * @param ruleHandlarByToken the rule handlar by token + * @param curBlock the cur block + * @param token the token + * @return true, if is ignore by current block + */ + public boolean isIgnoreByCurrentBlock(AbstractRuleHandler ruleHandlarByToken, ScriptBlockInfo curBlock, + SQLToken token) { + DMLParamScriptBlockInfo dmlParamScriptBlock = getDMLParamScriptBlock(curBlock); + return getCreateStmt(dmlParamScriptBlock).isIgnoreByCurrentBlock(ruleHandlarByToken, curBlock, token); + } + + /** + * Gets the script block. + * + * @param parent the parent + * @param token the token + * @return the script block + */ + protected ScriptBlockInfo getScriptBlock(ScriptBlockInfo parent, ISQLTokenData token) { + return new DMLParamScriptBlockInfo(parent, token.getToken(), this); + } + + /** + * Checks if is stop parent script block. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is stop parent script block + */ + public boolean isStopParentScriptBlock(ScriptBlockInfo curBlock, IToken token) { + DMLParamScriptBlockInfo dmlParamScriptBlock = getDMLParamScriptBlock(curBlock); + return getCreateStmt(dmlParamScriptBlock).isStopParentScriptBlock(getDMLParamScriptBlock(curBlock), + getSQLToken(token)); + } + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(ScriptBlockInfo curBlock, IToken token) { + DMLParamScriptBlockInfo dmlParamScriptBlock = getDMLParamScriptBlock(curBlock); + return getCreateStmt(dmlParamScriptBlock).isNested(dmlParamScriptBlock, (SQLToken) token); + } + + /** + * Checks if is block end. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is block end + */ + public boolean isBlockEnd(ScriptBlockInfo curBlock, SQLToken token) { + DMLParamScriptBlockInfo dmlParamScriptBlock = getDMLParamScriptBlock(curBlock); + return getCreateStmt(dmlParamScriptBlock).isBlockEnd(dmlParamScriptBlock, token); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/AbstractCreateStmt.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/AbstractCreateStmt.java new file mode 100644 index 0000000000000000000000000000000000000000..4b7489466834cfd2c9eec02bd4c275244176036e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/AbstractCreateStmt.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.handlerif.RuleHandlerIf; + +/** + * Title: AbstractCreateStmt + * + * @since 3.0.0 + */ +public class AbstractCreateStmt { + + /** + * Gets the end token type. + * + * @return the end token type + */ + public int getEndTokenType() { + return SQLTokenConstants.T_SQL_DELIMITER; + } + + /** + * Checks if is stop parent script block. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is stop parent script block + */ + public boolean isStopParentScriptBlock(T curBlock, SQLToken token) { + + return false; + } + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(T curBlock, SQLToken token) { + return false; + } + + /** + * Checks if is block end. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is block end + */ + public boolean isBlockEnd(T curBlock, SQLToken token) { + return null != curBlock && token.getType() == getEndTokenType(); + } + + /** + * Checks if is ignore by current block. + * + * @param ruleHandlarByToken the rule handlar by token + * @param curBlock the cur block + * @param token the token + * @return true, if is ignore by current block + */ + public boolean isIgnoreByCurrentBlock(AbstractRuleHandler ruleHandlarByToken, ScriptBlockInfo curBlock, + SQLToken token) { + return SQLTokenConstants.T_SQL_DDL_CONTROL_IF == token.getType() + || SQLTokenConstants.T_SQL_DML_WITH == token.getType(); + } + + /** + * Checks if is ignore by current block. + * + * @param currentRuleHandler the rule handlar by token + * @param curBlock the cur block + * @param lToken the token + * @return true, if is ignore by current block + */ + public boolean isRuleHandlerValid(RuleHandlerIf currentRuleHandler, ScriptBlockInfo curBlock, SQLToken lToken) { + return true; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/AbstractDMLRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/AbstractDMLRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..6d3f6cfff9dc105551a674ec2e48929ae29c8c79 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/AbstractDMLRuleHandler.java @@ -0,0 +1,418 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import java.util.List; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.DMLParamScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.SQLBracketParamData; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.RuleBean; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.SQLScriptElement; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.handlerif.RuleHandlerIf; + +/** + * Title: AbstractDMLRuleHandler + * + * @since 3.0.0 + */ +public class AbstractDMLRuleHandler extends AbstractRuleHandler { + + /** + * Checks if is stop script block. + * + * @param curBlock the cur block + * @param ruleHandlarByToken the rule handlar by token + * @return true, if is stop script block + */ + @Override + public boolean isStopScriptBlock(ScriptBlockInfo curBlock, AbstractRuleHandler ruleHandlarByToken) { + + if (ruleHandlarByToken instanceof AbstractDMLRuleHandler) { + return false; + } + + return true; + + } + + /** + * Gets the end token type. + * + * @param curBlockMain the cur block main + * @return the end token type + */ + @Override + public int getEndTokenType(ScriptBlockInfo curBlockMain) { + return SQLTokenConstants.T_SQL_DELIMITER; + } + + /** + * Handle block end. + * + * @param curBlockMain the cur block main + * @param lretList the lret list + * @param token the token + * @param lRuleBean the l rule bean + */ + public void handleBlockEnd(ScriptBlockInfo curBlockMain, List lretList, SQLToken token, + RuleBean lRuleBean) { + + ScriptBlockInfo curBlock = curBlockMain; + while (null != curBlock) { + + // if not nested then end and start new block + curBlock.getAbstractRuleHandler().endScriptBlock(curBlock, lretList, curBlock.getLastTokenOffSet(), + curBlock.getLastTokenlenght()); + + // check how many parents blocks need to end the script + + if (!curBlock.getAbstractRuleHandler().isStopParentScriptBlock(curBlock, token)) { + break; + } + + curBlock = curBlock.getParent(); + + } + + lRuleBean.setScriptBlockInfo(null != curBlock ? curBlock.getParent() : null); + + } + + /** + * Checks if is stop parent script block. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is stop parent script block + */ + public boolean isStopParentScriptBlock(ScriptBlockInfo curBlock, IToken token) { + + if (null != curBlock.getParent() && curBlock.getAbstractRuleHandler() instanceof AbstractDMLRuleHandler + && (curBlock.getParent().getAbstractRuleHandler() instanceof AbstractDMLRuleHandler)) { + return true; + } + + return false; + } + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(ScriptBlockInfo curBlock, IToken token) { + + if (curBlock.isNested() && null != getSQLToken(token) + && (getSQLToken(token).getType() == SQLTokenConstants.T_SQL_DML_SELECT)) { + return true; + } + + return false; + } + + /** + * Handle nested block script create. + * + * @param curBlock the cur block + * @param token the token + * @param lRuleBean the l rule bean + * @param tokenOffset the token offset + */ + public void handleNestedBlockScriptCreate(ScriptBlockInfo curBlock, ISQLTokenData token, RuleBean lRuleBean, + int tokenOffset) { + String lastKnownToken = curBlock.getLastKnownToken(); + + if (SQLFoldingConstants.SQL_BRACKET_START.equalsIgnoreCase(lastKnownToken) + || SQLFoldingConstants.SQL_KEYWORD_UNION.equalsIgnoreCase(lastKnownToken) + || SQLFoldingConstants.SQL_KEYWORD_INTERSECT.equalsIgnoreCase(lastKnownToken) + || SQLFoldingConstants.SQL_KEYWORD_EXCEPT.equalsIgnoreCase(lastKnownToken) + || SQLFoldingConstants.SQL_KEYWORD_MINUS.equalsIgnoreCase(lastKnownToken)) { + ScriptBlockInfo scriptBlock = createScriptBlock(curBlock, token, tokenOffset, true); + SQLBracketParamData lSQLBracketParamData = new SQLBracketParamData(); + + scriptBlock.setBracketParamData(lSQLBracketParamData); + + if (null != curBlock.getBracketParamData()) { + curBlock.getBracketParamData().decrStartEndTokenCounter(); + } + scriptBlock.setStartOffSetForBlock(tokenOffset); + + lRuleBean.setScriptBlockInfo(scriptBlock); + + } else { + super.handleNestedBlockScriptCreate(curBlock, token, lRuleBean, tokenOffset); + } + } + + /** + * Handle parent block end. + * + * @param curBlock the cur block + * @param lretList the lret list + * @param token the token + * @param ruleManager the rule manager + * @param lRuleBean the l rule bean + */ + public void handleParentBlockEnd(ScriptBlockInfo curBlock, List lretList, SQLToken token, + ISQLTokenData ruleManager, RuleBean lRuleBean) { + ScriptBlockInfo parentBlock = curBlock.getParent(); + + while (null != parentBlock) { + + if ((parentBlock.getAbstractRuleHandler() instanceof AbstractDMLRuleHandler + || (parentBlock.getAbstractRuleHandler() instanceof SQLCursorRuleHandler)) + && isBlockEnd(parentBlock, token)) { + parentBlock.getAbstractRuleHandler().endScriptBlock(parentBlock, lretList, ruleManager.getTokenOffset(), + ruleManager.getTokenLength()); + } else { + break; + } + + parentBlock = parentBlock.getParent(); + + } + + lRuleBean.setScriptBlockInfo(parentBlock); + } + + /** + * Handle other end. + * + * @param curBlock the cur block + * @param token the token + * @param lRuleBean the l rule bean + * @param lretList the lret list + * @param ruleManager the rule manager + */ + public void handleOtherEnd(ScriptBlockInfo curBlock, SQLToken token, RuleBean lRuleBean, + List lretList, ISQLTokenData ruleManager) { + manageCaseStmt(curBlock, token); + // get from the parent that the child is sub query with '(' then handle + // other '(' start and ')' end + SQLBracketParamData bracketParamData = curBlock.getBracketParamData(); + if (null != bracketParamData) { + + if (token.getType() == SQLTokenConstants.T_SQL_BRACKET_BEGIN) { + bracketParamData.incrStartEndTokenCounter(); + } else if (token.getType() == SQLTokenConstants.T_SQL_BRACKET_END) { + bracketParamData.decrStartEndTokenCounter(); + } + + if (bracketParamData.getStartEndTokenCounter() < 0) { + // stop the script + + endScriptBlock(curBlock, lretList, curBlock.getLastTokenOffSet(), curBlock.getLastTokenlenght()); + removeLastTokenAndAddToParent(curBlock.getParent(), ruleManager, curBlock); + lRuleBean.setScriptBlockInfo(curBlock.getParent()); + + return; + } + + } else if (null != curBlock.getParent() && curBlock.getParent() instanceof DMLParamScriptBlockInfo + && token.getType() == SQLTokenConstants.T_SQL_KEYWORK_LANGUAGE + && SQLFoldingConstants.SQL_DOUBLE_DOLLER.equalsIgnoreCase(curBlock.getLastKnownToken())) { + + setParentBlockInfo(curBlock); + + endScriptBlock(curBlock, lretList, curBlock.getLastKnownTokenOffSet(), curBlock.getLastKnownTokenlenght()); + lRuleBean.setScriptBlockInfo(curBlock.getParent()); + return; + + } else if (null != curBlock.getParent() + && (isSQLBlockEnd(curBlock, token) || isSQLIfEnd(curBlock, token) || isSQLElseIfEnd(curBlock, token))) { + + curBlock.getParent().setInvokeParent(true); + + endScriptBlock(curBlock, lretList, curBlock.getLastTokenOffSet(), curBlock.getLastTokenlenght()); + lRuleBean.setScriptBlockInfo(curBlock.getParent()); + return; + } + + handleStmtCustomEnd(curBlock, token, lRuleBean, lretList, ruleManager); + + } + + /** + * Checks if is case stmt open. + * + * @param curBlock the cur block + * @return true, if is case stmt open + */ + private boolean isCaseStmtOpen(ScriptBlockInfo curBlock) { + + SQLBracketParamData caseParamData = curBlock.getCaseParamData(); + + if (null == caseParamData) { + return false; + } + + return caseParamData.getStartEndTokenCounter() > 0; + } + + private void manageCaseStmt(ScriptBlockInfo curBlock, SQLToken token) { + + SQLBracketParamData caseParamData = curBlock.getCaseParamData(); + + if (token.getType() == SQLTokenConstants.T_SQL_KEYWORK_CASE) { + if (null == caseParamData) { + + caseParamData = new SQLBracketParamData(); + curBlock.setCaseParamData(caseParamData); + } + + caseParamData.incrStartEndTokenCounter(); + + } else if (null != caseParamData && token.getType() == SQLTokenConstants.T_SQL_BLOCK_END) { + caseParamData.decrStartEndTokenCounter(); + + } + } + + private boolean isSQLBlockEnd(ScriptBlockInfo curBlock, SQLToken token) { + return curBlock.getParent().getAbstractRuleHandler() instanceof SQLBlockRuleHandler + && token.getType() == SQLTokenConstants.T_SQL_BLOCK_END; + } + + private boolean isSQLIfEnd(ScriptBlockInfo curBlock, SQLToken token) { + return curBlock.getParent().getAbstractRuleHandler() instanceof SQLIFConditionRuleHandler + && isElseIfBlock(token); + } + + /** + * Checks if is else if block. + * + * @param token the token + * @return true, if is else if block + */ + public boolean isElseIfBlock(SQLToken token) { + return token.getType() == SQLTokenConstants.T_SQL_BLOCK_END + || token.getType() == SQLTokenConstants.T_SQL_DDL_CONTROL_ELSE + || token.getType() == SQLTokenConstants.T_SQL_DDL_CONTROL_ELSIF; + } + + private boolean isSQLElseIfEnd(ScriptBlockInfo curBlock, SQLToken token) { + return curBlock.getParent().getAbstractRuleHandler() instanceof SQLELSIFConditionRuleHandler + && isElseIfBlock(token); + } + + /** + * Sets the parent block info. + * + * @param curBlock the new parent block info + */ + public void setParentBlockInfo(ScriptBlockInfo curBlock) { + + ScriptBlockInfo parentBlock = curBlock.getParent(); + parentBlock.setInvokeParent(true); + + if (parentBlock instanceof DMLParamScriptBlockInfo) { + ((DMLParamScriptBlockInfo) parentBlock).setEndStmtFound(true); + } + } + + /** + * Handle stmt custom end. + * + * @param curBlock the cur block + * @param token the token + * @param lRuleBean the l rule bean + * @param lretList the lret list + * @param ruleManager the rule manager + */ + protected void handleStmtCustomEnd(ScriptBlockInfo curBlock, SQLToken token, RuleBean lRuleBean, + List lretList, ISQLTokenData ruleManager) { + if (isInMergeStmt(curBlock, token)) { + unreadAndEndScriptBlock(curBlock, lRuleBean, lretList, ruleManager); + } + } + + /** + * unread and End the ScriptBlock. + * + * @param curBlock the cur block + * @param lRuleBean the l rule bean + * @param lretList the lret list + * @param ruleManager the rule manager + */ + protected void unreadAndEndScriptBlock(ScriptBlockInfo curBlock, RuleBean lRuleBean, + List lretList, ISQLTokenData ruleManager) { + // 1.unread for the token size + if (null != this.getRuleScanner()) { + int tokenLength = ruleManager.getTokenLength(); + while (tokenLength > 0) { + this.getRuleScanner().unread(); + tokenLength--; + } + } + + // 2.remove last token + if (!curBlock.getAllTokenList().isEmpty()) { + curBlock.getAllTokenList().remove(curBlock.getAllTokenList().size() - 1); + } + + endScriptBlock(curBlock, lretList, curBlock.getLastTokenOffSet(), curBlock.getLastTokenlenght()); + lRuleBean.setScriptBlockInfo(curBlock.getParent()); + lRuleBean.setPreviousScriptBlock(curBlock); + } + + /** + * returns the select,insert or update is in Merge stmt or not. + * + * @param curBlock the cur block + * @param token the token + * @return weather it is in merge stmt or not in merge stmt + */ + protected boolean isInMergeStmt(ScriptBlockInfo curBlock, SQLToken token) { + return null != curBlock.getParent() && curBlock.getParent().getTokenType() == SQLTokenConstants.T_SQL_MERGE + && SQLTokenConstants.T_SQL_WHEN == token.getType(); + } + + /** + * Checks if is rule handler valid. + * + * @param currentRuleHandler the current rule handler + * @param curBlock the cur block + * @return true, if is rule handler valid + */ + public boolean isRuleHandlerValid(RuleHandlerIf currentRuleHandler, ScriptBlockInfo curBlock, SQLToken token) { + + if (currentRuleHandler instanceof SQLELSEConditionRuleHandler && isCaseStmtOpen(curBlock)) { + return false; + } + + return true; + } + + /** + * Checks if is case stmt nested. + * + * @param token the token + * @return true, if is case stmt nested + */ + protected boolean isCaseStmtNested(IToken token) { + return null != getSQLToken(token) && getSQLToken(token).getType() == SQLTokenConstants.T_SQL_KEYWORK_CASE; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/AbstractRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/AbstractRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..c52fb9ae82f3e273c3f56802b250abd680293f24 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/AbstractRuleHandler.java @@ -0,0 +1,594 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import java.util.List; + +import org.eclipse.jface.text.rules.BufferedRuleBasedScanner; +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.DMLParamScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.ScriptBlockInfoImpl; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.RuleBean; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.SQLQueryPosition; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.SQLScriptElement; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.SQLStmtTokenListBean; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.SQLStmtTokenManager; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.SQLTokenFactory; +import org.opengauss.mppdbide.gauss.sqlparser.handlerif.RuleHandlerIf; + +/** + * Title: AbstractRuleHandler + * + * @since 3.0.0 + */ +public abstract class AbstractRuleHandler implements RuleHandlerIf, Cloneable { + + private SQLStmtTokenManager sqlStmtTokenManager = null; + + private BufferedRuleBasedScanner ruleScanner = null; + + /** + * Gets the sql stmt token manager. + * + * @return the sql stmt token manager + */ + public SQLStmtTokenManager getSqlStmtTokenManager() { + return sqlStmtTokenManager; + } + + /** + * Sets the sql stmt token manager. + * + * @param sqlStmtTokenManager the new sql stmt token manager + */ + public void setSqlStmtTokenManager(SQLStmtTokenManager sqlStmtTokenManager) { + this.sqlStmtTokenManager = sqlStmtTokenManager; + } + + /** + * Gets the rule scanner. + * + * @return the rule scanner + */ + public BufferedRuleBasedScanner getRuleScanner() { + return ruleScanner; + } + + /** + * Sets the rule scanner. + * + * @param ruleScanner the new rule scanner + */ + public void setRuleScanner(BufferedRuleBasedScanner ruleScanner) { + this.ruleScanner = ruleScanner; + } + + /** + * Handle. + * + * @param curBlock the cur block + * @param lretList the lret list + * @param token the token + * @param ruleManager the rule manager + * @param ruleHandlarByToken the rule handlar by token + * @return the rule bean + */ + public RuleBean handle(ScriptBlockInfo curBlock, List lretList, IToken token, + ISQLTokenData ruleManager, AbstractRuleHandler ruleHandlarByToken) { + RuleBean lRuleBean = new RuleBean(); + lRuleBean.setScriptBlockInfo(curBlock); + + // for partial blocks. if block started partially then here we need to + // handle. + // create stmt from the first word we don't know what is the exact stmt. + // we will parse till we find the exact stmt and then move on to the + // isBlockEnd + + handlePartialStmt(curBlock); + + if (token instanceof SQLToken) { + SQLToken lSQLToken = (SQLToken) token; + if (isBlockEnd(curBlock, lSQLToken)) { + if (curBlock.getNextOptTokenToEnd() == SQLTokenConstants.T_SQL_UNKNOWN) { + endScriptStrategy(curBlock, lretList, lSQLToken, ruleManager, lRuleBean); + } + } else if (null != ruleHandlarByToken) { + // if this can have nested blocks. + handleNestedBlock(lretList, ruleManager, lRuleBean, ruleHandlarByToken, ruleManager.getTokenOffset()); + } else { + handleOtherEnd(curBlock, lSQLToken, lRuleBean, lretList, ruleManager); + } + } + return lRuleBean; + } + + /** + * Gets the SQL token. + * + * @param token the token + * @return the SQL token + */ + public SQLToken getSQLToken(IToken token) { + + if (token instanceof SQLToken) { + return (SQLToken) token; + } + + return null; + } + + /** + * End script strategy. + * + * @param curBlock the cur block + * @param lretList the lret list + * @param token the token + * @param ruleManager the rule manager + * @param lRuleBean the l rule bean + */ + public void endScriptStrategy(ScriptBlockInfo curBlock, List lretList, SQLToken token, + ISQLTokenData ruleManager, RuleBean lRuleBean) { + endScriptBlock(curBlock, lretList, ruleManager.getTokenOffset(), ruleManager.getTokenLength()); + + // need to check the parent applicability for closure. this is + // required for when select end with ; insert also should end. + + handleParentBlockEnd(curBlock, lretList, token, ruleManager, lRuleBean); + + // stop all the parent DML scripts in case of ; end + } + + /** + * End optional script. + * + * @param curBlock the cur block + * @param lretList the lret list + * @param token the token + * @param ruleManager the rule manager + * @return the rule bean + */ + public RuleBean endOptionalScript(ScriptBlockInfo curBlock, List lretList, SQLToken token, + ISQLTokenData ruleManager) { + RuleBean lRuleBean = new RuleBean(); + lRuleBean.setScriptBlockInfo(curBlock); + + endScriptStrategy(curBlock, lretList, token, ruleManager, lRuleBean); + return lRuleBean; + + } + + /** + * Handle parent block end. + * + * @param curBlock the cur block + * @param lretList the lret list + * @param token the token + * @param ruleManager the rule manager + * @param lRuleBean the l rule bean + */ + public void handleParentBlockEnd(ScriptBlockInfo curBlock, List lretList, SQLToken token, + ISQLTokenData ruleManager, RuleBean lRuleBean) { + lRuleBean.setScriptBlockInfo(curBlock.getParent()); + } + + /** + * Creates the script block. + * + * @param parent the parent + * @param token the token + * @param tokenOffset the token offset + * @return the script block info + */ + public ScriptBlockInfo createScriptBlock(ScriptBlockInfo parent, ISQLTokenData token, int tokenOffset) { + ScriptBlockInfo scriptBlock = getScriptBlock(parent, token); + scriptBlock.setStartOffSetForBlock(tokenOffset); + return scriptBlock; + } + + /** + * Creates the script block. + * + * @param parent the parent + * @param token the token + * @param tokenOffset the token offset + * @param removeTokenFromParent the remove token from parent + * @return the script block info + */ + public ScriptBlockInfo createScriptBlock(ScriptBlockInfo parent, ISQLTokenData token, int tokenOffset, + boolean removeTokenFromParent) { + ScriptBlockInfo scriptBlock = createScriptBlock(parent, token, tokenOffset); + if (removeTokenFromParent) { + removeLastTokenAndAddToChild(parent, token, scriptBlock); + } + return scriptBlock; + } + + /** + * remove the last token and add to child. + * + * @param parent parent script block + * @param token current token data + * @param scriptBlock current script block + */ + public void removeLastTokenAndAddToChild(ScriptBlockInfo parent, ISQLTokenData token, ScriptBlockInfo scriptBlock) { + scriptBlock.addSQLTokenData(token); + if (!parent.getAllTokenList().isEmpty()) { + parent.getAllTokenList().remove(parent.getAllTokenList().size() - 1); + } + } + + /** + * remove the last token and add to parent. + * + * @param parent parent script block + * @param token current token data + * @param scriptBlock current script block + */ + public void removeLastTokenAndAddToParent(ScriptBlockInfo parent, ISQLTokenData token, + ScriptBlockInfo scriptBlock) { + parent.addSQLTokenData(token); + if (!parent.getAllTokenList().isEmpty()) { + scriptBlock.getAllTokenList().remove(scriptBlock.getAllTokenList().size() - 1); + } + } + + /** + * Gets the script block. + * + * @param parent the parent + * @param token the token + * @return the script block + */ + protected ScriptBlockInfo getScriptBlock(ScriptBlockInfo parent, ISQLTokenData token) { + return new ScriptBlockInfoImpl(parent, token.getToken(), this); + } + + /** + * Handle nested block. + * + * @param lretList the lret list + * @param token the token + * @param lRuleBean the l rule bean + * @param ruleHandlarByToken the rule handlar by token + * @param tokenOffset the token offset + */ + public void handleNestedBlock(List lretList, ISQLTokenData token, RuleBean lRuleBean, + AbstractRuleHandler ruleHandlarByToken, int tokenOffset) { + ScriptBlockInfo curBlock = lRuleBean.getScriptBlockInfo(); + if (isIgnore(ruleHandlarByToken, curBlock, (SQLToken) token.getToken())) { + // if nested then find end or child + return; + } else if (isNested(curBlock, token.getToken())) { + // if nested then find end or child + ruleHandlarByToken.handleNestedBlockScriptCreate(curBlock, token, lRuleBean, tokenOffset); + handlePartialStmt(lRuleBean.getScriptBlockInfo()); + } else { + handleBlockEnd(lretList, token, lRuleBean, ruleHandlarByToken, tokenOffset); + } + } + + /** + * Checks if is ignore. + * + * @param ruleHandlarByToken the rule handlar by token + * @param curBlock the cur block + * @param token the token + * @return true, if is ignore + */ + public boolean isIgnore(AbstractRuleHandler ruleHandlarByToken, ScriptBlockInfo curBlock, SQLToken token) { + return isIgnoreByCurrentBlock(ruleHandlarByToken, curBlock, token) + || ruleHandlarByToken.isIgnoreByNextToken(this, curBlock, token); + } + + /** + * Checks if is ignore by current block. + * + * @param ruleHandlarByToken the rule handlar by token + * @param curBlock the cur block + * @param token the token + * @return true, if is ignore by current block + */ + public boolean isIgnoreByCurrentBlock(AbstractRuleHandler ruleHandlarByToken, ScriptBlockInfo curBlock, + SQLToken token) { + return false; + } + + /** + * Checks if is ignore by next token. + * + * @param ruleHandlarByToken the rule handlar by token + * @param curBlock the cur block + * @param token the token + * @return true, if is ignore by next token + */ + public boolean isIgnoreByNextToken(AbstractRuleHandler ruleHandlarByToken, ScriptBlockInfo curBlock, + SQLToken token) { + return false; + } + + /** + * Handle nested block script create. + * + * @param curBlock the cur block + * @param token the token + * @param lRuleBean the l rule bean + * @param tokenOffset the token offset + */ + public void handleNestedBlockScriptCreate(ScriptBlockInfo curBlock, ISQLTokenData token, RuleBean lRuleBean, + int tokenOffset) { + ScriptBlockInfo createScriptBlock = createScriptBlock(curBlock, token, tokenOffset, true); + lRuleBean.setScriptBlockInfo(createScriptBlock); + } + + /** + * Handle other end. + * + * @param curBlock the cur block + * @param token the token + * @param lRuleBean the l rule bean + * @param lretList the lret list + * @param ruleManager the rule manager + */ + public void handleOtherEnd(ScriptBlockInfo curBlock, SQLToken token, RuleBean lRuleBean, + List lretList, ISQLTokenData ruleManager) { + } + + /** + * Handle partial stmt. + * + * @param curBlock the cur block + */ + public void handlePartialStmt(ScriptBlockInfo curBlock) { + + } + + /** + * Checks if is block end by other block. + * + * @return true, if is block end by other block + */ + public boolean isBlockEndByOtherBlock() { + + return false; + } + + /** + * Handle block end. + * + * @param lretList the lret list + * @param sqlTokenData the sql token data + * @param lRuleBean the l rule bean + * @param ruleHandlarByToken the rule handlar by token + * @param tokenOffset the token offset + */ + public void handleBlockEnd(List lretList, ISQLTokenData sqlTokenData, RuleBean lRuleBean, + AbstractRuleHandler ruleHandlarByToken, int tokenOffset) { + ScriptBlockInfo curBlock = lRuleBean.getScriptBlockInfo(); + + // check if the new block is in the new line, if new line then can end + // the block + + if (!isBlockEndByOtherBlock() && !isEndBlockByThisToken(sqlTokenData.getToken(), curBlock)) { + if (curBlock.getRecentNewLineCount() < 3) { + return; + } + } + + if (!curBlock.getAllTokenList().isEmpty()) { + curBlock.getAllTokenList().remove(curBlock.getAllTokenList().size() - 1); + } + int lastTokenOffSet = getLastTokenOffSet(curBlock); + int lastTokenLength = getLastTokenlenght(curBlock); + + while (null != curBlock) { + // if not nested then end and start new block + + curBlock.getAbstractRuleHandler().endScriptBlock(curBlock, lretList, lastTokenOffSet, lastTokenLength); + + // check how many parents blocks need to end the script + + if (!curBlock.getAbstractRuleHandler().isStopParentScriptBlock(curBlock, sqlTokenData.getToken())) { + curBlock = curBlock.getParent(); + break; + } + curBlock = curBlock.getParent(); + } + + // new script token need to identify that the old script + // block is the end of it is the child of current script + // block. + + lRuleBean.setScriptBlockInfo(curBlock); + + // create a script block here and + ScriptBlockInfo createScriptBlock = ruleHandlarByToken.createScriptBlock(curBlock, sqlTokenData, tokenOffset); + createScriptBlock.addSQLTokenData(sqlTokenData); + // remove the sql token data from curBlock + lRuleBean.setScriptBlockInfo(createScriptBlock); + + } + + /** + * Adds the child stmt data parent. + * + * @param curBlock the cur block + * @return the script block info + */ + public ScriptBlockInfo addChildStmtDataParent(ScriptBlockInfo curBlock) { + + addSubTokenBeanData(curBlock); + + return curBlock; + } + + /** + * Gets the last tokenlenght. + * + * @param curBlock the cur block + * @return the last tokenlenght + */ + protected int getLastTokenlenght(ScriptBlockInfo curBlock) { + return curBlock.getLastTokenlenght(); + } + + /** + * Gets the last token off set. + * + * @param curBlock the cur block + * @return the last token off set + */ + protected int getLastTokenOffSet(ScriptBlockInfo curBlock) { + return curBlock.getLastTokenOffSet(); + } + + /** + * Checks if is end block by this token. + * + * @param token the token + * @param curBlock the cur block + * @return true, if is end block by this token + */ + protected boolean isEndBlockByThisToken(IToken token, ScriptBlockInfo curBlock) { + return false; + } + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public abstract boolean isNested(ScriptBlockInfo curBlock, IToken token); + + /** + * Checks if is stop script block. + * + * @param curBlock the cur block + * @param ruleHandlarByToken the rule handlar by token + * @return true, if is stop script block + */ + public abstract boolean isStopScriptBlock(ScriptBlockInfo curBlock, AbstractRuleHandler ruleHandlarByToken); + + /** + * End script block. + * + * @param curBlock the cur block + * @param lretList the lret list + * @param tokenOffset the token offset + * @param tokenLength the token length + */ + public void endScriptBlock(ScriptBlockInfo curBlock, List lretList, int tokenOffset, + int tokenLength) { + if (curBlock.isNested()) { + curBlock.setLenght((tokenOffset + tokenLength) - curBlock.getStartOffSetForBlock()); + + lretList.add(new SQLQueryPosition(curBlock.getStartOffSetForBlock(), curBlock.getLenght())); + + if (null != curBlock.getParent()) { + addSubTokenBeanData(curBlock); + } else { + addSQLStmtTokenList(curBlock); + } + } + } + + private void addSubTokenBeanData(ScriptBlockInfo curBlock) { + SQLStmtTokenListBean stmtTokenListBean = new SQLStmtTokenListBean(); + stmtTokenListBean.setStatementType(curBlock.getTokenType()); + + if (curBlock instanceof DMLParamScriptBlockInfo) { + stmtTokenListBean.setDdlType(((DMLParamScriptBlockInfo) curBlock).getDdlType()); + } + + List allTokenList = curBlock.getAllTokenList(); + stmtTokenListBean.setSqlTokenData(allTokenList); + + ISQLTokenData fullTokenData = SQLTokenFactory.getTokenData(); + fullTokenData.setSubTokenBean(stmtTokenListBean); + curBlock = curBlock.getParent(); + curBlock.addSQLTokenData(fullTokenData); + } + + private void addSQLStmtTokenList(ScriptBlockInfo curBlock) { + if (null != getSqlStmtTokenManager()) { + getSqlStmtTokenManager().addSQLStmtTokenListBean(curBlock); + } + } + + /** + * Checks if is block end. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is block end + */ + public boolean isBlockEnd(ScriptBlockInfo curBlock, SQLToken token) { + return null != curBlock && token.getType() == getEndTokenType(curBlock); + } + + /** + * Gets the end token type. + * + * @param curBlock the cur block + * @return the end token type + */ + public abstract int getEndTokenType(ScriptBlockInfo curBlock); + + /** + * Checks if is stop parent script block. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is stop parent script block + */ + public boolean isStopParentScriptBlock(ScriptBlockInfo curBlock, IToken token) { + + return false; + } + + /** + * Checks if is rule handler valid. + * + * @param currentRuleHandler the current rule handler + * @param curBlock the cur block + * @return true, if is rule handler valid + */ + public boolean isRuleHandlerValid(RuleHandlerIf currentRuleHandler, ScriptBlockInfo curBlock, SQLToken token) { + return true; + } + + /** + * Clone. + * + * @return the object + */ + @Override + public Object clone() { + try { + return this.getClass().newInstance(); + } catch (InstantiationException | IllegalAccessException e) { + + return null; + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/BaseCreatehandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/BaseCreatehandler.java new file mode 100644 index 0000000000000000000000000000000000000000..865fba0ce3b0d79b10f94b9bccaacc7ae845803a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/BaseCreatehandler.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.bean.DMLParamScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.handlerif.RuleHandlerIf; + +/** + * Title: BaseCreatehandler + * + * @since 3.0.0 + */ +public abstract class BaseCreatehandler extends AbstractRuleHandler implements IPartialStmt { + /** + * AbstractCreateStmt to maintain current Create stmt + */ + protected AbstractCreateStmt abstractCreateStmt = new AbstractCreateStmt(); + + public BaseCreatehandler() { + } + + /** + * create and returns specific create stmt + * + * @param curScriptBlock current DML script Object + * @return the abstract stmt + */ + protected AbstractCreateStmt getCreateStmt(DMLParamScriptBlockInfo curScriptBlock) { + return RuleHandlerConfig.getInstance().getCreateStmt(curScriptBlock, abstractCreateStmt); + } + + /** + * returns DML Script Block + * + * @param curBlock the cur block + * @return DML Script Block + */ + protected DMLParamScriptBlockInfo getDMLParamScriptBlock(ScriptBlockInfo curBlock) { + if (curBlock instanceof DMLParamScriptBlockInfo) { + return (DMLParamScriptBlockInfo) curBlock; + } + return null; + } + + /** + * Checks if is rule handler valid. + * + * @param currentRuleHandler the current rule handler + * @param curBlock the cur block + * @return true, if is rule handler valid + */ + public boolean isRuleHandlerValid(RuleHandlerIf currentRuleHandler, ScriptBlockInfo curBlock, SQLToken lToken) { + DMLParamScriptBlockInfo dmlParamScriptBlock = getDMLParamScriptBlock(curBlock); + return getCreateStmt(dmlParamScriptBlock).isRuleHandlerValid(currentRuleHandler, curBlock, lToken); + } + + /** + * Checks if is rule handler valid. + * + * @param currentRuleHandler the current rule handler + * @param curBlock the cur block + * @return true, if is rule handler valid + */ + public boolean isPackageStmt(RuleHandlerIf currentRuleHandler, ScriptBlockInfo curBlock, SQLToken lToken) { + DMLParamScriptBlockInfo dmlParamScriptBlock = getDMLParamScriptBlock(curBlock); + return getCreateStmt(dmlParamScriptBlock) instanceof PackageCreateStmt; + } + + /** + * Gets the abstract create stmt. + * + * @param curBlock the cur block + * @return the abstract create stmt + */ + public AbstractCreateStmt getAbstractCreateStmt(ScriptBlockInfo curBlock) { + DMLParamScriptBlockInfo dmlParamScriptBlock = getDMLParamScriptBlock(curBlock); + return RuleHandlerConfig.getInstance().getCreateStmt(dmlParamScriptBlock, abstractCreateStmt); + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/DeleteDMLRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/DeleteDMLRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..1be2c0a11a47f07aa3a1262180e3eeb52073ed65 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/DeleteDMLRuleHandler.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; + +/** + * + * Title: DeleteDMLRuleHandler + * + * @since 3.0.0 + */ +public class DeleteDMLRuleHandler extends AbstractDMLRuleHandler { + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(ScriptBlockInfo curBlock, IToken token) { + + String lastKnownToken = curBlock.getLastKnownToken(); + + if (curBlock.isNested() && (isSelectStmtNested(token, lastKnownToken) || isCaseStmtNested(token))) { + return true; + } + + return false; + } + + private boolean isSelectStmtNested(IToken token, String lastKnownToken) { + return getSQLToken(token).getType() == SQLTokenConstants.T_SQL_DML_SELECT + && SQLFoldingConstants.SQL_BRACKET_START.equalsIgnoreCase(lastKnownToken); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/DropBlockRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/DropBlockRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..e367690e4fe970346732ed7e57c8bc8b54c8fde6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/DropBlockRuleHandler.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; + +/** + * + * Title: SQLBlockRuleHandler + * + * @since 3.0.0 + */ +public class DropBlockRuleHandler extends AbstractRuleHandler { + + /** + * Gets the end token type. + * + * @param currentBlock the current block + * @return the end token type + */ + @Override + public int getEndTokenType(ScriptBlockInfo currentBlock) { + + return SQLTokenConstants.T_SQL_DELIMITER; + } + + /** + * Checks if is stop script block. + * + * @param currentBlock the current block + * @param ruleHandlarByToken the rule handlar by token + * @return true, if is stop script block + */ + @Override + public boolean isStopScriptBlock(ScriptBlockInfo currentBlock, AbstractRuleHandler ruleHandlarByToken) { + return false; + } + + /** + * Checks if is nested. + * + * @param currentBlock the current block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(ScriptBlockInfo currentBlock, IToken token) { + return false; + } + + /** + * Checks if is ignore by current block. + * + * @param ruleHandlarByToken the rule handlar by token + * @param currentBlock the current block + * @param token the token + * @return true, if is ignore by current block + */ + public boolean isIgnoreByCurrentBlock(AbstractRuleHandler ruleHandlarByToken, ScriptBlockInfo currentBlock, + SQLToken token) { + return SQLTokenConstants.T_SQL_DDL_CONTROL_IF == token.getType(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/FuncAndProcCreateStmt.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/FuncAndProcCreateStmt.java new file mode 100644 index 0000000000000000000000000000000000000000..530f97881a0db658516b7ed28c3115063d92a8cb --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/FuncAndProcCreateStmt.java @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLDDLTypeEnum; +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.DMLParamScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; + +/** + * + * Title: FuncAndProcCreateStmt + * + * @since 3.0.0 + */ +public class FuncAndProcCreateStmt extends AbstractCreateStmt { + + /** + * Gets the end token type. + * + * @return the end token type + */ + public int getEndTokenType() { + return SQLTokenConstants.T_SQL_NONEXIST; + } + + /** + * Checks if is stop parent script block. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is stop parent script block + */ + @Override + public boolean isStopParentScriptBlock(DMLParamScriptBlockInfo curBlock, SQLToken token) { + + return false; + } + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + @Override + public boolean isNested(DMLParamScriptBlockInfo curBlock, SQLToken token) { + + if (curBlock.isEndStmtFound() || isLangStmtEnd(curBlock)) { + return false; + } + + return true; + } + + /** + * Checks if is ignore by current block. + * + * @param ruleHandlarByToken the rule handlar by token + * @param curBlock the cur block + * @param token the token + * @return true, if is ignore by current block + */ + public boolean isIgnoreByCurrentBlock(AbstractRuleHandler ruleHandlarByToken, ScriptBlockInfo curBlock, + SQLToken token) { + return false; + } + + /** + * Checks if is lang stmt end. + * + * @param curBlock the cur block + * @return true, if is lang stmt end + */ + public boolean isLangStmtEnd(DMLParamScriptBlockInfo curBlock) { + return curBlock.isLangKeywordFound() && !curBlock.isLangKeywordFoundBeforeStart(); + } + + /** + * Checks if is block end. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is block end + */ + @Override + public boolean isBlockEnd(DMLParamScriptBlockInfo curBlock, SQLToken token) { + + String lastToken = curBlock.getLastKnownToken(); + + ScriptBlockInfo parent = curBlock.getParent(); + + if (null != parent && parent instanceof DMLParamScriptBlockInfo) { + DMLParamScriptBlockInfo dmlScript = (DMLParamScriptBlockInfo) parent; + SQLDDLTypeEnum ddlType = dmlScript.getDdlType(); + if (isPackageType(parent, ddlType)) { + // stop if found ; + if (token.getType() == SQLTokenConstants.T_SQL_DELIMITER) { + return true; + } + } + } + + if (token.getType() == SQLTokenConstants.T_SQL_KEYWORK_AS + || token.getType() == SQLTokenConstants.T_SQL_KEYWORK_IS) { + curBlock.setPlBodyStart(true); + } + + if (null == curBlock.getStartKeywork()) { + if (isLastTokenIsorAs(lastToken) && token.getType() == SQLTokenConstants.T_SQL_FUNCTION_END) { + curBlock.setStartKeywork(curBlock.getCurrentKnownToken()); + return false; + } else if (isProcOrFuncStart(token)) { + curBlock.setInvokeParent(true); + curBlock.setStartKeywork(curBlock.getCurrentKnownToken()); + return false; + } + } + + handleFuncEndStatement(curBlock, token, lastToken); + + if (isLangStmtEnd(curBlock) && token.getType() == SQLTokenConstants.T_SQL_DELIMITER) { + return true; + } else if (curBlock.isEndStmtFound() && (token.getType() == SQLTokenConstants.T_SQL_DELIMITER + || token.getType() == SQLTokenConstants.T_SQL_DELIMITER_FSLASH)) { + return true; + } + + return false; + } + + private void handleFuncEndStatement(DMLParamScriptBlockInfo curBlock, SQLToken token, String lastToken) { + if (isFuncEndKeyword(token, lastToken)) { + curBlock.setEndStmtFound(true); + } else if (token.getType() == SQLTokenConstants.T_SQL_BLOCK_END) { + curBlock.setEndStmtFound(true); + } + + if (token.getType() == SQLTokenConstants.T_SQL_KEYWORK_LANGUAGE) { + curBlock.setLangKeywordFound(true); + + curBlock.setLangKeywordFoundBeforeStart(!curBlock.isPlBodyStart()); + } + } + + private boolean isFuncEndKeyword(SQLToken token, String lastToken) { + return token.getType() == SQLTokenConstants.T_SQL_FUNCTION_END + && !SQLFoldingConstants.SQL_KEYWORK_AS.equalsIgnoreCase(lastToken) + && !SQLFoldingConstants.SQL_KEYWORK_IS.equalsIgnoreCase(lastToken); + } + + private boolean isPackageType(ScriptBlockInfo parent, SQLDDLTypeEnum ddlType) { + return ddlType == SQLDDLTypeEnum.PACKAGE && !(parent.getLastKnownTokenList().contains("body") + || parent.getLastKnownTokenList().contains("BODY")); + } + + /** + * Checks if is proc or func start. + * + * @param token the token + * @return true, if is proc or func start + */ + public boolean isProcOrFuncStart(SQLToken token) { + return token.getType() == SQLTokenConstants.T_SQL_BLOCK_BEGIN + || token.getType() == SQLTokenConstants.T_SQL_BLOCK_DECLARE; + } + + /** + * Checks if is last token isor as. + * + * @param lastToken the last token + * @return true, if is last token isor as + */ + public boolean isLastTokenIsorAs(String lastToken) { + return SQLFoldingConstants.SQL_KEYWORK_AS.equalsIgnoreCase(lastToken) + || SQLFoldingConstants.SQL_KEYWORK_IS.equalsIgnoreCase(lastToken); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/FunctionCreateStmt.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/FunctionCreateStmt.java new file mode 100644 index 0000000000000000000000000000000000000000..c1d1d04743c84eba6c3cf0f5ced869d1fc61354c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/FunctionCreateStmt.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +/** + * + * Title: FunctionCreateStmt + * + * @since 3.0.0 + */ +public class FunctionCreateStmt extends FuncAndProcCreateStmt { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/GrantPermissionBlockRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/GrantPermissionBlockRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..78f1e08b5ec69117d54e70d96e2026f959cb0014 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/GrantPermissionBlockRuleHandler.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +/** + * + * Title: GrantPermissionBlockRuleHandler + * + * @since 3.0.0 + */ +public class GrantPermissionBlockRuleHandler extends PermissionBlockRuleHandler { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/IPartialStmt.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/IPartialStmt.java new file mode 100644 index 0000000000000000000000000000000000000000..6e70ad2d5b674315b7205b98f44564244b6bc042 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/IPartialStmt.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; + +/** + * + * Title: IPartialStmt + * + * @since 3.0.0 + */ +public interface IPartialStmt { + + /** + * Handle SQL stmt. + * + * @param curBlock the cur block + */ + void handleSQLStmt(ScriptBlockInfo curBlock); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/InsertDMLRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/InsertDMLRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..c6a7e5cabbd44f24631ccded61b83c78069edb4d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/InsertDMLRuleHandler.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; + +/** + * + * Title: InsertDMLRuleHandler + * + * @since 3.0.0 + */ +public class InsertDMLRuleHandler extends AbstractDMLRuleHandler { + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(ScriptBlockInfo curBlock, IToken token) { + + String lastKnownToken = curBlock.getLastKnownToken(); + if (curBlock.isNested() && getSQLToken(token).getType() == SQLTokenConstants.T_SQL_DML_SELECT) { + if ((curBlock.getLastKnownTokenList().contains(SQLFoldingConstants.SQL_KEYWORK_VALUES) + || curBlock.getLastKnownTokenList().contains(SQLFoldingConstants.SQL_KEYWORK_VALUES_UPPER))) { + if (SQLFoldingConstants.SQL_BRACKET_START.equalsIgnoreCase(lastKnownToken)) { + return true; + } + return false; + } + return true; + } else if (isCaseStmtNested(token)) { + return true; + } + + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/PackageCreateStmt.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/PackageCreateStmt.java new file mode 100644 index 0000000000000000000000000000000000000000..5bb3aef05998f18e0b6aae63075f0e1546b96156 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/PackageCreateStmt.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +/** + * Title: FunctionCreateStmt + * + * @since 3.0.0 + */ +public class PackageCreateStmt extends FuncAndProcCreateStmt { +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/PermissionBlockRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/PermissionBlockRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..900787277a9b356028aa00e753decac685e3d748 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/PermissionBlockRuleHandler.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; + +/** + * + * Title: SQLBlockRuleHandler + * + * @since 3.0.0 + */ +public class PermissionBlockRuleHandler extends AbstractRuleHandler { + + /** + * Gets the end token type. + * + * @param curBlock the cur block + * @return the end token type + */ + @Override + public int getEndTokenType(ScriptBlockInfo curBlock) { + + return SQLTokenConstants.T_SQL_DELIMITER; + } + + /** + * Checks if is stop script block. + * + * @param curBlock the cur block + * @param ruleHandlarByToken the rule handlar by token + * @return true, if is stop script block + */ + @Override + public boolean isStopScriptBlock(ScriptBlockInfo curBlock, AbstractRuleHandler ruleHandlarByToken) { + return false; + } + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(ScriptBlockInfo curBlock, IToken token) { + return false; + } + + /** + * Checks if is ignore by current block. + * + * @param ruleHandlarByToken the rule handlar by token + * @param curBlock the cur block + * @param token the token + * @return true, if is ignore by current block + */ + public boolean isIgnoreByCurrentBlock(AbstractRuleHandler ruleHandlarByToken, ScriptBlockInfo curBlock, + SQLToken token) { + return SQLTokenConstants.T_SQL_DDL_CONTROL_IF == token.getType() + || SQLTokenConstants.T_SQL_DDL_CREATE == token.getType() + || SQLTokenConstants.T_SQL_DML_SELECT == token.getType() + || SQLTokenConstants.T_SQL_DML_INSERT == token.getType() + || SQLTokenConstants.T_SQL_DML_UPDATE == token.getType() + || SQLTokenConstants.T_SQL_DML_DELETE == token.getType() + || SQLTokenConstants.T_SQL_DML_WITH == token.getType() + || SQLTokenConstants.T_SQL_DML_TRUNCATE == token.getType() + || SQLTokenConstants.T_SQL_DDL_ALTER == token.getType(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/ProcedureCreateStmt.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/ProcedureCreateStmt.java new file mode 100644 index 0000000000000000000000000000000000000000..6ecb050c2e71b4f46ff94ff33b38e22c72005437 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/ProcedureCreateStmt.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +/** + * Title: ProcedureCreateStmt + * + * @since 3.0.0 + */ +public class ProcedureCreateStmt extends FuncAndProcCreateStmt { +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/RevokePermissionBlockRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/RevokePermissionBlockRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..3d1beed6f7e69c41910c72f3d5fda548c0063167 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/RevokePermissionBlockRuleHandler.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +/** + * + * Title: RevokePermissionBlockRuleHandler + * + * @since 3.0.0 + */ +public class RevokePermissionBlockRuleHandler extends PermissionBlockRuleHandler { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/RuleHandlerConfig.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/RuleHandlerConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..8a9a4e2875aea0a9796c23de91c93a36e658896e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/RuleHandlerConfig.java @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import java.util.HashMap; +import java.util.Map; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLDDLTypeEnum; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.DMLParamScriptBlockInfo; + +/** + * Title: RuleHandlerConfig + * + * @since 3.0.0 + */ +public class RuleHandlerConfig { + private Map ruleLibrary = new HashMap(10); + + private Map> createStmtLibrary = new HashMap>(); + + private Map alterStmtLibrary = new HashMap(); + + private static RuleHandlerConfig ruleHandlerConfig = new RuleHandlerConfig(); + + /** + * Gets the single instance of RuleHandlerConfig. + * + * @return single instance of RuleHandlerConfig + */ + public static RuleHandlerConfig getInstance() { + + return ruleHandlerConfig; + } + + private RuleHandlerConfig() { + ruleLibrary.put(SQLTokenConstants.T_SQL_BLOCK_BEGIN, new SQLBlockRuleHandler()); + + ruleLibrary.put(SQLTokenConstants.T_SQL_DML_SELECT, new SelectDMLRuleHandler()); + ruleLibrary.put(SQLTokenConstants.T_SQL_DML_INSERT, new InsertDMLRuleHandler()); + ruleLibrary.put(SQLTokenConstants.T_SQL_DML_UPDATE, new UpdateDMLRuleHandler()); + ruleLibrary.put(SQLTokenConstants.T_SQL_DML_DELETE, new DeleteDMLRuleHandler()); + ruleLibrary.put(SQLTokenConstants.T_SQL_DML_TRUNCATE, new TruncateDMLRuleHandler()); + ruleLibrary.put(SQLTokenConstants.T_SQL_DML_WITH, new WithDMLRuleHandler()); + + ruleLibrary.put(SQLTokenConstants.T_SQL_DDL_CONTROL_IF, new SQLIFConditionRuleHandler()); + + ruleLibrary.put(SQLTokenConstants.T_SQL_DDL_CONTROL_ELSE, new SQLELSEConditionRuleHandler()); + + ruleLibrary.put(SQLTokenConstants.T_SQL_DDL_CONTROL_ELSIF, new SQLELSIFConditionRuleHandler()); + + ruleLibrary.put(SQLTokenConstants.T_SQL_DDL_CREATE, new AbstractCreateHandler()); + + ruleLibrary.put(SQLTokenConstants.T_SQL_BLOCK_DECLARE, new SQLBlockDeclareRuleHandler()); + + ruleLibrary.put(SQLTokenConstants.T_SQL_DDL_ALTER, new AbstractAlterHandler()); + + ruleLibrary.put(SQLTokenConstants.T_SQL_LOOP, new SQLLoopRuleHandler()); + + ruleLibrary.put(SQLTokenConstants.T_SQL_KEYWORK_CASE, new SQLCaseStmtRuleHandler()); + + ruleLibrary.put(SQLTokenConstants.T_SQL_DROP, new DropBlockRuleHandler()); + + ruleLibrary.put(SQLTokenConstants.T_SQL_GRANT, new GrantPermissionBlockRuleHandler()); + + ruleLibrary.put(SQLTokenConstants.T_SQL_REVOKE, new RevokePermissionBlockRuleHandler()); + + ruleLibrary.put(SQLTokenConstants.T_SQL_KEYWORD_FOR, new SQLForLoopRuleHandler()); + + ruleLibrary.put(SQLTokenConstants.T_SQL_KEYWORD_CURSOR, new SQLCursorRuleHandler()); + + ruleLibrary.put(SQLTokenConstants.T_SQL_KEYWORK_UNION, new SQLUnionRuleHandler()); + + ruleLibrary.put(SQLTokenConstants.T_SQL_MERGE, new SQLMergeRuleHandler()); + + ruleLibrary.put(SQLTokenConstants.T_SQL_DDL_CREATE_PROC, new AbstractCreateHandler()); + ruleLibrary.put(SQLTokenConstants.T_SQL_DDL_CREATE_FUNC, new AbstractCreateHandler()); + + createStmtLibrary.put(SQLDDLTypeEnum.PROCEDURE, new ProcedureCreateStmt()); + + createStmtLibrary.put(SQLDDLTypeEnum.FUNCTION, new FunctionCreateStmt()); + + createStmtLibrary.put(SQLDDLTypeEnum.PACKAGE, new PackageCreateStmt()); + + createStmtLibrary.put(SQLDDLTypeEnum.TABLE, new TableCreateStmt()); + + createStmtLibrary.put(SQLDDLTypeEnum.VIEW, new ViewCreateStmt()); + + createStmtLibrary.put(SQLDDLTypeEnum.TRIGGER, new TriggerCreateStmt()); + + alterStmtLibrary.put(SQLDDLTypeEnum.VIEW, new ViewAlterStmt()); + + } + + /** + * Gets the creates the stmt. + * + * @param curScriptBlock the cur script block + * @param abstractCreateStmt the abstract create stmt + * @return the creates the stmt + */ + public AbstractCreateStmt getCreateStmt(DMLParamScriptBlockInfo curScriptBlock, + AbstractCreateStmt abstractCreateStmt) { + + return createStmtLibrary.getOrDefault(curScriptBlock.getDdlType(), abstractCreateStmt); + + } + + /** + * Gets the alter stmt. + * + * @param curScriptBlock the cur script block + * @param abstractCreateStmt the abstract create stmt + * @return the alter stmt + */ + public AbstractAlterStmt getAlterStmt(DMLParamScriptBlockInfo curScriptBlock, + AbstractAlterStmt abstractCreateStmt) { + + return alterStmtLibrary.getOrDefault(curScriptBlock.getDdlType(), abstractCreateStmt); + + } + + /** + * Gets the rule handle. + * + * @param type the type + * @return the rule handle + */ + public AbstractRuleHandler getRuleHandle(int type) { + + return ruleLibrary.get(type); + + } + + /** + * Gets the rule handle. + * + * @param type the type + * @return the rule handle + */ + public AbstractRuleHandler getNewRuleHandle(int type) { + + AbstractRuleHandler ruleHandlarByToken = ruleLibrary.get(type); + if (null != ruleHandlarByToken) { + return (AbstractRuleHandler) ruleHandlarByToken.clone(); + } + return null; + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLBlockDeclareRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLBlockDeclareRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..25861d75818a5ca92808ce270289c3c4bd448d91 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLBlockDeclareRuleHandler.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; + +/** + * + * Title: SQLBlockDeclareRuleHandler + * + * @since 3.0.0 + */ +public class SQLBlockDeclareRuleHandler extends AbstractRuleHandler { + + /** + * Gets the end token type. + * + * @param curBlock the cur block + * @return the end token type + */ + @Override + public int getEndTokenType(ScriptBlockInfo curBlock) { + + return SQLTokenConstants.T_SQL_NONEXIST; + } + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(ScriptBlockInfo curBlock, IToken token) { + + if (getSQLToken(token) != null && getSQLToken(token).getType() == SQLTokenConstants.T_SQL_BLOCK_BEGIN) { + + return false; + + } + + return true; + } + + /** + * Checks if is stop script block. + * + * @param curBlock the cur block + * @param ruleHandlarByToken the rule handlar by token + * @return true, if is stop script block + */ + @Override + public boolean isStopScriptBlock(ScriptBlockInfo curBlock, AbstractRuleHandler ruleHandlarByToken) { + return false; + } + + /** + * Checks if is block end by other block. + * + * @return true, if is block end by other block + */ + public boolean isBlockEndByOtherBlock() { + + return true; + } + + /** + * Checks if is ignore by current block. + * + * @param ruleHandlarByToken the rule handlar by token + * @param curBlock the cur block + * @param token the token + * @return true, if is ignore by current block + */ + public boolean isIgnoreByCurrentBlock(AbstractRuleHandler ruleHandlarByToken, ScriptBlockInfo curBlock, + SQLToken token) { + + return token.getType() == SQLTokenConstants.T_SQL_DML_WITH; + } + + /** + * Gets the last tokenlenght. + * + * @param curBlock the cur block + * @return the last tokenlenght + */ + protected int getLastTokenlenght(ScriptBlockInfo curBlock) { + return (curBlock.getPreNewlineTokenOffSet() == 0 && curBlock.getPreNewlineTokenlenght() == 0) + ? curBlock.getAnyTokenlenght() + : curBlock.getPreNewlineTokenlenght(); + } + + /** + * Gets the last token off set. + * + * @param curBlock the cur block + * @return the last token off set + */ + protected int getLastTokenOffSet(ScriptBlockInfo curBlock) { + return (curBlock.getPreNewlineTokenOffSet() == 0 && curBlock.getPreNewlineTokenlenght() == 0) + ? curBlock.getAnyTokenOffSet() + : curBlock.getPreNewlineTokenOffSet(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLBlockRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLBlockRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..9aeca734fe0e3c3b00fc32acbce945b8b816b572 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLBlockRuleHandler.java @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import java.util.List; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.RuleBean; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.SQLScriptElement; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; + +/** + * Title: SQLBlockRuleHandler + * + * @since 3.0.0 + */ +public class SQLBlockRuleHandler extends AbstractRuleHandler { + + /** + * Gets the end token type. + * + * @param curBlock the cur block + * @return the end token type + */ + @Override + public int getEndTokenType(ScriptBlockInfo curBlock) { + + return SQLTokenConstants.T_SQL_NONEXIST; + } + + /** + * Checks if is block end. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is block end + */ + public boolean isBlockEnd(ScriptBlockInfo curBlock, SQLToken token) { + + if (isBlockEndWithOutOptionalToken(curBlock, token)) { + + if (null != curBlock.getParent() && curBlock.getParent().isInvokeParent()) { + return true; + } + + curBlock.setNextOptTokenToEnd(SQLTokenConstants.T_SQL_DELIMITER); + return true; + } + + return false; + } + + /** + * Checks if is block end with out optional token. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is block end with out optional token + */ + public boolean isBlockEndWithOutOptionalToken(ScriptBlockInfo curBlock, SQLToken token) { + + return null != curBlock && token.getType() == SQLTokenConstants.T_SQL_BLOCK_END; + } + + /** + * Checks if is stop script block. + * + * @param curBlock the cur block + * @param ruleHandlarByToken the rule handlar by token + * @return true, if is stop script block + */ + @Override + public boolean isStopScriptBlock(ScriptBlockInfo curBlock, AbstractRuleHandler ruleHandlarByToken) { + return false; + } + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(ScriptBlockInfo curBlock, IToken token) { + return true; + } + + /** + * handles the parent block end case, when this block is getting ended + */ + public void handleParentBlockEnd(ScriptBlockInfo curBlock, List lretList, SQLToken token, + ISQLTokenData ruleManager, RuleBean lRuleBean) { + ScriptBlockInfo parentBlock = curBlock.getParent(); + while (null != parentBlock) { + if (parentBlock.getAbstractRuleHandler() instanceof AbstractCreateHandler + && parentBlock.getAbstractRuleHandler().isBlockEnd(parentBlock, token)) { + parentBlock.getAbstractRuleHandler().endScriptBlock(parentBlock, lretList, ruleManager.getTokenOffset(), + ruleManager.getTokenLength()); + } else { + break; + } + parentBlock = parentBlock.getParent(); + } + lRuleBean.setScriptBlockInfo(parentBlock); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLCaseStmtRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLCaseStmtRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..630d29e61dc8a74729c2f286fce17c64118e8334 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLCaseStmtRuleHandler.java @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import java.util.List; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.RuleBean; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.SQLScriptElement; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; + +/** + * Title: SQLIFConditionRuleHandler + * + * @since 3.0.0 + */ +public class SQLCaseStmtRuleHandler extends AbstractRuleHandler { + + /** + * Gets the end token type. + * + * @param curBlock the cur block + * @return the end token type + */ + @Override + public int getEndTokenType(ScriptBlockInfo curBlock) { + + return SQLTokenConstants.T_SQL_NONEXIST; + } + + /** + * Checks if is block end. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is block end + */ + public boolean isBlockEnd(ScriptBlockInfo curBlock, SQLToken token) { + + if (isBlockEndWithOutOptionalToken(curBlock, token)) { + curBlock.setNextOptTokenToEnd(SQLTokenConstants.T_SQL_DELIMITER); + curBlock.setNextMiddleOptTokenToEnd(SQLTokenConstants.T_SQL_KEYWORK_CASE); + return true; + } + + return false; + } + + /** + * Checks if is block end with out optional token. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is block end with out optional token + */ + public boolean isBlockEndWithOutOptionalToken(ScriptBlockInfo curBlock, SQLToken token) { + return null != curBlock && token.getType() == SQLTokenConstants.T_SQL_BLOCK_END; + } + + /** + * Checks if is ignore by next token. + * + * @param ruleHandlarByToken the rule handlar by token + * @param curBlock the cur block + * @param token the token + * @return true, if is ignore by next token + */ + public boolean isIgnoreByNextToken(AbstractRuleHandler ruleHandlarByToken, ScriptBlockInfo curBlock, + SQLToken token) { + + if (ruleHandlarByToken instanceof AbstractDMLRuleHandler) { + return false; + } + + return false; + } + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + @Override + public boolean isNested(ScriptBlockInfo curBlock, IToken token) { + + if (curBlock.isNested() && null != getSQLToken(token) + && (getSQLToken(token).getType() == SQLTokenConstants.T_SQL_DML_SELECT)) { + return true; + } + + return false; + } + + /** + * Checks if is stop script block. + * + * @param curBlock the cur block + * @param ruleHandlarByToken the rule handlar by token + * @return true, if is stop script block + */ + @Override + public boolean isStopScriptBlock(ScriptBlockInfo curBlock, AbstractRuleHandler ruleHandlarByToken) { + return false; + } + + /** + * Handle block end. + * + * @param lretList the lret list + * @param token the token + * @param lRuleBean the l rule bean + * @param ruleHandlarByToken the rule handlar by token + * @param tokenOffset the token offset + */ + public void handleBlockEnd(List lretList, ISQLTokenData sqlTokenData, RuleBean lRuleBean, + AbstractRuleHandler ruleHandlarByToken, int tokenOffset) { + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLCursorRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLCursorRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..3b5597de89d8b90f61978ed28e3de3dedf59f2b3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLCursorRuleHandler.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; + +/** + * Title: SQLBlockRuleHandler + * + * @since 3.0.0 + */ +public class SQLCursorRuleHandler extends AbstractRuleHandler { + + /** + * Gets the end token type. + * + * @param curBlock the cur block + * @return the end token type + */ + @Override + public int getEndTokenType(ScriptBlockInfo curBlock) { + + return SQLTokenConstants.T_SQL_DELIMITER; + } + + /** + * Checks if is stop script block. + * + * @param curBlock the cur block + * @param ruleHandlarByToken the rule handlar by token + * @return true, if is stop script block + */ + @Override + public boolean isStopScriptBlock(ScriptBlockInfo curBlock, AbstractRuleHandler ruleHandlarByToken) { + return false; + } + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(ScriptBlockInfo curBlock, IToken token) { + return curBlock.isNested() && getSQLToken(token).getType() == SQLTokenConstants.T_SQL_DML_SELECT; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLELSEConditionRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLELSEConditionRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..317323c487c0197275186894bdb19f9a3db38509 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLELSEConditionRuleHandler.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +/** + * + * Title: SQLELSEConditionRuleHandler + * + * @since 3.0.0 + */ +public class SQLELSEConditionRuleHandler extends SQLIFConditionRuleHandler { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLELSIFConditionRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLELSIFConditionRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..11cc420b8b0456c5f78e5a5a239eda84f6a995da --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLELSIFConditionRuleHandler.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +/** + * + * Title: SQLELSIFConditionRuleHandler + * + * @since 3.0.0 + */ +public class SQLELSIFConditionRuleHandler extends SQLIFConditionRuleHandler { +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLForLoopRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLForLoopRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..e42c1434a7b9d77079cfda44dac588ad922703fe --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLForLoopRuleHandler.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; + +/** + * Title: SQLBlockRuleHandler + * + * @since 3.0.0 + */ +public class SQLForLoopRuleHandler extends AbstractRuleHandler { + + /** + * Gets the end token type. + * + * @param curBlock the cur block + * @return the end token type + */ + @Override + public int getEndTokenType(ScriptBlockInfo curBlock) { + + return SQLTokenConstants.T_SQL_DELIMITER; + } + + /** + * Checks if is stop script block. + * + * @param curBlock the cur block + * @param ruleHandlarByToken the rule handlar by token + * @return true, if is stop script block + */ + @Override + public boolean isStopScriptBlock(ScriptBlockInfo curBlock, AbstractRuleHandler ruleHandlarByToken) { + return false; + } + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(ScriptBlockInfo curBlock, IToken token) { + return curBlock.isNested() && (getSQLToken(token).getType() == SQLTokenConstants.T_SQL_DML_SELECT + || getSQLToken(token).getType() == SQLTokenConstants.T_SQL_LOOP); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLIFConditionRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLIFConditionRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..7652fd843069691c556794297c272b1377c7c5db --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLIFConditionRuleHandler.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; + +/** + * + * Title: SQLIFConditionRuleHandler + * + * @since 3.0.0 + */ +public class SQLIFConditionRuleHandler extends AbstractRuleHandler { + + /** + * Gets the end token type. + * + * @param currentBlock the current block + * @return the end token type + */ + @Override + public int getEndTokenType(ScriptBlockInfo currentBlock) { + + return SQLTokenConstants.T_SQL_NONEXIST; + } + + /** + * Checks if is stop script block. + * + * @param currentBlock the current block + * @param ruleHandlarByToken the rule handlar by token + * @return true, if is stop script block + */ + @Override + public boolean isStopScriptBlock(ScriptBlockInfo currentBlock, AbstractRuleHandler ruleHandlarByToken) { + return false; + } + + /** + * Checks if is block end. + * + * @param currentBlock the current block + * @param token the token + * @return true, if is block end + */ + public boolean isBlockEnd(ScriptBlockInfo currentBlock, SQLToken token) { + + if (isBlockEndWithOutOptionalToken(currentBlock, token)) { + currentBlock.setNextOptTokenToEnd(SQLTokenConstants.T_SQL_DELIMITER); + return true; + } + + return false; + } + + /** + * Checks if is block end with out optional token. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is block end with out optional token + */ + public boolean isBlockEndWithOutOptionalToken(ScriptBlockInfo curBlock, SQLToken token) { + return null != curBlock && token.getType() == SQLTokenConstants.T_SQL_DDL_CONTROL_IF + && SQLFoldingConstants.SQL_KEYWORK_END.equalsIgnoreCase(curBlock.getLastToken()); + } + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(ScriptBlockInfo curBlock, IToken token) { + + if (getSQLToken(token).getType() == SQLTokenConstants.T_SQL_DDL_CONTROL_ELSIF + || getSQLToken(token).getType() == SQLTokenConstants.T_SQL_DDL_CONTROL_ELSE) { + return false; + } + + return true; + } + + /** + * Checks if is block end by other block. + * + * @return true, if is block end by other block + */ + public boolean isBlockEndByOtherBlock() { + + return true; + } + + /** + * Gets the last tokenlenght. + * + * @param curBlock the cur block + * @return the last tokenlenght + */ + protected int getLastTokenlenght(ScriptBlockInfo curBlock) { + return (curBlock.getPreNewlineTokenOffSet() == 0 && curBlock.getPreNewlineTokenlenght() == 0) + ? curBlock.getAnyTokenlenght() + : curBlock.getPreNewlineTokenlenght(); + } + + /** + * Gets the last token off set. + * + * @param curBlock the cur block + * @return the last token off set + */ + protected int getLastTokenOffSet(ScriptBlockInfo curBlock) { + return (curBlock.getPreNewlineTokenOffSet() == 0 && curBlock.getPreNewlineTokenlenght() == 0) + ? curBlock.getAnyTokenOffSet() + : curBlock.getPreNewlineTokenOffSet(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLLoopRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLLoopRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..f2d3b0b2cab87d82068f8db74c72f85ddc22c487 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLLoopRuleHandler.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import java.util.List; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.RuleBean; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.SQLScriptElement; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; + +/** + * Title: SQLIFConditionRuleHandler + * + * @since 3.0.0 + */ +public class SQLLoopRuleHandler extends AbstractRuleHandler { + + /** + * Gets the end token type. + * + * @param curBlock the cur block + * @return the end token type + */ + @Override + public int getEndTokenType(ScriptBlockInfo curBlock) { + + return SQLTokenConstants.T_SQL_NONEXIST; + } + + /** + * Checks if is stop script block. + * + * @param curBlock the cur block + * @param ruleHandlarByToken the rule handlar by token + * @return true, if is stop script block + */ + @Override + public boolean isStopScriptBlock(ScriptBlockInfo curBlock, AbstractRuleHandler ruleHandlarByToken) { + return false; + } + + /** + * Checks if is block end. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is block end + */ + public boolean isBlockEnd(ScriptBlockInfo curBlock, SQLToken token) { + + if (isBlockEndWithOutOptionalToken(curBlock, token)) { + curBlock.setNextOptTokenToEnd(SQLTokenConstants.T_SQL_DELIMITER); + return true; + } + + return false; + } + + /** + * Checks if is block end with out optional token. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is block end with out optional token + */ + public boolean isBlockEndWithOutOptionalToken(ScriptBlockInfo curBlock, SQLToken token) { + return null != curBlock && token.getType() == SQLTokenConstants.T_SQL_LOOP + && SQLFoldingConstants.SQL_KEYWORK_END.equalsIgnoreCase(curBlock.getLastKnownToken()); + } + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(ScriptBlockInfo curBlock, IToken token) { + return true; + } + + /** + * Handle parent block end. + * + * @param curBlock the cur block + * @param lretList the lret list + * @param token the token + * @param ruleManager the rule manager + * @param lRuleBean the l rule bean + */ + public void handleParentBlockEnd(ScriptBlockInfo curBlock, List lretList, SQLToken token, + ISQLTokenData ruleManager, RuleBean lRuleBean) { + ScriptBlockInfo parentBlock = curBlock.getParent(); + + while (null != parentBlock) { + + if (parentBlock.getAbstractRuleHandler() instanceof SQLForLoopRuleHandler + && parentBlock.getAbstractRuleHandler().isBlockEnd(parentBlock, token)) { + parentBlock.getAbstractRuleHandler().endScriptBlock(parentBlock, lretList, ruleManager.getTokenOffset(), + ruleManager.getTokenLength()); + } else { + break; + } + + parentBlock = parentBlock.getParent(); + + } + + lRuleBean.setScriptBlockInfo(parentBlock); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLMergeRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLMergeRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..d49f229083fe789872851cd3fefe2c47b7f19b2b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLMergeRuleHandler.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; + +/** + * Title: SQLBlockRuleHandler + * + * @since 3.0.0 + */ +public class SQLMergeRuleHandler extends AbstractDMLRuleHandler { + /** + * Gets the end token type. + * + * @param curBlock the cur block + * @return the end token type + */ + @Override + public int getEndTokenType(ScriptBlockInfo curBlock) { + return SQLTokenConstants.T_SQL_DELIMITER; + } + + /** + * Checks if is stop script block. + * + * @param curBlock the cur block + * @param ruleHandlarByToken the rule handlar by token + * @return true, if is stop script block + */ + @Override + public boolean isStopScriptBlock(ScriptBlockInfo curBlock, AbstractRuleHandler ruleHandlarByToken) { + return false; + } + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(ScriptBlockInfo curBlock, IToken token) { + return curBlock.isNested() && (getSQLToken(token).getType() == SQLTokenConstants.T_SQL_DML_SELECT + || getSQLToken(token).getType() == SQLTokenConstants.T_SQL_DML_INSERT + || getSQLToken(token).getType() == SQLTokenConstants.T_SQL_DML_DELETE + || getSQLToken(token).getType() == SQLTokenConstants.T_SQL_DML_UPDATE); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLUnionRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLUnionRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..94e162aeb8f103c0007740a809a2b93848dfc277 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SQLUnionRuleHandler.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; + +/** + * Title: SQLBlockRuleHandler + * + * @since 3.0.0 + */ +public class SQLUnionRuleHandler extends AbstractRuleHandler { + + /** + * Gets the end token type. + * + * @param curBlock the cur block + * @return the end token type + */ + @Override + public int getEndTokenType(ScriptBlockInfo curBlock) { + + return SQLTokenConstants.T_SQL_UNKNOWN; + } + + /** + * Checks if is stop script block. + * + * @param curBlock the cur block + * @param ruleHandlarByToken the rule handlar by token + * @return true, if is stop script block + */ + @Override + public boolean isStopScriptBlock(ScriptBlockInfo curBlock, AbstractRuleHandler ruleHandlarByToken) { + return false; + } + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(ScriptBlockInfo curBlock, IToken token) { + return false; + } + + /** + * Checks if is block end by other block. + * + * @return true, if is block end by other block + */ + public boolean isBlockEndByOtherBlock() { + return true; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SelectDMLRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SelectDMLRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..4164385cfea514f7e091951394cf0e848b435caf --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/SelectDMLRuleHandler.java @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import java.util.List; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.DMLParamScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.RuleBean; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.SQLScriptElement; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.handlerif.RuleHandlerIf; + +/** + * Title: SelectDMLRuleHandler + * + * @since 3.0.0 + */ +public class SelectDMLRuleHandler extends AbstractDMLRuleHandler { + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(ScriptBlockInfo curBlock, IToken token) { + + String lastKnownToken = curBlock.getLastKnownToken(); + + if (curBlock.isNested() + && (isSelectStmtNested(token, lastKnownToken) || isCaseStmtNested(token) || isUnionStmtNested(token))) { + + return true; + } + + return false; + } + + /** + * Checks if is union stmt nested. + * + * @param token the token + * @return true, if is union stmt nested + */ + protected boolean isUnionStmtNested(IToken token) { + return null != getSQLToken(token) && getSQLToken(token).getType() == SQLTokenConstants.T_SQL_KEYWORK_UNION; + } + + private boolean isSelectStmtNested(IToken token, String lastKnownToken) { + return getSQLToken(token).getType() == SQLTokenConstants.T_SQL_DML_SELECT + && (SQLFoldingConstants.SQL_BRACKET_START.equalsIgnoreCase(lastKnownToken) + || SQLFoldingConstants.SQL_KEYWORD_UNION.equalsIgnoreCase(lastKnownToken) + || SQLFoldingConstants.SQL_KEYWORD_INTERSECT.equalsIgnoreCase(lastKnownToken) + || SQLFoldingConstants.SQL_KEYWORD_EXCEPT.equalsIgnoreCase(lastKnownToken) + || SQLFoldingConstants.SQL_KEYWORD_MINUS.equalsIgnoreCase(lastKnownToken)); + } + + /** + * Handle stmt custom end. + * + * @param curBlock the cur block + * @param token the token + * @param lRuleBean the l rule bean + * @param lretList the lret list + * @param ruleManager the rule manager + */ + protected void handleStmtCustomEnd(ScriptBlockInfo curBlock, SQLToken token, RuleBean lRuleBean, + List lretList, ISQLTokenData ruleManager) { + if (SQLFoldingConstants.SQL_KEYWORD_UNION.equalsIgnoreCase(curBlock.getCurrentKnownToken()) + || SQLFoldingConstants.SQL_KEYWORD_INTERSECT.equalsIgnoreCase(curBlock.getCurrentKnownToken()) + || SQLFoldingConstants.SQL_KEYWORD_EXCEPT.equalsIgnoreCase(curBlock.getCurrentKnownToken()) + || SQLFoldingConstants.SQL_KEYWORD_MINUS.equalsIgnoreCase(curBlock.getCurrentKnownToken()) + || isInMergeStmt(curBlock, token)) { + unreadAndEndScriptBlock(curBlock, lRuleBean, lretList, ruleManager); + } + } + + /** + * Checks if is rule handler valid. + * + * @param currentRuleHandler the current rule handler + * @param curBlock the cur block + * @return true, if is rule handler valid + */ + public boolean isRuleHandlerValid(RuleHandlerIf currentRuleHandler, ScriptBlockInfo curBlock, SQLToken token) { + + if (super.isRuleHandlerValid(currentRuleHandler, curBlock, token)) { + if (currentRuleHandler instanceof UpdateDMLRuleHandler && ("for".equalsIgnoreCase(curBlock.getLastToken()) + || "key".equalsIgnoreCase(curBlock.getLastToken()))) { + return false; + } + return true; + } else { + return false; + } + + } + + /** + * Checks if is stop parent script block. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is stop parent script block + */ + public boolean isStopParentScriptBlock(ScriptBlockInfo curBlock, IToken token) { + + if (curBlock.getAbstractRuleHandler() instanceof AbstractDMLRuleHandler && null != curBlock.getParent()) { + + if (curBlock.getParent().getAbstractRuleHandler() instanceof AbstractDMLRuleHandler) { + return true; + } + + else if (curBlock.getParent().getAbstractRuleHandler() instanceof AbstractCreateHandler) { + + AbstractCreateStmt abstractCreateStmt = ((AbstractCreateHandler) curBlock + .getParent().getAbstractRuleHandler()).getAbstractCreateStmt(curBlock.getParent()); + if (abstractCreateStmt instanceof TableCreateStmt || abstractCreateStmt instanceof ViewCreateStmt) { + return true; + } + } + + return false; + + } + + return false; + } + + /** + * Checks if is end block by this token. + * + * @param token the token + * @param curBlock the cur block + * @return true, if is end block by this token + */ + protected boolean isEndBlockByThisToken(IToken token, ScriptBlockInfo curBlock) { + + if ((null != curBlock.getParent() + && curBlock.getParent().getAbstractRuleHandler() instanceof SQLForLoopRuleHandler + && getSQLToken(token).getType() == SQLTokenConstants.T_SQL_LOOP) + || (getSQLToken(token).getType() == SQLTokenConstants.T_SQL_LOOP + && curBlock.getRecentNewLineCount() >= 1)) { + return true; + } + + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/TableCreateStmt.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/TableCreateStmt.java new file mode 100644 index 0000000000000000000000000000000000000000..01508edf794a03d7875c1d0d79ddedb43a114875 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/TableCreateStmt.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.DMLParamScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; + +/** + * + * Title: TableCreateStmt + * + * @since 3.0.0 + */ +public class TableCreateStmt extends AbstractCreateStmt { + + /** + * Gets the end token type. + * + * @return the end token type + */ + public int getEndTokenType() { + return SQLTokenConstants.T_SQL_DELIMITER; + } + + /** + * Checks if is stop parent script block. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is stop parent script block + */ + public boolean isStopParentScriptBlock(DMLParamScriptBlockInfo curBlock, SQLToken token) { + + return false; + } + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(DMLParamScriptBlockInfo curBlock, SQLToken token) { + if (token.getType() == SQLTokenConstants.T_SQL_DML_SELECT) { + return true; + } + + return false; + } + + /** + * Checks if is ignore by current block. + * + * @param ruleHandlarByToken the rule handlar by token + * @param curBlock the cur block + * @param token the token + * @return true, if is ignore by current block + */ + public boolean isIgnoreByCurrentBlock(AbstractRuleHandler ruleHandlarByToken, ScriptBlockInfo curBlock, + SQLToken token) { + return SQLTokenConstants.T_SQL_DDL_CONTROL_IF == token.getType() + || SQLTokenConstants.T_SQL_DML_WITH == token.getType() + || SQLTokenConstants.T_SQL_DML_DELETE == token.getType(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/TriggerCreateStmt.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/TriggerCreateStmt.java new file mode 100644 index 0000000000000000000000000000000000000000..880235e16fc94719ddfffd7c4069496befb3b637 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/TriggerCreateStmt.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.DMLParamScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; + +/** + * Title: TableCreateStmt + * + * @since 3.0.0 + */ +public class TriggerCreateStmt extends AbstractCreateStmt { + /** + * Gets the end token type. + * + * @return the end token type + */ + public int getEndTokenType() { + return SQLTokenConstants.T_SQL_DELIMITER; + } + + /** + * Checks if is stop parent script block. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is stop parent script block + */ + public boolean isStopParentScriptBlock(DMLParamScriptBlockInfo curBlock, SQLToken token) { + return false; + } + + /** + * Checks if is ignore by current block. + * + * @param ruleHandlarByToken the rule handlar by token + * @param curBlock the cur block + * @param token the token + * @return true, if is ignore by current block + */ + public boolean isIgnoreByCurrentBlock(AbstractRuleHandler ruleHandlarByToken, ScriptBlockInfo curBlock, + SQLToken token) { + return false; + } + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(DMLParamScriptBlockInfo curBlock, SQLToken token) { + if (token.getType() == SQLTokenConstants.T_SQL_BLOCK_BEGIN + || token.getType() == SQLTokenConstants.T_SQL_BLOCK_DECLARE) { + return true; + } + return false; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/TruncateDMLRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/TruncateDMLRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..6074418e204214894a95e584d6f9d2076bbf0ba9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/TruncateDMLRuleHandler.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; + +/** + * + * Title: TruncateDMLRuleHandler + * + * @since 3.0.0 + */ +public class TruncateDMLRuleHandler extends AbstractDMLRuleHandler { + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(ScriptBlockInfo curBlock, IToken token) { + return false; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/UpdateDMLRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/UpdateDMLRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..87e7f1880126dbe29c9bce88315b72cd30d76858 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/UpdateDMLRuleHandler.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; + +/** + * + * Title: UpdateDMLRuleHandler + * + * @since 3.0.0 + */ +public class UpdateDMLRuleHandler extends AbstractDMLRuleHandler { + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(ScriptBlockInfo curBlock, IToken token) { + + String lastKnownToken = curBlock.getLastKnownToken(); + + if (curBlock.isNested() && getSQLToken(token).getType() == SQLTokenConstants.T_SQL_DML_SELECT + && SQLFoldingConstants.SQL_BRACKET_START.equalsIgnoreCase(lastKnownToken)) { + + return true; + } else if (isCaseStmtNested(token)) { + return true; + } + + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/ViewAlterStmt.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/ViewAlterStmt.java new file mode 100644 index 0000000000000000000000000000000000000000..3c419f81c89489482002a6e1c9777dc5e6fc92e8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/ViewAlterStmt.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +/** + * + * Title: ProcedureCreateStmt + * + * @since 3.0.0 + */ +public class ViewAlterStmt extends AbstractAlterStmt { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/ViewCreateStmt.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/ViewCreateStmt.java new file mode 100644 index 0000000000000000000000000000000000000000..0aab76824dd949e844f30920c8643ea8403e9901 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/ViewCreateStmt.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.DMLParamScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; + +/** + * + * Title: TableCreateStmt + * + * @since 3.0.0 + */ +public class ViewCreateStmt extends AbstractCreateStmt { + + /** + * Gets the end token type. + * + * @return the end token type + */ + public int getEndTokenType() { + return SQLTokenConstants.T_SQL_DELIMITER; + } + + /** + * Checks if is stop parent script block. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is stop parent script block + */ + public boolean isStopParentScriptBlock(DMLParamScriptBlockInfo curBlock, SQLToken token) { + + return false; + } + + /** + * Checks if is ignore by current block. + * + * @param ruleHandlarByToken the rule handlar by token + * @param curBlock the cur block + * @param token the token + * @return true, if is ignore by current block + */ + public boolean isIgnoreByCurrentBlock(AbstractRuleHandler ruleHandlarByToken, ScriptBlockInfo curBlock, + SQLToken token) { + return SQLTokenConstants.T_SQL_DDL_CONTROL_IF == token.getType() + || SQLTokenConstants.T_SQL_DML_WITH == token.getType(); + } + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(DMLParamScriptBlockInfo curBlock, SQLToken token) { + if (token.getType() == SQLTokenConstants.T_SQL_DML_SELECT) { + return true; + } + + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/WithDMLRuleHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/WithDMLRuleHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..d654bcba449c54d10984dd3dffbdd120aae44e00 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handler/WithDMLRuleHandler.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handler; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLDMLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; + +/** + * Title: WithDMLRuleHandler + * + * @since 3.0.0 + */ +public class WithDMLRuleHandler extends AbstractDMLRuleHandler { + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + public boolean isNested(ScriptBlockInfo curBlock, IToken token) { + + String lastKnownToken = curBlock.getLastKnownToken(); + + if (token instanceof SQLDMLToken) { + if (curBlock.isNested() && (SQLFoldingConstants.SQL_BRACKET_START.equalsIgnoreCase(lastKnownToken) + || SQLFoldingConstants.SQL_KEYWORD_UNION.equalsIgnoreCase(lastKnownToken) + || SQLFoldingConstants.SQL_KEYWORD_INTERSECT.equalsIgnoreCase(lastKnownToken) + || SQLFoldingConstants.SQL_KEYWORD_EXCEPT.equalsIgnoreCase(lastKnownToken) + || SQLFoldingConstants.SQL_KEYWORD_MINUS.equalsIgnoreCase(lastKnownToken))) { + return true; + } else if (curBlock.getAllowDMLWithoutBracket() < 1) { + curBlock.incrAllowDMLWithoutBracket(); + return true; + } + + } + + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handlerif/RuleHandlerIf.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handlerif/RuleHandlerIf.java new file mode 100644 index 0000000000000000000000000000000000000000..cbbe63c06f3761b604ecf961e30d24ede2240a8a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/handlerif/RuleHandlerIf.java @@ -0,0 +1,228 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.handlerif; + +import java.util.List; + +import org.eclipse.jface.text.rules.IToken; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.RuleBean; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.SQLScriptElement; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.handler.AbstractRuleHandler; + +/** + * Title: RuleHandlerIf + * + * @since 3.0.0 + */ +public interface RuleHandlerIf { + + /** + * Handle. + * + * @param curBlock the cur block + * @param lretList the lret list + * @param token the token + * @param ruleManager the rule manager + * @param ruleHandlarByToken the rule handlar by token + * @return the rule bean + */ + RuleBean handle(ScriptBlockInfo curBlock, List lretList, IToken token, ISQLTokenData ruleManager, + AbstractRuleHandler ruleHandlarByToken); + + /** + * Creates the script block. + * + * @param parent the parent + * @param token the token + * @param tokenOffset the token offset + * @return the script block info + */ + ScriptBlockInfo createScriptBlock(ScriptBlockInfo parent, ISQLTokenData token, int tokenOffset); + + /** + * Handle nested block. + * + * @param lretList the lret list + * @param token the token + * @param lRuleBean the l rule bean + * @param ruleHandlarByToken the rule handlar by token + * @param tokenOffset the token offset + */ + void handleNestedBlock(List lretList, ISQLTokenData token, RuleBean lRuleBean, + AbstractRuleHandler ruleHandlarByToken, int tokenOffset); + + /** + * Handle nested block script create. + * + * @param curBlock the cur block + * @param token the token + * @param lRuleBean the l rule bean + * @param tokenOffset the token offset + */ + void handleNestedBlockScriptCreate(ScriptBlockInfo curBlock, ISQLTokenData token, RuleBean lRuleBean, + int tokenOffset); + + /** + * Handle other end. + * + * @param curBlock the cur block + * @param token the token + * @param lRuleBean the l rule bean + * @param lretList the lret list + * @param ruleManager the rule manager + */ + void handleOtherEnd(ScriptBlockInfo curBlock, SQLToken token, RuleBean lRuleBean, List lretList, + ISQLTokenData ruleManager); + + /** + * Handle partial stmt. + * + * @param curBlock the cur block + */ + void handlePartialStmt(ScriptBlockInfo curBlock); + + /** + * Handle block end. + * + * @param lretList the lret list + * @param token the token + * @param lRuleBean the l rule bean + * @param ruleHandlarByToken the rule handlar by token + * @param tokenOffset the token offset + */ + void handleBlockEnd(List lretList, ISQLTokenData token, RuleBean lRuleBean, + AbstractRuleHandler ruleHandlarByToken, int tokenOffset); + + /** + * Checks if is nested. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is nested + */ + boolean isNested(ScriptBlockInfo curBlock, IToken token); + + /** + * Checks if is stop script block. + * + * @param curBlock the cur block + * @param ruleHandlarByToken the rule handlar by token + * @return true, if is stop script block + */ + boolean isStopScriptBlock(ScriptBlockInfo curBlock, AbstractRuleHandler ruleHandlarByToken); + + /** + * End script block. + * + * @param curBlock the cur block + * @param lretList the lret list + * @param tokenOffset the token offset + * @param tokenLength the token length + */ + void endScriptBlock(ScriptBlockInfo curBlock, List lretList, int tokenOffset, int tokenLength); + + /** + * Checks if is block end. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is block end + */ + boolean isBlockEnd(ScriptBlockInfo curBlock, SQLToken token); + + /** + * Gets the end token type. + * + * @param curBlock the cur block + * @return the end token type + */ + int getEndTokenType(ScriptBlockInfo curBlock); + + /** + * Checks if is stop parent script block. + * + * @param curBlock the cur block + * @param token the token + * @return true, if is stop parent script block + */ + boolean isStopParentScriptBlock(ScriptBlockInfo curBlock, IToken token); + + /** + * the isRuleHandlerValid + * + * @param currentRuleHandler the currentRuleHandler + * @param curBlock the curBlock + * @param token the token + * @return true. if is valid rule handler + */ + boolean isRuleHandlerValid(RuleHandlerIf currentRuleHandler, ScriptBlockInfo curBlock, SQLToken token); + + /** + * End script strategy. + * + * @param curBlock the cur block + * @param lretList the lret list + * @param token the token + * @param ruleManager the rule manager + * @param lRuleBean the l rule bean + */ + void endScriptStrategy(ScriptBlockInfo curBlock, List lretList, SQLToken token, + ISQLTokenData ruleManager, RuleBean lRuleBean); + + /** + * End optional script. + * + * @param curBlock the cur block + * @param lretList the lret list + * @param token the token + * @param ruleManager the rule manager + * @return the rule bean + */ + RuleBean endOptionalScript(ScriptBlockInfo curBlock, List lretList, SQLToken token, + ISQLTokenData ruleManager); + + /** + * Checks if is block end by other block. + * + * @return true, if is block end by other block + */ + boolean isBlockEndByOtherBlock(); + + /** + * Checks if is ignore by current block. + * + * @param ruleHandlarByToken the rule handlar by token + * @param curBlock the cur block + * @param token the token + * @return true, if is ignore by current block + */ + boolean isIgnoreByCurrentBlock(AbstractRuleHandler ruleHandlarByToken, ScriptBlockInfo curBlock, SQLToken token); + + /** + * Checks if is ignore by next token. + * + * @param ruleHandlarByToken the rule handlar by token + * @param curBlock the cur block + * @param token the token + * @return true, if is ignore by next token + */ + boolean isIgnoreByNextToken(AbstractRuleHandler ruleHandlarByToken, ScriptBlockInfo curBlock, SQLToken token); + +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/AbstractASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/AbstractASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..a99318378c582ab1e60bb55179387dd25501e561 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/AbstractASTNodeParser.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser; + +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; + +/** + * Title: AbstractASTNodeParser + * + * @param the element type + * @since 3.0.0 + */ +public abstract class AbstractASTNodeParser { + + private Set keywordList = null; + + /** + * Prepare AST stmt object. + * + * @param listIterator the list iterator + * @return the e + */ + public abstract E prepareASTStmtObject(ListIterator listIterator); + + /** + * Gets the keyword list. + * + * @return the keyword list + */ + public Set getKeywordList() { + return keywordList; + } + + /** + * Sets the keyword list. + * + * @param keywordList the new keyword list + */ + public void setKeywordList(Set keywordList) { + this.keywordList = keywordList; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/AbstractStmtParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/AbstractStmtParser.java new file mode 100644 index 0000000000000000000000000000000000000000..a89d9901eff6bc75ee022217994c22cdd98f9ca3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/AbstractStmtParser.java @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser; + +import java.util.List; +import java.util.ListIterator; +import java.util.Map; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.SQLStmtTokenListBean; +import org.opengauss.mppdbide.gauss.sqlparser.exception.GaussDBSQLParserException; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TCustomASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: AbstractStmtParser + * + * @since 3.0.0 + */ +public abstract class AbstractStmtParser { + + /** + * Gets the AST parser. + * + * @param tokenStr the token str + * @param astParserMap the ast parser map + * @return the AST parser + */ + public AbstractASTNodeParser getASTParser(String tokenStr, Map> astParserMap) { + Class parseNodeClass = astParserMap.get(getTokenLowerCase(tokenStr)); + if (null == parseNodeClass) { + MPPDBIDELoggerUtility.error("No class associated with parser node" + tokenStr); + AbstractASTNodeParser lAbstractASTNodeParser = getDefaultNodeParser(); + return lAbstractASTNodeParser; + } + AbstractASTNodeParser processor = null; + try { + processor = (AbstractASTNodeParser) parseNodeClass.newInstance(); + processor.setKeywordList(astParserMap.keySet()); + } catch (InstantiationException | IllegalAccessException exception) { + MPPDBIDELoggerUtility.error("Exception occured while getting CustomNode processor"); + } + return processor; + } + + /** + * overload method to return the custom node parser + * + * @return CTEASTNodeParser CTE Node parser + */ + protected CTEASTNodeParser getDefaultNodeParser() { + return new CTEASTNodeParser(); + } + + private String getTokenLowerCase(String tokenStr) { + if (null == tokenStr) { + return null; + } + return tokenStr.toLowerCase(); + } + + /** + * Gets the custom sql statement. + * + * @return the custom sql statement + */ + public abstract TCustomSqlStatement getCustomSqlStatement(); + + /** + * Prepare stmt object. + * + * @param stmtTokenListBean the stmt token list bean + * @return the t custom sql statement + */ + public TCustomSqlStatement prepareStmtObject(SQLStmtTokenListBean stmtTokenListBean) { + + List allTokenList = stmtTokenListBean.getSqlTokenData(); + + ListIterator listIterator = allTokenList.listIterator(); + + TCustomSqlStatement tsqlStmt = getCustomSqlStatement(); + + // create the object from the + String tokenString = getTokenString(listIterator); + + AbstractASTNodeParser astParser = getASTParser(tokenString, getAstNodeParserMap()); + + TCustomASTNode prepareASTStmtObject = null; + TCustomASTNode preAstNode = null; + + while (null != astParser && listIterator.hasNext()) { + + prepareASTStmtObject = astParser.prepareASTStmtObject(listIterator); + + if (null == prepareASTStmtObject) { + break; + } + + if (null != preAstNode) { + preAstNode.setNextNode(prepareASTStmtObject); + } + + preAstNode = prepareASTStmtObject; + + tsqlStmt.addAstNode(tokenString, prepareASTStmtObject); + tokenString = getTokenString(listIterator); + + if (null != tokenString && null != tsqlStmt.getCustomAstNode(getTokenLowerCase(tokenString))) { + // multiple tokens found can't parse the statement. + throw new GaussDBSQLParserException( + "Multiple AST Tokens found in the same statement. Can't parse the statement"); + } + + astParser = getASTParser(tokenString, getAstNodeParserMap()); + + } + + return tsqlStmt; + } + + private String getTokenString(ListIterator listIterator) { + + if (listIterator.hasNext()) { + ISQLTokenData lSQLTokenData = listIterator.next(); + listIterator.previous(); + return lSQLTokenData.getTokenStr(); + } + return null; + } + + /** + * Gets the ast node parser map. + * + * @return the ast node parser map + */ + protected abstract Map> getAstNodeParserMap(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/CTEASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/CTEASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..1db127e0312a93e5e388203446f0efaf9015abb6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/CTEASTNodeParser.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser; + +import java.util.ListIterator; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.common.TCTEASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; + +/** + * + * Title: CTEASTNodeParser + * + * @since 3.0.0 + */ +public class CTEASTNodeParser extends AbstractASTNodeParser { + + /** + * Prepare AST stmt object. + * + * @param listIterator the list iterator + * @return the TCTEAST node + */ + @Override + public TCTEASTNode prepareASTStmtObject(ListIterator listIterator) { + + TCTEASTNode orderByAstNode = new TCTEASTNode(); + + TExpression stmtExpression = null; + + while (listIterator.hasNext()) { + + ISQLTokenData next = listIterator.next(); + + if (null == stmtExpression) { + stmtExpression = getTExpression(); + stmtExpression.setDirectExpression(true); + orderByAstNode.setStmtExpression(stmtExpression); + } + + if (null != next.getSubTokenBean()) { + TCustomSqlStatement customSqlStmt = ParserFactory.getCustomSqlStmt(next.getSubTokenBean()); + + ParserUtils.addCustomStmtToExpression(stmtExpression, customSqlStmt, listIterator); + } else { + ParserUtils.addExpressionNode(stmtExpression, listIterator, next); + // wrong sql format + } + + } + + orderByAstNode.setStmtExpression(stmtExpression); + + return orderByAstNode; + } + + /** + * Gets the t expression. + * + * @return the t expression + */ + protected TExpression getTExpression() { + return new TExpression(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/CustomASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/CustomASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..339b1df69a3797011c2935c562176fe20cc56e12 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/CustomASTNodeParser.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TCTEExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; + +/** + * + * Title: CustomASTNodeParser + * + * @since 3.0.0 + */ +public class CustomASTNodeParser extends CTEASTNodeParser { + + /** + * Gets the t expression. + * + * @return the t expression + */ + protected TExpression getTExpression() { + return new TCTEExpression(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ParserFactory.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ParserFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..b7110f33034ab045f7927d6da1910a49a28c0023 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ParserFactory.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLDDLTypeEnum; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.SQLStmtTokenListBean; +import org.opengauss.mppdbide.gauss.sqlparser.exception.GaussDBSQLParserException; +import org.opengauss.mppdbide.gauss.sqlparser.parser.handler.ParserHandlerConfig; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: ParserFactory + * + * @since 3.0.0 + */ +public abstract class ParserFactory { + + /** + * Gets the custom sql stmt. + * + * @param stmtTokenListBean the stmt token list bean + * @return the custom sql stmt + */ + public static TCustomSqlStatement getCustomSqlStmt(SQLStmtTokenListBean stmtTokenListBean) { + TCustomSqlStatement prepareStmtObject = null; + if (stmtTokenListBean.getStatementType() == SQLTokenConstants.T_SQL_DDL_CREATE) { + if (!(stmtTokenListBean.getDdlType() == SQLDDLTypeEnum.FUNCTION + || stmtTokenListBean.getDdlType() == SQLDDLTypeEnum.PROCEDURE + || stmtTokenListBean.getDdlType() == SQLDDLTypeEnum.PACKAGE)) { + return prepareStmtObject; + } + } + AbstractStmtParser ruleHandle = ParserHandlerConfig.getInstance() + .getRuleHandle(stmtTokenListBean.getStatementType()); + + if (null != ruleHandle) { + try { + prepareStmtObject = ruleHandle.prepareStmtObject(stmtTokenListBean); + } catch (GaussDBSQLParserException exception) { + MPPDBIDELoggerUtility.error("error while parsing the statement"); + } + } + return prepareStmtObject; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ParserUtils.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ParserUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..8d8027b644e35414f122a8133ab98834515a1b00 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ParserUtils.java @@ -0,0 +1,348 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.ListIterator; + +import org.apache.commons.lang.StringUtils; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.comm.ISQLSyntax; +import org.opengauss.mppdbide.gauss.sqlparser.exception.GaussDBSQLParserException; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpressionNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.fullstmt.TFullStmt; + +/** + * Title: ParserUtils + * + * @since 3.0.0 + */ +public abstract class ParserUtils { + + /** + * to add the comments to give ParsetreeNode + * + * @param listIterator token items list + * @param lSelect the node to which comments need to be added + */ + public static void addCommentsR(ListIterator listIterator, TParseTreeNode lSelect) { + + if (listIterator.hasNext()) { + ISQLTokenData next = listIterator.next(); + + if (null != next.getSubTokenBean()) { + listIterator.previous(); + return; + } + + if (isTokenEmpty(next)) { + listIterator.previous(); + readSpaces(listIterator, lSelect); + addCommentsR(listIterator, lSelect); + } else if (next.getToken().getData() == ISQLSyntax.SQL_MULTILINE_COMMENT + || next.getToken().getData() == ISQLSyntax.SQL_COMMENT) { + lSelect.addComment(next.getTokenStr().toString()); + addCommentsR(listIterator, lSelect); + } else { + listIterator.previous(); + } + } + } + + /** + * read the whitespace characters after the give node + * + * @param listIterator token items list + * @param lSelect the node to which comments need to be added + */ + public static void readSpaces(ListIterator listIterator, TParseTreeNode lSelect) { + + if (listIterator.hasNext()) { + ISQLTokenData next = listIterator.next(); + if (isTokenEmpty(next)) { + // need to decide while format, need to split these or not + // if contains line seperator then add one line seperator + if (next.getTokenStr().contains(System.lineSeparator()) || next.getTokenStr().contains("\n")) { + lSelect.addComment(System.lineSeparator()); + } + readSpaces(listIterator, lSelect); + } else { + listIterator.previous(); + } + } + } + + /** + * to check weather the token is empty or not + * + * @param next the token which need to be check for null string + * @return true when it is empty, false if not empty. false when it is null + */ + public static boolean isTokenEmpty(ISQLTokenData next) { + if (null == next.getTokenStr()) { + return false; + } + + return StringUtils.isEmpty(next.getTokenStr().trim()); + } + + /** + * where separation list + * + * @return where separation list + */ + public static List getWhereSeperateList() { + List seperaterList = new ArrayList(); + seperaterList.add("AND"); + seperaterList.add("OR"); + return seperaterList; + } + + /** + * read the list and return the token when it matches with the list of + * tokens provided + * + * @param listIterator token items list + * @param tokens token list to match + * @return the SqlNode when matches to the given tokens + */ + public static TSqlNode handleToken(ListIterator listIterator, List tokens) { + return handleToken(listIterator, tokens, true); + } + + /** + * read the list and return the token when it matches with the list of + * tokens provided + * + * @param listIterator token items list + * @param tokens token list to match + * @param readComments to read the comments or not. + * @return the SqlNode when matches to the given tokens + */ + public static TSqlNode handleToken(ListIterator listIterator, List tokens, + boolean readComments) { + ISQLTokenData sqlTokenData = getSQLTokenData(listIterator, tokens); + + return handleComments(listIterator, readComments, sqlTokenData); + } + + /** + * to read the commnets + * + * @param listIterator token items list + * @param readComments to read the comments or not. + * @param sqlTokenData sqlToken Data Object + * @return the SqlNode when matches to the given tokens + */ + private static TSqlNode handleComments(ListIterator listIterator, boolean readComments, + ISQLTokenData sqlTokenData) { + if (null != sqlTokenData) { + + TSqlNode sqlCalc = new TSqlNode(); + sqlCalc.setNodeText(sqlTokenData.getTokenStr()); + if (readComments) { + ParserUtils.addCommentsR(listIterator, sqlCalc); + } else { + ParserUtils.readSpaces(listIterator, sqlCalc); + } + return sqlCalc; + } + return null; + } + + /** + * this is similar to handleToken , but it not find the token will throw + * exception + * + * @param listIterator token items list + * @param token tokenstr to match + * @return the SqlNode when matches to the given token string + */ + public static TSqlNode handleTokenWithException(ListIterator listIterator, String token) { + + TSqlNode sqlNode = handleToken(listIterator, token, true); + + if (null == sqlNode) { + throw new IllegalStateException("Unable to position the statement"); + } + + return handleToken(listIterator, token, true); + } + + /** + * return the token when it matches with the token string + * + * @param listIterator listIterator token items list + * @param token tokenstr to match + * @return the SqlNode when matches to the given token string + */ + public static TSqlNode handleToken(ListIterator listIterator, String token) { + return handleToken(listIterator, token, true); + } + + /** + * return the token when it matches with the token string + * + * @param listIterator listIterator token items list + * @param token tokenstr to match + * @param readComments to read the comments or not. + * @return the SqlNode when matches to the given token string + */ + public static TSqlNode handleToken(ListIterator listIterator, String token, boolean readComments) { + ISQLTokenData sqlTokenData = getSQLTokenData(listIterator, token); + + return handleComments(listIterator, readComments, sqlTokenData); + } + + private static ISQLTokenData getSQLTokenData(ListIterator listIterator, List tokens) { + if (listIterator.hasNext()) { + ISQLTokenData lSQLTokenData = listIterator.next(); + if (null != lSQLTokenData.getTokenStr() && tokens.contains(lSQLTokenData.getTokenStr().toLowerCase())) { + return lSQLTokenData; + } else { + listIterator.previous(); + } + } + return null; + } + + private static ISQLTokenData getSQLTokenData(ListIterator listIterator, String token) { + if (listIterator.hasNext()) { + ISQLTokenData lSQLTokenData = listIterator.next(); + if (token.equalsIgnoreCase(lSQLTokenData.getTokenStr())) { + return lSQLTokenData; + } else { + listIterator.previous(); + } + } + return null; + } + + /** + * get the sqlnode from the give sqltoken data + * + * @param listIterator listIterator token items list + * @param next given SQL Token Data + * @return sqlnode for the given tokenData + */ + public static TSqlNode getSqlNode(ListIterator listIterator, ISQLTokenData next) { + TSqlNode seperator = new TSqlNode(); + seperator.setNodeText(next.getTokenStr()); + ParserUtils.addCommentsR(listIterator, seperator); + return seperator; + } + + /** + * add Custom Statement to Full Stmt + * + * @param expression full stmt expression + * @param customSqlStmt parseTreeNode to add + * @param listIterator listIterator token items list + */ + public static void addCustomStmtToFullStmt(TFullStmt expression, TParseTreeNode customSqlStmt, + ListIterator listIterator) { + if (null == customSqlStmt) { + throw new GaussDBSQLParserException("Can't add the null stmt to the FullStmt. Can't parse the statement"); + } + + expression.addStmtNode(customSqlStmt); + + } + + /** + * util to add custom stmt to expression + * + * @param expression normal expression to add + * @param customSqlStmt parseTreeNode to add + * @param listIterator listIterator token items list + */ + public static void addCustomStmtToExpression(TExpression expression, TParseTreeNode customSqlStmt, + ListIterator listIterator) { + TExpressionNode expNode = new TExpressionNode(); + expNode.setCustomStmt(customSqlStmt); + expression.addExpressionNode(expNode); + ParserUtils.addCommentsR(listIterator, customSqlStmt); + } + + /** + * add expression to Node. + * + * @param expression expression to add. + * @param listIterator listIterator token items list + * @param next sql token data + */ + public static void addExpressionNode(TExpression expression, ListIterator listIterator, + ISQLTokenData next) { + TExpressionNode expNode = new TExpressionNode(); + expNode.getExpNode().setNodeText(next.getTokenStr()); + ParserUtils.addCommentsR(listIterator, expNode.getExpNode()); + expression.addExpressionNode(expNode); + } + + /** + * to check the given token str is math operator + * + * @param tokenStr toke string to match + * @return true to math operator, false if not math operator + */ + public static boolean isMathOperator(String tokenStr) { + List asList = Arrays.asList("+", "-", ".", "*", "/", "$", "|"); + return asList.contains(tokenStr); + } + + /** + * return Common List for Func and Procedure common words + * + * @return Common List for Func and Procedure common words + */ + public static List getCommonKeywordListForFunProc() { + + List asList = Arrays.asList("immutable", "stable", "volatile", "shippable", "package", "fenced", + "leakproof", "called", "returns", "strict", "external", "security", "authid", "cost", "rows", "set", + "not"); + + return asList; + } + + /** + * return Common List for Func and Procedure common words + * + * @return Common List for Func and Procedure common words + */ + public static List getCommonNotKeywordListForFunProc() { + + List asList = Arrays.asList("SHIPPABLE", "FENCED", "LEAKPROOF"); + + return asList; + } + + /** + * checks if it is commons keyword or not + * + * @param str keyword to check + * @return true if common keyword, false if not common + */ + public static boolean isCommonKeyword(String str) { + return str != null && getCommonKeywordListForFunProc().contains(str); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ast/BasicASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ast/BasicASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..73bcdf4aab472fd2be09780b20cac662895201ba --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ast/BasicASTNodeParser.java @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.ast; + +import java.util.ListIterator; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeListParserConverter; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: BasicASTNodeParser + * + * @since 3.0.0 + */ +public abstract class BasicASTNodeParser extends AbstractASTNodeParser { + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + public abstract TBasicASTNode getASTNodeBean(); + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + public abstract String getKeywordTokenStr(); + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + public abstract AbstractNodeListParser getNodeListParser(); + + /** + * Prepare AST stmt object. + * + * @param listIterator the list iterator + * @return the t basic AST node + */ + public TBasicASTNode prepareASTStmtObject(ListIterator listIterator) { + TBasicASTNode fromAstNode = getASTNodeBean(); + + TSqlNode lFrom = getKeywordToken(listIterator); + if (lFrom == null) { + return null; + } + fromAstNode.setKeywordNode(lFrom); + + // + prepareASTOtherStmtObject(listIterator, fromAstNode); + + prepareASTListItem(listIterator, fromAstNode); + + prepareASTAfterListItem(listIterator, fromAstNode); + + return fromAstNode; + } + + /** + * Gets the keyword token. + * + * @param listIterator the list iterator + * @return the keyword token + */ + protected TSqlNode getKeywordToken(ListIterator listIterator) { + return ParserUtils.handleToken(listIterator, getKeywordTokenStr()); + } + + /** + * Prepare AST after list item. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTAfterListItem(ListIterator listIterator, TBasicASTNode fromAstNode) { + + } + + /** + * Prepare AST list item. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTListItem(ListIterator listIterator, TBasicASTNode fromAstNode) { + TParseTreeNodeList handleFromList = handleFromList(listIterator); + + if (null != handleFromList) { + fromAstNode.setItemList(handleFromList); + } + } + + /** + * Prepare AST other stmt object. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTOtherStmtObject(ListIterator listIterator, TBasicASTNode fromAstNode) { + + } + + /** + * Handle from list. + * + * @param listIterator the list iterator + * @return the t parse tree node list + */ + protected TParseTreeNodeList handleFromList(ListIterator listIterator) { + AbstractNodeListParser lFromItemListParser = getNodeListParser(); + + if (null == lFromItemListParser) { + return null; + } + NodeListParserConverter.handleSelectList(listIterator, lFromItemListParser); + TParseTreeNodeList itemList = lFromItemListParser.getItemList(); + return itemList; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ast/FromASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ast/FromASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..5eeb50614f81259c53c5ef77355516ee52d071f6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ast/FromASTNodeParser.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.ast; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.FromItemListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.common.TFromASTNode; + +/** + * + * Title: FromASTNodeParser + * + * @since 3.0.0 + */ +public class FromASTNodeParser extends BasicASTNodeParser { + + @Override + public TFromASTNode getASTNodeBean() { + return new TFromASTNode(); + } + + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_FROM; + } + + @Override + public AbstractNodeListParser getNodeListParser() { + return new FromItemListParser(getKeywordList()); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ast/ReturningASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ast/ReturningASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..d90c62a2b7dcb0cb447c0ba0c7705d4de34d07c7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ast/ReturningASTNodeParser.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.ast; + +import java.util.HashSet; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.SelectResultListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.common.TReturningASTNode; + +/** + * + * Title: ReturningASTNodeParser + * + * @since 3.0.0 + */ +public class ReturningASTNodeParser extends BasicASTNodeParser { + + @Override + public TBasicASTNode getASTNodeBean() { + return new TReturningASTNode(); + } + + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_RETURNING; + } + + @Override + public AbstractNodeListParser getNodeListParser() { + Set asList = new HashSet<>(); + return new SelectResultListParser(asList); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ast/WhereASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ast/WhereASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..3a1e8952abe3046c2cf89db947821fd153163cbd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ast/WhereASTNodeParser.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.ast; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.WhereCluaseListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.common.TWhereASTNode; + +/** + * Title: WhereASTNodeParser + * + * @since 3.0.0 + */ +public class WhereASTNodeParser extends BasicASTNodeParser { + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TWhereASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_WHERE; + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + return new WhereCluaseListParser(getKeywordList()); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/BeginStmtParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/BeginStmtParser.java new file mode 100644 index 0000000000000000000000000000000000000000..01a7c1079dcc05bc2ebf5c15434dd791ba503d96 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/BeginStmtParser.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.begin; + +import java.util.HashMap; +import java.util.Map; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.begin.ast.BeginASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.block.TBeginSqlStatement; + +/** + * Title: BeginStmtParser + * + * @since 3.0.0 + */ +public class BeginStmtParser extends AbstractStmtParser { + private static Map> astNodeParserMap = null; + + /** + * Instantiates a new begin stmt parser. + */ + public BeginStmtParser() { + if (null == astNodeParserMap) { + astNodeParserMap = new HashMap>(10); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORK_BEGIN, BeginASTNodeParser.class); + } + } + + /** + * Gets the custom sql statement. + * + * @return the custom sql statement + */ + @Override + public TCustomSqlStatement getCustomSqlStatement() { + return new TBeginSqlStatement(); + } + + /** + * Gets the ast node parser map. + * + * @return the ast node parser map + */ + @Override + protected Map> getAstNodeParserMap() { + return astNodeParserMap; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/DeclareStmtParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/DeclareStmtParser.java new file mode 100644 index 0000000000000000000000000000000000000000..b299deb61809f23d52060ddda9150cdbe3da8901 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/DeclareStmtParser.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.begin; + +import java.util.HashMap; +import java.util.Map; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.begin.ast.DeclareASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.block.TDeclareSqlStatement; + +/** + * Title: DeclareStmtParser + * + * @since 3.0.0 + */ +public class DeclareStmtParser extends AbstractStmtParser { + + private static Map> astNodeParserMap = null; + + /** + * Instantiates a new declare stmt parser. + */ + public DeclareStmtParser() { + if (null == astNodeParserMap) { + astNodeParserMap = new HashMap>(10); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORK_DECLARE, DeclareASTNodeParser.class); + } + } + + /** + * Gets the custom sql statement. + * + * @return the custom sql statement + */ + @Override + public TCustomSqlStatement getCustomSqlStatement() { + + return new TDeclareSqlStatement(); + } + + /** + * Gets the ast node parser map. + * + * @return the ast node parser map + */ + @Override + protected Map> getAstNodeParserMap() { + + return astNodeParserMap; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/ast/BeginASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/ast/BeginASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..be5a1ce7d91612b5311eebf5246797dec778ef85 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/ast/BeginASTNodeParser.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.begin.ast; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.begin.nodelist.WhenItemListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.FullStatementConverter; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeExpressionConverter; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeListParserConverter; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.begin.TBeginASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.fullstmt.TFullStmt; + +/** + * Title: BeginASTNodeParser + * + * @since 3.0.0 + */ +public class BeginASTNodeParser extends BasicASTNodeParser { + + /** + * Prepare AST stmt object. + * + * @param listIterator the list iterator + * @return the t begin AST node + */ + @Override + public TBeginASTNode prepareASTStmtObject(ListIterator listIterator) { + + TBeginASTNode beginAstNode = new TBeginASTNode(); + + TSqlNode lBegin = ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_KEYWORK_BEGIN); + beginAstNode.setKeywordNode(lBegin); + + Set newKeyList = new HashSet(); + newKeyList.add(SQLFoldingConstants.SQL_KEYWORK_END); + newKeyList.add(SQLFoldingConstants.SQL_KEYWORK_EXCEPTION); + + TFullStmt fullStmt = FullStatementConverter.parseAndGetFullStmt(listIterator, newKeyList); + beginAstNode.setFullStmt(fullStmt); + + TSqlNode exception = ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_KEYWORK_EXCEPTION); + beginAstNode.setException(exception); + + if (null != exception) { + // handle when list + + Set lineBreakSet = new HashSet(Arrays.asList(SQLFoldingConstants.SQL_KEYWORK_END)); + + WhenItemListParser lWhenItemListParser = new WhenItemListParser(lineBreakSet); + + NodeListParserConverter.handleSelectList(listIterator, lWhenItemListParser); + beginAstNode.setExceptionWhenList(lWhenItemListParser.getItemList()); + } + + TSqlNode lend = ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_KEYWORK_END); + beginAstNode.setEnd(lend); + + TExpression expression = NodeExpressionConverter.parseAndGetExpression(listIterator, getKeywordList()); + beginAstNode.setEndExpression(expression); + + return beginAstNode; + } + + /** + * Prepare AST other stmt object. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTOtherStmtObject(ListIterator listIterator, TBasicASTNode fromAstNode) { + + TBeginASTNode beginAstNode = (TBeginASTNode) fromAstNode; + + Set lineBreakSet = new HashSet(Arrays.asList(SQLFoldingConstants.SQL_KEYWORK_END)); + + beginAstNode.setFullStmt(FullStatementConverter.parseAndGetFullStmt(listIterator, lineBreakSet)); + + // code to parse all the statements + + beginAstNode.setEnd(ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_KEYWORK_END)); + + beginAstNode.setEndExpression(NodeExpressionConverter.parseAndGetExpression(listIterator, null)); + } + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TBeginASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORK_BEGIN; + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/ast/DeclareASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/ast/DeclareASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..3496f9d13874a6fb58f13a515a3af2790f68573a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/ast/DeclareASTNodeParser.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.begin.ast; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.begin.nodelist.DeclareItemListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.begin.TDeclareASTNode; + +/** + * Title: DeclareASTNodeParser + * + * @since 3.0.0 + */ +public class DeclareASTNodeParser extends BasicASTNodeParser { + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TDeclareASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORK_DECLARE; + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + Set asList = new HashSet<>(Arrays.asList(SQLFoldingConstants.SQL_KEYWORK_BEGIN)); + return new DeclareItemListParser(asList); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/nodelist/DeclareItemListParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/nodelist/DeclareItemListParser.java new file mode 100644 index 0000000000000000000000000000000000000000..2192918051ea862002cd67a9deb7742f698865bd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/nodelist/DeclareItemListParser.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.begin.nodelist; + +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.SQLStmtTokenListBean; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.SelectResultListParser; + +/** + * + * Title: DeclareItemListParser + * + * @since 3.0.0 + */ +public class DeclareItemListParser extends SelectResultListParser { + + /** + * Instantiates a new declare item list parser. + * + * @param lineBreakSet the line break set + */ + public DeclareItemListParser(Set lineBreakSet) { + super(lineBreakSet); + + } + + /** + * Checks if is node end. + * + * @param nodeStr the node str + * @return true, if is node end + */ + @Override + public boolean isNodeEnd(String nodeStr) { + return ";".equalsIgnoreCase(nodeStr); + } + + /** + * Checks if is alias name. + * + * @param nodeStr the node str + * @return true, if is alias name + */ + public boolean isAliasName(String nodeStr) { + return !isInEndNode() && ":=".equalsIgnoreCase(nodeStr); + } + + /** + * Sets the exp contain stmt. + */ + public void setExpContainStmt() { + super.setExpContainStmt(); + resultColumn = null; + expression = null; + endNodeExpression = null; + inEndNode = false; + // stop the + + } + + /** + * Checks if is list break with custom SQL. + * + * @param previousNotEmptyToken the previous not empty token + * @param sqlStmtTokenListBean the sql stmt token list bean + * @return true, if is list break with custom SQL + */ + @Override + public boolean isListBreakWithCustomSQL(String previousNotEmptyToken, SQLStmtTokenListBean sqlStmtTokenListBean) { + + int statementType = sqlStmtTokenListBean.getStatementType(); + + if (statementType == SQLTokenConstants.T_SQL_BLOCK_DECLARE + || statementType == SQLTokenConstants.T_SQL_BLOCK_BEGIN + || statementType == SQLTokenConstants.T_SQL_DDL_CREATE_FUNC + || statementType == SQLTokenConstants.T_SQL_DDL_CREATE_PROC) { + return true; + } + + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/nodelist/DeclareResultListParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/nodelist/DeclareResultListParser.java new file mode 100644 index 0000000000000000000000000000000000000000..2c4ba9cc21e794a42ca709753753e136ed35a20d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/nodelist/DeclareResultListParser.java @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.begin.nodelist; + +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpressionNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.listitem.create.TDeclareResultColumn; + +/** + * Title: DeclareResultListParser + * + * @since 3.0.0 + */ +public class DeclareResultListParser extends AbstractNodeListParser { + + /** + * Result Column. + */ + protected TDeclareResultColumn resultColumn = null; + private TExpression expression = null; + private TDeclareVariableList variableList = new TDeclareVariableList(); + + /** + * Instantiates a new declare result list parser. + * + * @param lineBreakSet the line break set + */ + public DeclareResultListParser(Set lineBreakSet) { + super(lineBreakSet); + } + + /** + * Creates the T object. + */ + @Override + public void createTObject() { + if (null == resultColumn) { + resultColumn = new TDeclareResultColumn(); + expression = new TExpression(); + resultColumn.setExpression(expression); + variableList.addResultColumn(resultColumn); + } + } + + /** + * Handle node alias. + * + * @param listIterator the list iterator + * @param next the next + */ + @Override + public void handleNodeAlias(ListIterator listIterator, ISQLTokenData next) { + } + + /** + * Handle node end. + * + * @param listIterator the list iterator + * @param next the next + */ + @Override + public void handleNodeEnd(ListIterator listIterator, ISQLTokenData next) { + TSqlNode seperator = new TSqlNode(); + seperator.setNodeText(next.getTokenStr()); + ParserUtils.addCommentsR(listIterator, seperator); + resultColumn.setSeperator(seperator); + + resultColumn = null; + expression = null; + } + + /** + * Creates the T node. + * + * @param listIterator the list iterator + * @param next the next + * @param paramCount the param count + */ + @Override + public void createTNode(ListIterator listIterator, ISQLTokenData next, int paramCount) { + TExpressionNode expNode = new TExpressionNode(); + expNode.getExpNode().setNodeText(next.getTokenStr()); + ParserUtils.addCommentsR(listIterator, expNode.getExpNode()); + if (null != expression) { + expression.addExpressionNode(expNode); + } + } + + /** + * Creates the T custom stmt node. + * + * @param customSqlStmt the custom sql stmt + * @param listIterator the list iterator + * @param next the next + */ + @Override + public void createTCustomStmtNode(TParseTreeNode customSqlStmt, ListIterator listIterator, + ISQLTokenData next) { + } + + /** + * Checks if is node end. + * + * @param nodeStr the node str + * @return true, if is node end + */ + @Override + public boolean isNodeEnd(String nodeStr) { + return ";".equalsIgnoreCase(nodeStr); + } + + /** + * Checks if is alias name. + * + * @param nodeStr the node str + * @param previousNotEmptyToken the previous not empty token + * @return true, if is alias name + */ + @Override + public boolean isAliasName(String nodeStr, String previousNotEmptyToken) { + return false; + } + + /** + * Handle start end node. + * + * @param previousNotEmptyToken the previous not empty token + * @param next the next + * @param listIterator the list iterator + */ + @Override + public void handleStartEndNode(String previousNotEmptyToken, ISQLTokenData next, + ListIterator listIterator) { + } + + /** + * Gets the item list. + * + * @return the item list + */ + @Override + public TParseTreeNodeList getItemList() { + return variableList; + } + + /** + * Gets the expression. + * + * @return the expression + */ + public TExpression getExpression() { + return expression; + } + + /** + * Sets the expression. + * + * @param expression the new expression + */ + public void setExpression(TExpression expression) { + this.expression = expression; + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/nodelist/TDeclareVariableList.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/nodelist/TDeclareVariableList.java new file mode 100644 index 0000000000000000000000000000000000000000..aff0fd0984555f1a97b537fe4f2448e132cf9970 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/nodelist/TDeclareVariableList.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.begin.nodelist; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.listitem.create.TDeclareResultColumn; + +/** + * Title: TDeclareVariableList + * + * @since 3.0.0 + */ +public class TDeclareVariableList extends TParseTreeNodeList { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/nodelist/WhenItemListParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/nodelist/WhenItemListParser.java new file mode 100644 index 0000000000000000000000000000000000000000..0f2616471be5da095ec1b5c966366a06e99e2c12 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/begin/nodelist/WhenItemListParser.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.begin.nodelist; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.FullStatementConverter; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeExpressionConverter; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.exceptionwhen.TWhenExprList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.exceptionwhen.TWhenStmtExpr; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.fullstmt.TFullStmt; + +/** + * Title: CaseItemListParser + * + * @since 3.0.0 + */ +public class WhenItemListParser extends AbstractNodeListParser { + private TWhenStmtExpr listItem = null; + + private TWhenExprList resultColumnList = new TWhenExprList(); + + public WhenItemListParser(Set lineBreakSet) { + super(lineBreakSet); + } + + /** + * handle the object creation for withitem + */ + public void createTObject() { + // create and then it is the start of the expression + } + + private void createLocalObject() { + // create and then it is the start of the expression + if (null == listItem) { + listItem = new TWhenStmtExpr(); + + resultColumnList.addResultColumn(listItem); + } + } + + /** + * method to call when the nodeAlias condition met + */ + public void handleNodeAlias(ListIterator listIterator, ISQLTokenData next) { + // close the TExpressionNode + TSqlNode thenNode = new TSqlNode(); + thenNode.setNodeText(next.getTokenStr()); + ParserUtils.addCommentsR(listIterator, thenNode); + listItem.setThen(thenNode); + + prepareEndNode(listIterator); + } + + private void prepareEndNode(ListIterator listIterator) { + Set lineBreakSet = new HashSet( + Arrays.asList(SQLFoldingConstants.SQL_KEYWORK_END, SQLFoldingConstants.SQL_KEYWORD_WHEN)); + + TFullStmt fullStmt = FullStatementConverter.parseAndGetFullStmt(listIterator, lineBreakSet); + + listItem.setFullStmt(fullStmt); + } + + /** + * method to call when the node end condition met + */ + public void handleNodeEnd(ListIterator listIterator, ISQLTokenData next) { + listItem = null; + + createLocalObject(); + + TSqlNode when = new TSqlNode(); + when.setNodeText(next.getTokenStr()); + ParserUtils.addCommentsR(listIterator, when); + listItem.setWhen(when); + + Set endTableName = new HashSet(Arrays.asList("then")); + + listItem.setExceptionType(NodeExpressionConverter.parseAndGetExpression(listIterator, endTableName)); + } + + /** + * result column list + */ + @Override + public TParseTreeNodeList getItemList() { + return resultColumnList; + } + + /** + * handle for running object node data + */ + public void createTNode(ListIterator listIterator, ISQLTokenData next, int paramCount) { + } + + /** + * returns true when the node end + */ + public boolean isNodeEnd(String nodeStr) { + return "WHEN".equalsIgnoreCase(nodeStr); + } + + /** + * returns true when it is alias node + */ + public boolean isAliasName(String nodeStr, String previousNotEmptyToken) { + return "THEN".equalsIgnoreCase(nodeStr); + } + + /** + * handle Custom Stmt Node Object + */ + @Override + public void createTCustomStmtNode(TParseTreeNode customSqlStmt, ListIterator listIterator, + ISQLTokenData next) { + } + + /** + * handle the node end case + */ + public void handleStartEndNode(String previousNotEmptyToken, ISQLTokenData next, + ListIterator listIterator) { + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/casestmt/CaseASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/casestmt/CaseASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..083bbcdf9e6c3db0e737386846ea45eae92b44cd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/casestmt/CaseASTNodeParser.java @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.casestmt; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.casestmt.nodelist.CaseItemListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeExpressionConverter; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.casestmt.TCaseASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: CaseASTNodeParser + * + * @since 3.0.0 + */ +public class CaseASTNodeParser extends BasicASTNodeParser { + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TCaseASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_CASE; + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + + Set lineBreakSet = new HashSet(Arrays.asList(SQLFoldingConstants.SQL_KEYWORK_END)); + + return new CaseItemListParser(lineBreakSet); + } + + /** + * Prepare AST other stmt object. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTOtherStmtObject(ListIterator listIterator, TBasicASTNode fromAstNode) { + + TCaseASTNode orderByAstNode = (TCaseASTNode) fromAstNode; + + Set lineBreakSet = new HashSet(Arrays.asList(SQLFoldingConstants.SQL_KEYWORD_WHEN)); + + TExpression startExpression = NodeExpressionConverter.parseAndGetExpression(listIterator, lineBreakSet); + + if (null != startExpression) { + orderByAstNode.setColExpression(startExpression); + } + + } + + /** + * Prepare AST after list item. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTAfterListItem(ListIterator listIterator, TBasicASTNode fromAstNode) { + + // prapare node for the + + TCaseASTNode orderByAstNode = (TCaseASTNode) fromAstNode; + + TSqlNode end = ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_KEYWORK_END); + if (end != null) { + orderByAstNode.setEndNode(end); + } + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/casestmt/CaseStmtParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/casestmt/CaseStmtParser.java new file mode 100644 index 0000000000000000000000000000000000000000..95a1578afc596e0ecc8d5952256628a6d3880722 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/casestmt/CaseStmtParser.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.casestmt; + +import java.util.HashMap; +import java.util.Map; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.condition.TCaseSqlStatement; + +/** + * + * Title: CaseStmtParser + * + * @since 3.0.0 + */ +public class CaseStmtParser extends AbstractStmtParser { + + private static Map> astNodeParserMap = null; + + public CaseStmtParser() { + if (null == astNodeParserMap) { + astNodeParserMap = new HashMap>(10); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_CASE, CaseASTNodeParser.class); + } + } + + @Override + public TCustomSqlStatement getCustomSqlStatement() { + return new TCaseSqlStatement(); + } + + @Override + protected Map> getAstNodeParserMap() { + return astNodeParserMap; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/casestmt/nodelist/CaseItemListParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/casestmt/nodelist/CaseItemListParser.java new file mode 100644 index 0000000000000000000000000000000000000000..f0c9189a8e7948f76154ac62b852bb12a00c95c7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/casestmt/nodelist/CaseItemListParser.java @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.casestmt.nodelist; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeExpressionConverter; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeListParserConverter; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.WhereCluaseListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TWhereClause; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.casenode.TCaseExprList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.casenode.TCaseStmtExpr; + +/** + * + * Title: CaseItemListParser + * + * @since 3.0.0 + */ +public class CaseItemListParser extends AbstractNodeListParser { + + /** + * The list item. + */ + protected TCaseStmtExpr listItem = null; + + /** + * The condition expr. + */ + protected TWhereClause conditionExpr = null; + + /** + * The end node. + */ + protected TExpression endNode = null; + + private TCaseExprList resultColumnList = new TCaseExprList(); + + /** + * Instantiates a new case item list parser. + * + * @param lineBreakSet the line break set + */ + public CaseItemListParser(Set lineBreakSet) { + super(lineBreakSet); + } + + /** + * Creates the T object. + */ + public void createTObject() { + // create and then it is the start of the expression + + } + + private void createLocalObject() { + // create and then it is the start of the expression + if (null == listItem) { + listItem = new TCaseStmtExpr(); + + resultColumnList.addResultColumn(listItem); + } + } + + /** + * Handle node alias. + * + * @param listIterator the list iterator + * @param next the next + */ + public void handleNodeAlias(ListIterator listIterator, ISQLTokenData next) { + // close the TExpressionNode + TSqlNode thenNode = new TSqlNode(); + thenNode.setNodeText(next.getTokenStr()); + ParserUtils.addCommentsR(listIterator, thenNode); + listItem.setThen(thenNode); + + prepareEndNode(listIterator); + + } + + private void prepareEndNode(ListIterator listIterator) { + Set lineBreakSet = new HashSet(Arrays.asList(SQLFoldingConstants.SQL_KEYWORK_END, + SQLFoldingConstants.SQL_KEYWORD_WHEN, SQLFoldingConstants.SQL_KEYWORD_ELSE)); + + TExpression parseAndGetExpression = NodeExpressionConverter.parseAndGetExpression(listIterator, lineBreakSet); + + listItem.setEndNode(parseAndGetExpression); + } + + /** + * Handle node end. + * + * @param listIterator the list iterator + * @param next the next + */ + public void handleNodeEnd(ListIterator listIterator, ISQLTokenData next) { + + listItem = null; + + createLocalObject(); + + TSqlNode whenOrElse = new TSqlNode(); + whenOrElse.setNodeText(next.getTokenStr()); + ParserUtils.addCommentsR(listIterator, whenOrElse); + listItem.setWhenOrElse(whenOrElse); + + if (SQLFoldingConstants.SQL_KEYWORD_ELSE.equalsIgnoreCase(next.getTokenStr())) { + prepareEndNode(listIterator); + } else { + prepareWhenCondition(listIterator); + } + + } + + private void prepareWhenCondition(ListIterator listIterator) { + Set lineBreakSet = new HashSet( + Arrays.asList(SQLFoldingConstants.SQL_KEYWORK_END, SQLFoldingConstants.SQL_KEYWORD_THEN)); + lineBreakSet.addAll(listBreak); + + WhereCluaseListParser lWhereCluaseListParser = new WhereCluaseListParser(lineBreakSet); + + NodeListParserConverter.handleSelectList(listIterator, lWhereCluaseListParser); + conditionExpr = (TWhereClause) lWhereCluaseListParser.getItemList(); + + listItem.setConditionExpr(conditionExpr); + } + + /** + * Gets the item list. + * + * @return the item list + */ + @Override + public TParseTreeNodeList getItemList() { + return resultColumnList; + } + + /** + * Creates the T node. + * + * @param listIterator the list iterator + * @param next the next + * @param paramCount the param count + */ + public void createTNode(ListIterator listIterator, ISQLTokenData next, int paramCount) { + + } + + /** + * Checks if is node end. + * + * @param nodeStr the node str + * @return true, if is node end + */ + public boolean isNodeEnd(String nodeStr) { + return "WHEN".equalsIgnoreCase(nodeStr) || "ELSE".equalsIgnoreCase(nodeStr); + } + + /** + * Checks if is alias name. + * + * @param nodeStr the node str + * @param previousNotEmptyToken the previous not empty token + * @return true, if is alias name + */ + public boolean isAliasName(String nodeStr, String previousNotEmptyToken) { + return "THEN".equalsIgnoreCase(nodeStr); + } + + /** + * Creates the T custom stmt node. + * + * @param customSqlStmt the custom sql stmt + * @param listIterator the list iterator + * @param next the next + */ + @Override + public void createTCustomStmtNode(TParseTreeNode customSqlStmt, ListIterator listIterator, + ISQLTokenData next) { + } + + /** + * Handle start end node. + * + * @param previousNotEmptyToken the previous not empty token + * @param next the next + * @param listIterator the list iterator + */ + public void handleStartEndNode(String previousNotEmptyToken, ISQLTokenData next, + ListIterator listIterator) { + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/condition/ConditionBreakIf.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/condition/ConditionBreakIf.java new file mode 100644 index 0000000000000000000000000000000000000000..c312cd1ca450cdf5b642bdb560ef37e161e16bf1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/condition/ConditionBreakIf.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.condition; + +import java.util.ListIterator; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; + +/** + * Title: ConditionBreakIf + * + * @since 3.0.0 + */ +public interface ConditionBreakIf { + + /** + * Checks if is break condition. + * + * @param next the next + * @param listIterator the list iterator + * @return true, if is break condition + */ + boolean isBreakCondition(ISQLTokenData next, ListIterator listIterator); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/create/CreateStmtParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/create/CreateStmtParser.java new file mode 100644 index 0000000000000000000000000000000000000000..0fbeb312f606857cb6f8161db8c69d3278a2b1fe --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/create/CreateStmtParser.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.create; + +import java.util.HashMap; +import java.util.Map; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.CTEASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.CustomASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.begin.ast.BeginASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.begin.ast.DeclareASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.create.ast.AsASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.create.ast.CreateASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.create.ast.LanguageASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.create.ast.ReturnsASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TCustomASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.debugobj.TCreateSqlStatement; + +/** + * + * Title: CreateStmtParser + * + * @since 3.0.0 + */ +public class CreateStmtParser extends AbstractStmtParser { + + private static Map> astNodeParserMap = null; + + /** + * Instantiates a new creates the stmt parser. + */ + public CreateStmtParser() { + if (null == astNodeParserMap) { + astNodeParserMap = new HashMap>(10); + astNodeParserMap.put(SQLFoldingConstants.SQL_CREATE, CreateASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_FUNCTION, CreateASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_PROCEDURE, CreateASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_RETURN, ReturnsASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_RETURNS, ReturnsASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORK_AS, AsASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORK_IS, AsASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_LANGUAGE, LanguageASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORK_DECLARE, DeclareASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORK_BEGIN, BeginASTNodeParser.class); + } + } + + /** + * Gets the AST parser. + * + * @param tokenStr the token str + * @param astParserMap the ast parser map + * @return the AST parser + */ + public AbstractASTNodeParser getASTParser(String tokenStr, Map> astParserMap) { + AbstractASTNodeParser astNodeParser = super.getASTParser(tokenStr, astParserMap); + if (null == astNodeParser) { + AbstractASTNodeParser customastNodeParser = new CustomASTNodeParser(); + return customastNodeParser; + } + return astNodeParser; + } + + /** + * the getDefaultNodeParser + */ + protected CTEASTNodeParser getDefaultNodeParser() { + return new CustomASTNodeParser(); + } + + /** + * Gets the custom sql statement. + * + * @return the custom sql statement + */ + @Override + public TCustomSqlStatement getCustomSqlStatement() { + return new TCreateSqlStatement(); + } + + /** + * Gets the ast node parser map. + * + * @return the ast node parser map + */ + @Override + protected Map> getAstNodeParserMap() { + return astNodeParserMap; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/create/ast/AsASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/create/ast/AsASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..f58681aedfa334e7a59f564471331babdbc126b1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/create/ast/AsASTNodeParser.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.create.ast; + +import java.util.HashSet; +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.begin.nodelist.DeclareItemListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeListParserConverter; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.create.TAsASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * Title: AsASTNodeParser + * + * @since 3.0.0 + */ +public class AsASTNodeParser extends AbstractASTNodeParser { + + @Override + public TAsASTNode prepareASTStmtObject(ListIterator listIterator) { + + TAsASTNode asAstNode = new TAsASTNode(); + + TSqlNode lLanguage = ParserUtils.handleToken(listIterator, "AS"); + if (null != lLanguage) { + asAstNode.setKeywordNode(lLanguage); + } + + lLanguage = ParserUtils.handleToken(listIterator, "IS"); + if (null != lLanguage) { + asAstNode.setKeywordNode(lLanguage); + } + + asAstNode.setStratAs(ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_DOUBLE_DOLLER)); + + Set newKeyList = new HashSet(getKeywordList()); + newKeyList.add(SQLFoldingConstants.SQL_DOUBLE_DOLLER); + AbstractNodeListParser lFromItemListParser = new DeclareItemListParser(newKeyList); + + NodeListParserConverter.handleSelectList(listIterator, lFromItemListParser); + TParseTreeNodeList itemList = lFromItemListParser.getItemList(); + + asAstNode.setItemList(itemList); + + asAstNode.setEndAs(ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_DOUBLE_DOLLER)); + + return asAstNode; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/create/ast/CreateASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/create/ast/CreateASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..befb53a64811866b93087b0d5701f5ea58fb8cbb --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/create/ast/CreateASTNodeParser.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.create.ast; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.condition.ConditionBreakIf; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeExpressionConverter; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.SelectResultListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.create.TCreateASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * Title: CreateASTNodeParser + * + * @since 3.0.0 + */ +public class CreateASTNodeParser extends BasicASTNodeParser { + + /** + * Gets the keyword token. + * + * @param listIterator the list iterator + * @return the keyword token + */ + protected TSqlNode getKeywordToken(ListIterator listIterator) { + + return ParserUtils.handleToken(listIterator, Arrays.asList(SQLFoldingConstants.SQL_CREATE, + SQLFoldingConstants.SQL_FUNCTION, SQLFoldingConstants.SQL_PROCEDURE)); + } + + /** + * Prepare AST other stmt object. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTOtherStmtObject(ListIterator listIterator, TBasicASTNode fromAstNode) { + TCreateASTNode tCreateASTNode = (TCreateASTNode) fromAstNode; + + if (!(SQLFoldingConstants.SQL_FUNCTION.equalsIgnoreCase(fromAstNode.getKeywordNode().getNodeText()) + || SQLFoldingConstants.SQL_PROCEDURE.equalsIgnoreCase(fromAstNode.getKeywordNode().getNodeText()))) { + Set interMediateText = new HashSet(Arrays.asList(SQLFoldingConstants.SQL_PROCEDURE, + SQLFoldingConstants.SQL_FUNCTION, SQLFoldingConstants.SQL_PACKAGE)); + + TExpression parseAndGetExpression = NodeExpressionConverter.parseAndGetExpression(listIterator, + interMediateText); + + tCreateASTNode.setIntermediateText(parseAndGetExpression); + + TSqlNode procName = ParserUtils.handleToken(listIterator, Arrays.asList(SQLFoldingConstants.SQL_PROCEDURE, + SQLFoldingConstants.SQL_FUNCTION, SQLFoldingConstants.SQL_PACKAGE)); + + tCreateASTNode.setProcOrFunction(procName); + } + + Set endTableName = new HashSet(Arrays.asList(SQLFoldingConstants.SQL_BRACKET_START)); + + endTableName.addAll(getKeywordList()); + + tCreateASTNode.setProcOrFuncName( + NodeExpressionConverter.parseAndGetExpression(listIterator, endTableName, new ConditionBreakIf() { + @Override + public boolean isBreakCondition(ISQLTokenData next, ListIterator listIterator) { + if (null != next.getSubTokenBean()) { + return true; + } + return false; + } + })); + + TSqlNode startBracket = ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_BRACKET_START); + tCreateASTNode.setProcStartBracket(startBracket); + + } + + /** + * Prepare AST after list item. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTAfterListItem(ListIterator listIterator, TBasicASTNode fromAstNode) { + TCreateASTNode tCreateASTNode = (TCreateASTNode) fromAstNode; + TSqlNode endBracket = ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_BRACKET_END); + + tCreateASTNode.setProcEndBracket(endBracket); + + tCreateASTNode + .setCommonExpression(NodeExpressionConverter.parseAndGetExpression(listIterator, getKeywordList())); + + } + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TCreateASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_CREATE; + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + Set asList = new HashSet<>(Arrays.asList(SQLFoldingConstants.SQL_BRACKET_END)); + asList.addAll(getKeywordList()); + return new SelectResultListParser(asList); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/create/ast/LanguageASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/create/ast/LanguageASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..e23d56a825b48557f8f83156a57dd299ac872875 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/create/ast/LanguageASTNodeParser.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.create.ast; + +import java.util.HashSet; +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeExpressionConverter; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.create.TLaungageASTNode; + +/** + * + * Title: LanguageASTNodeParser + * + * @since 3.0.0 + */ +public class LanguageASTNodeParser extends BasicASTNodeParser { + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TLaungageASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return "LANGUAGE"; + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + return null; + } + + /** + * Prepare AST other stmt object. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTOtherStmtObject(ListIterator listIterator, TBasicASTNode fromAstNode) { + TLaungageASTNode tCreateASTNode = (TLaungageASTNode) fromAstNode; + + Set newKeyList = new HashSet(getKeywordList()); + newKeyList.addAll(ParserUtils.getCommonKeywordListForFunProc()); + + tCreateASTNode.setLanguageExpression(NodeExpressionConverter.parseAndGetExpression(listIterator, newKeyList)); + + tCreateASTNode + .setCommonExpression(NodeExpressionConverter.parseAndGetExpression(listIterator, getKeywordList())); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/create/ast/ReturnsASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/create/ast/ReturnsASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..03e195ec51671357f86e6d1b933ca805d1ff176c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/create/ast/ReturnsASTNodeParser.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.create.ast; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeExpressionConverter; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeListParserConverter; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.SelectResultListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.create.TReturnASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: ReturnsASTNodeParser + * + * @since 3.0.0 + */ +public class ReturnsASTNodeParser extends AbstractASTNodeParser { + + @Override + public TReturnASTNode prepareASTStmtObject(ListIterator listIterator) { + + TReturnASTNode returnAstNode = new TReturnASTNode(); + + TSqlNode lreturn = ParserUtils.handleToken(listIterator, "RETURNS"); + if (null != lreturn) { + returnAstNode.setKeywordNode(lreturn); + } else { + lreturn = ParserUtils.handleToken(listIterator, "RETURN"); + returnAstNode.setKeywordNode(lreturn); + } + + TSqlNode ltable = ParserUtils.handleToken(listIterator, "TABLE"); + returnAstNode.setTable(ltable); + + if (null != ltable) { + + // read the column list + // () + TSqlNode startBracket = ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_BRACKET_START); + returnAstNode.setReturnStartBracket(startBracket); + + Set asList = new HashSet<>(Arrays.asList(SQLFoldingConstants.SQL_BRACKET_END)); + asList.addAll(getKeywordList()); + + AbstractNodeListParser lFromItemListParser = new SelectResultListParser(asList); + + NodeListParserConverter.handleSelectList(listIterator, lFromItemListParser); + TParseTreeNodeList itemList = lFromItemListParser.getItemList(); + + returnAstNode.setReturnTableList(itemList); + + TSqlNode endBracket = ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_BRACKET_END); + returnAstNode.setReturnEndBracket(endBracket); + + } else { + + Set endLineBreakList = new HashSet(Arrays.asList("deterministic")); + endLineBreakList.addAll(getKeywordList()); + endLineBreakList.addAll(ParserUtils.getCommonKeywordListForFunProc()); + returnAstNode + .setResultExpression(NodeExpressionConverter.parseAndGetExpression(listIterator, endLineBreakList)); + + TSqlNode ldeterministic = ParserUtils.handleToken(listIterator, "DETERMINISTIC", false); + if (null != ldeterministic) { + returnAstNode.setDeterministic(ldeterministic); + } + + // expression read the return rettype + } + + returnAstNode + .setCommonExpression(NodeExpressionConverter.parseAndGetExpression(listIterator, getKeywordList())); + + return returnAstNode; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/cursor/CursorStmtParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/cursor/CursorStmtParser.java new file mode 100644 index 0000000000000000000000000000000000000000..903217c9c56d2931241914a46151dc1705d95abb --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/cursor/CursorStmtParser.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.cursor; + +import java.util.HashMap; +import java.util.Map; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.cursor.ast.CursorStmtASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.debugobj.TCursorSqlStatement; + +/** + * Title: IfElseStmtParser + * + * @since 3.0.0 + */ +public class CursorStmtParser extends AbstractStmtParser { + + private static Map> astNodeParserMap = null; + + public CursorStmtParser() { + if (null == astNodeParserMap) { + astNodeParserMap = new HashMap>(10); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_CURSOR, CursorStmtASTNodeParser.class); + } + } + + @Override + public TCustomSqlStatement getCustomSqlStatement() { + return new TCursorSqlStatement(); + } + + @Override + protected Map> getAstNodeParserMap() { + return astNodeParserMap; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/cursor/ast/CursorStmtASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/cursor/ast/CursorStmtASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..038f7ca8efe199f68fff979ab880191ef04fc915 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/cursor/ast/CursorStmtASTNodeParser.java @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.cursor.ast; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeExpressionConverter; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.SelectResultListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.cursor.TCursorASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; + +/** + * Title: IfElseStmtASTNodeParser + * + * @since 3.0.0 + */ +public class CursorStmtASTNodeParser extends BasicASTNodeParser { + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TCursorASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_CURSOR; + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + Set asList = new HashSet<>(Arrays.asList(SQLFoldingConstants.SQL_BRACKET_END)); + return new SelectResultListParser(asList); + } + + /** + * Prepare AST other stmt object. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTOtherStmtObject(ListIterator listIterator, TBasicASTNode fromAstNode) { + TCursorASTNode orderByAstNode = (TCursorASTNode) fromAstNode; + + Set onEndList = new HashSet(Arrays.asList(SQLFoldingConstants.SQL_BRACKET_START)); + TExpression parseAndGetExpression = NodeExpressionConverter.parseAndGetExpression(listIterator, onEndList); + parseAndGetExpression.setAddSpaceForCustomStmt(Boolean.TRUE); + orderByAstNode.setCursorExpression(parseAndGetExpression); + + orderByAstNode + .setParamStartBracket(ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_BRACKET_START)); + + } + + /** + * Prepare AST list item. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTListItem(ListIterator listIterator, TBasicASTNode fromAstNode) { + TCursorASTNode orderByAstNode = (TCursorASTNode) fromAstNode; + if (null != orderByAstNode.getParamStartBracket()) { + super.prepareASTListItem(listIterator, fromAstNode); + } + } + + /** + * Prepare AST after list item. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTAfterListItem(ListIterator listIterator, TBasicASTNode fromAstNode) { + TCursorASTNode orderByAstNode = (TCursorASTNode) fromAstNode; + orderByAstNode.setParamEndBracket(ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_BRACKET_END)); + + orderByAstNode.setForOrIs( + ParserUtils.handleToken(listIterator, Arrays.asList(SQLFoldingConstants.SQL_KEYWORD_FOR, "is"))); + + TExpression cursorStmts = NodeExpressionConverter.parseAndGetExpression(listIterator, null); + + orderByAstNode.setCursorStmts(cursorStmts); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/delete/DeleteStmtParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/delete/DeleteStmtParser.java new file mode 100644 index 0000000000000000000000000000000000000000..a2f2a95b2fc33154ff1f37cc7f63bb37bbf8622d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/delete/DeleteStmtParser.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.delete; + +import java.util.HashMap; +import java.util.Map; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.FromASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.ReturningASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.WhereASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.delete.ast.DeleteFromASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.delete.ast.DeleteUsingASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml.TDeleteSqlStatement; + +/** + * + * Title: DeleteStmtParser + * + * @since 3.0.0 + */ +public class DeleteStmtParser extends AbstractStmtParser { + + private static Map> astNodeParserMap = null; + + public DeleteStmtParser() { + if (null == astNodeParserMap) { + astNodeParserMap = new HashMap>(10); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_DELETE, DeleteFromASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_FROM, FromASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_USING, DeleteUsingASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_WHERE, WhereASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_RETURNING, ReturningASTNodeParser.class); + } + } + + @Override + public TCustomSqlStatement getCustomSqlStatement() { + return new TDeleteSqlStatement(); + } + + @Override + protected Map> getAstNodeParserMap() { + return astNodeParserMap; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/delete/ast/DeleteFromASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/delete/ast/DeleteFromASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..bef35148882291f9a3e32e8329319b13fb2bf332 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/delete/ast/DeleteFromASTNodeParser.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.delete.ast; + +import java.util.ListIterator; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeExpressionConverter; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.delete.TDeleteFromASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: DeleteFromASTNodeParser + * + * @since 3.0.0 + */ +public class DeleteFromASTNodeParser extends BasicASTNodeParser { + + /** + * Prepare AST other stmt object. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTOtherStmtObject(ListIterator listIterator, TBasicASTNode fromAstNode) { + + TDeleteFromASTNode groupByAstNode = (TDeleteFromASTNode) fromAstNode; + + TSqlNode only = ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_KEYWORD_ONLY); + groupByAstNode.setOnly(only); + + TSqlNode from = ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_KEYWORD_FROM); + groupByAstNode.setFrom(from); + + if (null == from) { + setTableName(listIterator, groupByAstNode); + return; + } else { + + setTableName(listIterator, groupByAstNode); + } + + } + + private void setTableName(ListIterator listIterator, TDeleteFromASTNode groupByAstNode) { + groupByAstNode.setTableName(NodeExpressionConverter.parseAndGetExpression(listIterator, getKeywordList())); + } + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TDeleteFromASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_DELETE; + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + return null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/delete/ast/DeleteUsingASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/delete/ast/DeleteUsingASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..dd97604b0511191e6f316f5855dddac3ab6e686a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/delete/ast/DeleteUsingASTNodeParser.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.delete.ast; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.FromItemListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.delete.TDeleteUsingASTNode; + +/** + * + * Title: DeleteUsingASTNodeParser + * + * @since 3.0.0 + */ +public class DeleteUsingASTNodeParser extends BasicASTNodeParser { + + @Override + public TDeleteUsingASTNode getASTNodeBean() { + return new TDeleteUsingASTNode(); + } + + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_USING; + } + + @Override + public AbstractNodeListParser getNodeListParser() { + return new FromItemListParser(getKeywordList()); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/forloop/ForLoopStmtParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/forloop/ForLoopStmtParser.java new file mode 100644 index 0000000000000000000000000000000000000000..456095a72c798cf1a350204fd3fec1b428a07d50 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/forloop/ForLoopStmtParser.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.forloop; + +import java.util.HashMap; +import java.util.Map; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.forloop.ast.ForLoopStmtASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.loop.TForLoopSqlStatement; + +/** + * Title: IfElseStmtParser + * + * @since 3.0.0 + */ +public class ForLoopStmtParser extends AbstractStmtParser { + + private static Map> astNodeParserMap = null; + + public ForLoopStmtParser() { + if (null == astNodeParserMap) { + astNodeParserMap = new HashMap>(10); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_FOR, ForLoopStmtASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_WHILE, ForLoopStmtASTNodeParser.class); + } + } + + @Override + public TCustomSqlStatement getCustomSqlStatement() { + return new TForLoopSqlStatement(); + } + + @Override + protected Map> getAstNodeParserMap() { + return astNodeParserMap; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/forloop/ast/ForLoopStmtASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/forloop/ast/ForLoopStmtASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..1aa80c0dc2d7f6dd39e346884fa1404fadfa9bef --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/forloop/ast/ForLoopStmtASTNodeParser.java @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.forloop.ast; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.SQLStmtTokenListBean; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.condition.ConditionBreakIf; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeExpressionConverter; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.WhereCluaseListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.forloop.TForLoopASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * Title: IfElseStmtASTNodeParser + * + * @since 3.0.0 + */ +public class ForLoopStmtASTNodeParser extends BasicASTNodeParser { + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TForLoopASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_FOR; + } + + /** + * Gets the keyword token. + * + * @param listIterator the list iterator + * @return the keyword token + */ + protected TSqlNode getKeywordToken(ListIterator listIterator) { + + return ParserUtils.handleToken(listIterator, + Arrays.asList(SQLFoldingConstants.SQL_KEYWORD_FOR, SQLFoldingConstants.SQL_KEYWORD_WHILE)); + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + Set lineBreakSet = new HashSet(); + return new WhereCluaseListParser(lineBreakSet) { + @Override + public boolean isListBreakWithCustomSQL(String previousNotEmptyToken, + SQLStmtTokenListBean sqlStmtTokenListBean) { + if (null != sqlStmtTokenListBean + && sqlStmtTokenListBean.getStatementType() == SQLTokenConstants.T_SQL_LOOP) { + return true; + } + return false; + } + + }; + } + + /** + * Prepare AST other stmt object. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTOtherStmtObject(ListIterator listIterator, TBasicASTNode fromAstNode) { + + TSqlNode startNode = (TSqlNode) fromAstNode.getStartNode(); + + if (null != startNode && SQLFoldingConstants.SQL_KEYWORD_WHERE.equalsIgnoreCase(startNode.getNodeText())) { + return; + } + + TForLoopASTNode orderByAstNode = (TForLoopASTNode) fromAstNode; + TExpression parseAndGetExpression = NodeExpressionConverter.parseAndGetExpression(listIterator, null, + new ConditionBreakIf() { + @Override + public boolean isBreakCondition(ISQLTokenData next, ListIterator listIterator) { + if (null != next.getSubTokenBean() + && next.getSubTokenBean().getStatementType() == SQLTokenConstants.T_SQL_LOOP) { + return true; + } + return false; + } + }); + parseAndGetExpression.setAddSpaceForCustomStmt(Boolean.TRUE); + orderByAstNode.setTargetName(parseAndGetExpression); + } + + /** + * Prepare AST list item. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTListItem(ListIterator listIterator, TBasicASTNode fromAstNode) { + + TForLoopASTNode orderByAstNode = (TForLoopASTNode) fromAstNode; + + TSqlNode startNode = (TSqlNode) orderByAstNode.getStartNode(); + + if (null != startNode && SQLFoldingConstants.SQL_KEYWORD_FOR.equalsIgnoreCase(startNode.getNodeText())) { + return; + } + + TParseTreeNodeList handleFromList = handleFromList(listIterator); + + if (null != handleFromList) { + fromAstNode.setItemList(handleFromList); + } + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/handler/ParserHandlerConfig.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/handler/ParserHandlerConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..f3351642cfb1a316058a30e2979ab5b9bf57daf7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/handler/ParserHandlerConfig.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.handler; + +import java.util.HashMap; +import java.util.Map; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractStmtParser; + +/** + * + * Title: RuleHandlerConfig + * + * Description:RuleHandlerConfig + * + * @since 3.0.0 + */ +public class ParserHandlerConfig { + private Map ruleLibrary = new HashMap(10); + + private volatile boolean initilized = false; + + private static ParserHandlerConfig ruleHandlerConfig = new ParserHandlerConfig(); + + /** + * Gets the single instance of RuleHandlerConfig. + * + * @return single instance of RuleHandlerConfig + */ + public static ParserHandlerConfig getInstance() { + + return ruleHandlerConfig; + } + + private ParserHandlerConfig() { + } + + /** + * Gets the rule handle. + * + * @param type the type + * @return the rule handle + */ + public AbstractStmtParser getRuleHandle(int type) { + return ruleLibrary.get(type); + + } + + /** + * Adds the rule handle. + * + * @param type the type + * @param stmtParser the stmt parser + */ + public void addRuleHandle(int type, AbstractStmtParser stmtParser) { + ruleLibrary.put(type, stmtParser); + } + + /** + * Checks if is initilized. + * + * @return true, if is initilized + */ + public boolean isInitilized() { + return initilized; + } + + /** + * Sets the initilized. + * + * @param initilized the new initilized + */ + public void setInitilized(boolean initilized) { + this.initilized = initilized; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ifstmt/IfElseStmtParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ifstmt/IfElseStmtParser.java new file mode 100644 index 0000000000000000000000000000000000000000..e06e90d35a41bbb46579c4f43f330cb039e7799d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ifstmt/IfElseStmtParser.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.ifstmt; + +import java.util.HashMap; +import java.util.Map; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ifstmt.ast.IfElseStmtASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.condition.TIfElseSqlStatement; + +/** + * Title: IfElseStmtParser + * + * @since 3.0.0 + */ +public class IfElseStmtParser extends AbstractStmtParser { + + private static Map> astNodeParserMap = null; + + public IfElseStmtParser() { + if (null == astNodeParserMap) { + astNodeParserMap = new HashMap>(10); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_IF, IfElseStmtASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_ELSE, IfElseStmtASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_ELSIF, IfElseStmtASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_ELSEIF, IfElseStmtASTNodeParser.class); + } + } + + @Override + public TCustomSqlStatement getCustomSqlStatement() { + return new TIfElseSqlStatement(); + } + + @Override + protected Map> getAstNodeParserMap() { + return astNodeParserMap; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ifstmt/ast/IfElseStmtASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ifstmt/ast/IfElseStmtASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..e7d7764e37065c03b6454efae4119878f1a263b2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/ifstmt/ast/IfElseStmtASTNodeParser.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.ifstmt.ast; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.FullStatementConverter; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeExpressionConverter; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.WhereCluaseListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.ifstmt.TIfElseASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: IfElseStmtASTNodeParser + * + * @since 3.0.0 + */ +public class IfElseStmtASTNodeParser extends BasicASTNodeParser { + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TIfElseASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_IF; + } + + /** + * Gets the keyword token. + * + * @param listIterator the list iterator + * @return the keyword token + */ + protected TSqlNode getKeywordToken(ListIterator listIterator) { + + return ParserUtils.handleToken(listIterator, Arrays.asList(SQLFoldingConstants.SQL_KEYWORD_ELSIF, + SQLFoldingConstants.SQL_KEYWORD_ELSE, SQLFoldingConstants.SQL_KEYWORD_IF)); + } + + /** + * Prepare AST list item. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTListItem(ListIterator listIterator, TBasicASTNode fromAstNode) { + + TIfElseASTNode orderByAstNode = (TIfElseASTNode) fromAstNode; + + TSqlNode startNode = (TSqlNode) orderByAstNode.getStartNode(); + + if (null != startNode && SQLFoldingConstants.SQL_KEYWORD_ELSE.equalsIgnoreCase(startNode.getNodeText())) { + return; + } + + TParseTreeNodeList handleFromList = handleFromList(listIterator); + + if (null != handleFromList) { + fromAstNode.setItemList(handleFromList); + } + + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + Set lineBreakSet = new HashSet( + Arrays.asList(SQLFoldingConstants.SQL_KEYWORK_END, SQLFoldingConstants.SQL_KEYWORD_THEN)); + return new WhereCluaseListParser(lineBreakSet); + } + + /** + * Prepare AST after list item. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTAfterListItem(ListIterator listIterator, TBasicASTNode fromAstNode) { + TIfElseASTNode orderByAstNode = (TIfElseASTNode) fromAstNode; + + TSqlNode then = ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_KEYWORD_THEN); + orderByAstNode.setThen(then); + + Set lineBreakSet = new HashSet(Arrays.asList(SQLFoldingConstants.SQL_KEYWORD_ELSIF, + SQLFoldingConstants.SQL_KEYWORD_ELSE, SQLFoldingConstants.SQL_KEYWORK_END)); + + orderByAstNode.setFullStmt(FullStatementConverter.parseAndGetFullStmt(listIterator, lineBreakSet)); + + // code to parse all the statements + + // if still have tokens those are with END IF + + TSqlNode end = ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_KEYWORK_END); + orderByAstNode.setEnd(end); + + orderByAstNode.setEndNode(NodeExpressionConverter.parseAndGetExpression(listIterator, null)); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/init/ParserInitilizer.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/init/ParserInitilizer.java new file mode 100644 index 0000000000000000000000000000000000000000..2ef26a8a15e958266cd5c623b5d54e9fed5a6d9b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/init/ParserInitilizer.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.init; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.begin.BeginStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.begin.DeclareStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.casestmt.CaseStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.create.CreateStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.cursor.CursorStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.delete.DeleteStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.forloop.ForLoopStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.handler.ParserHandlerConfig; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ifstmt.IfElseStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.insert.InsertStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.loop.LoopStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.merge.MergeStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.SelectStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.union.UnionStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.update.UpdateStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.with.WithStmtParser; + +/** + * Title: ParserInitilizer + * + * @since 3.0.0 + */ +public final class ParserInitilizer { + + /** + * Inits the parser. + */ + public static void initParser() { + + if (!ParserHandlerConfig.getInstance().isInitilized()) { + ParserHandlerConfig.getInstance().addRuleHandle(SQLTokenConstants.T_SQL_DML_SELECT, new SelectStmtParser()); + ParserHandlerConfig.getInstance().addRuleHandle(SQLTokenConstants.T_SQL_DML_WITH, new WithStmtParser()); + ParserHandlerConfig.getInstance().addRuleHandle(SQLTokenConstants.T_SQL_KEYWORK_CASE, new CaseStmtParser()); + + ParserHandlerConfig.getInstance().addRuleHandle(SQLTokenConstants.T_SQL_DML_INSERT, new InsertStmtParser()); + ParserHandlerConfig.getInstance().addRuleHandle(SQLTokenConstants.T_SQL_DML_DELETE, new DeleteStmtParser()); + ParserHandlerConfig.getInstance().addRuleHandle(SQLTokenConstants.T_SQL_DML_UPDATE, new UpdateStmtParser()); + + ParserHandlerConfig.getInstance().addRuleHandle(SQLTokenConstants.T_SQL_DDL_CREATE, new CreateStmtParser()); + ParserHandlerConfig.getInstance().addRuleHandle(SQLTokenConstants.T_SQL_DDL_CREATE_FUNC, + new CreateStmtParser()); + ParserHandlerConfig.getInstance().addRuleHandle(SQLTokenConstants.T_SQL_DDL_CREATE_PROC, + new CreateStmtParser()); + ParserHandlerConfig.getInstance().addRuleHandle(SQLTokenConstants.T_SQL_BLOCK_DECLARE, + new DeclareStmtParser()); + ParserHandlerConfig.getInstance().addRuleHandle(SQLTokenConstants.T_SQL_BLOCK_BEGIN, new BeginStmtParser()); + + ParserHandlerConfig.getInstance().addRuleHandle(SQLTokenConstants.T_SQL_DDL_CONTROL_IF, + new IfElseStmtParser()); + ParserHandlerConfig.getInstance().addRuleHandle(SQLTokenConstants.T_SQL_DDL_CONTROL_ELSE, + new IfElseStmtParser()); + ParserHandlerConfig.getInstance().addRuleHandle(SQLTokenConstants.T_SQL_DDL_CONTROL_ELSIF, + new IfElseStmtParser()); + + ParserHandlerConfig.getInstance().addRuleHandle(SQLTokenConstants.T_SQL_LOOP, new LoopStmtParser()); + + ParserHandlerConfig.getInstance().addRuleHandle(SQLTokenConstants.T_SQL_KEYWORD_CURSOR, + new CursorStmtParser()); + + ParserHandlerConfig.getInstance().addRuleHandle(SQLTokenConstants.T_SQL_KEYWORD_FOR, + new ForLoopStmtParser()); + + ParserHandlerConfig.getInstance().addRuleHandle(SQLTokenConstants.T_SQL_KEYWORK_UNION, + new UnionStmtParser()); + + ParserHandlerConfig.getInstance().addRuleHandle(SQLTokenConstants.T_SQL_MERGE, new MergeStmtParser()); + + ParserHandlerConfig.getInstance().setInitilized(true); + } + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/insert/InsertStmtParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/insert/InsertStmtParser.java new file mode 100644 index 0000000000000000000000000000000000000000..3607da237251b6327e9139e15e8978e80f159116 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/insert/InsertStmtParser.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.insert; + +import java.util.HashMap; +import java.util.Map; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.CTEASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.ReturningASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.WhereASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.insert.ast.InsertDefaultValuesASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.insert.ast.InsertIntoASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.insert.ast.InsertValuesListASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TCustomASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml.TInsertSqlStatement; + +/** + * + * Title: InsertStmtParser + * + * @since 3.0.0 + */ +public class InsertStmtParser extends AbstractStmtParser { + + private static Map> astNodeParserMap = null; + + /** + * Instantiates a new insert stmt parser. + */ + public InsertStmtParser() { + if (null == astNodeParserMap) { + astNodeParserMap = new HashMap>(10); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_INSERT, InsertIntoASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_DEFAULT, InsertDefaultValuesASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_VALUES, InsertValuesListASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_RETURNING, ReturningASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_WHERE, WhereASTNodeParser.class); + + } + } + + /** + * Gets the AST parser. + * + * @param tokenStr the token str + * @param astParserMap the ast parser map + * @return the AST parser + */ + public AbstractASTNodeParser getASTParser(String tokenStr, Map> astParserMap) { + + AbstractASTNodeParser astParser = super.getASTParser(tokenStr, astParserMap); + + if (null == astParser) { + AbstractASTNodeParser lAbstractASTNodeParser = new CTEASTNodeParser(); + + return lAbstractASTNodeParser; + } + + return astParser; + } + + /** + * Gets the custom sql statement. + * + * @return the custom sql statement + */ + @Override + public TCustomSqlStatement getCustomSqlStatement() { + return new TInsertSqlStatement(); + } + + /** + * Gets the ast node parser map. + * + * @return the ast node parser map + */ + @Override + protected Map> getAstNodeParserMap() { + return astNodeParserMap; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/insert/ast/InsertDefaultValuesASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/insert/ast/InsertDefaultValuesASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..20dc31de16d17a4292aef99cb41f42e166cd3ea1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/insert/ast/InsertDefaultValuesASTNodeParser.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.insert.ast; + +import java.util.ListIterator; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.insert.TInsertDefaultASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: InsertDefaultValuesASTNodeParser + * + * @since 3.0.0 + */ +public class InsertDefaultValuesASTNodeParser extends BasicASTNodeParser { + + /** + * Prepare AST other stmt object. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTOtherStmtObject(ListIterator listIterator, TBasicASTNode fromAstNode) { + TInsertDefaultASTNode groupByAstNode = (TInsertDefaultASTNode) fromAstNode; + TSqlNode values = ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_KEYWORD_VALUES); + groupByAstNode.setValues(values); + + } + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TInsertDefaultASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_DEFAULT; + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/insert/ast/InsertIntoASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/insert/ast/InsertIntoASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..ce9375a18651c95db016114c924aa3c2714b9471 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/insert/ast/InsertIntoASTNodeParser.java @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.insert.ast; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.condition.ConditionBreakIf; +import org.opengauss.mppdbide.gauss.sqlparser.parser.insert.nodelist.InsertIntoListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeExpressionConverter; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.insert.TInsertIntoASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: InsertIntoASTNodeParser + * + * @since 3.0.0 + */ +public class InsertIntoASTNodeParser extends BasicASTNodeParser { + + /** + * Prepare AST other stmt object. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTOtherStmtObject(ListIterator listIterator, TBasicASTNode fromAstNode) { + TInsertIntoASTNode groupByAstNode = (TInsertIntoASTNode) fromAstNode; + TSqlNode into = ParserUtils.handleToken(listIterator, "into"); + groupByAstNode.setInto(into); + + // prepare the table name in insert + + Set endTableName = new HashSet( + Arrays.asList(SQLFoldingConstants.SQL_BRACKET_START, SQLFoldingConstants.SQL_KEYWORK_VALUES)); + + endTableName.addAll(getKeywordList()); + + groupByAstNode.setTableName( + NodeExpressionConverter.parseAndGetExpression(listIterator, endTableName, new ConditionBreakIf() { + @Override + public boolean isBreakCondition(ISQLTokenData next, ListIterator listIterator) { + if (null != next.getSubTokenBean()) { + return true; + } + return false; + } + })); + + TSqlNode startBracket = ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_BRACKET_START); + + groupByAstNode.setStartInsertAstBracket(startBracket); + + } + + /** + * Prepare AST after list item. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTAfterListItem(ListIterator listIterator, TBasicASTNode fromAstNode) { + TInsertIntoASTNode groupByAstNode = (TInsertIntoASTNode) fromAstNode; + TSqlNode endBracket = ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_BRACKET_END); + + groupByAstNode.setEndInsertAstBracket(endBracket); + } + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TInsertIntoASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_INSERT; + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + Set asList = new HashSet<>( + Arrays.asList(SQLFoldingConstants.SQL_BRACKET_END, SQLFoldingConstants.SQL_KEYWORK_VALUES)); + asList.addAll(getKeywordList()); + return new InsertIntoListParser(asList); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/insert/ast/InsertValuesListASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/insert/ast/InsertValuesListASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..52be7033d11ba8cd760da2205e5b54b3be8ed2b0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/insert/ast/InsertValuesListASTNodeParser.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.insert.ast; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.exception.GaussDBSQLParserException; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.insert.nodelist.InsertValuesListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.insert.TInsertValuesASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; + +/** + * + * Title: InsertValuesListASTNodeParser + * + * @since 3.0.0 + */ +public class InsertValuesListASTNodeParser extends BasicASTNodeParser { + + @Override + public TBasicASTNode getASTNodeBean() { + return new TInsertValuesASTNode(); + } + + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_VALUES; + } + + @Override + public AbstractNodeListParser getNodeListParser() { + Set asList = new HashSet<>(Arrays.asList(";")); + asList.addAll(getKeywordList()); + return new InsertValuesListParser(asList); + } + + /** + * Prepare AST list item. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTListItem(ListIterator listIterator, TBasicASTNode fromAstNode) { + if (listIterator.hasNext()) { + ISQLTokenData next = listIterator.next(); + listIterator.previous(); + if (null != next && !"(".equals(next.getTokenStr())) { + throw new GaussDBSQLParserException("Unable to parse the statement"); + } + } + TParseTreeNodeList handleFromList = handleFromList(listIterator); + if (null != handleFromList) { + fromAstNode.setItemList(handleFromList); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/insert/nodelist/InsertIntoListParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/insert/nodelist/InsertIntoListParser.java new file mode 100644 index 0000000000000000000000000000000000000000..6beb6f2310ebbfddacafe27ec45ae6c5aa7cb681 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/insert/nodelist/InsertIntoListParser.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.insert.nodelist; + +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.SQLStmtTokenListBean; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.SelectResultListParser; + +/** + * + * Title: InsertIntoListParser + * + * @since 3.0.0 + */ +public class InsertIntoListParser extends SelectResultListParser { + + /** + * Instantiates a new insert into list parser. + * + * @param lineBreakSet the line break set + */ + public InsertIntoListParser(Set lineBreakSet) { + super(lineBreakSet); + + } + + /** + * Checks if is list break with custom SQL. + * + * @param previousNotEmptyToken the previous not empty token + * @param sqlStmtTokenListBean the sql stmt token list bean + * @return true, if is list break with custom SQL + */ + @Override + public boolean isListBreakWithCustomSQL(String previousNotEmptyToken, SQLStmtTokenListBean sqlStmtTokenListBean) { + + return true; + } + + /** + * Checks if is list break. + * + * @param nodeStr the node str + * @param parseCount the parse count + * @return true, if is list break + */ + @Override + public boolean isListBreak(String nodeStr, int parseCount) { + return parseCount == 0 && listBreak.contains(nodeStr.toLowerCase()); + } + + /** + * Handle start end node. + * + * @param previousNotEmptyToken the previous not empty token + * @param next the next + * @param listIterator the list iterator + */ + public void handleStartEndNode(String previousNotEmptyToken, ISQLTokenData next, + ListIterator listIterator) { + // do nothing + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/insert/nodelist/InsertValuesListParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/insert/nodelist/InsertValuesListParser.java new file mode 100644 index 0000000000000000000000000000000000000000..2c5f68bf12fb0cc3ae0faa188b4b264de59551f4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/insert/nodelist/InsertValuesListParser.java @@ -0,0 +1,220 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.insert.nodelist; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeListParserConverter; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.SelectResultListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.insert.TInsertValuesNodeItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.insert.TInsertValuesNodeItemList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: InsertValuesListParser + * + * @since 3.0.0 + */ +public class InsertValuesListParser extends AbstractNodeListParser { + + /** + * The result column. + */ + protected TInsertValuesNodeItem resultColumn = null; + + private TInsertValuesNodeItemList resultColumnList = new TInsertValuesNodeItemList(); + + /** + * Instantiates a new insert values list parser. + * + * @param lineBreakSet the line break set + */ + public InsertValuesListParser(Set lineBreakSet) { + super(lineBreakSet); + } + + /** + * Creates the T object. + */ + public void createTObject() { + // create and then it is the start of the expression + if (null == resultColumn) { + resultColumn = getResultColumn(); + resultColumnList.addResultColumn(resultColumn); + } + } + + /** + * Gets the result column. + * + * @return the result column + */ + protected TInsertValuesNodeItem getResultColumn() { + return new TInsertValuesNodeItem(); + } + + /** + * Handle node alias. + * + * @param listIterator the list iterator + * @param next the next + */ + public void handleNodeAlias(ListIterator listIterator, ISQLTokenData next) { + + } + + /** + * Handle node end. + * + * @param listIterator the list iterator + * @param next the next + */ + public void handleNodeEnd(ListIterator listIterator, ISQLTokenData next) { + + TSqlNode seperator = ParserUtils.getSqlNode(listIterator, next); + resultColumn.setSeperator(seperator); + resultColumn = null; + + } + + /** + * Gets the item list. + * + * @return the item list + */ + @Override + public TParseTreeNodeList getItemList() { + return resultColumnList; + } + + /** + * Checks if is list break. + * + * @param nodeStr the node str + * @param parseCount the parse count + * @return true, if is list break + */ + @Override + public boolean isListBreak(String nodeStr, int parseCount) { + return parseCount == 0 && listBreak.contains(nodeStr.toLowerCase()); + } + + /** + * Creates the T node. + * + * @param listIterator the list iterator + * @param next the next + * @param paramCount the param count + */ + public void createTNode(ListIterator listIterator, ISQLTokenData next, int paramCount) { + + if (null != resultColumn.getStartInsertBracket() || null != resultColumn.getValueItemList()) { + if (SQLFoldingConstants.SQL_BRACKET_END.equals(next.getTokenStr())) { + TSqlNode endBracket = ParserUtils.getSqlNode(listIterator, next); + resultColumn.setInsertEndBracket(endBracket); + } else { + throw new IllegalStateException("Unable to position the statement"); + } + return; + } + + if (SQLFoldingConstants.SQL_BRACKET_START.equals(next.getTokenStr())) { + TSqlNode startBracket = ParserUtils.getSqlNode(listIterator, next); + resultColumn.setStartInsertBracket(startBracket); + } + + // parse for the result list + + Set asList = new HashSet<>(Arrays.asList(SQLFoldingConstants.SQL_BRACKET_END)); + + SelectResultListParser lSelectResultListParser = new SelectResultListParser(asList) { + @Override + public boolean isListBreak(String nodeStr, int parseCount) { + return parseCount == 0 && listBreak.contains(nodeStr.toLowerCase()); + } + + @Override + public void handleStartEndNode(String previousNotEmptyToken, ISQLTokenData next, + ListIterator listIterator) { + // do nothing + } + }; + + NodeListParserConverter.handleSelectList(listIterator, lSelectResultListParser); + + TParseTreeNodeList handleSelectList = lSelectResultListParser.getItemList(); + if (null != handleSelectList) { + resultColumn.setValueItemList(handleSelectList); + } + + } + + /** + * Checks if is node end. + * + * @param nodeStr the node str + * @return true, if is node end + */ + public boolean isNodeEnd(String nodeStr) { + return ",".equalsIgnoreCase(nodeStr); + } + + /** + * Checks if is alias name. + * + * @param nodeStr the node str + * @param previousNotEmptyToken the previous not empty token + * @return true, if is alias name + */ + public boolean isAliasName(String nodeStr, String previousNotEmptyToken) { + return false; + } + + /** + * Creates the T custom stmt node. + * + * @param customSqlStmt the custom sql stmt + * @param listIterator the list iterator + * @param next the next + */ + @Override + public void createTCustomStmtNode(TParseTreeNode customSqlStmt, ListIterator listIterator, + ISQLTokenData next) { + + } + + /** + * Handle start end node. + * + * @param previousNotEmptyToken the previous not empty token + * @param next the next + * @param listIterator the list iterator + */ + public void handleStartEndNode(String previousNotEmptyToken, ISQLTokenData next, + ListIterator listIterator) { + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/loop/LoopStmtParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/loop/LoopStmtParser.java new file mode 100644 index 0000000000000000000000000000000000000000..7330cba995f91ad4a564f6a75e3e690be75081f2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/loop/LoopStmtParser.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.loop; + +import java.util.HashMap; +import java.util.Map; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.loop.ast.LoopStmtASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.loop.TLoopSqlStatement; + +/** + * + * Title: LoopStmtParser + * + * @since 3.0.0 + */ +public class LoopStmtParser extends AbstractStmtParser { + + private static Map> astNodeParserMap = null; + + public LoopStmtParser() { + if (null == astNodeParserMap) { + astNodeParserMap = new HashMap>(10); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_LOOP, LoopStmtASTNodeParser.class); + } + } + + @Override + public TCustomSqlStatement getCustomSqlStatement() { + return new TLoopSqlStatement(); + } + + @Override + protected Map> getAstNodeParserMap() { + return astNodeParserMap; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/loop/ast/LoopStmtASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/loop/ast/LoopStmtASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..c37889cb4662c3f62e848df6ad10113f82e24247 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/loop/ast/LoopStmtASTNodeParser.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.loop.ast; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.FullStatementConverter; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeExpressionConverter; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.loop.TLoopASTNode; + +/** + * + * Title: LoopStmtASTNodeParser + * + * @since 3.0.0 + */ +public class LoopStmtASTNodeParser extends BasicASTNodeParser { + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TLoopASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_LOOP; + } + + /** + * Prepare AST after list item. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTAfterListItem(ListIterator listIterator, TBasicASTNode fromAstNode) { + TLoopASTNode orderByAstNode = (TLoopASTNode) fromAstNode; + + Set lineBreakSet = new HashSet(Arrays.asList(SQLFoldingConstants.SQL_KEYWORK_END)); + + orderByAstNode.setFullStmt(FullStatementConverter.parseAndGetFullStmt(listIterator, lineBreakSet)); + + // code to parse all the statements + + Set endLineBreakList = new HashSet(); + + orderByAstNode.setEndLoop(NodeExpressionConverter.parseAndGetExpression(listIterator, endLineBreakList)); + + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/merge/MergeStmtParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/merge/MergeStmtParser.java new file mode 100644 index 0000000000000000000000000000000000000000..22a912d0563e7f0bfb14779412edc58095236e72 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/merge/MergeStmtParser.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.merge; + +import java.util.HashMap; +import java.util.Map; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.merge.ast.MergeASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.merge.ast.MergeWhenMatchedASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml.TMergeSqlStatement; + +/** + * Title: WithStmtParser + * + * @since 3.0.0 + */ +public class MergeStmtParser extends AbstractStmtParser { + + private static Map> astNodeParserMap = null; + + public MergeStmtParser() { + if (null == astNodeParserMap) { + astNodeParserMap = new HashMap>(10); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_MERGE, MergeASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_WHEN, MergeWhenMatchedASTNodeParser.class); + } + } + + @Override + public TCustomSqlStatement getCustomSqlStatement() { + return new TMergeSqlStatement(); + } + + @Override + protected Map> getAstNodeParserMap() { + return astNodeParserMap; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/merge/ast/MergeASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/merge/ast/MergeASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..cb354d59186621243da4c837b2eda0c237196b70 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/merge/ast/MergeASTNodeParser.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.merge.ast; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.comm.ISQLSyntax; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeExpressionConverter; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.WhereCluaseListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.merge.TMergeASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * Title: WithASTNodeParser + * + * @since 3.0.0 + */ +public class MergeASTNodeParser extends BasicASTNodeParser { + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TMergeASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_MERGE; + } + + /** + * Gets the keyword token. + * + * @param listIterator the list iterator + * @return the keyword token + */ + protected TSqlNode getKeywordToken(ListIterator listIterator) { + return ParserUtils.handleToken(listIterator, getKeywordTokenStr(), false); + } + + /** + * Prepare AST other stmt object. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTOtherStmtObject(ListIterator listIterator, TBasicASTNode fromAstNode) { + + TMergeASTNode orderByAstNode = (TMergeASTNode) fromAstNode; + + if (listIterator.hasNext()) { + ISQLTokenData sqlTokenData = listIterator.next(); + + if (null == sqlTokenData.getSubTokenBean() + && sqlTokenData.getToken().getData() == ISQLSyntax.SQL_MULTILINE_COMMENT) { + TSqlNode lSqlHint = new TSqlNode(); + lSqlHint.setNodeText(sqlTokenData.getTokenStr()); + ParserUtils.addCommentsR(listIterator, lSqlHint); + orderByAstNode.setHintInfo(lSqlHint); + } else { + listIterator.previous(); + } + } else { + ParserUtils.addCommentsR(listIterator, orderByAstNode.getKeywordNode()); + } + + orderByAstNode.setInto(ParserUtils.handleToken(listIterator, "into")); + + Set endTableName = new HashSet(Arrays.asList("using")); + endTableName.addAll(getKeywordList()); + + orderByAstNode.setSrcTable(NodeExpressionConverter.parseAndGetExpression(listIterator, endTableName)); + + orderByAstNode.setUsing(ParserUtils.handleToken(listIterator, "using")); + + Set onEndList = new HashSet(Arrays.asList("on")); + onEndList.addAll(getKeywordList()); + + orderByAstNode.setDestTable(NodeExpressionConverter.parseAndGetExpression(listIterator, onEndList)); + + orderByAstNode.setOn(ParserUtils.handleToken(listIterator, "on")); + + orderByAstNode.setOnStartBracket(ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_BRACKET_START)); + + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + Set lineBreakSet = new HashSet(Arrays.asList(SQLFoldingConstants.SQL_BRACKET_END)); + lineBreakSet.addAll(getKeywordList()); + return new WhereCluaseListParser(lineBreakSet); + } + + /** + * Prepare AST after list item. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTAfterListItem(ListIterator listIterator, TBasicASTNode fromAstNode) { + TMergeASTNode orderByAstNode = (TMergeASTNode) fromAstNode; + orderByAstNode.setOnEndBracket(ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_BRACKET_END)); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/merge/ast/MergeWhenMatchedASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/merge/ast/MergeWhenMatchedASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..11f2f7b683ae167f1a06c0d0c14328ddfa282a7a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/merge/ast/MergeWhenMatchedASTNodeParser.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.merge.ast; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.condition.ConditionBreakIf; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeExpressionConverter; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.merge.TMergeWhenASTNode; + +/** + * Title: WithASTNodeParser + * + * @since 3.0.0 + */ +public class MergeWhenMatchedASTNodeParser extends BasicASTNodeParser { + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TMergeWhenASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_WHEN; + } + + /** + * Prepare AST other stmt object. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTOtherStmtObject(ListIterator listIterator, TBasicASTNode fromAstNode) { + + TMergeWhenASTNode orderByAstNode = (TMergeWhenASTNode) fromAstNode; + + ConditionBreakIf conditionIfWhen = new ConditionBreakIf() { + @Override + public boolean isBreakCondition(ISQLTokenData next, ListIterator listIterator) { + if (null != next.getSubTokenBean()) { + return true; + } + return false; + } + }; + + orderByAstNode.setWhenMatch(NodeExpressionConverter.parseAndGetExpression(listIterator, null, conditionIfWhen)); + + Set endTableName = new HashSet(Arrays.asList("when", "log")); + + orderByAstNode.setMatchDML(NodeExpressionConverter.parseAndGetExpression(listIterator, endTableName)); + + orderByAstNode + .setWhenNotMatch(NodeExpressionConverter.parseAndGetExpression(listIterator, null, conditionIfWhen)); + + Set insertDmlExpression = new HashSet(Arrays.asList("log")); + + orderByAstNode.setInsertDML(NodeExpressionConverter.parseAndGetExpression(listIterator, insertDmlExpression)); + + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/nodelist/AbstractNodeListParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/nodelist/AbstractNodeListParser.java new file mode 100644 index 0000000000000000000000000000000000000000..949e34a726f102c985b16457fa9aa590b8dc5907 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/nodelist/AbstractNodeListParser.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist; + +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.SQLStmtTokenListBean; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; + +/** + * + * Title: AbstractNodeListParser + * + * @since 3.0.0 + */ +public abstract class AbstractNodeListParser implements NodeListParser { + + /** + * The list break. + */ + protected Set listBreak = null; + + /** + * Instantiates a new abstract node list parser. + * + * @param lineBreakSet the line break set + */ + public AbstractNodeListParser(Set lineBreakSet) { + this.listBreak = lineBreakSet; + } + + /** + * Gets the item list. + * + * @return the item list + */ + public abstract TParseTreeNodeList getItemList(); + + /** + * Checks if is list break. + * + * @param nodeStr the node str + * @param parseCount the parse count + * @return true, if is list break + */ + @Override + public boolean isListBreak(String nodeStr, int parseCount) { + return parseCount == 0 && listBreak.contains(nodeStr.toLowerCase()); + } + + /** + * Checks if is list break with custom SQL. + * + * @param previousNotEmptyToken the previous not empty token + * @param sqlStmtTokenListBean the sql stmt token list bean + * @return true, if is list break with custom SQL + */ + @Override + public boolean isListBreakWithCustomSQL(String previousNotEmptyToken, SQLStmtTokenListBean sqlStmtTokenListBean) { + return false; + } + + /** + * Sets the exp contain stmt. + */ + public void setExpContainStmt() { + getItemList().setExpContainStmt(true); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/nodelist/FullStatementConverter.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/nodelist/FullStatementConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..4262d02edbc10d680b61795dcd6a61fa51a7d665 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/nodelist/FullStatementConverter.java @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist; + +import java.util.HashSet; +import java.util.ListIterator; +import java.util.Set; + +import org.apache.commons.lang.StringUtils; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.comm.ISQLSyntax; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserFactory; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.utils.FullNodeExpressionType; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.fullstmt.TFullListNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.fullstmt.TFullStmt; + +/** + * Title: FullStatementConverter + * + * @since 3.0.0 + */ +public class FullStatementConverter { + + /** + * Parses the and get full stmt. + * + * @param listIterator the list iterator + * @param keywordList the keyword list + * @return the t full stmt + */ + public static TFullStmt parseAndGetFullStmt(ListIterator listIterator, Set keywordList) { + TFullStmt expression = new TFullStmt(); + + TFullListNode fulllistNode = null; + + while (listIterator.hasNext()) { + ISQLTokenData next = listIterator.next(); + String tokenStr = next.getTokenStr(); + if (isStopFullNode(fulllistNode, next)) { + fulllistNode = null; + } + + if (null != next.getSubTokenBean()) { + // sub query/stmt handle + TCustomSqlStatement customSqlStmt = ParserFactory.getCustomSqlStmt(next.getSubTokenBean()); + if (null == customSqlStmt) { + fulllistNode = new TFullListNode(); + TFullStmt parseAndGetFullStmt = FullStatementConverter.parseAndGetFullStmt( + next.getSubTokenBean().getSqlTokenData().listIterator(), new HashSet()); + fulllistNode.addSqlTokenDataList(parseAndGetFullStmt); + expression.addStmtNode(fulllistNode); + fulllistNode = null; + } else if (null != fulllistNode) { + fulllistNode.addSqlTokenDataList(customSqlStmt); + } else { + ParserUtils.addCustomStmtToFullStmt(expression, customSqlStmt, listIterator); + } + continue; + } + + if (SQLFoldingConstants.SQL_DELIM_SEMICOLON.equals(tokenStr) && null != fulllistNode) { + fulllistNode.addSqlTokenDataList(next); + fulllistNode = null; + continue; + } + + // if empty char then continue; + + if (keywordList.contains(tokenStr.toLowerCase())) { + listIterator.previous(); + break; + } + + if (null == fulllistNode) { + + fulllistNode = new TFullListNode(); + expression.addStmtNode(fulllistNode); + if (next.getToken().getData() == ISQLSyntax.SQL_COMMENT) { + fulllistNode.addSqlTokenDataList(next); + fulllistNode = null; + continue; + } + } + + fulllistNode.addSQLTokenData(next); + } + + return expression; + } + + private static boolean isStopFullNode(TFullListNode fulllistNode, ISQLTokenData next) { + boolean retVal = false; + if (null != fulllistNode && fulllistNode.getExpressionType() == FullNodeExpressionType.COMMENTS) { + if (null != next.getSubTokenBean()) { + retVal = true; + } else if (next.getToken().getData() != ISQLSyntax.SQL_MULTILINE_COMMENT + && StringUtils.isNotBlank(next.getTokenStr())) { + retVal = true; + } else { + retVal = false; + } + } else if (null != fulllistNode && fulllistNode.getExpressionType() == FullNodeExpressionType.NEWLINES) { + if (null != next.getSubTokenBean()) { + retVal = true; + } else if (StringUtils.isNotBlank(next.getTokenStr())) { + retVal = true; + } else { + retVal = false; + } + } else { + retVal = false; + } + return retVal; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/nodelist/NodeExpressionConverter.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/nodelist/NodeExpressionConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..e28c640ba551fdbc609ab00e891c3b3c11668f38 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/nodelist/NodeExpressionConverter.java @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist; + +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserFactory; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.condition.ConditionBreakIf; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpressionNode; + +/** + * + * Title: NodeExpressionConverter + * + * @since 3.0.0 + */ +public class NodeExpressionConverter { + + /** + * Parses the and get expression. + * + * @param listIterator the list iterator + * @param keywordList the keyword list + * @return the t expression + */ + public static TExpression parseAndGetExpression(ListIterator listIterator, Set keywordList) { + return parseAndGetExpression(listIterator, keywordList, null); + } + + /** + * Parses the and get expression break on subobject. + * + * @param listIterator the list iterator + * @param keywordList the keyword list + * @return the t expression + */ + public static TExpression parseAndGetExpressionBreakOnSubobject(ListIterator listIterator, + Set keywordList) { + return parseAndGetExpression(listIterator, keywordList, new ConditionBreakIf() { + @Override + public boolean isBreakCondition(ISQLTokenData next, ListIterator listIterator) { + if (null != next.getSubTokenBean()) { + return true; + } + return false; + } + }); + } + + /** + * Parses the and get expression. + * + * @param listIterator the list iterator + * @param keywordList the keyword list + * @param conditionIf the condition if + * @return the t expression + */ + public static TExpression parseAndGetExpression(ListIterator listIterator, Set keywordList, + ConditionBreakIf conditionIf) { + TExpression expression = null; + + while (listIterator.hasNext()) { + ISQLTokenData next = listIterator.next(); + String tokenStr = next.getTokenStr(); + + if (null != conditionIf && conditionIf.isBreakCondition(next, listIterator)) { + listIterator.previous(); + break; + } + + if (null != next.getSubTokenBean()) { + // sub query/stmt handle + TCustomSqlStatement customSqlStmt = ParserFactory.getCustomSqlStmt(next.getSubTokenBean()); + + if (null == expression) { + expression = new TExpression(); + } + ParserUtils.addCustomStmtToExpression(expression, customSqlStmt, listIterator); + continue; + } + + // if empty char then continue; + if (ParserUtils.isTokenEmpty(next)) { + continue; + } + + if (keywordList != null && keywordList.contains(tokenStr.toLowerCase())) { + listIterator.previous(); + break; + } + + TExpressionNode expNode = new TExpressionNode(); + expNode.getExpNode().setNodeText(next.getTokenStr()); + + ParserUtils.addCommentsR(listIterator, expNode.getExpNode()); + if (null == expression) { + expression = new TExpression(); + } + expression.addExpressionNode(expNode); + + } + + return expression; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/nodelist/NodeListParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/nodelist/NodeListParser.java new file mode 100644 index 0000000000000000000000000000000000000000..b8b5f80cab2c22fb3ecb5b3d913da5b44153992b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/nodelist/NodeListParser.java @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist; + +import java.util.ListIterator; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.SQLStmtTokenListBean; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: NodeListParser + * + * @since 3.0.0 + */ +public interface NodeListParser { + + /** + * Creates the T object. + */ + void createTObject(); + + /** + * Handle node alias. + * + * @param listIterator the list iterator + * @param next the next + */ + void handleNodeAlias(ListIterator listIterator, ISQLTokenData next); + + /** + * Handle node end. + * + * @param listIterator the list iterator + * @param next the next + */ + void handleNodeEnd(ListIterator listIterator, ISQLTokenData next); + + /** + * Creates the T node. + * + * @param listIterator the list iterator + * @param next the next + * @param paramCount the param count + */ + void createTNode(ListIterator listIterator, ISQLTokenData next, int paramCount); + + /** + * Creates the T custom stmt node. + * + * @param customSqlStmt the custom sql stmt + * @param listIterator the list iterator + * @param next the next + */ + void createTCustomStmtNode(TParseTreeNode customSqlStmt, ListIterator listIterator, + ISQLTokenData next); + + /** + * Checks if is node end. + * + * @param nodeStr the node str + * @return true, if is node end + */ + boolean isNodeEnd(String nodeStr); + + /** + * Checks if is alias name. + * + * @param nodeStr the node str + * @param previousNotEmptyToken the previous not empty token + * @return true, if is alias name + */ + boolean isAliasName(String nodeStr, String previousNotEmptyToken); + + /** + * Checks if is list break. + * + * @param nodeStr the node str + * @param paramCount the param count + * @return true, if is list break + */ + boolean isListBreak(String nodeStr, int paramCount); + + /** + * Handle start end node. + * + * @param previousNotEmptyToken the previous not empty token + * @param next the next + * @param listIterator the list iterator + */ + void handleStartEndNode(String previousNotEmptyToken, ISQLTokenData next, ListIterator listIterator); + + /** + * Checks if is list break with custom SQL. + * + * @param previousNotEmptyToken the previous not empty token + * @param sqlStmtTokenListBean the sql stmt token list bean + * @return true, if is list break with custom SQL + */ + boolean isListBreakWithCustomSQL(String previousNotEmptyToken, SQLStmtTokenListBean sqlStmtTokenListBean); + + /** + * Sets the exp contain stmt. + */ + void setExpContainStmt(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/nodelist/NodeListParserConverter.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/nodelist/NodeListParserConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..2cfe6205932c1bad6821915ed27428b6498f47b6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/nodelist/NodeListParserConverter.java @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist; + +import java.util.ListIterator; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.exception.GaussDBSQLParserException; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserFactory; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; + +/** + * + * Title: NodeListParserConverter + * + * @since 3.0.0 + */ +public class NodeListParserConverter { + + /** + * Handle select list. + * + * @param listIterator the list iterator + * @param listParser the list parser + */ + public static void handleSelectList(ListIterator listIterator, NodeListParser listParser) { + // select list contains elements which is separated by , and ends when + // the from clause occurs + int paramCount = 0; + String previousNotEmptyToken = null; + while (listIterator.hasNext()) { + ISQLTokenData next = listIterator.next(); + String tokenStr = next.getTokenStr(); + if (null != next.getSubTokenBean()) { + if (listParser.isListBreakWithCustomSQL(previousNotEmptyToken, next.getSubTokenBean())) { + listIterator.previous(); + break; + } + // sub query/stmt handle + TCustomSqlStatement customSqlStmt = handleSubQuery(listIterator, listParser, next); + continue; + } + // if empty char then continue; + if (ParserUtils.isTokenEmpty(next)) { + continue; + } + if (null == tokenStr) { + continue; + } + if (listParser.isListBreak(tokenStr, paramCount)) { + listIterator.previous(); + break; + } + paramCount = handleParameterCount(listParser, paramCount, tokenStr); + if (paramCount == 0) { + if (listParser.isNodeEnd(tokenStr)) { + previousNotEmptyToken = handleNodeEnd(listIterator, listParser, next, tokenStr); + continue; + } + if (listParser.isAliasName(tokenStr, previousNotEmptyToken)) { + previousNotEmptyToken = handleNodeAlias(listIterator, listParser, next, tokenStr); + continue; + } + listParser.handleStartEndNode(previousNotEmptyToken, next, listIterator); + } + previousNotEmptyToken = createNode(listIterator, listParser, paramCount, next, tokenStr); + } + } + + private static String handleNodeAlias(ListIterator listIterator, NodeListParser listParser, + ISQLTokenData next, String tokenStr) { + String previousNotEmptyToken; + listParser.handleNodeAlias(listIterator, next); + previousNotEmptyToken = tokenStr; + return previousNotEmptyToken; + } + + private static String handleNodeEnd(ListIterator listIterator, NodeListParser listParser, + ISQLTokenData next, String tokenStr) { + String previousNotEmptyToken; + listParser.handleNodeEnd(listIterator, next); + previousNotEmptyToken = tokenStr; + return previousNotEmptyToken; + } + + private static String createNode(ListIterator listIterator, NodeListParser listParser, + int paramCount, ISQLTokenData next, String tokenStr) { + String previousNotEmptyToken; + listParser.createTNode(listIterator, next, paramCount); + previousNotEmptyToken = tokenStr; + return previousNotEmptyToken; + } + + private static int handleParameterCount(NodeListParser listParser, int paramCountParam, String tokenStr) { + int paramCount = paramCountParam; + listParser.createTObject(); + + if ("(".equalsIgnoreCase(tokenStr)) { + paramCount++; + } + if (")".equalsIgnoreCase(tokenStr)) { + paramCount--; + } + return paramCount; + } + + private static TCustomSqlStatement handleSubQuery(ListIterator listIterator, + NodeListParser listParser, ISQLTokenData next) { + TCustomSqlStatement customSqlStmt = ParserFactory.getCustomSqlStmt(next.getSubTokenBean()); + if (null == customSqlStmt) { + throw new GaussDBSQLParserException("Unable to position the statement"); + } + listParser.createTObject(); + listParser.createTCustomStmtNode(customSqlStmt, listIterator, next); + listParser.setExpContainStmt(); + return customSqlStmt; + } + + /** + * Handle declare list. + * + * @param listIterator the list iterator + * @param listParser the list parser + */ + public static void handleDeclareList(ListIterator listIterator, NodeListParser listParser) { + while (listIterator.hasNext()) { + ISQLTokenData next = listIterator.next(); + String tokenStr = next.getTokenStr(); + + // if empty char then continue; + if (ParserUtils.isTokenEmpty(next)) { + continue; + } + + if (listParser.isListBreak(tokenStr, 0)) { + listIterator.previous(); + break; + } + + listParser.createTObject(); + + if (listParser.isNodeEnd(tokenStr)) { + listParser.handleNodeEnd(listIterator, next); + continue; + } + + listParser.createTNode(listIterator, next, 0); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/nodelist/TCreateParameterList.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/nodelist/TCreateParameterList.java new file mode 100644 index 0000000000000000000000000000000000000000..9baf4b37b496dbe6f55d42d080aa1875ba4277e9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/nodelist/TCreateParameterList.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TAbstractListItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; + +/** + * + * Title: TCreateParameterList + * + * @since 3.0.0 + */ +public class TCreateParameterList extends TParseTreeNodeList { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/SelectStmtParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/SelectStmtParser.java new file mode 100644 index 0000000000000000000000000000000000000000..46487cd992a8dacdf59057c632b66fda13d9ba4d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/SelectStmtParser.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.select; + +import java.util.HashMap; +import java.util.Map; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.FromASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.WhereASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast.ConnectByASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast.FetchASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast.ForASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast.GroupByASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast.HavingASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast.LimitASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast.OffsetASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast.OrderByASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast.SelectASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast.StartWithASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast.WindowASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml.TSelectSqlStatement; + +/** + * + * Title: SelectStmtParser + * + * @since 3.0.0 + */ +public class SelectStmtParser extends AbstractStmtParser { + + private static Map> astNodeParserMap = null; + + public SelectStmtParser() { + if (null == astNodeParserMap) { + astNodeParserMap = new HashMap>(10); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_SELECT, SelectASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_FROM, FromASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_WHERE, WhereASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_START, StartWithASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_CONNECT, ConnectByASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_GROUP, GroupByASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_ORDER, OrderByASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_HAVING, HavingASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_WINDOW, WindowASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_LIMIT, LimitASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_OFFSET, OffsetASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_FETCH, FetchASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_FOR, ForASTNodeParser.class); + } + } + + @Override + public TCustomSqlStatement getCustomSqlStatement() { + return new TSelectSqlStatement(); + } + + @Override + protected Map> getAstNodeParserMap() { + return astNodeParserMap; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/ConnectByASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/ConnectByASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..f557534c1759539a485d8843909dc096b84f87c5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/ConnectByASTNodeParser.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast; + +import java.util.ListIterator; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.WhereCluaseListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select.TConnectByASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: ConnectByASTNodeParser + * + * @since 3.0.0 + */ +public class ConnectByASTNodeParser extends BasicASTNodeParser { + + /** + * Prepare AST other stmt object. + * + * @param listIterator the list iterator + * @param basicAstNode the basic ast node + */ + protected void prepareASTOtherStmtObject(ListIterator listIterator, TBasicASTNode basicAstNode) { + TConnectByASTNode connectByAstNode = (TConnectByASTNode) basicAstNode; + TSqlNode lBy = ParserUtils.handleToken(listIterator, "by"); + connectByAstNode.setBy(lBy); + } + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TConnectByASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_CONNECT; + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + return new WhereCluaseListParser(getKeywordList()); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/FetchASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/FetchASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..541e735fe2d0802350f6d2150f2342df3c33f9e5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/FetchASTNodeParser.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select.TFetchASTNode; + +/** + * + * Title: FetchASTNodeParser + * + * Description: The Class FetchASTNodeParser. + * + * @since 3.0.0 + */ +public class FetchASTNodeParser extends LimitASTNodeParser { + + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_FETCH; + } + + @Override + public TBasicASTNode getASTNodeBean() { + return new TFetchASTNode(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/ForASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/ForASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..75b7f40e8060ba63c4d55f20d031e4388e161ade --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/ForASTNodeParser.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select.TForASTNode; + +/** + * + * Title: ForASTNodeParser + * + * @since 3.0.0 + */ +public class ForASTNodeParser extends LimitASTNodeParser { + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_FOR; + } + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TForASTNode(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/GroupByASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/GroupByASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..a80920ad7558d67fca94e10189cec2cc5c94fa09 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/GroupByASTNodeParser.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast; + +import java.util.ListIterator; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.SelectResultListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select.TGroupByASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: GroupByASTNodeParser + * + * @since 3.0.0 + */ +public class GroupByASTNodeParser extends BasicASTNodeParser { + + /** + * Prepare AST other stmt object. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTOtherStmtObject(ListIterator listIterator, TBasicASTNode fromAstNode) { + TGroupByASTNode groupByAstNode = (TGroupByASTNode) fromAstNode; + TSqlNode lBy = ParserUtils.handleToken(listIterator, "BY"); + groupByAstNode.setBy(lBy); + + } + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TGroupByASTNode getASTNodeBean() { + return new TGroupByASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_GROUP; + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + return new SelectResultListParser(getKeywordList()); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/HavingASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/HavingASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..ad7e5e621e4f7b11b6d5562a03aeb1bfe643e645 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/HavingASTNodeParser.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.WhereCluaseListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select.THavingASTNode; + +/** + * + * Title: HavingASTNodeParser + * + * @since 3.0.0 + */ +public class HavingASTNodeParser extends BasicASTNodeParser { + + @Override + public TBasicASTNode getASTNodeBean() { + return new THavingASTNode(); + } + + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_HAVING; + } + + @Override + public AbstractNodeListParser getNodeListParser() { + + return new WhereCluaseListParser(getKeywordList()); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/LimitASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/LimitASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..e5282e527b973bd728a2a61b4a44ed37730f8814 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/LimitASTNodeParser.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast; + +import java.util.ListIterator; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeExpressionConverter; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.limit.TLimitASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; + +/** + * + * Title: LimitASTNodeParser + * + * @since 3.0.0 + */ +public class LimitASTNodeParser extends BasicASTNodeParser { + + /** + * Prepare AST other stmt object. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTOtherStmtObject(ListIterator listIterator, TBasicASTNode fromAstNode) { + TLimitASTNode lTLimitASTNode = (TLimitASTNode) fromAstNode; + TExpression parseAndGetExpression = NodeExpressionConverter.parseAndGetExpression(listIterator, + getKeywordList()); + lTLimitASTNode.setLimitExpression(parseAndGetExpression); + } + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TLimitASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_LIMIT; + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/OffsetASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/OffsetASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..af81768bc230acc952838c3e1eb24ca125419049 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/OffsetASTNodeParser.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.limit.TOffsetASTNode; + +/** + * Title: OffsetASTNodeParser + * + * @since 3.0.0 + */ +public class OffsetASTNodeParser extends LimitASTNodeParser { + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_OFFSET; + } + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TOffsetASTNode(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/OrderByASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/OrderByASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..59da1c78cf89351084be4ef1bde4925c9cc06131 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/OrderByASTNodeParser.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast; + +import java.util.ListIterator; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.OrderByListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.common.TOrderByASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: OrderByASTNodeParser + * + * @since 3.0.0 + */ +public class OrderByASTNodeParser extends BasicASTNodeParser { + + /** + * Prepare AST other stmt object. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTOtherStmtObject(ListIterator listIterator, TBasicASTNode fromAstNode) { + + TOrderByASTNode orderByAstNode = (TOrderByASTNode) fromAstNode; + + TSqlNode lSiblings = ParserUtils.handleToken(listIterator, "SIBLINGS"); + if (lSiblings != null) { + orderByAstNode.setSIBLINGS(lSiblings); + } + + TSqlNode lBy = ParserUtils.handleToken(listIterator, "BY"); + if (lBy != null) { + orderByAstNode.setBy(lBy); + } + + } + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TOrderByASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_ORDER; + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + return new OrderByListParser(getKeywordList()); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/SelectASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/SelectASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..f78d7e557d2201ff629a7a4904cf21c95910adef --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/SelectASTNodeParser.java @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast; + +import java.util.Arrays; +import java.util.ListIterator; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.comm.ISQLSyntax; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeListParserConverter; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.SelectResultListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.common.TOrderByASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select.TSelectASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: SelectASTNodeParser + * + * @since 3.0.0 + */ +public class SelectASTNodeParser extends AbstractASTNodeParser { + + /** + * Prepare AST stmt object. + * + * @param listIterator the list iterator + * @return the t select AST node + */ + public TSelectASTNode prepareASTStmtObject(ListIterator listIterator) { + + TSelectASTNode selectAstNode = new TSelectASTNode(); + + TSqlNode lSelect = ParserUtils.handleToken(listIterator, "SELECT", false); + selectAstNode.setKeywordNode(lSelect); + + if (listIterator.hasNext()) { + ISQLTokenData sqlTokenData = listIterator.next(); + + if (null == sqlTokenData.getSubTokenBean() + && sqlTokenData.getToken().getData() == ISQLSyntax.SQL_MULTILINE_COMMENT) { + TSqlNode lSqlHint = new TSqlNode(); + lSqlHint.setNodeText(sqlTokenData.getTokenStr()); + ParserUtils.addCommentsR(listIterator, lSqlHint); + selectAstNode.setHintInfo(lSqlHint); + } else { + listIterator.previous(); + } + } else { + ParserUtils.addCommentsR(listIterator, lSelect); + } + + // check for the SQL_CALC_FOUND_ROWS + + TSqlNode sqlCalcRows = ParserUtils.handleToken(listIterator, "SQL_CALC_FOUND_ROWS"); + if (null != sqlCalcRows) { + selectAstNode.setSqlCalcFoundRows(sqlCalcRows); + } + + // check for the SQL_CALC_FOUND_ROWS + TSqlNode selectDistinct = ParserUtils.handleToken(listIterator, Arrays.asList("distinct", "all")); + if (null != selectDistinct) { + selectAstNode.setDistinct(selectDistinct); + } + + // code to find the columns till found the from cluase, select + // expression + + SelectResultListParser lSelectResultListParser = new SelectResultListParser(getKeywordList()); + + NodeListParserConverter.handleSelectList(listIterator, lSelectResultListParser); + + TParseTreeNodeList handleSelectList = lSelectResultListParser.getItemList(); + if (null != handleSelectList) { + selectAstNode.setItemList(handleSelectList); + } + + return selectAstNode; + + } + + /** + * Prepare AST other stmt object. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTOtherStmtObject(ListIterator listIterator, TBasicASTNode fromAstNode) { + + TOrderByASTNode orderByAstNode = (TOrderByASTNode) fromAstNode; + + TSqlNode lSiblings = ParserUtils.handleToken(listIterator, "SIBLINGS"); + if (lSiblings != null) { + orderByAstNode.setSIBLINGS(lSiblings); + } + + TSqlNode lBy = ParserUtils.handleToken(listIterator, "BY"); + if (lSiblings != null) { + orderByAstNode.setBy(lBy); + } + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/StartWithASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/StartWithASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..10951e5b89558d0fd9f34a717549760d234a6a81 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/StartWithASTNodeParser.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast; + +import java.util.ListIterator; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.WhereCluaseListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select.TStartWithASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: StartWithASTNodeParser + * + * @since 3.0.0 + */ +public class StartWithASTNodeParser extends BasicASTNodeParser { + + /** + * Prepare AST other stmt object. + * + * @param listIterator the list iterator + * @param basicAstNode the basic ast node + */ + protected void prepareASTOtherStmtObject(ListIterator listIterator, TBasicASTNode basicAstNode) { + TStartWithASTNode startWithAstNode = (TStartWithASTNode) basicAstNode; + TSqlNode lWith = ParserUtils.handleToken(listIterator, "with"); + startWithAstNode.setWith(lWith); + } + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TStartWithASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_START; + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + return new WhereCluaseListParser(getKeywordList()); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/WindowASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/WindowASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..d5f834b21e8d98ea0b22f9b52dfc60fb61552f39 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/ast/WindowASTNodeParser.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.select.ast; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.with.nodelist.WithItemListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select.TWindowASTNode; + +/** + * + * Title: WindowASTNodeParser + * + * Description: The Class WindowASTNodeParser. + * + * @since 3.0.0 + */ +public class WindowASTNodeParser extends BasicASTNodeParser { + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_WINDOW; + } + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TWindowASTNode(); + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + return new WithItemListParser(getKeywordList()); + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/nodelist/FromItemListParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/nodelist/FromItemListParser.java new file mode 100644 index 0000000000000000000000000000000000000000..e141a5d7eff142663a152f37de2963bf0a968557 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/nodelist/FromItemListParser.java @@ -0,0 +1,310 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.ListIterator; +import java.util.Set; + +import org.apache.commons.lang.StringUtils; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.exception.GaussDBSQLParserException; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeListParserConverter; +import org.opengauss.mppdbide.gauss.sqlparser.parser.utils.ExpressionTypeEnum; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpressionNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TWhereClause; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.from.TFromItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.from.TFromItemList; + +/** + * Title: FromItemListParser + * + * @since 3.0.0 + */ +public class FromItemListParser extends AbstractNodeListParser { + + private TFromItemList fromItemList = new TFromItemList(); + + private TFromItem fromItem = null; + + private TExpression table = null; + + private TExpression aliasExpression = null; + + private TExpression joinType = null; + + private TWhereClause joinCondition = null; + + private boolean inEndNode = false; + + /** + * Instantiates a new from item list parser. + * + * @param lineBreakSet the line break set + */ + public FromItemListParser(Set lineBreakSet) { + super(lineBreakSet); + } + + /** + * Creates the T object. + */ + @Override + public void createTObject() { + if (fromItem == null) { + fromItem = new TFromItem(); + table = new TExpression(); + + fromItem.setTable(table); + fromItemList.addResultColumn(fromItem); + } + } + + /** + * Handle node alias. + * + * @param listIterator the list iterator + * @param next the next + */ + @Override + public void handleNodeAlias(ListIterator listIterator, ISQLTokenData next) { + table = null; + TSqlNode asNode = new TSqlNode(); + asNode.setNodeText(next.getTokenStr()); + fromItem.setAs(asNode); + ParserUtils.addCommentsR(listIterator, asNode); + + addNodeEndExpression(); + } + + private void addNodeEndExpression() { + table = null; + aliasExpression = new TExpression(); + fromItem.setAliasName(aliasExpression); + inEndNode = true; + } + + /** + * Handle node end. + * + * @param listIterator the list iterator + * @param next the next + */ + @Override + public void handleNodeEnd(ListIterator listIterator, ISQLTokenData next) { + inEndNode = false; + if (",".equalsIgnoreCase(next.getTokenStr())) { + TSqlNode seperator = new TSqlNode(); + seperator.setNodeText(next.getTokenStr()); + ParserUtils.addCommentsR(listIterator, seperator); + fromItem.setSeperator(seperator); + fromItem = null; + aliasExpression = null; + return; + } + + if ("JOIN".equalsIgnoreCase(next.getTokenStr())) { + table = null; + if (joinType == null) { + joinType = new TExpression(ExpressionTypeEnum.LIST); + fromItemList.setJoinStmt(true); + fromItem.setJoinType(joinType); + } + ParserUtils.addExpressionNode(joinType, listIterator, next); + joinType = null; + fromItem = null; + aliasExpression = null; + return; + } + } + + /** + * Creates the T node. + * + * @param listIterator the list iterator + * @param next the next + * @param paramCount the param count + */ + @Override + public void createTNode(ListIterator listIterator, ISQLTokenData next, int paramCount) { + String tokenStr = next.getTokenStr(); + + if (paramCount == 0) { + if ("ON".equalsIgnoreCase(tokenStr)) { + table = null; + TSqlNode onCluase = new TSqlNode(); + onCluase.setNodeText(tokenStr); + fromItem.setOn(onCluase); + ParserUtils.addCommentsR(listIterator, onCluase); + joinCondition = new TWhereClause(); + + Set lineBreakSet = new HashSet( + Arrays.asList("where", "left", "right", "full", "inner", "outer", ",", "join")); + lineBreakSet.addAll(listBreak); + + WhereCluaseListParser lWhereCluaseListParser = new WhereCluaseListParser(lineBreakSet); + + NodeListParserConverter.handleSelectList(listIterator, lWhereCluaseListParser); + joinCondition = (TWhereClause) lWhereCluaseListParser.getItemList(); + fromItem.setJoinCondition(joinCondition); + joinCondition = null; + + return; + } + + if ("LEFT".equalsIgnoreCase(tokenStr) || "RIGHT".equalsIgnoreCase(tokenStr) + || "FULL".equalsIgnoreCase(tokenStr) || "INNER".equalsIgnoreCase(tokenStr) + || "OUTER".equalsIgnoreCase(tokenStr)) { + table = null; + if (joinType == null) { + joinType = new TExpression(ExpressionTypeEnum.LIST); + fromItemList.setJoinStmt(true); + fromItem.setJoinType(joinType); + } + + ParserUtils.addExpressionNode(joinType, listIterator, next); + + return; + } + + } + + if (table != null) { + TExpressionNode tableName = new TExpressionNode(); + tableName.getExpNode().setNodeText(next.getTokenStr()); + ParserUtils.addCommentsR(listIterator, tableName.getExpNode()); + table.addExpressionNode(tableName); + } else if (null != aliasExpression) { + ParserUtils.addExpressionNode(aliasExpression, listIterator, next); + } else { + throw new GaussDBSQLParserException("Unable to position the statement in From Cluase"); + } + } + + /** + * Checks if is node end. + * + * @param nodeStr the node str + * @return true, if is node end + */ + @Override + public boolean isNodeEnd(String nodeStr) { + return ",".equalsIgnoreCase(nodeStr) || "JOIN".equalsIgnoreCase(nodeStr); + } + + /** + * Checks if is alias name. + * + * @param nodeStr the node str + * @param previousNotEmptyToken the previous not empty token + * @return true, if is alias name + */ + @Override + public boolean isAliasName(String nodeStr, String previousNotEmptyToken) { + return !isInEndNode() && "AS".equalsIgnoreCase(nodeStr); + } + + /** + * Sets the list break. + * + * @param listBreak the new list break + */ + public void setListBreak(Set listBreak) { + this.listBreak = listBreak; + } + + /** + * Creates the T custom stmt node. + * + * @param customSqlStmt the custom sql stmt + * @param listIterator the list iterator + * @param next the next + */ + @Override + public void createTCustomStmtNode(TParseTreeNode customSqlStmt, ListIterator listIterator, + ISQLTokenData next) { + + if (null != table) { + TExpressionNode expNode = new TExpressionNode(); + expNode.setCustomStmt(customSqlStmt); + table.addExpressionNode(expNode); + ParserUtils.addCommentsR(listIterator, customSqlStmt); + } else { + throw new GaussDBSQLParserException( + "Unable to position the statement in From Cluase createTCustomStmtNode"); + } + + } + + /** + * Gets the item list. + * + * @return the item list + */ + @Override + public TParseTreeNodeList getItemList() { + return fromItemList; + } + + /** + * Handle start end node. + * + * @param previousNotEmptyToken the previous not empty token + * @param next the next + * @param listIterator the list iterator + */ + public void handleStartEndNode(String previousNotEmptyToken, ISQLTokenData next, + ListIterator listIterator) { + + if (listIterator.hasPrevious()) { + ISQLTokenData previous = listIterator.previous(); + if (listIterator.hasPrevious()) { + previous = listIterator.previous(); + listIterator.next(); + } + + if (StringUtils.isBlank(previous.getTokenStr()) && ParserUtils.isMathOperator(previousNotEmptyToken)) { + + } else if (StringUtils.isBlank(previous.getTokenStr()) && ParserUtils.isMathOperator(next.getTokenStr())) { + + } else if (StringUtils.isBlank(previous.getTokenStr()) && null != table && table.getExpList().size() > 0) { + addNodeEndExpression(); + } + + listIterator.next(); + + } + + } + + /** + * Checks if is in end node. + * + * @return true, if is in end node + */ + public boolean isInEndNode() { + return inEndNode; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/nodelist/OrderByListParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/nodelist/OrderByListParser.java new file mode 100644 index 0000000000000000000000000000000000000000..861e802001e4e06eb2d1f13d56c73ef1674a763f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/nodelist/OrderByListParser.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist; + +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TResultColumn; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.order.TOrderByItem; + +/** + * + * Title: OrderByListParser + * + * @since 3.0.0 + */ +public class OrderByListParser extends SelectResultListParser { + + /** + * Instantiates a new order by list parser. + * + * @param lineBreakSet the line break set + */ + public OrderByListParser(Set lineBreakSet) { + super(lineBreakSet); + + } + + /** + * Checks if is alias name. + * + * @param nodeStr the node str + * @return true, if is alias name + */ + public boolean isAliasName(String nodeStr) { + return !isInEndNode() && ("AS".equalsIgnoreCase(nodeStr) || "ASC".equalsIgnoreCase(nodeStr) + || "DESC".equalsIgnoreCase(nodeStr)); + } + + /** + * Gets the result column. + * + * @return the result column + */ + protected TResultColumn getResultColumn() { + return new TOrderByItem(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/nodelist/SelectResultListParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/nodelist/SelectResultListParser.java new file mode 100644 index 0000000000000000000000000000000000000000..a77419704cf52a2a438eb0df29718db8b64dbbdb --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/nodelist/SelectResultListParser.java @@ -0,0 +1,261 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist; + +import java.util.ListIterator; +import java.util.Set; + +import org.apache.commons.lang.StringUtils; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.exception.GaussDBSQLParserException; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpressionNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TResultColumn; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TResultColumnList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: SelectResultListParser + * + * @since 3.0.0 + */ +public class SelectResultListParser extends AbstractNodeListParser { + + /** + * The result column. + */ + protected TResultColumn resultColumn = null; + + /** + * The expression. + */ + protected TExpression expression = null; + + /** + * The end node expression. + */ + protected TExpression endNodeExpression = null; + + /** + * The in end node. + */ + protected boolean inEndNode = false; + + private TResultColumnList resultColumnList = new TResultColumnList(); + + /** + * Instantiates a new select result list parser. + * + * @param lineBreakSet the line break set + */ + public SelectResultListParser(Set lineBreakSet) { + super(lineBreakSet); + } + + /** + * Creates the T object. + */ + public void createTObject() { + // create and then it is the start of the expression + if (null == resultColumn) { + resultColumn = getResultColumn(); + expression = new TExpression(); + endNodeExpression = null; + resultColumn.setExpression(expression); + + resultColumnList.addResultColumn(resultColumn); + } + } + + /** + * Gets the result column. + * + * @return the result column + */ + protected TResultColumn getResultColumn() { + return new TResultColumn(); + } + + /** + * Handle node alias. + * + * @param listIterator the list iterator + * @param next the next + */ + public void handleNodeAlias(ListIterator listIterator, ISQLTokenData next) { + // close the TExpressionNode + TSqlNode asCluase = new TSqlNode(); + asCluase.setNodeText(next.getTokenStr()); + resultColumn.setAs(asCluase); + + ParserUtils.addCommentsR(listIterator, asCluase); + addNodeEndExpression(); + } + + private void addNodeEndExpression() { + expression = null; + endNodeExpression = new TExpression(); + resultColumn.setEndNode(endNodeExpression); + inEndNode = true; + } + + /** + * Handle node end. + * + * @param listIterator the list iterator + * @param next the next + */ + public void handleNodeEnd(ListIterator listIterator, ISQLTokenData next) { + TSqlNode seperator = new TSqlNode(); + seperator.setNodeText(next.getTokenStr()); + ParserUtils.addCommentsR(listIterator, seperator); + resultColumn.setSeperator(seperator); + + resultColumn = null; + expression = null; + endNodeExpression = null; + inEndNode = false; + } + + /** + * Gets the item list. + * + * @return the item list + */ + @Override + public TParseTreeNodeList getItemList() { + return resultColumnList; + } + + /** + * Creates the T node. + * + * @param listIterator the list iterator + * @param next the next + * @param paramCount the param count + */ + public void createTNode(ListIterator listIterator, ISQLTokenData next, int paramCount) { + + TExpressionNode expNode = new TExpressionNode(); + expNode.getExpNode().setNodeText(next.getTokenStr()); + + if (null != expression) { + + expression.addExpressionNode(expNode); + + } else { + + endNodeExpression.addExpressionNode(expNode); + + } + + ParserUtils.addCommentsR(listIterator, expNode.getExpNode()); + + } + + /** + * Checks if is node end. + * + * @param nodeStr the node str + * @return true, if is node end + */ + public boolean isNodeEnd(String nodeStr) { + return ",".equalsIgnoreCase(nodeStr); + } + + /** + * Checks if is alias name. + * + * @param nodeStr the node str + * @param previousNotEmptyToken the previous not empty token + * @return true, if is alias name + */ + public boolean isAliasName(String nodeStr, String previousNotEmptyToken) { + return !isInEndNode() && "AS".equalsIgnoreCase(nodeStr); + } + + /** + * Creates the T custom stmt node. + * + * @param customSqlStmt the custom sql stmt + * @param listIterator the list iterator + * @param next the next + */ + @Override + public void createTCustomStmtNode(TParseTreeNode customSqlStmt, ListIterator listIterator, + ISQLTokenData next) { + + if (null != expression) { + ParserUtils.addCustomStmtToExpression(expression, customSqlStmt, listIterator); + } else if (null != endNodeExpression) { + + ParserUtils.addCustomStmtToExpression(endNodeExpression, customSqlStmt, listIterator); + + } else { + throw new GaussDBSQLParserException("Unable to position the statement"); + + } + + } + + /** + * Handle start end node. + * + * @param previousNotEmptyToken the previous not empty token + * @param next the next + * @param listIterator the list iterator + */ + public void handleStartEndNode(String previousNotEmptyToken, ISQLTokenData next, + ListIterator listIterator) { + + if (listIterator.hasPrevious()) { + ISQLTokenData previous = listIterator.previous(); + if (listIterator.hasPrevious()) { + previous = listIterator.previous(); + listIterator.next(); + } + + if (StringUtils.isBlank(previous.getTokenStr()) && ParserUtils.isMathOperator(previousNotEmptyToken)) { + + } else if (StringUtils.isBlank(previous.getTokenStr()) && ParserUtils.isMathOperator(next.getTokenStr())) { + + } else if (StringUtils.isBlank(previous.getTokenStr()) && null != expression + && expression.getExpList().size() > 0) { + addNodeEndExpression(); + } + + listIterator.next(); + + } + + } + + /** + * Checks if is in end node. + * + * @return true, if is in end node + */ + public boolean isInEndNode() { + return inEndNode; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/nodelist/WhereCluaseListParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/nodelist/WhereCluaseListParser.java new file mode 100644 index 0000000000000000000000000000000000000000..7d5148dd081b096f74ed1e532b2ae091c34c8ae1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/select/nodelist/WhereCluaseListParser.java @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist; + +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpressionNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TWhereClause; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.WhereClauseItem; + +/** + * + * Title: WhereCluaseListParser + * + * @since 3.0.0 + */ +public class WhereCluaseListParser extends AbstractNodeListParser { + + private TWhereClause resultColumnList = new TWhereClause(); + + private TExpression expression = null; + + private WhereClauseItem whereItem = null; + + /** + * Instantiates a new where cluase list parser. + * + * @param lineBreakSet the line break set + */ + public WhereCluaseListParser(Set lineBreakSet) { + super(lineBreakSet); + } + + /** + * Creates the T object. + */ + public void createTObject() { + // create and then it is the start of the expression + if (null == whereItem) { + whereItem = new WhereClauseItem(); + expression = new TExpression(); + whereItem.setWhereExpression(expression); + resultColumnList.addResultColumn(whereItem); + } + } + + /** + * Handle node alias. + * + * @param listIterator the list iterator + * @param next the next + */ + public void handleNodeAlias(ListIterator listIterator, ISQLTokenData next) { + } + + /** + * Handle node end. + * + * @param listIterator the list iterator + * @param next the next + */ + public void handleNodeEnd(ListIterator listIterator, ISQLTokenData next) { + + TSqlNode conditionSep = new TSqlNode(); + conditionSep.setNodeText(next.getTokenStr()); + ParserUtils.addCommentsR(listIterator, conditionSep); + whereItem.setConSep(conditionSep); + + whereItem = null; + createTObject(); + + } + + /** + * Gets the item list. + * + * @return the item list + */ + @Override + public TParseTreeNodeList getItemList() { + return resultColumnList; + } + + /** + * Creates the T node. + * + * @param listIterator the list iterator + * @param next the next + * @param paramCount the param count + */ + public void createTNode(ListIterator listIterator, ISQLTokenData next, int paramCount) { + TExpressionNode expNode = new TExpressionNode(); + expNode.getExpNode().setNodeText(next.getTokenStr()); + ParserUtils.addCommentsR(listIterator, expNode.getExpNode()); + expression.addExpressionNode(expNode); + + } + + /** + * Checks if is node end. + * + * @param nodeStr the node str + * @return true, if is node end + */ + public boolean isNodeEnd(String nodeStr) { + return ParserUtils.getWhereSeperateList().contains(nodeStr.toUpperCase()); + } + + /** + * Checks if is alias name. + * + * @param nodeStr the node str + * @param previousNotEmptyToken the previous not empty token + * @return true, if is alias name + */ + public boolean isAliasName(String nodeStr, String previousNotEmptyToken) { + return "AS".equalsIgnoreCase(nodeStr); + } + + /** + * Creates the T custom stmt node. + * + * @param customSqlStmt the custom sql stmt + * @param listIterator the list iterator + * @param next the next + */ + @Override + public void createTCustomStmtNode(TParseTreeNode customSqlStmt, ListIterator listIterator, + ISQLTokenData next) { + if (null != expression) { + TExpressionNode expNode = new TExpressionNode(); + expNode.setCustomStmt(customSqlStmt); + expression.addExpressionNode(expNode); + ParserUtils.addCommentsR(listIterator, customSqlStmt); + } else { + throw new IllegalStateException("Unable to position the statement"); + } + + } + + /** + * Handle start end node. + * + * @param previousNotEmptyToken the previous not empty token + * @param next the next + * @param listIterator the list iterator + */ + @Override + public void handleStartEndNode(String previousNotEmptyToken, ISQLTokenData next, + ListIterator listIterator) { + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/union/UnionStmtParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/union/UnionStmtParser.java new file mode 100644 index 0000000000000000000000000000000000000000..1fa0aef67299d8298471a86a4b2582e023111637 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/union/UnionStmtParser.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.union; + +import java.util.HashMap; +import java.util.Map; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.union.ast.UnionASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.common.TUnionSqlStatement; + +/** + * Title: WithStmtParser + * + * @since 3.0.0 + */ +public class UnionStmtParser extends AbstractStmtParser { + + private static Map> astNodeParserMap = null; + + public UnionStmtParser() { + if (null == astNodeParserMap) { + astNodeParserMap = new HashMap>(10); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_UNION, UnionASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_INTERSECT, UnionASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_MINUS, UnionASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_EXCEPT, UnionASTNodeParser.class); + } + } + + @Override + public TCustomSqlStatement getCustomSqlStatement() { + return new TUnionSqlStatement(); + } + + @Override + protected Map> getAstNodeParserMap() { + return astNodeParserMap; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/union/ast/UnionASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/union/ast/UnionASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..4358a7ddd210b8a8d9c08a92d27a94528a3fb949 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/union/ast/UnionASTNodeParser.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.union.ast; + +import java.util.Arrays; +import java.util.ListIterator; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.NodeExpressionConverter; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.union.TUnionASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * Title: WithASTNodeParser + * + * @since 3.0.0 + */ +public class UnionASTNodeParser extends BasicASTNodeParser { + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TUnionASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_UNION; + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + return null; + } + + /** + * returns the keyword token from the given list iterator. + * + * @param listIterator the list iterator + * @return the keyword token + */ + protected TSqlNode getKeywordToken(ListIterator listIterator) { + return ParserUtils.handleToken(listIterator, + Arrays.asList(SQLFoldingConstants.SQL_KEYWORD_UNION, SQLFoldingConstants.SQL_KEYWORD_INTERSECT, + SQLFoldingConstants.SQL_KEYWORD_MINUS, SQLFoldingConstants.SQL_KEYWORD_EXCEPT)); + } + + /** + * Prepare AST other stmt object. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTOtherStmtObject(ListIterator listIterator, TBasicASTNode fromAstNode) { + + TUnionASTNode orderByAstNode = (TUnionASTNode) fromAstNode; + + orderByAstNode.setRemainingStmt(NodeExpressionConverter.parseAndGetExpression(listIterator, null)); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/update/UpdateStmtParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/update/UpdateStmtParser.java new file mode 100644 index 0000000000000000000000000000000000000000..c67f80ccdd111277891c110264b9f3117190abba --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/update/UpdateStmtParser.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.update; + +import java.util.HashMap; +import java.util.Map; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.FromASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.ReturningASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.WhereASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.update.ast.UpdateSetASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.update.ast.UpdateASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml.TUpdateSqlStatement; + +/** + * + * Title: UpdateStmtParser + * + * @since 3.0.0 + */ +public class UpdateStmtParser extends AbstractStmtParser { + + private static Map> astNodeParserMap = null; + + public UpdateStmtParser() { + if (null == astNodeParserMap) { + astNodeParserMap = new HashMap>(10); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_UPDATE, UpdateASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_SET, UpdateSetASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_FROM, FromASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_WHERE, WhereASTNodeParser.class); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_RETURNING, ReturningASTNodeParser.class); + + } + } + + @Override + public TCustomSqlStatement getCustomSqlStatement() { + return new TUpdateSqlStatement(); + } + + @Override + protected Map> getAstNodeParserMap() { + return astNodeParserMap; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/update/ast/UpdateASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/update/ast/UpdateASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..99275433e9383b34f4c0ba57db38cdd3d764e343 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/update/ast/UpdateASTNodeParser.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.update.ast; + +import java.util.ListIterator; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.FromItemListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.update.TUpdateIntoASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: UpdateASTNodeParser + * + * @since 3.0.0 + */ +public class UpdateASTNodeParser extends BasicASTNodeParser { + + /** + * Prepare AST other stmt object. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTOtherStmtObject(ListIterator listIterator, TBasicASTNode fromAstNode) { + + TUpdateIntoASTNode groupByAstNode = (TUpdateIntoASTNode) fromAstNode; + + TSqlNode only = ParserUtils.handleToken(listIterator, SQLFoldingConstants.SQL_KEYWORD_ONLY); + groupByAstNode.setOnly(only); + + } + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TUpdateIntoASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_UPDATE; + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + return new FromItemListParser(getKeywordList()); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/update/ast/UpdateSetASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/update/ast/UpdateSetASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..c85703ead81f020be431ad5d4c19816fc7e6899b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/update/ast/UpdateSetASTNodeParser.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.update.ast; + +import java.util.ListIterator; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.SelectResultListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.update.TUpdateSetASTNode; + +/** + * + * Title: UpdateSetASTNodeParser + * + * @since 3.0.0 + */ +public class UpdateSetASTNodeParser extends BasicASTNodeParser { + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TUpdateSetASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_SET; + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + return new SelectResultListParser(getKeywordList()) { + }; + } + + /** + * handles the StartEndNode + * + * @param previousNotEmptyToken the previousNotEmptyToken + * @param next the next + * @param listIterator the listIterator + */ + public void handleStartEndNode(String previousNotEmptyToken, ISQLTokenData next, + ListIterator listIterator) { + // do nothing + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/utils/ExpressionTypeEnum.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/utils/ExpressionTypeEnum.java new file mode 100644 index 0000000000000000000000000000000000000000..5a3f15e4810c21cc49ad095a6c2d49bad7f18c3c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/utils/ExpressionTypeEnum.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.utils; + +/** + * + * Title: ExpressionTypeEnum + * + * @since 3.0.0 + */ +public enum ExpressionTypeEnum { + NORMAL, LIST +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/utils/FullNodeExpressionType.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/utils/FullNodeExpressionType.java new file mode 100644 index 0000000000000000000000000000000000000000..af9f1ca2b1e9350f45cbeec1650da442b736b239 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/utils/FullNodeExpressionType.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.utils; + +/** + * Title: FullNodeExpressionType + * + * @since 3.0.0 + */ +public enum FullNodeExpressionType { + COMMENTS, NEWLINES, NORMAL, UNKNOWN, ASSIGNMENTS +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/with/WithStmtParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/with/WithStmtParser.java new file mode 100644 index 0000000000000000000000000000000000000000..4a7c1ca2ea17009fb9f0fe61619b409065461e36 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/with/WithStmtParser.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.with; + +import java.util.HashMap; +import java.util.Map; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.AbstractStmtParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.CTEASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.with.ast.WithASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TCustomASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml.TWithSqlStatement; + +/** + * + * Title: WithStmtParser + * + * @since 3.0.0 + */ +public class WithStmtParser extends AbstractStmtParser { + + private static Map> astNodeParserMap = null; + + /** + * Instantiates a new with stmt parser. + */ + public WithStmtParser() { + if (null == astNodeParserMap) { + astNodeParserMap = new HashMap>(10); + astNodeParserMap.put(SQLFoldingConstants.SQL_KEYWORD_WITH, WithASTNodeParser.class); + } + } + + /** + * Gets the AST parser. + * + * @param tokenStr the token str + * @param astParserMap the ast parser map + * @return the AST parser + */ + public AbstractASTNodeParser getASTParser(String tokenStr, Map> astParserMap) { + + AbstractASTNodeParser astParser = super.getASTParser(tokenStr, astParserMap); + + if (null == astParser) { + AbstractASTNodeParser lAbstractASTNodeParser = new CTEASTNodeParser(); + + return lAbstractASTNodeParser; + } + + return astParser; + } + + /** + * Gets the custom sql statement. + * + * @return the custom sql statement + */ + @Override + public TCustomSqlStatement getCustomSqlStatement() { + return new TWithSqlStatement(); + } + + /** + * Gets the ast node parser map. + * + * @return the ast node parser map + */ + @Override + protected Map> getAstNodeParserMap() { + return astNodeParserMap; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/with/ast/WithASTNodeParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/with/ast/WithASTNodeParser.java new file mode 100644 index 0000000000000000000000000000000000000000..0f84ee4688ca01434f759570c0c4d767d227b6e5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/with/ast/WithASTNodeParser.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.with.ast; + +import java.util.ListIterator; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ParserUtils; +import org.opengauss.mppdbide.gauss.sqlparser.parser.ast.BasicASTNodeParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.nodelist.AbstractNodeListParser; +import org.opengauss.mppdbide.gauss.sqlparser.parser.with.nodelist.WithItemListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.with.TWithASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: WithASTNodeParser + * + * @since 3.0.0 + */ +public class WithASTNodeParser extends BasicASTNodeParser { + + /** + * Gets the AST node bean. + * + * @return the AST node bean + */ + @Override + public TBasicASTNode getASTNodeBean() { + return new TWithASTNode(); + } + + /** + * Gets the keyword token str. + * + * @return the keyword token str + */ + @Override + public String getKeywordTokenStr() { + return SQLFoldingConstants.SQL_KEYWORD_WITH; + } + + /** + * Gets the node list parser. + * + * @return the node list parser + */ + @Override + public AbstractNodeListParser getNodeListParser() { + + return new WithItemListParser(getKeywordList()); + } + + /** + * Prepare AST other stmt object. + * + * @param listIterator the list iterator + * @param fromAstNode the from ast node + */ + protected void prepareASTOtherStmtObject(ListIterator listIterator, TBasicASTNode fromAstNode) { + + TWithASTNode orderByAstNode = (TWithASTNode) fromAstNode; + + TSqlNode lSiblings = ParserUtils.handleToken(listIterator, "RECURSIVE"); + if (lSiblings != null) { + orderByAstNode.setRecursive(lSiblings); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/with/nodelist/WithItemListParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/with/nodelist/WithItemListParser.java new file mode 100644 index 0000000000000000000000000000000000000000..37512a909b07aafb66c38da46e08250ecd6c5cae --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/parser/with/nodelist/WithItemListParser.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.parser.with.nodelist; + +import java.util.ListIterator; +import java.util.Set; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.SQLStmtTokenListBean; +import org.opengauss.mppdbide.gauss.sqlparser.parser.select.nodelist.SelectResultListParser; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TResultColumn; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.with.TWithItem; + +/** + * + * Title: WithItemListParser + * + * @since 3.0.0 + */ +public class WithItemListParser extends SelectResultListParser { + + /** + * Instantiates a new with item list parser. + * + * @param lineBreakSet the line break set + */ + public WithItemListParser(Set lineBreakSet) { + super(lineBreakSet); + + } + + /** + * Checks if is alias name. + * + * @param nodeStr the node str + * @return true, if is alias name + */ + public boolean isAliasName(String nodeStr) { + return !isInEndNode() && "AS".equalsIgnoreCase(nodeStr); + } + + /** + * Gets the result column. + * + * @return the result column + */ + protected TResultColumn getResultColumn() { + return new TWithItem(); + } + + /** + * Checks if is list break with custom SQL. + * + * @param previousNotEmptyToken the previous not empty token + * @param sqlStmtTokenListBean the sql stmt token list bean + * @return true, if is list break with custom SQL + */ + @Override + public boolean isListBreakWithCustomSQL(String previousNotEmptyToken, SQLStmtTokenListBean sqlStmtTokenListBean) { + + if (")".equalsIgnoreCase(previousNotEmptyToken)) { + return true; + } + + return false; + } + + /** + * Handle start end node. + * + * @param previousNotEmptyToken the previous not empty token + * @param next the next + * @param listIterator the list iterator + */ + public void handleStartEndNode(String previousNotEmptyToken, ISQLTokenData next, + ListIterator listIterator) { + // do nothing in case of with + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/TBasicASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/TBasicASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..0e880eb460cc5f7d5a204ce8f0178ef988540084 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/TBasicASTNode.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: TBasicASTNode + * + * @since 3.0.0 + */ +public abstract class TBasicASTNode extends TCustomASTNode { + private TSqlNode keywordNode = null; + + private TParseTreeNodeList itemList = null; + + public TSqlNode getKeywordNode() { + return keywordNode; + } + + public void setKeywordNode(TSqlNode keywordNode) { + this.keywordNode = keywordNode; + setPreviousObject(this.keywordNode); + } + + @Override + public TParseTreeNode getStartNode() { + return keywordNode; + } + + public TParseTreeNodeList getItemList() { + return itemList; + } + + public void setItemList(TParseTreeNodeList itemList) { + this.itemList = itemList; + setPreviousObject(this.itemList); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/TCustomASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/TCustomASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..1c4c6e8b4a531a636144617b357b61ca221d7b9b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/TCustomASTNode.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: TCustomASTNode + * + * @since 3.0.0 + */ +public abstract class TCustomASTNode extends TParseTreeNode { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/begin/TBeginASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/begin/TBeginASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..44fad25bbf0a82221a74abed075df41249a230a8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/begin/TBeginASTNode.java @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.begin; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.fullstmt.TFullStmt; + +/** + * Title: TBeginASTNode + * + * @since 3.0.0 + */ +public class TBeginASTNode extends TBasicASTNode { + + /** + * The full stmt. + */ + private TFullStmt tFullStmt = null; + + /** + * The exception. + */ + private TSqlNode exception = null; + + /** + * The end. + */ + private TSqlNode sqlNodeEnd = null; + + /** + * The end expression. + */ + private TExpression endExpression = null; + + /** + * The exception when list. + */ + private TParseTreeNodeList exceptionWhenList = null; + + /** + * Gets the full stmt. + * + * @return the full stmt + */ + public TFullStmt getFullStmt() { + return tFullStmt; + } + + /** + * Sets the full stmt. + * + * @param fullStmt the new full stmt + */ + public void setFullStmt(TFullStmt fullStmt) { + this.tFullStmt = fullStmt; + setPreviousObject(this.tFullStmt); + } + + /** + * Gets the end. + * + * @return the end + */ + public TSqlNode getEnd() { + return sqlNodeEnd; + } + + /** + * Sets the end. + * + * @param end the new end + */ + public void setEnd(TSqlNode end) { + this.sqlNodeEnd = end; + setPreviousObject(this.sqlNodeEnd); + } + + /** + * Gets the end expression. + * + * @return the end expression + */ + public TExpression getEndExpression() { + return endExpression; + } + + /** + * Sets the end expression. + * + * @param endExpression the new end expression + */ + public void setEndExpression(TExpression endExpression) { + this.endExpression = endExpression; + setPreviousObject(this.endExpression); + } + + /** + * Gets the exception. + * + * @return the exception + */ + public TSqlNode getException() { + return exception; + } + + /** + * Sets the exception. + * + * @param exception the new exception + */ + public void setException(TSqlNode exception) { + this.exception = exception; + setPreviousObject(this.exception); + } + + /** + * Gets the exception when list. + * + * @return the exception when list + */ + public TParseTreeNodeList getExceptionWhenList() { + return exceptionWhenList; + } + + /** + * Sets the exception when list. + * + * @param tParseTreeNodeList the new exception when list + */ + public void setExceptionWhenList(TParseTreeNodeList tParseTreeNodeList) { + this.exceptionWhenList = tParseTreeNodeList; + setPreviousObject(this.exceptionWhenList); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/begin/TDeclareASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/begin/TDeclareASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..1fb57e5031c24081d9fd22a5ff11bf15d39f7c11 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/begin/TDeclareASTNode.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.begin; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * Title: TDeclareASTNode + * + * @since 3.0.0 + */ +public class TDeclareASTNode extends TBasicASTNode { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/casestmt/TCaseASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/casestmt/TCaseASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..7883a72d8e9b57e9dc56acb6472c8340ab29b94a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/casestmt/TCaseASTNode.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.casestmt; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: TCaseASTNode + * + * @since 3.0.0 + */ +public class TCaseASTNode extends TBasicASTNode { + + private TExpression colExpression = null; + + private TSqlNode endNode = null; + + public TExpression getColExpression() { + return colExpression; + } + + public void setColExpression(TExpression colExpression) { + this.colExpression = colExpression; + setPreviousObject(this.colExpression); + } + + public TSqlNode getEndNode() { + return endNode; + } + + public void setEndNode(TSqlNode endNode) { + this.endNode = endNode; + setPreviousObject(this.endNode); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/common/TCTEASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/common/TCTEASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..4d8ca97c75bc90e6a300c7cff8f2dc470f3c4ab0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/common/TCTEASTNode.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.common; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TCustomASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: TCTEASTNode + * + * @since 3.0.0 + */ +public class TCTEASTNode extends TCustomASTNode { + + private TExpression stmtExpression = null; + + public TExpression getStmtExpression() { + return stmtExpression; + } + + public void setStmtExpression(TExpression stmtExpression) { + this.stmtExpression = stmtExpression; + } + + @Override + public TParseTreeNode getStartNode() { + return this.stmtExpression; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/common/TFromASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/common/TFromASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..3e4ef24678f525bac07889fe6827b9bec420778e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/common/TFromASTNode.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.common; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * + * Title: TFromASTNode + * + * @since 3.0.0 + */ +public class TFromASTNode extends TBasicASTNode { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/common/TOrderByASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/common/TOrderByASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..4dd34a81907280f5e98e201bbc4015047eb65916 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/common/TOrderByASTNode.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.common; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: TOrderByASTNode + * + * @since 3.0.0 + */ +public class TOrderByASTNode extends TBasicASTNode { + + private TSqlNode SIBLINGS = null; + + private TSqlNode by = null; + + public TSqlNode getSIBLINGS() { + return SIBLINGS; + } + + public void setSIBLINGS(TSqlNode sIBLINGS) { + SIBLINGS = sIBLINGS; + setPreviousObject(this.SIBLINGS); + } + + public TSqlNode getBy() { + return by; + } + + public void setBy(TSqlNode by) { + this.by = by; + setPreviousObject(this.by); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/common/TReturningASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/common/TReturningASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..b395ba4bc7923bfb3147c70b326f80e8154739b6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/common/TReturningASTNode.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.common; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * + * Title: TReturningASTNode + * + * @since 3.0.0 + */ +public class TReturningASTNode extends TBasicASTNode { +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/common/TWhereASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/common/TWhereASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..ed8e5483a82e98eac848ec8ad77bf218cc1760d9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/common/TWhereASTNode.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.common; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * + * Title: TWhereASTNode + * + * @since 3.0.0 + */ +public class TWhereASTNode extends TBasicASTNode { +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/create/TAsASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/create/TAsASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..648668cd6ef113a781aea7da72dcea2697761c8d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/create/TAsASTNode.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.create; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * Title: TAsASTNode + * + * @since 3.0.0 + */ +public class TAsASTNode extends TBasicASTNode { + + private TExpression asDefExpression = null; + + private TExpression commonExpression = null; + + private TSqlNode stratAs = null; + + private TSqlNode endAs = null; + + public TExpression getAsDefExpression() { + return asDefExpression; + } + + public void setAsDefExpression(TExpression asDefExpression) { + this.asDefExpression = asDefExpression; + setPreviousObject(this.asDefExpression); + } + + public TExpression getCommonExpression() { + return commonExpression; + } + + public void setCommonExpression(TExpression commonExpression) { + this.commonExpression = commonExpression; + setPreviousObject(this.commonExpression); + } + + public TSqlNode getStratAs() { + return stratAs; + } + + public void setStratAs(TSqlNode stratAs) { + this.stratAs = stratAs; + setPreviousObject(this.stratAs); + } + + public TSqlNode getEndAs() { + return endAs; + } + + public void setEndAs(TSqlNode endAs) { + this.endAs = endAs; + setPreviousObject(this.endAs); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/create/TCreateASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/create/TCreateASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..1207f6d017f34b8fe4afa5a509b2c131d7e89bb5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/create/TCreateASTNode.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.create; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: TCreateASTNode + * + * @since 3.0.0 + */ +public class TCreateASTNode extends TBasicASTNode { + + /** + * the text between create and Procedure and Function is maintained in the + * below expression + */ + private TExpression intermediateText = null; + + private TExpression ifNotExists = null; + + private TSqlNode procOrFunction = null; + + private TExpression procOrFuncName = null; + + private TSqlNode procStartBracket = null; + + private TSqlNode procEndBracket = null; + + private TExpression commonExpression = null; + + public TExpression getIntermediateText() { + return intermediateText; + } + + public void setIntermediateText(TExpression intermediateText) { + this.intermediateText = intermediateText; + setPreviousObject(this.intermediateText); + } + + public TSqlNode getProcOrFunction() { + return procOrFunction; + } + + public void setProcOrFunction(TSqlNode procOrFunction) { + this.procOrFunction = procOrFunction; + setPreviousObject(this.procOrFunction); + } + + public TExpression getProcOrFuncName() { + return procOrFuncName; + } + + public void setProcOrFuncName(TExpression procOrFuncName) { + this.procOrFuncName = procOrFuncName; + setPreviousObject(this.procOrFuncName); + } + + public TSqlNode getProcStartBracket() { + return procStartBracket; + } + + public void setProcStartBracket(TSqlNode procStartBracket) { + this.procStartBracket = procStartBracket; + setPreviousObject(this.procStartBracket); + } + + public TSqlNode getProcEndBracket() { + return procEndBracket; + } + + public void setProcEndBracket(TSqlNode procEndBracket) { + this.procEndBracket = procEndBracket; + setPreviousObject(this.procEndBracket); + } + + public TExpression getCommonExpression() { + return commonExpression; + } + + public void setCommonExpression(TExpression commonExpression) { + this.commonExpression = commonExpression; + setPreviousObject(this.commonExpression); + } + + public TExpression getIfNotExists() { + return ifNotExists; + } + + public void setIfNotExists(TExpression ifNotExists) { + this.ifNotExists = ifNotExists; + setPreviousObject(this.ifNotExists); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/create/TLaungageASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/create/TLaungageASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..db15fc0c912b57f1207299b71fa27bbb80f48f13 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/create/TLaungageASTNode.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.create; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; + +/** + * + * Title: TLaungageASTNode + * + * @since 3.0.0 + */ +public class TLaungageASTNode extends TBasicASTNode { + + private TExpression languageExpression = null; + private TExpression commonExpression = null; + + public TExpression getLanguageExpression() { + return languageExpression; + } + + public void setLanguageExpression(TExpression languageExpression) { + this.languageExpression = languageExpression; + setPreviousObject(this.languageExpression); + } + + public TExpression getCommonExpression() { + return commonExpression; + } + + public void setCommonExpression(TExpression commonExpression) { + this.commonExpression = commonExpression; + setPreviousObject(this.commonExpression); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/create/TReturnASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/create/TReturnASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..2f3933b49f492e760261b878231ac4491917687d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/create/TReturnASTNode.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.create; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: TReturnASTNode + * + * @since 3.0.0 + */ +public class TReturnASTNode extends TBasicASTNode { + + private TSqlNode deterministic = null; + private TSqlNode table = null; + private TExpression resultExpression = null; + + private TParseTreeNodeList returnTableList = null; + + private TExpression commonExpression = null; + + private TSqlNode returnStartBracket = null; + + private TSqlNode returnEndBracket = null; + + public TExpression getCommonExpression() { + return commonExpression; + } + + public void setCommonExpression(TExpression commonExpression) { + this.commonExpression = commonExpression; + setPreviousObject(this.commonExpression); + } + + public TExpression getResultExpression() { + return resultExpression; + } + + public void setResultExpression(TExpression resultExpression) { + this.resultExpression = resultExpression; + setPreviousObject(this.resultExpression); + } + + public TSqlNode getTable() { + return table; + } + + public void setTable(TSqlNode table) { + this.table = table; + setPreviousObject(this.table); + } + + public TSqlNode getDeterministic() { + return deterministic; + } + + public void setDeterministic(TSqlNode deterministic) { + this.deterministic = deterministic; + setPreviousObject(this.deterministic); + } + + public TParseTreeNodeList getReturnTableList() { + return returnTableList; + } + + public void setReturnTableList(TParseTreeNodeList returnTableList) { + this.returnTableList = returnTableList; + setPreviousObject(this.returnTableList); + } + + public TSqlNode getReturnStartBracket() { + return returnStartBracket; + } + + public void setReturnStartBracket(TSqlNode returnStartBracket) { + this.returnStartBracket = returnStartBracket; + setPreviousObject(this.returnStartBracket); + } + + public TSqlNode getReturnEndBracket() { + return returnEndBracket; + } + + public void setReturnEndBracket(TSqlNode returnEndBracket) { + this.returnEndBracket = returnEndBracket; + setPreviousObject(this.returnEndBracket); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/cursor/TCursorASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/cursor/TCursorASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..93a857491050a41d39c9f9cb1842441b864f7f2a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/cursor/TCursorASTNode.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.cursor; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * Title: TLoopASTNode + * + * @since 3.0.0 + */ +public class TCursorASTNode extends TBasicASTNode { + + private TExpression cursorExpression = null; + + private TSqlNode paramStartBracket = null; + + private TSqlNode paramEndBracket = null; + + private TSqlNode forOrIs = null; + + private TExpression cursorStmts = null; + + public TExpression getCursorExpression() { + return cursorExpression; + } + + public void setCursorExpression(TExpression sursorExpression) { + this.cursorExpression = sursorExpression; + setPreviousObject(this.cursorExpression); + } + + public TSqlNode getParamStartBracket() { + return paramStartBracket; + } + + public void setParamStartBracket(TSqlNode paramStartBracket) { + this.paramStartBracket = paramStartBracket; + setPreviousObject(this.paramStartBracket); + } + + public TSqlNode getParamEndBracket() { + return paramEndBracket; + } + + public void setParamEndBracket(TSqlNode paramEndBracket) { + this.paramEndBracket = paramEndBracket; + setPreviousObject(this.paramEndBracket); + } + + public TSqlNode getForOrIs() { + return forOrIs; + } + + public void setForOrIs(TSqlNode forOrIs) { + this.forOrIs = forOrIs; + setPreviousObject(this.forOrIs); + } + + public TExpression getCursorStmts() { + return cursorStmts; + } + + public void setCursorStmts(TExpression cursorStmts) { + this.cursorStmts = cursorStmts; + setPreviousObject(this.cursorStmts); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/delete/TDeleteFromASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/delete/TDeleteFromASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..258b260d36ccd942f83851703cefbf6c91999002 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/delete/TDeleteFromASTNode.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.delete; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: TDeleteFromASTNode + * + * @since 3.0.0 + */ +public class TDeleteFromASTNode extends TBasicASTNode { + + private TSqlNode from = null; + + private TSqlNode only = null; + + private TExpression tableName = null; + + public TSqlNode getFrom() { + return from; + } + + public void setFrom(TSqlNode from) { + this.from = from; + setPreviousObject(this.from); + } + + public TSqlNode getOnly() { + return only; + } + + public void setOnly(TSqlNode only) { + this.only = only; + setPreviousObject(this.only); + } + + public TExpression getTableName() { + return tableName; + } + + public void setTableName(TExpression tableName) { + this.tableName = tableName; + setPreviousObject(this.tableName); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/delete/TDeleteUsingASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/delete/TDeleteUsingASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..4405134cf9c64f43591ae04c6dccff7cdbc92454 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/delete/TDeleteUsingASTNode.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.delete; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * + * Title: TDeleteUsingASTNode + * + * @since 3.0.0 + */ +public class TDeleteUsingASTNode extends TBasicASTNode { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/forloop/TForLoopASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/forloop/TForLoopASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..5bc76d9a4faccdfd2774a501a4be833e9f7062a2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/forloop/TForLoopASTNode.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.forloop; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; + +/** + * Title: TLoopASTNode + * + * @since 3.0.0 + */ +public class TForLoopASTNode extends TBasicASTNode { + + private TExpression targetName = null; + + public TExpression getTargetName() { + return targetName; + } + + public void setTargetName(TExpression targetName) { + this.targetName = targetName; + setPreviousObject(this.targetName); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/ifstmt/TIfElseASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/ifstmt/TIfElseASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..06b4104c13236619be0e580255d69d16a0873b42 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/ifstmt/TIfElseASTNode.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.ifstmt; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.fullstmt.TFullStmt; + +/** + * + * Title: TIfElseASTNode + * + * @since 3.0.0 + */ +public class TIfElseASTNode extends TBasicASTNode { + + private TSqlNode then = null; + + private TFullStmt fullStmt = null; + + private TSqlNode end = null; + + private TExpression endNode = null; + + // list of statements to the expression which should include including the + // spaces + + public TSqlNode getThen() { + return then; + } + + public void setThen(TSqlNode then) { + this.then = then; + setPreviousObject(this.then); + } + + public TFullStmt getFullStmt() { + return fullStmt; + } + + public void setFullStmt(TFullStmt fullStmt) { + this.fullStmt = fullStmt; + setPreviousObject(this.fullStmt); + } + + public TSqlNode getEnd() { + return end; + } + + public void setEnd(TSqlNode end) { + this.end = end; + setPreviousObject(this.end); + } + + public TExpression getEndNode() { + return endNode; + } + + public void setEndNode(TExpression endNode) { + this.endNode = endNode; + setPreviousObject(this.endNode); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/insert/TInsertDefaultASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/insert/TInsertDefaultASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..e6f38dc57f1272ae04bbb24871830f44a81e60bf --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/insert/TInsertDefaultASTNode.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.insert; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: TInsertDefaultASTNode + * + * @since 3.0.0 + */ +public class TInsertDefaultASTNode extends TBasicASTNode { + + private TSqlNode values = null; + + public TSqlNode getValues() { + return values; + } + + public void setValues(TSqlNode values) { + this.values = values; + setPreviousObject(this.values); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/insert/TInsertIntoASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/insert/TInsertIntoASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..558dc6e9d5534ce41dfeb889b123bf905150679f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/insert/TInsertIntoASTNode.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.insert; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: TInsertIntoASTNode + * + * @since 3.0.0 + */ +public class TInsertIntoASTNode extends TBasicASTNode { + + private TSqlNode into = null; + + private TExpression tableName = null; + + private TSqlNode startInsertAstBracket = null; + + private TSqlNode endInsertAstBracket = null; + + public TSqlNode getInto() { + return into; + } + + public void setInto(TSqlNode into) { + this.into = into; + setPreviousObject(this.into); + } + + public TExpression getTableName() { + return tableName; + } + + public void setTableName(TExpression tableName) { + this.tableName = tableName; + setPreviousObject(this.tableName); + } + + public TSqlNode getStartInsertAstBracket() { + return startInsertAstBracket; + } + + public void setStartInsertAstBracket(TSqlNode startBracket) { + this.startInsertAstBracket = startBracket; + setPreviousObject(this.startInsertAstBracket); + } + + public TSqlNode getEndInsertAstBracket() { + return endInsertAstBracket; + } + + public void setEndInsertAstBracket(TSqlNode endBracket) { + this.endInsertAstBracket = endBracket; + setPreviousObject(this.endInsertAstBracket); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/insert/TInsertValuesASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/insert/TInsertValuesASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..522754739a570545af17202f7ec211c740647e54 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/insert/TInsertValuesASTNode.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.insert; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * + * Title: TInsertValuesASTNode + * + * @since 3.0.0 + */ +public class TInsertValuesASTNode extends TBasicASTNode { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/insert/TInsertValuesNodeItem.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/insert/TInsertValuesNodeItem.java new file mode 100644 index 0000000000000000000000000000000000000000..adc10d6ff7aed9a762e026fa989402becd64c0b3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/insert/TInsertValuesNodeItem.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.insert; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TAbstractListItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: TInsertValuesNodeItem + * + * @since 3.0.0 + */ +public class TInsertValuesNodeItem extends TAbstractListItem { + + private TSqlNode startInsertBracket = null; + + private TParseTreeNodeList valueItemList = null; + + private TSqlNode endInsertBracket = null; + + private TSqlNode seperator = null; + + /** + * Gets the start insert bracket. + * + * @return the start insert bracket + */ + public TSqlNode getStartInsertBracket() { + return startInsertBracket; + } + + /** + * Sets the start insert bracket. + * + * @param startBracket the new start insert bracket + */ + public void setStartInsertBracket(TSqlNode startBracket) { + this.startInsertBracket = startBracket; + setPreviousObject(this.startInsertBracket); + } + + /** + * Gets the insert end bracket. + * + * @return the insert end bracket + */ + public TSqlNode getInsertEndBracket() { + return endInsertBracket; + } + + /** + * Sets the insert end bracket. + * + * @param endBracket the new insert end bracket + */ + public void setInsertEndBracket(TSqlNode endBracket) { + this.endInsertBracket = endBracket; + setPreviousObject(this.endInsertBracket); + } + + /** + * Gets the value item list. + * + * @return the value item list + */ + public TParseTreeNodeList getValueItemList() { + return valueItemList; + } + + /** + * Sets the value item list. + * + * @param valueItemList the new value item list + */ + public void setValueItemList(TParseTreeNodeList valueItemList) { + this.valueItemList = valueItemList; + setPreviousObject(this.valueItemList); + } + + /** + * Gets the seperator. + * + * @return the seperator + */ + public TSqlNode getSeperator() { + return seperator; + } + + /** + * Sets the seperator. + * + * @param seperator the new seperator + */ + public void setSeperator(TSqlNode seperator) { + this.seperator = seperator; + setPreviousObject(this.seperator); + } + + /** + * Gets the start node. + * + * @return the start node + */ + @Override + public TParseTreeNode getStartNode() { + return this.getAutoStartBean(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/insert/TInsertValuesNodeItemList.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/insert/TInsertValuesNodeItemList.java new file mode 100644 index 0000000000000000000000000000000000000000..4b827f819b0f6066bd2f9a9a3ad8812a1dbccd17 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/insert/TInsertValuesNodeItemList.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.insert; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; + +/** + * + * Title: TInsertValuesNodeItemList + * + * @since 3.0.0 + */ +public class TInsertValuesNodeItemList extends TParseTreeNodeList { +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/limit/TLimitASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/limit/TLimitASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..826a2515750f65c13046a0b244811fe0621002c8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/limit/TLimitASTNode.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.limit; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; + +/** + * + * Title: TLimitASTNode + * + * @since 3.0.0 + */ +public class TLimitASTNode extends TBasicASTNode { + + private TExpression limitExpression = null; + + public TExpression getLimitExpression() { + return limitExpression; + } + + public void setLimitExpression(TExpression limitExpression) { + this.limitExpression = limitExpression; + setPreviousObject(this.limitExpression); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/limit/TOffsetASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/limit/TOffsetASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..305a9413eeaef6357b70682132ec7000804f7ce3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/limit/TOffsetASTNode.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.limit; + +/** + * + * Title: TLimitASTNode + * + * @since 3.0.0 + */ +public class TOffsetASTNode extends TLimitASTNode { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/loop/TLoopASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/loop/TLoopASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..cf3c403c4c04c3951b6c8db7ad5eb75eb454d182 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/loop/TLoopASTNode.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.loop; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.fullstmt.TFullStmt; + +/** + * + * Title: TLoopASTNode + * + * @since 3.0.0 + */ +public class TLoopASTNode extends TBasicASTNode { + + private TFullStmt fullStmt = null; + + private TExpression endLoop = null; + + // list of statements to the expression which should include including the + // spaces + + public TFullStmt getFullStmt() { + return fullStmt; + } + + public void setFullStmt(TFullStmt fullStmt) { + this.fullStmt = fullStmt; + setPreviousObject(this.fullStmt); + } + + public TExpression getEndLoop() { + return endLoop; + } + + public void setEndLoop(TExpression endLoop) { + this.endLoop = endLoop; + setPreviousObject(this.endLoop); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/merge/TMergeASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/merge/TMergeASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..b3fdffd2b783ee00782f53dc54db20514abfb08e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/merge/TMergeASTNode.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.merge; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * Title: TMergeASTNode + * + * @since 3.0.0 + */ +public class TMergeASTNode extends TBasicASTNode { + + private TSqlNode hintInfo = null; + + private TSqlNode into = null; + + private TExpression srcTable = null; + + private TSqlNode using = null; + + private TExpression destTable = null; + + private TSqlNode on = null; + + private TSqlNode onStartBracket = null; + + private TSqlNode onEndBracket = null; + + public TSqlNode getHintInfo() { + return hintInfo; + } + + public void setHintInfo(TSqlNode hintInfo) { + this.hintInfo = hintInfo; + setPreviousObject(this.hintInfo); + } + + public TSqlNode getInto() { + return into; + } + + public void setInto(TSqlNode into) { + this.into = into; + setPreviousObject(this.into); + } + + public TExpression getSrcTable() { + return srcTable; + } + + public void setSrcTable(TExpression srcTable) { + this.srcTable = srcTable; + setPreviousObject(this.srcTable); + } + + public TSqlNode getUsing() { + return using; + } + + public void setUsing(TSqlNode using) { + this.using = using; + setPreviousObject(this.using); + } + + public TExpression getDestTable() { + return destTable; + } + + public void setDestTable(TExpression destTable) { + this.destTable = destTable; + setPreviousObject(this.destTable); + } + + public TSqlNode getOn() { + return on; + } + + public void setOn(TSqlNode on) { + this.on = on; + setPreviousObject(this.on); + } + + public TSqlNode getOnStartBracket() { + return onStartBracket; + } + + public void setOnStartBracket(TSqlNode onStartBracket) { + this.onStartBracket = onStartBracket; + setPreviousObject(this.onStartBracket); + } + + public TSqlNode getOnEndBracket() { + return onEndBracket; + } + + public void setOnEndBracket(TSqlNode onEndBracket) { + this.onEndBracket = onEndBracket; + setPreviousObject(this.onEndBracket); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/merge/TMergeWhenASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/merge/TMergeWhenASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..51dc7ef6133de1fdcb13a83265444d839c1cbd49 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/merge/TMergeWhenASTNode.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.merge; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; + +/** + * Title: TMergeASTNode + * + * @since 3.0.0 + */ +public class TMergeWhenASTNode extends TBasicASTNode { + + private TExpression whenMatch = null; + + private TExpression matchDML = null; + + private TExpression whenNotMatch = null; + + private TExpression insertDML = null; + + public TExpression getWhenMatch() { + return whenMatch; + } + + public void setWhenMatch(TExpression whenMatch) { + this.whenMatch = whenMatch; + setPreviousObject(this.whenMatch); + } + + public TExpression getMatchDML() { + return matchDML; + } + + public void setMatchDML(TExpression matchDML) { + this.matchDML = matchDML; + setPreviousObject(this.matchDML); + } + + public TExpression getWhenNotMatch() { + return whenNotMatch; + } + + public void setWhenNotMatch(TExpression whenNotMatch) { + this.whenNotMatch = whenNotMatch; + setPreviousObject(this.whenNotMatch); + } + + public TExpression getInsertDML() { + return insertDML; + } + + public void setInsertDML(TExpression insertDML) { + this.insertDML = insertDML; + setPreviousObject(this.insertDML); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/TConnectByASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/TConnectByASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..7fa28b6bb6d73208660ee7aadec5a0c68ce38216 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/TConnectByASTNode.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: TConnectByASTNode + * + * @since 3.0.0 + */ +public class TConnectByASTNode extends TBasicASTNode { + private TSqlNode by = null; + + /** + * Gets the connect. + * + * @return the connect + */ + public TSqlNode getConnect() { + return getKeywordNode(); + } + + /** + * Gets the by. + * + * @return the by + */ + public TSqlNode getBy() { + return by; + } + + /** + * Sets the by. + * + * @param by the new by + */ + public void setBy(TSqlNode by) { + this.by = by; + setPreviousObject(this.by); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/TFetchASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/TFetchASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..2fd6e5a7716eb7ec8c7f2e7d97fb21394e693c56 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/TFetchASTNode.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.limit.TLimitASTNode; + +/** + * + * Title: TFetchASTNode + * + * Description: The Class TFetchASTNode. + * + * @since 3.0.0 + */ +public class TFetchASTNode extends TLimitASTNode { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/TForASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/TForASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..27c14d88754bce259e417f6171984026f155ba2d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/TForASTNode.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.limit.TLimitASTNode; + +/** + * + * Title: TForASTNode + * + * Description: The Class TForASTNode. + * + * @since 3.0.0 + */ +public class TForASTNode extends TLimitASTNode { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/TGroupByASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/TGroupByASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..e900e571a14ea4de229908015ffe80e440e10d51 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/TGroupByASTNode.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: TGroupByASTNode + * + * @since 3.0.0 + */ +public class TGroupByASTNode extends TBasicASTNode { + private TSqlNode by = null; + + /** + * Gets the group. + * + * @return the group + */ + public TSqlNode getGroup() { + return getKeywordNode(); + } + + /** + * Gets the by. + * + * @return the by + */ + public TSqlNode getBy() { + return by; + } + + /** + * Sets the by. + * + * @param by the new by + */ + public void setBy(TSqlNode by) { + this.by = by; + setPreviousObject(this.by); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/THavingASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/THavingASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..233bc8e99e48ab1b4fae806e32d25925b15f1329 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/THavingASTNode.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * + * Title: THavingASTNode + * + * @since 3.0.0 + */ +public class THavingASTNode extends TBasicASTNode { +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/TSelectASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/TSelectASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..d5e2fcfd276e58a9745ecafd5d2f2652fa34dc0e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/TSelectASTNode.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: TSelectASTNode + * + * @since 3.0.0 + */ +public class TSelectASTNode extends TBasicASTNode { + + private TSqlNode hintInfo = null; + + private TSqlNode SQL_CALC_FOUND_ROWS = null; + + private TSqlNode distinct = null; + + /** + * Gets the hint info. + * + * @return the hint info + */ + public TSqlNode getHintInfo() { + return hintInfo; + } + + /** + * Sets the hint info. + * + * @param hintInfo the new hint info + */ + public void setHintInfo(TSqlNode hintInfo) { + this.hintInfo = hintInfo; + setPreviousObject(this.hintInfo); + } + + /** + * Gets the sql calc found rows. + * + * @return the sql calc found rows + */ + public TSqlNode getSqlCalcFoundRows() { + return SQL_CALC_FOUND_ROWS; + } + + /** + * Sets the sql calc found rows. + * + * @param sQL_CALC_FOUND_ROWS the new sql calc found rows + */ + public void setSqlCalcFoundRows(TSqlNode sQL_CALC_FOUND_ROWS) { + SQL_CALC_FOUND_ROWS = sQL_CALC_FOUND_ROWS; + setPreviousObject(this.SQL_CALC_FOUND_ROWS); + } + + /** + * Gets the distinct. + * + * @return the distinct + */ + public TSqlNode getDistinct() { + return distinct; + } + + /** + * Sets the distinct. + * + * @param distinct the new distinct + */ + public void setDistinct(TSqlNode distinct) { + this.distinct = distinct; + setPreviousObject(this.distinct); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/TStartWithASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/TStartWithASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..18963ea8cab913034ca7e354b07105fa4ff15498 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/TStartWithASTNode.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: TStartWithASTNode + * + * @since 3.0.0 + */ +public class TStartWithASTNode extends TBasicASTNode { + private TSqlNode with = null; + + /** + * Gets the start. + * + * @return the start + */ + public TSqlNode getStart() { + return getKeywordNode(); + } + + /** + * Gets the with. + * + * @return the with + */ + public TSqlNode getWith() { + return with; + } + + /** + * Sets the with. + * + * @param with the new with + */ + public void setWith(TSqlNode with) { + this.with = with; + setPreviousObject(this.with); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/TWindowASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/TWindowASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..a9b155370290c4b9eeb36d025228bfed988b0bf8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/select/TWindowASTNode.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.select; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * + * Title: TWindowASTNode + * + * Description: The Class TWindowASTNode. + * + * @since 3.0.0 + */ +public class TWindowASTNode extends TBasicASTNode { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/union/TUnionASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/union/TUnionASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..69751bb44bf8cdf60418dca976ad3bafa02b8c48 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/union/TUnionASTNode.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.union; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; + +/** + * Title: TLoopASTNode + * + * @since 3.0.0 + */ +public class TUnionASTNode extends TBasicASTNode { + + private TExpression remainingStmt = null; + + public TExpression getRemainingStmt() { + return remainingStmt; + } + + public void setRemainingStmt(TExpression remainingStmt) { + this.remainingStmt = remainingStmt; + setPreviousObject(this.remainingStmt); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/update/TUpdateIntoASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/update/TUpdateIntoASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..ba33f632c64706756d130ea4e085ab122c45ccb0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/update/TUpdateIntoASTNode.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.update; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: TUpdateIntoASTNode + * + * @since 3.0.0 + */ +public class TUpdateIntoASTNode extends TBasicASTNode { + + private TSqlNode only = null; + + public TSqlNode getOnly() { + return only; + } + + public void setOnly(TSqlNode only) { + this.only = only; + setPreviousObject(this.only); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/update/TUpdateSetASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/update/TUpdateSetASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..35a47202db10545d87e212b9f43932b03640864c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/update/TUpdateSetASTNode.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.update; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; + +/** + * + * Title: TUpdateSetASTNode + * + * @since 3.0.0 + */ +public class TUpdateSetASTNode extends TBasicASTNode { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/update/TUpdateSetValuesBean.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/update/TUpdateSetValuesBean.java new file mode 100644 index 0000000000000000000000000000000000000000..9ecc0a0d5d6c406cc1e648cd1ae75338f78b9b7a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/update/TUpdateSetValuesBean.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.update; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: TUpdateSetValuesBean + * + * @since 3.0.0 + */ +public class TUpdateSetValuesBean extends TParseTreeNode { + + private TSqlNode startUpdateBracket = null; + + private TParseTreeNodeList valueItemList = null; + + private TSqlNode endUpdateBracket = null; + + /** + * Gets the update start bracket. + * + * @return the update start bracket + */ + public TSqlNode getUpdateStartBracket() { + return startUpdateBracket; + } + + /** + * Sets the update start bracket. + * + * @param startBracket the new update start bracket + */ + public void setUpdateStartBracket(TSqlNode startBracket) { + this.startUpdateBracket = startBracket; + setPreviousObject(this.startUpdateBracket); + } + + /** + * Gets the update end bracket. + * + * @return the update end bracket + */ + public TSqlNode getUpdateEndBracket() { + return endUpdateBracket; + } + + /** + * Sets the update end bracket. + * + * @param endBracket the new update end bracket + */ + public void setUpdateEndBracket(TSqlNode endBracket) { + this.endUpdateBracket = endBracket; + setPreviousObject(this.endUpdateBracket); + } + + /** + * Gets the value item list. + * + * @return the value item list + */ + public TParseTreeNodeList getValueItemList() { + return valueItemList; + } + + /** + * Sets the value item list. + * + * @param valueItemList the new value item list + */ + public void setValueItemList(TParseTreeNodeList valueItemList) { + this.valueItemList = valueItemList; + setPreviousObject(this.valueItemList); + } + + /** + * Gets the start node. + * + * @return the start node + */ + @Override + public TParseTreeNode getStartNode() { + return this.getAutoStartBean(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/update/TUpdateSetValuesNodeItem.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/update/TUpdateSetValuesNodeItem.java new file mode 100644 index 0000000000000000000000000000000000000000..098b05192fb125687d7b70029d8b5dd421ff9556 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/update/TUpdateSetValuesNodeItem.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.update; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TAbstractListItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: TUpdateSetValuesNodeItem + * + * @since 3.0.0 + */ +public class TUpdateSetValuesNodeItem extends TAbstractListItem { + + private TUpdateSetValuesBean leftNodeItem = null; + + private TSqlNode equalNode = null; + + private TUpdateSetValuesBean rightNodeItem = null; + + private TSqlNode seperator = null; + + public TUpdateSetValuesBean getLeftNodeItem() { + return leftNodeItem; + } + + public void setLeftNodeItem(TUpdateSetValuesBean leftNodeItem) { + this.leftNodeItem = leftNodeItem; + setPreviousObject(this.leftNodeItem); + } + + public TSqlNode getEqualNode() { + return equalNode; + } + + public void setEqualNode(TSqlNode equalNode) { + this.equalNode = equalNode; + setPreviousObject(this.equalNode); + } + + public TUpdateSetValuesBean getRightNodeItem() { + return rightNodeItem; + } + + public void setRightNodeItem(TUpdateSetValuesBean rightNodeItem) { + this.rightNodeItem = rightNodeItem; + setPreviousObject(this.rightNodeItem); + } + + public TSqlNode getSeperator() { + return seperator; + } + + public void setSeperator(TSqlNode seperator) { + this.seperator = seperator; + setPreviousObject(this.seperator); + } + + @Override + public TParseTreeNode getStartNode() { + return this.getAutoStartBean(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/update/TUpdateSetValuesNodeItemList.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/update/TUpdateSetValuesNodeItemList.java new file mode 100644 index 0000000000000000000000000000000000000000..eb75bc515d5171d099e1ace0cc834b9f58f7ecaf --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/update/TUpdateSetValuesNodeItemList.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.update; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; + +/** + * + * Title: TUpdateSetValuesNodeItemList + * + * @since 3.0.0 + */ +public class TUpdateSetValuesNodeItemList extends TParseTreeNodeList { +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/with/TWithASTNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/with/TWithASTNode.java new file mode 100644 index 0000000000000000000000000000000000000000..aadf6de9a2ef2f2ade9b8c562ed3192547c053e6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/astnode/with/TWithASTNode.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.with; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TBasicASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * + * Title: TWithASTNode + * + * @since 3.0.0 + */ +public class TWithASTNode extends TBasicASTNode { + + private TSqlNode recursive = null; + + private TExpression stmtExpression = null; + + public TSqlNode getRecursive() { + return recursive; + + } + + public void setRecursive(TSqlNode recursive) { + this.recursive = recursive; + setPreviousObject(this.recursive); + } + + public TExpression getStmtExpression() { + return stmtExpression; + } + + public void setStmtExpression(TExpression stmtExpression) { + this.stmtExpression = stmtExpression; + setPreviousObject(this.stmtExpression); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/TCustomSqlStatement.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/TCustomSqlStatement.java new file mode 100644 index 0000000000000000000000000000000000000000..9029610154c48909f6519312dc405fed3ae84dbd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/TCustomSqlStatement.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.custom; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.astnode.TCustomASTNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmtbeanif.StatementBeanIf; + +/** + * + * Title: TCustomSqlStatement + * + * @since 3.0.0 + */ +public abstract class TCustomSqlStatement extends TParseTreeNode implements StatementBeanIf { + /** + * The ast node map. + */ + protected Map astNodeMap = new LinkedHashMap(); + + /** + * Adds the ast node. + * + * @param tokenKeyword the token keyword + * @param astNode the ast node + */ + public void addAstNode(String tokenKeyword, TCustomASTNode astNode) { + astNodeMap.put(tokenKeyword, astNode); + } + + /** + * Gets the custom ast node. + * + * @param key the key + * @return the custom ast node + */ + public TCustomASTNode getCustomAstNode(String key) { + return astNodeMap.get(key); + } + + /** + * Gets the start node. + * + * @return the start node + */ + @Override + public TParseTreeNode getStartNode() { + if (astNodeMap.isEmpty()) { + return null; + } + return astNodeMap.entrySet().iterator().next().getValue(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/block/TBeginSqlStatement.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/block/TBeginSqlStatement.java new file mode 100644 index 0000000000000000000000000000000000000000..2271892107f6452974a0b2c13c8c86589d4095f8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/block/TBeginSqlStatement.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.block; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; + +/** + * Title: TBeginSqlStatement + * + * @since 3.0.0 + */ +public class TBeginSqlStatement extends TCustomSqlStatement { +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/block/TDeclareSqlStatement.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/block/TDeclareSqlStatement.java new file mode 100644 index 0000000000000000000000000000000000000000..71d35b05ffbfed8c00e21f0675dac64577fe2b55 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/block/TDeclareSqlStatement.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.block; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; + +/** + * Title: TDeclareSqlStatement + * + * @since 3.0.0 + */ +public class TDeclareSqlStatement extends TCustomSqlStatement { +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/common/TUnionSqlStatement.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/common/TUnionSqlStatement.java new file mode 100644 index 0000000000000000000000000000000000000000..4a5c31b0fca20d926c6866676268fca7bf0775d2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/common/TUnionSqlStatement.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.common; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; + +/** + * + * Title: TWithSqlStatement + * + * @since 3.0.0 + */ +public class TUnionSqlStatement extends TCustomSqlStatement { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/condition/TCaseSqlStatement.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/condition/TCaseSqlStatement.java new file mode 100644 index 0000000000000000000000000000000000000000..05267b55b8cb7ab0711932eeea770ebfa1a41dde --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/condition/TCaseSqlStatement.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.condition; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: TCaseSqlStatement + * + * @since 3.0.0 + */ +public class TCaseSqlStatement extends TCustomSqlStatement { + + @Override + public TParseTreeNode getStartNode() { + if (astNodeMap.isEmpty()) { + return null; + } + return astNodeMap.entrySet().iterator().next().getValue(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/condition/TIfElseSqlStatement.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/condition/TIfElseSqlStatement.java new file mode 100644 index 0000000000000000000000000000000000000000..9426650212cf288d11b04e02b917d853bcd6cf2b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/condition/TIfElseSqlStatement.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.condition; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; + +/** + * + * Title: TIfElseSqlStatement + * + * @since 3.0.0 + */ +public class TIfElseSqlStatement extends TCustomSqlStatement { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/debugobj/TCreateSqlStatement.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/debugobj/TCreateSqlStatement.java new file mode 100644 index 0000000000000000000000000000000000000000..9ee6fd717ce75e21e423c5d9b063683c94efe0f5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/debugobj/TCreateSqlStatement.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.debugobj; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; + +/** + * + * Title: TCreateSqlStatemet + * + * @since 3.0.0 + */ +public class TCreateSqlStatement extends TCustomSqlStatement { +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/debugobj/TCursorSqlStatement.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/debugobj/TCursorSqlStatement.java new file mode 100644 index 0000000000000000000000000000000000000000..f896cd35a3f5bbc4ea8941fbb9009e3406e011af --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/debugobj/TCursorSqlStatement.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.debugobj; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; + +/** + * Title: TLoopSqlStatement + * + * @since 3.0.0 + */ +public class TCursorSqlStatement extends TCustomSqlStatement { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/dml/TDeleteSqlStatement.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/dml/TDeleteSqlStatement.java new file mode 100644 index 0000000000000000000000000000000000000000..dede0751c8cc2c9a724daf791af904436a2c7e9b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/dml/TDeleteSqlStatement.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; + +/** + * + * Title: TDeleteSqlStatement + * + * @since 3.0.0 + */ +public class TDeleteSqlStatement extends TCustomSqlStatement { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/dml/TInsertSqlStatement.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/dml/TInsertSqlStatement.java new file mode 100644 index 0000000000000000000000000000000000000000..0892e84a145c2c0d4ce8132697502751ab3a097c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/dml/TInsertSqlStatement.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; + +/** + * + * Title: TInsertSqlStatement + * + * @since 3.0.0 + */ +public class TInsertSqlStatement extends TCustomSqlStatement { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/dml/TMergeSqlStatement.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/dml/TMergeSqlStatement.java new file mode 100644 index 0000000000000000000000000000000000000000..cf6c881371cdd9194ebc7d500d7c4d92c3c03c06 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/dml/TMergeSqlStatement.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; + +/** + * + * Title: TWithSqlStatement + * + * @since 3.0.0 + */ +public class TMergeSqlStatement extends TCustomSqlStatement { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/dml/TSelectSqlStatement.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/dml/TSelectSqlStatement.java new file mode 100644 index 0000000000000000000000000000000000000000..19c819877b227942e15d8156bb2018aa934a5482 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/dml/TSelectSqlStatement.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; + +/** + * + * Title: TSelectSqlStatement + * + * @since 3.0.0 + */ +public class TSelectSqlStatement extends TCustomSqlStatement { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/dml/TUpdateSqlStatement.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/dml/TUpdateSqlStatement.java new file mode 100644 index 0000000000000000000000000000000000000000..27dfb9c21a6e6a60441964650bf62365287afcc1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/dml/TUpdateSqlStatement.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; + +/** + * + * Title: TUpdateSqlStatement + * + * @since 3.0.0 + */ +public class TUpdateSqlStatement extends TCustomSqlStatement { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/dml/TWithSqlStatement.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/dml/TWithSqlStatement.java new file mode 100644 index 0000000000000000000000000000000000000000..79916872ed0fb1f04fe3bd24600ba23e79cac404 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/dml/TWithSqlStatement.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.dml; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; + +/** + * + * Title: TWithSqlStatement + * + * @since 3.0.0 + */ +public class TWithSqlStatement extends TCustomSqlStatement { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/loop/TForLoopSqlStatement.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/loop/TForLoopSqlStatement.java new file mode 100644 index 0000000000000000000000000000000000000000..1d080ff28ff116278e8197c6ebd644ce27f33e36 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/loop/TForLoopSqlStatement.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.loop; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; + +/** + * Title: TLoopSqlStatement + * + * @since 3.0.0 + */ +public class TForLoopSqlStatement extends TCustomSqlStatement { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/loop/TLoopSqlStatement.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/loop/TLoopSqlStatement.java new file mode 100644 index 0000000000000000000000000000000000000000..a98611ae1e9320de8a9bfae0dcc71e4ae615f194 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/custom/loop/TLoopSqlStatement.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.loop; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.custom.TCustomSqlStatement; + +/** + * Title: TLoopSqlStatement + * + * @since 3.0.0 + */ +public class TLoopSqlStatement extends TCustomSqlStatement { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TAbstractListItem.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TAbstractListItem.java new file mode 100644 index 0000000000000000000000000000000000000000..5a2c6fe41682395a27ae5d208689e834adb1be36 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TAbstractListItem.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node; + +/** + * + * Title: TAbstractListItem + * + * @since 3.0.0 + */ +public abstract class TAbstractListItem extends TParseTreeNode { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TCTEExpression.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TCTEExpression.java new file mode 100644 index 0000000000000000000000000000000000000000..583aa0c2d42a9a026b855cc9612411a3db4ea8d3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TCTEExpression.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node; + +/** + * Title: TCTEExpression + * + * @since 3.0.0 + */ +public class TCTEExpression extends TExpression { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TColumnListWithBracket.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TColumnListWithBracket.java new file mode 100644 index 0000000000000000000000000000000000000000..014e815c016b71e4d1e99d29cd7dcbea2ba6a634 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TColumnListWithBracket.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node; + +/** + * + * Title: TColumnListWithBracket + * + * @since 3.0.0 + */ +public class TColumnListWithBracket extends TListItem { + + private TSqlNode openColumnListBracket = null; + private TResultColumnList tableColumns = null; + private TSqlNode closeColumnListBracket = null; + + public TSqlNode getOpenColumnListBracket() { + return openColumnListBracket; + } + + public void setOpenColumnListBracket(TSqlNode openBracket) { + this.openColumnListBracket = openBracket; + } + + public TResultColumnList getTableColumns() { + return tableColumns; + } + + public void setTableColumns(TResultColumnList tableColumns) { + this.tableColumns = tableColumns; + } + + public TSqlNode getCloseColumnListBracket() { + return closeColumnListBracket; + } + + public void setCloseColumnListBracket(TSqlNode closeBracket) { + this.closeColumnListBracket = closeBracket; + } + + @Override + public TParseTreeNode getStartNode() { + return openColumnListBracket; + } + + @Override + public TSqlNode getSeperator() { + return null; + } + + @Override + public TSqlNode getEndNode() { + return null; + } + + @Override + public TSqlNode getAs() { + return null; + } + + @Override + public TParseTreeNode getItemListNode() { + return null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TCustomSqlWithBracket.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TCustomSqlWithBracket.java new file mode 100644 index 0000000000000000000000000000000000000000..1033ea48696b9eaacc6587332fedb075bb5ce263 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TCustomSqlWithBracket.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node; + +/** + * + * Title: TCustomSqlWithBracket + * + * @since 3.0.0 + */ +public class TCustomSqlWithBracket extends TListItem { + private TSqlNode openCustomSqlBracket = null; + private TExpression sql = null; + private TSqlNode closeCustomSqlBracket = null; + + public TSqlNode getOpenCustomSqlBracket() { + return openCustomSqlBracket; + } + + public void setOpenCustomSqlBracket(TSqlNode openBracket) { + this.openCustomSqlBracket = openBracket; + } + + public TExpression getSql() { + return sql; + } + + public void setSql(TExpression sql) { + this.sql = sql; + } + + public TSqlNode getCloseCustomSqlBracket() { + return closeCustomSqlBracket; + } + + public void setCloseCustomSqlBracket(TSqlNode closeBracket) { + this.closeCustomSqlBracket = closeBracket; + } + + @Override + public TParseTreeNode getStartNode() { + return openCustomSqlBracket; + } + + @Override + public TParseTreeNode getItemListNode() { + return null; + } + + @Override + public TSqlNode getAs() { + return null; + } + + @Override + public TSqlNode getEndNode() { + return null; + } + + @Override + public TSqlNode getSeperator() { + return null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TExpression.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TExpression.java new file mode 100644 index 0000000000000000000000000000000000000000..94b66dbfcabd638f8275850f25847d3aaa458b66 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TExpression.java @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node; + +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.gauss.sqlparser.parser.utils.ExpressionTypeEnum; + +/** + * Title: TExpression + * + * @since 3.0.0 + */ +public class TExpression extends TParseTreeNode { + + private ExpressionTypeEnum expressionType = ExpressionTypeEnum.NORMAL; + + private List expList = new ArrayList(); + + private boolean containStmt = false; + + private boolean directExpression = false; + + private Boolean addSpaceForCustomStmt = Boolean.FALSE; + + /** + * Instantiates a new t expression. + */ + public TExpression() { + + } + + /** + * Instantiates a new t expression. + * + * @param expType the exp type + */ + public TExpression(ExpressionTypeEnum expType) { + this.expressionType = expType; + } + + /** + * Gets the exp list. + * + * @return the exp list + */ + public List getExpList() { + return expList; + } + + /** + * Sets the exp list. + * + * @param expList the new exp list + */ + public void setExpList(List expList) { + this.expList = expList; + } + + /** + * Adds the expression node. + * + * @param exp the exp + */ + public void addExpressionNode(TExpressionNode exp) { + this.expList.add(exp); + } + + /** + * Checks if is contain stmt. + * + * @return true, if is contain stmt + */ + public boolean isContainStmt() { + return containStmt; + } + + /** + * Sets the contain stmt. + * + * @param containStmt the new contain stmt + */ + public void setContainStmt(boolean containStmt) { + this.containStmt = containStmt; + } + + /** + * Gets the expression type. + * + * @return the expression type + */ + public ExpressionTypeEnum getExpressionType() { + return expressionType; + } + + /** + * Sets the expression type. + * + * @param expressionType the new expression type + */ + public void setExpressionType(ExpressionTypeEnum expressionType) { + this.expressionType = expressionType; + } + + /** + * Checks if is direct expression. + * + * @return true, if is direct expression + */ + public boolean isDirectExpression() { + return directExpression; + } + + /** + * Sets the direct expression. + * + * @param directExpression the new direct expression + */ + public void setDirectExpression(boolean directExpression) { + this.directExpression = directExpression; + } + + /** + * Gets the adds the space for custom stmt. + * + * @return the adds the space for custom stmt + */ + public Boolean getAddSpaceForCustomStmt() { + return addSpaceForCustomStmt; + } + + /** + * Sets the adds the space for custom stmt. + * + * @param addSpaceForCustomStmt the new adds the space for custom stmt + */ + public void setAddSpaceForCustomStmt(Boolean addSpaceForCustomStmt) { + this.addSpaceForCustomStmt = addSpaceForCustomStmt; + } + + /** + * Gets the start node. + * + * @return the start node + */ + @Override + public TParseTreeNode getStartNode() { + return this; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TExpressionNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TExpressionNode.java new file mode 100644 index 0000000000000000000000000000000000000000..9f5acee507481a41058214e8e02c43a366044a79 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TExpressionNode.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node; + +/** + * + * Title: TExpressionNode + * + * @since 3.0.0 + */ +public class TExpressionNode extends TParseTreeNode { + + private TParseTreeNode customStmt = null; + + private TSqlNode expNode = new TSqlNode(); + + public TParseTreeNode getCustomStmt() { + return customStmt; + } + + public void setCustomStmt(TParseTreeNode customStmt) { + this.customStmt = customStmt; + } + + public TSqlNode getExpNode() { + return expNode; + } + + public void setExpNode(TSqlNode expNode) { + this.expNode = expNode; + } + + @Override + public TParseTreeNode getStartNode() { + return null == customStmt ? expNode : customStmt; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TItemListNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TItemListNode.java new file mode 100644 index 0000000000000000000000000000000000000000..7b7c6a32673f411092d5bdd1e1f285e64a0e5513 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TItemListNode.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node; + +/** + * + * Title: TItemListNode + * + * @since 3.0.0 + */ +public class TItemListNode extends TParseTreeNode { + + @Override + public TParseTreeNode getStartNode() { + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TListItem.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TListItem.java new file mode 100644 index 0000000000000000000000000000000000000000..63d022fd827366e9d5c214281f3c6391c40977c3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TListItem.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node; + +/** + * + * Title: TListItem + * + * @since 3.0.0 + */ +public abstract class TListItem extends TAbstractListItem { + + private int itemSize; + + /** + * Gets the item list node. + * + * @return the item list node + */ + public abstract TParseTreeNode getItemListNode(); + + /** + * Gets the as. + * + * @return the as + */ + public abstract TSqlNode getAs(); + + /** + * Gets the end node. + * + * @return the end node + */ + public abstract TParseTreeNode getEndNode(); + + /** + * Gets the seperator. + * + * @return the seperator + */ + public abstract TSqlNode getSeperator(); + + /** + * Gets the item size. + * + * @return the item size + */ + public int getItemSize() { + return itemSize; + } + + /** + * Sets the item size. + * + * @param itemSize the new item size + */ + public void setItemSize(int itemSize) { + this.itemSize = itemSize; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TParseTreeNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TParseTreeNode.java new file mode 100644 index 0000000000000000000000000000000000000000..e02e4edf0a0cb9df259a2d3e191d5b715f941d62 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TParseTreeNode.java @@ -0,0 +1,225 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node; + +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.gauss.format.processor.listener.IFormarProcessorListener; + +/** + * + * Title: TParseTreeNode + * + * @since 3.0.0 + */ +public abstract class TParseTreeNode { + + private List nextComments = null; + + private List preText = null; + + private List postText = null; + + private IFormarProcessorListener formatListener = null; + + private TParseTreeNode nextNode = null; + + private TParseTreeNode currentObject = null; + + private TParseTreeNode autoStartBean = null; + + private Boolean checkPreviousNewLine = Boolean.FALSE; + + /** + * Sets the previous object. + * + * @param currOjb the new previous object + */ + public void setPreviousObject(TParseTreeNode currOjb) { + if (null == currOjb) { + return; + } + + if (null != currentObject) { + currentObject.setNextNode(currOjb); + } else { + autoStartBean = currOjb; + } + + currentObject = currOjb; + } + + /** + * Gets the next comments. + * + * @return the next comments + */ + public List getNextComments() { + return nextComments; + } + + /** + * Sets the next comments. + * + * @param nextComments the new next comments + */ + public void setNextComments(List nextComments) { + this.nextComments = nextComments; + } + + /** + * Adds the comment. + * + * @param nodeText the node text + */ + public void addComment(String nodeText) { + if (null == nextComments) { + nextComments = new ArrayList(15); + } + nextComments.add(nodeText); + } + + /** + * Gets the next node. + * + * @return the next node + */ + public TParseTreeNode getNextNode() { + return nextNode; + } + + /** + * Sets the next node. + * + * @param nextNode the new next node + */ + public void setNextNode(TParseTreeNode nextNode) { + this.nextNode = nextNode; + } + + /** + * Adds the pre text. + * + * @param nodeText the node text + */ + public void addPreText(String nodeText) { + if (null == preText) { + preText = new ArrayList(15); + } + preText.add(nodeText); + } + + /** + * Adds the post text. + * + * @param nodeText the node text + */ + public void addPostText(String nodeText) { + if (null == postText) { + postText = new ArrayList(15); + } + postText.add(nodeText); + } + + /** + * Gets the pre text. + * + * @return the pre text + */ + public List getPreText() { + return preText; + } + + /** + * Sets the pre text. + * + * @param preText the new pre text + */ + public void setPreText(List preText) { + this.preText = preText; + } + + /** + * Gets the post text. + * + * @return the post text + */ + public List getPostText() { + return postText; + } + + /** + * Sets the post text. + * + * @param postText the new post text + */ + public void setPostText(List postText) { + this.postText = postText; + } + + /** + * Gets the start node. + * + * @return the start node + */ + public abstract TParseTreeNode getStartNode(); + + /** + * Gets the format listener. + * + * @return the format listener + */ + public IFormarProcessorListener getFormatListener() { + return formatListener; + } + + /** + * Sets the format listener. + * + * @param formatListener the new format listener + */ + public void setFormatListener(IFormarProcessorListener formatListener) { + this.formatListener = formatListener; + } + + /** + * Gets the auto start bean. + * + * @return the auto start bean + */ + public TParseTreeNode getAutoStartBean() { + return autoStartBean; + } + + /** + * Gets the check previous new line. + * + * @return the check previous new line + */ + public Boolean getCheckPreviousNewLine() { + return checkPreviousNewLine; + } + + /** + * Sets the check previous new line. + * + * @param checkPreviousNewLine the new check previous new line + */ + public void setCheckPreviousNewLine(Boolean checkPreviousNewLine) { + this.checkPreviousNewLine = checkPreviousNewLine; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TParseTreeNodeList.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TParseTreeNodeList.java new file mode 100644 index 0000000000000000000000000000000000000000..efd561fc9b6fa1a9ee1d51279a814dfc17811187 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TParseTreeNodeList.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node; + +import java.util.ArrayList; +import java.util.List; + +/** + * + * Title: TParseTreeNodeList + * + * @since 3.0.0 + */ +public class TParseTreeNodeList extends TParseTreeNode { + private List resultList = new ArrayList(); + + private boolean expContainStmt = false; + + /** + * Gets the result list. + * + * @return the result list + */ + public List getResultList() { + return resultList; + } + + /** + * Sets the result list. + * + * @param resultList the new result list + */ + public void setResultList(List resultList) { + this.resultList = resultList; + } + + /** + * Adds the result column. + * + * @param resultCol the result col + */ + public void addResultColumn(E resultCol) { + this.resultList.add(resultCol); + } + + /** + * Checks if is exp contain stmt. + * + * @return true, if is exp contain stmt + */ + public boolean isExpContainStmt() { + return expContainStmt; + } + + /** + * Sets the exp contain stmt. + * + * @param expContainStmt the new exp contain stmt + */ + public void setExpContainStmt(boolean expContainStmt) { + this.expContainStmt = expContainStmt; + } + + @Override + public TParseTreeNode getStartNode() { + return this; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TResultColumn.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TResultColumn.java new file mode 100644 index 0000000000000000000000000000000000000000..4c7a2070a156318e6d5372505c3f54daf0a13e75 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TResultColumn.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node; + +/** + * + * Title: TResultColumn + * + * @since 3.0.0 + */ +public class TResultColumn extends TListItem { + + private TExpression expression = null; + + private TSqlNode as = null; + + private TExpression endNode = null; + + private TSqlNode seperator = null; + + public TExpression getExpression() { + return expression; + } + + public void setExpression(TExpression expression) { + this.expression = expression; + setPreviousObject(this.expression); + + } + + public TSqlNode getAs() { + return as; + } + + public void setSeperator(TSqlNode seperator) { + this.seperator = seperator; + setPreviousObject(this.seperator); + } + + public void setAs(TSqlNode as) { + this.as = as; + setPreviousObject(this.as); + } + + public TExpression getEndNode() { + return endNode; + } + + public void setEndNode(TExpression aliasName) { + this.endNode = aliasName; + setPreviousObject(this.endNode); + } + + @Override + public TParseTreeNode getItemListNode() { + return expression; + } + + @Override + public TSqlNode getSeperator() { + return seperator; + } + + @Override + public TParseTreeNode getStartNode() { + return expression; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TResultColumnList.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TResultColumnList.java new file mode 100644 index 0000000000000000000000000000000000000000..038d24c798a8231ee124263faf41ef758984f2b1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TResultColumnList.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node; + +/** + * + * Title: TResultColumnList + * + * @since 3.0.0 + */ +public class TResultColumnList extends TParseTreeNodeList { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TSqlNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TSqlNode.java new file mode 100644 index 0000000000000000000000000000000000000000..29d92580dc68d70080b08df4063d4f57159520da --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TSqlNode.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node; + +/** + * + * Title: TSqlNode + * + * @since 3.0.0 + */ +public class TSqlNode extends TParseTreeNode { + + private String nodeText = null; + + public String getNodeText() { + return nodeText; + } + + public void setNodeText(String nodeText) { + this.nodeText = nodeText; + } + + @Override + public TParseTreeNode getStartNode() { + return this; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TWhereClause.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TWhereClause.java new file mode 100644 index 0000000000000000000000000000000000000000..5105c8e5411f4885be3982f6ca8e52760af50e36 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TWhereClause.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node; + +/** + * + * Title: TWhereClause + * + * @since 3.0.0 + */ +public class TWhereClause extends TParseTreeNodeList { +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TWhereListItem.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TWhereListItem.java new file mode 100644 index 0000000000000000000000000000000000000000..2deaee52154e962924ea2d809704096d02a72ff2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/TWhereListItem.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node; + +/** + * + * Title: TWhereListItem + * + * @since 3.0.0 + */ +public abstract class TWhereListItem extends TAbstractListItem { + + /** + * Gets the item list node. + * + * @return the item list node + */ + public abstract TParseTreeNode getItemListNode(); + + /** + * Gets the con sep. + * + * @return the con sep + */ + public abstract TSqlNode getConSep(); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/WhereClauseItem.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/WhereClauseItem.java new file mode 100644 index 0000000000000000000000000000000000000000..376a699b0f2fc9888506f16a278fd6d2ff3f8443 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/WhereClauseItem.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node; + +/** + * + * Title: WhereClauseItem + * + * @since 3.0.0 + */ +public class WhereClauseItem extends TWhereListItem { + + private TExpression whereExpression = null; + + private TSqlNode conditionSeparator = null; + + /** + * Gets the where expression. + * + * @return the where expression + */ + public TExpression getWhereExpression() { + return whereExpression; + } + + /** + * Sets the where expression. + * + * @param whereExpression the new where expression + */ + public void setWhereExpression(TExpression whereExpression) { + this.whereExpression = whereExpression; + setPreviousObject(this.whereExpression); + } + + /** + * Gets the con sep. + * + * @return the con sep + */ + public TSqlNode getConSep() { + return conditionSeparator; + } + + /** + * Sets the con sep. + * + * @param conSep the new con sep + */ + public void setConSep(TSqlNode conSep) { + this.conditionSeparator = conSep; + setPreviousObject(this.conditionSeparator); + } + + /** + * Gets the start node. + * + * @return the start node + */ + @Override + public TParseTreeNode getStartNode() { + return whereExpression; + } + + /** + * Gets the item list node. + * + * @return the item list node + */ + @Override + public TParseTreeNode getItemListNode() { + return whereExpression; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/casenode/TCaseExprList.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/casenode/TCaseExprList.java new file mode 100644 index 0000000000000000000000000000000000000000..21111e1c2a634842ee73aa422d4de262901c234e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/casenode/TCaseExprList.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node.casenode; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TAbstractListItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; + +/** + * + * Title: TCaseExprList + * + * @since 3.0.0 + */ +public class TCaseExprList extends TParseTreeNodeList { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/casenode/TCaseStmtExpr.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/casenode/TCaseStmtExpr.java new file mode 100644 index 0000000000000000000000000000000000000000..52fea218fd3d487fbca407e2877642793636fb5a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/casenode/TCaseStmtExpr.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node.casenode; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TAbstractListItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TWhereClause; + +/** + * + * Title: TCaseStmtExpr + * + * @since 3.0.0 + */ +public class TCaseStmtExpr extends TAbstractListItem { + + private TSqlNode whenOrElse = null; + + private TWhereClause conditionExpr = null; + + private TSqlNode then = null; + + private TExpression endNode = null; + + public TSqlNode getWhenOrElse() { + return whenOrElse; + } + + public void setWhenOrElse(TSqlNode whenOrElse) { + this.whenOrElse = whenOrElse; + setPreviousObject(this.whenOrElse); + } + + public TWhereClause getConditionExpr() { + return conditionExpr; + } + + public void setConditionExpr(TWhereClause conditionExpr) { + this.conditionExpr = conditionExpr; + setPreviousObject(this.conditionExpr); + } + + public TSqlNode getThen() { + return then; + } + + public void setThen(TSqlNode then) { + this.then = then; + setPreviousObject(this.then); + } + + public TExpression getEndNode() { + return endNode; + } + + public void setEndNode(TExpression endNode) { + this.endNode = endNode; + setPreviousObject(this.endNode); + } + + @Override + public TParseTreeNode getStartNode() { + return whenOrElse; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/exceptionwhen/TWhenExprList.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/exceptionwhen/TWhenExprList.java new file mode 100644 index 0000000000000000000000000000000000000000..bb8f0879fac68fd6b6342363b86d23c24639c7a7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/exceptionwhen/TWhenExprList.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node.exceptionwhen; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TAbstractListItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; + +/** + * + * Title: TCaseExprList + * + * @since 3.0.0 + */ +public class TWhenExprList extends TParseTreeNodeList { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/exceptionwhen/TWhenStmtExpr.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/exceptionwhen/TWhenStmtExpr.java new file mode 100644 index 0000000000000000000000000000000000000000..b48cf6f29e680677436f1c77c80693dda2fc9683 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/exceptionwhen/TWhenStmtExpr.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node.exceptionwhen; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TAbstractListItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.fullstmt.TFullStmt; + +/** + * Title: TWhenStmtExpr + * + * @since 3.0.0 + */ +public class TWhenStmtExpr extends TAbstractListItem { + + private TSqlNode when = null; + + private TExpression exceptionType = null; + + private TSqlNode sqlNodeThen = null; + + private TFullStmt tFullStmt = null; + + public TSqlNode getWhen() { + return when; + } + + public void setWhen(TSqlNode when) { + this.when = when; + setPreviousObject(this.when); + } + + public TExpression getExceptionType() { + return exceptionType; + } + + public void setExceptionType(TExpression exceptionType) { + this.exceptionType = exceptionType; + setPreviousObject(this.exceptionType); + } + + /** + * get the Then node + * + * @return sqlNodeThen the sqlNodeThen + */ + public TSqlNode getThen() { + return sqlNodeThen; + } + + /** + * sets the Then node + * + * @param then the then node + */ + public void setThen(TSqlNode then) { + this.sqlNodeThen = then; + setPreviousObject(this.sqlNodeThen); + } + + /** + * gets the FullStmt + * + * @return tFullStmt the tFullStmt + */ + public TFullStmt getFullStmt() { + return tFullStmt; + } + + /** + * sets the FullStmt + * + * @param fullStmt the fullStmt + */ + public void setFullStmt(TFullStmt fullStmt) { + this.tFullStmt = fullStmt; + setPreviousObject(this.tFullStmt); + } + + @Override + public TParseTreeNode getStartNode() { + return when; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/from/TFromItem.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/from/TFromItem.java new file mode 100644 index 0000000000000000000000000000000000000000..050071abbed95e401b746f4b09fd51ddb2275e1b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/from/TFromItem.java @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node.from; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TListItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TWhereClause; + +/** + * + * Title: TFromItem + * + * @since 3.0.0 + */ +public class TFromItem extends TListItem { + + private TExpression table = null; + private TSqlNode as = null; + private TExpression aliasName = null; + + private TExpression joinType = null; + private TSqlNode on = null; + private TWhereClause joinCondition = null; + + private TSqlNode seperator = null; + + private boolean hasJoin = false; + + /** + * Gets the table. + * + * @return the table + */ + public TExpression getTable() { + return table; + } + + /** + * Sets the table. + * + * @param table the new table + */ + public void setTable(TExpression table) { + this.table = table; + setPreviousObject(this.table); + } + + /** + * Gets the as. + * + * @return the as + */ + public TSqlNode getAs() { + return as; + } + + /** + * Sets the as. + * + * @param as the new as + */ + public void setAs(TSqlNode as) { + this.as = as; + setPreviousObject(this.as); + } + + /** + * Gets the end node. + * + * @return the end node + */ + public TExpression getEndNode() { + return aliasName; + } + + /** + * Sets the alias name. + * + * @param aliasName the new alias name + */ + public void setAliasName(TExpression aliasName) { + this.aliasName = aliasName; + setPreviousObject(this.aliasName); + } + + /** + * Gets the join type. + * + * @return the join type + */ + public TExpression getJoinType() { + return joinType; + } + + /** + * Sets the join type. + * + * @param joinType the new join type + */ + public void setJoinType(TExpression joinType) { + this.joinType = joinType; + setPreviousObject(this.joinType); + } + + /** + * Gets the on. + * + * @return the on + */ + public TSqlNode getOn() { + return on; + } + + /** + * Sets the on. + * + * @param on the new on + */ + public void setOn(TSqlNode on) { + this.on = on; + setPreviousObject(this.on); + } + + /** + * Gets the join condition. + * + * @return the join condition + */ + public TWhereClause getJoinCondition() { + return joinCondition; + } + + /** + * Sets the join condition. + * + * @param joinCondition the new join condition + */ + public void setJoinCondition(TWhereClause joinCondition) { + this.joinCondition = joinCondition; + setPreviousObject(this.joinCondition); + } + + /** + * Gets the start node. + * + * @return the start node + */ + @Override + public TParseTreeNode getStartNode() { + return table; + } + + /** + * Gets the item list node. + * + * @return the item list node + */ + @Override + public TParseTreeNode getItemListNode() { + return table; + } + + /** + * Gets the seperator. + * + * @return the seperator + */ + public TSqlNode getSeperator() { + return seperator; + } + + /** + * Sets the seperator. + * + * @param seperator the new seperator + */ + public void setSeperator(TSqlNode seperator) { + this.seperator = seperator; + setPreviousObject(this.seperator); + } + + /** + * Checks if is checks for join. + * + * @return true, if is checks for join + */ + public boolean isHasJoin() { + return hasJoin; + } + + /** + * Sets the checks for join. + * + * @param hasJoin the new checks for join + */ + public void setHasJoin(boolean hasJoin) { + this.hasJoin = hasJoin; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/from/TFromItemList.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/from/TFromItemList.java new file mode 100644 index 0000000000000000000000000000000000000000..10e3a4a9be0f25ae99309537b984f13d94716be9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/from/TFromItemList.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node.from; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TAbstractListItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; + +/** + * + * Title: TFromItemList + * + * @since 3.0.0 + */ +public class TFromItemList extends TParseTreeNodeList { + + private boolean joinStmt = false; + + public boolean isJoinStmt() { + return joinStmt; + } + + public void setJoinStmt(boolean joinStmt) { + this.joinStmt = joinStmt; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/from/TJoinType.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/from/TJoinType.java new file mode 100644 index 0000000000000000000000000000000000000000..feea8c3f9c93f762caebc38b07ffa0b79b2a5aae --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/from/TJoinType.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node.from; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TListItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; + +/** + * + * Title: TJoinType + * + * @since 3.0.0 + */ +public class TJoinType extends TParseTreeNodeList { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/from/TTableList.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/from/TTableList.java new file mode 100644 index 0000000000000000000000000000000000000000..b4222890c0018ed83d39d2c6864ed443a585bc21 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/from/TTableList.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node.from; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; + +/** + * + * Title: TTableList + * + * @since 3.0.0 + */ +public class TTableList extends TParseTreeNodeList { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/from/TTableReference.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/from/TTableReference.java new file mode 100644 index 0000000000000000000000000000000000000000..582ae49cd363972e371b22cde36581a8d898c44b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/from/TTableReference.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node.from; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: TTableReference + * + * @since 3.0.0 + */ +public class TTableReference extends TParseTreeNode { + private TExpression tableExpression = null; + + public TExpression getTableExpression() { + return tableExpression; + } + + public void setTableExpression(TExpression tableExpression) { + this.tableExpression = tableExpression; + } + + @Override + public TParseTreeNode getStartNode() { + return tableExpression; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/fullstmt/TFullExpression.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/fullstmt/TFullExpression.java new file mode 100644 index 0000000000000000000000000000000000000000..b9410eec9c92e3dd9815a971f6b6ed145e3d2e60 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/fullstmt/TFullExpression.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node.fullstmt; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; + +/** + * + * Title: TFullExpression + * + * @since 3.0.0 + */ +public class TFullExpression extends TExpression { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/fullstmt/TFullListNode.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/fullstmt/TFullListNode.java new file mode 100644 index 0000000000000000000000000000000000000000..54a104ca645769e273fd6946a9a2f00f0f6d2d1d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/fullstmt/TFullListNode.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node.fullstmt; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.StringUtils; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.comm.ISQLSyntax; +import org.opengauss.mppdbide.gauss.sqlparser.parser.utils.FullNodeExpressionType; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmtbeanif.StatementBeanIf; + +/** + * Title: TFullListNode + * + * @since 3.0.0 + */ +public class TFullListNode extends TParseTreeNode { + + private FullNodeExpressionType expressionType = FullNodeExpressionType.UNKNOWN; + + private List sqlTokenDataList = new ArrayList(10); + + private TParseTreeNode nullNode = null; + + private String lastNonEmptyToken = null; + + private int nonEmptyCharcount = 0; + + public List getSqlTokenDataList() { + return sqlTokenDataList; + } + + public void setSqlTokenDataList(List sqlTokenDataList) { + this.sqlTokenDataList = sqlTokenDataList; + } + + /** + * add sqltokendata to list + * + * @param sqlTokenData which is added to sql token list + */ + public void addSqlTokenDataList(StatementBeanIf sqlTokenData) { + if (expressionType != FullNodeExpressionType.ASSIGNMENTS) { + expressionType = FullNodeExpressionType.NORMAL; + } + this.sqlTokenDataList.add(sqlTokenData); + } + + /** + * add sql tokendata with type + * + * @param sqlTokenData which is added to sql token list + */ + public void addSQLTokenData(ISQLTokenData sqlTokenData) { + if (FullNodeExpressionType.UNKNOWN == expressionType) { + if (sqlTokenData.getToken().getData() == ISQLSyntax.SQL_MULTILINE_COMMENT) { + expressionType = FullNodeExpressionType.COMMENTS; + } else if (StringUtils.isBlank(sqlTokenData.getTokenStr())) { + expressionType = FullNodeExpressionType.NEWLINES; + } else { + expressionType = FullNodeExpressionType.NORMAL; + } + } + + assignAssignmentStmt(sqlTokenData); + + this.sqlTokenDataList.add(sqlTokenData); + } + + private void assignAssignmentStmt(ISQLTokenData sqlTokenData) { + if (StringUtils.isNotBlank(sqlTokenData.getTokenStr()) && nonEmptyCharcount < 8) { + nonEmptyCharcount++; + if (expressionType != FullNodeExpressionType.ASSIGNMENTS) { + + if ("=".equals(sqlTokenData.getTokenStr()) && ":".equals(lastNonEmptyToken)) { + expressionType = FullNodeExpressionType.ASSIGNMENTS; + } + lastNonEmptyToken = sqlTokenData.getTokenStr(); + } + } + } + + public FullNodeExpressionType getExpressionType() { + return expressionType; + } + + @Override + public TParseTreeNode getStartNode() { + return nullNode; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/fullstmt/TFullStmt.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/fullstmt/TFullStmt.java new file mode 100644 index 0000000000000000000000000000000000000000..aa9b04c19bc8afadab974a1eb1de84cc60eb9b0f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/fullstmt/TFullStmt.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node.fullstmt; + +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmtbeanif.StatementBeanIf; + +/** + * + * Title: TFullStmt + * + * @since 3.0.0 + */ +public class TFullStmt extends TParseTreeNode implements StatementBeanIf { + + private List stmtList = new ArrayList(); + + /** + * Adds the stmt node. + * + * @param exp the exp + */ + public void addStmtNode(TParseTreeNode exp) { + this.stmtList.add(exp); + } + + /** + * Gets the stmt list. + * + * @return the stmt list + */ + public List getStmtList() { + return stmtList; + } + + /** + * Gets the start node. + * + * @return the start node + */ + @Override + public TParseTreeNode getStartNode() { + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/listitem/create/TCreateItem.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/listitem/create/TCreateItem.java new file mode 100644 index 0000000000000000000000000000000000000000..6eb38629b56ec5ece5870051a85374a1a22f6799 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/listitem/create/TCreateItem.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node.listitem.create; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TAbstractListItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; + +/** + * + * Title: TCreateItem + * + * @since 3.0.0 + */ +public class TCreateItem extends TAbstractListItem { + private TExpression table = null; + private TExpression expression = null; + + public TExpression getTable() { + return table; + } + + public void setTable(TExpression table) { + this.table = table; + } + + @Override + public TParseTreeNode getStartNode() { + return table; + } + + public TExpression getExpression() { + return expression; + } + + public void setExpression(TExpression expression) { + this.expression = expression; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/listitem/create/TDeclareResultColumn.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/listitem/create/TDeclareResultColumn.java new file mode 100644 index 0000000000000000000000000000000000000000..bb227d9610617deb11956f8005b57b57b3774080 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/listitem/create/TDeclareResultColumn.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node.listitem.create; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TAbstractListItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TExpression; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNode; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TSqlNode; + +/** + * Title: TDeclareResultColumn + * + * @since 3.0.0 + */ +public class TDeclareResultColumn extends TAbstractListItem { + private TExpression expression = null; + private TSqlNode seperator = null; + + /** + * Gets the start node. + * + * @return the start node + */ + @Override + public TParseTreeNode getStartNode() { + return null; + } + + /** + * Gets the expression. + * + * @return the expression + */ + public TExpression getExpression() { + return expression; + } + + /** + * Sets the expression. + * + * @param expression the new expression + */ + public void setExpression(TExpression expression) { + this.expression = expression; + setPreviousObject(this.expression); + } + + /** + * Gets the seperator. + * + * @return the seperator + */ + public TSqlNode getSeperator() { + return seperator; + } + + /** + * Sets the seperator. + * + * @param seperator the new seperator + */ + public void setSeperator(TSqlNode seperator) { + this.seperator = seperator; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/order/TOrderByItem.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/order/TOrderByItem.java new file mode 100644 index 0000000000000000000000000000000000000000..d03b9fb11994bdd6eb3f338640d7518e6d2d34e9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/order/TOrderByItem.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node.order; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TResultColumn; + +/** + * + * Title: TOrderByItem + * + * @since 3.0.0 + */ +public class TOrderByItem extends TResultColumn { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/with/TWithItem.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/with/TWithItem.java new file mode 100644 index 0000000000000000000000000000000000000000..5a6669ca22019ddc315e6d6c9662ac1cf15978be --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/with/TWithItem.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node.with; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TResultColumn; + +/** + * + * Title: TWithItem + * + * @since 3.0.0 + */ +public class TWithItem extends TResultColumn { +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/with/TWithItemList.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/with/TWithItemList.java new file mode 100644 index 0000000000000000000000000000000000000000..9a196fd820a31fc287f87daefc7daf703e07c5ff --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmt/node/with/TWithItemList.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmt.node.with; + +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TListItem; +import org.opengauss.mppdbide.gauss.sqlparser.stmt.node.TParseTreeNodeList; + +/** + * + * Title: TWithItemList + * + * @since 3.0.0 + */ +public class TWithItemList extends TParseTreeNodeList { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmtbeanif/StatementBeanIf.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmtbeanif/StatementBeanIf.java new file mode 100644 index 0000000000000000000000000000000000000000..c496f34361b963e56ea30360878a80039286acc4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/stmtbeanif/StatementBeanIf.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.stmtbeanif; + +/** + * Title: StatementBeanIf + * + * @since 3.0.0 + */ +public interface StatementBeanIf { + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/word/SQLFoldingWordDetector.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/word/SQLFoldingWordDetector.java new file mode 100644 index 0000000000000000000000000000000000000000..911585139b053341a585d6a84dc8534a1587fce1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/gauss/sqlparser/word/SQLFoldingWordDetector.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.gauss.sqlparser.word; + +/** + * + * Title: SQLFoldingWordDetector + * + * @since 3.0.0 + */ +public class SQLFoldingWordDetector { + + /** + * Checks if is word start. + * + * @param charValue the c + * @return true, if is word start + */ + public boolean isWordStart(char charValue) { + return Character.isUnicodeIdentifierStart(charValue); + } + + /** + * Checks if is word part. + * + * @param charValue the c + * @return true, if is word part + */ + public boolean isWordPart(char charValue) { + return Character.isUnicodeIdentifierPart(charValue) || charValue == '$'; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/AbstractPropertiesContext.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/AbstractPropertiesContext.java new file mode 100644 index 0000000000000000000000000000000000000000..80f876b700102eb4e71bf0d7f0db90b082e2e243 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/AbstractPropertiesContext.java @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view; + +import org.opengauss.mppdbide.presentation.IResultDisplayUIManager; +import org.opengauss.mppdbide.presentation.objectproperties.handler.PropertyHandlerCore; +import org.opengauss.mppdbide.presentation.resultsetif.IResultConfig; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.MessageQueue; +import org.opengauss.mppdbide.view.terminal.executioncontext.AbstractTerminalExecutionContext; + +/** + * + * Title: class + * + * Description: The Class AbstractPropertiesContext. + * + * @since 3.0.0 + */ +public abstract class AbstractPropertiesContext extends AbstractTerminalExecutionContext { + + /** + * The core. + */ + protected PropertyHandlerCore core; + + /** + * Instantiates a new abstract properties context. + * + * @param core2 the core 2 + */ + protected AbstractPropertiesContext(PropertyHandlerCore core2) { + super(core2.getTermConnection()); + this.core = core2; + } + + /** + * Gets the property handler core. + * + * @return the property handler core + */ + public PropertyHandlerCore getPropertyHandlerCore() { + return this.core; + } + + /** + * Can free connection after use. + * + * @return true, if successful + */ + @Override + public boolean canFreeConnectionAfterUse() { + return true; + } + + /** + * Need query parse and split. + * + * @return true, if successful + */ + @Override + public boolean needQueryParseAndSplit() { + return false; + } + + /** + * Sets the critical error thrown. + * + * @param value the new critical error thrown + */ + @Override + public void setCriticalErrorThrown(boolean value) { + MPPDBIDELoggerUtility.none(Boolean.toString(value)); + } + + /** + * Gets the query. + * + * @return the query + */ + @Override + public String getQuery() { + return null; + } + + /** + * Sets the working job context. + * + * @param jobContext the new working job context + */ + @Override + public void setWorkingJobContext(Object jobContext) { + MPPDBIDELoggerUtility.none(jobContext.toString()); + } + + /** + * Gets the notice message queue. + * + * @return the notice message queue + */ + @Override + public MessageQueue getNoticeMessageQueue() { + return null; + } + + /** + * Gets the connection profile ID. + * + * @return the connection profile ID + */ + @Override + public String getConnectionProfileID() { + return null; + } + + /** + * Handle successfull completion. + */ + @Override + public void handleSuccessfullCompletion() { + MPPDBIDELoggerUtility.none("empty msg"); + + } + + /** + * Sets the job done. + */ + @Override + public void setJobDone() { + + } + + /** + * Job type. + * + * @return the string + */ + @Override + public String jobType() { + return MPPDBIDEConstants.CANCELABLEJOB; + } + + /** + * Gets the context name. + * + * @return the context name + */ + @Override + public abstract String getContextName(); + + /** + * Gets the result config. + * + * @return the result config + */ + @Override + public abstract IResultConfig getResultConfig(); + + /** + * Gets the result display UI manager. + * + * @return the result display UI manager + */ + @Override + public abstract IResultDisplayUIManager getResultDisplayUIManager(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/AbstractPropertyViewWorker.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/AbstractPropertyViewWorker.java new file mode 100644 index 0000000000000000000000000000000000000000..dc2ace319fc6fa68723874acd5ea15872335cbe5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/AbstractPropertyViewWorker.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view; + +import java.sql.SQLException; + +import org.opengauss.mppdbide.presentation.IExecutionContext; +import org.opengauss.mppdbide.presentation.objectproperties.handler.IPropertyDetail; +import org.opengauss.mppdbide.presentation.objectproperties.handler.PropertyHandlerCore; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.logger.ILogger; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.view.terminal.TerminalQueryExecutionWorker; + +/** + * + * Title: class + * + * Description: The Class AbstractPropertyViewWorker. + * + * @since 3.0.0 + */ +public abstract class AbstractPropertyViewWorker extends TerminalQueryExecutionWorker { + + /** + * The propertycore. + */ + protected PropertyHandlerCore propertycore; + + /** + * The properties object. + */ + protected IPropertyDetail propertiesObject; + + /** + * Instantiates a new abstract property view worker. + * + * @param context the context + */ + public AbstractPropertyViewWorker(IExecutionContext context) { + super(context); + } + + /** + * Display property. + * + * @throws MPPDBIDEException the MPPDBIDE exception + * @throws SQLException the SQL exception + */ + protected void displayProperty() throws MPPDBIDEException, SQLException { + propertiesObject = propertycore.getproperty(); + + displayUIResult(); + performPostExecutionAction(); + } + + /** + * Setup display UI manager. + * + * @throws MPPDBIDEException the MPPDBIDE exception + */ + protected void setupDisplayUIManager() throws MPPDBIDEException { + MPPDBIDELoggerUtility.perf(MPPDBIDEConstants.GUI, ILogger.PERF_EXECUTE_SQLTERMINAL_QUERY, true); + this.context.setCriticalErrorThrown(false); + + this.context.getResultDisplayUIManager().handlePreExecutionUIDisplaySetup(this.context.getTermConnection(), + true); + } + + /** + * Display UI result. + */ + protected void displayUIResult() { + context.getResultDisplayUIManager().handleResultDisplay(propertiesObject); + } + + /** + * On critical exception UI action. + * + * @param exception the exception + */ + @Override + public void onCriticalExceptionUIAction(DatabaseCriticalException exception) { + context.getResultDisplayUIManager().handleExceptionDisplay(exception); + } + + /** + * On operational exception UI action. + * + * @param exception the exception + */ + @Override + public void onOperationalExceptionUIAction(DatabaseOperationException exception) { + context.getResultDisplayUIManager().handleExceptionDisplay(exception); + + } + + /** + * On MPPDBIDE exception UI action. + * + * @param exception the exception + */ + @Override + public void onMPPDBIDEExceptionUIAction(MPPDBIDEException exception) { + context.getResultDisplayUIManager().handleExceptionDisplay(exception); + } + + /** + * Final cleanup UI. + */ + @Override + public void finalCleanupUI() { + this.context.getResultDisplayUIManager().handleFinalCleanup(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/Activator.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/Activator.java new file mode 100644 index 0000000000000000000000000000000000000000..407d66ce03fdcaa1aba6a043006eccec770c67f7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/Activator.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; + +/** + * + * Title: class + * + * Description: The Class Activator. + * + * @since 3.0.0 + */ +public class Activator implements BundleActivator { + + private static BundleContext context; + private static final Object LOCK = new Object(); + + /** + * Gets the context. + * + * @return the context + */ + public static BundleContext getContext() { + return context; + } + + /** + * Start. + * + * @param bundleContext the bundle context + */ + public void start(BundleContext bundleContext) { + synchronized (LOCK) { + setContext(bundleContext); + bundleContext.getBundle().getBundleId(); + } + } + + /** + * Sets the context. + * + * @param bundleContext the new context + */ + public static void setContext(BundleContext bundleContext) { + context = bundleContext; + } + + /** + * Stop. + * + * @param bundleContext the bundle context + */ + public void stop(BundleContext bundleContext) { + removeContext(); + } + + /** + * Removes the context. + */ + public static void removeContext() { + context = null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/DsRendererFactory.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/DsRendererFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..632148386c86c644f428d82eaf9f1ef8932cc2a3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/DsRendererFactory.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view; + +import java.util.Arrays; +import java.util.List; + +import org.eclipse.e4.ui.internal.workbench.swt.AbstractPartRenderer; +import org.eclipse.e4.ui.model.application.ui.MUIElement; +import org.eclipse.e4.ui.model.application.ui.basic.MPartStack; +import org.eclipse.e4.ui.workbench.renderers.swt.WorkbenchRendererFactory; + +import org.opengauss.mppdbide.view.ui.visualexplainplan.VisualExplainPartsManager; +import org.opengauss.mppdbide.view.utils.consts.UIConstants; + +/** + * Title: DsRendererFactory + * + * Description: A factory for creating DsRenderer objects. + * + * @since 3.0.0 + */ +public class DsRendererFactory extends WorkbenchRendererFactory { + private DsStackRenderer stackRenderer; + + /** + * Gets the renderer. + * + * @param uiElement the ui element + * @param parent the parent + * @return the renderer + */ + @Override + public AbstractPartRenderer getRenderer(MUIElement uiElement, Object parent) { + if (uiElement instanceof MPartStack) { + MPartStack partStack = (MPartStack) uiElement; + List partStackIdList = Arrays.asList(UIConstants.PARTSTACK_ID_EDITOR, + VisualExplainPartsManager.MAIN_PART_STACKID, VisualExplainPartsManager.OVERALL_PROPERTIES_STACKID, + VisualExplainPartsManager.DETAILS_STACKID); + + if (partStackIdList.contains(partStack.getElementId())) { + if (null == stackRenderer) { + stackRenderer = new DsStackRenderer(); + super.initRenderer(stackRenderer); + } + + return stackRenderer; + } + } + + return super.getRenderer(uiElement, parent); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/DsStackRenderer.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/DsStackRenderer.java new file mode 100644 index 0000000000000000000000000000000000000000..fc38354876084006072bede05bc69c9e5e630ceb --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/DsStackRenderer.java @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.inject.Inject; + +import org.eclipse.core.commands.ParameterizedCommand; +import org.eclipse.core.runtime.preferences.IEclipsePreferences.PreferenceChangeEvent; +import org.eclipse.e4.core.commands.ECommandService; +import org.eclipse.e4.core.commands.EHandlerService; +import org.eclipse.e4.ui.model.application.ui.MUIElement; +import org.eclipse.e4.ui.model.application.ui.basic.MPart; +import org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.CTabFolder; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.MenuItem; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.ui.terminal.SQLTerminal; + +/** + * + * Title: class + * + * Description: The Class DsStackRenderer. + * + * @since 3.0.0 + */ +public class DsStackRenderer extends StackRenderer { + private static final int TAB_MIN_CHARS = 15; + @Inject + private EHandlerService handlerService; + + @Inject + private ECommandService commandService; + + /** + * Show tab. + * + * @param element the element + */ + @Override + protected void showTab(MUIElement element) { + ((CTabFolder) getParentWidget(element)).setMinimumCharacters(TAB_MIN_CHARS); + super.showTab(element); + } + + private void i10nlizeTabContextMenuText(Menu menu) { + + /** + * Default Eclipse text that needs to be translated to Chinese: + * + * choosePartsToSaveTitle=Save Parts choosePartsToSave=Select the parts + * to save: menuClose = &Close menuCloseOthers = Close &Others + * menuCloseAll = Close &All menuCloseRight = Close Tabs to the &Right + * menuCloseLeft = Close Tabs to the &Left viewMenu = View Menu + * tabScrollingLeft = Scroll list left tabScrollingRight = Scroll list + * right + */ + + String itemText; + String newItemText = ""; + List listToRemove = new ArrayList(1); + addContexMenuText(menu, listToRemove); + + if (listToRemove.size() >= 1) { + listToRemove.stream().forEach(item -> { + item.dispose(); + }); + } + } + + private void addContexMenuText(Menu menu, List listToRemove) { + String itemText; + String newItemText = null; + for (MenuItem item : menu.getItems()) { + itemText = item.getText(); + + switch (itemText) { + case "&Close": { + newItemText = MessageConfigLoader.getProperty(IMessagesConstants.CLOSE_TAB_MENU); + break; + } + case "Close &Others": { + newItemText = MessageConfigLoader.getProperty(IMessagesConstants.CLOSE_OTHER_TABS_MENU); + break; + } + case "Close &All": { + newItemText = MessageConfigLoader.getProperty(IMessagesConstants.CLOSE_ALL_TAB_MENU); + break; + } + case "Close Tabs to the &Right": { + newItemText = MessageConfigLoader.getProperty(IMessagesConstants.CLOSE_RIGHT_TABS_MENU); + break; + } + case "Close Tabs to the &Left": { + newItemText = MessageConfigLoader.getProperty(IMessagesConstants.CLOSE_LEFT_TABS_MENU); + break; + } + // Below are dead code as we donot use dirty flags and save all + // SQL terminal Windows (except for Edit table data window). + case "Save Parts": { + newItemText = MessageConfigLoader.getProperty(IMessagesConstants.SAVE_PARTS); + break; + } + case "Select the parts to save:": { + newItemText = MessageConfigLoader.getProperty(IMessagesConstants.SELECT_PARTS_FOR_SAVE); + break; + } + case "&Detach": + case "": { + listToRemove.add(item); + break; + } + default: { + newItemText = itemText; + break; + } + } + if (newItemText != null) { + item.setText(newItemText); + } + } + } + + /** + * Populate tab menu. + * + * @param menu the menu + * @param part the part + */ + @Override + protected void populateTabMenu(final Menu menu, final MPart part) { + if (part.getObject() instanceof SQLTerminal) { + MenuItem menuItem = new MenuItem(menu, SWT.NONE); + new MenuItem(menu, SWT.SEPARATOR); + menuItem.setText(MessageConfigLoader.getProperty(IMessagesConstants.RENAME_TERMINAL_NAME)); + menuItem.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + String sqlTerminalPart = "org.opengauss.mppdbide.view.commandparameter.sqlTerminalPart"; + Map params = new HashMap(5); + params.put(sqlTerminalPart, part.getElementId()); + ParameterizedCommand cmd = commandService + .createCommand("org.opengauss.mppdbide.view.command.renameSqlTerminal", params); + if (handlerService.canExecute(cmd)) { + handlerService.executeHandler(cmd); + } + } + }); + + if (((SQLTerminal) (part.getObject())).isFileTerminalFlag()) { + menuItem.setEnabled(false); + } + } + super.populateTabMenu(menu, part); + i10nlizeTabContextMenuText(menu); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/aliasparser/AliasParserManager.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/aliasparser/AliasParserManager.java new file mode 100644 index 0000000000000000000000000000000000000000..605991a97675534d88b22f5d19ab65c84efd0922 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/aliasparser/AliasParserManager.java @@ -0,0 +1,241 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.aliasparser; + +import java.util.ArrayList; +import java.util.Stack; + +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.view.workerjob.UIWorkerJob; + +/** + * + * Title: class + * + * Description: The Class AliasParserManager. + * + * @since 3.0.0 + */ +public class AliasParserManager extends UIWorkerJob implements IAliasParserJobManager { + + /** + * The Constant ALIAS_PARSER_MAX_WORKER_NUMBER. + */ + public static final int ALIAS_PARSER_MAX_WORKER_NUMBER = 1; + + private static volatile AliasParserManager aliasparsermanager = null; + private ArrayList aliasParserWorkerPool; + private Stack aliasParserJobStack; + private boolean isExitFlagSet; + private final Object instanceLock = new Object(); + + /** + * Instantiates a new alias parser manager. + * + * @param name the name + * @param family the family + */ + public AliasParserManager(String name, Object family) { + super(name, family); + aliasParserWorkerPool = new ArrayList(ALIAS_PARSER_MAX_WORKER_NUMBER); + initializeAliasParserJobStack(); + isExitFlagSet = false; + } + + private void initializeAliasParserJobStack() { + synchronized (instanceLock) { + aliasParserJobStack = new Stack(); + } + } + + /** + * Launch alias parser worker threads. + */ + public void launchAliasParserWorkerThreads() { + for (int workerCounter = 0; workerCounter < ALIAS_PARSER_MAX_WORKER_NUMBER; workerCounter++) { + AliasParserWorker worker = new AliasParserWorker("Alias Parser Worker:" + workerCounter, null, + workerCounter); + aliasParserWorkerPool.add(worker); + worker.schedule(); + } + } + + /** + * Sets the alias parser manager exit flag. + */ + public void setAliasParserManagerExitFlag() { + this.isExitFlagSet = true; + } + + /** + * Stop all alias parser worker threads. + */ + public void stopAllAliasParserWorkerThreads() { + for (AliasParserWorker worker : aliasParserWorkerPool) { + worker.stopAliasParserWorker(); + worker.getThread().interrupt(); + } + } + + /** + * Do job. + * + * @return the object + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws MPPDBIDEException the MPPDBIDE exception + * @throws Exception the exception + */ + @Override + public Object doJob() throws DatabaseOperationException, DatabaseCriticalException, MPPDBIDEException, Exception { + while (!this.isExitFlagSet) { + try { + if (!isAliasParserJobStackEmpty()) { + /* Pick an idle worker and assign the parsing job to it */ + for (AliasParserWorker worker : aliasParserWorkerPool) { + if (AliasParserWorkerState.IDLE == worker.getWorkerState()) { + AliasRequestResponsePacket packet = popFromAliasParserStack(); + worker.setWorkingContext(packet); + worker.schedule(); + break; + } else { + cancelAliasParserWorker(worker); + } + } + } + + Thread.sleep(10); + } catch (Exception exception) { + MPPDBIDELoggerUtility.error("Alias parser manager got exception. Ignoring...", exception); + } + } + return null; + } + + private boolean isAliasParserJobStackEmpty() { + synchronized (instanceLock) { + return aliasParserJobStack.isEmpty(); + } + } + + private AliasRequestResponsePacket popFromAliasParserStack() { + synchronized (instanceLock) { + AliasRequestResponsePacket mostRecentJob = aliasParserJobStack.pop(); + aliasParserJobStack.clear(); + return mostRecentJob; + } + } + + /** + * Gets the single instance of AliasParserManager. + * + * @return single instance of AliasParserManager + */ + public static AliasParserManager getInstance() { + return aliasparsermanager; + } + + /** + * Creates the alias parser manager instance. + */ + public static void createAliasParserManagerInstance() { + if (aliasparsermanager == null) { + aliasparsermanager = new AliasParserManager("Alias Parser", null); + } + } + + private void pushToAliasParserJobStack(AliasRequestResponsePacket job) { + synchronized (instanceLock) { + aliasParserJobStack.add(job); + } + } + + /** + * Submit alias parser job. + * + * @param job the job + */ + @Override + public void submitAliasParserJob(AliasRequestResponsePacket job) { + if (job.changeState(AliasRequestResponsePacketState.REQUEST)) { + pushToAliasParserJobStack(job); + } + } + + /** + * Cancel alias parser job. + * + * @param packetId the packet id + */ + @Override + public void cancelAliasParserJob(int packetId) { + for (AliasParserWorker worker : aliasParserWorkerPool) { + if (worker.getWorkingContext() != null && worker.getWorkingContext().getPacketId() == packetId) { + if (worker.getWorkerState() == AliasParserWorkerState.BUSY) { + cancelAliasParserWorker(worker); + } + } + } + } + + private void cancelAliasParserWorker(AliasParserWorker worker) { + worker.setCancelled(true); + worker.getThread().interrupt(); + } + + /** + * Final cleanup. + * + * @throws MPPDBIDEException the MPPDBIDE exception + */ + @Override + public void finalCleanup() throws MPPDBIDEException { + this.aliasParserWorkerPool = null; + cleanupAliasParserJobStack(); + } + + private void cleanupAliasParserJobStack() { + synchronized (instanceLock) { + this.aliasParserJobStack = null; + } + } + + /** + * On critical exception UI action. + * + * @param exception the exception + */ + @Override + public void onCriticalExceptionUIAction(DatabaseCriticalException exception) { + return; + + } + + /** + * On operational exception UI action. + * + * @param exception the exception + */ + @Override + public void onOperationalExceptionUIAction(DatabaseOperationException exception) { + return; + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/aliasparser/AliasParserWorker.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/aliasparser/AliasParserWorker.java new file mode 100644 index 0000000000000000000000000000000000000000..542be9b38bef2e3b21cc9fec1b1b858179d87d82 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/aliasparser/AliasParserWorker.java @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.aliasparser; + +import java.util.ArrayList; + +import org.opengauss.mppdbide.parser.alias.AliasParser; +import org.opengauss.mppdbide.utils.SQLTerminalQuerySplit; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.view.workerjob.UIWorkerJob; + +/** + * + * Title: class + * + * Description: The Class AliasParserWorker.Worker responsible for invoking + * parsing job and getting the parsed data + * + * @since 3.0.0 + */ +public class AliasParserWorker extends UIWorkerJob { + + private final int workerId; + private AliasParserWorkerState workerState; + private AliasRequestResponsePacket packet; + private AliasParser aliasParser; + private boolean canReschedule; + private SQLTerminalQuerySplit querySplitter; + private ArrayList queryArray; + private final Object instanceLock = new Object(); + + /** + * Instantiates a new alias parser worker. + * + * @param name the name + * @param family the family + * @param workerId the worker id + */ + public AliasParserWorker(String name, Object family, int workerId) { + super(name, family); + this.workerId = workerId; + this.aliasParser = new AliasParser(); + this.canReschedule = true; + this.queryArray = new ArrayList(1); + this.querySplitter = new SQLTerminalQuerySplit(); + this.setWorkerState(AliasParserWorkerState.IDLE); + this.packet = null; + } + + private void resetWorkerData() { + this.setWorkerState(AliasParserWorkerState.IDLE); + this.packet = null; + this.queryArray.clear(); + } + + /** + * Do job. + * + * @return the object + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws MPPDBIDEException the MPPDBIDE exception + * @throws Exception the exception + */ + @Override + public Object doJob() throws DatabaseOperationException, DatabaseCriticalException, MPPDBIDEException, Exception { + while (true) { + if (null != packet) { + setWorkerState(AliasParserWorkerState.BUSY); + + try { + /* + * Split queries in SQL terminal till current cursor + * location + */ + querySplitter.splitQuerries(queryArray, packet.getQueries(), true); + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("AliasParserWorker: splitting queries failed.", exception); + resetWorkerData(); + continue; + } + + packet.calculateQueryExtents(queryArray); + String currentQuery = packet.extractFormattedCurrentQuery(queryArray); + + if (null != currentQuery) { + /* invoke parsing of query in the request */ + aliasParser.parseQuery(currentQuery); + /* + * set parsed data in the packet and change packet state to + * indicate parsing done + */ + packet.setPContext(aliasParser.getParseContext()); + packet.changeState(AliasRequestResponsePacketState.RESPONSE); + } + resetWorkerData(); + } + Thread.sleep(10); + } + } + + /** + * Stop alias parser worker. + */ + public void stopAliasParserWorker() { + this.canReschedule = false; + } + + /** + * On success UI action. + * + * @param obj the obj + */ + @Override + public void onSuccessUIAction(Object obj) { + // This is a daemon thread. Control never comes here, hence nothing todo + stopAliasParserWorker(); + } + + /** + * On critical exception UI action. + * + * @param e the e + */ + @Override + public void onCriticalExceptionUIAction(DatabaseCriticalException e) { + // Nothing todo + } + + /** + * On operational exception UI action. + * + * @param e the e + */ + @Override + public void onOperationalExceptionUIAction(DatabaseOperationException e) { + // Nothing todo + } + + /** + * Final cleanup. + * + * @throws MPPDBIDEException the MPPDBIDE exception + */ + @Override + public void finalCleanup() throws MPPDBIDEException { + if (canReschedule) { + resetWorkerData(); + this.schedule(); + } else { + this.aliasParser = null; + this.packet = null; + } + } + + /** + * Final cleanup UI. + */ + @Override + public void finalCleanupUI() { + // Nothing todo + } + + /** + * Sets the working context. + * + * @param inPacket the new working context + */ + public void setWorkingContext(AliasRequestResponsePacket inPacket) { + this.packet = inPacket; + } + + /** + * Gets the working context. + * + * @return the working context + */ + public AliasRequestResponsePacket getWorkingContext() { + return this.packet; + } + + /** + * Gets the worker state. + * + * @return the worker state + */ + public AliasParserWorkerState getWorkerState() { + synchronized (instanceLock) { + return this.workerState; + } + } + + private void setWorkerState(AliasParserWorkerState state) { + synchronized (instanceLock) { + this.workerState = state; + } + } + + /** + * Gets the worker id. + * + * @return the worker id + */ + public int getWorkerId() { + return this.workerId; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/aliasparser/AliasParserWorkerState.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/aliasparser/AliasParserWorkerState.java new file mode 100644 index 0000000000000000000000000000000000000000..29a8cce928405afdf0bed4d7b024bb8f6b870976 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/aliasparser/AliasParserWorkerState.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.aliasparser; + +/** + * + * Title: enum + * + * Description: The Enum AliasParserWorkerState. State machine for Alias parser + * worker IDLE : Serving no job BUSY : Processing a parsing request + * + * @since 3.0.0 + */ +public enum AliasParserWorkerState { + + /** + * The idle. + */ + IDLE, + /** + * The busy. + */ + BUSY +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/aliasparser/AliasRequestResponsePacket.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/aliasparser/AliasRequestResponsePacket.java new file mode 100644 index 0000000000000000000000000000000000000000..ed925fc10eb16667e4e480c9a49918586ac854cf --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/aliasparser/AliasRequestResponsePacket.java @@ -0,0 +1,228 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.aliasparser; + +import java.util.ArrayList; + +import org.opengauss.mppdbide.bl.queryparser.ParseContext; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class AliasRequestResponsePacket. + * + * @since 3.0.0 + */ +public class AliasRequestResponsePacket { + private int packetId; + /* + * Request + */ + private String queries; + /* + * Response + */ + private ParseContext pContext; + /* + * State + */ + private AliasRequestResponsePacketState state; + /* + * prefix with dot flag + */ + private boolean isPrefixEndsWithDot; + /* + * prefix offset + */ + private int offset; + + private ArrayList queryBounds; + private static final int INVALID_ARRAY_INDEX = -1; + + /** + * Instantiates a new alias request response packet. + * + * @param queries the queries + * @param packetId the packet id + * @param isPrefixEndsWithDot the is prefix ends with dot + * @param offset the offset + */ + public AliasRequestResponsePacket(String queries, int packetId, boolean isPrefixEndsWithDot, int offset) { + this.packetId = packetId; + this.queries = queries; + this.pContext = null; + this.state = AliasRequestResponsePacketState.INIT; + this.isPrefixEndsWithDot = isPrefixEndsWithDot; + this.offset = offset; + this.queryBounds = new ArrayList(1); + } + + /** + * Gets the p context. + * + * @return the p context + */ + public ParseContext getPContext() { + return pContext; + } + + /** + * Sets the p context. + * + * @param inPContext the new p context + */ + public void setPContext(ParseContext inPContext) { + this.pContext = inPContext; + } + + /** + * Gets the queries. + * + * @return the queries + */ + public String getQueries() { + return this.queries; + } + + /** + * Gets the packet id. + * + * @return the packet id + */ + public int getPacketId() { + return this.packetId; + } + + /** + * Gets the packet state. + * + * @return the packet state + */ + public AliasRequestResponsePacketState getPacketState() { + return this.state; + } + + /** + * Change state. + * + * @param newState the new state + * @return true, if successful + */ + public boolean changeState(AliasRequestResponsePacketState newState) { + if (stateChangeAllowed(newState)) { + this.state = newState; + return true; + } + return false; + } + + /* Check if state transition of packet is valid */ + private boolean stateChangeAllowed(AliasRequestResponsePacketState newState) { + boolean returnValue; + if (MPPDBIDELoggerUtility.isDebugEnabled()) { + MPPDBIDELoggerUtility.debug( + "AliasRequestResponsePacket state change request received: FROM " + this.state + " TO " + newState); + } + switch (this.state) { + case INIT: { + if (newState == AliasRequestResponsePacketState.REQUEST) { + returnValue = true; + } else { + returnValue = false; + } + break; + } + case REQUEST: { + if (newState == AliasRequestResponsePacketState.RESPONSE) { + returnValue = true; + } else { + returnValue = false; + } + break; + } + default: { + returnValue = false; + break; + } + } + return returnValue; + } + + private boolean getPrefixEndsWithDot() { + return isPrefixEndsWithDot; + } + + private int getOffset() { + return offset; + } + + /** + * Calculate query extents. + * + * @param queryArray the query array + */ + public void calculateQueryExtents(ArrayList queryArray) { + int prevOffset = 0; + int queryLength = 0; + /* Calculate start and end offsets for each query */ + for (int item = 0; item < queryArray.size(); item++) { + queryLength = queryArray.get(item).length(); + queryBounds.add(new int[] {prevOffset, prevOffset + queryLength}); + prevOffset += queryLength + 1; + } + } + + private int getCurrentQuery() { + for (int element = 0; element < queryBounds.size(); element++) { + if (offset >= queryBounds.get(element)[0] && offset <= queryBounds.get(element)[1]) { + return element; + } + } + return INVALID_ARRAY_INDEX; + } + + private String addDummyToken(String currentQuery, int number) { + return currentQuery.substring(0, number).concat("##unknown").concat(currentQuery.substring(number)); + } + + /** + * Extract formatted current query. + * + * @param queryArray the query array + * @return the string + */ + public String extractFormattedCurrentQuery(ArrayList queryArray) { + int currentQueryIndex = getCurrentQuery(); + String currentQuery = null; + if (currentQueryIndex != INVALID_ARRAY_INDEX) { + currentQuery = queryArray.get(currentQueryIndex); + } + + /* Add a dummy string at current cursor location : Parser requirement */ + if (null != currentQuery && getPrefixEndsWithDot() && currentQueryIndex < queryBounds.size() + && queryBounds.get(currentQueryIndex).length > 0) { + currentQuery = addDummyToken(currentQuery, getOffset() - queryBounds.get(currentQueryIndex)[0]); + } + if (null != currentQuery) { + currentQuery = currentQuery.concat(";"); + } + this.queryBounds.clear(); + /* End query by semicolon */ + return currentQuery; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/aliasparser/AliasRequestResponsePacketState.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/aliasparser/AliasRequestResponsePacketState.java new file mode 100644 index 0000000000000000000000000000000000000000..e376eec19947bce80c40bb9e9479df61c7949acf --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/aliasparser/AliasRequestResponsePacketState.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.aliasparser; + +/** + * + * Title: enum + * + * Description: The Enum AliasRequestResponsePacketState. State machine for + * Alias parser packet INIT : Packet initialized REQUEST : Packet in alias + * parser job queue RESPONSE : Parsing request processed + * + * @since 3.0.0 + */ +public enum AliasRequestResponsePacketState { + + /** + * The init. + */ + INIT, + /** + * The request. + */ + REQUEST, + /** + * The response. + */ + RESPONSE +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/aliasparser/IAliasParserJobManager.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/aliasparser/IAliasParserJobManager.java new file mode 100644 index 0000000000000000000000000000000000000000..f541ee15c1c4b55706307e3ff8650cb09c79c7a3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/aliasparser/IAliasParserJobManager.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.aliasparser; + +/** + * + * Title: interface + * + * Description: The Interface IAliasParserJobManager. + * + * @since 3.0.0 + */ +public interface IAliasParserJobManager { + + /** + * Submit alias parser job. + * + * @param job the job + */ + public void submitAliasParserJob(AliasRequestResponsePacket job); + + /** + * Cancel alias parser job. + * + * @param packetId the packet id + */ + public void cancelAliasParserJob(int packetId); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/autorefresh/AutoRefreshFactory.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/autorefresh/AutoRefreshFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..11f4adaa207a1fc469e2968f37af392cb1d70154 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/autorefresh/AutoRefreshFactory.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.autorefresh; + +import java.util.HashSet; + +import org.opengauss.mppdbide.presentation.IExecutionContext; + +/** + * Title: AutoRefreshFactory + * + * Description:AutoRefreshFactory + * + * @since 3.0.0 + */ +public class AutoRefreshFactory { + + /** + * Gets the auto refresh instance. + * + * @param listOfObjects the list of objects + * @param executionContext the execution context + * @return the auto refresh instance + */ + public static AutoRefreshObject getAutoRefreshInstance(HashSet listOfObjects, + IExecutionContext executionContext) { + AutoRefreshObject autoRefreshObject; + + autoRefreshObject = new AutoRefreshOLAP(listOfObjects, executionContext); + return autoRefreshObject; + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/autorefresh/AutoRefreshOLAP.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/autorefresh/AutoRefreshOLAP.java new file mode 100644 index 0000000000000000000000000000000000000000..0b8edb1a8f73bdaf48aa8c5de1a8482a596abf61 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/autorefresh/AutoRefreshOLAP.java @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.autorefresh; + +import java.util.HashSet; +import java.util.List; +import java.util.Locale; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.INamespace; +import org.opengauss.mppdbide.bl.serverdatacache.IndexMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.groups.TableObjectGroup; +import org.opengauss.mppdbide.presentation.IExecutionContext; +import org.opengauss.mppdbide.presentation.autorefresh.RefreshObjectDetails; +import org.opengauss.mppdbide.view.utils.common.UICommonUtil; + +/** + * Title: AutoRefreshOLAP + * + * Description:AutoRefreshOLAP + * + * @since 3.0.0 + */ +public class AutoRefreshOLAP extends AutoRefreshObject { + + /** + * Instantiates a new auto refresh OLAP. + * + * @param listOfObjects the list of objects + * @param executionContext the execution context + */ + public AutoRefreshOLAP(HashSet listOfObjects, IExecutionContext executionContext) { + super(listOfObjects, executionContext); + } + + /** + * Gets the view objects. + * + * @param database the database + * @param namespace the namespace + * @param listOfObjects the list of objects + * @param tableName the table name + * @return the view objects + */ + @Override + public void getViewObjects(Database database, INamespace namespace, RefreshObjectDetails refObject2, + String tableName) { + refObject2.setParent(((Namespace) namespace).getViewGroup()); + } + + /** + * Gets the table objects. + * + * @param db the db + * @param namespace the namespace + * @param listOfObjects the list of objects + * @return the table objects + */ + @Override + public void getTableObjects(Database db, INamespace namespace, RefreshObjectDetails refObject2) { + refObject2.setParent(((Namespace) namespace).getTablesGroup()); + + } + + /** + * Gets the alter table object. + * + * @param tableName the table name + * @param namespace the namespace + * @param listOfObjects the list of objects + * @return the alter table object + */ + @Override + public void getAlterTableObject(String tableName, INamespace namespace, RefreshObjectDetails refObject2) { + tableName = getUnQuotedIdentifier(tableName); + refObject2.setParent(((Namespace) namespace).getTables().get(tableName)); + } + + /** + * Gets the alter view object. + * + * @param tableName the table name + * @param namespace the namespace + * @param listOfObjects the list of objects + * @return the alter view object + */ + @Override + public void getAlterViewObject(String tableName, INamespace namespace, RefreshObjectDetails refObject2) { + tableName = getUnQuotedIdentifier(tableName); + refObject2.setParent(((Namespace) namespace).getViewGroup().get(tableName)); + } + + /** + * Gets the un quoted identifier. + * + * @param queryString the query string + * @return the un quoted identifier + */ + public String getUnQuotedIdentifier(String queryString) { + return UICommonUtil.getUnQuotedIdentifierOLAP(queryString); + } + + /** + * Gets the trigger objects. + * + * @param Database the database + * @param INamespace the namespace + * @param RefreshObjectDetails the refresh object detail + * @return the trigger objects + */ + @Override + public void getTriggerObjects(Database database, + INamespace namespace, + RefreshObjectDetails refObject2) { + refObject2.setParent(((Namespace) namespace).getTriggerObjectGroup()); + } + + /** + * Gets the table name for index. + * + * @param namespace the namespace + * @param tableName the table name + * @return the table name for index + */ + @Override + public String getTableNameForIndex(INamespace namespace, String tableName) { + TableObjectGroup tables = ((Namespace) namespace).getTables(); + tableName = getUnQuotedIdentifier(tableName); + for (TableMetaData table : tables) { + List indexMetaData = table.getIndexArrayList(); + for (IndexMetaData index : indexMetaData) { + if (index.getName().equals(tableName)) { + tableName = index.getParent().getName(); + return tableName; + } + } + } + return tableName; + } + + @Override + protected void getDropViewObjects(Database db, INamespace namespace, RefreshObjectDetails refObject2) { + refObject2.setParent(((Namespace) namespace).getViewGroup()); + } + + @Override + protected String getQualifiedTableName(String tableName2) { + return tableName2.toLowerCase(Locale.ENGLISH); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/autorefresh/AutoRefreshObject.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/autorefresh/AutoRefreshObject.java new file mode 100644 index 0000000000000000000000000000000000000000..5293e91f0f0e45ac8cd14725308f8ee73156f17d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/autorefresh/AutoRefreshObject.java @@ -0,0 +1,597 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.autorefresh; + +import java.util.HashSet; +import java.util.Locale; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.INamespace; +import org.opengauss.mppdbide.presentation.IExecutionContext; +import org.opengauss.mppdbide.presentation.autorefresh.AutoRefreshQueryFormation; +import org.opengauss.mppdbide.presentation.autorefresh.RefreshObjectDetails; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.JSQLParserUtils; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: AutoRefresh + * + * Description:AutoRefreshObject + * + * @since 3.0.0 + */ +public abstract class AutoRefreshObject { + + private String tableName; + private String schemaName; + private Database db; + private INamespace namespace; + private INamespace destnSchema = null; + private IExecutionContext execContext; + private boolean isAlterQuery = false; + private RefreshObjectDetails refObject; + + /** + * The list of objects. + */ + HashSet listOfObjects; + private int quoteCount = 0; + + /** + * Instantiates a new auto refresh object. + * + * @param listOfObjects the list of objects + * @param executionContext the execution context + */ + public AutoRefreshObject(HashSet listOfObjects, IExecutionContext executionContext) { + this.listOfObjects = listOfObjects; + execContext = executionContext; + this.db = executionContext.getTermConnection().getDatabase(); + } + + /** + * Execute auto refresh. + * + * @param query the query + * @throws DatabaseCriticalException the database critical exception + */ + public void executeAutoRefresh(String query) throws DatabaseCriticalException { + String objType = null; + query = query.replaceAll("(--.*?(" + MPPDBIDEConstants.LINE_SEPARATOR + "|$)|\\/\\*.*?\\*\\/)", ""); + String modifiedQuery = query.toLowerCase(Locale.ENGLISH).trim().replaceAll(" +", " "); + String[] spltedQuery = query.split("\\s+"); + try { + if (modifiedQuery.startsWith(MPPDBIDEConstants.COMMENT_KW)) { + objType = parseTableRColumnDescriptionQuery(query, spltedQuery); + } else if (modifiedQuery.startsWith(MPPDBIDEConstants.ALTER_INDEX_KW) + || modifiedQuery.startsWith(MPPDBIDEConstants.ALTER_INDEX_IF_EXISTS_KW)) { + objType = parseAlterIndex(query); + } else if (modifiedQuery.startsWith(MPPDBIDEConstants.ALTER_KW) + && isAlterWithRenameRSetRAlterClause(spltedQuery)) { + objType = parseRenameSetAlterClauseFromAlterStmt(query, spltedQuery); + } else if ((modifiedQuery.startsWith(MPPDBIDEConstants.ALTER_KW) + && !(isAlterWithRenameRSetRAlterClause(spltedQuery))) + || modifiedQuery.startsWith(MPPDBIDEConstants.DROP_KW)) { + getQualifiedDDLTblNameRViewName(query); + objType = getObjectTypeForDDLstatements(query); + } else if (modifiedQuery.startsWith(MPPDBIDEConstants.CREATE_KW)) { + objType = parseCreateTable(query); + } + if (objType != null && tableName != null) { + // This check avoids repeatedly finding the schema name for + // alter index + if (!isAlterQuery) { + getSchemaNameFromSplittedQualifiedName(); + namespace = getNameSpaceObject(schemaName); + } + isNameSpaceLoaded(listOfObjects, objType); + } + } catch (DatabaseOperationException databaseOperationException) { + MPPDBIDELoggerUtility.error("Exception occured while executing auto-refresh", databaseOperationException); + } catch (DatabaseCriticalException databaseCriticalException) { + MPPDBIDELoggerUtility.error( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_DATABASE_OPERATION_FAILURE), + databaseCriticalException); + throw new DatabaseCriticalException(IMessagesConstants.ERR_DATABASE_OPERATION_FAILURE, + databaseCriticalException); + } + + } + + private String parseCreateTable(String query) throws DatabaseOperationException, DatabaseCriticalException { + String str = query; + String nstr = ""; + boolean isTbl = false; + boolean isIndex = false; + boolean isOnKW = false; + str = removeIfExistsKeywords(str); + // removing the formatting + str = str.replaceAll(MPPDBIDEConstants.NEW_LINE_SIGN, " "); + for (int index = 0; index < str.length(); index++) { + boolean isEven = evenQuotes(str.charAt(index)); + if ((str.charAt(index) == ' ' || str.charAt(index) == '(') && isEven) { + isTbl = isItTable(nstr, isTbl); + isIndex = isItIndex(nstr, isIndex); + isOnKW = isItOnKw(nstr, isOnKW); + if (isTbl) { + if (!nstr.equalsIgnoreCase(MPPDBIDEConstants.TABLE_KW) && !nstr.isEmpty()) { + tableName = nstr; + break; + } + } else if (isIndex && isOnKW) { + if (!nstr.equalsIgnoreCase("on") && !nstr.isEmpty() + && !nstr.equalsIgnoreCase(MPPDBIDEConstants.INDEX_KW)) { + tableName = nstr; + break; + } + } + nstr = ""; + } else { + nstr = nstr + str.charAt(index); + } + } + getTableNameFromLastWord(nstr, isIndex, isOnKW); + return setObjTypeForCreate(query, isTbl, isIndex); + } + + private void getTableNameFromLastWord(String nstr, boolean isIndex, boolean isOnKW) { + if (isIndex && isOnKW && tableName == null) { + tableName = nstr; + } + } + + /** + * Removes the if exists keywords. + * + * @param str the str + * @return the string + */ + public String removeIfExistsKeywords(String str) { + boolean ifNotExists = str.toLowerCase(Locale.ENGLISH).contains(MPPDBIDEConstants.IF_NOT_EXISTS_KW); + boolean ifExists = str.toLowerCase(Locale.ENGLISH).contains(MPPDBIDEConstants.IF_EXISTS_KW); + if (ifNotExists) { + str = str.replace(MPPDBIDEConstants.IF_NOT_EXISTS_KW, ""); + } + if (ifExists) { + str = str.replace(MPPDBIDEConstants.IF_EXISTS_KW, ""); + } + return str; + } + + private boolean evenQuotes(char ch) { + if (ch == '"') { + quoteCount++; + } + return quoteCount % 2 == 0; + } + + private String setObjTypeForCreate(String query, boolean isTbl, boolean isIndex) + throws DatabaseOperationException, DatabaseCriticalException { + if (isTbl || isIndex) { + return MPPDBIDEConstants.CREATE_TABLE; + } else { + getQualifiedDDLTblNameRViewName(query); + return getObjectTypeForDDLstatements(query); + } + } + + private boolean isItTable(String nstr, boolean isTbl) { + if (nstr.equalsIgnoreCase(MPPDBIDEConstants.TABLE_KW)) { + isTbl = true; + } + return isTbl; + } + + private boolean isItIndex(String nstr, boolean isIndx) { + if (nstr.equalsIgnoreCase(MPPDBIDEConstants.INDEX_KW)) { + isIndx = true; + } + return isIndx; + } + + private boolean isItOnKw(String nstr, boolean onKWFnd) { + if (nstr.equalsIgnoreCase("on")) { + onKWFnd = true; + } + return onKWFnd; + } + + /** + * Gets the object type for DD lstatements. + * + * @param query the query + * @return the object type for DD lstatements + */ + public String getObjectTypeForDDLstatements(String query) { + String objType; + objType = JSQLParserUtils.setObjectType(query); + return objType; + } + + /** + * Checks if is name space loaded. + * + * @param listOfObjects the list of objects + * @param objType the obj type + */ + public void isNameSpaceLoaded(HashSet listOfObjects, String objType) { + refObject = new RefreshObjectDetails(); + refObject.setObjectName(getTableName(tableName)); + refObject.setNamespace(namespace); + refObject.setOperationType(objType); + refObject.setDesctNamespace(destnSchema); + if (namespace != null && namespace.isLoaded()) { + AutoRefreshQueryFormation.getObjectToBeRefreshed(refObject, listOfObjects); + for (Object obj : listOfObjects) { + RefreshObjectDetails ref = (RefreshObjectDetails) obj; + String objTypeRef = ref.getOperationType(); + getRefreshObjects(objTypeRef, ref); + } + } + } + + /** + * gets the TableName + * + * @param table the table + * @return the table name + */ + protected String getTableName(String table) { + String tableName2 = table; + String regex = "^[a-zA-Z0-9_]+$"; + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(tableName2); + if (matcher.matches()) { + tableName2 = getQualifiedTableName(tableName2); + } else if (tableName2.startsWith("\"") && tableName2.endsWith("\"")) { + tableName2 = tableName2.replace('"', ' ').trim(); + } else { + // No need to to do anything + } + return tableName2; + } + + /** + * Gets the qualified table name. + * + * @param tableName2 the table name 2 + * @return the qualified table name + */ + protected abstract String getQualifiedTableName(String tableName2); + + /** + * Checks if is alter with rename R set R alter clause. + * + * @param spltedQuery the splted query + * @return true, if is alter with rename R set R alter clause + */ + public boolean isAlterWithRenameRSetRAlterClause(String[] spltedQuery) { + if (spltedQuery[3].equalsIgnoreCase(MPPDBIDEConstants.RENAME_KW) + || spltedQuery[3].equalsIgnoreCase(MPPDBIDEConstants.ALTER_KW) + || spltedQuery[3].equalsIgnoreCase(MPPDBIDEConstants.SET_KW) + || (spltedQuery[3].equalsIgnoreCase(MPPDBIDEConstants.ADD_KW) + && spltedQuery[4].equalsIgnoreCase(MPPDBIDEConstants.CONSTRAINT_KW))) { + return true; + } else { + return false; + } + } + + /** + * Parses the rename set alter clause from alter stmt. + * + * @param query the query + * @param spltedQuery the splted query + * @return the string + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public String parseRenameSetAlterClauseFromAlterStmt(String query, String[] spltedQuery) + throws DatabaseOperationException, DatabaseCriticalException { + String objType = null; + tableName = spltedQuery[2]; + objType = parseSetSchemaQuery(query, spltedQuery); + if (objType == null) { + if (spltedQuery[1].equalsIgnoreCase(MPPDBIDEConstants.TABLE_KW)) { + objType = MPPDBIDEConstants.ALTER_TABLE; + } else { + objType = MPPDBIDEConstants.ALTER_VIEW; + } + } + return objType; + } + + /** + * Gets the name space object. + * + * @param schemaName the schema name + * @return the name space object + * @throws DatabaseOperationException the database operation exception + */ + public INamespace getNameSpaceObject(String schemaName) throws DatabaseOperationException { + INamespace iNamespace = null; + try { + schemaName = getUnQuotedIdentifier(schemaName); + iNamespace = db.getNameSpaceByName(schemaName); + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("Exception occured while getting namespace object", exception); + } + return iNamespace; + } + + /** + * Parses the table R column description query. + * + * @param query the query + * @param spltedQuery the splted query + * @return the string + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + private String parseTableRColumnDescriptionQuery(String query, String[] spltedQuery) + throws DatabaseOperationException, DatabaseCriticalException { + String objType = null; + if (query.toLowerCase(Locale.ENGLISH).startsWith(MPPDBIDEConstants.COMMENT_KW) + && (spltedQuery[2].equalsIgnoreCase(MPPDBIDEConstants.TABLE_KW) + || spltedQuery[2].equalsIgnoreCase(MPPDBIDEConstants.COLUMN_KW))) { + tableName = spltedQuery[3]; + objType = MPPDBIDEConstants.ALTER_TABLE; + } + return objType; + } + + /** + * Parses the set schema query. + * + * @param query the query + * @param spltedQuery the splted query + * @return the i namespace + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + private String parseSetSchemaQuery(String query, String[] spltedQuery) + throws DatabaseOperationException, DatabaseCriticalException { + String objType = null; + String destnSchemaName = null; + for (int entry = 0; entry < (spltedQuery.length - 1); entry++) { + if (spltedQuery[entry].toLowerCase(Locale.ENGLISH).equals(MPPDBIDEConstants.SET_KW) + && spltedQuery[entry + 1].toLowerCase(Locale.ENGLISH).equals(MPPDBIDEConstants.SCHEMA_KW)) { + destnSchemaName = spltedQuery[spltedQuery.length - 1]; + destnSchema = getNameSpaceObject(destnSchemaName); + if (destnSchema != null) { + destnSchema = destnSchema.isLoaded() ? destnSchema : null; + } + + if (spltedQuery[1].equalsIgnoreCase(MPPDBIDEConstants.TABLE_KW)) { + objType = MPPDBIDEConstants.SET_SCHEMA_TABLE; + } else { + objType = MPPDBIDEConstants.SET_SCHEMA_VIEW; + } + } + } + return objType; + } + + /** + * Gets the refresh objects. + * + * @param objType the obj type + * @param refObject2 the list of objects + * @return the refresh objects + */ + public void getRefreshObjects(String objType, RefreshObjectDetails refObject2) { + switch (objType) { + case MPPDBIDEConstants.CREATE_VIEW: { + getViewObjects(db, refObject2.getNamespace(), refObject2, tableName); + break; + } + case MPPDBIDEConstants.DROP_TABLE: + case MPPDBIDEConstants.CREATE_TABLE: { + getTableObjects(db, refObject2.getNamespace(), refObject2); + break; + } + case MPPDBIDEConstants.ALTER_TABLE: { + getAlterTableObject(tableName, refObject2.getNamespace(), refObject2); + break; + } + case MPPDBIDEConstants.ALTER_VIEW: { + getAlterViewObject(tableName, refObject2.getNamespace(), refObject2); + break; + } + case MPPDBIDEConstants.DROP_VIEW: { + getDropViewObjects(db, refObject2.getNamespace(), refObject2); + break; + } + case MPPDBIDEConstants.CREATE_TRIGGER: { + getTriggerObjects(db, refObject2.getNamespace(), refObject2); + break; + } + default: { + break; + } + } + // resetting object type to make to every time it gets the latest value. + objType = ""; + } + + /** + * Gets the qualified DDL tbl name R view name. + * + * @param query the query + * @return the qualified DDL tbl name R view name + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void getQualifiedDDLTblNameRViewName(String query) + throws DatabaseOperationException, DatabaseCriticalException { + tableName = JSQLParserUtils.getQualifiedTblRViewName(query); + + } + + /** + * Gets the schema name from splitted qualified name. + * + * @return the schema name from splitted qualified name + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public void getSchemaNameFromSplittedQualifiedName() throws DatabaseOperationException, DatabaseCriticalException { + DBConnection dbConnection = execContext.getTermConnection().getConnection(); + String[] splitArray = null; + if (tableName.contains(".")) { + splitArray = JSQLParserUtils.getSplitQualifiedName(tableName, true); + if (splitArray.length > 1) { + if (tableName.startsWith("\"") || tableName.endsWith("\"") && tableName.contains(".")) { + // appending the quotes back to table/schema name + schemaName = appendQuotes(splitArray[0]); + tableName = appendQuotes(splitArray[1]); + } else { + schemaName = splitArray[0]; + tableName = splitArray[1]; + } + } else { + schemaName = db.getDefaultSchemaName(dbConnection); + } + } else { + schemaName = db.getDefaultSchemaName(dbConnection); + } + } + + private String appendQuotes(String name) { + name = "\"" + name + "\""; + return name; + } + + /** + * Gets the view objects. + * + * @param db the db + * @param namespace the namespace + * @param refObject2 the list of objects + * @param tableName the table name + * @return the view objects + */ + public abstract void getViewObjects(Database db, INamespace namespace, RefreshObjectDetails refObject2, + String tableName); + + /** + * Gets the table objects. + * + * @param db the db + * @param namespace the namespace + * @param refObject2 the list of objects + * @return the table objects + */ + public abstract void getTableObjects(Database db, INamespace namespace, RefreshObjectDetails refObject2); + + /** + * gets the AlterTableObject + * + * @param tableName the tableName + * @param namespace the namespace + * @param refObject2 the refObject2 + */ + public abstract void getAlterTableObject(String tableName, INamespace namespace, RefreshObjectDetails refObject2); + + /** + * gets the AlterViewObject + * + * @param tableName the tableName + * @param namespace the namespace + * @param refObject2 the refObject2 + */ + public abstract void getAlterViewObject(String tableName, INamespace namespace, RefreshObjectDetails refObject2); + + /** + * Gets the un quoted identifier. + * + * @param str the str + * @return the un quoted identifier + */ + public abstract String getUnQuotedIdentifier(String str); + + /** + * Gets the table for index. + * + * @param ns the ns + * @param tableName the table name + * @return the table for index + */ + private String parseAlterIndex(String query) throws DatabaseOperationException, DatabaseCriticalException { + isAlterQuery = true; + String str = removeIfExistsKeywords(query); + String nstr = ""; + boolean isIndex = false; + for (int index = 0; index < str.length(); index++) { + boolean isEven = evenQuotes(str.charAt(index)); + if (str.charAt(index) == ' ' && isEven) { + isIndex = isItIndex(nstr, isIndex); + if (isIndex) { + if (!nstr.isEmpty() && !nstr.equalsIgnoreCase(MPPDBIDEConstants.INDEX_KW)) { + tableName = nstr; + break; + } + } + nstr = ""; + } else { + nstr = nstr + str.charAt(index); + } + } + getSchemaNameFromSplittedQualifiedName(); + namespace = getNameSpaceObject(schemaName); + if (namespace != null) { + tableName = getTableNameForIndex(namespace, tableName); + } + return MPPDBIDEConstants.ALTER_TABLE; + } + + /** + * Gets the table name for index. + * + * @param namespace the namespace + * @param tableName the table name + * @return the table name for index + */ + protected abstract String getTableNameForIndex(INamespace namespace, String tableName); + + /** + * Gets the drop view objects. + * + * @param db the db + * @param namespace the namespace + * @param refObject2 the list of objects + * @return the drop view objects + */ + protected abstract void getDropViewObjects(Database db, INamespace namespace, RefreshObjectDetails refObject2); + + /** + * Gets the create trigger objects + * + * @param Database the db + * @param INamespace the namespace + * @param RefreshObjectDetails the refresh object detail + */ + protected abstract void getTriggerObjects(Database db, INamespace namespace, RefreshObjectDetails refObject2); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/autorefresh/RefreshObjects.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/autorefresh/RefreshObjects.java new file mode 100644 index 0000000000000000000000000000000000000000..60a9166121b93d2934520f06f3858d874dda2e65 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/autorefresh/RefreshObjects.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.autorefresh; + +import java.util.Locale; + +import org.eclipse.jface.viewers.TreeViewer; + +import org.opengauss.mppdbide.bl.serverdatacache.groups.FilterObject; +import org.opengauss.mppdbide.presentation.autorefresh.RefreshObjectDetails; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.messaging.Message; +import org.opengauss.mppdbide.view.core.statusbar.ObjectBrowserStatusBarProvider; + +/** + * Title: RefreshObjects + * + * @since 3.0.0 + */ +public class RefreshObjects { + /** + * Refresh objects in tree viewer. + * + * @param objectDetail the object detail + * @param viewer the viewer + */ + public static void refreshObjectsInTreeViewer(RefreshObjectDetails objectDetail, TreeViewer viewer) { + String operationType = objectDetail.getOperationType(); + if (null == operationType) { + return; + } + switch (operationType) { + case "CREATE_TABLE": + case "CREATE_FUNC_PROC": + case "CREATE_VIEW": + case "CREATE_TRIGGER": { + String text = FilterObject.getInstance().getFilterText(); + if ((text == null) || (objectDetail.getObjToBeRefreshed().getName().toLowerCase(Locale.ENGLISH) + .contains(text.toLowerCase(Locale.ENGLISH)))) { + viewer.add(objectDetail.getParent(), objectDetail.getObjToBeRefreshed()); + viewer.update(objectDetail.getParent(), null); + if ("CREATE_TRIGGER".equals(operationType) || "CREATE_VIEW".equals(operationType)) { + viewer.refresh(); + } + } + break; + } + case "ALTER_TABLE": + // fall through + case "ALTER_VIEW": { + viewer.refresh(objectDetail.getObjToBeRefreshed()); + break; + } + case "DROP_TABLE": + // fall through + case "DROP_VIEW": { + viewer.remove(objectDetail.getObjToBeRefreshed()); + viewer.update(objectDetail.getParent(), null); + break; + } + default: { + break; + } + } + ObjectBrowserStatusBarProvider.getStatusBar().displayMessage( + Message.getError(MessageConfigLoader.getProperty(IMessagesConstants.AUTO_REFRESH_SUCCESS_MSG))); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/autosave/AutoSaveLazyLoader.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/autosave/AutoSaveLazyLoader.java new file mode 100644 index 0000000000000000000000000000000000000000..510e7bc5fd2de0a1c924403767e32025bea99b7f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/autosave/AutoSaveLazyLoader.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.autosave; + +import java.util.List; + +import org.opengauss.mppdbide.bl.autosave.AutoSaveMetadata; +import org.opengauss.mppdbide.bl.util.ExecTimer; +import org.opengauss.mppdbide.bl.util.IExecTimer; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.ui.autosave.IAutoSaveObject; +import org.opengauss.mppdbide.view.utils.UIElement; +import org.opengauss.mppdbide.view.workerjob.UIWorkerJob; + +/** + * + * Title: class + * + * Description: The Class AutoSaveLazyLoader. + * + * @since 3.0.0 + */ +public class AutoSaveLazyLoader extends UIWorkerJob { + + /** + * The autosave MD list. + */ + List autosaveMDList; + + /** + * The part object list. + */ + List partObjectList; + + /** + * The timer. + */ + IExecTimer timer; + + /** + * Instantiates a new auto save lazy loader. + * + * @param autosaveMDList1 the autosave MD list 1 + * @param partObjectList1 the part object list 1 + */ + public AutoSaveLazyLoader(List autosaveMDList1, List partObjectList1) { + super(MessageConfigLoader.getProperty(IMessagesConstants.PRESERVESQL_STARTUP_LAZY_JOB_NAME), null); + autosaveMDList = autosaveMDList1; + partObjectList = partObjectList1; + } + + /** + * Do job. + * + * @return the object + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws MPPDBIDEException the MPPDBIDE exception + * @throws Exception the exception + */ + @Override + public Object doJob() throws DatabaseOperationException, DatabaseCriticalException, MPPDBIDEException, Exception { + timer = new ExecTimer("AutoSaveLazyLoader Job"); + timer.start(); + AutoSaveManager.getInstance().readAutoSaveFilesForLazyLoad(autosaveMDList, partObjectList); + return null; + } + + /** + * On operational exception UI action. + * + * @param exception the exception + */ + @Override + public void onOperationalExceptionUIAction(DatabaseOperationException exception) { + showFailedStatus(); + } + + /** + * On success UI action. + * + * @param obj the obj + */ + @Override + public void onSuccessUIAction(Object obj) { + UIElement.getInstance().setStatusBarMessage( + MessageConfigLoader.getProperty(IMessagesConstants.PRESERVESQL_STARTUP_LOADING_FINISHED)); + } + + /** + * Final cleanup. + * + * @throws MPPDBIDEException the MPPDBIDE exception + */ + @Override + public void finalCleanup() throws MPPDBIDEException { + timer.stopAndLog(); + } + + /** + * Final cleanup UI. + */ + @Override + public void finalCleanupUI() { + } + + private void showFailedStatus() { + UIElement.getInstance().setStatusBarMessage( + MessageConfigLoader.getProperty(IMessagesConstants.PRESERVESQL_STARTUP_LOADING_FAILED)); + } + + /** + * On critical exception UI action. + * + * @param exception the exception + */ + @Override + public void onCriticalExceptionUIAction(DatabaseCriticalException exception) { + showFailedStatus(); + } + + /** + * On MPPDBIDE exception UI action. + * + * @param exception the exception + */ + @Override + public void onMPPDBIDEExceptionUIAction(MPPDBIDEException exception) { + super.onMPPDBIDEExceptionUIAction(exception); + showFailedStatus(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/autosave/AutoSaveManager.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/autosave/AutoSaveManager.java new file mode 100644 index 0000000000000000000000000000000000000000..5c23ac0c8bf9af4f3ea3e5fda0556d47b8e388d7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/autosave/AutoSaveManager.java @@ -0,0 +1,1068 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.autosave; + +import java.io.FileOutputStream; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; + +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.preference.PreferenceStore; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; + +import org.opengauss.mppdbide.bl.autosave.AutoSaveDbgObjInfo; +import org.opengauss.mppdbide.bl.autosave.AutoSaveInfo; +import org.opengauss.mppdbide.bl.autosave.AutoSaveMetadata; +import org.opengauss.mppdbide.bl.autosave.AutosaveFileUtility; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.DebugObjects; +import org.opengauss.mppdbide.bl.serverdatacache.IDebugObject; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.util.ExecTimer; +import org.opengauss.mppdbide.bl.util.IExecTimer; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DataStudioSecurityException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.FileOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import org.opengauss.mppdbide.view.prefernces.PreferenceWrapper; +import org.opengauss.mppdbide.view.ui.autosave.AutoSaveTerminalStatus; +import org.opengauss.mppdbide.view.ui.autosave.IAutoSaveDbgObject; +import org.opengauss.mppdbide.view.ui.autosave.IAutoSaveObject; +import org.opengauss.mppdbide.view.utils.Preferencekeys; +import org.opengauss.mppdbide.view.utils.UIElement; +import org.opengauss.mppdbide.view.utils.dialog.NonCloseableDialog; +import org.opengauss.mppdbide.view.workerjob.UIWorkerJob; + +/** + * + * Title: class + * + * Description: The Class AutoSaveManager. + * + * @since 3.0.0 + */ +public class AutoSaveManager implements Preferencekeys { + + /** + * The worker. + */ + AutoSaveWorker worker = null; + + /** + * The Constant DEFAULT_INTERVAL. + */ + + public static final int DEFAULT_INTERVAL = 5; + + private AutoSaveInfo autosaveInfo; + + private static boolean isAutoSave = true; + + private static boolean isAutoSaveEncrypted = true; + + private static int autoSaveInterval = DEFAULT_INTERVAL * 1000 * 60; + + private static volatile AutoSaveManager autosaveManager = null; + + private static final Object LOCK = new Object(); + private final Object instanceLock = new Object(); + + private static final String AUTOSAVE_INFO_FILENAME = "autosave.info"; + + private static final String AUTOSAVE_INFO_TMP_FILENAME = "autosave_tmp.info"; + + private static final String AUTOSAVE_DATA_FILE_PATTERN = ".autosave"; + + private boolean isInitialized = false; + + private AutosaveFileUtility autosaveFileUtility; + + private long startTime; + + private static final long STARTUP_CUTOFF_DURATION = 10 * 1000L; + + private volatile IAutoSaveObject partObject = null; + private boolean isOneTabLoaded; + + private AutoSaveManager() { + this.autosaveFileUtility = new AutosaveFileUtility(); + } + + /** + * Gets the single instance of AutoSaveManager. + * + * @return single instance of AutoSaveManager + */ + public static AutoSaveManager getInstance() { + if (autosaveManager == null) { + synchronized (LOCK) { + if (autosaveManager == null) { + autosaveManager = new AutoSaveManager(); + } + } + } + + return autosaveManager; + } + + /** + * Initialize. + * + * @throws FileOperationException the file operation exception + * @throws DatabaseOperationException the database operation exception + * @throws UnsupportedPlatformException the unsupported platform exception + */ + public void initialize() throws FileOperationException, DatabaseOperationException { + synchronized (instanceLock) { + if (!isInitialized) { + autosaveFileUtility.createFolderStructure(); + loadAutosaveInfo(); + isInitialized = true; + } + } + } + + /** + * Destroy. + * + * @throws FileOperationException the file operation exception + */ + public void destroy() throws FileOperationException { + synchronized (instanceLock) { + if (isInitialized) { + autosaveFileUtility.deleteFolderStructure(); + autosaveInfo.invalidate(); + autosaveInfo = null; + isInitialized = false; + } + } + } + + /** + * Gets the autosave info. + * + * @return the autosave info + */ + public AutoSaveInfo getAutosaveInfo() { + return autosaveInfo; + } + + /** + * Save auto save info. + * + * @throws FileOperationException the file operation exception + */ + public void saveAutoSaveInfo() throws FileOperationException { + autosaveFileUtility.saveAutosaveInfo(autosaveInfo, AUTOSAVE_INFO_FILENAME, AUTOSAVE_INFO_TMP_FILENAME); + } + + private void loadAutosaveInfo() throws FileOperationException { + if (autosaveInfo == null) { + try { + autosaveInfo = readAutoSaveInfo(); + } catch (MPPDBIDEException exception) { + MPPDBIDELoggerUtility.error("AutoSaveManager: load auto save info failed.", exception); + } + // No info available, so create new and add a new info on the disk + if (autosaveInfo == null) { + autosaveInfo = new AutoSaveInfo(); + autosaveFileUtility.saveAutosaveInfo(autosaveInfo, AUTOSAVE_INFO_FILENAME, AUTOSAVE_INFO_TMP_FILENAME); + } + } + } + + /** + * Delete autosave metadata. + * + * @param metaData the meta data + */ + public void deleteAutosaveMetadata(AutoSaveMetadata metaData) { + if (metaData != null) { + boolean isRemoved = autosaveInfo.removeAutoSaveMetadata(metaData); + if (isRemoved) { + autosaveFileUtility.deleteFile(metaData.getAutoSaveFileName()); + } + } + } + + /** + * Gets the data writer. + * + * @param metaData the meta data + * @return the data writer + * @throws FileOperationException the file operation exception + */ + public FileOutputStream getDataWriter(AutoSaveMetadata metaData) throws FileOperationException { + return autosaveFileUtility.getFileOutputStream(metaData); + } + + /** + * + * Title: class + * + * Description: The Class CheckWorkerSleeping. + */ + /* + * A class can implement Callable interface to provide call method that + * returns boolean + */ + private class CheckWorkerSleeping implements Callable { + @Override + public Boolean call() { + if (worker == null) { + return false; + } + return worker.getState() == Job.SLEEPING; + } + } + + /** + * + * Title: class + * + * Description: The Class CheckWorkerFinished. + */ + private static class CheckWorkerFinished implements Callable { + private AutoSaveLoader loadWorker = null; + + @Override + public Boolean call() { + if (getLoadWorker() == null) { + return false; + } + return getLoadWorker().isFinished(); + } + + /** + * Gets the load worker. + * + * @return the load worker + */ + public AutoSaveLoader getLoadWorker() { + return loadWorker; + } + + /** + * Sets the load worker. + * + * @param loadWorker the new load worker + */ + public void setLoadWorker(AutoSaveLoader loadWorker) { + this.loadWorker = loadWorker; + } + + } + + /* + * inputs Callable interface implementation as event loop breaker if it is + * null, loops until Shell is disposed + */ + private void runEventLoop(Shell loopShell, Callable breakConditionChecker) { + + // Use the display provided by the shell if possible + Display display; + if (loopShell == null) { + display = Display.getDefault(); + } else { + display = loopShell.getDisplay(); + } + + while (loopShell != null && !loopShell.isDisposed()) { + try { + /* + * if condition breaker parameter is present, check if breaking + * condition is true break event loop and return in that case + */ + if (breakConditionChecker != null) { + Boolean res = breakConditionChecker.call(); + if (res != null && res.booleanValue()) { + return; + } + } + } catch (Exception exception) { + MPPDBIDELoggerUtility.error("AutoSaveManager: Exception thrown by callable interface", exception); + } + + try { + if (!display.readAndDispatch()) { + display.sleep(); + } + } catch (Throwable exception) { + MPPDBIDELoggerUtility.error("AutoSaveManager: display interrupted", exception); + } + } + if (!display.isDisposed()) { + display.update(); + } + } + + /** + * Load. + */ + public void load() { + NonCloseableDialog dialog = new NonCloseableDialog( + MessageConfigLoader.getProperty(IMessagesConstants.PRESERVESQL_STARTUP_DIALOG_MESSAGE), + Display.getDefault().getActiveShell()); + Job loaderJob = new AutoSaveLoader(this, dialog); + + dialog.setBlockOnOpen(false); + dialog.open(); + + loaderJob.schedule(); + CheckWorkerFinished checkWorkerFinished = new CheckWorkerFinished(); + checkWorkerFinished.setLoadWorker((AutoSaveLoader) loaderJob); + runEventLoop(dialog.getShell(), checkWorkerFinished); + dialog.close(); + } + + /** + * Graceful exit. + */ + public void gracefulExit() { + NonCloseableDialog dialog = new NonCloseableDialog( + MessageConfigLoader.getProperty(IMessagesConstants.PRESERVESQL_GRACEFUL_EXIT_MSG), + Display.getDefault().getActiveShell()); + dialog.setBlockOnOpen(false); + dialog.open(); + if (worker != null && worker.getState() != Job.NONE) { + if (worker.getState() == Job.SLEEPING) { + worker.wakeUp(); + worker.schedule(); + } + runEventLoop(dialog.getShell(), new CheckWorkerSleeping()); + } + dialog.close(); + } + + /** + * Creates the periodic worker job. + */ + public void createPeriodicWorkerJob() { + worker = new AutoSaveWorker(MessageConfigLoader.getProperty(IMessagesConstants.PRESERVESQL_PERIODIC_JOB_NAME), + null); + worker.schedule(getAutoSaveInterval()); + } + + /** + * Gets the auto save interval. + * + * @return the auto save interval + */ + public int getAutoSaveInterval() { + return autoSaveInterval; + } + + /** + * Checks if is auto save enabled. + * + * @return true, if is auto save enabled + */ + public boolean isAutoSaveEnabled() { + return isAutoSave; + } + + /** + * Checks if is auto save encrypted. + * + * @return true, if is auto save encrypted + */ + public boolean isAutoSaveEncrypted() { + return isAutoSaveEncrypted; + } + + private IAutoSaveObject createPart(final UIElement uielement, final AutoSaveMetadata autosaveMD) { + Display.getDefault().syncExec(new Runnable() { + @Override + public void run() { + partObject = null; + if (MPPDBIDEConstants.SQL_TERMINAL.equals(autosaveMD.getType())) { + partObject = uielement.createNewTerminal(autosaveMD.getDatabaseName(), + autosaveMD.getConnectionName(), autosaveMD.getTabID(), autosaveMD.getTabLabel(), + autosaveMD.getTabToolTip()); + } else if (MPPDBIDEConstants.PLSQL_EDITOR.equals(autosaveMD.getType())) { + AutoSaveDbgObjInfo dbgObj = autosaveMD.getDbgObjInfo(); + if (dbgObj != null) { + IDebugObject obj = null; + obj = new DebugObjects(dbgObj.getOid(), dbgObj.getName(), dbgObj.getObjType(), null); + partObject = uielement.createEditor(obj, autosaveMD.getTabID(), autosaveMD.getTabLabel(), + autosaveMD.getTabToolTip(), dbgObj.isDirty()); + if (partObject instanceof IAutoSaveDbgObject) { + IAutoSaveDbgObject autosavedbgObj = (IAutoSaveDbgObject) partObject; + autosavedbgObj.setDirty(dbgObj.isDirty()); + autosavedbgObj.setNamespaceName(dbgObj.getSchemaName()); + } + } + } + + } + }); + + return partObject; + } + + private boolean isValidMetadata(AutoSaveMetadata autosaveMD) { + if (autosaveMD.getConnectionName() == null || "".equals(autosaveMD.getConnectionName())) { + + return false; + } + + if (autosaveMD.getDatabaseName() == null || "".equals(autosaveMD.getDatabaseName())) { + return false; + } + + if (autosaveMD.getTabID() == null || "".equals(autosaveMD.getTabID())) { + return false; + } + + if (autosaveMD.getTabLabel() == null || "".equals(autosaveMD.getTabLabel())) { + return false; + } + + if (autosaveMD.getTabToolTip() == null || "".equals(autosaveMD.getTabToolTip())) { + return false; + } + + if (autosaveMD.getType() == null || "".equals(autosaveMD.getType())) { + return false; + } + + if (autosaveMD.getAutoSaveFileName() == null || "".equals(autosaveMD.getAutoSaveFileName())) { + return false; + } + + if (!autosaveMD.calcAndCompare()) { + return false; + } + + return isValidEncoding(autosaveMD.getEncoding()); + } + + private boolean isValidEncoding(String encoding) { + if (encoding == null || "".equals(encoding)) { + return false; + } + + return true; + } + + private boolean isValidDbgObjInfo(AutoSaveDbgObjInfo dbgObjInfo) { + if (dbgObjInfo.getName() == null || "".equals(dbgObjInfo.getName())) { + return false; + } + + if (dbgObjInfo.getSchemaName() == null || "".equals(dbgObjInfo.getSchemaName())) { + return false; + } + + if (dbgObjInfo.getObjType() == null) { + return false; + } + + if (OBJECTTYPE.PLSQLFUNCTION != dbgObjInfo.getObjType() && OBJECTTYPE.SQLFUNCTION != dbgObjInfo.getObjType() + && OBJECTTYPE.PROCEDURE != dbgObjInfo.getObjType() && OBJECTTYPE.CFUNCTION != dbgObjInfo.getObjType()) { + return false; + } + + return true; + } + + private boolean verifyAutoSaveMD(AutoSaveMetadata autosaveMD) { + autosaveMD.setVersionNumber(-1); + if (!isValidMetadata(autosaveMD)) { + return false; + } + + if (!MPPDBIDEConstants.SQL_TERMINAL.equals(autosaveMD.getType()) + && !MPPDBIDEConstants.PLSQL_EDITOR.equals(autosaveMD.getType())) { + return false; + } + + if (MPPDBIDEConstants.SQL_TERMINAL.equals(autosaveMD.getType()) && autosaveMD.getDbgObjInfo() != null) { + return false; + } + + if (MPPDBIDEConstants.PLSQL_EDITOR.equals(autosaveMD.getType())) { + if (autosaveMD.getDbgObjInfo() == null) { + return false; + } + + if (!isValidDbgObjInfo(autosaveMD.getDbgObjInfo())) { + return false; + } + } + double fileLimit = PreferenceWrapper.getInstance().getPreferenceStore() + .getInt(Preferencekeys.FILE_LIMIT_FOR_SQL); + if (autosaveFileUtility.isValidFile(autosaveMD.getAutoSaveFileName(), fileLimit)) { + autosaveMD.setVersionNumber(0); + return true; + } + + return false; + } + + private AutoSaveInfo readAutoSaveInfo() throws MPPDBIDEException { + // Read from Main File, Not found then try to read from tmp file + AutoSaveInfo info = null; + try { + info = autosaveFileUtility.getAutosaveInfo(getAutosaveInfoFilename(), UIElement.getMaxTabsAllowed()); + } catch (MPPDBIDEException exception) { + MPPDBIDELoggerUtility.error("Failed to read saved autosave info", exception); + } + + if (null == info) { + info = autosaveFileUtility.getAutosaveInfo(getAutosaveInfoTmpFilename(), UIElement.getMaxTabsAllowed()); + if (info != null) { + autosaveFileUtility.rename(getAutosaveInfoTmpFilename(), getAutosaveInfoFilename()); + } + } + + return info; + } + + /** + * Sets the default preferences. + * + * @param ps the new default preferences + */ + public static void setDefaultPreferences(PreferenceStore ps) { + ps.setDefault(AUTOSAVE_ENABLE_PREFERENCE_KEY, true); + ps.setDefault(AUTOSAVE_INTERVAL_PREFERENCE_KEY, DEFAULT_INTERVAL); + ps.setDefault(AUTOSAVE_ENCRYPTION_PREFERENCE_FLAG, true); + } + + /** + * Update autosave preferences. + * + * @param preferenceStore the preference store + */ + public static void updateAutosavePreferences(IPreferenceStore preferenceStore) { + synchronized (LOCK) { + isAutoSave = preferenceStore.getBoolean(AUTOSAVE_ENABLE_PREFERENCE_KEY); + autoSaveInterval = preferenceStore.getInt(AUTOSAVE_INTERVAL_PREFERENCE_KEY) * 1000 * 60; + isAutoSaveEncrypted = preferenceStore.getBoolean(AUTOSAVE_ENCRYPTION_PREFERENCE_FLAG); + } + } + + private void readTerminal(IAutoSaveObject obj, AutoSaveMetadata autosaveMD) { + String terminalRawData = null; + + try { + obj.updateStatus(AutoSaveTerminalStatus.LOADING); + terminalRawData = readData(autosaveMD.getAutoSaveFileName(), autosaveMD.isEncrypted(), + autosaveMD.getEncoding()); + obj.setText(terminalRawData); + + // So that first periodic job do not trigger file write if no + // modification done. + obj.setModified(false); + if (obj instanceof IAutoSaveDbgObject) { + IAutoSaveDbgObject objDbg = (IAutoSaveDbgObject) obj; + objDbg.getDebugObject().getSourceCode().setCode(terminalRawData); + } + } catch (Error | MPPDBIDEException exception) { + MPPDBIDELoggerUtility.error("Error while reading SQL terminal data for Autosave", exception); + } finally { + obj.setEditable(true); + obj.updateStatus(AutoSaveTerminalStatus.LOAD_FINISHED); + } + } + + /** + * Read auto save files. + * + * @param autosaveMDList the autosave MD list + * @param partObjectList2 the part object list 2 + * @return true, if successful + */ + public boolean readAutoSaveFiles(List autosaveMDList, List partObjectList2) { + int terminalCnt = autosaveMDList.size(); + IAutoSaveObject obj = null; + + int count; + for (count = 0; count < terminalCnt && !isCutOffTimeReached(); count++) { + if (partObjectList2.size() > count) { + obj = partObjectList2.get(count); + } + + if (obj != null && obj.getStatus() == AutoSaveTerminalStatus.INIT) { + readTerminal(obj, autosaveMDList.get(count)); + } + } + + return count == terminalCnt; + } + + /** + * Read auto save files for lazy load. + * + * @param autosaveMDList the autosave MD list + * @param partObjectList2 the part object list 2 + */ + public void readAutoSaveFilesForLazyLoad(List autosaveMDList, + List partObjectList2) { + int terminalCnt = autosaveMDList.size(); + IAutoSaveObject obj = null; + + for (int count = 0; count < terminalCnt; count++) { + if (partObjectList2.size() > count) { + obj = partObjectList2.get(count); + } + + if (obj != null && obj.getStatus() == AutoSaveTerminalStatus.INIT) { + readTerminal(obj, autosaveMDList.get(count)); + } + } + } + + /** + * Start cut off time. + */ + public void startCutOffTime() { + startTime = System.currentTimeMillis(); + } + + private boolean isCutOffTimeReached() { + long currTime = System.currentTimeMillis(); + if (currTime - startTime >= STARTUP_CUTOFF_DURATION) { + return true; + } + + return false; + } + + private String readData(String fileName, boolean isEncrypted, String charSet) throws MPPDBIDEException { + + double fileLimit = PreferenceWrapper.getInstance().getPreferenceStore() + .getInt(Preferencekeys.FILE_LIMIT_FOR_SQL); + byte[] data = autosaveFileUtility.read(fileName, fileLimit); + String text = null; + try { + SecureUtil secureUtil = new SecureUtil(); + secureUtil.setPackagePath(ConnectionProfileManagerImpl.getInstance().getDiskUtility().getOsCurrentUserFolderPath()); + if (isEncrypted) { + data = secureUtil.decryptByteArray(data); + } + + text = new String(data, charSet); + } catch (UnsupportedEncodingException exp) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.PRESERVESQL_FILEENCODINGEXCEPTION), exp); + throw new MPPDBIDEException(IMessagesConstants.PRESERVESQL_FILEENCODINGEXCEPTION); + } catch (DataStudioSecurityException exp) { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_DS_SECURITY_ERROR), exp); + throw new MPPDBIDEException(IMessagesConstants.ERR_DS_SECURITY_ERROR); + } + + return text; + } + + private boolean loadAutoSaveInformation(AutoSaveInfo info) { + List partObjectList = new ArrayList<>(1); + List autosaveMDList = info.getAutosaveMD(); + + AutoSaveMetadata autosaveMD = null; + final UIElement uielement = UIElement.getInstance(); + int terminalCnt = autosaveMDList.size(); + + String activeTerminal = info.getActiveTerminalName(); + int activeTabId = -1; + + startCutOffTime(); + for (int element = 0; element < terminalCnt; element++) { + autosaveMD = autosaveMDList.get(element); + + if (activeTerminal != null && activeTerminal.equals(autosaveMD.getTabID())) { + activeTabId = element; + } + + if (verifyAutoSaveMD(autosaveMD)) { + setAutoSaveObjectData(partObjectList, autosaveMD, uielement, element); + } else { + partObjectList.add(element, null); + } + } + + partObject = null; + activeTabId = getActiveTerminal(partObjectList, activeTabId); + + readActiveTerminals(partObjectList, autosaveMDList, uielement, terminalCnt, activeTabId); + + boolean isAllLoaded = readAutoSaveFiles(autosaveMDList, partObjectList); + if (!isAllLoaded) { + createLazyLoadJob(autosaveMDList, partObjectList); + } + + return isAllLoaded; + } + + private void readActiveTerminals(List partObjectList, List autosaveMDList, + final UIElement uielement, int terminalCnt, int activeTabId) { + if (activeTabId < terminalCnt && partObjectList.get(activeTabId) != null) { + final String tabId = autosaveMDList.get(activeTabId).getTabID(); + + // Read the active terminal first + readTerminal(partObjectList.get(activeTabId), autosaveMDList.get(activeTabId)); + Display.getDefault().syncExec(new Runnable() { + @Override + public void run() { + uielement.bringPartOnTop(tabId); + } + }); + } + } + + private boolean setAutoSaveObjectData(List partObjectList, AutoSaveMetadata autosaveMD, + final UIElement uielement, int count) { + boolean isMaxPopupOpened = false; + if (!uielement.isWindowLimitReached()) { + try { + IAutoSaveObject obj = createPart(uielement, autosaveMD); + partObjectList.add(count, obj); + if (obj != null) { + isOneTabLoaded = true; + obj.setEditable(false); + obj.updateStatus(AutoSaveTerminalStatus.INIT); + obj.setConnectionName(autosaveMD.getConnectionName()); + obj.setDatabaseName(autosaveMD.getDatabaseName()); + obj.setElementID(autosaveMD.getTabID()); + obj.setTabLabel(autosaveMD.getTabLabel()); + obj.setTabToolTip(autosaveMD.getTabToolTip()); + obj.setModifiedAfterCreate(true); + // connection dependent buttons + obj.resetConnButtons(false); + + obj.resetButtons(); // db dependent buttons + } + } catch (Exception | OutOfMemoryError exception) { + MPPDBIDELoggerUtility.error("AutoSaveManager: load auto save info failed.", exception); + } + } else { + partObjectList.add(count, null); + + // Open Max Window reached Dialog only once + if (!isMaxPopupOpened) { + uielement.openMaxSourceViewerDialogStartup(); + isMaxPopupOpened = true; + } + } + return isMaxPopupOpened; + } + + private void createLazyLoadJob(List autosaveMDList, List partObjectList2) { + Job loader = new AutoSaveLazyLoader(autosaveMDList, partObjectList2); + loader.schedule(); + } + + /** + * + * Title: class + * + * Description: The Class AutoSaveLoader. + */ + public class AutoSaveLoader extends UIWorkerJob { + private boolean isAllLoaded; + private IExecTimer timer; + private boolean isFinished; + + /** + * Instantiates a new auto save loader. + * + * @param autoSaveManager1 the auto save manager 1 + * @param dialog1 the dialog 1 + */ + public AutoSaveLoader(AutoSaveManager autoSaveManager1, NonCloseableDialog dialog1) { + super(MessageConfigLoader.getProperty(IMessagesConstants.PRESERVESQL_STARTUP_JOB_NAME), null); + isAllLoaded = false; + isOneTabLoaded = false; + this.isFinished = false; + } + + /** + * Do job. + * + * @return the object + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws MPPDBIDEException the MPPDBIDE exception + * @throws Exception the exception + */ + @Override + public Object doJob() + throws DatabaseOperationException, DatabaseCriticalException, MPPDBIDEException, Exception { + timer = new ExecTimer("AutoSaveLoader Job"); + timer.start(); + AutoSaveInfo info = readAutoSaveInfo(); + if (null != info) { + if (isAutoSaveEnabled()) { + isAllLoaded = loadAutoSaveInformation(info); + } else { + cleanupAutoSaveInfo(info); + } + + autosaveInfo = info; + deleteMetaDataEntry(); + deleteStaleFiles(); + return null; + } + deleteStaleFiles(); + return null; + } + + private void cleanupAutoSaveInfo(AutoSaveInfo info) { + List autosaveMDList = info.getAutosaveMD(); + int terminalCnt = autosaveMDList.size(); + + for (int cnt = 0; cnt < terminalCnt; cnt++) { + if (autosaveMDList.get(cnt).getAutoSaveFileName() != null + && !"".equals(autosaveMDList.get(cnt).getAutoSaveFileName())) { + deleteFile(autosaveMDList.get(cnt).getAutoSaveFileName()); + } + } + + deleteFile(getAutosaveInfoFilename()); + deleteFile(getAutosaveInfoTmpFilename()); + + deleteFolderIfEmpty(); + } + + private void deleteFolderIfEmpty() { + autosaveFileUtility.deleteFolderStructureIfEmpty(); + } + + private void deleteFile(String fileName) { + autosaveFileUtility.deleteFile(fileName); + } + + private void deleteMetaDataEntry() { + List autosaveMD = new ArrayList<>(1); + List autosaveMDOldList = autosaveInfo.getAutosaveMD(); + for (AutoSaveMetadata item : autosaveMDOldList) { + if (item.getVersionNumber() != -1) { + autosaveMD.add(item); + } + } + + autosaveInfo.setAutosaveMD(autosaveMD); + } + + private void deleteStaleFiles() { + ArrayList validFileList = new ArrayList<>(1); + if (autosaveInfo != null) { + List autosaveMD = autosaveInfo.getAutosaveMD(); + for (AutoSaveMetadata item : autosaveMD) { + if (item.getAutoSaveFileName() != null && !"".equals(item.getAutoSaveFileName())) { + validFileList.add(item.getAutoSaveFileName()); + } + } + } else { + // Startup Metadata file is corrupted, so clean it. + deleteFile(getAutosaveInfoFilename()); + deleteFile(getAutosaveInfoTmpFilename()); + } + + autosaveFileUtility.deleteStaleFiles(validFileList, getAutoSaveDataFilePattern()); + } + + /** + * On success UI action. + * + * @param obj the obj + */ + @Override + public void onSuccessUIAction(Object obj) { + if (isAllLoaded && isOneTabLoaded) { + UIElement.getInstance().setStatusBarMessage( + MessageConfigLoader.getProperty(IMessagesConstants.PRESERVESQL_STARTUP_LOADING_FINISHED)); + } + } + + /** + * On critical exception UI action. + * + * @param exception the exception + */ + @Override + public void onCriticalExceptionUIAction(DatabaseCriticalException exception) { + showFailedStatus(); + } + + /** + * On operational exception UI action. + * + * @param e the e + */ + @Override + public void onOperationalExceptionUIAction(DatabaseOperationException e) { + showFailedStatus(); + } + + /** + * On MPPDBIDE exception UI action. + * + * @param exception the exception + */ + @Override + public void onMPPDBIDEExceptionUIAction(MPPDBIDEException exception) { + super.onMPPDBIDEExceptionUIAction(exception); + showFailedStatus(); + } + + /** + * Final cleanup. + * + * @throws MPPDBIDEException the MPPDBIDE exception + */ + @Override + public void finalCleanup() throws MPPDBIDEException { + try { + timer.stopAndLog(); + setFinished(true); + } catch (Exception exception) { + // Execute below statement to end the event loop + setFinished(true); + } + } + + /** + * Final cleanup UI. + */ + @Override + public void finalCleanupUI() { + } + + private void showFailedStatus() { + UIElement.getInstance().setStatusBarMessage( + MessageConfigLoader.getProperty(IMessagesConstants.PRESERVESQL_STARTUP_LOADING_FAILED)); + } + + /** + * Checks if is finished. + * + * @return true, if is finished + */ + public boolean isFinished() { + return isFinished; + } + + /** + * Sets the finished. + * + * @param isFinished1 the new finished + */ + public void setFinished(boolean isFinished1) { + this.isFinished = isFinished1; + } + } + + /** + * Gets the disk utility. + * + * @return the disk utility + */ + public AutosaveFileUtility getDiskUtility() { + return autosaveFileUtility; + } + + /** + * Gets the active terminal. + * + * @param partObjectList the part object list + * @param activeTabIdParam the active tab id param + * @return the active terminal + */ + public int getActiveTerminal(List partObjectList, int activeTabIdParam) { + int activeTabId = activeTabIdParam; + int terminalCnt = partObjectList.size(); + int id = activeTabId == -1 ? 0 : activeTabId; + int itrCnt = 0; + + activeTabId = -1; + while (itrCnt < terminalCnt) { + if (id == terminalCnt) { + id = 0; + } + + if (partObjectList.get(id) != null) { + activeTabId = id; + break; + } + + id++; + itrCnt++; + } + + if (activeTabId == -1) { + activeTabId = 0; + } + + return activeTabId; + } + + /** + * Gets the auto save data file pattern. + * + * @return the auto save data file pattern + */ + public static String getAutoSaveDataFilePattern() { + return AUTOSAVE_DATA_FILE_PATTERN; + } + + /** + * Gets the autosave info filename. + * + * @return the autosave info filename + */ + public static String getAutosaveInfoFilename() { + return AUTOSAVE_INFO_FILENAME; + } + + /** + * Gets the autosave info tmp filename. + * + * @return the autosave info tmp filename + */ + public static String getAutosaveInfoTmpFilename() { + return AUTOSAVE_INFO_TMP_FILENAME; + } + + /** + * Clean file for autosave disable. + * + * @param fileName the file name + */ + public void cleanFileForAutosaveDisable(String fileName) { + autosaveFileUtility.deleteFile(fileName); + } + + /** + * Gets the default intervall. + * + * @return the default intervall + */ + public static int getDefaultIntervall() { + return DEFAULT_INTERVAL * 1000 * 60; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/autosave/AutoSaveWorker.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/autosave/AutoSaveWorker.java new file mode 100644 index 0000000000000000000000000000000000000000..10e938b565d1299d3874171157f903bbe4164da6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/autosave/AutoSaveWorker.java @@ -0,0 +1,396 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.autosave; + +import java.io.BufferedOutputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.stream.Collectors; + +import org.opengauss.mppdbide.bl.autosave.AutoSaveDbgObjInfo; +import org.opengauss.mppdbide.bl.autosave.AutoSaveInfo; +import org.opengauss.mppdbide.bl.autosave.AutoSaveMetadata; +import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.util.ExecTimer; +import org.opengauss.mppdbide.bl.util.IExecTimer; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DataStudioSecurityException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.FileOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import org.opengauss.mppdbide.view.ui.autosave.AutoSaveTerminalStatus; +import org.opengauss.mppdbide.view.ui.autosave.IAutoSaveDbgObject; +import org.opengauss.mppdbide.view.ui.autosave.IAutoSaveObject; +import org.opengauss.mppdbide.view.ui.terminalautosave.SQLTerminalAutoSaveIf; +import org.opengauss.mppdbide.view.utils.UIElement; +import org.opengauss.mppdbide.view.workerjob.UIWorkerJob; + +/** + * + * Title: class + * + * Description: The Class AutoSaveWorker. + * + * @since 3.0.0 + */ +public class AutoSaveWorker extends UIWorkerJob { + private boolean autoSaveEncrypted; + private boolean isEnabled; + private String encoding; + private IExecTimer timer; + private int noOfFilesSaved; + + /** + * Instantiates a new auto save worker. + * + * @param name the name + * @param family the family + */ + public AutoSaveWorker(String name, Object family) { + super(name, family); + } + + /** + * Do job. + * + * @return the object + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws FileOperationException the file operation exception + * @throws Exception the exception + */ + @Override + public Object doJob() + throws DatabaseOperationException, DatabaseCriticalException, FileOperationException, Exception { + timer = new ExecTimer("Terminal Auto Save "); + noOfFilesSaved = 0; + timer.start(); + isEnabled = AutoSaveManager.getInstance().isAutoSaveEnabled(); + if (isEnabled) { + autoSaveEncrypted = AutoSaveManager.getInstance().isAutoSaveEncrypted(); + if (BLPreferenceManager.getInstance().getBLPreference().getFileEncoding().isEmpty()) { + encoding = StandardCharsets.UTF_8.name(); + } else { + encoding = BLPreferenceManager.getInstance().getBLPreference().getFileEncoding(); + } + AutoSaveManager.getInstance().initialize(); + setAutosaveMembers(); + + List openTabsList = UIElement.getInstance().getAllOpenTabs(); + + // AutoSave is not applicable for file terminal + List openSQLTerminalTabList = openTabsList.stream().collect(Collectors.toList()); + openTabsList.stream().forEach(tab -> { + if (tab instanceof SQLTerminalAutoSaveIf && ((SQLTerminalAutoSaveIf) tab).isFileTerminalFlag()) { + openSQLTerminalTabList.remove(tab); + } + }); + + boolean isUpdated = deleteMetaData(openSQLTerminalTabList); + if (openSQLTerminalTabList != null) { + List modifiedTabList = addUpdateMetaData(isUpdated, openSQLTerminalTabList); + storeAutoSaveContent(modifiedTabList); + if (modifiedTabList.size() != 0) { + AutoSaveManager.getInstance().saveAutoSaveInfo(); + } + } + } else { + AutoSaveManager.getInstance().destroy(); + } + return null; + } + + private void setAutosaveMembers() { + AutoSaveInfo autosaveInfo = AutoSaveManager.getInstance().getAutosaveInfo(); + autosaveInfo.setTimestamp(new Date().toString()); + if (UIElement.getInstance().getActivePartObject() instanceof IAutoSaveObject) { + autosaveInfo.setActiveTerminalName( + ((IAutoSaveObject) UIElement.getInstance().getActivePartObject()).getElementID()); + } else { + autosaveInfo.setActiveTerminalName(""); + } + } + + private boolean deleteMetaData(List openTabsList) { + AutoSaveInfo autosaveInfo = AutoSaveManager.getInstance().getAutosaveInfo(); + List autosaveMDList = autosaveInfo.getAutosaveMD(); + Iterator metadataIterator = autosaveMDList.iterator(); + boolean isMetaDataChanged = false; + while (metadataIterator.hasNext()) { + AutoSaveMetadata metaData = metadataIterator.next(); + String uiID = metaData.getTabID(); + boolean isMetaDataFound = false; + for (IAutoSaveObject openTab : openTabsList) { + if (uiID.equals(openTab.getElementID())) { + if (openTab.isModifiedAfterCreate()) { + isMetaDataFound = true; + } + break; + } + } + if (!isMetaDataFound) { + AutoSaveManager.getInstance().deleteAutosaveMetadata(metaData); + isMetaDataChanged = true; + } + } + + return isMetaDataChanged; + } + + private List addUpdateMetaData(boolean metaDataChangeDoneParam, List openTabsList) + throws MPPDBIDEException { + boolean metaDataChangeDone = metaDataChangeDoneParam; + AutoSaveInfo autosaveInfo = AutoSaveManager.getInstance().getAutosaveInfo(); + + List modifiedTabList = new ArrayList(); + Iterator openTabIterator = openTabsList.iterator(); + List mdList = new ArrayList(); + + int tabIdFileCntr = 1; + + while (openTabIterator.hasNext()) { + IAutoSaveObject openTab = openTabIterator.next(); + String uiID = openTab.getElementID(); + AutoSaveMetadata metaData = autosaveInfo.getMetaData(uiID); + + // only create entries in file if there is a modification + if (openTab.isModified() && AutoSaveTerminalStatus.LOAD_FINISHED == openTab.getStatus()) { + if (metaData == null) { + metaData = createAutosaveMetaData(openTab, tabIdFileCntr); + tabIdFileCntr++; + AutoSaveManager.getInstance().getAutosaveInfo().addAutoSaveMetadata(metaData); + } else { + updateModifiedMetaData(metaData, openTab, autoSaveEncrypted, encoding); + } + + metaDataChangeDone = true; + mdList.add(metaData); + modifiedTabList.add(openTab); + } else { + if (metaData != null) { + updateModifiedMetaData(metaData, openTab, metaData.isEncrypted(), metaData.getEncoding()); + metaDataChangeDone = true; + mdList.add(metaData); + } + } + } + + if (metaDataChangeDone) { + autosaveInfo.setAutosaveMD(mdList); + AutoSaveManager.getInstance().saveAutoSaveInfo(); + } + + return modifiedTabList; + } + + private void updateModifiedMetaData(AutoSaveMetadata autosaveMD, IAutoSaveObject openTab, boolean isEncryptFlag, + String encoding1) { + autosaveMD.setConnectionName(openTab.getConnectionName()); + autosaveMD.setDatabaseName(openTab.getDatabaseName()); + autosaveMD.setTabID(openTab.getElementID()); + autosaveMD.setTabLabel(openTab.getTabLabel()); + autosaveMD.setTabToolTip(openTab.getTabToolTip()); + autosaveMD.setType(openTab.getType()); + autosaveMD.setEncrypted(isEncryptFlag); + autosaveMD.setEncoding(encoding1); + if (openTab instanceof IAutoSaveDbgObject) { + IAutoSaveDbgObject dbgObjTab = (IAutoSaveDbgObject) openTab; + AutoSaveDbgObjInfo dbgObjInfo = new AutoSaveDbgObjInfo(); + dbgObjInfo.setDirty(dbgObjTab.isObjDirty()); + dbgObjInfo.setName(dbgObjTab.getName()); + dbgObjInfo.setOid(dbgObjTab.getOid()); + dbgObjInfo.setSchemaName(dbgObjTab.getNameSpaceName()); + dbgObjInfo.setObjType(dbgObjTab.getDbgObjType()); + autosaveMD.setDbgObjInfo(dbgObjInfo); + } + + autosaveMD.setTimestamp(new Date().toString()); + autosaveMD.updateShaval(); + } + + private AutoSaveMetadata createAutosaveMetaData(IAutoSaveObject openTabs, int tabIdFileCntr) { + AutoSaveMetadata newOpenTab = new AutoSaveMetadata(); + newOpenTab.setConnectionName(openTabs.getConnectionName()); + newOpenTab.setDatabaseName(openTabs.getDatabaseName()); + newOpenTab.setEncrypted(autoSaveEncrypted); + newOpenTab.setEncoding(encoding); + newOpenTab.setAutoSaveFileName("tabinfo" + System.currentTimeMillis() + tabIdFileCntr + ".autosave"); + newOpenTab.setTabID(openTabs.getElementID()); + newOpenTab.setTabLabel(openTabs.getTabLabel()); + newOpenTab.setTabToolTip(openTabs.getTabToolTip()); + newOpenTab.setType(openTabs.getType()); + if (openTabs instanceof IAutoSaveDbgObject) { + AutoSaveDbgObjInfo dbgObjInfo = new AutoSaveDbgObjInfo(); + IAutoSaveDbgObject dbgObjTab = (IAutoSaveDbgObject) openTabs; + dbgObjInfo.setDirty(dbgObjTab.isObjDirty()); + dbgObjInfo.setName(dbgObjTab.getName()); + dbgObjInfo.setOid(dbgObjTab.getOid()); + dbgObjInfo.setSchemaName(dbgObjTab.getNameSpaceName()); + dbgObjInfo.setObjType(dbgObjTab.getDbgObjType()); + newOpenTab.setDbgObjInfo(dbgObjInfo); + } + newOpenTab.setTimestamp(new Date().toString()); + newOpenTab.updateShaval(); + return newOpenTab; + } + + private void storeAutoSaveContent(List modifiedTabList) { + IExecTimer timertoWriteintoFile = null; + for (Iterator iterator = modifiedTabList.iterator(); iterator.hasNext();) { + IAutoSaveObject iAutoSaveObject = (IAutoSaveObject) iterator.next(); + + AutoSaveInfo autosaveInfo = AutoSaveManager.getInstance().getAutosaveInfo(); + AutoSaveMetadata autoSaveMetadata = autosaveInfo.getMetaData(iAutoSaveObject.getElementID()); + if (autoSaveMetadata != null) { + iAutoSaveObject.setModified(false); + BufferedOutputStream writer = null; + try (FileOutputStream storeAutosaveData = AutoSaveManager.getInstance() + .getDataWriter(autoSaveMetadata)) { + writer = new BufferedOutputStream(storeAutosaveData); + String text = iAutoSaveObject.getText(); + if (text.length() != 0) { + byte[] bytes = text.getBytes(autoSaveMetadata.getEncoding()); + if (autoSaveMetadata.isEncrypted()) { + SecureUtil secureUtil = new SecureUtil(); + secureUtil.setPackagePath(ConnectionProfileManagerImpl.getInstance().getDiskUtility() + .getOsCurrentUserFolderPath()); + bytes = secureUtil.encryptByteArray(bytes); + } + timertoWriteintoFile = new ExecTimer( + "Write Autosave file " + autoSaveMetadata.getAutoSaveFileName()); + timertoWriteintoFile.start(); + writer.write(bytes); + writer.flush(); + } + + iAutoSaveObject.setTabStatusMsg(MessageConfigLoader.getProperty( + IMessagesConstants.PRESERVESQL_PERIODIC_SAVE_TAB_STATUS, System.currentTimeMillis())); + noOfFilesSaved++; + } catch (FileOperationException | IOException | DataStudioSecurityException + | OutOfMemoryError exception) { + iAutoSaveObject.setModified(true); + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty( + IMessagesConstants.PRESERVESQL_FILEWRITEEXCEPTION, new Date().toString()), exception); + + // delete the file if possible + AutoSaveManager.getInstance().cleanFileForAutosaveDisable(autoSaveMetadata.getAutoSaveFileName()); + } finally { + storeAutoSaveFinally(timertoWriteintoFile, writer); + } + + updateModifiedMetaData(autoSaveMetadata, iAutoSaveObject, autoSaveMetadata.isEncrypted(), + autoSaveMetadata.getEncoding()); + } + } + } + + private void storeAutoSaveFinally(IExecTimer timertoWriteintoFile, BufferedOutputStream writer) { + if (null != writer) { + try { + writer.close(); + if (null != timertoWriteintoFile) { + timertoWriteintoFile.stopAndLogNoException(); + } + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("AutoSaveWorker: Stream close Error.", exception); + } + } + } + + /** + * On success UI action. + * + * @param obj the obj + */ + @Override + public void onSuccessUIAction(Object obj) { + // This will be changed into logger once tab wise status bar is + // implemented + if (isEnabled) { + UIElement.getInstance().setStatusBarMessage(MessageConfigLoader + .getProperty(IMessagesConstants.PRESERVESQL_PERIODIC_SAVE_FINISHED, new Date().toString())); + } + } + + /** + * On critical exception UI action. + * + * @param exception the exception + */ + @Override + public void onCriticalExceptionUIAction(DatabaseCriticalException exception) { + return; + } + + /** + * On operational exception UI action. + * + * @param exception the exception + */ + @Override + public void onOperationalExceptionUIAction(DatabaseOperationException exception) { + return; + } + + /** + * On MPPDBIDE exception. + * + * @param exception the exception + */ + public void onMPPDBIDEException(MPPDBIDEException exception) { + super.onMPPDBIDEException(exception); + MPPDBIDELoggerUtility.error("AutoSaveWorker: MPPDBException thrown.", exception); + } + + /** + * On exception. + * + * @param exception the exception + */ + public void onException(Exception exception) { + super.onException(exception); + MPPDBIDELoggerUtility.error("AutoSaveWorker: OnException handle.", exception); + } + + /** + * Final cleanup. + * + * @throws MPPDBIDEException the MPPDBIDE exception + */ + @Override + public void finalCleanup() throws MPPDBIDEException { + if (MPPDBIDELoggerUtility.isInfoEnabled()) { + MPPDBIDELoggerUtility.info("Number of files autosaved :" + noOfFilesSaved); + } + timer.stopAndLog(); + if (AutoSaveManager.getInstance().isAutoSaveEnabled()) { + schedule(AutoSaveManager.getInstance().getAutoSaveInterval()); + } else { + schedule(AutoSaveManager.getDefaultIntervall()); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/batchdrop/BatchDropWorkerJob.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/batchdrop/BatchDropWorkerJob.java new file mode 100644 index 0000000000000000000000000000000000000000..c9b804acdf4f996b65d8a189c715457f200de157 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/batchdrop/BatchDropWorkerJob.java @@ -0,0 +1,365 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.batchdrop; + +import java.util.List; + +import javax.annotation.PreDestroy; + +import org.eclipse.jface.viewers.StructuredSelection; + +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DebugObjects; +import org.opengauss.mppdbide.bl.serverdatacache.IndexMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.PartitionMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.PartitionTable; +import org.opengauss.mppdbide.bl.serverdatacache.SequenceMetadata; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.SynonymMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ViewColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.groups.UserRoleObjectGroup; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.presentation.grid.batchdrop.BatchDropDataProvider; +import org.opengauss.mppdbide.presentation.grid.batchdrop.BatchDropDataRow; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.Message; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.utils.observer.DSEventTable; +import org.opengauss.mppdbide.utils.observer.IDSGridUIListenable; +import org.opengauss.mppdbide.view.core.statusbar.ObjectBrowserStatusBarProvider; +import org.opengauss.mppdbide.view.handler.connection.ObjectBrowserOperationUIWorkerJob; +import org.opengauss.mppdbide.view.ui.terminal.BatchDropDisplayUIManager; +import org.opengauss.mppdbide.view.ui.uiif.ObjectBrowserIf; +import org.opengauss.mppdbide.view.utils.common.ObjectBrowserUtil; + +/** + * Title: class Description: The Class BatchDropWorkerJob. + * + * @since 3.0.0 + */ +public class BatchDropWorkerJob extends ObjectBrowserOperationUIWorkerJob { + /** + * The Constant JOB_NOT_EXIST_ERR_MSG_OPEN_GAUSS. + */ + private static final String JOB_NOT_EXIST_ERR_MSG_OPEN_GAUSS = "Can not find job id"; + + private BatchDropDataProvider dataProvider; + + private List objectsToDropParent; + + private DSEventTable eventTable; + + private String statusElement; + + private boolean isCancelFlow; + + private BatchDropDisplayUIManager uiManager; + + private List userRoleToDropParent; + + /** + * Instantiates a new batch drop worker job. + * + * @param name the name + * @param obj the obj + * @param msg the msg + * @param family the family + * @param ui the ui + */ + public BatchDropWorkerJob(String name, ServerObject obj, String msg, Object family, BatchDropDisplayUIManager ui) { + super(name, obj, msg, family); + this.isCancelFlow = false; + this.uiManager = ui; + } + + /** + * Inits the. + * + * @param dataProvider1 the data provider 1 + * @param objctsToDropParent the objcts to drop parent + * @param usrRoleToDrpParent the usr role to drp parent + * @param zUserRoleObjectGroup the z user role object group + * @param zRoleToDropParent the z role to drop parent + * @param zTableElementsToDropParent the z table elements to drop parent + * @param eventTable2 the event table 2 + * @param statusEle the status ele + */ + public void init(BatchDropDataProvider dataProvider1, List objctsToDropParent, + List usrRoleToDrpParent, DSEventTable eventTable2, String statusEle) { + this.dataProvider = dataProvider1; + this.objectsToDropParent = objctsToDropParent; + this.userRoleToDropParent = usrRoleToDrpParent; + this.eventTable = eventTable2; + this.statusElement = statusEle; + } + + /** + * Gets the success msg for OB status bar. + * + * @return the success msg for OB status bar + */ + @Override + protected String getSuccessMsgForOBStatusBar() { + String message = MessageConfigLoader.getProperty(IMessagesConstants.DROP_OBJECTS_JOB_FINISHED_STATUS, + statusElement); + return message; + } + + /** + * Gets the object browser refresh item. + * + * @return the object browser refresh item + */ + @Override + protected ServerObject getObjectBrowserRefreshItem() { + return null; + } + + /** + * Do job. + * + * @return the object + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws MPPDBIDEException the MPPDBIDE exception + * @throws Exception the exception + */ + @Override + public Object doJob() throws DatabaseOperationException, DatabaseCriticalException, MPPDBIDEException, Exception { + if (conn == null) { + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_BATCHDROP_CONN_FAILED, null)); + return null; + } + + dataProvider.startExecute(conn); + return null; + } + + /** + * On success UI action. + * + * @param obj the obj + */ + @Override + public void onSuccessUIAction(Object obj) { + refresh(); + if (!isCancelFlow) { + ObjectBrowserStatusBarProvider.getStatusBar() + .displayMessage(Message.getInfo(getSuccessMsgForOBStatusBar())); + } + } + + /** + * On critical exception UI action. + * + * @param exception the exception + */ + @Override + public void onCriticalExceptionUIAction(DatabaseCriticalException exception) { + handleException(exception); + } + + /** + * On operational exception UI action. + * + * @param exception the exception + */ + @Override + public void onOperationalExceptionUIAction(DatabaseOperationException exception) { + handleException(exception); + } + + /** + * On pre setup failure. + * + * @param exception the exception + */ + @Override + public void onPreSetupFailure(MPPDBIDEException exception) { + uiManager.userCancelledOperation(); + } + + private void handleException(MPPDBIDEException exception) { + MPPDBIDELoggerUtility.error("BatchDropWorkerJob: handleException.", exception); + String message = MessageConfigLoader.getProperty(IMessagesConstants.DROP_OBJECTS_JOB_FAILURE_STATUS, + statusElement); + ObjectBrowserStatusBarProvider.getStatusBar().displayMessage(Message.getInfo(message)); + } + + /** + * Handle stop. + */ + public void handleStop() { + try { + if (conn != null) { + conn.cancelQuery(); + dataProvider.rollbackAndNotifyUIMgr(conn); + } + } catch (DatabaseCriticalException exception) { + MPPDBIDELoggerUtility.error("BatchDropWorkerJob: handle stop failed.", exception); + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("BatchDropWorkerJob: handle stop failed.", exception); + } finally { + refresh(); + } + } + + /** + * Canceling. + */ + @Override + protected void canceling() { + super.canceling(); + isCancelFlow = true; + if (null != eventTable) { + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_BATCHDROP_JOB_CANCEL, null)); + } + } + + private void refresh() { + if (null == dataProvider) { + /* Batch drop window is already closed. No need to refresh */ + return; + } + boolean isOneObjectDropped = false; + List rows = dataProvider.getAllFetchedRows(); + int objectDropped = dataProvider.getTotalObjectCnt(); + + BatchDropDataRow row = null; + if (this.getDatabase() != null && this.getDatabase().isConnected()) { + for (int objCnt = 0; objCnt < objectDropped; objCnt++) { + row = (rows.size() > objCnt) ? (BatchDropDataRow) rows.get(objCnt) : null; + if (null != row && row.isDropped()) { + remove(row.getServerObject()); + isOneObjectDropped = true; + } + } + + /* Set selection to nothing */ + if (isOneObjectDropped) { + handleRefresh(rows); + } + } + } + + private void handleRefresh(List rows) { + BatchDropDataRow row = null; + ObjectBrowserIf objectBrowserModel = ObjectBrowserUtil.getObjectBrowserModel(); + if (null != objectBrowserModel) { + objectBrowserModel.setSelection(StructuredSelection.EMPTY); + } + + refreshServerObject(rows, objectBrowserModel); + + // support UserRoleObjectGroup by Martin + int element = 0; + boolean refreshed = false; + UserRoleObjectGroup droppedUserRole = null; + if (isUserRoleObjectGroupDrop()) { + for (UserRoleObjectGroup obj : userRoleToDropParent) { + row = (BatchDropDataRow) rows.get(element++); + if (row.isDropped()) { + refreshed = true; + droppedUserRole = (UserRoleObjectGroup) obj; + } + } + } + + if (null != droppedUserRole && refreshed == true) { + refeshOLAPUserGroup(objectBrowserModel, droppedUserRole); + } + + } + + private boolean isUserRoleObjectGroupDrop() { + return null != userRoleToDropParent && userRoleToDropParent.size() > 0; + } + + /** + * Refesh OLAP user group. + * + * @Title: refeshOLAPUserGroup + * @param objectBrowserModel the object browser model + * @param droppedUserRole the dropped user role + */ + private void refeshOLAPUserGroup(ObjectBrowserIf objectBrowserModel, UserRoleObjectGroup droppedUserRole) { + try { + droppedUserRole.getServer().refreshUserRoleObjectGroup(); + } catch (MPPDBIDEException exception) { + MPPDBIDELoggerUtility.error("DropUserRoleWorkerJob: refresh failed.", exception); + } + if (null != objectBrowserModel) { + objectBrowserModel.refreshObject(droppedUserRole); + } + } + + /** + * Refresh server object. + * + * @param rows the rows + * @param objectBrowserModel the object browser model + */ + private void refreshServerObject(List rows, ObjectBrowserIf objectBrowserModel) { + BatchDropDataRow row; + int cnt = 0; + for (ServerObject obj : objectsToDropParent) { + row = (BatchDropDataRow) rows.get(cnt++); + if (row.isDropped()) { + if (null != objectBrowserModel) { + objectBrowserModel.refreshObject(obj); + } + } + } + } + + private void remove(ServerObject obj) { + if (obj instanceof Namespace) { + ((Database) (obj.getParent())).remove(obj); + } else if (obj instanceof TableMetaData || obj instanceof SequenceMetadata || obj instanceof ViewMetaData + || obj instanceof DebugObjects || obj instanceof SynonymMetaData) { + ((Namespace) (obj.getParent())).remove(obj); + } else if (obj instanceof ColumnMetaData || obj instanceof ConstraintMetaData || obj instanceof IndexMetaData) { + ((TableMetaData) (obj.getParent())).remove(obj); + } else if (obj instanceof PartitionMetaData) { + ((PartitionTable) (obj.getParent())).remove(obj); + } else if (obj instanceof ViewColumnMetaData) { + ((ViewMetaData) (obj.getParent())).remove(obj); + } else { + MPPDBIDELoggerUtility.info("Drop Object not supported."); + } + } + + /** + * Pre destroy. + */ + @PreDestroy + public void preDestroy() { + this.dataProvider = null; + this.objectsToDropParent = null; + this.eventTable = null; + this.userRoleToDropParent = null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/cmdline/CmdLineCharObject.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/cmdline/CmdLineCharObject.java new file mode 100644 index 0000000000000000000000000000000000000000..7befe1a5548a3ec48021527da3c7f8fb80e70c95 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/cmdline/CmdLineCharObject.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.cmdline; + +import org.opengauss.mppdbide.utils.security.SecureUtil; + +/** + * Title: CmdLineObject + * + * @since 3.0.0 + */ +public class CmdLineCharObject { + + private char[] prd = new char[0]; + + /** + * Gets the prd. + * + * @return the prd + */ + public char[] getPrd() { + if (this.prd == null) { + return new char[0]; + } + return prd.clone(); + } + + /** + * Sets the prd. + * + * @param prd the new prd + */ + public void setPrd(char[] prd) { + this.prd = prd.clone(); + } + + /** + * Clear pssrd. + */ + public void clearPssrd() { + SecureUtil.clearPassword(this.prd); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/DSGridStateMachine.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/DSGridStateMachine.java new file mode 100644 index 0000000000000000000000000000000000000000..8d41133bb14a0dc78e71a25fc29e0c1896f74348 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/DSGridStateMachine.java @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component; + +import java.util.Observable; + +import javax.annotation.PreDestroy; + +import org.eclipse.swt.SWT; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class DSGridStateMachine. + * + * @since 3.0.0 + */ +public class DSGridStateMachine extends Observable { + + /** + * + * Title: enum + * + * Description: The Enum State. + */ + public enum State { + + /** + * The loading. + */ + LOADING(MessageConfigLoader.getProperty(IMessagesConstants.LOADING_DATA_STATUS_MSG), SWT.COLOR_BLUE), + + /** + * The exporting. + */ + EXPORTING(MessageConfigLoader.getProperty(IMessagesConstants.EXPORTING_DATA_STATUS_MSG), SWT.COLOR_BLUE), + + /** + * The refreshing. + */ + REFRESHING(MessageConfigLoader.getProperty(IMessagesConstants.MSG_GUI_REFRESH_STATUSBAR), SWT.COLOR_BLUE), + + /** + * The idle. + */ + IDLE("", SWT.COLOR_BLACK), + + /** + * The error. + */ + ERROR(MessageConfigLoader.getProperty(IMessagesConstants.ERROR_LOADING_DATA_STATUS_MSG), SWT.COLOR_RED); + + private final String displayMsg; + private final int color; + + private State(String msg, int color) { + this.displayMsg = msg; + this.color = color; + } + + /** + * Gets the display msg. + * + * @return the display msg + */ + public String getDisplayMsg() { + return this.displayMsg; + } + + /** + * Gets the color. + * + * @return the color + */ + public int getColor() { + return this.color; + } + }; + + private State currentState; + + /** + * Instantiates a new DS grid state machine. + */ + public DSGridStateMachine() { + this.currentState = State.IDLE; + } + + /** + * Can. + * + * @param newState the new state + * @return true, if successful + */ + public boolean can(State newState) { + /* + * Allowed state changes: IDLE -> Loading IDLE -> EXPORT EXPORT -> IDLE + * LOADING -> IDLE, LOADING -> ERROR + */ + return (!isIdle(currentState) && isIdle(newState)) || (isIdle(currentState) && !isIdle(newState)) + || (isLoading() && newState == State.ERROR); + } + + /** + * Sets the. + * + * @param newState the new state + * @return true, if successful + */ + public boolean set(State newState) { + if (can(newState)) { + this.currentState = newState; + setChanged(); + notifyObservers(currentState); + return true; + } + + return false; + } + + private boolean isIdle(State givenState) { + return givenState == State.IDLE; + } + + /** + * Checks if is loading. + * + * @return true, if is loading + */ + public boolean isLoading() { + return currentState == State.LOADING; + } + + /** + * Checks if is exporting. + * + * @return true, if is exporting + */ + public boolean isExporting() { + return currentState == State.EXPORTING; + } + + /** + * Checks if is refreshing. + * + * @return true, if is refreshing + */ + public boolean isRefreshing() { + return currentState == State.REFRESHING; + } + + /** + * Checks if is error. + * + * @return true, if is error + */ + public boolean isError() { + return currentState == State.ERROR; + } + + /** + * Pre destroy. + */ + @PreDestroy + public void preDestroy() { + this.currentState = null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/GridUIPreference.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/GridUIPreference.java new file mode 100644 index 0000000000000000000000000000000000000000..0ab4b2146333274b64669d5d9d7c5716c621c30b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/GridUIPreference.java @@ -0,0 +1,363 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component; + +import org.eclipse.jface.preference.PreferenceStore; + +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.view.prefernces.EditTableOptionProviderForPreferences; +import org.opengauss.mppdbide.view.prefernces.PreferenceWrapper; +import org.opengauss.mppdbide.view.prefernces.UserEncodingOption; + +/** + * + * Title: class + * + * Description: The Class GridUIPreference. + * + * @since 3.0.0 + */ +public class GridUIPreference implements IGridUIPreference { + + /** + * The pref store. + */ + protected PreferenceStore prefStore; + private static final String NULL_VALUE = "[NULL]"; + private static final String DEFAULT_VALUE = "[DEFAULT]"; + + /** + * Instantiates a new grid UI preference. + */ + public GridUIPreference() { + prefStore = PreferenceWrapper.getInstance().getPreferenceStore(); + } + + /** + * Gets the column width. + * + * @return the column width + */ + @Override + public int getColumnWidth() { + return (getColumnWidthStrategy() == ColumnWidthType.FIXED_WIDTH) + ? prefStore.getInt(MPPDBIDEConstants.PREF_COLUMN_WIDTH_LENGTH) + : 100; + } + + /** + * Checks if is show query area. + * + * @return true, if is show query area + */ + @Override + public boolean isShowQueryArea() { + return true; + } + + /** + * Checks if is enable global fuzzy search. + * + * @return true, if is enable global fuzzy search + */ + @Override + public boolean isEnableGlobalFuzzySearch() { + return true; + } + + /** + * Checks if is show global search panel on start. + * + * @return true, if is show global search panel on start + */ + @Override + public boolean isShowGlobalSearchPanelOnStart() { + return true; + } + + /** + * Checks if is enable sort. + * + * @return true, if is enable sort + */ + @Override + public boolean isEnableSort() { + return false; + } + + /** + * Checks if is enable edit. + * + * @return true, if is enable edit + */ + @Override + public boolean isEnableEdit() { + return false; + } + + /** + * Checks if is allow column reorder. + * + * @return true, if is allow column reorder + */ + @Override + public boolean isAllowColumnReorder() { + return true; + } + + /** + * Checks if is allow row reorder. + * + * @return true, if is allow row reorder + */ + @Override + public boolean isAllowRowReorder() { + return false; + } + + /** + * Checks if is allow column hide. + * + * @return true, if is allow column hide + */ + @Override + public boolean isAllowColumnHide() { + return false; + } + + /** + * Checks if is allow row hide. + * + * @return true, if is allow row hide + */ + @Override + public boolean isAllowRowHide() { + return false; + } + + /** + * Gets the column width strategy. + * + * @return the column width strategy + */ + @Override + public ColumnWidthType getColumnWidthStrategy() { + boolean isWidthByColumnData = prefStore.getBoolean(MPPDBIDEConstants.PREF_RESULT_IS_COLUMN_LENGTH_BY_VALUE); + return isWidthByColumnData ? ColumnWidthType.DATA_WIDTH : ColumnWidthType.FIXED_WIDTH; + } + + /** + * Checks if is support data export. + * + * @return true, if is support data export + */ + @Override + public boolean isSupportDataExport() { + return true; + } + + /** + * Checks if is copy with column header. + * + * @return true, if is copy with column header + */ + @Override + public boolean isCopyWithColumnHeader() { + return prefStore.getBoolean(MPPDBIDEConstants.PREF_RESULT_IS_COPY_COLUMN_HEADER); + } + + /** + * Checks if is copywith row header. + * + * @return true, if is copywith row header + */ + @Override + public boolean isCopywithRowHeader() { + return prefStore.getBoolean(MPPDBIDEConstants.PREF_RESULT_IS_COPY_ROW_HEADER); + } + + /** + * Checks if is word wrap. + * + * @return true, if is word wrap + */ + @Override + public boolean isWordWrap() { + return true; + } + + /** + * Checks if is fit to one page. + * + * @return true, if is fit to one page + */ + @Override + public boolean isFitToOnePage() { + return false; + } + + /** + * Gets the max display data length. + * + * @return the max display data length + */ + @Override + public int getMaxDisplayDataLength() { + return 1000; + } + + /** + * Edits the table data UI preference. + * + * @return true, if successful + */ + @Override + public boolean editTableDataUIPreference() { + + return !PreferenceWrapper.getInstance().getPreferenceStore() + .getBoolean(EditTableOptionProviderForPreferences.EDITTABLE_COMMIT_ON_FAILURE); + } + + /** + * Gets the NULL value text. + * + * @return the NULL value text + */ + @Override + public String getNULLValueText() { + return NULL_VALUE; + } + + /** + * Checks if is refresh supported. + * + * @return true, if is refresh supported + */ + @Override + public boolean isRefreshSupported() { + return false; + } + + /** + * Checks if is need advanced copy. + * + * @return true, if is need advanced copy + */ + @Override + public boolean isNeedAdvancedCopy() { + return true; + } + + /** + * Gets the default value text. + * + * @return the default value text + */ + @Override + public String getDefaultValueText() { + return DEFAULT_VALUE; + } + + /** + * Checks if is adds the batch drop tool. + * + * @return true, if is adds the batch drop tool + */ + @Override + public boolean isAddBatchDropTool() { + return false; + } + + /** + * Checks if is edits the query results flow. + * + * @return true, if is edits the query results flow + */ + @Override + public boolean isEditQueryResultsFlow() { + return false; + } + + /** + * Checks if is show status bar. + * + * @return true, if is show status bar + */ + @Override + public boolean isShowStatusBar() { + return true; + } + + /** + * Checks if is delete item supported. + * + * @return true, if is delete item supported + */ + @Override + public boolean isDeleteItemSupported() { + return false; + } + + /** + * Gets the default encoding. + * + * @return the default encoding + */ + @Override + public String getDefaultEncoding() { + return prefStore.getString(UserEncodingOption.DATA_STUDIO_ENCODING); + } + + /** + * Checks if is include encoding. + * + * @return true, if is include encoding + */ + @Override + public boolean isIncludeEncoding() { + return prefStore.getBoolean(MPPDBIDEConstants.PREF_RESULT_IS_SHOW_ENCODING); + } + + /** + * Replace tab. + * + * @return the int + */ + @Override + public int replaceTab() { + return prefStore.getInt(MPPDBIDEConstants.TAB_WIDTH_OPTION); + } + + /** + * Checks if is adds the item supported. + * + * @return true, if is adds the item supported + */ + @Override + public boolean isAddItemSupported() { + return false; + } + + /** + * Checks if is cancel changes supported. + * + * @return true, if is cancel changes supported + */ + @Override + public boolean isCancelChangesSupported() { + return false; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/IGridUIPreference.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/IGridUIPreference.java new file mode 100644 index 0000000000000000000000000000000000000000..2f65c24b71006329b9aa5c2d22cac8c1b05be59f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/IGridUIPreference.java @@ -0,0 +1,285 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component; + +import java.util.HashMap; +import java.util.Map; + +import org.eclipse.nebula.widgets.nattable.edit.editor.IComboBoxDataProvider; + +/** + * + * Title: interface + * + * Description: The Interface IGridUIPreference. + * + * @since 3.0.0 + */ +public interface IGridUIPreference extends IGridUIPreferenceBase { + + /** + * + * Title: enum + * + * Description: The Enum ColumnWidthType. + */ + enum ColumnWidthType { + + /** + * The fixed width. + */ + FIXED_WIDTH, + /** + * The header width. + */ + HEADER_WIDTH, + /** + * The data width. + */ + DATA_WIDTH + }; + + /** + * Gets the column width strategy. + * + * @return the column width strategy + */ + ColumnWidthType getColumnWidthStrategy(); + + /** + * Checks if is support data export. + * + * @return true, if is support data export + */ + boolean isSupportDataExport(); + + /** + * Checks if is copy with column header. + * + * @return true, if is copy with column header + */ + boolean isCopyWithColumnHeader(); + + /** + * Checks if is copywith row header. + * + * @return true, if is copywith row header + */ + boolean isCopywithRowHeader(); + + /** + * Checks if is word wrap. + * + * @return true, if is word wrap + */ + boolean isWordWrap(); + + /** + * Checks if is fit to one page. + * + * @return true, if is fit to one page + */ + boolean isFitToOnePage(); + + /** + * Gets the max display data length. + * + * @return the max display data length + */ + int getMaxDisplayDataLength(); + + /** + * Edits the table data UI preference. + * + * @return true, if successful + */ + boolean editTableDataUIPreference(); + + /** + * Gets the NULL value text. + * + * @return the NULL value text + */ + String getNULLValueText(); + + /** + * Checks if is need advanced copy. + * + * @return true, if is need advanced copy + */ + boolean isNeedAdvancedCopy(); + + /** + * Gets the default value text. + * + * @return the default value text + */ + String getDefaultValueText(); + + /** + * Checks if is adds the batch drop tool. + * + * @return true, if is adds the batch drop tool + */ + boolean isAddBatchDropTool(); + + /** + * Checks if is edits the query results flow. + * + * @return true, if is edits the query results flow + */ + boolean isEditQueryResultsFlow(); + + /** + * Checks if is show status bar. + * + * @return true, if is show status bar + */ + boolean isShowStatusBar(); + + /** + * Checks if is include encoding. + * + * @return true, if is include encoding + */ + boolean isIncludeEncoding(); + + /** + * Gets the default encoding. + * + * @return the default encoding + */ + String getDefaultEncoding(); + + /** + * Checks if is adds the item supported. + * + * @return true, if is adds the item supported + */ + boolean isAddItemSupported(); + + /** + * Checks if is delete item supported. + * + * @return true, if is delete item supported + */ + boolean isDeleteItemSupported(); + + /** + * Checks if is cancel changes supported. + * + * @return true, if is cancel changes supported + */ + boolean isCancelChangesSupported(); + + /** + * Checks if is refresh supported. + * + * @return true, if is refresh supported + */ + boolean isRefreshSupported(); + + /** + * Gets the combo box data providers. + * + * @return the combo box data providers + */ + default Map getComboBoxDataProviders() { + // returning an empty Map for default behaviour instead of null + return new HashMap<>(); + } + + /** + * Checks if is show right click menu. + * + * @return true, if is show right click menu + */ + default boolean isShowRightClickMenu() { + return false; + } + + /** + * Checks if is show generate insert. + * + * @return true, if is show generate insert + */ + default boolean isShowGenerateInsert() { + return false; + } + + /** + * Checks if is start select query. + * + * @return true, if is start select query + */ + default boolean isStartSelectQuery() { + return false; + } + + /** + * Gets the selected encoding. + * + * @return the selected encoding + */ + default String getSelectedEncoding() { + return null; + } + + /** + * Checks if is closed connection. + * + * @return true, if is closed connection + */ + default boolean isClosedConnection() { + return false; + } + + /** + * Checks if is need create text mode. + * + * @return true, if is need create text mode + */ + default boolean isNeedCreateTextMode() { + return false; + } + + /** + * Replace tab. + * + * @return the int + */ + default int replaceTab() { + return 0; + } + + /** + * Checks if is show load more record button. + * + * @return true, if is show load more record button + */ + default boolean isShowLoadMoreRecordButton() { + return false; + } + + /** + * checks if add export all button + * + * @return true, if is add export all button + */ + default boolean isAddItemExportAll() { + return true; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/IGridUIPreferenceBase.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/IGridUIPreferenceBase.java new file mode 100644 index 0000000000000000000000000000000000000000..69374a74d4bd2b6a5965ed4238437b78d8614e62 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/IGridUIPreferenceBase.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component; + +/** + * + * Title: interface + * + * Description: The Interface IGridUIPreferenceBase. + * + * @since 3.0.0 + */ +public interface IGridUIPreferenceBase { + + /** + * Gets the column width. + * + * @return the column width + */ + int getColumnWidth(); + + /** + * Checks if is show query area. + * + * @return true, if is show query area + */ + boolean isShowQueryArea(); + + /** + * Checks if is enable global fuzzy search. + * + * @return true, if is enable global fuzzy search + */ + boolean isEnableGlobalFuzzySearch(); + + /** + * Checks if is show global search panel on start. + * + * @return true, if is show global search panel on start + */ + boolean isShowGlobalSearchPanelOnStart(); + + /** + * Checks if is enable sort. + * + * @return true, if is enable sort + */ + boolean isEnableSort(); + + /** + * Checks if is enable edit. + * + * @return true, if is enable edit + */ + boolean isEnableEdit(); + + /** + * Checks if is allow column reorder. + * + * @return true, if is allow column reorder + */ + boolean isAllowColumnReorder(); + + /** + * Checks if is allow row reorder. + * + * @return true, if is allow row reorder + */ + boolean isAllowRowReorder(); + + /** + * Checks if is allow column hide. + * + * @return true, if is allow column hide + */ + boolean isAllowColumnHide(); + + /** + * Checks if is allow row hide. + * + * @return true, if is allow row hide + */ + boolean isAllowRowHide(); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/TabGridUIPreference.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/TabGridUIPreference.java new file mode 100644 index 0000000000000000000000000000000000000000..084dcd8b8d5ff63eb6d073c4f73b2e68cfea51fe --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/TabGridUIPreference.java @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component; + +/** + * + * Title: class + * + * Description: The Class TabGridUIPreference. + * + * @since 3.0.0 + */ +public class TabGridUIPreference extends GridUIPreference { + + /** + * Checks if is allow column reorder. + * + * @return true, if is allow column reorder + */ + @Override + public boolean isAllowColumnReorder() { + return false; + } + + /** + * Checks if is support data export. + * + * @return true, if is support data export + */ + @Override + public boolean isSupportDataExport() { + return false; + } + + /** + * Gets the column width. + * + * @return the column width + */ + @Override + public int getColumnWidth() { + return 300; + } + + /** + * Gets the column width strategy. + * + * @return the column width strategy + */ + @Override + public ColumnWidthType getColumnWidthStrategy() { + return ColumnWidthType.FIXED_WIDTH; + } + + /** + * Gets the max display data length. + * + * @return the max display data length + */ + @Override + public int getMaxDisplayDataLength() { + return 2000; + } + + /** + * Checks if is fit to one page. + * + * @return true, if is fit to one page + */ + @Override + public boolean isFitToOnePage() { + return true; + } + + /** + * Edits the table data UI preference. + * + * @return true, if successful + */ + @Override + public boolean editTableDataUIPreference() { + return false; + } + + /** + * Checks if is need advanced copy. + * + * @return true, if is need advanced copy + */ + @Override + public boolean isNeedAdvancedCopy() { + return false; + } + + /** + * Gets the default value text. + * + * @return the default value text + */ + @Override + public String getDefaultValueText() { + return ""; + } + + /** + * Checks if is show status bar. + * + * @return true, if is show status bar + */ + @Override + public boolean isShowStatusBar() { + return true; + } + + /** + * Checks if is include encoding. + * + * @return true, if is include encoding + */ + @Override + public boolean isIncludeEncoding() { + + return false; + } + + /** + * Checks if is adds the item supported. + * + * @return true, if is adds the item supported + */ + @Override + public boolean isAddItemSupported() { + return false; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/AddPropertiesInfoDialog.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/AddPropertiesInfoDialog.java new file mode 100644 index 0000000000000000000000000000000000000000..940011111169c3817c715e6faabcc2e8c9340c37 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/AddPropertiesInfoDialog.java @@ -0,0 +1,277 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; + +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.ui.table.AddColumn; +import org.opengauss.mppdbide.view.ui.table.AddConstraint; +import org.opengauss.mppdbide.view.ui.table.CreateIndexDialog; + +/** + * + * Title: class + * + * Description: The Class AddPropertiesInfoDialog. + * + * @since 3.0.0 + */ +public class AddPropertiesInfoDialog { + + private ServerObjectTypeForDialog dialogType; + private ServerObject serverObject; + private Shell shell; + private TableMetaData tableMetaData; + + /** + * Instantiates a new adds the properties info dialog. + * + * @param type the type + * @param shell the shell + * @param tableMetaData the table meta data + */ + public AddPropertiesInfoDialog(ServerObjectTypeForDialog type, Shell shell, TableMetaData tableMetaData) { + this.dialogType = type; + this.shell = shell; + this.tableMetaData = tableMetaData; + + } + + /** + * Creates the dialog. + */ + public void createDialog() { + if (dialogType == ServerObjectTypeForDialog.COLUMNS) { + createAddColumnDialog(); + } else if (dialogType == ServerObjectTypeForDialog.CONSTRAINTS) { + createConstraintDialog(); + } else if (dialogType == ServerObjectTypeForDialog.INDEX) { + createIndexDialog(); + } + } + + private void createIndexDialog() { + + PropertiesAddIndexDialog newIndex = new PropertiesAddIndexDialog(shell, tableMetaData, + tableMetaData.getServer()); + newIndex.open(); + } + + private void createConstraintDialog() { + + PropertiesAddConstraintDialog constraintDialog = new PropertiesAddConstraintDialog(shell, tableMetaData); + constraintDialog.open(); + } + + private void createAddColumnDialog() { + + PropertiesAddColumnDialog dialog = new PropertiesAddColumnDialog(this.shell, this.tableMetaData); + dialog.open(); + + } + + /** + * Gets the server object. + * + * @return the server object + */ + public ServerObject getServerObject() { + return this.serverObject; + } + + /** + * + * Title: class + * + * Description: The Class PropertiesAddColumnDialog. + */ + private final class PropertiesAddColumnDialog extends AddColumn { + + private ColumnMetaData column; + + /** + * Instantiates a new properties add column dialog. + * + * @param shell the shell + * @param tableMetaData the table meta data + */ + public PropertiesAddColumnDialog(Shell shell, TableMetaData tableMetaData) { + super(shell, tableMetaData); + } + + @Override + public Object open() { + Object obj = super.open(); + return obj; + + } + + @Override + protected void performOkPressed() { + okButton.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent e) { + column = columnUI.getDBColumn(null, false, tableMetaData.getOrientation()); + if (null != column) { + if (null == column.getName() || "".equals(column.getName())) { + lblLblerrormsg + .setText(MessageConfigLoader.getProperty(IMessagesConstants.PLS_ENTER_COL_NAME)); + } else if (null == column.getDataType()) { + lblLblerrormsg + .setText(MessageConfigLoader.getProperty(IMessagesConstants.PLS_SELECT_DATA_TYPE)); + } else { + serverObject = column; + close(); + } + + } else { + lblLblerrormsg.setText(MessageConfigLoader.getProperty(IMessagesConstants.PLS_ENTER_COL_NAME)); + } + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + + } + }); + } + + } + + /** + * + * Title: class + * + * Description: The Class PropertiesAddConstraintDialog. + */ + private class PropertiesAddConstraintDialog extends AddConstraint { + + /** + * Instantiates a new properties add constraint dialog. + * + * @param shell the shell + * @param tableMetaData the table meta data + */ + public PropertiesAddConstraintDialog(Shell shell, TableMetaData tableMetaData) { + + super(shell, tableMetaData); + } + + @Override + public Object open() { + + return super.open(); + } + + @Override + protected void performOkPressed() { + okButton.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent e) { + ConstraintMetaData constraint = constraintUI.getConstraint(true); + lblErrormsg.setText(""); + + if (null != constraint) { + constraint.setTable(tableMetaData); + serverObject = constraint; + + close(); + + } + + else { + lblErrormsg + .setText(MessageConfigLoader.getProperty(IMessagesConstants.PLS_ENTER_TABLE_FOR_CONS)); + } + + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + + } + }); + + } + + } + + /** + * + * Title: class + * + * Description: The Class PropertiesAddIndexDialog. + */ + private class PropertiesAddIndexDialog extends CreateIndexDialog { + + /** + * Instantiates a new properties add index dialog. + * + * @param parent the parent + * @param tbl the tbl + * @param server the server + */ + public PropertiesAddIndexDialog(Shell parent, TableMetaData tbl, Server server) { + super(parent, tbl, server); + } + + @Override + protected Control createContents(Composite parent) { + + return super.createContents(parent); + } + + @Override + protected void performOkPressed() { + btnCreateIndex.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent e) { + try { + setIdx(ui.getIndexMetaData()); + close(); + serverObject = getIdx(); + } catch (DatabaseOperationException e1) { + showError(e1.getMessage()); + btnCancel.setEnabled(true); + return; + } + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + + } + }); + + } + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/BatchDropGridStyleConfiguration.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/BatchDropGridStyleConfiguration.java new file mode 100644 index 0000000000000000000000000000000000000000..86d613c87e44c0ded28b6dfeb0aa7ba5d30c127b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/BatchDropGridStyleConfiguration.java @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import org.eclipse.nebula.widgets.nattable.config.AbstractRegistryConfiguration; +import org.eclipse.nebula.widgets.nattable.config.CellConfigAttributes; +import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry; +import org.eclipse.nebula.widgets.nattable.layer.cell.ColumnOverrideLabelAccumulator; +import org.eclipse.nebula.widgets.nattable.style.DisplayMode; + +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.batchdrop.BatchDropColumnProvider; +import org.opengauss.mppdbide.presentation.grid.batchdrop.BatchDropDataProvider; +import org.opengauss.mppdbide.view.component.grid.core.DSAbstractRegistryConfiguration; + +/** + * + * Title: class + * + * Description: The Class BatchDropGridStyleConfiguration. + * + * @since 3.0.0 + */ +public class BatchDropGridStyleConfiguration extends AbstractRegistryConfiguration { + + /** + * The Constant COL_LABEL_DROP_STATUS. + */ + public static final String COL_LABEL_DROP_STATUS = "BATCHDROP_STATUS"; + + /** + * Configure registry. + * + * @param configRegistry the config registry + */ + @Override + public void configureRegistry(IConfigRegistry configRegistry) { + batchDropRegistry(configRegistry); + } + + /** + * Batch drop registry. + * + * @param configRegistry the config registry + */ + public static void batchDropRegistry(IConfigRegistry configRegistry) { + configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, new BatchDropObjectStatusPainter(), + DisplayMode.NORMAL, COL_LABEL_DROP_STATUS); + } + + /** + * Gets the column accumulator. + * + * @param columnLabelAccumulator the column label accumulator + * @param dataGridContext the data grid context + * @return the column accumulator + */ + public static DSAbstractRegistryConfiguration getColumnAccumulator( + final ColumnOverrideLabelAccumulator columnLabelAccumulator, final IDataGridContext dataGridContext) { + return new RegistryConfiguration(columnLabelAccumulator, dataGridContext); + } + + /** + * + * Title: class + * + * Description: The Class RegistryConfiguration. + */ + private static final class RegistryConfiguration extends DSAbstractRegistryConfiguration { + private IDataGridContext dataGridContext; + private ColumnOverrideLabelAccumulator columnLabelAccumulator; + private int statusColumnIdx = 3; + + private RegistryConfiguration(ColumnOverrideLabelAccumulator columnLabelAccumulator, + IDataGridContext dataGridContext) { + this.columnLabelAccumulator = columnLabelAccumulator; + this.dataGridContext = dataGridContext; + } + + @Override + public void configureRegistry(IConfigRegistry configRegistry) { + + IDSGridDataProvider dataProvider = dataGridContext.getDataProvider(); + registerConfigLabelsOnColumns(columnLabelAccumulator, dataProvider.getColumnDataProvider()); + + if (dataProvider instanceof BatchDropDataProvider) { + batchDropRegistry(configRegistry); + } + } + + @Override + public void registerConfigLabelsOnColumns(final ColumnOverrideLabelAccumulator columnLblAccumulator, + IDSGridColumnProvider columnDataProvider) { + if (columnDataProvider instanceof BatchDropColumnProvider) { + columnLblAccumulator.registerColumnOverrides(statusColumnIdx, COL_LABEL_DROP_STATUS); + } + } + + /** + * Sets the column label accumulator. + * + * @param columnLabelAccumulator the new column label accumulator + */ + public void setColumnLabelAccumulator(ColumnOverrideLabelAccumulator columnLabelAccumulator) { + this.columnLabelAccumulator = columnLabelAccumulator; + } + + @Override + public void registerUiRegistryToEachColumn(IConfigRegistry configRegistry, + IDSGridColumnProvider columnDataProvider) { + + } + + @Override + protected void onPreDestroy() { + this.columnLabelAccumulator = null; + this.dataGridContext = null; + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/BatchDropObjectStatusPainter.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/BatchDropObjectStatusPainter.java new file mode 100644 index 0000000000000000000000000000000000000000..67276e1a910c3fe8ec9dcffd4aaac518247bf6f1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/BatchDropObjectStatusPainter.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry; +import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell; +import org.eclipse.nebula.widgets.nattable.painter.cell.ImagePainter; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Rectangle; + +import org.opengauss.mppdbide.presentation.grid.batchdrop.BatchDropStatusEnum; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * + * Title: class + * + * Description: The Class BatchDropObjectStatusPainter. + * + * @since 3.0.0 + */ +public class BatchDropObjectStatusPainter extends ImagePainter { + private final Image completedImg; + private final Image inProgressImg; + private final Image errorImg; + private final Image toStartImg; + + /** + * Instantiates a new batch drop object status painter. + */ + public BatchDropObjectStatusPainter() { + this(true); + } + + /** + * Instantiates a new batch drop object status painter. + * + * @param paintBg the paint bg + */ + public BatchDropObjectStatusPainter(boolean paintBg) { + super(paintBg); + this.completedImg = IconUtility.getIconImage(IiconPath.ICON_DROP_OBJECTS_COMPLETED, this.getClass()); + this.inProgressImg = IconUtility.getIconImage(IiconPath.ICON_DROP_OBJECTS_INPROGRESS, this.getClass()); + this.errorImg = IconUtility.getIconImage(IiconPath.ICON_DROP_OBJECTS_ERROR, this.getClass()); + this.toStartImg = IconUtility.getIconImage(IiconPath.ICON_DROP_OBJECTS_TOSTART, this.getClass()); + } + + /** + * Gets the preferred width. + * + * @param status the status + * @return the preferred width + */ + public int getPreferredWidth(BatchDropStatusEnum status) { + return getImage(status).getBounds().width; + } + + /** + * Gets the preferred height. + * + * @param status the status + * @return the preferred height + */ + public int getPreferredHeight(BatchDropStatusEnum status) { + return getImage(status).getBounds().height; + } + + /** + * Paint icon image. + * + * @param gc the gc + * @param rectangle the rectangle + * @param yOffset the y offset + * @param status the status + */ + public void paintIconImage(GC gc, Rectangle rectangle, int yOffset, BatchDropStatusEnum status) { + Image statusImage = getImage(status); + + // Center image + int xAxis = rectangle.x + (rectangle.width / 2) - (statusImage.getBounds().width / 2); + + gc.drawImage(statusImage, xAxis, rectangle.y + yOffset); + } + + /** + * Gets the image. + * + * @param status the status + * @return the image + */ + public Image getImage(BatchDropStatusEnum status) { + if (status == BatchDropStatusEnum.TO_START) { + return this.toStartImg; + } + if (status == BatchDropStatusEnum.IN_PROGRESS) { + return this.inProgressImg; + } + if (status == BatchDropStatusEnum.ERROR) { + return this.errorImg; + } + if (status == BatchDropStatusEnum.COMPLETED) { + return this.completedImg; + } + + return this.toStartImg; + } + + /** + * Gets the image. + * + * @param cell the cell + * @param configRegistry the config registry + * @return the image + */ + @Override + protected Image getImage(ILayerCell cell, IConfigRegistry configRegistry) { + return getImage(convertDataType(cell, configRegistry)); + } + + /** + * Convert data type. + * + * @param cell the cell + * @param configRegistry the config registry + * @return the batch drop status enum + */ + protected BatchDropStatusEnum convertDataType(ILayerCell cell, IConfigRegistry configRegistry) { + if (cell.getDataValue() instanceof BatchDropStatusEnum) { + return (BatchDropStatusEnum) cell.getDataValue(); + } + + return BatchDropStatusEnum.TO_START; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/CommitInputData.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/CommitInputData.java new file mode 100644 index 0000000000000000000000000000000000000000..57ff04a191045f602cb31d628e68ad1b72a97266 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/CommitInputData.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import java.util.List; + +/** + * + * Title: class + * + * Description: The Class CommitInputData. + * + * @since 3.0.0 + */ +public class CommitInputData { + + private List uniqueKeys; + private boolean isAtomic; + private boolean isRemember; + + /** + * Instantiates a new commit input data. + */ + public CommitInputData() { + + } + + /** + * Gets the unique keys. + * + * @return the unique keys + */ + public List getUniqueKeys() { + return uniqueKeys; + } + + /** + * Checks if is atomic. + * + * @return true, if is atomic + */ + public boolean isAtomic() { + return isAtomic; + } + + /** + * Sets the unique keys. + * + * @param uniqueKeys the new unique keys + */ + public void setUniqueKeys(List uniqueKeys) { + this.uniqueKeys = uniqueKeys; + } + + /** + * Sets the atomic. + * + * @param isAtmic the new atomic + */ + public void setAtomic(boolean isAtmic) { + this.isAtomic = isAtmic; + } + + /** + * Sets the remember. + * + * @param isRmember the new remember + */ + public void setRemember(boolean isRmember) { + this.isRemember = isRmember; + } + + /** + * Gets the remember. + * + * @return the remember + */ + public boolean getRemember() { + return this.isRemember; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/CommitRecordEventData.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/CommitRecordEventData.java new file mode 100644 index 0000000000000000000000000000000000000000..9a882e56d02dd8e521d5ed6216589fdc51d33eaf --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/CommitRecordEventData.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.utils.observer.DSEventTable; +import org.opengauss.mppdbide.view.component.grid.core.DataGrid; +import org.opengauss.mppdbide.view.component.grid.core.DataText; + +/** + * + * Title: class + * + * Description: The Class CommitRecordEventData. + * + * @since 3.0.0 + */ +public class CommitRecordEventData { + + private CommitInputData commitData; + private DataGrid datagrid; + private DataText datatext; + private DSEventTable eventTable; + private IDSGridDataProvider dataProvider; + + /** + * Instantiates a new commit record event data. + */ + public CommitRecordEventData() { + + } + + /** + * Gets the data provider. + * + * @return the data provider + */ + public IDSGridDataProvider getDataProvider() { + return dataProvider; + } + + /** + * Sets the data provider. + * + * @param dataProvider the new data provider + */ + public void setDataProvider(IDSGridDataProvider dataProvider) { + this.dataProvider = dataProvider; + } + + /** + * Gets the commit data. + * + * @return the commit data + */ + public CommitInputData getCommitData() { + return commitData; + } + + /** + * Gets the data grid. + * + * @return the data grid + */ + public DataGrid getDataGrid() { + return datagrid; + } + + /** + * Gets the data text. + * + * @return the data text + */ + public DataText getDataText() { + return datatext; + } + + /** + * Gets the event table. + * + * @return the event table + */ + public DSEventTable getEventTable() { + return eventTable; + } + + /** + * Sets the commit data. + * + * @param commitData the new commit data + */ + public void setCommitData(CommitInputData commitData) { + this.commitData = commitData; + } + + /** + * Sets the datagrid. + * + * @param datagrid the new datagrid + */ + public void setDatagrid(DataGrid datagrid) { + this.datagrid = datagrid; + } + + /** + * Sets the data text. + * + * @param text the new data text + */ + public void setDataText(DataText text) { + this.datatext = text; + } + + /** + * Sets the event table. + * + * @param eventTable the new event table + */ + public void setEventTable(DSEventTable eventTable) { + this.eventTable = eventTable; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/CustomDialogCellEditor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/CustomDialogCellEditor.java new file mode 100644 index 0000000000000000000000000000000000000000..944a62de2b7773aa4b55554bc6905ded2c76c4f2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/CustomDialogCellEditor.java @@ -0,0 +1,269 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import java.util.List; + +import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry; +import org.eclipse.nebula.widgets.nattable.edit.editor.AbstractCellEditor; +import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer.MoveDirectionEnum; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; + +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableRecordStates; +import org.opengauss.mppdbide.presentation.edittabledata.IDSGridEditDataRow; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.presentation.objectproperties.DSObjectPropertiesGridDataProvider; +import org.opengauss.mppdbide.presentation.objectproperties.DSObjectPropertiesGridDataRow; +import org.opengauss.mppdbide.presentation.objectproperties.ObjectPropColumnTabInfo; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.ui.table.ChangeDataTypeDialog; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs.MESSAGEDIALOGTYPE; + +/** + * + * Title: class + * + * Description: The Class CustomDialogCellEditor. + * + * @since 3.0.0 + */ +public class CustomDialogCellEditor extends AbstractCellEditor { + + private IDSGridDataProvider dataProvider; + private ChangePropertiesDatatypeDialog dilg; + private ColumnMetaData columnMetadata; + private ObjectPropColumnTabInfo info; + private TableMetaData table; + + /** + * Instantiates a new custom dialog cell editor. + * + * @param dataProvider the data provider + */ + public CustomDialogCellEditor(IDSGridDataProvider dataProvider) { + this.dataProvider = dataProvider; + this.table = (TableMetaData) dataProvider.getTable(); + + } + + /** + * Gets the editor value. + * + * @return the editor value + */ + @Override + public Object getEditorValue() { + return this.info; + } + + /** + * Sets the editor value. + * + * @param value the new editor value + */ + @Override + public void setEditorValue(Object value) { + + } + + /** + * Sets the canonical value. + * + * @param canonicalValue the new canonical value + */ + @Override + public void setCanonicalValue(Object canonicalValue) { + } + + /** + * Gets the canonical value. + * + * @return the canonical value + */ + @Override + public Object getCanonicalValue() { + return info; + } + + /** + * Gets the editor control. + * + * @return the editor control + */ + @Override + public Control getEditorControl() { + return null; + } + + /** + * Creates the editor control. + * + * @param parent the parent + * @return the control + */ + @Override + public Control createEditorControl(Composite parent) { + + return null; + } + + /** + * Activate cell. + * + * @param parent the parent + * @param originalCanonicalValue the original canonical value + * @return the control + */ + @Override + protected Control activateCell(Composite parent, Object originalCanonicalValue) { + boolean colNotFound = true; + List allRows = ((DSObjectPropertiesGridDataProvider) dataProvider).getAllRows(); + IDSGridEditDataRow idsGridDataRow; + if (allRows.size() > getRowIndex()) { + idsGridDataRow = (IDSGridEditDataRow) allRows.get(getRowIndex()); + } else { + return null; + } + /* + * The below check is used for getting the columnmetadata directly from + * the row while changing the datatype of a column + */ + if (((IDSGridEditDataRow) idsGridDataRow).getUpdatedState(getColumnIndex()) == EditTableRecordStates.INSERT) { + this.columnMetadata = (ColumnMetaData) ((DSObjectPropertiesGridDataRow) idsGridDataRow).getServerObject(); + } else { + + List columnMetaDataList = this.table.getColumnMetaDataList(); + for (ColumnMetaData col : columnMetaDataList) { + if (idsGridDataRow.getOriginalValue(0).equals(col.getName())) { + colNotFound = false; + this.columnMetadata = col; + break; + } + } + + if (colNotFound) { + MPPDBIDEDialogs.generateOKMessageDialog(MESSAGEDIALOGTYPE.ERROR, true, + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_WINDOW_ERROR_POPUP_HEADER), + MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_COMPLEX_DATATYPE_ERROR_MSG, + idsGridDataRow.getOriginalValue(0))); + return null; + } + } + + dilg = new ChangePropertiesDatatypeDialog(parent.getShell(), this.table, this.columnMetadata); + dilg.open(); + return null; + } + + /** + * + * Title: class + * + * Description: The Class ChangePropertiesDatatypeDialog. + */ + private final class ChangePropertiesDatatypeDialog extends ChangeDataTypeDialog { + private ColumnMetaData modifiedColumn; + + /** + * Instantiates a new change properties datatype dialog. + * + * @param shell the shell + * @param tableMetaData the table meta data + * @param column the column + */ + public ChangePropertiesDatatypeDialog(Shell shell, TableMetaData tableMetaData, ColumnMetaData column) { + super(shell, tableMetaData, column); + this.modifiedColumn = column; + } + + @Override + public Object open() { + + return super.open(); + } + + @Override + public void performOkButtonPressed() { + super.performOkButtonPressed(); + getDBColumn(); + collectUserData(); + String formattedTextToDisplay = formatDataForChangeDatatye(); + setEditorValue(formattedTextToDisplay); + commit(MoveDirectionEnum.NONE, true); + dilg.close(); + } + + @Override + public void cancelPressed() { + dilg.close(); + } + + private void collectUserData() { + info = new ObjectPropColumnTabInfo(); + info.setDataTypeSchema(comboClmDataSchema.getText()); + info.setColDataType(modifiedColumn.getDataType()); + info.setPrecision(Integer.parseInt(spinnerPrevSize.getText())); + info.setScale(Integer.parseInt(spinnerScale.getText())); + } + + } + + /** + * Support multi edit. + * + * @param configRegistry the config registry + * @param configLabels the config labels + * @return true, if successful + */ + @Override + public boolean supportMultiEdit(IConfigRegistry configRegistry, List configLabels) { + if (configLabels.contains(IEditTableGridStyleLabelFactory.COL_LABEL_CUSTOM_DIALOG)) { + return false; + } + return super.supportMultiEdit(configRegistry, configLabels); + } + + /** + * Format data for change datatye. + * + * @return the string + */ + public String formatDataForChangeDatatye() { + + StringBuilder formattedString = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + formattedString.append(info.getColDatatype()); + if (info.getPrecision() > 0) { + formattedString.append('('); + formattedString.append(info.getPrecision()); + if (info.getScale() > 0) { + formattedString.append(','); + formattedString.append(info.getScale()); + } + formattedString.append(')'); + } + + return formattedString.toString(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/DSCDateTimeCellEditor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/DSCDateTimeCellEditor.java new file mode 100644 index 0000000000000000000000000000000000000000..f2accc0b1518c3a3ee7b2ea22c766db4535a861d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/DSCDateTimeCellEditor.java @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import java.util.List; + +import org.eclipse.nebula.widgets.cdatetime.CDateTime; +import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry; +import org.eclipse.nebula.widgets.nattable.extension.nebula.cdatetime.CDateTimeCellEditor; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.events.MouseListener; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Text; + +/** + * + * Title: class + * + * Description: The Class DSCDateTimeCellEditor. + * + * @since 3.0.0 + */ +public class DSCDateTimeCellEditor extends CDateTimeCellEditor { + private boolean isCellEditable = false; + + /** + * Instantiates a new DSC date time cell editor. + * + * @param moveSelectionOnEnter the move selection on enter + * @param style the style + */ + public DSCDateTimeCellEditor(boolean moveSelectionOnEnter, int style) { + super(moveSelectionOnEnter, style); + } + + /** + * Activate cell. + * + * @param parent the parent + * @param originalCanonicalValue the original canonical value + * @return the control + */ + @Override + protected Control activateCell(Composite parent, Object originalCanonicalValue) { + + super.activateCell(parent, originalCanonicalValue); + isCellEditable = labelStack.hasLabel(IEditTableGridStyleLabelFactory.COL_LABEL_READONLY_CELL); + Text text = (Text) getEditorControl().getChildren()[0]; + DSGridMenuManager.addContextMenuWithID(text, !isCellEditable); + getEditorControl().addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent event) { + + } + + @Override + public void widgetDefaultSelected(SelectionEvent event) { + if (labelStack.hasLabel(IEditTableGridStyleLabelFactory.COL_LABEL_READONLY_CELL)) { + event.doit = false; + } + + } + }); + + getEditorControl().addMouseListener(new MouseListener() { + + @Override + public void mouseUp(MouseEvent mouseEvent) { + if (labelStack.hasLabel(IEditTableGridStyleLabelFactory.COL_LABEL_READONLY_CELL)) { + CDateTime editorControl = getEditorControl(); + editorControl.setEditable(false); + } + getEditorControl().getDisplay().getActiveShell().forceFocus(); + } + + @Override + public void mouseDown(MouseEvent mouseEvent) { + } + + @Override + public void mouseDoubleClick(MouseEvent mouseEvent) { + + } + }); + + return getEditorControl(); + } + + /** + * Support multi edit. + * + * @param configRegistry the config registry + * @param configLabels the config labels + * @return true, if successful + */ + @Override + public boolean supportMultiEdit(IConfigRegistry configRegistry, List configLabels) { + if (configLabels.contains(IEditTableGridStyleLabelFactory.COL_LABEL_READONLY_CELL)) { + return false; + } + return super.supportMultiEdit(configRegistry, configLabels); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/DSGridComponent.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/DSGridComponent.java new file mode 100644 index 0000000000000000000000000000000000000000..ee815262a39eb947ccd6b4ca0849916e82db2338 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/DSGridComponent.java @@ -0,0 +1,1016 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import java.util.Observable; +import java.util.Observer; + +import javax.annotation.PreDestroy; + +import org.eclipse.jface.layout.GridDataFactory; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.ToolItem; + +import org.opengauss.mppdbide.adapter.keywordssyntax.SQLSyntax; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.sqlhistory.IQueryExecutionSummary; +import org.opengauss.mppdbide.presentation.edittabledata.CommitStatus; +import org.opengauss.mppdbide.presentation.edittabledata.DSResultSetGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSEditGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.objectproperties.DSObjectPropertiesGridDataProvider; +import org.opengauss.mppdbide.presentation.objectproperties.PropertiesUserRoleImpl; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.utils.observer.DSEventTable; +import org.opengauss.mppdbide.utils.observer.IDSGridUIListenable; +import org.opengauss.mppdbide.utils.observer.IDSListener; +import org.opengauss.mppdbide.view.component.DSGridStateMachine; +import org.opengauss.mppdbide.view.component.IGridUIPreference; +import org.opengauss.mppdbide.view.component.DSGridStateMachine.State; +import org.opengauss.mppdbide.view.component.grid.core.DSCursorResultSetTable; +import org.opengauss.mppdbide.view.component.grid.core.DataGrid; +import org.opengauss.mppdbide.view.component.grid.core.DataText; +import org.opengauss.mppdbide.view.component.grid.listeners.MultiColumnSortPoUpListener; +import org.opengauss.mppdbide.view.ui.DatabaseListControl; +import org.opengauss.mppdbide.view.utils.UIElement; + +/** + * + * Title: class + * + * Description: The Class DSGridComponent. + * + * @since 3.0.0 + */ +public class DSGridComponent implements IDSGridUIListenable, Observer { + // Children + + /** + * The query area. + */ + protected GridQueryArea queryArea; + + /** + * The search area. + */ + protected GridSearchArea searchArea; + + /** + * The toolbar. + */ + protected GridToolbar toolbar; + + /** + * The grid. + */ + protected DataGrid grid; + + /** + * The text. + */ + protected DataText text; + + /** + * The status bar. + */ + protected GridStatusBar statusBar; + + /** + * The event table. + */ + protected DSEventTable eventTable; + + /** + * The state machine. + */ + protected DSGridStateMachine stateMachine; + + /** + * The ui pref. + */ + protected volatile IGridUIPreference uiPref; + + /** + * The data provider. + */ + protected IDSGridDataProvider dataProvider; + private GridSearchAreaToDataGrid gridSearchAreaToDataGrid; + private MultiColumnSortPoUpListener multiColumnSortPoUpListener; + private final Object INSTANCE_LOCK = new Object(); + + /** + * Instantiates a new DS grid component. + * + * @param uiPref the ui pref + * @param dataProvider the data provider + */ + public DSGridComponent(IGridUIPreference uiPref, IDSGridDataProvider dataProvider) { + this.uiPref = uiPref; + this.dataProvider = dataProvider; + this.eventTable = new DSEventTable(); + this.stateMachine = new DSGridStateMachine(); + this.grid = null; + this.statusBar = null; + DatabaseListControl databaseListControl = UIElement.getInstance().getDatabaseListControl(); + if (null != databaseListControl) { + databaseListControl.addObserver(this); + } + } + + /** + * Creates the components. + * + * @param parent the parent + */ + public void createComponents(Composite parent) { + Composite gridComposite = createNewComposite(parent); + createToolbarAndSearchArea(gridComposite); + + addToolbarOptionsAndUiPrefs(false); + + addUiPrefs(false); + + if (null != this.grid && (!uiPref.isEnableEdit() || uiPref.isEditQueryResultsFlow())) { + ((DataGrid) this.grid).configureLoadOnScroll(this.eventTable); + if (null != this.text) { + ((DataText) this.text).configureLoadOnScroll(this.eventTable); + } + + } + if (uiPref.isShowQueryArea()) { + this.queryArea.doHideQueryArea(); + this.toolbar.updateToggleQueryAreaImage(); + } + + this.eventTable.sendEvent(new DSEvent(LISTEN_TYPE_ON_GRID_CREATION, toolbar)); + statusMsgEventRegister(); + if (null != this.grid) { + this.grid.setFocus(); + } + } + + /** + * return component + * + * @param parent the parent + * @return the cursor popup component + */ + public Composite cursorPopupComponents(Composite parent, boolean isCursorPopup) { + Composite gridComposite = createNewComposite(parent); + + createCursorResultGridDataArea(gridComposite); + addToolbarOptionsAndUiPrefs(true); + addUiPrefs(isCursorPopup); + + if (null != this.grid && (!uiPref.isEnableEdit() || uiPref.isEditQueryResultsFlow())) { + ((DataGrid) this.grid).configureLoadOnScroll(this.eventTable); + if (null != this.text) { + ((DataText) this.text).configureLoadOnScroll(this.eventTable); + } + + } + if (null != this.grid) { + this.grid.setFocus(); + } + + return gridComposite; + } + + /** + * create grid area for cursor popup window + * + * @param gridComposite the gridComposite + */ + private void createCursorResultGridDataArea(Composite gridComposite) { + this.toolbar = createToolBar(gridComposite, this.dataProvider); + this.searchArea = createSearchArea(gridComposite); + if (uiPref.isNeedCreateTextMode()) { + this.text = createDataTextArea(gridComposite); + this.searchArea.setText(this.text); + this.searchArea.setToolbar(toolbar); + } + this.grid = createDataGridArea(gridComposite); + + this.searchArea.setGrid(this.grid); + this.toolbar.addItemCopy(this.stateMachine, false); + this.toolbar.setDsExportState(this.stateMachine); + + if (this.uiPref.isNeedAdvancedCopy()) { + this.toolbar.addItemAdvancedCopy(this.stateMachine); + } + + } + + private void addUiPrefs(boolean isCursorPopup) { + if (uiPref.isEnableSort()) { + ToolItem beginSeparator = new ToolItem(this.toolbar.getToolBar(), SWT.SEPARATOR); + beginSeparator.setEnabled(true); + multiColumnSortPoUpListener = new MultiColumnSortPoUpListener(this.grid); + this.toolbar.addItemMultiSort(multiColumnSortPoUpListener); + this.toolbar.addItemClearSort(); + } + if (uiPref.isAddBatchDropTool()) { + this.toolbar.addBatchDropToolbar(this.eventTable); + } + if (uiPref.isEnableEdit()) { + this.toolbar.handleDataEditEvent(true); + } + if (uiPref.isNeedCreateTextMode()) { + // Add grid text button + ToolItem beginSeparator = new ToolItem(this.toolbar.getToolBar(), SWT.SEPARATOR); + beginSeparator.setEnabled(true); + this.toolbar.addItemShowGrid(this.eventTable); + this.toolbar.addItemShowText(this.eventTable); + } + if (uiPref.isShowLoadMoreRecordButton()) { + ToolItem beginSeparator = new ToolItem(this.toolbar.getToolBar(), SWT.SEPARATOR); + beginSeparator.setEnabled(true); + this.toolbar.addLoadMoreRecord(this.eventTable, this.stateMachine); + } + if (uiPref.isIncludeEncoding()) { + this.toolbar.addEncoding(this.eventTable, uiPref.getDefaultEncoding()); + } + + if (uiPref.isShowStatusBar() && !isCursorPopup) { + this.statusBar.updateDataProviderSummaryData(this.dataProvider); + } + } + + private void addToolbarOptionsAndUiPrefs(boolean isCursorPopup) { + if (this.uiPref.isSupportDataExport()) { + if (this.uiPref.isAddItemExportAll() && !this.dataProvider.isFuncProcExport()) { + this.toolbar.addItemExportAll(this.eventTable, this.stateMachine, isCursorPopup); + } + this.toolbar.addItemExportCurrentPage(this.eventTable, this.stateMachine); + } + + // check for edit table data + if (uiPref.isEnableEdit() && ((IDSEditGridDataProvider) dataProvider).isEditSupported()) { + ToolItem beginSeparator = new ToolItem(this.toolbar.getToolBar(), SWT.SEPARATOR); + beginSeparator.setEnabled(true); + + this.toolbar.addItemPasteCells(this.eventTable, this.stateMachine); + boolean needToBeValidated = isNeedToValidate(); + if (needToBeValidated) { + this.toolbar.addItemInsertRow(this.eventTable, this.stateMachine); + this.toolbar.addItemDeleteRow(this.eventTable, this.stateMachine); + } + this.toolbar.addItemCommitRecord(this.eventTable, this.stateMachine); + this.toolbar.addItemRollBackChanges(this.eventTable, this.stateMachine); + this.toolbar.addForgetItem(this.eventTable); + + ToolItem endSeparator = new ToolItem(this.toolbar.getToolBar(), SWT.SEPARATOR); + endSeparator.setEnabled(true); + } + if (uiPref.isRefreshSupported()) { + this.toolbar.addRefreshItem(this.eventTable, this.stateMachine); + } + if (uiPref.isShowQueryArea()) { + this.toolbar.addItemToggleQueryArea(this.queryArea); + } + + // check for edit table data + + this.toolbar.addItemToggleSearchArea(this.searchArea); + } + + private void createToolbarAndSearchArea(Composite gridComposite) { + this.toolbar = createToolBar(gridComposite, this.dataProvider); + this.searchArea = createSearchArea(gridComposite); + if (uiPref.isShowQueryArea()) { + this.queryArea = createQueryArea(gridComposite); + } + if (uiPref.isNeedCreateTextMode()) { + this.text = createDataTextArea(gridComposite); + this.searchArea.setText(this.text); + this.searchArea.setToolbar(toolbar); + } + this.grid = createDataGridArea(gridComposite); + + if (uiPref.isShowStatusBar()) { + this.statusBar = createStatusBar(gridComposite, this.dataProvider); + } + this.searchArea.setGrid(this.grid); + this.toolbar.addItemCopy(this.stateMachine, false); + this.toolbar.setDsExportState(this.stateMachine); + + if (this.uiPref.isNeedAdvancedCopy()) { + this.toolbar.addItemAdvancedCopy(this.stateMachine); + } + } + + private DataText createDataTextArea(Composite gridComposite) { + // Create a text container + Composite textComposite = createNewComposite(gridComposite); + // Create a search container + Composite searchComposite = createNewComposite(gridComposite); + this.text = new DataText(this.uiPref, this.dataProvider, this.eventTable, this.stateMachine, this); + this.text.setInitDataTextFlag(true); + this.text.setSearchParent(searchComposite); + this.text.setSearArea(searchArea); + if (uiPref.isEnableEdit() && ((IDSEditGridDataProvider) dataProvider).isEditSupported()) { + if (isNeedToValidate()) { + this.text.setShowOrHiderefFlag(true); + } + } + text.createComponent(textComposite); + text.createSearchComponent(); + if (uiPref.isNeedCreateTextMode()) { + doHideTextComposite(textComposite); + doHideTextComposite(searchComposite); + } + return text; + } + + /** + * Do hide text composite. + * + * @param textComposite the text composite + */ + protected void doHideTextComposite(Composite textComposite) { + GridUIUtils.toggleCompositeSectionVisibility(textComposite, true, null, false); + } + + private boolean isNeedToValidate() { + return !(dataProvider instanceof DSObjectPropertiesGridDataProvider) + || (dataProvider instanceof DSObjectPropertiesGridDataProvider + && !(((DSObjectPropertiesGridDataProvider) dataProvider) + .getObjectPropertyObject() instanceof PropertiesUserRoleImpl)); + } + + /** + * Status msg event register. + */ + protected void statusMsgEventRegister() { + if (this.uiPref.isShowStatusBar()) { + addListener(LISTEN_TYPE_POST_GRID_DATA_LOAD, this.statusBar.getUpdateMessageListener()); + addListener(LISTEN_TYPE_ON_ERROR, this.statusBar.getDataLoadErrorListener(this.stateMachine)); + addListener(LISTEN_EDITTABLE_COMMIT_STATUS, this.statusBar.getUpdateEditTableStatus()); + } + if (this.grid != null) { + addListener(LISTEN_EDITTABLE_COMMIT_STATUS, ((DataGrid) this.grid).getCommitStatusListener()); + } + addListener(LISTEN_EDITTABLE_REMEMBERED_USER_OPTION, this.toolbar.getRemberUserOptionListener()); + } + + /** + * Gets the data edit listener. + * + * @return the data edit listener + */ + public IDSListener getDataEditListener() { + return new IDSListener() { + @Override + public void handleEvent(DSEvent event) { + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + synchronized (INSTANCE_LOCK) { + + if (uiPref.isEnableEdit()) { + Database db = dataProvider.getDatabse(); + if (db != null) { + DSGridComponent.this.toolbar.handleDataEditEvent(db.isConnected()); + } + if (uiPref.isShowStatusBar()) { + DSGridComponent.this.statusBar.handleDataEditEvent(); + } + } + } + } + }); + } + }; + + } + + /** + * Save sort state. + */ + public void saveSortState() { + if (null == this.grid) { + return; + } + this.grid.saveSortState(); + } + + /** + * Restore last sort state. + */ + public void restoreLastSortState() { + if (null == this.grid) { + return; + } + this.grid.restoreLastSortState(null); + } + + /** + * Save reorder state. + */ + public void saveReorderState() { + if (null == this.grid) { + return; + } + this.grid.saveReorderState(); + } + + /** + * Restore last reorder state. + */ + public void restoreLastReorderState() { + if (null == this.grid) { + return; + } + this.grid.restoreReorderState(); + } + + /** + * Creates the query area. + * + * @param gridComposite the grid composite + * @return the grid query area + */ + protected GridQueryArea createQueryArea(Composite gridComposite) { + GridQueryArea area = new GridQueryArea(this.dataProvider); + if (this.dataProvider.getDatabse() != null) { + area.setSQLSyntax(this.dataProvider.getDatabse().getSqlSyntax()); + } + area.createComponent(gridComposite, false); + return area; + } + + /** + * Creates the search area. + * + * @param gridComposite the grid composite + * @return the grid search area + */ + protected GridSearchArea createSearchArea(Composite gridComposite) { + GridSearchArea area = new GridSearchArea(); + area.createComponent(gridComposite, stateMachine); + return area; + } + + /** + * Creates the tool bar. + * + * @param gridComposite the grid composite + * @param gridDataProvider the grid data provider + * @return the grid toolbar + */ + protected GridToolbar createToolBar(Composite gridComposite, IDSGridDataProvider gridDataProvider) { + GridToolbar gridToolbar = new GridToolbar(); + stateMachine.addObserver(gridToolbar); + gridToolbar.createComponent(gridComposite, gridDataProvider, this); + return gridToolbar; + } + + /** + * Creates the data grid area. + * + * @param gridComposite the grid composite + * @return the data grid + */ + protected DataGrid createDataGridArea(Composite gridComposite) { + Composite composite = new Composite(gridComposite, SWT.None); + DSGridComponent.setLayoutProperties(composite); + DataGrid dataGrid = null; + + if (this.uiPref.isIncludeEncoding() && dataProvider instanceof DSResultSetGridDataProvider) { + ((DSResultSetGridDataProvider) dataProvider).setIncludeEncoding(true); + ((DSResultSetGridDataProvider) dataProvider).changeEncoding(this.uiPref.getDefaultEncoding()); + } + + dataGrid = createDataGrid(composite); + eventTable.sendEvent(new DSEvent(LISTEN_TYPE_POST_GRID_DATA_LOAD, dataProvider)); + + return dataGrid; + } + + /** + * Creates the data grid. + * + * @param composite the composite + * @return the data grid + */ + protected DataGrid createDataGrid(Composite composite) { + DataGrid dataGrid; + dataGrid = new DataGrid(this.uiPref, this.dataProvider, this.eventTable, this.stateMachine); + dataGrid.createComponent(composite); + return dataGrid; + } + + /** + * Creates the status bar. + * + * @param gridComposite the grid composite + * @param gridDataProvider the grid data provider + * @return the grid status bar + */ + protected GridStatusBar createStatusBar(Composite gridComposite, IDSGridDataProvider gridDataProvider) { + GridStatusBar gridStatusBar = new GridStatusBar(); + gridStatusBar.createComponent(gridComposite, stateMachine, gridDataProvider); + return gridStatusBar; + } + + /** + * Creates the new composite. + * + * @param parent the parent + * @return the composite + */ + protected Composite createNewComposite(Composite parent) { + DSGridComponent.setLayoutProperties(parent); + Composite gridComposite = new Composite(parent, SWT.BORDER); + DSGridComponent.setLayoutProperties(gridComposite); + + return gridComposite; + } + + /** + * Sets the layout properties. + * + * @param parent the new layout properties + */ + public static void setLayoutProperties(Composite parent) { + GridLayout gridlayout = new GridLayout(); + + gridlayout.marginTop = 0; + gridlayout.marginBottom = 0; + gridlayout.marginRight = 0; + gridlayout.marginLeft = 0; + gridlayout.marginHeight = 0; + gridlayout.marginWidth = 0; + gridlayout.verticalSpacing = 0; + gridlayout.horizontalSpacing = 0; + parent.setLayout(gridlayout); + GridDataFactory.fillDefaults().grab(true, true).applyTo(parent); + } + + /** + * Adds the listener. + * + * @param type the type + * @param listener the listener + */ + @Override + public void addListener(int type, IDSListener listener) { + eventTable.hook(type, listener); + } + + /** + * Removes the listener. + * + * @param type the type + * @param listener the listener + */ + @Override + public void removeListener(int type, IDSListener listener) { + eventTable.unhook(type, listener); + } + + /** + * On pre destroy. + */ + @PreDestroy + public void onPreDestroy() { + // Cleanup + DatabaseListControl databaseListControl = UIElement.getInstance().getDatabaseListControl(); + if (null != databaseListControl) { + databaseListControl.deleteObserver(this); + } + if (null != this.stateMachine) { + this.stateMachine.deleteObservers(); + this.stateMachine.preDestroy(); + this.stateMachine = null; + } + + this.uiPref = null; + + if (null != this.eventTable) { + this.eventTable.unhookall(); + this.eventTable = null; + } + + if (null != this.queryArea) { + this.queryArea.preDestroy(); + this.queryArea = null; + } + + if (gridSearchAreaToDataGrid != null) { + gridSearchAreaToDataGrid.onPreDestroy(); + gridSearchAreaToDataGrid = null; + + } + + if (this.multiColumnSortPoUpListener != null) { + multiColumnSortPoUpListener.onPreDestroy(); + multiColumnSortPoUpListener = null; + } + if (null != this.searchArea) { + this.searchArea.preDestroy(); + this.searchArea = null; + } + + cleanupOnPreDestroy(); + } + + private void cleanupOnPreDestroy() { + if (null != this.toolbar) { + this.toolbar.preDestroy(); + this.toolbar = null; + } + + if (null != this.grid) { + this.grid.onPreDestroy(); + this.grid = null; + } + if (null != this.text) { + this.text.onPreDestroy(); + this.text = null; + } + if (null != this.statusBar) { + this.statusBar.preDestroy(); + this.statusBar = null; + } + + if (null != this.dataProvider) { + this.dataProvider.preDestroy(); + this.dataProvider = null; + } + } + + /** + * Sets the data provider. + * + * @param dataProvider the new data provider + */ + public void setDataProvider(IDSGridDataProvider dataProvider) { + + final boolean preserveScrollLocation = true; + String encoding = null; + try { + if (this.uiPref.isIncludeEncoding() && dataProvider instanceof DSResultSetGridDataProvider) { + ((DSResultSetGridDataProvider) dataProvider).setIncludeEncoding(true); + encoding = this.toolbar.getSelectedEncoding(); + if (encoding != null) { + ((DSResultSetGridDataProvider) dataProvider).changeEncoding(encoding); + } else { + ((DSResultSetGridDataProvider) dataProvider).changeEncoding(this.uiPref.getDefaultEncoding()); + } + } + this.grid.inputChanged(dataProvider, preserveScrollLocation); + // Load data after triggering scroll bar or refresh button + if (null != this.text && !text.isInitDataTextFlag()) { + this.text.resetTextData(dataProvider); + } + this.toolbar.setDataProvider(dataProvider); + if (this.uiPref.isShowStatusBar()) { + this.statusBar.setDataProvider(dataProvider); + } + // updating the data provider + this.dataProvider = dataProvider; + } catch (OutOfMemoryError e) { + dataLoadOutOfMemError(e.getCause()); + } + } + + /** + * Data load out of mem error. + * + * @param throwable the throwable + */ + public void dataLoadOutOfMemError(Throwable throwable) { + String msg = MessageConfigLoader.getProperty(IMessagesConstants.ERR_OUT_OF_MEMORY_OCCURED); + eventTable.sendEvent(new DSEvent(LISTEN_TYPE_ON_ERROR, new DatabaseOperationException(msg, throwable))); + } + + /** + * Data load error. + */ + public void dataLoadError() { + eventTable.sendEvent(new DSEvent(LISTEN_TYPE_ON_ERROR, null)); + } + + /** + * Gets the data provider. + * + * @return the data provider + */ + public IDSGridDataProvider getDataProvider() { + return dataProvider; + } + + /** + * Gets the UI data iterator. + * + * @return the UI data iterator + */ + public GridViewPortData getUIDataIterator() { + return this.grid.getViewLayerDataIterator(); + } + + /** + * Gets the select data iterator. + * + * @return the select data iterator + */ + public GridSelectionLayerPortData getSelectDataIterator() { + return this.grid.getSelectionLayerDataIterator(); + } + + /** + * Focus. + */ + public void focus() { + if (this.grid != null && this.grid.getDataGrid() != null && !this.grid.getDataGrid().isDisposed()) { + this.grid.setFocus(); + } + } + + /** + * Sets the loading status. + * + * @param status the new loading status + */ + public void setLoadingStatus(boolean status) { + State state = status ? State.LOADING : State.IDLE; + stateMachine.set(state); + } + + /** + * Enable disable grid. + * + * @param enable the enable + */ + public void enableDisableGrid(boolean enable) { + if (grid == null || grid.getDataGrid() == null || grid.getDataGrid().isDisposed()) { + return; + } + grid.getDataGrid().setEnabled(enable); + } + + /** + * Saved user option. + */ + public void savedUserOption() { + + Boolean boolTrue = Boolean.valueOf(true); + eventTable.sendEvent(new DSEvent(LISTEN_EDITTABLE_REMEMBERED_USER_OPTION, boolTrue)); + + } + + /** + * Gets the toolbar. + * + * @return the toolbar + */ + public GridToolbar getToolbar() { + return this.toolbar; + } + + /** + * Checks if is disposed. + * + * @return true, if is disposed + */ + public boolean isDisposed() { + return this.grid.getDataGrid().isDisposed(); + } + + /** + * Update grid data. + */ + public void updateGridData() { + grid.updateGridData(); + } + + /** + * Update grid status bar. + * + * @param summary the summary + */ + public void updateGridStatusBar(IQueryExecutionSummary summary) { + this.statusBar.updateDataProviderSummaryData(summary); + } + + /** + * Gets the search area. + * + * @return the search area + */ + public GridSearchAreaToDataGrid getSearchArea() { + if (this.gridSearchAreaToDataGrid == null) { + gridSearchAreaToDataGrid = new GridSearchAreaToDataGrid(this.searchArea); + } + return gridSearchAreaToDataGrid; + } + + /** + * Update. + * + * @param o the o + * @param arg the arg + */ + @Override + public void update(Observable o, Object arg) { + SQLSyntax syntax = null; + if (dataProvider != null && dataProvider.getDatabse() != null && dataProvider.getDatabse().isConnected()) { + syntax = dataProvider.getDatabse().getSqlSyntax(); + } + if (this.queryArea != null) { + this.queryArea.reconfigure(syntax); + } + } + + /** + * Gets the data grid. + * + * @return the data grid + */ + public DataGrid getDataGrid() { + return this.grid; + } + + /** + * Gets the data text. + * + * @return the data text + */ + public DataText getDataText() { + return this.text; + } + + /** + * Sets the commit status. + * + * @param commitStatus the new commit status + */ + public void setCommitStatus(CommitStatus commitStatus) { + + } + + /** + * Gets the selected encoding. + * + * @return the selected encoding + */ + public String getSelectedEncoding() { + return this.toolbar.getSelectedEncoding(); + } + + /** + * Update grid status bar for data text. + * + * @param partloaded the partloaded + * @param loadedRowCnt the loaded row cnt + */ + public void updateGridStatusBarForDataText(boolean partloaded, int loadedRowCnt) { + if (null != this.statusBar && uiPref.isNeedCreateTextMode()) { + this.statusBar.setEditableOrNonEditableStatusMessageForDataText(this.dataProvider, partloaded, + loadedRowCnt); + } + } + + /** + * Update grid status bar for data grid. + */ + public void updateGridStatusBarForDataGrid() { + if (null != this.statusBar && this.uiPref.isShowStatusBar()) { + this.statusBar.setEditableOrNonEditableStatusMessageForDataGrid(this.dataProvider); + } + } + + /** + * Show status bar. + */ + public void showStatusBar() { + if (null != this.statusBar && this.uiPref.isShowStatusBar()) { + this.statusBar.showStatusBar(); + } + } + + /** + * Hide status bar. + */ + public void hideStatusBar() { + if (null != this.statusBar && this.uiPref.isShowStatusBar()) { + this.statusBar.hideStatusBar(); + } + } + + /** + * Validate search option. + * + * @return true, if successful + */ + public boolean validateSearchOption() { + return getSearchArea().getCmbSearchOpt().getText().equals(SEARCHOPTIONS.SRCH_NULL.getDisplayName()); + } + + /** + * Gets the search txt string. + * + * @return the search txt string + */ + public String getSearchTxtString() { + return getSearchArea().getTxtSearchStr().getText(); + } + + /** + * Checks if is show grid or show text select. + * + * @return true, if is show grid or show text select + */ + public boolean isShowGridOrShowTextSelect() { + return getToolbar().isShowGridOrShowTextSelect(); + } + + /** + * Checks if is refresh but enable. + * + * @return true, if is refresh but enable + */ + public boolean isRefreshButEnable() { + return getToolbar().isRefreshButEnable(); + } + + /** + * Updata but status on load data text. + * + * @param boolValue the boolValue + */ + public void updataButStatusOnLoadDataText(boolean boolValue) { + getToolbar().updataButStatusOnLoadDataText(boolValue); + + } + + /** + * Gets the trigger search. + * + * @param string the string + * @param boolValue the boolValue + * @return the trigger search + */ + public void getTriggerSearch(String string, boolean boolValue) { + getSearchArea().getTriggerSearch(string, boolValue); + + } + + /** + * Sets the txt seatrch text. + * + * @param seleText the new txt seatrch text + */ + public void setTxtSeatrchText(String seleText) { + getSearchArea().getTxtSearchStr().setText(seleText); + + } + + /** + * Refresh data grid. + */ + public void refreshDataGrid() { + getDataGrid().closeEditor(); + getDataGrid().refresh(); + + } + + /** + * Gets the state machine. + * + * @return the state machine + */ + public DSGridStateMachine getStateMachine() { + return stateMachine; + } + + /** + * updateBatchDropButtons method + */ + public void updateBatchDropButtons() { + getToolbar().updateBatchDropStartButton(true); + getToolbar().updateBatchDropStopButton(false); + getToolbar().updateBatchDropAtomicButton(true); + getToolbar().updateBatchDropCascadeButton(true); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/DSGridMenuManager.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/DSGridMenuManager.java new file mode 100644 index 0000000000000000000000000000000000000000..2c6d4b995671165a53f794bd697b80ce95d25912 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/DSGridMenuManager.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.MenuItem; +import org.eclipse.swt.widgets.Text; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class DSGridMenuManager. + * + * @since 3.0.0 + */ +public class DSGridMenuManager { + + /** + * Adds the context menu with ID. + * + * @param editControl the edit control + * @param isCellEditable the is cell editable + */ + public static void addContextMenuWithID(final Text editControl, boolean isCellEditable) { + Menu menu = new Menu(editControl); + MenuItem copyItem = new MenuItem(menu, SWT.PUSH); + copyItem.setText(MessageConfigLoader.getProperty(IMessagesConstants.STATUS_MSG_PLVIEWER_OPTION_COPY)); + copyItem.addListener(SWT.Selection, new Listener() { + @Override + public void handleEvent(Event event) { + editControl.copy(); + + } + }); + if (isCellEditable) { + MenuItem pasteItem = new MenuItem(menu, SWT.PUSH); + pasteItem.setText(MessageConfigLoader.getProperty(IMessagesConstants.STATUS_MSG_PLVIEWER_OPTION_PASTE)); + pasteItem.addListener(SWT.Selection, new Listener() { + @Override + public void handleEvent(Event event) { + editControl.paste(); + } + }); + } + MenuItem selectAllItem = new MenuItem(menu, SWT.PUSH); + selectAllItem.setText(MessageConfigLoader.getProperty(IMessagesConstants.STATUS_MSG_PLVIEWER_OPTION_SELECTALL)); + selectAllItem.addListener(SWT.Selection, new Listener() { + @Override + public void handleEvent(Event event) { + editControl.selectAll(); + } + }); + editControl.setMenu(menu); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/DSGridToolTipProvider.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/DSGridToolTipProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..4e34bc2104b0a10667d76fcfba8e09ad9449e315 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/DSGridToolTipProvider.java @@ -0,0 +1,389 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import java.sql.Timestamp; +import java.sql.Types; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.eclipse.nebula.widgets.nattable.NatTable; +import org.eclipse.nebula.widgets.nattable.config.CellConfigAttributes; +import org.eclipse.nebula.widgets.nattable.config.ConfigRegistry; +import org.eclipse.nebula.widgets.nattable.data.ListDataProvider; +import org.eclipse.nebula.widgets.nattable.data.convert.DefaultDateDisplayConverter; +import org.eclipse.nebula.widgets.nattable.grid.GridRegion; +import org.eclipse.nebula.widgets.nattable.layer.LabelStack; +import org.eclipse.nebula.widgets.nattable.layer.cell.CellDisplayConversionUtils; +import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell; +import org.eclipse.nebula.widgets.nattable.style.DisplayMode; +import org.eclipse.nebula.widgets.nattable.tooltip.NatTableContentTooltip; +import org.eclipse.swt.widgets.Event; + +import org.opengauss.mppdbide.explainplan.ui.model.ExplainAnalyzePlanNodeTreeDisplayDataTreeFormat; +import org.opengauss.mppdbide.explainplan.ui.model.TreeGridColumnHeader; +import org.opengauss.mppdbide.presentation.edittabledata.DSResultSetGridDataRow; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableRecordExecutionStatus; +import org.opengauss.mppdbide.presentation.edittabledata.IDSGridEditDataRow; +import org.opengauss.mppdbide.presentation.grid.IDSEditGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnGroupProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.presentation.objectproperties.DSObjectPropertiesGridDataProvider; +import org.opengauss.mppdbide.utils.ConvertTimeStampValues; +import org.opengauss.mppdbide.utils.ConvertTimeValues; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.ui.table.UIUtils; +import org.opengauss.mppdbide.view.utils.DateFormatUtils; +import org.opengauss.mppdbide.view.utils.MaxSizeHelper; +import org.opengauss.mppdbide.view.utils.UserPreference; + +/** + * + * Title: class + * + * Description: The Class DSGridToolTipProvider. + * + * @since 3.0.0 + */ +public class DSGridToolTipProvider extends NatTableContentTooltip { + private ListDataProvider gridBodyDataProvider; + private static final String BIT_ONE = "1"; + private static final String BIT_ZERO = "0"; + private static final String BIT_DATATYPE = "bit"; + private boolean isEditSupported; + private IDataGridContext dataGridContext; + private static final int VARCHAR_DEF_SIZE = 2147483647; + private static final int CHAR_OR_BIT_DEF_SIZE = 1; + + /** + * Instantiates a new DS grid tool tip provider. + * + * @param gridTable the grid table + * @param tooltipRegions the tooltip regions + * @param dataGridContext the data grid context + * @param bodyDataProvider the body data provider + * @param isEditSupported the is edit supported + */ + public DSGridToolTipProvider(NatTable gridTable, String[] tooltipRegions, IDataGridContext dataGridContext, + ListDataProvider bodyDataProvider, boolean isEditSupported) { + super(gridTable, tooltipRegions); + this.dataGridContext = dataGridContext; + this.gridBodyDataProvider = bodyDataProvider; + this.isEditSupported = isEditSupported; + } + + /** + * Gets the text. + * + * @param event the event + * @return the text + */ + @Override + protected String getText(Event event) { + LabelStack labels = this.natTable.getRegionLabelsByXY(event.x, event.y); + + int col = this.natTable.getColumnPositionByX(event.x); + int rowPos = this.natTable.getRowPositionByY(event.y); + + ILayerCell cell = this.natTable.getCellByPosition(col, rowPos); + LabelStack cellLabels = this.natTable.getConfigLabelsByPosition(col, rowPos); + if (cell == null) { + return ""; + } + + if (null == labels) { + return ""; + } + + IDSGridDataProvider dataProvider = this.dataGridContext.getDataProvider(); + + if (dataProvider instanceof ExplainAnalyzePlanNodeTreeDisplayDataTreeFormat + && labels.hasLabel(GridRegion.BODY)) { + return getExplainAnalyzePlanTooltip(cell, cellLabels); + } else if (labels.hasLabel(GridRegion.BODY)) { + return getTextForLabelHavingBody(cell, dataProvider); + } else if (labels.hasLabel(GridRegion.ROW_HEADER)) { + int row = this.natTable.getRowIndexByPosition(rowPos); + IDSGridEditDataRow editedRow = getCurrRow(row); + if (null != editedRow && editedRow.getExecutionStatus() == EditTableRecordExecutionStatus.FAILED) { + return editedRow.getCommitStatusMessage(); + } + } else if (labels.hasLabel(GridRegion.COLUMN_GROUP_HEADER)) { + return getTextForLabelHavingColumnGroupHeader(cell, dataProvider); + } else if (labels.hasLabel(GridRegion.COLUMN_HEADER)) { + return getColumnHeaderToolTip(cell); + } + + return ""; + } + + private String getTextForLabelHavingColumnGroupHeader(ILayerCell cell, IDSGridDataProvider dataProvider) { + IDSGridColumnGroupProvider columnGroupProvider = dataProvider.getColumnGroupProvider(); + String columnGroupName = ""; + if (columnGroupProvider != null) { + columnGroupName = columnGroupProvider + .getColumnGroupName(columnGroupProvider.getColumnGroupIndex(cell.getColumnIndex())); + } + return columnGroupName; + } + + private String getTextForLabelHavingBody(ILayerCell cell, IDSGridDataProvider dataProvider) { + // Pass empty configregistry to avoid search markup html tags. + String convertedDataType = CellDisplayConversionUtils.convertDataType(cell, getToolTipConfigRegistry()); + String columnDataType = dataProvider.getColumnDataProvider().getColumnDataTypeName(cell.getColumnIndex()); + + if (MPPDBIDEConstants.BLOB.equalsIgnoreCase(columnDataType) && !convertedDataType.isEmpty()) { + return MPPDBIDEConstants.BLOB_WATERMARK; + } + Object cellValue = cell.getDataValue(); + int dataType = dataProvider.getColumnDataProvider().getColumnDatatype(cell.getColumnIndex()); + if (Types.TIMESTAMP == dataType || Types.TIMESTAMP_WITH_TIMEZONE == dataType || Types.TIME == dataType + || Types.TIME_WITH_TIMEZONE == dataType) { + return handleTimeStampValues(cell, dataProvider, cellValue); + } + + if (cellValue != null && cellValue instanceof List) { + List cellValueObject = (List) cellValue; + if (cellValueObject.get(0) instanceof DSResultSetGridDataRow) { + return MessageConfigLoader.getProperty(IMessagesConstants.CURSOR_TOOLTIP_TEXT); + } + } + if (MPPDBIDEConstants.RETURN_VOID.equals(cellValue)) { + return MessageConfigLoader.getProperty(IMessagesConstants.VOID_VALUE_TOOLTIP_TEXT); + } + if (cell.getRowPosition() > 0 && !dataProvider.getAllFetchedRows().isEmpty() + && cell.getRowPosition() - 1 < dataProvider.getAllFetchedRows().size() + && dataProvider.getAllFetchedRows().get(cell.getRowPosition() - 1) != null) { + Object[] row = dataProvider.getAllFetchedRows().get(cell.getRowPosition() - 1).getValues(); + if (cell.getColumnPosition() > 1 && cell.getColumnPosition() - 2 < row.length + && "IN".equals(row[cell.getColumnPosition() - 2])) { + return row[cell.getColumnPosition() - 1].toString(); + } + } + return getToolTipForLabelAsBody(convertedDataType, columnDataType); + } + + private String handleTimeStampValues(ILayerCell cell, IDSGridDataProvider dataProvider, Object cellValue) { + if (Types.TIMESTAMP == dataProvider.getColumnDataProvider().getColumnDatatype(cell.getColumnIndex()) + || Types.TIMESTAMP_WITH_TIMEZONE == dataProvider.getColumnDataProvider() + .getColumnDatatype(cell.getColumnIndex())) { + if (cellValue != null && cellValue instanceof ConvertTimeStampValues) { + return cellValue.toString(); + } + } + if (Types.TIME == dataProvider.getColumnDataProvider().getColumnDatatype(cell.getColumnIndex()) + || Types.TIME_WITH_TIMEZONE == dataProvider.getColumnDataProvider() + .getColumnDatatype(cell.getColumnIndex())) { + if (cellValue != null && cellValue instanceof ConvertTimeValues) { + return cellValue.toString(); + } + } + return ""; + } + + private String getToolTipForLabelAsBody(String convertedDataType, String columnDataType) { + if (MPPDBIDEConstants.BLOB.equalsIgnoreCase(columnDataType) && !convertedDataType.isEmpty()) { + return MPPDBIDEConstants.BLOB_WATERMARK; + } else if (MPPDBIDEConstants.BYTEA.equalsIgnoreCase(columnDataType) && !convertedDataType.isEmpty()) { + return MPPDBIDEConstants.BYTEA_WATERMARK; + } else { + return getConvertedColumnData(convertedDataType, columnDataType); + } + } + + private String getExplainAnalyzePlanTooltip(ILayerCell cell, LabelStack cellLabels) { + String tooltip = ""; + if (cellLabels != null && cellLabels.hasLabel(TreeGridColumnHeader.COLUMN_LABEL_HEAVIEST)) { + tooltip = MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_ANALYSIS_HEAVIEST); + return tooltip; + } + if (cellLabels != null && cellLabels.hasLabel(TreeGridColumnHeader.COLUMN_LABEL_COSTLIEST)) { + tooltip = MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_ANALYSIS_COSTLIEST); + return tooltip; + } + if (cellLabels != null && cellLabels.hasLabel(TreeGridColumnHeader.COLUMN_LABEL_SLOWEST)) { + tooltip = MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_ANALYSIS_SLOWEST); + return tooltip; + } + Object dataValue = cell.getDataValue(); + if (dataValue == null) { + return ""; + } + return dataValue.toString(); + } + + private String getColumnHeaderToolTip(ILayerCell cell) { + IDSGridDataProvider dataProvider = this.dataGridContext.getDataProvider(); + IDSGridColumnProvider columnDataProvider = dataProvider.getColumnDataProvider(); + String toolTipText = getTooltipText(cell, columnDataProvider); + if (isEditSupported) { + String colDatatypeName = columnDataProvider + + .getColumnDataTypeName(cell.getColumnIndex()); + + int colPrecisionVal = columnDataProvider.getPrecision(cell.getColumnIndex()); + if (dataProvider instanceof IDSEditGridDataProvider + && ((IDSEditGridDataProvider) dataProvider).isDistributionColumn(cell.getColumnIndex())) { + return toolTipText + MessageConfigLoader.getProperty(IMessagesConstants.TOOLTIP_DISTRIBUTION_COL); + } else if (dataProvider instanceof DSObjectPropertiesGridDataProvider) { + return toolTipText; + } else if (!GridUIUtils.isDatatypeEditSupported(colDatatypeName, colPrecisionVal)) { + return toolTipText + MessageConfigLoader.getProperty(IMessagesConstants.TOOLTIP_READONLY_COL); + } + } + + return toolTipText; + } + + private String getTooltipText(ILayerCell cell, IDSGridColumnProvider columnDataProvider) { + String toolTipText = null; + String datatype = UIUtils + .convertToDisplayDatatype(columnDataProvider.getColumnDataTypeName(cell.getColumnIndex())); + if (datatype.isEmpty()) { + toolTipText = columnDataProvider.getColumnName(cell.getColumnIndex()); + } else { + toolTipText = columnDataProvider.getColumnName(cell.getColumnIndex()) + ": " + datatype; + } + int precision = columnDataProvider.getPrecision(cell.getColumnIndex()); + int scale = columnDataProvider.getScale(cell.getColumnIndex()); + int maxLength = columnDataProvider.getMaxLength(cell.getColumnIndex()); + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append(toolTipText); + if ("VARCHAR".equals(UIUtils.getDatatypeFamilyForTooltip(datatype)) && maxLength > 0 + && maxLength != VARCHAR_DEF_SIZE) { + sb.append('(').append(maxLength).append(')'); + } else if (isCharOrBitStringTooltip(datatype, maxLength)) { + sb.append('(').append(maxLength).append(')'); + } else if ("NUMERIC".equals(UIUtils.getDatatypeFamilyForTooltip(datatype)) && precision > 0) { + sb.append('(').append(precision); + if (scale > 0) { + sb.append(',').append(scale); + } + sb.append(')'); + } + + String columnComment = columnDataProvider.getColumnComment(cell.getColumnIndex()); + if (StringUtils.isNotEmpty(columnComment)) { + sb.append(MPPDBIDEConstants.NEW_LINE_SIGN).append(columnComment); + } + + toolTipText = sb.toString(); + return toolTipText; + } + + private boolean isCharOrBitStringTooltip(String datatype, int maxLength) { + return ("CHAR".equals(UIUtils.getDatatypeFamilyForTooltip(datatype)) + || "BITSTRING".equals(UIUtils.getDatatypeFamilyForTooltip(datatype))) && maxLength > 0 + && maxLength != CHAR_OR_BIT_DEF_SIZE; + } + + private String getConvertedColumnData(String convertedDataType, String columnDataType) { + if (BIT_DATATYPE.equals(columnDataType)) { + if (Boolean.toString(true).equalsIgnoreCase(convertedDataType)) { + return BIT_ONE; + } else if (Boolean.toString(false).equalsIgnoreCase(convertedDataType)) { + return BIT_ZERO; + } + } + return MaxSizeHelper.trimTextToLimitEndWithDots(convertedDataType); + } + + private ConfigRegistry getToolTipConfigRegistry() { + ConfigRegistry config = new ConfigRegistry(); + + config.registerConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER, + new DefaultDateDisplayConverter(ITableGridStyleLabelFactory.COMMON_GRID_TIME_FORMAT), + DisplayMode.NORMAL, ITableGridStyleLabelFactory.COL_LABEL_TIME_DATATYPE); + + config.registerConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER, + new DefaultDateDisplayConverter(ITableGridStyleLabelFactory.COMMON_GRID_DATE_FORMAT), + DisplayMode.NORMAL, ITableGridStyleLabelFactory.COL_LABEL_DATE_DATATYPE); + + config.registerConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER, + new DefaultDateDisplayConverter(ITableGridStyleLabelFactory.COMMON_GRID_DATE_FORMAT), + DisplayMode.NORMAL, ITableGridStyleLabelFactory.COL_LABEL_TIME_WITHTIMEZONE); + + return config; + } + + private IDSGridEditDataRow getCurrRow(int rowIdx) { + if (dataGridContext.getDataProvider() instanceof IDSEditGridDataProvider) { + IDSGridDataRow currRow = this.gridBodyDataProvider.getRowObject(rowIdx); + if (currRow instanceof IDSGridEditDataRow) { + return (IDSGridEditDataRow) currRow; + } + } + + return null; + } + + /** + * Should create tool tip. + * + * @param event the event + * @return true, if successful + */ + @Override + protected boolean shouldCreateToolTip(Event event) { + if (super.shouldCreateToolTip(event)) { + return true; + } + + LabelStack labels = this.natTable.getRegionLabelsByXY(event.x, event.y); + + if (null != labels && labels.hasLabel(GridRegion.ROW_HEADER)) { + if (dataGridContext.getDataProvider() instanceof IDSEditGridDataProvider) { + int rowPos = this.natTable.getRowPositionByY(event.y); + int row = this.natTable.getRowIndexByPosition(rowPos); + + if (row < 0) { + // This condition is not supposed to be failed. + return false; + } + + IDSGridEditDataRow editedRow = getCurrRow(row); + if (editedRow != null && editedRow.getExecutionStatus() == EditTableRecordExecutionStatus.FAILED) { + return true; + } + } + } + + return false; + } + + /** + * Sets the body data provider. + * + * @param bodyDataProvider the new body data provider + */ + public void setBodyDataProvider(ListDataProvider bodyDataProvider) { + this.gridBodyDataProvider = bodyDataProvider; + } + + /** + * On pre destroy. + */ + public void onPreDestroy() { + this.dataGridContext = null; + this.gridBodyDataProvider = null; + this.natTable = null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/DSHTMLAwareRegexMarkupValue.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/DSHTMLAwareRegexMarkupValue.java new file mode 100644 index 0000000000000000000000000000000000000000..9172c9d332cded7ad4a3bb132e62029173bdab86 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/DSHTMLAwareRegexMarkupValue.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import java.io.StringReader; +import java.util.regex.Pattern; + +import javax.xml.stream.XMLEventReader; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.events.Characters; +import javax.xml.stream.events.XMLEvent; + +import org.apache.commons.lang.StringEscapeUtils; +import org.eclipse.nebula.widgets.nattable.extension.nebula.richtext.RegexMarkupValue; +import org.eclipse.nebula.widgets.richtext.RichTextPainter; + +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class DSHTMLAwareRegexMarkupValue. + * + * @since 3.0.0 + */ +public class DSHTMLAwareRegexMarkupValue extends RegexMarkupValue { + private static final String GROUP_INDEX_PLACEHOLDER = "$1"; + private XMLInputFactory factory = XMLInputFactory.newInstance(); + private String markupValue; + + /** + * Instantiates a new DSHTML aware regex markup value. + * + * @param value the value + * @param markupPrefix the markup prefix + * @param markupSuffix the markup suffix + */ + public DSHTMLAwareRegexMarkupValue(String value, String markupPrefix, String markupSuffix) { + super(value, markupPrefix, markupSuffix); + this.markupValue = markupPrefix + GROUP_INDEX_PLACEHOLDER + markupSuffix; + } + + /** + * Apply markup. + * + * @param input the input + * @return the string + */ + @Override + public String applyMarkup(String input) { + String result = ""; + StringBuffer resultBuf = new StringBuffer(); + if (getOriginalRegexValue() != null && !getOriginalRegexValue().isEmpty()) { + XMLEventReader parser = null; + XMLEvent event = null; + try { + parser = this.factory.createXMLEventReader(new StringReader( + RichTextPainter.FAKE_ROOT_TAG_START + input + RichTextPainter.FAKE_ROOT_TAG_END)); + if (parser != null) { + boolean hasNext = parser.hasNext(); + while (hasNext) { + event = parser.nextEvent(); + + applyMarkup1(resultBuf, event); + hasNext = parser.hasNext(); + } + // To highlight the search + replaceWithMarkUpValue(resultBuf); + } + } catch (XMLStreamException exception) { + // Not expected to come here. Need to ignore. + MPPDBIDELoggerUtility.error("HTML parser error while printing data in grid", exception); + } finally { + if (parser != null) { + try { + parser.close(); + } catch (XMLStreamException exception) { + MPPDBIDELoggerUtility.error("HTML parser error while closing in grid", exception); + } + } + } + + result = resultBuf.toString().replace(RichTextPainter.FAKE_ROOT_TAG_START, "") + .replace(RichTextPainter.FAKE_ROOT_TAG_END, ""); + } else { + result = input; + } + return result; + } + + private void applyMarkup1(StringBuffer resultBuf, XMLEvent event) { + switch (event.getEventType()) { + case XMLStreamConstants.CHARACTERS: { + Characters characters = event.asCharacters(); + String text = characters != null ? StringEscapeUtils.escapeHtml(characters.getData()) : ""; + resultBuf.append(text); + break; + } + case XMLStreamConstants.START_DOCUMENT: { + break; + } + case XMLStreamConstants.END_DOCUMENT: { + break; + } + default: { + resultBuf.append(event.toString()); + } + } + } + + private void replaceWithMarkUpValue(StringBuffer resultBuf) { + String replaceResultBuf = resultBuf.toString(); + replaceResultBuf = replaceResultBuf.replace("", ""); + replaceResultBuf = replaceResultBuf.replace("", ""); + Pattern regexValuePattern = Pattern.compile(getOriginalRegexValue(), Pattern.CASE_INSENSITIVE); + java.util.regex.Matcher regexValueMatcher = regexValuePattern.matcher(replaceResultBuf); + + if (regexValueMatcher.find()) { + resultBuf.setLength(0); + replaceResultBuf = replaceResultBuf.replaceAll(getOriginalRegexValue(), this.markupValue); + resultBuf.append("").append(replaceResultBuf).append(""); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/DSHtmlEscapedMarkupDisplayConverter.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/DSHtmlEscapedMarkupDisplayConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..eb8c76b328de8a91d7a249d4e2a8224b14e02d41 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/DSHtmlEscapedMarkupDisplayConverter.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import java.math.BigDecimal; +import java.sql.Types; +import java.util.List; + +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.commons.lang.StringUtils; +import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry; +import org.eclipse.nebula.widgets.nattable.extension.nebula.richtext.MarkupDisplayConverter; +import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell; + +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.DBTYPE; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.objectproperties.DSObjectPropertiesGridDataProvider; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.view.component.IGridUIPreference; +import org.opengauss.mppdbide.view.utils.MaxSizeHelper; + +/** + * + * Title: class + * + * Description: The Class DSHtmlEscapedMarkupDisplayConverter. + * + * @since 3.0.0 + */ +public class DSHtmlEscapedMarkupDisplayConverter extends MarkupDisplayConverter { + private IGridUIPreference uiPref; + private IDataGridContext dataGridContext; + + /** + * Instantiates a new DS html escaped markup display converter. + * + * @param uiPref the ui pref + * @param dataGridContext the data grid context + */ + public DSHtmlEscapedMarkupDisplayConverter(IGridUIPreference uiPref, IDataGridContext dataGridContext) { + this.uiPref = uiPref; + this.dataGridContext = dataGridContext; + } + + /** + * Canonical to display value. + * + * @param cell the cell + * @param configRegistry the config registry + * @param canonicalValueParam the canonical value param + * @return the object + */ + @Override + public Object canonicalToDisplayValue(ILayerCell cell, IConfigRegistry configRegistry, Object canonicalValueParam) { + Object canonicalValue = canonicalValueParam; + IDSGridDataProvider dataProvider = dataGridContext.getDataProvider(); + + if (Types.OTHER == dataProvider.getColumnDataProvider() + .getColumnDatatype(dataProvider.getColumnDataProvider().getColumnCount() - 1) + && canonicalValueParam != null && canonicalValue instanceof List) { + return MPPDBIDEConstants.CURSOR_WATERMARK; + + } + + if (MPPDBIDEConstants.BLOB + .equalsIgnoreCase(dataProvider.getColumnDataProvider().getColumnDataTypeName(cell.getColumnIndex())) + && canonicalValueParam != null) { + return MPPDBIDEConstants.BLOB_WATERMARK; + } + if (MPPDBIDEConstants.BYTEA + .equalsIgnoreCase(dataProvider.getColumnDataProvider().getColumnDataTypeName(cell.getColumnIndex())) + && canonicalValueParam != null) { + return MPPDBIDEConstants.BYTEA_WATERMARK; + } + + if (dataProvider instanceof DSObjectPropertiesGridDataProvider && canonicalValue == null) { + return this.uiPref.getNULLValueText(); + } + + else if (null == canonicalValue) { + return handleNullCanonicalValue(cell, dataProvider); + } else { + // If we convert the Bigdecimal value to String while adding to + // Dataprovider, it consumes more memory and leads to performance + // issue. So, now we are converting to String while display instead + // while setting to Dataprovider + if ("NUMERIC".equalsIgnoreCase( + dataProvider.getColumnDataProvider().getColumnDataTypeName(cell.getColumnIndex()))) { + canonicalValue = ((BigDecimal) canonicalValue).toPlainString(); + } + String value = StringEscapeUtils.escapeHtml(String.valueOf(canonicalValue)); + value = value.replaceAll("[\\s\\x00]+$", ""); + return super.canonicalToDisplayValue(cell, configRegistry, MaxSizeHelper.trimTextToLimitEndWithDots(value)); + } + } + + private Object handleNullCanonicalValue(ILayerCell cell, IDSGridDataProvider dataProvider) { + if (cell.getRowPosition() > 0 && !dataProvider.getAllFetchedRows().isEmpty() + && cell.getRowPosition() - 1 < dataProvider.getAllFetchedRows().size() + && dataProvider.getAllFetchedRows().get(cell.getRowPosition() - 1) != null) { + Object[] row = dataProvider.getAllFetchedRows().get(cell.getRowPosition() - 1).getValues(); + if (cell.getColumnPosition() > 1 && ("IN").equals(row[cell.getColumnPosition() - 2])) { + return row[cell.getColumnPosition() - 1]; + } + } else if (dataProvider.getDatabse() != null && dataProvider.getDatabse().getDBType() == DBTYPE.OPENGAUSS) { + List columnMetaDataList = dataGridContext.getColumnMetaDataList(); + if (columnMetaDataList != null && columnMetaDataList.size() > 0 + && columnMetaDataList.get(cell.getColumnIndex()).getHasDefVal()) { + return this.uiPref.getDefaultValueText(); + } + } else if (!StringUtils.isEmpty(dataProvider.getColumnDataProvider().getDefaultValue(cell.getColumnIndex()))) { + return this.uiPref.getDefaultValueText(); + } + return this.uiPref.getNULLValueText(); + } + + /** + * Display to canonical value. + * + * @param cell the cell + * @param configRegistry the config registry + * @param displayValue the display value + * @return the object + */ + @Override + public Object displayToCanonicalValue(ILayerCell cell, IConfigRegistry configRegistry, Object displayValue) { + if ("".equals(displayValue)) { + return ""; + } + + if (this.uiPref.getNULLValueText().equals(displayValue)) { + return null; + } else { + String value = StringEscapeUtils.unescapeHtml(String.valueOf(displayValue)); + return super.displayToCanonicalValue(cell, configRegistry, value); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/DSdefaultBooleanDisplayConverter.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/DSdefaultBooleanDisplayConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..9779cb9926065d18c09f5488fac22a556b8fd55c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/DSdefaultBooleanDisplayConverter.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry; +import org.eclipse.nebula.widgets.nattable.data.convert.DefaultBooleanDisplayConverter; +import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell; + +/** + * + * Title: class + * + * Description: The Class DSdefaultBooleanDisplayConverter. + * + * @since 3.0.0 + */ +public class DSdefaultBooleanDisplayConverter extends DefaultBooleanDisplayConverter { + + private static final String BIT_ONE = "1"; + private static final String BIT_ZERO = "0"; + private static final String BOOLEAN_TRUE = "true"; + private static final String BOOLEAN_FALSE = "false"; + + /** + * Canonical to display value. + * + * @param cell the cell + * @param configRegistry the config registry + * @param canonicalValue the canonical value + * @return the object + */ + @Override + public Object canonicalToDisplayValue(ILayerCell cell, IConfigRegistry configRegistry, Object canonicalValue) { + + if (canonicalValue == null) { + return null; + } else { + if (BIT_ONE.equals(canonicalValue) || BOOLEAN_TRUE.equals(canonicalValue)) { + return true; + } + if (BIT_ZERO.equals(canonicalValue) || BOOLEAN_FALSE.equals(canonicalValue)) { + return false; + } + return canonicalValue.toString(); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/EditTableGridStyleConfiguration.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/EditTableGridStyleConfiguration.java new file mode 100644 index 0000000000000000000000000000000000000000..2e7789fead46a2c813bff8f51922a770daebbc44 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/EditTableGridStyleConfiguration.java @@ -0,0 +1,575 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import java.sql.Types; + +import org.eclipse.nebula.widgets.cdatetime.CDT; +import org.eclipse.nebula.widgets.nattable.config.AbstractRegistryConfiguration; +import org.eclipse.nebula.widgets.nattable.config.CellConfigAttributes; +import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry; +import org.eclipse.nebula.widgets.nattable.config.IEditableRule; +import org.eclipse.nebula.widgets.nattable.edit.EditConfigAttributes; +import org.eclipse.nebula.widgets.nattable.edit.editor.CheckBoxCellEditor; +import org.eclipse.nebula.widgets.nattable.extension.nebula.cdatetime.CDateTimeCellEditor; +import org.eclipse.nebula.widgets.nattable.grid.GridRegion; +import org.eclipse.nebula.widgets.nattable.layer.cell.ColumnOverrideLabelAccumulator; +import org.eclipse.nebula.widgets.nattable.layer.config.DefaultColumnHeaderStyleConfiguration; +import org.eclipse.nebula.widgets.nattable.painter.cell.CheckBoxPainter; +import org.eclipse.nebula.widgets.nattable.painter.cell.ImagePainter; +import org.eclipse.nebula.widgets.nattable.painter.cell.decorator.CellPainterDecorator; +import org.eclipse.nebula.widgets.nattable.style.CellStyleAttributes; +import org.eclipse.nebula.widgets.nattable.style.DisplayMode; +import org.eclipse.nebula.widgets.nattable.style.IStyle; +import org.eclipse.nebula.widgets.nattable.style.Style; +import org.eclipse.nebula.widgets.nattable.ui.util.CellEdgeEnum; +import org.eclipse.nebula.widgets.nattable.util.GUIHelper; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Display; + +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.objectproperties.DSObjectPropertiesGridColumnDataProvider; +import org.opengauss.mppdbide.presentation.objectproperties.DSObjectPropertiesGridDataProvider; +import org.opengauss.mppdbide.presentation.objectproperties.PropertiesConstants; +import org.opengauss.mppdbide.presentation.objectproperties.PropertiesUserRoleImpl; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.component.IGridUIPreference; +import org.opengauss.mppdbide.view.component.grid.core.DSAbstractRegistryConfiguration; +import org.opengauss.mppdbide.view.component.grid.core.DSBlobCellEditor; +import org.opengauss.mppdbide.view.component.grid.core.DSCursorResultSetTable; +import org.opengauss.mppdbide.view.component.grid.core.DSByteACellEditor; +import org.opengauss.mppdbide.view.component.grid.core.DSTextCellEditor; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; + +/** + * + * Title: class + * + * Description: The Class EditTableGridStyleConfiguration. + * + * @since 3.0.0 + */ +public class EditTableGridStyleConfiguration extends AbstractRegistryConfiguration + implements IEditTableGridStyleLabelFactory { + private static final String COL_LABEL_TIMESTAMP = "TIMESTAMP"; + + /** + * Configure registry. + * + * @param configRegistry the config registry + */ + @Override + public void configureRegistry(IConfigRegistry configRegistry) { + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, IEditableRule.ALWAYS_EDITABLE, + DisplayMode.NORMAL); + + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, IEditableRule.NEVER_EDITABLE, + DisplayMode.NORMAL, COL_LABEL_READONLY_CELL); + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, IEditableRule.ALWAYS_EDITABLE, + DisplayMode.NORMAL, COL_LABEL_COPY_READONLY_CELL); + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, IEditableRule.NEVER_EDITABLE, + DisplayMode.NORMAL, GridRegion.ROW_HEADER); + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, IEditableRule.NEVER_EDITABLE, + DisplayMode.NORMAL, GridRegion.COLUMN_HEADER); + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, IEditableRule.NEVER_EDITABLE, + DisplayMode.NORMAL, GridRegion.COLUMN_GROUP_HEADER); + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, IEditableRule.NEVER_EDITABLE, + DisplayMode.NORMAL, GridRegion.ROW_GROUP_HEADER); + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, IEditableRule.NEVER_EDITABLE, + DisplayMode.NORMAL, GridRegion.CORNER); + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, IEditableRule.ALWAYS_EDITABLE, + DisplayMode.NORMAL, ITableGridStyleLabelFactory.COL_LABEL_TIME_WITHTIMEZONE); + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, IEditableRule.ALWAYS_EDITABLE, + DisplayMode.NORMAL, ITableGridStyleLabelFactory.COL_LABEL_DATE_DATATYPE); + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, IEditableRule.ALWAYS_EDITABLE, + DisplayMode.NORMAL, ITableGridStyleLabelFactory.COL_LABEL_TIME_DATATYPE); + + cellLabelConfigUration(configRegistry); + applyRowHeaderStyles(configRegistry); + } + + private void cellLabelConfigUration(IConfigRegistry configRegistry) { + applyCellStyle(configRegistry, GUIHelper.COLOR_GREEN, COL_LABEL_INSERT, DisplayMode.NORMAL); + applyCellStyle(configRegistry, GUIHelper.COLOR_GRAY, COL_LABEL_DELETE, DisplayMode.NORMAL); + applyCellStyle(configRegistry, GUIHelper.COLOR_GREEN, COL_LABEL_UPDATE, DisplayMode.NORMAL); + applyCellStyle(configRegistry, GUIHelper.COLOR_GREEN, COL_LABEL_FAILED_AND_MODIFIED, DisplayMode.NORMAL); + applyCellStyle(configRegistry, GUIHelper.COLOR_GREEN, COL_LABEL_INSERT, DisplayMode.SELECT); + applyCellStyle(configRegistry, GUIHelper.COLOR_GRAY, COL_LABEL_DELETE, DisplayMode.SELECT); + applyCellStyle(configRegistry, GUIHelper.COLOR_GREEN, COL_LABEL_UPDATE, DisplayMode.SELECT); + applyCellStyle(configRegistry, GUIHelper.COLOR_GREEN, COL_LABEL_FAILED_AND_MODIFIED, DisplayMode.SELECT); + + applyCellStyle(configRegistry, GUIHelper.COLOR_RED, COL_LABEL_CHANGE_FAILED, DisplayMode.NORMAL); + applyCellStyle(configRegistry, GUIHelper.COLOR_RED, COL_LABEL_CHANGE_FAILED, DisplayMode.SELECT); + applyCellStyle(configRegistry, GUIHelper.COLOR_DARK_GRAY, COL_LABEL_OUT_PARA_TYPE_CELL, DisplayMode.NORMAL); + applyCellStyle(configRegistry, GUIHelper.COLOR_DARK_GRAY, COL_LABEL_OUT_PARA_TYPE_CELL, DisplayMode.SELECT); + + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, IEditableRule.ALWAYS_EDITABLE, + DisplayMode.NORMAL, COL_LABEL_EDIT_INSERTED_DISTRIBUTABLE_COLUMN); + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, IEditableRule.ALWAYS_EDITABLE, + DisplayMode.NORMAL, COL_LABEL_CUSTOM_DIALOG); + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, IEditableRule.ALWAYS_EDITABLE, + DisplayMode.NORMAL, COL_LABEL_CUSTOM_DIALOG_REFERENCING_TABLE); + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, IEditableRule.ALWAYS_EDITABLE, + DisplayMode.NORMAL, COL_LABEL_CUSTOM_CLMS_DIALOG); + } + + private void applyRowHeaderStyles(IConfigRegistry configRegistry) { + GridEditColumnHeaderStyleConfig editColumnHeaderStyleConfig = new GridEditColumnHeaderStyleConfig(); + editColumnHeaderStyleConfig.configureRegistry(configRegistry); + } + + private void applyCellStyle(IConfigRegistry configRegistry, Color color, String cellLabel, String displayMode) { + /* + * registerConfigAttribute accepts 1. attribute to apply 2. value of the + * attribute 3. apply during normal rendering i.e not during selection + * or edit 4. apply the above for all cells with this label + */ + Style style = new Style(); + style.setAttributeValue(CellStyleAttributes.BACKGROUND_COLOR, color); + configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, style, displayMode, cellLabel); + + applyCellStyleForEditableCells(configRegistry, GUIHelper.COLOR_GRAY, COL_LABEL_NULL_VALUES, DisplayMode.SELECT); + applyCellStyleForEditableCells(configRegistry, GUIHelper.COLOR_BLACK, COL_LABEL_NULL_VALUES, DisplayMode.EDIT); + + } + + private void applyCellStyleForEditableCells(IConfigRegistry configRegistry, Color color, String cellLabel, + String displayMode) { + Style nullStyle = new Style(); + nullStyle.setAttributeValue(CellStyleAttributes.FOREGROUND_COLOR, color); + configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, nullStyle, displayMode, cellLabel); + + Style nullStyleForEditMode = new Style(); + nullStyleForEditMode.setAttributeValue(CellStyleAttributes.FOREGROUND_COLOR, color); + configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, nullStyleForEditMode, displayMode, + cellLabel); + } + + /** + * Date edit configuration. + * + * @param configRegistry the config registry + */ + public static void dateEditConfiguration(IConfigRegistry configRegistry) { + + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, + new CDateTimeCellEditor(false, DROP_DOWN | DATE_SHORT), DisplayMode.EDIT, + ITableGridStyleLabelFactory.COL_LABEL_DATE_DATATYPE); + + } + + /** + * Edits the date configuration. + * + * @param configRegistry the config registry + */ + public static void editDateConfiguration(IConfigRegistry configRegistry) { + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, + new CDateTimeCellEditor(false, DROP_DOWN | DATE_SHORT), DisplayMode.EDIT, COL_LABEL_TIMESTAMP); + } + + /** + * Check box registry. + * + * @param configRegistry the config registry + */ + public static void checkBoxRegistry(IConfigRegistry configRegistry) { + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, new CheckBoxCellEditor(), + DisplayMode.EDIT, COL_LABEL_BOOLEAN_DATATYPE); + configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, new CheckBoxPainter(), + DisplayMode.NORMAL, COL_LABEL_BOOLEAN_DATATYPE); + configRegistry.registerConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER, + new DSdefaultBooleanDisplayConverter(), DisplayMode.NORMAL, COL_LABEL_BOOLEAN_DATATYPE); + configRegistry.registerConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER, + new DSdefaultBooleanDisplayConverter(), DisplayMode.EDIT, COL_LABEL_BOOLEAN_DATATYPE); + + } + + /** + * Date and time configuration. + * + * @param configRegistry the config registry + */ + public static void dateAndTimeConfiguration(IConfigRegistry configRegistry) { + /* + * Date time Column to use default pattern of the client system. And use + * Calendar + Clock for edit + */ + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, + new DSCDateTimeCellEditor(true, CDT.DROP_DOWN | CDT.DATE_SHORT | CDT.TIME_MEDIUM), DisplayMode.EDIT, + ITableGridStyleLabelFactory.COL_LABEL_TIME_WITHTIMEZONE); + + /* + * Date time Column to use default date pattern of the client system. + * And use Calendar for edit + */ + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, + new DSCDateTimeCellEditor(true, CDT.DROP_DOWN | CDT.DATE_SHORT), DisplayMode.EDIT, + ITableGridStyleLabelFactory.COL_LABEL_DATE_DATATYPE); + + /* + * Date time Column to use default time pattern of the client system. + * And use Number based time editor. + */ + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, + new DSCDateTimeCellEditor(true, CDT.DROP_DOWN | CDT.TIME_MEDIUM), DisplayMode.EDIT, + ITableGridStyleLabelFactory.COL_LABEL_TIME_DATATYPE); + + } + + /** + * Gets the datatype column accumulator. + * + * @param columnLabelAccumulator the column label accumulator + * @param dataGridContext the data grid context + * @param uiPref the ui pref + * @return the datatype column accumulator + */ + public static DSAbstractRegistryConfiguration getDatatypeColumnAccumulator( + final ColumnOverrideLabelAccumulator columnLabelAccumulator, final IDataGridContext dataGridContext, + IGridUIPreference uiPref) { + return new RegistryConfiguration(columnLabelAccumulator, dataGridContext, uiPref); + } + + /** + * + * Title: class + * + * Description: The Class GridEditColumnHeaderStyleConfig. + */ + private static class GridEditColumnHeaderStyleConfig extends DefaultColumnHeaderStyleConfiguration { + @Override + public void configureRegistry(IConfigRegistry configRegistry) { + super.configureRegistry(configRegistry); + Image myImage = IconUtility.getIconSmallImage(IconUtility.ICON_COLUMN_EDIT_LOCK, getClass()); + ImagePainter decoratorImagePainter = new ImagePainter(myImage); + CellPainterDecorator painter = new CellPainterDecorator(this.cellPainter, CellEdgeEnum.LEFT, 100, + decoratorImagePainter, false, true); + + configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, painter, DisplayMode.NORMAL, + IEditTableGridStyleLabelFactory.COL_HEADER_LABEL_READONLY_CELL); + } + } + + /** + * + * Title: class + * + * Description: The Class RegistryConfiguration. + */ + private static final class RegistryConfiguration extends DSAbstractRegistryConfiguration { + + private static final String IS_NULLABLE = MessageConfigLoader + .getProperty(IMessagesConstants.PROPERTIES_COLUMNS_ISNULLABLE); + private static final String DATA_TYPE = MessageConfigLoader + .getProperty(IMessagesConstants.PROPERTIES_COLUMNS_DATATYPE); + private IDataGridContext dataGridContext; + private ColumnOverrideLabelAccumulator columnLabelAccumulator; + private IGridUIPreference uiPref; + + private RegistryConfiguration(ColumnOverrideLabelAccumulator columnLabelAccumulator, + IDataGridContext dataGridContext, IGridUIPreference uiPref) { + this.columnLabelAccumulator = columnLabelAccumulator; + this.dataGridContext = dataGridContext; + this.uiPref = uiPref; + } + + @Override + public void configureRegistry(IConfigRegistry configRegistry) { + + IDSGridDataProvider dataProvider = dataGridContext.getDataProvider(); + registerConfigLabelsOnColumns(columnLabelAccumulator, dataProvider.getColumnDataProvider()); + + int columnCount = dataProvider.getColumnDataProvider().getColumnCount(); + + if (dataProvider instanceof DSObjectPropertiesGridDataProvider) { + handleDSObjectGridConfigureRegistry(configRegistry, dataProvider, columnCount); + } + handleCommonColumnConfigureRegistry(configRegistry, dataProvider, columnCount); + + } + + private void handleCommonColumnConfigureRegistry(IConfigRegistry configRegistry, + IDSGridDataProvider dataProvider, int columnCount) { + int colDatatype = 0; + for (int i = 0; i < columnCount; i++) { + colDatatype = dataProvider.getColumnDataProvider().getColumnDatatype(i); + switch (colDatatype) { + case Types.BIT: + case Types.BOOLEAN: { + checkBoxRegistry(configRegistry); + break; + } + case Types.TIME: + case Types.DATE: + case Types.TIME_WITH_TIMEZONE: + case Types.TIMESTAMP_WITH_TIMEZONE: + case Types.TIMESTAMP: { + dateAndTimeConfiguration(configRegistry); + break; + } + case Types.BLOB: { + handleCommonColumnConfigureForBlob(configRegistry, dataProvider, i); + break; + } + case Types.OTHER: { + cursorTypeConfiguration(configRegistry, dataProvider); + break; + } + + case Types.BINARY: { + handleCommonColumnConfigureForBinary(configRegistry, dataProvider, i); + break; + } + default: { + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, new DSTextCellEditor(), + DisplayMode.NORMAL, COL_LABEL_COPY_READONLY_CELL); + break; + } + } + } + } + + private void handleCommonColumnConfigureForBinary(IConfigRegistry configRegistry, + IDSGridDataProvider dataProvider, int i) { + if (MPPDBIDEConstants.BYTEA.equals(dataProvider.getColumnDataProvider().getColumnDataTypeName(i))) { + byteAConfiguration(configRegistry, dataProvider); + } else { + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, new DSTextCellEditor(), + DisplayMode.NORMAL, COL_LABEL_COPY_READONLY_CELL); + } + } + + private void handleCommonColumnConfigureForBlob(IConfigRegistry configRegistry, + IDSGridDataProvider dataProvider, int i) { + if (MPPDBIDEConstants.BLOB.equals(dataProvider.getColumnDataProvider().getColumnDataTypeName(i))) { + blobConfiguration(configRegistry, dataProvider); + } else { + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, new DSTextCellEditor(), + DisplayMode.NORMAL, COL_LABEL_COPY_READONLY_CELL); + } + } + + /** + * Blob configuration. + * + * @param configRegistry the config registry + * @param dataProvider the data provider + */ + public static void blobConfiguration(IConfigRegistry configRegistry, IDSGridDataProvider dataProvider) { + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, new DSBlobCellEditor(), + DisplayMode.NORMAL, COL_LABEL_BLOB_TYPE_CELL); + linkStyleConfiguration(configRegistry, COL_LABEL_BLOB_TYPE_CELL); + } + + /** + * Byte A configuration. + * + * @param configRegistry the config registry + * @param dataProvider the data provider + */ + public static void byteAConfiguration(IConfigRegistry configRegistry, IDSGridDataProvider dataProvider) { + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, new DSByteACellEditor(), + DisplayMode.NORMAL, COL_LABEL_BYTEA_TYPE_CELL); + linkStyleConfiguration(configRegistry, COL_LABEL_BYTEA_TYPE_CELL); + } + + private static void linkStyleConfiguration(IConfigRegistry configRegistry, String label) { + IStyle linkStyle = new Style(); + linkStyle.setAttributeValue(CellStyleAttributes.FOREGROUND_COLOR, + Display.getDefault().getSystemColor(SWT.COLOR_BLUE)); + configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, linkStyle, DisplayMode.NORMAL, + label); + } + + /** + * Blob configuration. + * + * @param configRegistry the config registry + * @param dataProvider the data provider + */ + public static void cursorTypeConfiguration(IConfigRegistry configRegistry, IDSGridDataProvider dataProvider) { + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, new DSCursorResultSetTable(), + DisplayMode.NORMAL, COL_LABEL_CURSOR_TYPE_CELL); + } + + private void handleDSObjectGridConfigureRegistry(IConfigRegistry configRegistry, + IDSGridDataProvider dataProvider, int columnCount) { + String colName; + for (int i = 0; i < columnCount; i++) { + colName = dataProvider.getColumnDataProvider().getColumnName(i); + if (DATA_TYPE.equalsIgnoreCase(colName)) { + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, + new CustomDialogCellEditor(dataProvider), DisplayMode.NORMAL, COL_LABEL_CUSTOM_DIALOG); + } else if (IS_NULLABLE.equalsIgnoreCase(colName)) { + checkBoxRegistry(configRegistry); + } + } + + // user role management + if (((DSObjectPropertiesGridDataProvider) dataProvider) + .getObjectPropertyObject() instanceof PropertiesUserRoleImpl) { + if (columnCount >= 2 + && MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_TAB_COLUMN_TITLE_VALUE) + .equals(dataProvider.getColumnDataProvider().getColumnName(1))) { + PropertiesUserRoleImpl propertiesUserRoleImpl = (PropertiesUserRoleImpl) ((DSObjectPropertiesGridDataProvider) dataProvider) + .getObjectPropertyObject(); + + dateStrRegister(configRegistry); + + dropDownListRegistry(configRegistry, + this.uiPref.getComboBoxDataProviders() + .get(PropertiesConstants.RESOURCE_POOL_COMBO_BOX_DATA_PROVIDER), + DROP_DOWN_LIST_DATA_TYPE); + } + + if (columnCount >= 2 + && MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_TAB_COLUMN_TITLE_IS_ENABLE) + .equals(dataProvider.getColumnDataProvider().getColumnName(1))) { + checkBoxRegistry(configRegistry); + } + + if (columnCount >= 2 + && MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_TAB_COLUMN_TITLE_BELONG_TO) + .equals(dataProvider.getColumnDataProvider().getColumnName(1))) { + comboBoxRegistry(configRegistry, this.uiPref.getComboBoxDataProviders() + .get(PropertiesConstants.MEMBER_SHIP_COMBO_BOX_DATA_PROVIDER)); + } + } + } + + @Override + public void registerConfigLabelsOnColumns(final ColumnOverrideLabelAccumulator columnLblAccumulator, + IDSGridColumnProvider columnDataProvider) { + int colCount = columnDataProvider.getColumnCount(); + int colDatatype = 0; + String colName = ""; + + if (columnDataProvider instanceof DSObjectPropertiesGridColumnDataProvider) { + for (int i = 0; i < colCount; i++) { + colName = columnDataProvider.getColumnName(i); + if (DATA_TYPE.equalsIgnoreCase(colName)) { + columnLblAccumulator.registerColumnOverrides(i, COL_LABEL_CUSTOM_DIALOG); + } else if (IS_NULLABLE.equalsIgnoreCase(colName)) { + columnLblAccumulator.registerColumnOverrides(i, COL_LABEL_BOOLEAN_DATATYPE); + } + } + } + registerConfigLblForClmDatatypes(columnLblAccumulator, columnDataProvider, colCount); + } + + private void registerConfigLblForClmDatatypes(final ColumnOverrideLabelAccumulator columnLblAccumulator, + IDSGridColumnProvider columnDataProvider, int colCount) { + int colDatatype; + for (int i = 0; i < colCount; i++) { + colDatatype = columnDataProvider.getColumnDatatype(i); + int colPrecisionVal = columnDataProvider.getPrecision(i); + + switch (colDatatype) { + case Types.BIT: + case Types.BOOLEAN: { + if (colPrecisionVal <= 1) { + columnLblAccumulator.registerColumnOverrides(i, COL_LABEL_BOOLEAN_DATATYPE); + } + break; + } + case Types.DATE: + case Types.TIMESTAMP: + case Types.TIME_WITH_TIMEZONE: + case Types.TIMESTAMP_WITH_TIMEZONE: { + columnLblAccumulator.registerColumnOverrides(i, + ITableGridStyleLabelFactory.COL_LABEL_TIME_WITHTIMEZONE); + break; + } + case Types.TIME: { + columnLblAccumulator.registerColumnOverrides(i, + ITableGridStyleLabelFactory.COL_LABEL_TIME_DATATYPE); + break; + } + case Types.BLOB: { + registerConfigLblForClmTypeBlob(columnLblAccumulator, columnDataProvider, i); + break; + } + case Types.OTHER: { + columnLblAccumulator.registerColumnOverrides(i, COL_LABEL_CURSOR_TYPE_CELL); + columnLblAccumulator.registerColumnOverrides(i, COL_LABEL_COPY_READONLY_CELL); + break; + } + case Types.BINARY: { + registerConfigLblForClmTypeBinary(columnLblAccumulator, columnDataProvider, i); + break; + } + default: { + columnLblAccumulator.registerColumnOverrides(i, COL_LABEL_COPY_READONLY_CELL); + break; + } + + } + + } + } + + private void registerConfigLblForClmTypeBinary(final ColumnOverrideLabelAccumulator columnLblAccumulator, + IDSGridColumnProvider columnDataProvider, int i) { + if (MPPDBIDEConstants.BYTEA.equals(columnDataProvider.getColumnDataTypeName(i))) { + columnLblAccumulator.registerColumnOverrides(i, COL_LABEL_BYTEA_TYPE_CELL); + columnLblAccumulator.registerColumnOverrides(i, COL_LABEL_COPY_READONLY_CELL); + } else { + columnLblAccumulator.registerColumnOverrides(i, COL_LABEL_COPY_READONLY_CELL); + } + } + + private void registerConfigLblForClmTypeBlob(final ColumnOverrideLabelAccumulator columnLblAccumulator, + IDSGridColumnProvider columnDataProvider, int i) { + if (MPPDBIDEConstants.BLOB.equals(columnDataProvider.getColumnDataTypeName(i))) { + columnLblAccumulator.registerColumnOverrides(i, COL_LABEL_BLOB_TYPE_CELL); + columnLblAccumulator.registerColumnOverrides(i, COL_LABEL_COPY_READONLY_CELL); + } else { + columnLblAccumulator.registerColumnOverrides(i, COL_LABEL_COPY_READONLY_CELL); + } + } + + /** + * Sets the column label accumulator. + * + * @param columnLabelAccumulator the new column label accumulator + */ + public void setColumnLabelAccumulator(ColumnOverrideLabelAccumulator columnLabelAccumulator) { + this.columnLabelAccumulator = columnLabelAccumulator; + } + + @Override + public void registerUiRegistryToEachColumn(IConfigRegistry configRegistry, + IDSGridColumnProvider columnDataProvider) { + + } + + /** + * the onPreDestroy + */ + public void onPreDestroy() { + columnLabelAccumulator = null; + dataGridContext = null; + uiPref = null; + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/ExecutionPlanGridComponent.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/ExecutionPlanGridComponent.java new file mode 100644 index 0000000000000000000000000000000000000000..fb71abc1e87759b98726d3f30cb71bd8977a0c33 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/ExecutionPlanGridComponent.java @@ -0,0 +1,337 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import org.eclipse.jface.layout.GridDataFactory; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StackLayout; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.ToolItem; + +import org.opengauss.mppdbide.adapter.keywordssyntax.SQLSyntax; +import org.opengauss.mppdbide.explainplan.ui.model.ExplainAnalyzePlanNodeTreeDisplayDataTreeFormat; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.visualexplainplan.ExecutionPlanTextDisplayGrid; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.view.component.IGridUIPreference; +import org.opengauss.mppdbide.view.component.grid.core.DataGrid; +import org.opengauss.mppdbide.view.component.grid.core.TreeDataGrid; + +/** + * + * Title: class + * + * Description: The Class ExecutionPlanGridComponent. + * + * @since 3.0.0 + */ +public class ExecutionPlanGridComponent extends DSGridComponent { + private TreeDataGrid treeGrid; + private DataGrid textGrid; + + // execution plan data providers + private ExplainAnalyzePlanNodeTreeDisplayDataTreeFormat execPlanTreeData; + private ExecutionPlanTextDisplayGrid execPlanTextData; + + private Composite textTabComposite; + private Composite treeTabComposite; + + private StackLayout slayout; + + private GRIDTYPE gridType; + private Composite gridComposite; + private Composite toolbarComposite; + private Composite statusbarComposite; + private SQLSyntax sqlSyntax; + + /** + * On pre destroy. + */ + @Override + public void onPreDestroy() { + super.onPreDestroy(); + + if (this.treeGrid != null) { + this.treeGrid.onPreDestroy(); + } + this.treeGrid = null; + if (this.textGrid != null) { + this.textGrid.onPreDestroy(); + } + this.textGrid = null; + + if (this.execPlanTreeData != null) { + this.execPlanTreeData.preDestroy(); + } + this.execPlanTreeData = null; + if (this.execPlanTextData != null) { + this.execPlanTextData.preDestroy(); + } + this.execPlanTextData = null; + this.slayout = null; + this.gridType = null; + + if (searchArea != null) { + searchArea.preDestroy(); + } + if (this.toolbar != null) { + this.toolbar.preDestroy(); + } + this.toolbar = null; + } + + /** + * + * Title: enum + * + * Description: The Enum GRIDTYPE. + */ + private enum GRIDTYPE { + TABLE, TREE + }; + + /** + * Instantiates a new execution plan grid component. + * + * @param gridUiPref2 the grid ui pref 2 + * @param treeView2 the tree view 2 + * @param textView2 the text view 2 + * @param sqlSyntax the sql syntax + */ + public ExecutionPlanGridComponent(IGridUIPreference gridUiPref2, + ExplainAnalyzePlanNodeTreeDisplayDataTreeFormat treeView2, ExecutionPlanTextDisplayGrid textView2, + SQLSyntax sqlSyntax) { + super(gridUiPref2, treeView2); + this.uiPref = gridUiPref2; + this.execPlanTreeData = treeView2; + this.execPlanTextData = textView2; + this.textGrid = null; + this.treeGrid = null; + this.gridType = GRIDTYPE.TREE; + this.sqlSyntax = sqlSyntax; + } + + /** + * Reset data provider. + * + * @param dataProvider the data provider + */ + public void resetDataProvider(IDSGridDataProvider dataProvider) { + this.dataProvider = dataProvider; + } + + private void showTable(Composite composite) { + slayout.topControl = composite; + gridComposite.layout(); + } + + /** + * Switch execution plan grid data. + */ + public void switchExecutionPlanGridData() { + if (gridType == GRIDTYPE.TREE) { + gridType = GRIDTYPE.TABLE; + resetDataProvider(this.execPlanTextData); + this.grid = this.textGrid; + showTable(textTabComposite); + } else { + gridType = GRIDTYPE.TREE; + resetDataProvider(this.execPlanTreeData); + this.grid = this.treeGrid; + showTable(treeTabComposite); + } + this.searchArea.setGrid(this.grid); + } + + /** + * Sets the data provider. + * + * @param treeView the tree view + * @param textView the text view + */ + public void setDataProvider(ExplainAnalyzePlanNodeTreeDisplayDataTreeFormat treeView, + ExecutionPlanTextDisplayGrid textView) { + IDSGridDataProvider dataProvider = (this.gridType == GRIDTYPE.TREE) ? treeView : textView; + if (this.execPlanTreeData != null) { + this.execPlanTreeData.preDestroy(); + this.execPlanTreeData = null; + } + this.execPlanTreeData = treeView; + if (this.execPlanTextData != null) { + this.execPlanTextData.preDestroy(); + this.execPlanTextData = null; + } + this.execPlanTextData = textView; + super.setDataProvider(dataProvider); + updateGridStatusBar(this.execPlanTreeData.getSummary()); + } + + /** + * Creates the data grid area. + * + * @param parent the parent + * @return the data grid + */ + protected DataGrid createDataGridArea(Composite parent) { + ExecutionPlanGridComponent.setExecGridLayoutProperties(parent); + DataGrid dataGrid = null; + dataGrid = createDataGrid(parent); + eventTable.sendEvent(new DSEvent(LISTEN_TYPE_POST_GRID_DATA_LOAD, dataProvider)); + return dataGrid; + } + + /** + * Sets the exec grid layout properties. + * + * @param parent the new exec grid layout properties + */ + public static void setExecGridLayoutProperties(Composite parent) { + GridLayout gridlt = new GridLayout(); + + gridlt.marginTop = 0; + gridlt.marginBottom = 0; + gridlt.marginRight = 0; + gridlt.marginLeft = 0; + gridlt.marginHeight = 0; + gridlt.marginWidth = 0; + gridlt.verticalSpacing = 0; + gridlt.horizontalSpacing = 0; + parent.setLayout(gridlt); + GridDataFactory.fillDefaults().grab(true, false).applyTo(parent); + } + + /** + * Creates the components. + * + * @param parent the parent + */ + public void createComponents(Composite parent) { + + toolbarComposite = createNewComposite(parent); + gridComposite = createNewComposite(parent); + textTabComposite = createNewComposite(gridComposite); + treeTabComposite = createNewComposite(gridComposite); + statusbarComposite = createNewComposite(parent); + + this.toolbar = createToolBar(toolbarComposite, this.dataProvider); + this.searchArea = createSearchArea(toolbarComposite); + this.searchArea.setExecutionPlanTabFlag(); + if (uiPref.isShowQueryArea()) { + this.queryArea = createQueryArea(toolbarComposite); + this.queryArea.setExecutionPlanTabFlag(); + } + this.grid = createDataGridArea(parent); + + if (uiPref.isShowStatusBar()) { + this.statusBar = createStatusBar(statusbarComposite, this.dataProvider); + updateGridStatusBar(this.execPlanTreeData.getSummary()); + } + + this.searchArea.setGrid(this.grid); + + ToolItem beginSeparator = new ToolItem(this.toolbar.getToolBar(), SWT.SEPARATOR); + beginSeparator.setEnabled(true); + this.toolbar.addItemTreeView(this.eventTable, this.stateMachine); + this.toolbar.addItemTextView(this.eventTable, this.stateMachine); + ToolItem endSeparator = new ToolItem(this.toolbar.getToolBar(), SWT.SEPARATOR); + endSeparator.setEnabled(true); + this.toolbar.addItemCopy(this.stateMachine, false); + this.toolbar.setDsExportState(this.stateMachine); + this.toolbar.addRefreshPlanItem(this.eventTable, this.stateMachine); + this.toolbar.setDsRefreshState(this.stateMachine); + + if (uiPref.isShowQueryArea()) { + this.toolbar.addItemToggleQueryArea(this.queryArea); + } + this.toolbar.addItemToggleSearchArea(this.searchArea); + + if (this.uiPref.isSupportDataExport()) { + this.toolbar.addItemExportExecutionPlan(this.eventTable, this.stateMachine); + } + + ((GridData) toolbarComposite.getLayoutData()).grabExcessVerticalSpace = false; + ((GridData) gridComposite.getLayoutData()).grabExcessVerticalSpace = true; + ((GridData) textTabComposite.getLayoutData()).grabExcessVerticalSpace = true; + ((GridData) treeTabComposite.getLayoutData()).grabExcessVerticalSpace = true; + ((GridData) statusbarComposite.getLayoutData()).grabExcessVerticalSpace = false; + + this.slayout = new StackLayout(); + gridComposite.setLayout(slayout); + + showTable(treeTabComposite); + + this.grid.setFocus(); + } + + /** + * Creates the query area. + * + * @param gridCmposite the grid cmposite + * @return the grid query area + */ + protected GridQueryArea createQueryArea(Composite gridCmposite) { + GridQueryArea area = new GridQueryArea(this.execPlanTreeData.getSummary().getQuery()); + area.setSQLSyntax(getSqlSyntax()); + area.createComponent(gridCmposite, false); + return area; + } + + /** + * Creates the data grid. + * + * @param composite the composite + * @return the data grid + */ + protected DataGrid createDataGrid(Composite composite) { + DataGrid dataGrid; + /* + * for execution plan tree view + */ + + this.treeGrid = new TreeDataGrid(this.uiPref, + (ExplainAnalyzePlanNodeTreeDisplayDataTreeFormat) this.execPlanTreeData, this.eventTable, + this.stateMachine); + this.treeGrid.createComponent(treeTabComposite); + /* + * and execution plan text view + */ + this.textGrid = new DataGrid(this.uiPref, this.execPlanTextData, this.eventTable, this.stateMachine); + this.textGrid.createComponent(textTabComposite); + + dataGrid = this.treeGrid; + return dataGrid; + } + + /** + * Gets the sql syntax. + * + * @return the sql syntax + */ + public SQLSyntax getSqlSyntax() { + return sqlSyntax; + } + + /** + * Sets the SQL syntax. + * + * @param sqlSyntax the new SQL syntax + */ + public void setSQLSyntax(SQLSyntax sqlSyntax) { + this.sqlSyntax = sqlSyntax; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridAndTextScrollEventDataLoadListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridAndTextScrollEventDataLoadListener.java new file mode 100644 index 0000000000000000000000000000000000000000..6dd696d3a25366aaba42730acd3a7c00026a3eb5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridAndTextScrollEventDataLoadListener.java @@ -0,0 +1,236 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import java.time.LocalDateTime; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.events.KeyListener; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.ScrollBar; + +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.utils.observer.DSEventTable; +import org.opengauss.mppdbide.view.component.DSGridStateMachine; + +/** + * Title: GridAndTextScrollEventDataLoadListener + * + * Description:The listener interface for receiving + * gridAndTextScrollEventDataLoad events. The class that is interested in + * processing a gridAndTextScrollEventDataLoad event implements this interface, + * and the object created with that class is registered with a component using + * the component's addGridAndTextScrollEventDataLoadListener method. + * When the gridAndTextScrollEventDataLoad event occurs, that object's + * appropriate method is invoked. + * + * @since 3.0.0 + */ +public abstract class GridAndTextScrollEventDataLoadListener implements Listener, KeyListener { + private IDSGridDataProvider dataProvider; + private DSEventTable eventTable; + private DSGridStateMachine stateMachine; + private String currentSearchString; + private LocalDateTime lastLoadTime; + private boolean currentInitDataTextSatatu; + + /** + * Instantiates a new grid and text scroll event data load listener. + * + * @param dataProvider the data provider + * @param eventTable the event table + * @param stateMachine the state machine + */ + public GridAndTextScrollEventDataLoadListener(IDSGridDataProvider dataProvider, DSEventTable eventTable, + DSGridStateMachine stateMachine) { + this.dataProvider = dataProvider; + this.eventTable = eventTable; + this.stateMachine = stateMachine; + this.lastLoadTime = LocalDateTime.now(); + } + + /** + * Handle event. + * + * @param event the event + */ + @Override + public void handleEvent(Event event) { + ScrollBar bar = (ScrollBar) event.widget; + updateScrolledPosition(bar.getSelection(), bar.getPageIncrement(), bar.getIncrement()); + if (bar.getSelection() + bar.getThumb() == bar.getMaximum()) { + triggerLoadMoreRecords(false); + } + } + + /** + * Key pressed. + * + * @param event the event + */ + @Override + public void keyPressed(KeyEvent event) { + if (event.keyCode == SWT.ARROW_DOWN || event.keyCode == SWT.PAGE_DOWN) { + triggerLoadMoreRecords(true); + } + } + + /** + * update scrolled position + * + * @param position the ui scrolled position + * @param pageIncrement the page increment + * @param increment the one row increment + */ + public abstract void updateScrolledPosition(int position, int pageIncrement, int increment); + + /** + * Checks if is last row selected. + * + * @return true, if is last row selected + */ + public abstract boolean isLastRowSelected(); + + /** + * Trigger load more records. + * + * @param isKeyStrokeTriggeredScrollEvent the is key stroke triggered scroll + * event + */ + public abstract void triggerLoadMoreRecords(boolean isKeyStrokeTriggeredScrollEvent); + + /** + * Key released. + * + * @param e the e + */ + @Override + public void keyReleased(KeyEvent e) { + // Ignore. No need to handle release event. + } + + /** + * Reset loading status. + */ + public void resetLoadingStatus() { + this.stateMachine.set(DSGridStateMachine.State.IDLE); + } + + /** + * Gets the data provider. + * + * @return the data provider + */ + public IDSGridDataProvider getDataProvider() { + return dataProvider; + } + + /** + * Sets the data provider. + * + * @param dataProvider the new data provider + */ + public void setDataProvider(IDSGridDataProvider dataProvider) { + this.dataProvider = dataProvider; + } + + /** + * Sets the search string. + * + * @param searchText the new search string + */ + public void setSearchString(String searchText) { + this.currentSearchString = searchText; + } + + /** + * Checks if is search in progress. + * + * @return true, if is search in progress + */ + public boolean isSearchInProgress() { + return null != this.currentSearchString && !this.currentSearchString.isEmpty(); + } + + /** + * Gets the event table. + * + * @return the event table + */ + public DSEventTable getEventTable() { + return eventTable; + } + + /** + * Gets the last load time. + * + * @return the last load time + */ + public LocalDateTime getLastLoadTime() { + return lastLoadTime; + } + + /** + * Sets the last load time. + * + * @param lastLoadTime the new last load time + */ + public void setLastLoadTime(LocalDateTime lastLoadTime) { + this.lastLoadTime = lastLoadTime; + } + + /** + * Gets the state machine. + * + * @return the state machine + */ + public DSGridStateMachine getStateMachine() { + return stateMachine; + } + + /** + * Checks if is current init data text satatu. + * + * @return true, if is current init data text satatu + */ + public boolean isCurrentInitDataTextSatatu() { + return currentInitDataTextSatatu; + } + + /** + * Sets the current init data text satatu. + * + * @param currentInitDataTextSatatu the new current init data text satatu + */ + public void setCurrentInitDataTextSatatu(boolean currentInitDataTextSatatu) { + this.currentInitDataTextSatatu = currentInitDataTextSatatu; + } + + /** + * On pre destroy. + */ + public void onPreDestroy() { + this.dataProvider = null; + this.eventTable = null; + this.lastLoadTime = null; + this.currentSearchString = null; + if (this.stateMachine != null && this.stateMachine.countObservers() > 0) { + this.stateMachine.deleteObservers(); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridQueryArea.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridQueryArea.java new file mode 100644 index 0000000000000000000000000000000000000000..c8410e402c51c41ad90f53238a90eea0f2240049 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridQueryArea.java @@ -0,0 +1,312 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import javax.annotation.PreDestroy; + +import org.eclipse.jface.layout.GridDataFactory; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.text.source.ISharedTextColors; +import org.eclipse.jface.text.source.SourceViewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.dnd.Clipboard; +import org.eclipse.swt.dnd.TextTransfer; +import org.eclipse.swt.dnd.Transfer; +import org.eclipse.swt.events.KeyAdapter; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.MenuItem; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.internal.editors.text.EditorsPlugin; +import org.eclipse.ui.texteditor.SourceViewerDecorationSupport; + +import org.opengauss.mppdbide.adapter.keywordssyntax.SQLSyntax; +import org.opengauss.mppdbide.bl.sqlhistory.IQueryExecutionSummary; +import org.opengauss.mppdbide.presentation.edittabledata.DSResultSetGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.core.sourceeditor.SQLDocumentPartitioner; +import org.opengauss.mppdbide.view.core.sourceeditor.SQLSourceViewerConfig; +import org.opengauss.mppdbide.view.utils.IUserPreference; +import org.opengauss.mppdbide.view.utils.UserPreference; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * Title: class + * Description: The Class GridQueryArea. + * + * @since 3.0.0 + */ +public class GridQueryArea { + private String query = null; + + private Composite queryComposite; + + private SourceViewer sourceViewer; + + private Text queryText; + + private SourceViewerDecorationSupport sourceViewerDecorationSupport; + + private SQLSyntax syntax; + + private boolean isExecutionPlantab = false; + + /** + * Sets the execution plan tab flag. + */ + public void setExecutionPlanTabFlag() { + this.isExecutionPlantab = true; + } + + /** + * Instantiates a new grid query area. + * + * @param dataProvider the data provider + */ + public GridQueryArea(IDSGridDataProvider dataProvider) { + if (dataProvider instanceof DSResultSetGridDataProvider) { + DSResultSetGridDataProvider rsDataProvider = (DSResultSetGridDataProvider) dataProvider; + IQueryExecutionSummary summary = rsDataProvider.getSummary(); + if (null != summary) { + this.query = summary.getQuery(); + } + } + } + + /** + * Instantiates a new grid query area. + * + * @param queryToDisplay the query to display + */ + public GridQueryArea(String queryToDisplay) { + this.query = queryToDisplay; + } + + /** + * Creates the component. + * + * @param parent the parent + * @param isVisualPlan the is visual plan + */ + public void createComponent(Composite parent, boolean isVisualPlan) { + if (null == query) { + return; + } + + this.queryComposite = createComposite(parent); + addItemQueryText(isVisualPlan); + + } + + /** + * Sets the SQL syntax. + * + * @param syntx the new SQL syntax + */ + public void setSQLSyntax(SQLSyntax syntx) { + this.syntax = syntx; + } + + private Composite createComposite(Composite parent) { + Composite newSearchComposite = new Composite(parent, SWT.TOOL | SWT.DIALOG_TRIM); + DSGridComponent.setLayoutProperties(newSearchComposite); + Object layoutDataObj = newSearchComposite.getLayoutData(); + if (layoutDataObj instanceof GridLayout) { + GridLayout layout = (GridLayout) layoutDataObj; + layout.marginHeight = 20; + } + GridDataFactory.fillDefaults().grab(true, false).applyTo(newSearchComposite); + + return newSearchComposite; + } + + private void setDecoration() { + IPreferenceStore prefStore = UserPreference.getInstance().getPrefernceStore(); + ISharedTextColors sharedTextColors = EditorsPlugin.getDefault().getSharedTextColors(); + + sourceViewerDecorationSupport = + new SourceViewerDecorationSupport(this.sourceViewer, null, null, sharedTextColors); + sourceViewerDecorationSupport.setCursorLinePainterPreferenceKeys(IUserPreference.CURRENT_LINE_VISIBILITY, + IUserPreference.CURRENTLINE_COLOR); + sourceViewerDecorationSupport.install(prefStore); + } + + private void addItemQueryText(boolean isVisualPlan) { + GridData grid = new GridData(); + if (isVisualPlan) { + grid.heightHint = 690; + } else { + grid.heightHint = 20; + } + grid.horizontalAlignment = SWT.FILL; + grid.grabExcessHorizontalSpace = true; + grid.grabExcessVerticalSpace = false; + + String lquery = validateQuery(); + if (lquery.length() > 100) { + this.queryText = new Text(this.queryComposite, SWT.MULTI | SWT.WRAP | SWT.READ_ONLY | SWT.V_SCROLL); + this.queryText.setLayoutData(grid); + this.queryText.setText(this.query); + this.queryText.addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent event) { + if (event.stateMask == SWT.CTRL && event.keyCode == 'a') { + queryText.selectAll(); + event.doit = false; + } + } + }); + } else { + this.sourceViewer = + new SourceViewer(this.queryComposite, null, null, false, SWT.V_SCROLL | SWT.WRAP | SWT.NONE); + this.sourceViewer.getControl().setLayoutData(grid); + this.sourceViewer.setEditable(false); + this.sourceViewer.setDocument(new Document(validateQuery())); + setDecoration(); + this.sourceViewer.configure(new SQLSourceViewerConfig(this.syntax)); + SQLDocumentPartitioner.connectDocument(sourceViewer.getDocument(), 0); + Menu menu = new Menu(getControl()); + sourceViewer.getTextWidget().setMenu(menu); + addCopyMenuItem(menu); + } + } + + private Control getControl() { + Control ctrl = sourceViewer.getControl(); + if (ctrl instanceof Composite) { + Composite cmpst = (Composite) ctrl; + Control[] childControls = cmpst.getChildren(); + Control childControl = null; + for (int i = 0; i < childControls.length; i++) { + childControl = childControls[i]; + if (childControl instanceof StyledText) { + ctrl = childControl; + break; + } + } + } + return ctrl; + } + + /** + * Adds the copy menu item. + * + * @param menu the menu + */ + protected void addCopyMenuItem(Menu menu) { + MenuItem menuCopy = new MenuItem(menu, SWT.PUSH); + menuCopy.setText(MessageConfigLoader.getProperty(IMessagesConstants.STATUS_MSG_PLVIEWER_OPTION_COPY)); + menuCopy.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent e) { + + ITextSelection textSel = (ITextSelection) sourceViewer.getSelectionProvider().getSelection(); + String selectedText = textSel.getText(); + String str = ""; + if (selectedText != null && selectedText.length() > 0) { + str = selectedText; + } else { + str = sourceViewer.getDocument().get(); + } + Clipboard cb = new Clipboard(Display.getDefault()); + + cb.setContents(new Object[] {str}, new Transfer[] {TextTransfer.getInstance()}); + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + + } + }); + menuCopy.setImage(IconUtility.getIconImage(IiconPath.ICO_COPY, this.getClass())); + } + + private String validateQuery() { + String strQuery = ""; + if (null != this.query) { + strQuery = this.query.replaceAll(MPPDBIDEConstants.NEW_LINE_SIGN, " "); + strQuery = strQuery.replaceAll(MPPDBIDEConstants.LINE_SEPARATOR, " "); + } + return strQuery; + } + + /** + * Do hide query area. + */ + public void doHideQueryArea() { + GridUIUtils.toggleCompositeSectionVisibility(this.queryComposite, true, null, this.isExecutionPlantab); + } + + /** + * Do show query area. + */ + public void doShowQueryArea() { + GridUIUtils.toggleCompositeSectionVisibility(this.queryComposite, false, null, this.isExecutionPlantab); + } + + /** + * Checks if is quuery area visible. + * + * @return true, if is quuery area visible + */ + public boolean isQuueryAreaVisible() { + return this.queryComposite.isVisible(); + } + + /** + * Pre destroy. + */ + @PreDestroy + public void preDestroy() { + if (sourceViewer != null) { + syntax = null; + sourceViewerDecorationSupport.uninstall(); + sourceViewerDecorationSupport = null; + sourceViewer.unconfigure(); + sourceViewer = null; + } + } + + /** + * Reconfigure. + * + * @param sytax the sytax + */ + public void reconfigure(SQLSyntax sytax) { + if (sourceViewer != null) { + sourceViewer.unconfigure(); + sourceViewer.configure(new SQLSourceViewerConfig(sytax)); + if (sourceViewer.getDocument() != null) { + SQLDocumentPartitioner.connectDocument(sourceViewer.getDocument(), 0); + } + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridScrollEventDataLoadListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridScrollEventDataLoadListener.java new file mode 100644 index 0000000000000000000000000000000000000000..14541c1d8341fc454b129a0386c73fe480386a5f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridScrollEventDataLoadListener.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; + +import org.opengauss.mppdbide.presentation.grid.IDSEditGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.utils.observer.DSEventTable; +import org.opengauss.mppdbide.utils.observer.IDSGridUIListenable; +import org.opengauss.mppdbide.view.component.DSGridStateMachine; +import org.opengauss.mppdbide.view.component.grid.core.DataGrid; +import org.opengauss.mppdbide.view.component.grid.core.GridViewPortLayer; + +/** + * Title: GridScrollEventDataLoadListener + * + * Description: The listener interface for receiving gridScrollEventDataLoad + * events. The class that is interested in processing a gridScrollEventDataLoad + * event implements this interface, and the object created with that class is + * registered with a component using the component's + * addGridScrollEventDataLoadListener method. When the + * gridScrollEventDataLoad event occurs, that object's appropriate method is + * invoked. + * + * @since 3.0.0 + */ +public class GridScrollEventDataLoadListener extends GridAndTextScrollEventDataLoadListener { + private GridViewPortLayer viewportLayer; + private DataGrid dataGrid; + + /** + * Instantiates a new grid scroll event data load listener. + * + * @param viewportLayer the viewport layer + * @param dataProvider the data provider + * @param eventTable the event table + * @param stateMachine the state machine + * @param dataGrid the data grid + */ + public GridScrollEventDataLoadListener(GridViewPortLayer viewportLayer, IDSGridDataProvider dataProvider, + DSEventTable eventTable, DSGridStateMachine stateMachine, DataGrid dataGrid) { + super(dataProvider, eventTable, stateMachine); + this.viewportLayer = viewportLayer; + this.dataGrid = dataGrid; + } + + /** + * Checks if is last row selected. + * + * @return true, if is last row selected + */ + @Override + public boolean isLastRowSelected() { + if (this.getDataProvider() instanceof IDSEditGridDataProvider) { + return this.dataGrid.getSelectedRowPosition() == (this.getDataProvider().getRecordCount() + + ((IDSEditGridDataProvider) this.getDataProvider()).getInsertedRowCount()) - 1; + } + return this.dataGrid.getSelectedRowPosition() == this.getDataProvider().getRecordCount() - 1; + } + + /** + * Trigger load more records. + * + * @param isKeyStrokeTriggeredScrollEvent the is key stroke triggered scroll + * event + */ + @Override + public void triggerLoadMoreRecords(boolean isKeyStrokeTriggeredScrollEvent) { + if ((isKeyStrokeTriggeredScrollEvent ? isLastRowSelected() : this.viewportLayer.isScrolledToEndOfPage()) + && !this.getDataProvider().isEndOfRecords() && !isSearchInProgress() + && !isCurrentInitDataTextSatatu()) { + if (ChronoUnit.MILLIS.between(this.getLastLoadTime(), LocalDateTime.now()) >= 2000) { + this.setLastLoadTime(LocalDateTime.now()); + if (this.getStateMachine().set(DSGridStateMachine.State.LOADING)) { + this.getEventTable().sendEvent( + new DSEvent(IDSGridUIListenable.LISTEN_TYPE_ON_REEXECUTE_QUERY, getDataProvider())); + } + } + } + } + + /** + * On pre destroy. + */ + public void onPreDestroy() { + super.onPreDestroy(); + this.dataGrid = null; + this.viewportLayer = null; + } + + @Override + public void updateScrolledPosition(int position, int pageIncrement, int increment) { + int pageRowSize = pageIncrement / increment ; + dataGrid.updateScrolledInfo(position, pageRowSize); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridSearchArea.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridSearchArea.java new file mode 100644 index 0000000000000000000000000000000000000000..bdb2e57c807bb5ee415ad752c991c7bf6428df28 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridSearchArea.java @@ -0,0 +1,430 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import org.eclipse.jface.layout.GridDataFactory; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.KeyAdapter; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Text; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.component.DSGridStateMachine; +import org.opengauss.mppdbide.view.component.grid.core.DataGrid; +import org.opengauss.mppdbide.view.component.grid.core.DataText; +import org.opengauss.mppdbide.view.utils.InitListener; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * + * Title: class + * + * Description: The Class GridSearchArea. + * + * @since 3.0.0 + */ +public class GridSearchArea { + + /** + * The Constant REGEX_FOR_NULL_VALUE. + */ + protected static final String REGEX_FOR_NULL_VALUE = "^$"; + + private Composite searchArea; + private Text txtSearchStr; + private DataGrid grid; + private DataText text; + private GridToolbar toolbar; + private Button btnSearch; + private Button btnClearSearchTxt; + private Combo cmbSearchOpt; + private boolean isExecutionPlanTab = false; + + /** + * Sets the execution plan tab flag. + */ + public void setExecutionPlanTabFlag() { + this.isExecutionPlanTab = true; + } + + /** + * Creates the component. + * + * @param parent the parent + * @param stateMachine the state machine + */ + public void createComponent(Composite parent, DSGridStateMachine stateMachine) { + this.searchArea = createComposite(parent); + addItemSearchType(SEARCHOPTIONS.SRCH_CONTAINS); + addItemSearchText(); + addItemSearchButton(); + addItemClearButton(); + } + + /** + * Sets the grid. + * + * @param grid2 the new grid + */ + public void setGrid(DataGrid grid2) { + this.grid = grid2; + } + + /** + * Sets the text. + * + * @param text2 the new text + */ + public void setText(DataText text2) { + this.text = text2; + } + + private Composite createComposite(Composite parent) { + Composite newSearchComposite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(4, false); + layout.marginWidth = 0; + layout.marginHeight = 0; + layout.horizontalSpacing = 0; + newSearchComposite.setLayout(layout); + GridDataFactory.fillDefaults().grab(true, false).applyTo(newSearchComposite); + + return newSearchComposite; + } + + /** + * Adds the item search type. + * + * @param defaultSearchOption the default search option + */ + public void addItemSearchType(SEARCHOPTIONS defaultSearchOption) { + this.cmbSearchOpt = new Combo(this.searchArea, SWT.READ_ONLY); + String[] items = new String[] {SEARCHOPTIONS.SRCH_CONTAINS.getDisplayName(), + SEARCHOPTIONS.SRCH_EQUALS.getDisplayName(), SEARCHOPTIONS.SRCH_STARTS_WITH.getDisplayName(), + SEARCHOPTIONS.SRCH_NULL.getDisplayName()}; + + this.cmbSearchOpt.setItems(items); + this.cmbSearchOpt.setText(SEARCHOPTIONS.SRCH_CONTAINS.getDisplayName()); + this.cmbSearchOpt.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent e) { + if (cmbSearchOpt.getText().equals(SEARCHOPTIONS.SRCH_NULL.getDisplayName())) { + txtSearchStr.setText(""); + txtSearchStr.setEnabled(false); + } else { + txtSearchStr.setEnabled(true); + } + + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + + } + }); + } + + /** + * Adds the item search text. + */ + public void addItemSearchText() { + this.txtSearchStr = new Text(this.searchArea, SWT.SEARCH | SWT.ICON_SEARCH | SWT.ICON_CANCEL | SWT.NONE); + this.txtSearchStr.setMessage(MessageConfigLoader.getProperty(IMessagesConstants.SEARCH_ITEM_TEXT)); + + GridData gridData = new GridData(); + gridData.horizontalAlignment = SWT.FILL; + gridData.grabExcessHorizontalSpace = true; + this.txtSearchStr.setLayoutData(gridData); + this.txtSearchStr.addListener(SWT.MenuDetect, new InitListener()); + this.txtSearchStr.addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent keyEvent) { + if (keyEvent.keyCode == SWT.CR || keyEvent.keyCode == SWT.KEYPAD_CR) { + triggerSearch(true); + } + } + }); + } + + /** + * Adds the item search button. + */ + public void addItemSearchButton() { + btnSearch = new Button(this.searchArea, SWT.PUSH); + btnSearch.setImage(IconUtility.getIconImage(IiconPath.SEARCH_TEXT, getClass())); + btnSearch.setToolTipText(MessageConfigLoader.getProperty(IMessagesConstants.SEARCH_GRID)); + btnSearch.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent e) { + triggerSearch(true); + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + // Ignore + } + }); + } + + /** + * Trigger search. + * + * @param doSearch the do search + */ + protected void triggerSearch(boolean doSearch) { + String searchStr = this.txtSearchStr.getText(); + matcherSearch(searchStr, doSearch); + } + + /** + * Trigger search. + * + * @param valueStr the value str + * @param doSearch the do search + */ + protected void triggerSearch(String valueStr, boolean doSearch) { + matcherSearch(valueStr, doSearch); + } + + /** + * Matcher search. + * + * @param targetValueStrParam the target value str param + * @param doSearch the do search + */ + protected void matcherSearch(String targetValueStrParam, boolean doSearch) { + String targetValueStr = targetValueStrParam; + String optStr = this.cmbSearchOpt.getText(); + SEARCHOPTIONS searchOpt = null; + + if (optStr.equals(SEARCHOPTIONS.SRCH_CONTAINS.getDisplayName())) { + searchOpt = SEARCHOPTIONS.SRCH_CONTAINS; + } else if (optStr.equals(SEARCHOPTIONS.SRCH_EQUALS.getDisplayName())) { + searchOpt = SEARCHOPTIONS.SRCH_EQUALS; + } else if (optStr.equals(SEARCHOPTIONS.SRCH_STARTS_WITH.getDisplayName())) { + searchOpt = SEARCHOPTIONS.SRCH_STARTS_WITH; + } else if (optStr.equals(SEARCHOPTIONS.SRCH_REGEX.getDisplayName())) { + searchOpt = SEARCHOPTIONS.SRCH_REGEX; + } else { + if (doSearch) { + targetValueStr = REGEX_FOR_NULL_VALUE; + } + + searchOpt = SEARCHOPTIONS.SRCH_NULL; + } + if (null != this.text) { + if (this.toolbar.isShowGridOrShowTextSelect()) { + this.grid.doSearch(targetValueStr, searchOpt); + } else { + doSearch(targetValueStr, searchOpt); + } + } else { + this.grid.doSearch(targetValueStr, searchOpt); + } + } + + /** + * Do search. + * + * @param searchText the search text + * @param searchOptions the search options + */ + public void doSearch(String searchText, SEARCHOPTIONS searchOptions) { + search(searchText, searchOptions); + // Scroll bar is unavailable in search mode + this.text.setSearchStringForScrollBar(searchText); + // In search mode, the refresh button is grayed out + this.text.enableDisableRefreshButton(searchText); + } + + private void search(String searchText, SEARCHOPTIONS searchOptions) { + switch (searchOptions) { + case SRCH_CONTAINS: { + this.text.searchContains(searchText); + break; + } + case SRCH_EQUALS: { + this.text.searchEquals(searchText); + break; + } + case SRCH_STARTS_WITH: { + this.text.searchStartsWith(searchText); + break; + } + case SRCH_NULL: { + this.text.searchReg(searchText); + break; + } + default: { + break; + } + } + } + + /** + * Adds the item clear button. + */ + public void addItemClearButton() { + btnClearSearchTxt = new Button(this.searchArea, SWT.PUSH); + btnClearSearchTxt.setImage(IconUtility.getIconImage(IiconPath.CLEAR_SEARCH_TEXT, getClass())); + btnClearSearchTxt.setToolTipText(MessageConfigLoader.getProperty(IMessagesConstants.CLEAR_SEARCH_GRID)); + btnClearSearchTxt.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent e) { + if (!txtSearchStr.getEnabled()) { + txtSearchStr.setEnabled(true); + } + GridSearchArea.this.txtSearchStr.setText(""); + cmbSearchOpt.setText(SEARCHOPTIONS.SRCH_CONTAINS.getDisplayName()); + triggerSearch(false); + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + // Ignore + } + }); + + } + + /** + * Do hide search area. + */ + public void doHideSearchArea() { + GridUIUtils.toggleCompositeSectionVisibility(this.searchArea, true, null, this.isExecutionPlanTab); + } + + /** + * Do show search area. + */ + public void doShowSearchArea() { + GridUIUtils.toggleCompositeSectionVisibility(this.searchArea, false, this.txtSearchStr, + this.isExecutionPlanTab); + } + + /** + * Checks if is search area visible. + * + * @return true, if is search area visible + */ + public boolean isSearchAreaVisible() { + return this.searchArea.isVisible(); + } + + /** + * Sets the focus. + */ + public void setFocus() { + this.txtSearchStr.setFocus(); + } + + /** + * Pre destroy. + */ + public void preDestroy() { + this.grid = null; + } + + /** + * Gets the txt search str. + * + * @return the txt search str + */ + public Text getTxtSearchStr() { + return txtSearchStr; + } + + /** + * Sets the txt search str. + * + * @param txtSearchStr the new txt search str + */ + public void setTxtSearchStr(Text txtSearchStr) { + this.txtSearchStr = txtSearchStr; + } + + /** + * Sets the toolbar. + * + * @param toolbar the new toolbar + */ + public void setToolbar(GridToolbar toolbar) { + this.toolbar = toolbar; + } + + /** + * Gets the cmb search opt. + * + * @return the cmb search opt + */ + public Combo getCmbSearchOpt() { + return cmbSearchOpt; + } + + /** + * Sets the cmb search opt. + * + * @param cmbSearchOpt the new cmb search opt + */ + public void setCmbSearchOpt(Combo cmbSearchOpt) { + this.cmbSearchOpt = cmbSearchOpt; + } + + /** + * On pre destroy. + */ + public void onPreDestroy() { + this.searchArea = null; + this.cmbSearchOpt = null; + this.grid = null; + this.txtSearchStr = null; + this.btnClearSearchTxt = null; + this.btnSearch = null; + } + + /** + * Updata but status on data text search. + * + * @param status the status + */ + public void updataButStatusOnDataTextSearch(boolean status) { + this.cmbSearchOpt.setEnabled(status); + this.txtSearchStr.setEnabled(status); + this.btnClearSearchTxt.setEnabled(status); + this.btnSearch.setEnabled(status); + } + + /** + * Checks if is search but enable. + * + * @return true, if is search but enable + */ + public boolean isSearchButEnable() { + if (null != btnSearch && btnSearch.isEnabled()) { + return true; + } + return false; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridSearchAreaToDataGrid.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridSearchAreaToDataGrid.java new file mode 100644 index 0000000000000000000000000000000000000000..74fc7ee2145ab2d76731124172ffeaa0b3f19e46 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridSearchAreaToDataGrid.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Text; + +/** + * + * Title: class + * + * Description: The Class GridSearchAreaToDataGrid. + * + * @since 3.0.0 + */ +public class GridSearchAreaToDataGrid { + private GridSearchArea searchArea; + + /** + * Instantiates a new grid search area to data grid. + * + * @param searchArea the search area + */ + public GridSearchAreaToDataGrid(GridSearchArea searchArea) { + this.searchArea = searchArea; + } + + /** + * Gets the txt search str. + * + * @return the txt search str + */ + public Text getTxtSearchStr() { + return searchArea.getTxtSearchStr(); + } + + /** + * Gets the trigger search. + * + * @param targetValueStr the target value str + * @param doSearch the do search + * @return the trigger search + */ + public void getTriggerSearch(String targetValueStr, boolean doSearch) { + searchArea.triggerSearch(targetValueStr, doSearch); + } + + /** + * Gets the cmb search opt. + * + * @return the cmb search opt + */ + public Combo getCmbSearchOpt() { + return searchArea.getCmbSearchOpt(); + } + + /** + * Gets the trigger search. + * + * @param doSearch the do search + * @return the trigger search + */ + public void getTriggerSearch(boolean doSearch) { + searchArea.triggerSearch(doSearch); + + } + + /** + * On pre destroy. + */ + public void onPreDestroy() { + this.searchArea = null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridSelectionLayerPortData.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridSelectionLayerPortData.java new file mode 100644 index 0000000000000000000000000000000000000000..14875ba1daf03142a9562598418ae02a8b40fe51 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridSelectionLayerPortData.java @@ -0,0 +1,289 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import java.sql.Date; +import java.sql.Time; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.eclipse.nebula.widgets.nattable.coordinate.PositionCoordinate; +import org.eclipse.nebula.widgets.nattable.print.command.TurnViewportOffCommand; +import org.eclipse.nebula.widgets.nattable.print.command.TurnViewportOnCommand; +import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer; +import org.eclipse.nebula.widgets.nattable.util.IClientAreaProvider; + +import org.opengauss.mppdbide.presentation.exportdata.ExportCursorExecuteVisitor.ColumnDataType; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class GridSelectionLayerPortData. + * + * @since 3.0.0 + */ +public class GridSelectionLayerPortData { + private SelectionLayer selectionLayer; + private IDSGridDataProvider dataProvider; + private PositionCoordinate[] rowSelectedPosition; + private int[] colIndexSelected; + private List rowCoordinate; + private Set rowSelectCountSet; + private List headerList; + private List listOfRows; + private IClientAreaProvider originalClientAreaProvider; + private int rowSelectCount; + private int rowCount; + private String columnName; + private Boolean isCellPositionSelected; + + /** + * Instantiates a new grid selection layer port data. + * + * @param selectionLayer the selection layer + * @param dataProvider the data provider + */ + public GridSelectionLayerPortData(SelectionLayer selectionLayer, IDSGridDataProvider dataProvider) { + this.selectionLayer = selectionLayer; + this.dataProvider = dataProvider; + this.rowSelectCountSet = new HashSet<>(); + this.rowCoordinate = new ArrayList<>(); + this.headerList = new ArrayList<>(); + this.listOfRows = new ArrayList<>(); + this.rowSelectCount = this.selectionLayer.getSelectedRowCount(); + this.rowSelectedPosition = this.selectionLayer.getSelectedCellPositions(); + this.colIndexSelected = this.selectionLayer.getSelectedColumnPositions(); + this.rowCount = this.selectionLayer.getRowCount(); + for (PositionCoordinate row : rowSelectedPosition) { + rowSelectCountSet.add(row.rowPosition); + + } + Iterator it = rowSelectCountSet.iterator(); + while (it.hasNext()) { + rowCoordinate.add((Integer) it.next()); + + } + } + + /** + * Gets the row coordinate. + * + * @return the row coordinate + */ + public List getRowCoordinate() { + return rowCoordinate; + } + + /** + * Gets the row count. + * + * @return the row count + */ + public int getRowCount() { + return rowCount; + } + + /** + * Finalize layer. + */ + public void finalizeLayer() { + this.selectionLayer.setClientAreaProvider(originalClientAreaProvider); + this.selectionLayer.doCommand(new TurnViewportOnCommand()); + } + + /** + * Initialize layer. + */ + public void initializeLayer() { + originalClientAreaProvider = this.selectionLayer.getClientAreaProvider(); + this.selectionLayer.doCommand(new TurnViewportOffCommand()); + + } + + /** + * Gets the cell data. + * + * @return the cell data + */ + public String getCellData() { + String cellDataValue = null; + int selectRowSize = this.rowCoordinate.size(); + if (selectRowSize > 0) { + for (int j = 0; j < selectRowSize; j++) { + for (int i = 0; i < colIndexSelected.length; i++) { + cellDataValue = getObjectString( + selectionLayer.getDataValueByPosition(colIndexSelected[i], rowCoordinate.get(j))); + } + } + } + return cellDataValue; + } + + /** + * Gets the header list. + * + * @return the header list + */ + public List getHeaderList() { + headerList.clear(); + headerList.add(null); + for (int i : colIndexSelected) { + columnName = dataProvider.getColumnDataProvider().getColumnName(selectionLayer.getColumnIndexByPosition(i)); + headerList.add(columnName); + } + return headerList; + } + + /** + * Gets the select row. + * + * @param i the i + * @param j the j + * @return the select row + */ + public Object getSelectRow(int i, int j) { + Object cellDataValue = getObjectString(selectionLayer.getDataValueByPosition(j, i)); + return cellDataValue; + } + + /** + * Gets the row. + * + * @return the row + */ + public List getRow() { + String[] cellDataValue = null; + for (int j = 0; j < this.rowCoordinate.size(); j++) { + cellDataValue = new String[this.colIndexSelected.length + 1]; + cellDataValue[0] = getObjectString(j + 1); + isCellPositionSelected = false; + for (int i = 0; i < colIndexSelected.length; i++) { + isCellPositionSelected = selectionLayer.isCellPositionSelected(colIndexSelected[i], + rowCoordinate.get(j)); + // get actual col position even after reorder + int col = selectionLayer.getColumnIndexByPosition(colIndexSelected[i]); + String colDataypeName = dataProvider.getColumnDataProvider().getColumnDataTypeName(col); + Object dataValueByPos = selectionLayer.getDataValueByPosition(colIndexSelected[i], + rowCoordinate.get(j)); + + // convert to water mark for unstructured data + if (isCellPositionSelected && colDataypeName != null && dataValueByPos != null) { + switch (colDataypeName) { + case MPPDBIDEConstants.BLOB: { + cellDataValue[i + 1] = MPPDBIDEConstants.BLOB_WATERMARK; + continue; + } + case MPPDBIDEConstants.BYTEA: { + cellDataValue[i + 1] = MPPDBIDEConstants.BYTEA_WATERMARK; + continue; + } + default: { + break; + } + } + } + cellDataValue[i + 1] = getObjectString( + selectionLayer.getDataValueByPosition(colIndexSelected[i], rowCoordinate.get(j))); + } + listOfRows.add(cellDataValue); + } + return listOfRows; + } + + /** + * Gets the excel data type. + * + * @return the excel data type + */ + public List getExcelDataType() { + + List columnList = new ArrayList(); + Object data = null; + columnList.add(ColumnDataType.STRING); + for (int j = 0; j < this.rowCoordinate.size(); j++) { + for (int i = 0; i < colIndexSelected.length; i++) { + data = selectionLayer.getDataValueByPosition(colIndexSelected[i], rowCoordinate.get(j)); + + if (data instanceof Float) { + columnList.add(ColumnDataType.DOUBLE); + } else if (data instanceof Double) { + columnList.add(ColumnDataType.DOUBLE); + } else if (data instanceof Date) { + columnList.add(ColumnDataType.DATE); + } else if (data instanceof Timestamp) { + columnList.add(ColumnDataType.DATE); + } else if (data instanceof Boolean) { + columnList.add(ColumnDataType.BOOLEAN); + } else { + columnList.add(ColumnDataType.STRING); + } + } + } + return columnList; + + } + + /** + * Gets the object string. + * + * @param data1 the data + * @return the object string + */ + private String getObjectString(Object data1) { + if (data1 instanceof Byte) { + return Byte.toString((Byte) data1); + } else if (data1 instanceof Short) { + return Short.toString((Short) data1); + } else if (data1 instanceof Integer) { + return Integer.toString((Integer) data1); + } else if (data1 instanceof Long) { + return Long.toString((Long) data1); + } else if (data1 instanceof Float) { + return Float.toString((Float) data1); + } else if (data1 instanceof Double) { + return Double.toString((Double) data1); + } else if (data1 instanceof Boolean) { + return Boolean.toString((Boolean) data1); + } else if (data1 instanceof Date) { + return ((Date) data1).toString(); + } else if (data1 instanceof Time) { + return ((Time) data1).toString(); + } else if (data1 instanceof Timestamp) { + return ((Timestamp) data1).toString(); + } else if (data1 instanceof List) { + return MPPDBIDEConstants.CURSOR_WATERMARK; + } else { + return null == data1 ? "" : data1.toString(); + } + } + + /** + * Gets the row select count. + * + * @return the row select count + */ + public int getRowSelectCount() { + return rowSelectCount; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridStatusBar.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridStatusBar.java new file mode 100644 index 0000000000000000000000000000000000000000..a3f55fd3ae34141c6bf365d11a82b0e659562f51 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridStatusBar.java @@ -0,0 +1,459 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import java.util.Observable; +import java.util.Observer; + +import javax.annotation.PreDestroy; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Label; + +import org.opengauss.mppdbide.bl.sqlhistory.IQueryExecutionSummary; +import org.opengauss.mppdbide.presentation.edittabledata.CommitStatus; +import org.opengauss.mppdbide.presentation.edittabledata.DSResultSetGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSEditGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.objectproperties.DSObjectPropertiesGridDataProvider; +import org.opengauss.mppdbide.presentation.visualexplainplan.ExecutionPlanTextDisplayGrid; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.utils.observer.IDSListener; +import org.opengauss.mppdbide.view.component.DSGridStateMachine; +import org.opengauss.mppdbide.view.component.DSGridStateMachine.State; + +/** + * + * Title: class + * + * Description: The Class GridStatusBar. + * + * @since 3.0.0 + */ +public class GridStatusBar { + private Label lblFetchedSummary; + private Label lblExecutionTime; + private Label lblOperationDesc; + private Label refreshLbl; + + private IDSGridDataProvider dataProvider; + private Composite statusCom; + + /** + * Creates the component. + * + * @param parent the parent + * @param stateMachine the state machine + * @param gridDataProvider the grid data provider + */ + public void createComponent(Composite parent, DSGridStateMachine stateMachine, + IDSGridDataProvider gridDataProvider) { + statusCom = createComposite(parent); + + addExecutionTime(statusCom); + addFetchedSummary(statusCom); + addRefreshLabel(statusCom); + addOperationDescItem(statusCom, stateMachine); + setDataProvider(gridDataProvider); + } + + private void addExecutionTime(Composite statusComposite) { + lblExecutionTime = new Label(statusComposite, SWT.BORDER); + GridData layout = new GridData(SWT.FILL, SWT.BEGINNING, true, false); + layout.widthHint = 100; + lblExecutionTime.setLayoutData(layout); + } + + private void addFetchedSummary(Composite statusComposite) { + lblFetchedSummary = new Label(statusComposite, SWT.BORDER); + GridData layout = new GridData(SWT.FILL, SWT.BEGINNING, true, false); + layout.widthHint = 10; + lblFetchedSummary.setLayoutData(layout); + } + + private void addRefreshLabel(Composite statusComposite) { + refreshLbl = new Label(statusComposite, SWT.BORDER); + refreshLbl.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLUE)); + GridData layout = new GridData(SWT.FILL, SWT.BEGINNING, true, false); + refreshLbl.setLayoutData(layout); + } + + private void addOperationDescItem(Composite statusComposite, DSGridStateMachine stateMachine) { + lblOperationDesc = new Label(statusComposite, SWT.BORDER); + GridData layout = new GridData(SWT.FILL, SWT.BEGINNING, true, false); + lblOperationDesc.setLayoutData(layout); + + stateMachine.addObserver(new Observer() { + @Override + public void update(Observable o, Object arg) { + if (arg instanceof DSGridStateMachine.State) { + DSGridStateMachine.State newState = (DSGridStateMachine.State) arg; + if (!lblOperationDesc.isDisposed()) { + lblOperationDesc.setText(newState.getDisplayMsg()); + lblOperationDesc.setToolTipText(newState.getDisplayMsg()); + } + setOperationDescColor(newState); + } + } + }); + } + + private Composite createComposite(Composite parent) { + Composite newComposite = new Composite(parent, SWT.NONE); + /* Make each row expand horizontally but not vertically */ + GridData layout = new GridData(SWT.FILL, SWT.BEGINNING, true, false); + layout.heightHint = 20; + GridLayout glayout = new GridLayout(4, false); + glayout.marginWidth = 0; + glayout.marginHeight = 0; + glayout.horizontalSpacing = 0; + glayout.verticalSpacing = 0; + newComposite.setLayout(glayout); + newComposite.setLayoutData(layout); + return newComposite; + } + + /** + * Update data provider summary data. + * + * @param dataObj the data obj + */ + public void updateDataProviderSummaryData(IDSGridDataProvider dataObj) { + if (dataObj instanceof DSResultSetGridDataProvider | dataObj instanceof ExecutionPlanTextDisplayGrid) { + IQueryExecutionSummary summary = null; + if (dataObj instanceof DSResultSetGridDataProvider) { + summary = ((DSResultSetGridDataProvider) dataObj).getSummary(); + } else { + summary = ((ExecutionPlanTextDisplayGrid) dataObj).getSummary(); + } + lblExecutionTime.setText(composeQuerySubmitTimeMsg(summary)); + + lblExecutionTime.setToolTipText(composeQuerySubmitTimeMsg(summary)); + + lblFetchedSummary.setText(composeFetchRecordSummary(dataObj, summary)); + + lblFetchedSummary.setToolTipText(composeFetchRecordSummary(dataObj, summary)); + + setEditableOrNonEditableStatusMessage(dataObj); + } + } + + /** + * Update data provider summary data. + * + * @param summary the summary + */ + public void updateDataProviderSummaryData(IQueryExecutionSummary summary) { + lblExecutionTime.setText(composeQuerySubmitTimeMsg(summary)); + lblExecutionTime.setToolTipText(composeQuerySubmitTimeMsg(summary)); + lblFetchedSummary.setText(composeExecutionTimeTaken(summary)); + lblFetchedSummary.setToolTipText(composeExecutionTimeTaken(summary)); + } + + private void setEditableOrNonEditableStatusMessage(IDSGridDataProvider dataObj) { + if (this.refreshLbl == null || this.refreshLbl.isDisposed()) { + return; + } + if (!(this.dataProvider instanceof DSObjectPropertiesGridDataProvider)) { + refreshLblSetText(dataObj); + } + } + + /** + * Sets the editable or non editable status message for data text. + * + * @param dataObj the data obj + * @param partloaded the partloaded + * @param loadedRowCnt the loaded row cnt + */ + public void setEditableOrNonEditableStatusMessageForDataText(IDSGridDataProvider dataObj, boolean partloaded, + int loadedRowCnt) { + if (this.refreshLbl == null || this.refreshLbl.isDisposed()) { + return; + } + if (!(dataObj instanceof DSObjectPropertiesGridDataProvider)) { + if (partloaded) { + refreshLbl.setText( + MessageConfigLoader.getProperty(IMessagesConstants.RESULTSET_ALL_DATALOAD_MSG, loadedRowCnt)); + refreshLbl.setToolTipText( + MessageConfigLoader.getProperty(IMessagesConstants.RESULTSET_ALL_DATALOAD_MSG, loadedRowCnt)); + } else { + refreshLbl.setText(MessageConfigLoader.getProperty(IMessagesConstants.RESULTSET_NON_EDITABLE_MSG)); + refreshLbl + .setToolTipText(MessageConfigLoader.getProperty(IMessagesConstants.RESULTSET_NON_EDITABLE_MSG)); + } + + } + } + + /** + * Sets the editable or non editable status message for data grid. + * + * @param dataObj the new editable or non editable status message for data + * grid + */ + public void setEditableOrNonEditableStatusMessageForDataGrid(IDSGridDataProvider dataObj) { + if (this.refreshLbl == null || this.refreshLbl.isDisposed()) { + return; + } + if (!(this.dataProvider instanceof DSObjectPropertiesGridDataProvider)) { + refreshLblSetText(dataObj); + + } + } + + private void refreshLblSetText(IDSGridDataProvider dataObj) { + if (dataObj instanceof IDSEditGridDataProvider) { + refreshLbl.setText(MessageConfigLoader.getProperty(IMessagesConstants.RESULTSET_EDITABLE_MSG)); + refreshLbl.setToolTipText(MessageConfigLoader.getProperty(IMessagesConstants.RESULTSET_EDITABLE_MSG)); + } else { + refreshLbl.setText(MessageConfigLoader.getProperty(IMessagesConstants.RESULTSET_NON_EDITABLE_MSG)); + refreshLbl.setToolTipText(MessageConfigLoader.getProperty(IMessagesConstants.RESULTSET_NON_EDITABLE_MSG)); + } + } + + /** + * Update edit table status. + * + * @param dataObj the data obj + */ + private void updateEditTableStatus(IDSGridDataProvider dataObj) { + if (dataObj instanceof IDSEditGridDataProvider) { + IDSEditGridDataProvider editDataProvider = (IDSEditGridDataProvider) dataObj; + CommitStatus commitStatus = editDataProvider.getLastCommitStatus(); + updateEditTableDataMsg(commitStatus); + } + } + + private String composeExecutionTimeTaken(IQueryExecutionSummary summary) { + String msg; + msg = MessageConfigLoader.getProperty(IMessagesConstants.RESULT_WINDOW_EXECUTION_TIME, + summary.getElapsedTime()); + return msg; + } + + private String composeFetchRecordSummary(IDSGridDataProvider dataProvidr, IQueryExecutionSummary summary) { + String msg; + + if (dataProvidr.isEndOfRecords() || dataProvidr.getRecordCount() == 0) { + if (summary.getNumRecordsFetched() == 1) { + msg = MessageConfigLoader.getProperty(IMessagesConstants.RESULT_WINDOW_RECORD_FETCHED_ONE, + summary.getNumRecordsFetched(), summary.getElapsedTime()); + } else { + msg = MessageConfigLoader.getProperty(IMessagesConstants.RESULT_WINDOW_RECORD_FETCHED_ALL, + summary.getNumRecordsFetched(), summary.getElapsedTime()); + } + } else { + if (summary.getNumRecordsFetched() == 1) { + msg = MessageConfigLoader.getProperty(IMessagesConstants.RESULT_WINDOW_ROW_FETCHED, + summary.getNumRecordsFetched(), summary.getElapsedTime(), + MessageConfigLoader.getProperty(IMessagesConstants.RESULT_WINDOW_RECORD_MORE)); + } else { + msg = MessageConfigLoader.getProperty(IMessagesConstants.RESULT_WINDOW_ROWS_FETCHED, + summary.getNumRecordsFetched(), summary.getElapsedTime(), + MessageConfigLoader.getProperty(IMessagesConstants.RESULT_WINDOW_RECORD_MORE)); + } + } + + return msg; + } + + private String composeQuerySubmitTimeMsg(IQueryExecutionSummary summary) { + return MessageConfigLoader.getProperty(IMessagesConstants.RESULT_WINDOW_QUERY_SUBMIT_TIME, + summary.getQueryStartDate()); + } + + /** + * Gets the update message listener. + * + * @return the update message listener + */ + public IDSListener getUpdateMessageListener() { + return new IDSListener() { + @Override + public void handleEvent(DSEvent event) { + Object dataObj = event.getObject(); + if (dataObj instanceof IDSGridDataProvider) { + updateDataProviderSummaryData((IDSGridDataProvider) dataObj); + } + } + + }; + } + + /** + * Gets the data load error listener. + * + * @param stateMachine the state machine + * @return the data load error listener + */ + public IDSListener getDataLoadErrorListener(final DSGridStateMachine stateMachine) { + return new IDSListener() { + @Override + public void handleEvent(DSEvent event) { + stateMachine.set(State.ERROR); + } + }; + } + + /** + * Gets the update edit table status. + * + * @return the update edit table status + */ + public IDSListener getUpdateEditTableStatus() { + return new IDSListener() { + @Override + public void handleEvent(DSEvent event) { + Object dataObj = event.getObject(); + if (dataObj instanceof IDSGridDataProvider) { + updateEditTableStatus((IDSGridDataProvider) dataObj); + } + } + }; + + } + + /** + * Gets the update Z edit properties status. + * + * @return the update Z edit properties status + */ + public IDSListener getUpdateZEditPropertiesStatus() { + return new IDSListener() { + @Override + public void handleEvent(DSEvent event) { + + Object dataObj = event.getObject(); + updateEditTableDataMsg((CommitStatus) dataObj); + } + }; + + } + + /** + * Update edit table data msg. + * + * @param commitStatus the commit status + */ + private void updateEditTableDataMsg(CommitStatus commitStatus) { + int successCount = (null == commitStatus) ? 0 : commitStatus.getListOfSuccessRows().size(); + int failureCount = (null == commitStatus) ? 0 : commitStatus.getListOfFailureRows().size(); + int updatedRows = (null == commitStatus) ? 0 : commitStatus.getUpdatedRecords(); + int nonExecutedRows = (null == commitStatus) ? 0 : commitStatus.getListOfNotExecutedRows().size(); + + String msg = MessageConfigLoader.getProperty(IMessagesConstants.RESULT_WINDOW_EDITTABLE_COMMIT_SUCCESS, + successCount, + MessageConfigLoader.getProperty(IMessagesConstants.RESULT_WINDOW_EDITTABLE_COMMIT_FAILURE, + failureCount), + MessageConfigLoader.getProperty(IMessagesConstants.RESULT_WINDOW_EDITTABLE_COMMIT_UPDATED, updatedRows), + MessageConfigLoader.getProperty(IMessagesConstants.RESULT_WINDOW_EDITTABLE_COMMIT_NONEXECUTED, + nonExecutedRows)); + if (!lblOperationDesc.isDisposed()) { + lblOperationDesc.setText(msg); + lblOperationDesc.setToolTipText(msg); + } + if (!(this.dataProvider instanceof DSObjectPropertiesGridDataProvider)) { + if (!refreshLbl.isDisposed()) { + refreshLbl.setText( + MessageConfigLoader.getProperty(IMessagesConstants.RESULT_WINDOW_EDITTABLE_COMMIT_REFRESH)); + refreshLbl.setToolTipText( + MessageConfigLoader.getProperty(IMessagesConstants.RESULT_WINDOW_EDITTABLE_COMMIT_REFRESH)); + } + } + if (failureCount > 0) { + setOperationDescColor(DSGridStateMachine.State.ERROR); + } else if (successCount > 0) { + setOperationDescColor(DSGridStateMachine.State.LOADING); + } else { + setOperationDescColor(DSGridStateMachine.State.IDLE); + } + } + + /** + * Handle data edit event. + */ + public void handleDataEditEvent() { + + if (this.dataProvider instanceof IDSEditGridDataProvider) { + IDSEditGridDataProvider editDP = (IDSEditGridDataProvider) this.dataProvider; + StringBuilder strBlr = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + final String statusBreak = " / "; + setEditableOrNonEditableStatusMessage(this.dataProvider); + strBlr.append(MessageConfigLoader.getProperty(IMessagesConstants.GRID_EDIT_STATUS_INSERTED)); + strBlr.append(editDP.getInsertedRowCount()); + strBlr.append(statusBreak); + strBlr.append(MessageConfigLoader.getProperty(IMessagesConstants.GRID_EDIT_STATUS_UPDATED)); + strBlr.append(editDP.getUpdatedRowCount()); + strBlr.append(statusBreak); + strBlr.append(MessageConfigLoader.getProperty(IMessagesConstants.GRID_EDIT_STATUS_DELETED)); + strBlr.append(editDP.getDeletedRowCount()); + if (!lblOperationDesc.isDisposed()) { + lblOperationDesc.setText(strBlr.toString()); + lblOperationDesc.setToolTipText(strBlr.toString()); + setOperationDescColor(DSGridStateMachine.State.IDLE); + } + } + + } + + private void setOperationDescColor(DSGridStateMachine.State state) { + int fgColor = state.getColor(); + if (null != lblOperationDesc && !lblOperationDesc.isDisposed()) { + lblOperationDesc.setForeground(Display.getDefault().getSystemColor(fgColor)); + } + } + + /** + * Sets the data provider. + * + * @param dataProvider the new data provider + */ + public void setDataProvider(IDSGridDataProvider dataProvider) { + this.dataProvider = dataProvider; + } + + /** + * Pre destroy. + */ + @PreDestroy + public void preDestroy() { + dataProvider = null; + } + + /** + * Show status bar. + */ + public void showStatusBar() { + + GridUIUtils.toggleCompositeSectionVisibility(statusCom, false, null, false); + } + + /** + * Hide status bar. + */ + public void hideStatusBar() { + + GridUIUtils.toggleCompositeSectionVisibility(statusCom, true, null, false); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridToolbar.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridToolbar.java new file mode 100644 index 0000000000000000000000000000000000000000..ebaa3bdb244e76e528026c3e25f1ab02fc51eec4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridToolbar.java @@ -0,0 +1,2379 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Locale; +import java.util.Observable; +import java.util.Observer; + +import javax.annotation.PreDestroy; + +import org.eclipse.jface.action.ToolBarManager; +import org.eclipse.jface.layout.GridDataFactory; +import org.eclipse.nebula.widgets.nattable.layer.ILayerListener; +import org.eclipse.nebula.widgets.nattable.layer.event.ILayerEvent; +import org.eclipse.nebula.widgets.nattable.selection.event.CellSelectionEvent; +import org.eclipse.nebula.widgets.nattable.selection.event.ColumnSelectionEvent; +import org.eclipse.nebula.widgets.nattable.selection.event.RowSelectionEvent; +import org.eclipse.nebula.widgets.nattable.viewport.command.ShowRowInViewportCommand; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.FontMetrics; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.ToolBar; +import org.eclipse.swt.widgets.ToolItem; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.explainplan.ui.model.ExplainAnalyzePlanNodeTreeDisplayDataTreeFormat; +import org.opengauss.mppdbide.presentation.edittabledata.DSResultSetGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSEditGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.objectproperties.IObjectPropertyData; +import org.opengauss.mppdbide.presentation.visualexplainplan.ExecutionPlanTextDisplayGrid; +import org.opengauss.mppdbide.utils.DsEncodingEnum; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.utils.observer.DSEventTable; +import org.opengauss.mppdbide.utils.observer.IDSGridUIListenable; +import org.opengauss.mppdbide.utils.observer.IDSListener; +import org.opengauss.mppdbide.view.component.DSGridStateMachine; +import org.opengauss.mppdbide.view.component.grid.core.DataGrid; +import org.opengauss.mppdbide.view.component.grid.core.DataText; +import org.opengauss.mppdbide.view.handler.IHandlerUtilities; +import org.opengauss.mppdbide.view.ui.DatabaseListControl; +import org.opengauss.mppdbide.view.utils.UIElement; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * + * Title: class + * + * Description: The Class GridToolbar. + * + * @since 3.0.0 + */ +public class GridToolbar implements Observer { + private Composite toolbarComposite; + private ToolBar toolbar; + private ToolItem copyItem; + private ToolItem copyAdvancedItem; + private ToolItem exportAllItem; + private ToolItem exportCurrentItem; + private ToolItem exportExecutionPlan; + private ToolItem toggleSearchArea; + private ToolItem toggleSqlArea; + private ToolItem multiColumnSort; + private ToolItem clearSort; + private ToolItem insertRow; + private ToolItem deleteRow; + private ToolItem commitRecord; + private ToolItem rollbackChanges; + private ToolItem refresh; + private ToolItem pasteData; + + private ToolItem savePlan; + private ToolItem textView; + private ToolItem treeView; + + private DSEventTable eventEditTable; + private IDSGridDataProvider dataProvider; + private ToolItem forgetOption; + private boolean forgetOptionisEnabled; + private DSGridStateMachine dsExportState; + private DSGridStateMachine dsRefreshState; + + private Database resultTabDB; + private boolean deleteRowState; + private boolean isSearched; + + private boolean copyAdvanceFlag; + private boolean insertRowFlag; + private boolean deleteRowFlag; + private boolean commitRecordFlag; + private boolean rollbackChangesFlag; + private boolean forgetOptionFlag; + private boolean pasteDataFlag; + private boolean multiColumnSortFlag; + private boolean clearSortFlag; + private boolean exportCurrentItemFlag; + private boolean exportAllItemFlag; + private boolean comboFlag; + private int gridAndTextButSwitchCount; + + private Label batchDropObjectsParent; + private Label batchDropRuns; + private Label batchDropErrors; + private Button batchDropCascadeBtn; + private Button batchDropAtomicBtn; + private Button batchDropStartBtn; + private Button batchDropStopBtn; + private Combo combo; + private ArrayList dsEncodingList; + private ILayerListener iLayerListener; + private DataGrid dataGrid; + private boolean isExplainQuery; + private ToolItem showGrid; + private ToolItem showText; + private DSGridComponent dsGridComponent; + + private HashMap toolManagerMap; + + private final Object INSTANCE_LOCK = new Object(); + + private ToolItem loadMoreRecord; + + /** + * Gets the tool manager map. + * + * @return the tool manager map + */ + public HashMap getToolManagerMap() { + return toolManagerMap; + } + + /** + * Creates the component. + * + * @param parent the parent + * @param gridDataProvider the grid data provider + * @param dsGrid the ds grid + */ + public void createComponent(Composite parent, IDSGridDataProvider gridDataProvider, DSGridComponent dsGrid) { + this.toolbarComposite = createComposite(parent); + GridLayout gl = (GridLayout) this.toolbarComposite.getLayout(); + gl.numColumns = 2; + toolbarComposite.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false, false, 2, 0)); + ToolBarManager toolbarMgr = new ToolBarManager(); + setDataProvider(gridDataProvider); + toolbarMgr.setStyle(SWT.FLAT); + this.toolbar = toolbarMgr.createControl(this.toolbarComposite); + this.dsGridComponent = dsGrid; + DatabaseListControl databaseListControl = UIElement.getInstance().getDatabaseListControl(); + if (null != databaseListControl) { + databaseListControl.addObserver(this); + } + dsEncodingList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + toolManagerMap = new HashMap(); + } + + /** + * + * @param txt Name to be displayed on the tool bar item. Can be empty if + * only image is expected. + * @param imgPath Image path understandable by IconUtility. + * @param swtType Supports SWT.PUSH, SWT.CHECK, SWT.RADIO, SWT.SEPARATOR, + * SWT.DROP_DOWN + * @return Tool bar button/item + */ + private ToolItem getToolItem(int swtType, String txt, String imgPath, String toolTip) { + ToolItem item = new ToolItem(this.toolbar, swtType); + if (txt != null) { + item.setText(txt); + } + + if (imgPath != null) { + Image icon = IconUtility.getIconImage(imgPath, getClass()); + item.setImage(icon); + } + + return item; + } + + private Composite createComposite(Composite parent) { + Composite newComp = new Composite(parent, SWT.NONE); + DSGridComponent.setLayoutProperties(newComp); + GridDataFactory.fillDefaults().grab(true, false).applyTo(newComp); + return newComp; + } + + /** + * Adds the item copy. + * + * @param stateMachine the state machine + */ + public void addItemCopy(DSGridStateMachine stateMachine, boolean isOltpCreateTable) { + String toolTipMsg = MessageConfigLoader.getProperty(IMessagesConstants.COPY_RESULT_WINDOW_CONTENTS); + this.copyItem = getToolItem(SWT.PUSH, null, IiconPath.ICO_COPY, toolTipMsg); + toolManagerMap.put(ToolBarConstants.COPY_TOOLITEM, this.copyItem); + this.copyItem.setToolTipText(toolTipMsg); + this.copyItem.setEnabled(IHandlerUtilities.getExportDataSelectionOptions()); + this.copyItem.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent event) { + if (!isOltpCreateTable && IHandlerUtilities.disableToolBarIfEnabled(copyItem, + IHandlerUtilities.getExportDataSelectionOptions())) { + return; + } + + if (null != dsGridComponent.getDataText()) { + if (showGrid.getSelection()) { + dsGridComponent.getDataGrid().doCopy(); + } else if (showText.getSelection()) { + dsGridComponent.getDataText().doCopy(); + } + } else { + dsGridComponent.getDataGrid().doCopy(); + } + + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + // Ignore + } + }); + + stateMachine.addObserver(new Observer() { + @Override + public void update(Observable observable, Object arg) { + if (arg instanceof DSGridStateMachine.State) { + DSGridStateMachine.State newState = (DSGridStateMachine.State) arg; + if (!toolbar.isDisposed()) { + copyItem.setEnabled(newState != DSGridStateMachine.State.LOADING); + IHandlerUtilities.setToolItemEnabled(copyItem, + IHandlerUtilities.getExportDataSelectionOptions()); + } + + } + } + }); + } + + /** + * Adds the item advanced copy. + * + * @param stateMachine the state machine + */ + public void addItemAdvancedCopy(DSGridStateMachine stateMachine) { + String toolTipMsg = MessageConfigLoader.getProperty(IMessagesConstants.COPY_ADVANCED_RESULT_WINDOW_CONTENTS); + this.copyAdvancedItem = getToolItem(SWT.PUSH, null, IiconPath.ICO_COPY_ADVANCED, toolTipMsg); + this.copyAdvancedItem.setToolTipText(toolTipMsg); + this.copyAdvancedItem.setEnabled(IHandlerUtilities.getExportDataSelectionOptions()); + this.copyAdvancedItem.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent event) { + if (IHandlerUtilities.disableToolBarIfEnabled(copyAdvancedItem, + IHandlerUtilities.getExportDataSelectionOptions())) { + return; + } + dsGridComponent.getDataGrid().doAdvancedCopy(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + // Ignore + } + }); + + stateMachine.addObserver(new Observer() { + @Override + public void update(Observable observable, Object arg) { + if (arg instanceof DSGridStateMachine.State) { + DSGridStateMachine.State newState = (DSGridStateMachine.State) arg; + if (!toolbar.isDisposed()) { + copyAdvancedItem.setEnabled(newState != DSGridStateMachine.State.LOADING); + IHandlerUtilities.setToolItemEnabled(copyAdvancedItem, + IHandlerUtilities.getExportDataSelectionOptions()); + } + } + } + }); + + } + + /** + * Adds the item paste cells. + * + * @param eventTable the event table + * @param stateMachine the state machine + */ + public void addItemPasteCells(DSEventTable eventTable, DSGridStateMachine stateMachine) { + + if (dsGridComponent.getDataGrid().isPropertiesGrid()) { + return; + } + dsGridComponent.getDataGrid().commitAndCloseActiveCellEditor(); + String toolTip = MessageConfigLoader.getProperty(IMessagesConstants.PASTE_TOOTIP); + pasteData = getToolItem(SWT.PUSH, null, IiconPath.ICO_PASTE, toolTip); + this.pasteData.setToolTipText(toolTip); + this.pasteData.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent event) { + + dsGridComponent.getDataGrid().paste(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + + } + }); + + } + + /** + * Adds the item export current page. + * + * @param eventTable the event table + * @param stateMachine the state machine + */ + public void addItemExportCurrentPage(final DSEventTable eventTable, final DSGridStateMachine stateMachine) { + this.exportCurrentItem = getToolItem(SWT.PUSH, null, IiconPath.ICO_EXPORT_CURRENT_PAGE, + MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_CSV)); + this.exportCurrentItem.setToolTipText(MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_CSV)); + this.exportCurrentItem.setEnabled(IHandlerUtilities.getExportDataSelectionOptions()); + this.exportCurrentItem.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent event) { + if (IHandlerUtilities.disableToolBarIfEnabled(exportCurrentItem, + IHandlerUtilities.getExportDataSelectionOptions())) { + return; + } + + if (stateMachine.set(DSGridStateMachine.State.EXPORTING)) { + eventTable.sendEvent( + new DSEvent(IDSGridUIListenable.LISTEN_TYPE_EXPORT_CURR_PAGE_DATA, new Observer() { + @Override + public void update(Observable observable, Object arg) { + if (arg instanceof Boolean && ((boolean) arg)) { + stateMachine.set(DSGridStateMachine.State.IDLE); + } + } + })); + } + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + + } + }); + + stateMachine.addObserver(new Observer() { + @Override + public void update(Observable observable, Object arg) { + if (arg instanceof DSGridStateMachine.State) { + DSGridStateMachine.State newState = (DSGridStateMachine.State) arg; + if (!toolbar.isDisposed()) { + exportCurrentItem.setEnabled(newState != DSGridStateMachine.State.EXPORTING + && newState != DSGridStateMachine.State.LOADING); + IHandlerUtilities.setToolItemEnabled(exportCurrentItem, + IHandlerUtilities.getExportDataSelectionOptions()); + } + + } + } + }); + } + + /** + * Adds the item export execution plan. + * + * @param eventTable the event table + * @param stateMachine the state machine + */ + public void addItemExportExecutionPlan(final DSEventTable eventTable, final DSGridStateMachine stateMachine) { + this.exportExecutionPlan = getToolItem(SWT.PUSH, null, IiconPath.ICO_EXPORT_CURRENT_PAGE, + MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_EXEC)); + this.exportExecutionPlan.setToolTipText(MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_EXEC)); + this.exportExecutionPlan.setEnabled(IHandlerUtilities.getExportDataSelectionOptions()); + this.exportExecutionPlan.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent event) { + if (IHandlerUtilities.disableToolBarIfEnabled(exportExecutionPlan, + IHandlerUtilities.getExportDataSelectionOptions())) { + return; + } + + if (stateMachine.set(DSGridStateMachine.State.EXPORTING)) { + eventTable.sendEvent( + new DSEvent(IDSGridUIListenable.LISTEN_TYPE_EXPORT_CURR_PAGE_DATA, new Observer() { + @Override + public void update(Observable observable, Object obj) { + if (obj instanceof Boolean && ((boolean) obj)) { + stateMachine.set(DSGridStateMachine.State.IDLE); + } + } + })); + } + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectEvent) { + + } + }); + + stateMachine.addObserver(new Observer() { + @Override + public void update(Observable observable, Object obj) { + if (obj instanceof DSGridStateMachine.State) { + DSGridStateMachine.State newState = (DSGridStateMachine.State) obj; + if (!toolbar.isDisposed()) { + exportExecutionPlan.setEnabled(newState != DSGridStateMachine.State.EXPORTING + && newState != DSGridStateMachine.State.LOADING); + IHandlerUtilities.setToolItemEnabled(exportExecutionPlan, + IHandlerUtilities.getExportDataSelectionOptions()); + } + + } + } + }); + } + + /** + * Adds the item export all. + * + * @param eventTable the event table + * @param stateMachine the state machine + */ + public void addItemExportAll(final DSEventTable eventTable, final DSGridStateMachine stateMachine, + boolean isCursorPopup) { + + this.exportAllItem = getToolItem(SWT.PUSH, null, IiconPath.ICO_EXPORT_ALL_DATA, + MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_CSV_STAR)); + this.exportAllItem.setToolTipText(MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_CSV_STAR)); + this.exportAllItem.setEnabled(IHandlerUtilities.getExportDataSelectionOptions()); + this.exportAllItem.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent event) { + if (IHandlerUtilities.disableToolBarIfEnabled(exportAllItem, + IHandlerUtilities.getExportDataSelectionOptions())) { + return; + } + + if (stateMachine.set(DSGridStateMachine.State.EXPORTING)) { + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_EXPORT_ALL_DATA, new Observer() { + // once Export is over ImportExportDataCore, + // we will be notified here. + @Override + public void update(Observable observable, Object arg) { + // If export is not progress then Update + // state machine + if (arg instanceof Boolean && !((boolean) arg)) { + stateMachine.set(DSGridStateMachine.State.IDLE); + } + } + })); + } + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + + } + }); + if (!isCursorPopup) { + setExplainQuery(); + } + stateMachine.addObserver(new Observer() { + @Override + public void update(Observable observable, Object arg) { + if (arg instanceof DSGridStateMachine.State) { + enableDisableExportAllButton(); + } + } + }); + } + + /** + * Adds the item multi sort. + * + * @param multiColumnSortPoUpListener the multi column sort po up listener + */ + public void addItemMultiSort(final SelectionListener multiColumnSortPoUpListener) { + String toolTipMsg = MessageConfigLoader.getProperty(IMessagesConstants.GRIDDATA_SORT); + this.multiColumnSort = getToolItem(SWT.PUSH, null, IiconPath.ICO_SORT_MULTI_COLUMN, toolTipMsg); + this.multiColumnSort.setToolTipText(toolTipMsg); + + this.multiColumnSort.addSelectionListener(multiColumnSortPoUpListener); + + } + + /** + * Adds the item clear sort. + */ + public void addItemClearSort() { + String toolTipMsg = MessageConfigLoader.getProperty(IMessagesConstants.CLEAR_SORT); + this.clearSort = getToolItem(SWT.PUSH, null, IiconPath.ICO_SORT_CLEAR, toolTipMsg); + this.clearSort.setToolTipText(toolTipMsg); + + this.clearSort.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent event) { + dsGridComponent.getDataGrid().clearSort(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + + } + }); + + } + + /** + * Adds the item toggle query area. + * + * @param queryArea the query area + */ + public void addItemToggleQueryArea(final GridQueryArea queryArea) { + this.toggleSqlArea = getToolItem(SWT.PUSH, null, IiconPath.SQL_BAR_TOGGLE_ENABLE, + MessageConfigLoader.getProperty(IMessagesConstants.RESULT_WINDOW_EXECUTED_QUERY_TOOLTIP)); + this.toggleSqlArea.setToolTipText(MessageConfigLoader.getProperty(IMessagesConstants.SHOW_HIDE_QUERY_BAR)); + final ToolItem item = this.toggleSqlArea; + this.toggleSqlArea.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent event) { + if (queryArea.isQuueryAreaVisible()) { + queryArea.doHideQueryArea(); + item.setImage(IconUtility.getIconImage(IiconPath.SQL_BAR_TOGGLE_DISABLE, getClass())); + } else { + queryArea.doShowQueryArea(); + item.setImage(IconUtility.getIconImage(IiconPath.SQL_BAR_TOGGLE_ENABLE, getClass())); + } + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + + } + }); + } + + /** + * Update toggle query area image. + */ + public void updateToggleQueryAreaImage() { + final ToolItem item = this.toggleSqlArea; + item.setImage(IconUtility.getIconImage(IiconPath.SQL_BAR_TOGGLE_DISABLE, getClass())); + } + + /** + * Adds the item toggle search area. + * + * @param searchArea the search area + */ + public void addItemToggleSearchArea(final GridSearchArea searchArea) { + this.toggleSearchArea = getToolItem(SWT.PUSH, null, IiconPath.SEARCH_BAR_TOGGLE_ENABLE, + MessageConfigLoader.getProperty(IMessagesConstants.RESULT_WINDOW_EXECUTED_QUERY_TOOLTIP)); + final ToolItem item = this.toggleSearchArea; + this.toggleSearchArea.setToolTipText(MessageConfigLoader.getProperty(IMessagesConstants.SHOW_HIDE_SEARCH_BAR)); + this.toggleSearchArea.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent event) { + if (searchArea.isSearchAreaVisible()) { + searchArea.doHideSearchArea(); + item.setImage(IconUtility.getIconImage(IiconPath.SEARCH_BAR_TOGGLE_DISABLE, getClass())); + } else { + searchArea.doShowSearchArea(); + item.setImage(IconUtility.getIconImage(IiconPath.SEARCH_BAR_TOGGLE_ENABLE, getClass())); + } + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + + } + }); + } + + /** + * Adds the item insert row. + * + * @param eventTable the event table + * @param stateMachine the state machine + */ + public void addItemInsertRow(DSEventTable eventTable, DSGridStateMachine stateMachine) { + + final DataGrid grid = dsGridComponent.getDataGrid(); + final ServerObjectTypeForDialog type = grid.getTypeOfDialogRequired(); + grid.commitAndCloseActiveCellEditor(); + String toolTip = MessageConfigLoader.getProperty(IMessagesConstants.INSERT_ROW_TOOLTIP); + this.insertRow = getToolItem(SWT.PUSH, null, IiconPath.ICO_EDIT_ADD, toolTip); + toolManagerMap.put(ToolBarConstants.ADD_TOOLITEM, this.insertRow); + this.insertRow.setToolTipText(toolTip); + /* + * The general tab of the properties window of a table should not have + * insert button enabled + */ + if (type != null && type == ServerObjectTypeForDialog.GENERAL) { + insertRow.setEnabled(false); + return; + } + this.insertRow.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent event) { + if (grid.isPropertiesGrid()) { + + // code for properties window insert operation + AddPropertiesInfoDialog dialog = new AddPropertiesInfoDialog(type, grid.getDataGrid().getShell(), + (TableMetaData) dataProvider.getTable()); + dialog.createDialog(); + + // serverObject is null when user press cancel or close in + // dialog + if (dialog.getServerObject() == null) { + return; + } + grid.insertEmptyRow(isSearched, dialog.getServerObject()); + + } else { + grid.insertEmptyRow(isSearched, null); + } + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + + } + }); + + stateMachine.addObserver(new Observer() { + @Override + public void update(Observable observable, Object arg) { + if (arg instanceof DSGridStateMachine.State) { + DSGridStateMachine.State newState = (DSGridStateMachine.State) arg; + if (!insertRow.isDisposed()) { + insertRow.setEnabled(newState != DSGridStateMachine.State.LOADING); + } + } + } + }); + + } + + /** + * Adds the item delete row. + * + * @param eventTable the event table + * @param stateMachine the state machine + */ + public void addItemDeleteRow(DSEventTable eventTable, DSGridStateMachine stateMachine) { + final DataGrid grid = dsGridComponent.getDataGrid(); + String toolTip = MessageConfigLoader.getProperty(IMessagesConstants.DELETE_ROW_TOOLTIP); + this.deleteRow = getToolItem(SWT.PUSH, null, IiconPath.ICO_EDIT_DELETE, toolTip); + toolManagerMap.put(ToolBarConstants.DELETE_TOOLITEM, this.deleteRow); + this.deleteRow.setEnabled(false); + this.deleteRow.setToolTipText(toolTip); + setEventEditTable(eventTable); + /* + * The general tab of the properties window of a table should not have + * delete button enabled + */ + if (dataProvider instanceof IObjectPropertyData) { + String objectPropertyName = ((IObjectPropertyData) dataProvider).getObjectPropertyName(); + if (objectPropertyName != null && objectPropertyName.equals("General")) { + deleteRow.setEnabled(false); + return; + } + } + setRowListener(grid, eventTable); + this.deleteRow.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent event) { + grid.closeEditor(); + grid.deleteRow(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + + } + }); + + } + + private void setRowListener(final DataGrid grid, DSEventTable eventTable) { + iLayerListener = new ILayerListener() { + @Override + public void handleLayerEvent(ILayerEvent event) { + boolean isEncodingChanged = false; + if (event instanceof CellSelectionEvent || event instanceof RowSelectionEvent + || event instanceof ColumnSelectionEvent) { + deleteRowState = true; + if (dataProvider instanceof DSResultSetGridDataProvider + && ((DSResultSetGridDataProvider) dataProvider).isIncludeEncoding() + && ((DSResultSetGridDataProvider) dataProvider).isEncodingChanged()) { + isEncodingChanged = true; + } + deleteRow.setEnabled(dataProvider.getDatabse() != null && dataProvider.getDatabse().isConnected() + && (grid.isRowsOnlySelected() && !isEncodingChanged)); + } + deleteRowState = false; + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_ROW_SELECTED, grid.isRowsOnlySelected())); + } + }; + grid.addGridLayerListener(iLayerListener); + dataGrid = grid; + } + + /** + * Adds the item commit record. + * + * @param eventTable the event table + * @param stateMachine the state machine + */ + public void addItemCommitRecord(final DSEventTable eventTable, DSGridStateMachine stateMachine) { + final DataGrid grid = dsGridComponent.getDataGrid(); + final DataText text = dsGridComponent.getDataText(); + grid.commitAndCloseActiveCellEditor(); + + final CommitRecordEventData commitEventData = new CommitRecordEventData(); + commitEventData.setDatagrid(grid); + commitEventData.setDataText(text); + commitEventData.setEventTable(eventTable); + setEventEditTable(eventTable); + + String toolTip = MessageConfigLoader.getProperty(IMessagesConstants.COMMIT_CHANGES_TOOLTIP); + this.commitRecord = getToolItem(SWT.PUSH, null, IiconPath.ICO_EDIT_COMMIT, toolTip); + toolManagerMap.put(ToolBarConstants.COMMIT_TOOLITEM, this.commitRecord); + this.commitRecord.setToolTipText(toolTip); + commitRecord.setEnabled(false); + this.commitRecord.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent event) { + commitEventData.setDataProvider(dataProvider); + commitRecord.setEnabled(false); + if (rollbackChanges != null) { + rollbackChanges.setEnabled(false); + } + eventTable.sendEvent( + new DSEvent(IDSGridUIListenable.LISTEN_TYPE_PROPERITES_COMMIT_DATA, commitEventData)); + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_EDITTABLE_COMMIT_DATA, commitEventData)); + + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + + } + }); + } + + /** + * Gets the tool bar. + * + * @return the tool bar + */ + public ToolBar getToolBar() { + return this.toolbar; + } + + /** + * Adds the item roll back changes. + * + * @param eventTable the event table + * @param stateMachine the state machine + */ + public void addItemRollBackChanges(final DSEventTable eventTable, DSGridStateMachine stateMachine) { + String toolTip = MessageConfigLoader.getProperty(IMessagesConstants.ROLLBACK_CHANGES_TOOLTIP); + this.rollbackChanges = getToolItem(SWT.PUSH, null, IiconPath.ICO_DELETE, toolTip); + toolManagerMap.put(ToolBarConstants.CANCEL_TOOLITEM, this.rollbackChanges); + this.rollbackChanges.setToolTipText(toolTip); + + this.rollbackChanges.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent event) { + rollbackChangesForEditedData(eventTable); + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + + } + }); + } + + private void rollbackChangesForEditedData(final DSEventTable eventTable) { + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_EDITTABLE_ROLLBACK_DATA, null)); + dsGridComponent.getDataGrid().closeEditor(); + dsGridComponent.getDataGrid().rollBackChanges(); + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LIRTEN_ROLLBACK_PROPERTIES, dataProvider)); + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_EDITTABLE_ROLLBACK_DATA_COMPLETE, dataProvider)); + } + + /** + * Adds the refresh item. + * + * @param eventTable the event table + * @param stateMachine the state machine + */ + public void addRefreshItem(DSEventTable eventTable, DSGridStateMachine stateMachine) { + this.refresh = getToolItem(SWT.PUSH, null, IiconPath.ICO_REFRESH, ""); + toolManagerMap.put(ToolBarConstants.REFRESH_TOOLITEM, this.refresh); + if (null != dsGridComponent.getDataText() && dsGridComponent.getDataText().isInitDataTextFlag()) { + refresh.setEnabled(false); + } + setEventEditTable(eventTable); + this.refresh.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent event) { + if (null != dsGridComponent.getDataText()) { + dsGridComponent.getDataText().setRefreshFlag(true); + } + dsGridComponent.getDataGrid().closeEditor(); + dsGridComponent.getDataGrid().refresh(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + } + }); + + stateMachine.addObserver(new Observer() { + @Override + public void update(Observable observable, Object arg) { + if (arg instanceof DSGridStateMachine.State) { + DSGridStateMachine.State newState = (DSGridStateMachine.State) arg; + if (!refresh.isDisposed()) { + refresh.setEnabled(newState != DSGridStateMachine.State.LOADING); + } + } + } + }); + updateRefreshButtonTooltip(true); + } + + /** + * Adds the forget item. + * + * @param eventTable the event table + */ + public void addForgetItem(final DSEventTable eventTable) { + if (dsGridComponent.getDataGrid().isPropertiesGrid()) { + return; + } + this.forgetOption = getToolItem(SWT.PUSH, null, IiconPath.ICON_EDITTABLE_FORGET_DISABLE, null); + this.forgetOption.setToolTipText(MessageConfigLoader.getProperty(IMessagesConstants.EDIT_TABLE_FORGET_OPTIONS)); + setForgotOptionEnabled(false); + + this.forgetOption.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent event) { + if (GridToolbar.this.forgetOptionisEnabled) { + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_EDITTABLE_USER_FORGET_OPTION, null)); + setForgotOptionEnabled(false); + } + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + // Nothing to do. ignore. + } + }); + } + + /** + * Adds the encoding. + * + * @param eventTable the event table + * @param defaultEncoding the default encoding + */ + public void addEncoding(final DSEventTable eventTable, String defaultEncoding) { + + // Add a separator pipe + new ToolItem(toolbar, SWT.SEPARATOR); + + ToolItem seperatorLabel = new ToolItem(toolbar, SWT.SEPARATOR); + + Label encodingLbl = new Label(toolbar, SWT.NONE); + encodingLbl.setText(MessageConfigLoader.getProperty(IMessagesConstants.ENCODING_MSG) + " : "); + encodingLbl.pack(); + seperatorLabel.setWidth(encodingLbl.getSize().x); + seperatorLabel.setControl(encodingLbl); + + ToolItem sep = new ToolItem(toolbar, SWT.SEPARATOR); + + combo = new Combo(this.toolbar, SWT.READ_ONLY); + for (DsEncodingEnum dsEncoding : DsEncodingEnum.values()) { + + dsEncodingList.add(dsEncoding.getEncoding()); + } + for (String encoding : dsEncodingList) { + + combo.add(encoding); + } + + for (String item : dsEncodingList) { + if (item.equals(defaultEncoding)) { + combo.setText(item); + } + } + combo.pack(); + if (null != dsGridComponent.getDataText() && dsGridComponent.getDataText().isInitDataTextFlag()) { + combo.setEnabled(false); + } + combo.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent event) { + if (null != dsGridComponent.getDataText()) { + dsGridComponent.getDataText().setEndodingFlag(true); + } + String selectedEncoding = combo.getItem(combo.getSelectionIndex()); + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_DATA_CHANGE_ENCODING, selectedEncoding)); + if (dataProvider instanceof DSResultSetGridDataProvider + && ((DSResultSetGridDataProvider) dataProvider).isEditSupported()) { + + rollbackChangesForEditedData(eventTable); + } + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + } + }); + sep.setWidth(combo.getSize().x); + sep.setControl(combo); + } + + /** + * Gets the selected encoding. + * + * @return the selected encoding + */ + public String getSelectedEncoding() { + if (combo != null) { + return combo.getText(); + } + return null; + } + + private void setForgotOptionEnabled(boolean isEnabled) { + this.forgetOptionisEnabled = isEnabled; + setIconToDisplay(); + } + + // To enable or disable ICON_EDITTABLE_FORGET + private void setIconToDisplay() { + String iconToDisplay = (forgetOptionisEnabled) ? IiconPath.ICON_EDITTABLE_FORGET_ENABLE + : IiconPath.ICON_EDITTABLE_FORGET_DISABLE; + if (!this.forgetOption.isDisposed()) { + this.forgetOption.setImage(IconUtility.getIconImage(iconToDisplay, getClass())); + } + } + + private void updateRefreshButtonTooltip(boolean isEnabled) { + String toolTip = ""; + if (isEnabled) { + toolTip = MessageConfigLoader.getProperty(IMessagesConstants.REFRESH_TABLE_TOOLTIP); + } else { + toolTip = MessageConfigLoader.getProperty(IMessagesConstants.REFRESH_TABLE_TOOLTIP_DISABLED); + } + + this.refresh.setToolTipText(toolTip); + } + + /** + * Handle data edit event. + * + * @param isDbConnected the is db connected + */ + public void handleDataEditEvent(boolean isDbConnected) { + if (this.dataProvider instanceof IDSEditGridDataProvider) { + IDSEditGridDataProvider editDP = (IDSEditGridDataProvider) dataProvider; + boolean isEdited = editDP.isGridDataEdited(); + + handleEditDataProvider(isDbConnected, isEdited); + } + } + + /** + * Handle non edit events + * + * @param isDbConnected the is db connected + */ + public void handleNonDataEditEvent(boolean isDbConnected) { + if (this.refresh != null && !this.refresh.isDisposed()) { + this.refresh.setEnabled(!isSearched && isDbConnected); + } + + if (this.exportAllItem != null && !this.exportAllItem.isDisposed()) { + this.exportAllItem.setEnabled(isDbConnected && IHandlerUtilities.getExportDataSelectionOptions()); + } + + if (isDbConnected) { + resetLoadMoreRecordStatus(); + } else { + if (this.loadMoreRecord != null && !this.loadMoreRecord.isDisposed()) { + this.loadMoreRecord.setEnabled(false); + } + } + } + + private void handleEditDataProvider(boolean isDbConnected, boolean isEdited) { + handleRefreshButtonEnabling(isDbConnected, isEdited); + handleCommitButtonEnabling(isDbConnected, isEdited); + handleRollbackButtonEnabling(isDbConnected, isEdited); + + if (this.exportCurrentItem != null && !this.exportCurrentItem.isDisposed()) { + this.exportCurrentItem.setEnabled(true); + } + + IHandlerUtilities.setToolItemEnabled(exportCurrentItem, IHandlerUtilities.getExportDataSelectionOptions()); + + if (this.exportAllItem != null && !this.exportAllItem.isDisposed()) { + this.exportAllItem + .setEnabled(isDbConnected && IHandlerUtilities.getExportDataSelectionOptions() && !isEdited); + } + + if (this.insertRow != null && !this.insertRow.isDisposed()) { + this.insertRow.setEnabled(isDbConnected && !dsExportState.isLoading() + && checkForConditionalEnableDisable(isDbConnected) && !isEncodingToBeModified()); + } + if (this.deleteRow != null && !this.deleteRow.isDisposed()) { + this.deleteRow.setEnabled(isDbConnected && deleteRowState && checkForConditionalEnableDisable(isDbConnected) + && !isEncodingToBeModified()); + } + if (this.pasteData != null && !this.pasteData.isDisposed()) { + this.pasteData.setEnabled(isDbConnected && !isEncodingToBeModified()); + } + handShowGridAndShowTextButEnabling(isDbConnected); + + if (isDbConnected) { + resetLoadMoreRecordStatus(); + } else { + if (this.loadMoreRecord != null && !this.loadMoreRecord.isDisposed()) { + this.loadMoreRecord.setEnabled(false); + } + } + + } + + private void handShowGridAndShowTextButEnabling(boolean isDbConnected) { + if (this.showGrid != null && !this.showGrid.isDisposed()) { + this.showGrid.setEnabled(isDbConnected); + } + if (this.showText != null && !this.showText.isDisposed()) { + this.showText.setEnabled(isDbConnected); + } + if (null != this.dsGridComponent.getDataText() && null != this.showText && !this.showText.isDisposed() + && showText.getSelection()) { + disableButtons(); + } + } + + private void handleRollbackButtonEnabling(boolean isDbConnected, boolean isEdited) { + if (this.rollbackChanges != null && !this.rollbackChanges.isDisposed()) { + this.rollbackChanges.setEnabled(isEdited && isDbConnected && !isEncodingToBeModified()); + } + } + + private void handleCommitButtonEnabling(boolean isDbConnected, boolean isEdited) { + if (this.commitRecord != null && !this.commitRecord.isDisposed()) { + this.commitRecord.setEnabled(isEdited && isDbConnected && !isEncodingToBeModified()); + } + } + + private void handleRefreshButtonEnabling(boolean isDbConnected, boolean isEdited) { + if (this.refresh != null && !this.refresh.isDisposed()) { + this.refresh.setEnabled(!isSearched && !isEdited && isDbConnected); + updateRefreshButtonTooltip(!isSearched && !isEdited && isDbConnected); + } + } + + private boolean isEncodingToBeModified() { + if (this.dataProvider instanceof DSResultSetGridDataProvider + && ((DSResultSetGridDataProvider) this.dataProvider).isIncludeEncoding() + && ((DSResultSetGridDataProvider) this.dataProvider).isEncodingChanged()) { + return true; + } + return false; + } + + /** + * Enable disable export all button. + */ + public void enableDisableExportAllButton() { + if (isExportAllButtonDisposed() && null != getResultTabDB()) { + // getResultTabDB().isDdlOperationSupported() :this check is added + // for OLTP V1R6 version as copy manager syntax is not supported can + // be removed once issue fixed + exportAllItem.setEnabled(getResultTabDB().isConnected() && canExportAllEnabled() + && !dataProvider.getResultTabDirtyFlag() && !isExplainQuery); + + if (isExplainQuery) { + exportAllItem.setToolTipText( + MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_ALL_DATA_DISABLE_TOOLTIP)); + } + } + + IHandlerUtilities.setToolItemEnabled(exportAllItem, IHandlerUtilities.getExportDataSelectionOptions()); + if (null != this.dsGridComponent.getDataText() && !this.showText.isDisposed() && showText.getSelection()) { + this.disableButtons(); + } + } + + /** + * Enable disable export all button. + * + * @param value the value + */ + public void enableDisableExportAllButton(boolean value) { + if (isExportAllButtonDisposed() && null != getResultTabDB()) { + exportAllItem.setEnabled(value); + } + IHandlerUtilities.setToolItemEnabled(exportAllItem, IHandlerUtilities.getExportDataSelectionOptions()); + } + + private boolean canExportAllEnabled() { + return null != getDsExportState() && !getDsExportState().isExporting() && !getDsExportState().isLoading(); + } + + private boolean isExportAllButtonDisposed() { + return null != exportAllItem && !exportAllItem.isDisposed(); + } + + private void setExplainQuery() { + // For Explain Plan Query ExportAllData icon will be disabled. + isExplainQuery = ((DSResultSetGridDataProvider) this.dataProvider).getSummary().getQuery() + .toLowerCase(Locale.ENGLISH).startsWith("explain"); + } + + /** + * Update. + * + * @param o the o + * @param arg the arg + */ + @Override + public void update(Observable observable, Object arg) { + DSEventTable eventEditTbl = getEventEditTable(); + updateDatabaseConnectDisconnect(eventEditTbl); + } + + private void updateDatabaseConnectDisconnect(DSEventTable eventResultTab) { + if (null != eventResultTab) { + eventResultTab.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_DATABASE_CONNECT_DISCONNECT_STATUS, this)); + } + enableDisableExportAllButton(); + enableDisableShowGridAndShowTextBttton(); + } + + private void enableDisableShowGridAndShowTextBttton() { + if (null != getResultTabDB()) { + handShowGridAndShowTextButEnabling(getResultTabDB().isConnected()); + } + } + + private DSEventTable getEventEditTable() { + return eventEditTable; + } + + private void setEventEditTable(DSEventTable eventEditTable) { + this.eventEditTable = eventEditTable; + } + + /** + * Sets the data provider. + * + * @param dataProvider the new data provider + */ + public void setDataProvider(IDSGridDataProvider dataProvider) { + if ((dataProvider instanceof ExecutionPlanTextDisplayGrid + || dataProvider instanceof ExplainAnalyzePlanNodeTreeDisplayDataTreeFormat) + && this.dataProvider != null) { + this.dataProvider.preDestroy(); + this.dataProvider = null; + } + this.dataProvider = dataProvider; + } + + /** + * Gets the rember user option listener. + * + * @return the rember user option listener + */ + public IDSListener getRemberUserOptionListener() { + return new IDSListener() { + @Override + public void handleEvent(final DSEvent event) { + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + Object val = event.getObject(); + if (val instanceof Boolean) { + GridToolbar.this.setForgotOptionEnabled((Boolean) val); + } + } + }); + + } + }; + } + + private DSGridStateMachine getDsRefreshState() { + return dsRefreshState; + } + + /** + * Sets the ds refresh state. + * + * @param dsRefreshState the new ds refresh state + */ + public void setDsRefreshState(DSGridStateMachine dsRefreshState) { + this.dsRefreshState = dsRefreshState; + } + + private DSGridStateMachine getDsExportState() { + return dsExportState; + } + + /** + * Sets the ds export state. + * + * @param dsExportState the new ds export state + */ + public void setDsExportState(DSGridStateMachine dsExportState) { + this.dsExportState = dsExportState; + } + + /** + * Gets the result tab DB. + * + * @return the result tab DB + */ + public Database getResultTabDB() { + return resultTabDB; + } + + /** + * Sets the result tab DB. + * + * @param resultTabDB the new result tab DB + */ + public void setResultTabDB(Database resultTabDB) { + this.resultTabDB = resultTabDB; + } + + /** + * Enable disable on search. + * + * @param enable the enable + * @param isConnected the is connected + */ + public void enableDisableOnSearch(boolean enable, boolean isConnected) { + isSearched = enable; + if (!this.refresh.isDisposed()) { + IDSEditGridDataProvider editDP = (IDSEditGridDataProvider) dataProvider; + boolean isEdited = editDP.isGridDataEdited(); + this.refresh.setEnabled(!isSearched && !isEdited && isConnected); + updateRefreshButtonTooltip(!isSearched && !isEdited && isConnected); + } + } + + /** + * Enable disable on search non-edit + * + * @param enable the enable + * @param isConnected the is connected + */ + public void enableDisableOnSearchNonEdit(boolean enable, boolean isConnected) { + isSearched = enable; + if (!this.refresh.isDisposed()) { + this.refresh.setEnabled(!isSearched && isConnected); + } + } + + private boolean checkForConditionalEnableDisable(boolean isDbConnected) { + if (dataProvider instanceof IObjectPropertyData) { + String objectPropertyName = ((IObjectPropertyData) dataProvider).getObjectPropertyName(); + if (objectPropertyName != null && objectPropertyName.equals("General")) { + return false; + } else { + return true; + } + } + return isDbConnected; + } + + /** + * Adds the batch drop toolbar. + * + * @param eventTable the event table + */ + public void addBatchDropToolbar(final DSEventTable eventTable) { + int maxObjectNameChars = 50; + int maxObjectsLoadableChars = 6; + Color color = new Color(null, 0xf9, 0xf9, 0xf9); + + ToolItem separator = new ToolItem(toolbar, SWT.SEPARATOR); + separator.setEnabled(true); + + GC gc = new GC(toolbarComposite.getShell()); + FontMetrics fontMetrics = gc.getFontMetrics(); + + Composite comp = getComposite(); + + Label name = new Label(comp, SWT.NONE); + name.setText(MessageConfigLoader.getProperty(IMessagesConstants.DROP_OBJECTS_OPER_DB_NAME)); + name.setLayoutData(new GridData()); + + addBatchDropObjectParentLbl(maxObjectNameChars, color, fontMetrics, comp); + + addBatchDropAtomicBtn(comp); + + addBatchDropCascadeStartStopBtns(comp); + + addRunsImageLbl(comp); + + addBatchDropRunsLbl(maxObjectsLoadableChars, color, fontMetrics, comp); + + addErrorImgAndLbl(comp); + + addBatchDropErrorLbl(maxObjectsLoadableChars, color, fontMetrics, comp); + + this.batchDropAtomicBtn.addSelectionListener(new BatchDropAtomicBtnSelectionListener(eventTable)); + + this.batchDropCascadeBtn.addSelectionListener(new BatchDropCascadeBtnSelectionListener(eventTable)); + + this.batchDropStartBtn.addListener(SWT.Selection, batchDropStartBtnSelectionListener(eventTable)); + + this.batchDropStopBtn.addListener(SWT.Selection, batchDropStopBtnSelectionListener(eventTable)); + + gc.dispose(); + } + + private void addBatchDropErrorLbl(int maxObjectsLoadableChars, Color color, FontMetrics fontMetrics, + Composite comp) { + this.batchDropErrors = new Label(comp, SWT.NONE); + this.batchDropErrors.setText("0"); + GridData gd2 = new GridData(); + gd2.widthHint = fontMetrics.getAverageCharWidth() * (maxObjectsLoadableChars + 1); + gd2.horizontalAlignment = SWT.BEGINNING; + this.batchDropErrors.setLayoutData(gd2); + this.batchDropErrors.setBackground(color); + } + + private void addErrorImgAndLbl(Composite comp) { + Label errorsImg = new Label(comp, SWT.NONE); + errorsImg.setLayoutData(new GridData()); + errorsImg.setImage(IconUtility.getIconImage(IiconPath.ICON_DROP_OBJECTS_ERRORS, this.getClass())); + + Label errors = new Label(comp, SWT.NONE); + errors.setText(MessageConfigLoader.getProperty(IMessagesConstants.DROP_OBJECTS_OPER_LBL_ERRORS)); + errors.setLayoutData(new GridData()); + } + + private void addBatchDropRunsLbl(int maxObjectsLoadableChars, Color color, FontMetrics fontMetrics, + Composite comp) { + this.batchDropRuns = new Label(comp, SWT.NONE); + this.batchDropRuns.setText("0/0"); + GridData gd1 = new GridData(); + gd1.widthHint = fontMetrics.getAverageCharWidth() * (2 * maxObjectsLoadableChars + 3); + gd1.horizontalAlignment = SWT.BEGINNING; + this.batchDropRuns.setLayoutData(gd1); + this.batchDropRuns.setBackground(color); + } + + private void addRunsImageLbl(Composite comp) { + Label runsImg = new Label(comp, SWT.NONE); + runsImg.setLayoutData(new GridData()); + runsImg.setImage(IconUtility.getIconImage(IiconPath.ICON_DROP_OBJECTS_RUNS, this.getClass())); + Label runs = new Label(comp, SWT.NONE); + runs.setText(MessageConfigLoader.getProperty(IMessagesConstants.DROP_OBJECTS_OPER_LBL_RUNS)); + runs.setLayoutData(new GridData()); + } + + private void addBatchDropCascadeStartStopBtns(Composite comp) { + this.batchDropCascadeBtn = new Button(comp, SWT.CHECK); + this.batchDropCascadeBtn.setText(MessageConfigLoader.getProperty(IMessagesConstants.DROP_OBJECTS_OPER_CASCADE)); + + this.batchDropStartBtn = new Button(comp, SWT.PUSH); + this.batchDropStartBtn.setText(MessageConfigLoader.getProperty(IMessagesConstants.DROP_OBJECTS_OPER_START)); + + this.batchDropStopBtn = new Button(comp, SWT.PUSH); + this.batchDropStopBtn.setText(MessageConfigLoader.getProperty(IMessagesConstants.DROP_OBJECTS_OPER_STOP)); + this.batchDropStopBtn.setEnabled(false); + } + + private void addBatchDropAtomicBtn(Composite comp) { + this.batchDropAtomicBtn = new Button(comp, SWT.CHECK); + this.batchDropAtomicBtn.setText(MessageConfigLoader.getProperty(IMessagesConstants.DROP_OBJECTS_OPER_ATOMIC)); + if (null != dataProvider.getDatabse()) { + this.batchDropAtomicBtn.setEnabled(dataProvider.getDatabse().hasSupportForAtomicDDL()); + } + } + + private void addBatchDropObjectParentLbl(int maxObjectNameChars, Color color, FontMetrics fontMetrics, + Composite comp) { + this.batchDropObjectsParent = new Label(comp, SWT.NONE); + this.batchDropObjectsParent.setText(""); + GridData gd = new GridData(); + gd.widthHint = fontMetrics.getAverageCharWidth() * maxObjectNameChars; + gd.horizontalAlignment = SWT.BEGINNING; + this.batchDropObjectsParent.setLayoutData(gd); + this.batchDropObjectsParent.setBackground(color); + } + + private Composite getComposite() { + Composite comp = createComposite(toolbarComposite); + GridLayout gl = (GridLayout) comp.getLayout(); + gl.numColumns = 13; + gl.marginLeft = 5; + gl.horizontalSpacing = 7; + comp.setLayout(gl); + return comp; + } + + private Listener batchDropStopBtnSelectionListener(final DSEventTable eventTable) { + return new Listener() { + + /** + * Handle event. + * + * @param e the e + */ + public void handleEvent(Event e) { + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_BATCHDROP_STOP_OPTION, null)); + } + }; + } + + private Listener batchDropStartBtnSelectionListener(final DSEventTable eventTable) { + return new Listener() { + + /** + * Handle event. + * + * @param e the e + */ + public void handleEvent(Event e) { + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_BATCHDROP_START_OPTION, null)); + } + }; + } + + /** + * The listener interface for receiving batchDropCascadeBtnSelection events. + * The class that is interested in processing a batchDropCascadeBtnSelection + * event implements this interface, and the object created with that class + * is registered with a component using the component's + * addBatchDropCascadeBtnSelectionListener method. When the + * batchDropCascadeBtnSelection event occurs, that object's appropriate + * method is invoked. + * + * BatchDropCascadeBtnSelectionEvent + */ + private class BatchDropCascadeBtnSelectionListener implements SelectionListener { + private DSEventTable eventTable; + + /** + * Instantiates a new batch drop cascade btn selection listener. + * + * @param eventTable the event table + */ + public BatchDropCascadeBtnSelectionListener(DSEventTable eventTable) { + this.eventTable = eventTable; + } + + @Override + public void widgetSelected(SelectionEvent event) { + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_BATCHDROP_CASCADE_OPTION, batchDropCascadeBtn)); + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + + } + } + + /** + * The listener interface for receiving batchDropAtomicBtnSelection events. + * The class that is interested in processing a batchDropAtomicBtnSelection + * event implements this interface, and the object created with that class + * is registered with a component using the component's + * addBatchDropAtomicBtnSelectionListener method. When the + * batchDropAtomicBtnSelection event occurs, that object's appropriate + * method is invoked. + * + * BatchDropAtomicBtnSelectionEvent + */ + private class BatchDropAtomicBtnSelectionListener implements SelectionListener { + private DSEventTable eventTable; + + /** + * Instantiates a new batch drop atomic btn selection listener. + * + * @param eventTable the event table + */ + public BatchDropAtomicBtnSelectionListener(DSEventTable eventTable) { + this.eventTable = eventTable; + } + + @Override + public void widgetSelected(SelectionEvent event) { + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_BATCHDROP_ATOMIC_OPTION, batchDropAtomicBtn)); + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + + } + } + + /** + * Update batch drop atomic button. + * + * @param isEnabled the is enabled + */ + public void updateBatchDropAtomicButton(boolean isEnabled) { + if (!batchDropAtomicBtn.isDisposed()) { + this.batchDropAtomicBtn.setEnabled(isEnabled); + } + } + + /** + * Update batch drop cascade button. + * + * @param isEnabled the is enabled + */ + public void updateBatchDropCascadeButton(boolean isEnabled) { + if (!batchDropCascadeBtn.isDisposed()) { + this.batchDropCascadeBtn.setEnabled(isEnabled); + } + } + + /** + * Update batch drop start button. + * + * @param isEnabled the is enabled + */ + public void updateBatchDropStartButton(boolean isEnabled) { + if (!this.batchDropStartBtn.isDisposed()) { + this.batchDropStartBtn.setEnabled(isEnabled); + } + } + + /** + * Update batch drop stop button. + * + * @param isEnabled the is enabled + */ + public void updateBatchDropStopButton(boolean isEnabled) { + if (!this.batchDropStopBtn.isDisposed()) { + this.batchDropStopBtn.setEnabled(isEnabled); + } + } + + /** + * Update batch drop runs label. + * + * @param successDropCount the success drop count + * @param totalDropCount the total drop count + */ + public void updateBatchDropRunsLabel(int successDropCount, int totalDropCount) { + if (!batchDropRuns.isDisposed()) { + batchDropRuns.setText(successDropCount + "/" + totalDropCount); + } + } + + /** + * Update batch drop errors label. + * + * @param errorDropCount the error drop count + */ + public void updateBatchDropErrorsLabel(int errorDropCount) { + if (!batchDropErrors.isDisposed()) { + batchDropErrors.setText("" + errorDropCount); + } + } + + /** + * Update batch drop object label. + * + * @param objectNameParam the object name param + */ + public void updateBatchDropObjectLabel(String objectNameParam) { + String objectName = objectNameParam; + if (objectName.length() > 50) { + objectName = objectName.substring(0, 47) + "..."; + } + + if (!batchDropObjectsParent.isDisposed()) { + batchDropObjectsParent.setText(objectName); + } + } + + /** + * Pre destroy. + */ + @PreDestroy + public void preDestroy() { + DatabaseListControl databaseListControl = UIElement.getInstance().getDatabaseListControl(); + if (null != databaseListControl) { + databaseListControl.deleteObserver(this); + } + dataProvider = null; + eventEditTable = null; + resultTabDB = null; + dsExportState = null; + dsRefreshState = null; + dsGridComponent = null; + + if (null != dsEncodingList) { + this.dsEncodingList.clear(); + this.dsEncodingList = null; + } + if (null != toolManagerMap) { + this.toolManagerMap.clear(); + this.toolManagerMap = null; + } + if (dataGrid != null && null != dataGrid.getDataGrid() && !dataGrid.getDataGrid().isDisposed()) { + dataGrid.getDataGrid().removeLayerListener(iLayerListener); + iLayerListener = null; + } + this.multiColumnSort = null; + copyItem = null; + copyAdvancedItem = null; + exportAllItem = null; + exportCurrentItem = null; + toggleSearchArea = null; + insertRow = null; + deleteRow = null; + commitRecord = null; + refresh = null; + rollbackChanges = null; + pasteData = null; + eventEditTable = null; + forgetOption = null; + if (!toolbar.isDisposed()) { + toolbar.dispose(); + } + } + + /** + * Adds the item save plan. + * + * @param eventTable the event table + * @param stateMachine the state machine + */ + public void addItemSavePlan(final DSEventTable eventTable, DSGridStateMachine stateMachine) { + String toolTipMsg = MessageConfigLoader.getProperty(IMessagesConstants.MENU_SAVE); + this.savePlan = getToolItem(SWT.PUSH, null, IiconPath.ICO_SAVE_SQL, toolTipMsg); + this.savePlan.setToolTipText(toolTipMsg); + this.savePlan.addSelectionListener(savePlanSelectionListener(eventTable, stateMachine)); + + stateMachine.addObserver(stateMachineSavePlanObserver()); + + } + + private Observer stateMachineSavePlanObserver() { + return new Observer() { + @Override + public void update(Observable observable, Object arg) { + if (arg instanceof DSGridStateMachine.State) { + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + synchronized (INSTANCE_LOCK) { + enableDisableSavePlanButton(); + } + } + }); + + } + } + }; + } + + private SelectionListener savePlanSelectionListener(final DSEventTable eventTable, + DSGridStateMachine stateMachine) { + return new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent event) { + if (stateMachine.set(DSGridStateMachine.State.EXPORTING)) { + eventTable.sendEvent( + new DSEvent(IDSGridUIListenable.LISTEN_EXEC_PLAN_WINDOW_SAVE_PLAN, new Observer() { + @Override + public void update(Observable observable, Object arg) { + if (arg instanceof Boolean && !((boolean) arg)) { + stateMachine.set(DSGridStateMachine.State.IDLE); + } + } + })); + } + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + // Ignore + } + }; + } + + /** + * Enable disable save plan button. + */ + protected void enableDisableSavePlanButton() { + if (null != savePlan && !savePlan.isDisposed()) { + savePlan.setEnabled(null != getDsExportState() && !getDsExportState().isExporting()); + } + + } + + /** + * Enable disable refresh plan button. + */ + public void enableDisableRefreshPlanButton() { + if (null != refresh && !refresh.isDisposed()) { + refresh.setEnabled(null != getDsRefreshState() && !getDsRefreshState().isRefreshing() + && UIElement.getInstance().isDatabaseConnected()); + } + } + + /** + * Adds the item tree view. + * + * @param eventTable the event table + * @param stateMachine the state machine + */ + public void addItemTreeView(final DSEventTable eventTable, DSGridStateMachine stateMachine) { + String toolTipMsg = MessageConfigLoader.getProperty(IMessagesConstants.TOOLBAR_TREE_VIEW); + this.treeView = getToolItem(SWT.PUSH, null, IiconPath.ICON_EXECUTION_PLAN_TREE_VIEW, toolTipMsg); + this.treeView.setToolTipText(toolTipMsg); + this.treeView.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent event) { + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_EXEC_PLAN_WINDOW_TREE_VIEW, this)); + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + // Ignore + } + }); + + stateMachine.addObserver(new Observer() { + + @Override + public void update(Observable arg0, Object arg1) { + + } + + }); + + } + + /** + * Adds the item text view. + * + * @param eventTable the event table + * @param stateMachine the state machine + */ + public void addItemTextView(final DSEventTable eventTable, DSGridStateMachine stateMachine) { + String toolTipMsg = MessageConfigLoader.getProperty(IMessagesConstants.TOOLBAR_TEXT_VIEW); + this.textView = getToolItem(SWT.PUSH, null, IiconPath.ICON_EXECUTION_PLAN_TEXT_VIEW, toolTipMsg); + this.textView.setToolTipText(toolTipMsg); + this.textView.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent event) { + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_EXEC_PLAN_WINDOW_TEXT_VIEW, this)); + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + // Ignore + } + }); + + stateMachine.addObserver(new Observer() { + + @Override + public void update(Observable arg0, Object arg1) { + + } + + }); + + } + + /** + * Adds the refresh plan item. + * + * @param eventTable the event table + * @param stateMachine the state machine + */ + public void addRefreshPlanItem(final DSEventTable eventTable, DSGridStateMachine stateMachine) { + String toolTipMsg = MessageConfigLoader.getProperty(IMessagesConstants.RESULT_WINDOW_REFRESH); + this.refresh = getToolItem(SWT.PUSH, null, IiconPath.ICO_REFRESH, toolTipMsg); + this.refresh.setToolTipText(toolTipMsg); + setEventEditTable(eventTable); + this.refresh.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent event) { + if (stateMachine.set(DSGridStateMachine.State.REFRESHING)) { + eventTable + .sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_EXEC_PLAN_WINDOW_REFRESH, new Observer() { + @Override + public void update(Observable observable, Object arg) { + if (arg instanceof Boolean && !((boolean) arg)) { + stateMachine.set(DSGridStateMachine.State.IDLE); + } + } + })); + } + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + // Ignore + } + }); + + stateMachine.addObserver(new Observer() { + @Override + public void update(Observable observable, Object arg) { + if (arg instanceof DSGridStateMachine.State) { + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + synchronized (INSTANCE_LOCK) { + enableDisableRefreshPlanButton(); + } + } + }); + + } + } + }); + updateRefreshButtonTooltip(true); + } + + /** + * Adds the item show grid. + * + * @param eventTable the event table + */ + public void addItemShowGrid(DSEventTable eventTable) { + String toolTipMsg = MessageConfigLoader.getProperty(IMessagesConstants.RESULT_WINDOW_SHOW_GRID); + this.showGrid = getToolItem(SWT.CHECK, null, IiconPath.ICO_GRID, toolTipMsg); + this.showGrid.setToolTipText(toolTipMsg); + this.showGrid.setSelection(true); + DataText dataText = dsGridComponent.getDataText(); + this.showGrid.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent event) { + showGrid.setSelection(true); + dsGridComponent.updateGridStatusBarForDataGrid(); + gridAndTextButSwitchCount = 0; + enableButtons(); + if (dataText.isSearchStatus()) { + dataText.changeButStatus(true); + } + if (showText.getSelection()) { + showText.setSelection(false); + } + // Display grid content + dsGridComponent.hideStatusBar(); + dsGridComponent.getDataGrid().doShowGrid(dsGridComponent.getDataGrid().getParent()); + dataText.doHideText(dataText.getTextParent()); + dataText.doHideText(dataText.getSearchParent()); + dsGridComponent.showStatusBar(); + if (dataGrid != null) { + int scrolledRowIndex = dataText.getTopIndex(); + dataGrid.updateScrolledInfo(scrolledRowIndex, -1); + dataGrid.getDataGrid().doCommand(new ShowRowInViewportCommand( + dataGrid.getCurrentScrolledBeginRow(scrolledRowIndex)) + ); + } + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + // Ignore + } + }); + } + + /** + * Adds the item show text. + * + * @param eventTable the event table + */ + public void addItemShowText(DSEventTable eventTable) { + String toolTipMsg = MessageConfigLoader.getProperty(IMessagesConstants.RESULT_WINDOW_SHOW_TEXT); + this.showText = getToolItem(SWT.CHECK, null, IiconPath.ICO_TEXT, toolTipMsg); + this.showText.setToolTipText(toolTipMsg); + DataText dataText = dsGridComponent.getDataText(); + if (dataText.isInitDataTextFlag()) { + showText.setEnabled(false); + } + this.showText.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent event) { + showText.setSelection(true); + dsGridComponent.updateGridStatusBarForDataText(dataText.isPartloaded(), dataText.getLoadedRowCnt()); + gridAndTextButSwitchCount++; + if (gridAndTextButSwitchCount == 1) { + recordButtonStatus(); + } + if (dataText.isSearchStatus()) { + dataText.changeButStatus(false); + } + if (showGrid.getSelection()) { + showGrid.setSelection(false); + } + disableButtons(); + dsGridComponent.hideStatusBar(); + dsGridComponent.getDataGrid().doHideGrid(dsGridComponent.getDataGrid().getParent()); + if (dataText.isSearchHideOrShowFlag()) { + dataText.doShowText(dataText.getSearchParent()); + } else { + dataText.doShowText(dataText.getTextParent()); + } + dsGridComponent.showStatusBar(); + if (dataGrid != null) { + dataText.setTopIndex(dataGrid.getCurScrolledRow()); + } + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + // Ignore + } + }); + } + + /** + * Disable buttons. + */ + private void disableButtons() { + if (null != copyAdvancedItem) { + copyAdvancedItem.setEnabled(false); + } + if (null != exportAllItem) { + exportAllItem.setEnabled(false); + } + + if (null != exportCurrentItem) { + exportCurrentItem.setEnabled(false); + } + + IHandlerUtilities.setToolItemEnabled(exportAllItem, IHandlerUtilities.getExportDataSelectionOptions()); + IHandlerUtilities.setToolItemEnabled(exportCurrentItem, IHandlerUtilities.getExportDataSelectionOptions()); + IHandlerUtilities.setToolItemEnabled(copyAdvancedItem, IHandlerUtilities.getExportDataSelectionOptions()); + + if (null != insertRow) { + insertRow.setEnabled(false); + } + if (null != deleteRow) { + deleteRow.setEnabled(false); + } + if (null != commitRecord) { + commitRecord.setEnabled(false); + } + if (null != rollbackChanges) { + rollbackChanges.setEnabled(false); + } + if (null != forgetOption) { + forgetOption.setEnabled(false); + } + if (null != pasteData) { + pasteData.setEnabled(false); + } + if (null != multiColumnSort) { + multiColumnSort.setEnabled(false); + } + if (null != clearSort) { + clearSort.setEnabled(false); + } + if (null != this.combo) { + combo.setEnabled(false); + } + } + + /** + * Enable buttons. + */ + public void enableButtons() { + enableCopyAdvancedItem(); + enableExportCurrentItem(); + enableExportAllItem(); + enableInsertRow(); + enableDeleteRow(); + enableCommitRecord(); + enableRollbackChanges(); + enableForgetOption(); + enablePasteData(); + enableMultiColumnSort(); + enableClearSort(); + enableCombo(); + } + + private void enableCombo() { + if (null != combo && comboFlag) { + combo.setEnabled(true); + } + } + + private void enableClearSort() { + if (null != clearSort && clearSortFlag) { + clearSort.setEnabled(true); + } + } + + private void enableMultiColumnSort() { + if (null != multiColumnSort && multiColumnSortFlag) { + multiColumnSort.setEnabled(true); + } + } + + private void enablePasteData() { + if (null != pasteData && pasteDataFlag) { + pasteData.setEnabled(true); + } + } + + private void enableForgetOption() { + if (null != forgetOption && forgetOptionFlag) { + forgetOption.setEnabled(true); + } + } + + private void enableRollbackChanges() { + if (null != rollbackChanges && rollbackChangesFlag) { + rollbackChanges.setEnabled(true); + } + } + + private void enableCommitRecord() { + if (null != commitRecord && commitRecordFlag) { + commitRecord.setEnabled(true); + } + } + + private void enableDeleteRow() { + if (null != deleteRow && deleteRowFlag) { + deleteRow.setEnabled(true); + } + } + + private void enableInsertRow() { + if (null != insertRow && insertRowFlag) { + insertRow.setEnabled(true); + } + } + + private void enableExportAllItem() { + if (null != exportAllItem && exportAllItemFlag) { + exportAllItem.setEnabled(true); + } + + IHandlerUtilities.setToolItemEnabled(exportAllItem, IHandlerUtilities.getExportDataSelectionOptions()); + + } + + private void enableExportCurrentItem() { + if (null != exportCurrentItem && exportCurrentItemFlag) { + exportCurrentItem.setEnabled(true); + } + + IHandlerUtilities.setToolItemEnabled(exportCurrentItem, IHandlerUtilities.getExportDataSelectionOptions()); + } + + private void enableCopyAdvancedItem() { + if (null != copyAdvancedItem && copyAdvanceFlag) { + copyAdvancedItem.setEnabled(true); + } + IHandlerUtilities.setToolItemEnabled(copyAdvancedItem, IHandlerUtilities.getExportDataSelectionOptions()); + } + + private void recordButtonStatus() { + recordCopyAdvancedItemStatus(); + recordExportAllItemStatus(); + recordExportCurrentItemStatus(); + recordInsertRowStatus(); + recordDeleteRowStatus(); + recordCommitRecordStatus(); + recordRollbackChangesStatus(); + recordForgetOptionStatus(); + recordPasteDataStatus(); + recordMultiColumnSortStatus(); + recordClearSortStatus(); + + recordComboStatus(); + } + + private void recordComboStatus() { + if (null != combo && combo.isEnabled()) { + this.comboFlag = true; + } else { + this.comboFlag = false; + } + } + + private void recordClearSortStatus() { + if (null != clearSort && clearSort.isEnabled()) { + this.clearSortFlag = true; + } else { + this.clearSortFlag = false; + } + } + + private void recordMultiColumnSortStatus() { + if (null != multiColumnSort && multiColumnSort.isEnabled()) { + this.multiColumnSortFlag = true; + } else { + this.multiColumnSortFlag = false; + } + } + + private void recordPasteDataStatus() { + if (null != pasteData && pasteData.isEnabled()) { + this.pasteDataFlag = true; + } else { + this.pasteDataFlag = false; + } + } + + private void recordForgetOptionStatus() { + if (null != forgetOption && forgetOption.isEnabled()) { + this.forgetOptionFlag = true; + } else { + this.forgetOptionFlag = false; + } + } + + private void recordRollbackChangesStatus() { + if (null != rollbackChanges && rollbackChanges.isEnabled()) { + this.rollbackChangesFlag = true; + } else { + this.rollbackChangesFlag = false; + } + } + + private void recordCommitRecordStatus() { + if (null != commitRecord && commitRecord.isEnabled()) { + this.commitRecordFlag = true; + } else { + this.commitRecordFlag = false; + } + } + + private void recordDeleteRowStatus() { + if (null != deleteRow && deleteRow.isEnabled()) { + this.deleteRowFlag = true; + } else { + this.deleteRowFlag = false; + } + } + + private void recordInsertRowStatus() { + if (null != insertRow && insertRow.isEnabled()) { + this.insertRowFlag = true; + } else { + this.insertRowFlag = false; + } + } + + private void recordExportCurrentItemStatus() { + if (null != exportCurrentItem && exportCurrentItem.isEnabled()) { + this.exportCurrentItemFlag = true; + } else { + this.exportCurrentItemFlag = false; + } + } + + private void recordExportAllItemStatus() { + if (null != exportAllItem && exportAllItem.isEnabled()) { + this.exportAllItemFlag = true; + } else { + this.exportAllItemFlag = false; + } + } + + private void recordCopyAdvancedItemStatus() { + if (null != copyAdvancedItem && copyAdvancedItem.isEnabled()) { + this.copyAdvanceFlag = true; + } else { + this.copyAdvanceFlag = false; + } + } + + /** + * Updata but status on init data text. + */ + public void updataButStatusOnInitDataText() { + if (null != showText && !showText.isDisposed()) { + showText.setEnabled(true); + } + if (null != refresh) { + refresh.setEnabled(true); + } + if (null != combo) { + combo.setEnabled(true); + } + } + + /** + * Updata but status on load data text. + * + * @param loadStatus the load status + */ + public void updataButStatusOnLoadDataText(boolean loadStatus) { + if (UIElement.getInstance().getSqlTerminalModel() == null) { + return; + } + boolean isDbConnected = UIElement.getInstance().isDatabaseConnected(); + if (isShowGridOrShowTextSelect()) { + showText.setEnabled(isDbConnected && loadStatus); + if (null != combo) { + combo.setEnabled(loadStatus); + } + } else { + showGrid.setEnabled(isDbConnected && loadStatus); + } + if (null != refresh) { + refresh.setEnabled(isDbConnected && loadStatus); + } + } + + /** + * Updata but status on load data text exception. + */ + public void updataButStatusOnLoadDataTextException() { + if (isShowGridOrShowTextSelect()) { + showText.setEnabled(false); + if (null != combo) { + combo.setEnabled(true); + } + if (null != refresh) { + refresh.setEnabled(true); + } + } else { + showGrid.setEnabled(false); + if (null != refresh) { + refresh.setEnabled(false); + } + } + } + + /** + * Updata but status on init data text cancel or exception. + */ + public void updataButStatusOnInitDataTextCancelOrException() { + if (null != showText) { + showText.setEnabled(false); + } + if (null != refresh) { + refresh.setEnabled(true); + } + if (null != combo) { + combo.setEnabled(true); + } + } + + /** + * Checks if is show grid or show text select. + * + * @return true, if is show grid or show text select + */ + public boolean isShowGridOrShowTextSelect() { + if (this.showGrid.getSelection()) { + return true; + } + return false; + } + + /** + * Checks if is refresh but enable. + * + * @return true, if is refresh but enable + */ + public boolean isRefreshButEnable() { + if (null != refresh && refresh.isEnabled()) { + return true; + } + return false; + } + + /** + * Adds the load more record. + * + * @param eventTable the event table + * @param stateMachine the state machine + */ + public void addLoadMoreRecord(final DSEventTable eventTable, DSGridStateMachine stateMachine) { + String toolTipMsg = MessageConfigLoader.getProperty(IMessagesConstants.LOAD_MORE_RECORD_TOOL_ITEM); + this.loadMoreRecord = getToolItem(SWT.PUSH, null, IiconPath.ICON_LOAD_MORE_RECORD, toolTipMsg); + this.loadMoreRecord.setToolTipText(toolTipMsg); + this.loadMoreRecord.setEnabled(false); + + if (!dsGridComponent.getDataGrid().getDataProvider().isEndOfRecords()) { + this.loadMoreRecord.setEnabled(true); + } + + this.loadMoreRecord.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent event) { + if (stateMachine.set(DSGridStateMachine.State.LOADING)) { + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_ON_REEXECUTE_QUERY, + dsGridComponent.getDataGrid().getDataProvider())); + } + } + + @Override + public void widgetDefaultSelected(SelectionEvent selectDefaultEvent) { + + } + }); + } + + /** + * Reset load more record status. + */ + public void resetLoadMoreRecordStatus() { + DSGridStateMachine stateMachine = this.dsGridComponent.getStateMachine(); + if (stateMachine == null || this.loadMoreRecord == null || this.loadMoreRecord.isDisposed()) { + return; + } + + if (stateMachine.isLoading() || stateMachine.isExporting() || stateMachine.isRefreshing()) { + this.loadMoreRecord.setEnabled(false); + } else { + DataGrid dGrid = this.dsGridComponent.getDataGrid(); + if (dGrid != null && dGrid.getDataProvider() != null && !dGrid.getDataProvider().isEndOfRecords()) { + this.loadMoreRecord.setEnabled(true); + } + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridUIUtils.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridUIUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..e2821735de626eac992b8c9bbca34a7b3a58e3fd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridUIUtils.java @@ -0,0 +1,267 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import java.util.Locale; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; + +import org.opengauss.mppdbide.presentation.objectproperties.PropertiesConstants; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class GridUIUtils. + * + * @since 3.0.0 + */ +public class GridUIUtils { + + /** + * Hide or show UI component + * + * @param composite + * @param isHide + * @param focusElem + */ + private static final String GEN_TAB = "General"; + private static final String COLUMNS_TAB = "Columns"; + private static final String CONSTRAINT_TAB = "Constraints"; + private static final String INDEX_TAB = "Index"; + private static final String GEN_TAB_VALUE = MessageConfigLoader + .getProperty(IMessagesConstants.PROPERTIES_WID_VALUE); + + /** + * Toggle composite section visibility. + * + * @param composite the composite + * @param isHide the is hide + * @param focusElem the focus elem + * @param parentResizeSpecial the parent resize special + */ + public static void toggleCompositeSectionVisibility(Composite composite, boolean isHide, Control focusElem, + boolean parentResizeSpecial) { + composite.setVisible(!isHide); + Object layoutData = composite.getLayoutData(); + if (null != layoutData && layoutData instanceof GridData) { + ((GridData) layoutData).exclude = isHide; + } + + if (parentResizeSpecial) { + /* + * this is only to be used for explain plan tabs where composite + * structure is more layered. + */ + final GridData data = (GridData) composite.getParent().getParent().getLayoutData(); + data.heightHint -= 20; + composite.getParent().getParent().layout(); + } else { + /* + * resulttab case + */ + composite.getParent().layout(true, true); + } + + if (!isHide && null != focusElem) { + focusElem.setFocus(); + } + } + + /** + * Checks if is datatype edit supported. + * + * @param sqlType the sql type + * @param precision the precision + * @return true, if is datatype edit supported + */ + public static boolean isDatatypeEditSupported(String sqlType, int precision) { + switch (sqlType.toLowerCase(Locale.ENGLISH)) { + case "bpchar": + case "char": + case "varchar": + case "text": + case "int4": + case "int2": + case "int8": + case "date": + case "numeric": + case "decimal": + case "float8": + case "float4": + case "time": + case "timestamp": + case "bool": + case "serial": + case "integer": + case "bigint": + case "real": + case "number": + case "boolean": + case MPPDBIDEConstants.BYTEA: { + return true; + } + case "bit": { + if (precision > 1) { + return false; + } + return true; + } + default: { + return false; + } + } + + } + + /** + * Checks if is editable properties attributes. + * + * @param propertyName the property name + * @param columnName the column name + * @param rowData the row data + * @return true, if is editable properties attributes + */ + public static boolean isEditablePropertiesAttributes(String propertyName, String columnName, String rowData) { + switch (propertyName) { + case GEN_TAB: { + return isGeneralEditablePropAttributes(columnName, rowData); + } + + case COLUMNS_TAB: { + return true; + } + case CONSTRAINT_TAB: { + return isConstraintEditablePropAttributes(columnName); + } + case INDEX_TAB: { + return isIndexTabEditablePropAttributes(columnName); + } + case PropertiesConstants.USER_ROLE_PROPERTY_TAB_GENERAL: { + return isUserRolePropTabGeneralEditableAttributes(columnName, rowData); + } + case PropertiesConstants.USER_ROLE_PROPERTY_TAB_PRIVILEGE: { + return isUserRolePropTabPrivilegeEditableAttributes(columnName); + } + case PropertiesConstants.USER_ROLE_PROPERTY_TAB_MEMBERSHIP: { + return isUserRolePropTabMembershipEditableAttributes(columnName); + } + default: { + break; + } + + } + + return false; + } + + private static boolean isUserRolePropTabMembershipEditableAttributes(String columnName) { + if (columnName + .equals(MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_TAB_COLUMN_TITLE_USER_ROLE))) { + return false; + } + return true; + } + + private static boolean isUserRolePropTabPrivilegeEditableAttributes(String columnName) { + if (columnName + .equals(MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_TAB_COLUMN_TITLE_PROPERTY))) { + return false; + } + return true; + } + + private static boolean isIndexTabEditablePropAttributes(String columnName) { + if (columnName.equals(MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_INDEX_INDEXNAME))) { + return true; + } + return false; + } + + private static boolean isConstraintEditablePropAttributes(String columnName) { + if (columnName + .equals(MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_CONSTRAINT_CONSTRAINTNAME))) { + return true; + } + return false; + } + + private static boolean isUserRolePropTabGeneralEditableAttributes(String columnName, String rowData) { + if (columnName.equals(MessageConfigLoader.getProperty(IMessagesConstants.USER_ROLE_TAB_COLUMN_TITLE_VALUE))) { + if (rowData != null && (rowData.equals(MessageConfigLoader.getProperty(IMessagesConstants.OID_MSG)))) { + return false; + } + } + return true; + } + + private static boolean isGeneralEditablePropAttributes(String columnName, String rowData) { + if (rowData != null && rowData.equals(MessageConfigLoader.getProperty(IMessagesConstants.DESC_MSG)) + && columnName.equals(GEN_TAB_VALUE)) { + return true; + } + return false; + } + + /** + * Truncate string. + * + * @param str the str + * @param maxLength the max length + * @return the string + */ + public static String truncateString(String str, int maxLength) { + if (str != null && str.length() > maxLength) { + return str.substring(0, maxLength); + } + return str; + } + + /** + * Creates the horizontal line. + * + * @param parent the parent + * @return the label + */ + public static Label createHorizontalLine(Composite parent) { + return createHorizontalLine(parent, 1, 0); + } + + /** + * Creates the horizontal line. + * + * @param parent the parent + * @param hSpan the h span + * @param vIndent the v indent + * @return the label + */ + public static Label createHorizontalLine(Composite parent, int hSpan, int vIndent) { + Label horizontalLine = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL); + GridData gd = new GridData(GridData.FILL, GridData.FILL, true, false, 1, 1); + gd.horizontalSpan = hSpan; + gd.verticalIndent = vIndent; + horizontalLine.setLayoutData(gd); + return horizontalLine; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridViewPortData.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridViewPortData.java new file mode 100644 index 0000000000000000000000000000000000000000..513055ad70cebd864862cedb9ff23356c26397e4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/GridViewPortData.java @@ -0,0 +1,240 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import java.sql.Date; +import java.sql.Time; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; + +import org.eclipse.nebula.widgets.nattable.layer.ILayer; +import org.eclipse.nebula.widgets.nattable.print.command.TurnViewportOffCommand; +import org.eclipse.nebula.widgets.nattable.print.command.TurnViewportOnCommand; +import org.eclipse.nebula.widgets.nattable.util.IClientAreaProvider; + +import org.opengauss.mppdbide.presentation.exportdata.ExportCursorExecuteVisitor.ColumnDataType; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class GridViewPortData. + * + * @since 3.0.0 + */ +public class GridViewPortData implements Iterable { + private ILayer viewport; + private int dataReadIndex; + private int rowCount; + + private int colCount; + + /** + * Gets the col count. + * + * @return the col count + */ + public int getColCount() { + return colCount; + } + + /** + * Sets the col count. + * + * @param colCount the new col count + */ + public void setColCount(int colCount) { + this.colCount = colCount; + } + + private IClientAreaProvider originalClientAreaProvider; + + /** + * Instantiates a new grid view port data. + * + * @param layer the layer + */ + public GridViewPortData(ILayer layer) { + this.viewport = layer; + this.dataReadIndex = 0; + } + + /** + * Gets the row count. + * + * @return the row count + */ + public int getRowCount() { + return rowCount; + } + + /** + * Sets the row count. + * + * @param rowCount the new row count + */ + public void setRowCount(int rowCount) { + this.rowCount = rowCount; + } + + /** + * Iterator. + * + * @return the iterator + */ + @Override + public Iterator iterator() { + return new Iterator() { + + @Override + public boolean hasNext() { + return dataReadIndex < rowCount; + } + + @Override + public String[] next() { + if (dataReadIndex >= rowCount) { + throw new NoSuchElementException(); + } + return getRow(); + } + + }; + } + + /** + * Finalize layer. + */ + public void finalizeLayer() { + this.viewport.setClientAreaProvider(originalClientAreaProvider); + this.viewport.doCommand(new TurnViewportOnCommand()); + } + + /** + * Initialize layer. + */ + public void initializeLayer() { + originalClientAreaProvider = this.viewport.getClientAreaProvider(); + this.viewport.doCommand(new TurnViewportOffCommand()); + setRowCount(this.viewport.getRowCount()); + setColCount(this.viewport.getColumnCount()); + } + + /** + * Gets the row. + * + * @return the row + */ + public String[] getRow() { + String[] rowData = new String[this.colCount - 1]; + + // As we operate on Grid Layer, Skip the row number column + for (int i = 1; i < this.colCount; i++) { + // If the datatype is Blob, [BLOB] watermark is added + // instead of the content since it can be huge + if (this.viewport.getConfigLabelsByPosition(i, this.dataReadIndex) + .hasLabel(IEditTableGridStyleLabelFactory.COL_LABEL_BLOB_TYPE_CELL) + && this.viewport.getDataValueByPosition(i, this.dataReadIndex) != null) { + rowData[i - 1] = MPPDBIDEConstants.BLOB_WATERMARK; + continue; + } + + if (this.viewport.getConfigLabelsByPosition(i, this.dataReadIndex) + .hasLabel(IEditTableGridStyleLabelFactory.COL_LABEL_CURSOR_TYPE_CELL) + && this.viewport.getDataValueByPosition(i, this.dataReadIndex) != null + && this.viewport.getDataValueByPosition(i, this.dataReadIndex) instanceof List) { + rowData[i - 1] = MPPDBIDEConstants.CURSOR_WATERMARK; + continue; + } + if (this.viewport.getConfigLabelsByPosition(i, this.dataReadIndex) + .hasLabel(IEditTableGridStyleLabelFactory.COL_LABEL_BYTEA_TYPE_CELL) + && this.viewport.getDataValueByPosition(i, this.dataReadIndex) != null) { + rowData[i - 1] = MPPDBIDEConstants.BYTEA_WATERMARK; + continue; + } + rowData[i - 1] = getObjectString(this.viewport.getDataValueByPosition(i, this.dataReadIndex)); + } + this.dataReadIndex++; + return rowData; + } + + /** + * Gets the excel data type. + * + * @return the excel data type + */ + public List getExcelDataType() { + + List columnList = new ArrayList(); + for (int i = 1; i < colCount; i++) { + Object data1 = this.viewport.getDataValueByPosition(i, 1); + if (data1 instanceof Float) { + columnList.add(ColumnDataType.DOUBLE); + } else if (data1 instanceof Double) { + columnList.add(ColumnDataType.DOUBLE); + } else if (data1 instanceof Date) { + columnList.add(ColumnDataType.DATE); + } else if (data1 instanceof Timestamp) { + columnList.add(ColumnDataType.DATE); + } else if (data1 instanceof Boolean) { + columnList.add(ColumnDataType.BOOLEAN); + } else { + columnList.add(ColumnDataType.STRING); + } + } + return columnList; + + } + + /** + * Converts known type of object to string for export operation. Limitation: + * To be extended for format like Date time format, because What use see on + * UI and exported file may be different. + * + * @param data the data + * @return the object string + */ + private String getObjectString(Object data) { + if (data instanceof Byte) { + return Byte.toString((Byte) data); + } else if (data instanceof Short) { + return Short.toString((Short) data); + } else if (data instanceof Integer) { + return Integer.toString((Integer) data); + } else if (data instanceof Long) { + return Long.toString((Long) data); + } else if (data instanceof Float) { + return Float.toString((Float) data); + } else if (data instanceof Double) { + return Double.toString((Double) data); + } else if (data instanceof Boolean) { + return Boolean.toString((Boolean) data); + } else if (data instanceof Date) { + return ((Date) data).toString(); + } else if (data instanceof Time) { + return ((Time) data).toString(); + } else if (data instanceof Timestamp) { + return ((Timestamp) data).toString(); + } else { + return null == data ? "" : data.toString(); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/IButtonConfigLabels.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/IButtonConfigLabels.java new file mode 100644 index 0000000000000000000000000000000000000000..0a0c1178fe5ddcffeebacb66a2a2275120fd884a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/IButtonConfigLabels.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +/** + * + * Title: enum + * + * Description: The Enum IButtonConfigLabels. + * + * @since 3.0.0 + */ +public enum IButtonConfigLabels { + + /** + * The add. + */ + ADD, + /** + * The delete. + */ + DELETE, + /** + * The commit. + */ + COMMIT, + /** + * The refresh. + */ + REFRESH, + /** + * The cancelchanges. + */ + CANCELCHANGES, + /** + * The copy. + */ + COPY, + /** + * The advancedcopy. + */ + ADVANCEDCOPY, + /** + * The exportall. + */ + EXPORTALL, + /** + * The exportcurrentpage. + */ + EXPORTCURRENTPAGE, + /** + * The paste. + */ + PASTE, + /** + * The forgetoption. + */ + FORGETOPTION +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/IDataGridContext.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/IDataGridContext.java new file mode 100644 index 0000000000000000000000000000000000000000..91305ba371cd01e42fe8cfd5e27f9711bd362723 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/IDataGridContext.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import java.util.List; + +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; + +/** + * + * Title: interface + * + * Description: The Interface IDataGridContext. + * + * @since 3.0.0 + */ +public interface IDataGridContext { + + /** + * Gets the data provider. + * + * @return the data provider + */ + IDSGridDataProvider getDataProvider(); + + /** + * Gets the column meta data list. + * + * @return the column meta data list + */ + List getColumnMetaDataList(); + + /** + * Sets the data provider. + * + * @param dataprovider the new data provider + */ + void setDataProvider(IDSGridDataProvider dataprovider); + + /** + * the onPreDestroy + */ + void onPreDestroy(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/IEditTableGridStyleLabelFactory.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/IEditTableGridStyleLabelFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..74e3f9c78e3b798024e1526a046282b27091b5e7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/IEditTableGridStyleLabelFactory.java @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +/** + * Title: IEditTableGridStyleLabelFactory + * + * Description:A factory for creating IEditTableGridStyleLabel objects. + * + * @since 3.0.0 + */ +public interface IEditTableGridStyleLabelFactory { + + /** + * The drop down. + */ + int DROP_DOWN = 2; + + /** + * The date short. + */ + int DATE_SHORT = 1048576; + + /** + * The canonical limit. + */ + int CANONICAL_LIMIT = 1000; + + /** + * The col label insert. + */ + String COL_LABEL_INSERT = "INSERT"; + + /** + * The col label update. + */ + String COL_LABEL_UPDATE = "UPDATE"; + + /** + * The col label delete. + */ + String COL_LABEL_DELETE = "DELTEE"; + + /** + * The col label change success. + */ + String COL_LABEL_CHANGE_SUCCESS = "EDIT_SUCCESS"; + + /** + * The col label change failed. + */ + String COL_LABEL_CHANGE_FAILED = "EDIT_FAILED"; + + /** + * The col label boolean datatype.labels for the datatype configuration + */ + String COL_LABEL_BOOLEAN_DATATYPE = "BOOLEAN_DATATYPE"; + + /** + * The col label date time datatype. + */ + String COL_LABEL_DATE_TIME_DATATYPE = "DATE_TIME_DATATYPE"; + + /** + * The check box config label. + */ + String CHECK_BOX_CONFIG_LABEL = "CHECK_BOX_CONFIG_LABEL"; + + /** + * The date data type. + */ + String DATE_DATA_TYPE = "DATE_DATA_TYPE"; + + /** + * The drop down list data type. + */ + String DROP_DOWN_LIST_DATA_TYPE = "DROP_DOWN_LIST_DATA_TYPE"; + + /** + * The drop down list on delete. + */ + String DROP_DOWN_LIST_ON_DELETE = "DROP_DOWN_LIST_ON_DELETE"; + + /** + * The combo box data type. + */ + String COMBO_BOX_DATA_TYPE = "COMBO_BOX_DATA_TYPE"; + + /** + * The col label readonly cell. + */ + String COL_LABEL_READONLY_CELL = "DISTRIBUTED_COLUMN"; + + /** + * The col label copy readonly cell. + */ + String COL_LABEL_COPY_READONLY_CELL = "PARTIAL_COPY_CELL"; + + /** + * The col header label readonly cell. + */ + String COL_HEADER_LABEL_READONLY_CELL = "READ_ONLY_HEADER"; + + /** + * The col label edit inserted distributable column. + */ + String COL_LABEL_EDIT_INSERTED_DISTRIBUTABLE_COLUMN = "EDIT_DISTRIBUTABLE_COLUMN"; + + /** + * The col label null values. + */ + String COL_LABEL_NULL_VALUES = "NULL_VALUES"; + + /** + * The col label failed and modified. + */ + String COL_LABEL_FAILED_AND_MODIFIED = "FAILED_AND_MODIFIED"; + + /** + * The col label custom dialog. + */ + String COL_LABEL_CUSTOM_DIALOG = "CUSTOM_DIALOG"; + + /** + * The col label custom dialog referencing table. + */ + String COL_LABEL_CUSTOM_DIALOG_REFERENCING_TABLE = "CUSTOM_DIALOG_REFERENCING_TABLE"; + + /** + * The col label custom clms dialog. + */ + String COL_LABEL_CUSTOM_CLMS_DIALOG = "COL_LABEL_CUSTOM_CLMS_DIALOG"; + + /** + * The col label not supported multidialog. + */ + String COL_LABEL_NOT_SUPPORTED_MULTIDIALOG = "MULTIDIALOG_NOT_SUPPORTED"; + + /** + * The drop down list part type. + */ + String DROP_DOWN_LIST_PART_TYPE = "DROP_DOWN_LIST_PART_TYPE"; + + /** + * The col label blob type cell. + */ + String COL_LABEL_BLOB_TYPE_CELL = "COL_LABEL_BLOB_TYPE_CELL"; + + /** + * The col label cursor type cell. + */ + String COL_LABEL_CURSOR_TYPE_CELL = "COL_LABEL_CURSOR_TYPE_CELL"; + + /** + * The col label out parameter type cell. + */ + String COL_LABEL_OUT_PARA_TYPE_CELL = "COL_LABEL_OUT_PARA_TYPE_CELL"; + + /** + * The col label bytea type cell. + */ + String COL_LABEL_BYTEA_TYPE_CELL = "COL_LABEL_BYTEA_TYPE_CELL"; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/ITableGridStyleLabelFactory.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/ITableGridStyleLabelFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..f437e16ad554cb135c73c02fc7dddc897f9960f2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/ITableGridStyleLabelFactory.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +/** + * Title: ITableGridStyleLabelFactory + * + * Description:A factory for creating ITableGridStyleLabel objects. + * + * @since 3.0.0 + */ +public interface ITableGridStyleLabelFactory { + + /** + * The col label date datatype. + */ + String COL_LABEL_DATE_DATATYPE = "DATE_DATATYPE"; + + /** + * The col label time datatype. + */ + String COL_LABEL_TIME_DATATYPE = "TIME_DATATYPE"; + + /** + * The col label time withtimezone. + */ + String COL_LABEL_TIME_WITHTIMEZONE = "TIME_WITH_TIMEZONE"; + + /** + * The common grid date format. + */ + String COMMON_GRID_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; + + /** + * The common grid time format. + */ + String COMMON_GRID_TIME_FORMAT = "HH:mm:ss"; + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/RowEffectedConfirmationPrompt.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/RowEffectedConfirmationPrompt.java new file mode 100644 index 0000000000000000000000000000000000000000..1a1f8372b68aa1d85cef5bf5e96147778af87c0a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/RowEffectedConfirmationPrompt.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.utils.DBDisconnectConfirmationDialog; + +/** + * + * Title: class + * + * Description: The Class RowEffectedConfirmationPrompt. + * + * @since 3.0.0 + */ +public class RowEffectedConfirmationPrompt extends DBDisconnectConfirmationDialog { + private static final int YES = 1; + + /** + * Instantiates a new row effected confirmation prompt. + * + * @param parentShell the parent shell + * @param dialogTitle the dialog title + * @param dialogTitleImage the dialog title image + * @param dialogMessage the dialog message + * @param dialogImageType the dialog image type + * @param subMessage the sub message + * @param defaultIndex the default index + */ + public RowEffectedConfirmationPrompt(Shell parentShell, String dialogTitle, Image dialogTitleImage, + String dialogMessage, int dialogImageType, String[] subMessage, int defaultIndex) { + super(parentShell, dialogTitle, dialogTitleImage, dialogMessage, dialogImageType, subMessage, defaultIndex); + + } + + /** + * Creates the custom area. + * + * @param parent the parent + * @return the control + */ + @Override + protected Control createCustomArea(Composite parent) { + Composite comp = new Composite(parent, SWT.NONE); + GridData data = new GridData(); + data.horizontalAlignment = SWT.CENTER; + comp.setLayout(new GridLayout()); + comp.setLayoutData(data); + + return comp; + } + + /** + * Button pressed. + * + * @param buttonId the button id + */ + @Override + protected void buttonPressed(int buttonId) { + super.buttonPressed(buttonId); + } + + /** + * Creates the buttons for button bar. + * + * @param parent the parent + */ + @Override + protected void createButtonsForButtonBar(Composite parent) { + final String labelContinueBtn = " " + MessageConfigLoader.getProperty(IMessagesConstants.BTN_OK) + " "; + + Button continueBtn = createButton(parent, YES, labelContinueBtn, false); + continueBtn.setData(MPPDBIDEConstants.SWTBOT_KEY, "ID_CONTINUE_001"); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/SEARCHOPTIONS.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/SEARCHOPTIONS.java new file mode 100644 index 0000000000000000000000000000000000000000..f45293fe7ae99db7898ce08379eac361ce4cf566 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/SEARCHOPTIONS.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: enum + * + * Description: The Enum SEARCHOPTIONS. + * + * @since 3.0.0 + */ +public enum SEARCHOPTIONS { + + /** + * The srch contains. + */ + SRCH_CONTAINS(MessageConfigLoader.getProperty(IMessagesConstants.SEARCH_OPT_CONTAINS)), + + /** + * The srch equals. + */ + SRCH_EQUALS(MessageConfigLoader.getProperty(IMessagesConstants.SEARCH_OPT_EQUALS)), + + /** + * The srch starts with. + */ + SRCH_STARTS_WITH(MessageConfigLoader.getProperty(IMessagesConstants.SEARCH_OPT_STARTS_WITH)), + + /** + * The srch regex. + */ + SRCH_REGEX(MessageConfigLoader.getProperty(IMessagesConstants.SEARCH_OPT_REGEX)), + + /** + * The srch null. + */ + SRCH_NULL(MessageConfigLoader.getProperty(IMessagesConstants.SEARCH_OPT_NULL)); + + private final String displayName; + + private SEARCHOPTIONS(String name) { + this.displayName = name; + } + + /** + * Gets the display name. + * + * @return the display name + */ + public String getDisplayName() { + return this.displayName; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/ServerObjectTypeForDialog.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/ServerObjectTypeForDialog.java new file mode 100644 index 0000000000000000000000000000000000000000..c570203f345704fd90e77ac64277fa15a26f0b40 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/ServerObjectTypeForDialog.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +/** + * + * Title: enum + * + * Description: The Enum ServerObjectTypeForDialog. + * + * @since 3.0.0 + */ +public enum ServerObjectTypeForDialog { + + COLUMNS, CONSTRAINTS, INDEX, GENERAL +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/TableGridStyleConfiguration.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/TableGridStyleConfiguration.java new file mode 100644 index 0000000000000000000000000000000000000000..903468655cb8b87904b469f1ef7fa567fb722836 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/TableGridStyleConfiguration.java @@ -0,0 +1,232 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import javax.annotation.PreDestroy; + +import org.eclipse.nebula.widgets.nattable.config.CellConfigAttributes; +import org.eclipse.nebula.widgets.nattable.config.DefaultNatTableStyleConfiguration; +import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry; +import org.eclipse.nebula.widgets.nattable.extension.nebula.richtext.MarkupDisplayConverter; +import org.eclipse.nebula.widgets.nattable.extension.nebula.richtext.RegexMarkupValue; +import org.eclipse.nebula.widgets.nattable.extension.nebula.richtext.RichTextCellPainter; +import org.eclipse.nebula.widgets.nattable.grid.GridRegion; +import org.eclipse.nebula.widgets.nattable.layer.cell.CellDisplayConversionUtils; +import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell; +import org.eclipse.nebula.widgets.nattable.painter.cell.BackgroundPainter; +import org.eclipse.nebula.widgets.nattable.painter.cell.ImagePainter; +import org.eclipse.nebula.widgets.nattable.painter.cell.decorator.PaddingDecorator; +import org.eclipse.nebula.widgets.nattable.resize.command.ColumnResizeCommand; +import org.eclipse.nebula.widgets.nattable.resize.command.RowResizeCommand; +import org.eclipse.nebula.widgets.nattable.style.CellStyleAttributes; +import org.eclipse.nebula.widgets.nattable.style.CellStyleUtil; +import org.eclipse.nebula.widgets.nattable.style.DisplayMode; +import org.eclipse.nebula.widgets.nattable.style.IStyle; +import org.eclipse.nebula.widgets.nattable.style.SelectionStyleLabels; +import org.eclipse.nebula.widgets.nattable.style.Style; +import org.eclipse.nebula.widgets.nattable.util.GUIHelper; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Rectangle; + +import org.opengauss.mppdbide.view.component.IGridUIPreference; +import org.opengauss.mppdbide.view.component.IGridUIPreference.ColumnWidthType; +import org.opengauss.mppdbide.view.component.grid.core.DsGridRichTextPainter; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * + * Title: class + * + * Description: The Class TableGridStyleConfiguration. + * + * @since 3.0.0 + */ +public class TableGridStyleConfiguration extends DefaultNatTableStyleConfiguration + implements ITableGridStyleLabelFactory { + + /** + * The regex markup value. + */ + protected RegexMarkupValue regexMarkupValue; + private IGridUIPreference uiPref; + private IDataGridContext dataGridContext; + + /** + * Instantiates a new table grid style configuration. + * + * @param regexMarkupValue the regex markup value + * @param uiPref the ui pref + * @param dataGridContext the data grid context + */ + public TableGridStyleConfiguration(RegexMarkupValue regexMarkupValue, IGridUIPreference uiPref, + IDataGridContext dataGridContext) { + this.regexMarkupValue = regexMarkupValue; + this.uiPref = uiPref; + this.dataGridContext = dataGridContext; + /* + * 1. text wrapping enabled and 2. auto-resizing disabled. 3. cell + * Padding added to 2 pixels + */ + // wrapText: true, calculateByTextLength: false, calculateByTextHeight: + // false + RichTextCellPainter richTextCellPainter = null; + if (uiPref.getColumnWidthStrategy() == ColumnWidthType.DATA_WIDTH) { + // Automatically grow the column length to max configured size. + richTextCellPainter = new GridRichTextPainter(); + } else { + // Restricted column length + richTextCellPainter = new RichTextCellPainter(uiPref.isWordWrap(), false, false); + } + + this.cellPainter = new BackgroundPainter(new PaddingDecorator(richTextCellPainter, 2)); + + /* + * Can control 1. Support Text wrapping? 2. Repaint background? 3. space + * between text & cell border? 4. calculate borders based on content? + */ + // wrapText + + } + + /** + * Configure registry. + * + * @param configRegistry the config registry + */ + @Override + public void configureRegistry(IConfigRegistry configRegistry) { + super.configureRegistry(configRegistry); + + // Markuip for highlighting + MarkupDisplayConverter markupCoverter = new DSHtmlEscapedMarkupDisplayConverter(this.uiPref, + this.dataGridContext); + markupCoverter.registerMarkup("highlight", regexMarkupValue); + + // Register markup display converter for normal display mode. + configRegistry.registerConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER, markupCoverter, + DisplayMode.NORMAL, GridRegion.BODY); + + configRegistry.registerConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER, new MarkupDisplayConverter(), + DisplayMode.EDIT, GridRegion.BODY); + + // Display corner icon. + configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, + new ImagePainter(IconUtility.getIconImage(IiconPath.DSGRID_CORNER_BUTTON, this.getClass())), + DisplayMode.NORMAL, GridRegion.CORNER); + + // Configure null value style + configureSelectionCellStyle(configRegistry); + + // Configure Date Time display configuration + } + + /** + * Configure selection cell style. + * + * @param configuredRegistry the configured registry + */ + protected void configureSelectionCellStyle(IConfigRegistry configuredRegistry) { + Style style = new Style(); + style.setAttributeValue(CellStyleAttributes.FOREGROUND_COLOR, GUIHelper.COLOR_BLACK); + + configuredRegistry.registerConfigAttribute( + // This is attribute to apply + CellConfigAttributes.CELL_STYLE, + // this is value of the attribute + style, + // apply during normal rendering i.e + // except during selection or edit + DisplayMode.SELECT, + // apply above for all cells with this label + SelectionStyleLabels.SELECTION_ANCHOR_STYLE); + + Style nullStyle = new Style(); + nullStyle.setAttributeValue(CellStyleAttributes.FOREGROUND_COLOR, GUIHelper.COLOR_GRAY); + configuredRegistry.registerConfigAttribute( + // this is attribute to apply + CellConfigAttributes.CELL_STYLE, + // this is value of the attribute + nullStyle, + // apply during normal rendering + // except during selection or edit + DisplayMode.NORMAL, + // apply the above for all cells with this label + IEditTableGridStyleLabelFactory.COL_LABEL_NULL_VALUES); + + } + + /** + * Pre destroy. + */ + @PreDestroy + public void preDestroy() { + uiPref = null; + this.cellPainter = null; + this.dataGridContext = null; + } + + /** + * + * Title: class + * + * Description: The Class GridRichTextPainter. + */ + private final class GridRichTextPainter extends RichTextCellPainter { + private GridRichTextPainter() { + super(uiPref.isWordWrap(), true, true); + this.richTextPainter = new DsGridRichTextPainter(true); + } + + @Override + public int getPreferredWidth(ILayerCell cell, GC gc, IConfigRegistry configRegistry) { + int preferredWidth = super.getPreferredWidth(cell, gc, configRegistry); + int maxWidth = TableGridStyleConfiguration.this.uiPref.getMaxDisplayDataLength(); + + return (preferredWidth > maxWidth) ? maxWidth : preferredWidth; + } + + @Override + public void paintCell(ILayerCell cell, GC gc, Rectangle bounds, IConfigRegistry configRegistry) { + IStyle cellStyle = CellStyleUtil.getCellStyle(cell, configRegistry); + setupGCFromConfig(gc, cellStyle); + + String htmlText = CellDisplayConversionUtils.convertDataType(cell, configRegistry); + + Rectangle painterBounds = new Rectangle(bounds.x, bounds.y - this.richTextPainter.getParagraphSpace(), 1000, + bounds.height); + this.richTextPainter.preCalculate(htmlText, gc, painterBounds, true); + + painterBounds.width = this.richTextPainter.getPreferredSize().x; + painterBounds.height = this.richTextPainter.getPreferredSize().y; + this.richTextPainter.paintHTML(htmlText, gc, painterBounds); + int height = this.richTextPainter.getPreferredSize().y - 2 * this.richTextPainter.getParagraphSpace(); + if (height > bounds.height) { + cell.getLayer().doCommand(new RowResizeCommand(cell.getLayer(), cell.getRowPosition(), + GUIHelper.convertVerticalDpiToPixel(height) + (cell.getBounds().height - bounds.height))); + } + + int width = (cell.getBounds().width < bounds.width) ? 0 : cell.getBounds().width - bounds.width; + + if (this.richTextPainter.getPreferredSize().x > bounds.width) { + cell.getLayer().doCommand(new ColumnResizeCommand(cell.getLayer(), cell.getColumnPosition(), + GUIHelper.convertHorizontalDpiToPixel(this.richTextPainter.getPreferredSize().x) + width)); + } + + } + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/TextScrollEventDataLoadListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/TextScrollEventDataLoadListener.java new file mode 100644 index 0000000000000000000000000000000000000000..9ee56441e09b3a4da9000c4e4f5a2ea2c0a8579c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/TextScrollEventDataLoadListener.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; + +import org.eclipse.swt.custom.StyledText; + +import org.opengauss.mppdbide.presentation.grid.IDSEditGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.utils.observer.DSEventTable; +import org.opengauss.mppdbide.utils.observer.IDSGridUIListenable; +import org.opengauss.mppdbide.view.component.DSGridStateMachine; +import org.opengauss.mppdbide.view.component.grid.core.DataText; + +/** + * Title: TextScrollEventDataLoadListener + * + * Description:The listener interface for receiving textScrollEventDataLoad + * events. The class that is interested in processing a textScrollEventDataLoad + * event implements this interface, and the object created with that class is + * registered with a component using the component's + * addTextScrollEventDataLoadListener method. When the + * textScrollEventDataLoad event occurs, that object's appropriate method is + * invoked. + * + * @since 3.0.0 + */ +public class TextScrollEventDataLoadListener extends GridAndTextScrollEventDataLoadListener { + private DataText datatext; + private StyledText text; + + /** + * Instantiates a new text scroll event data load listener. + * + * @param text the text + * @param dataProvider the data provider + * @param eventTable the event table + * @param stateMachine the state machine + * @param datatext the datatext + */ + public TextScrollEventDataLoadListener(StyledText text, IDSGridDataProvider dataProvider, DSEventTable eventTable, + DSGridStateMachine stateMachine, DataText datatext) { + super(dataProvider, eventTable, stateMachine); + this.datatext = datatext; + this.text = text; + } + + /** + * Checks if is last row selected. + * + * @return true, if is last row selected + */ + @Override + public boolean isLastRowSelected() { + if (this.getDataProvider() instanceof IDSEditGridDataProvider) { + return this.datatext.getSelectedRowPosition() == (this.getDataProvider().getRecordCount() + + ((IDSEditGridDataProvider) this.getDataProvider()).getInsertedRowCount()) - 1; + } + return this.datatext.getSelectedRowPosition() == this.getDataProvider().getRecordCount() - 1; + } + + /** + * Trigger load more records. + * + * @param isKeyStrokeTriggeredScrollEvent the is key stroke triggered scroll + * event + */ + @Override + public void triggerLoadMoreRecords(boolean isKeyStrokeTriggeredScrollEvent) { + if ((isKeyStrokeTriggeredScrollEvent ? isLastRowSelected() + : text.getVerticalBar().getSelection() + text.getVerticalBar().getPageIncrement() >= text + .getVerticalBar().getMaximum()) + && !this.getDataProvider().isEndOfRecords() && !isSearchInProgress() + && !isCurrentInitDataTextSatatu()) { + if (ChronoUnit.MILLIS.between(this.getLastLoadTime(), LocalDateTime.now()) >= 2000) { + this.setLastLoadTime(LocalDateTime.now()); + if (this.getStateMachine().set(DSGridStateMachine.State.LOADING)) { + this.getEventTable().sendEvent( + new DSEvent(IDSGridUIListenable.LISTEN_TYPE_ON_REEXECUTE_QUERY, getDataProvider())); + } + } + } + + } + + /** + * On pre destroy. + */ + public void onPreDestroy() { + super.onPreDestroy(); + this.datatext = null; + } + + @Override + public void updateScrolledPosition(int position, int pageIncrement, int increment) { + datatext.updateScrolledInfo(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/ToolBarConstants.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/ToolBarConstants.java new file mode 100644 index 0000000000000000000000000000000000000000..f1bc26d2796207fbc0b3777e36ab4db672f25ee7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/ToolBarConstants.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +/** + * + * Title: interface + * + * Description: The Interface ToolBarConstants. + * + * @since 3.0.0 + */ +public interface ToolBarConstants { + + /** + * The Constant COPY_TOOLITEM. + */ + public static final String COPY_TOOLITEM = "COPY"; + + /** + * The Constant ADD_TOOLITEM. + */ + public static final String ADD_TOOLITEM = "ADD"; + + /** + * The Constant DELETE_TOOLITEM. + */ + public static final String DELETE_TOOLITEM = "DELETE"; + + /** + * The Constant COMMIT_TOOLITEM. + */ + public static final String COMMIT_TOOLITEM = "COMMIT"; + + /** + * The Constant CANCEL_TOOLITEM. + */ + public static final String CANCEL_TOOLITEM = "CANCEL"; + + /** + * The Constant REFRESH_TOOLITEM. + */ + public static final String REFRESH_TOOLITEM = "REFRESH"; + + /** + * The Constant CASESENSITIVE_TOOLITEM. + */ + public static final String CASESENSITIVE_TOOLITEM = "CASESENSITIVE"; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/UserPromptMessageForUnqCons.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/UserPromptMessageForUnqCons.java new file mode 100644 index 0000000000000000000000000000000000000000..6eb3166d2d1c52e38521629f0d028986e2b3d7f6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/UserPromptMessageForUnqCons.java @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.utils.DBDisconnectConfirmationDialog; + +/** + * + * Title: class + * + * Description: The Class UserPromptMessageForUnqCons. + * + * @since 3.0.0 + */ +public class UserPromptMessageForUnqCons extends DBDisconnectConfirmationDialog { + private static final int USE_ALL_COLUMN = 0; + private static final int CUSTOM_COLUMN = 1; + private static final int CANCEL = 2; + private Button rememberDecisionBtn; + private boolean userSelectionOfRemember; + + /** + * Checks if is user selection of remember. + * + * @return true, if is user selection of remember + */ + public boolean isUserSelectionOfRemember() { + return userSelectionOfRemember; + } + + /** + * Instantiates a new user prompt message for unq cons. + * + * @param parentShell the parent shell + * @param dialogTitle the dialog title + * @param dialogTitleImage the dialog title image + * @param dialogMessage the dialog message + * @param dialogImageType the dialog image type + * @param subMessage the sub message + * @param defaultIndex the default index + */ + public UserPromptMessageForUnqCons(Shell parentShell, String dialogTitle, Image dialogTitleImage, + String dialogMessage, int dialogImageType, String[] subMessage, int defaultIndex) { + super(parentShell, dialogTitle, dialogTitleImage, dialogMessage, dialogImageType, subMessage, defaultIndex); + } + + /** + * Creates the custom area. + * + * @param parent the parent + * @return the control + */ + @Override + protected Control createCustomArea(Composite parent) { + Composite comp = new Composite(parent, SWT.NONE); + GridData data = new GridData(); + data.horizontalAlignment = SWT.CENTER; + comp.setLayout(new GridLayout()); + comp.setLayoutData(data); + + rememberDecisionBtn = new Button(comp, SWT.CHECK | SWT.UP); + rememberDecisionBtn.setText(MessageConfigLoader.getProperty(IMessagesConstants.EDIT_TABLE_REMEMBER_CHOICE)); + rememberDecisionBtn.setSelection(false); + + return comp; + } + + /** + * Button pressed. + * + * @param buttonId the button id + */ + @Override + protected void buttonPressed(int buttonId) { + this.userSelectionOfRemember = rememberDecisionBtn.getSelection(); + super.buttonPressed(buttonId); + } + + /** + * Creates the buttons for button bar. + * + * @param parent the parent + */ + @Override + protected void createButtonsForButtonBar(Composite parent) { + Button useAllColumnBtn = null; + Button customUnqKeyBtn = null; + Button cancelBtn = null; + + final String labelUseAllColBtn = " " + + MessageConfigLoader.getProperty(IMessagesConstants.USE_ALL_COLUMNS_LABEL) + " "; + + final String labelCustomUnqKey = " " + + MessageConfigLoader.getProperty(IMessagesConstants.CUSTOM_UNIQUE_KEY_LABEL) + " "; + + final String labelCancel = " " + MessageConfigLoader.getProperty(IMessagesConstants.CANCEL_LABEL) + " "; + + useAllColumnBtn = createButton(parent, USE_ALL_COLUMN, labelUseAllColBtn, false); + useAllColumnBtn.setData(MPPDBIDEConstants.SWTBOT_KEY, "ID_BUT_CONNECTION_CONTINUE_001"); + + customUnqKeyBtn = createButton(parent, CUSTOM_COLUMN, labelCustomUnqKey, true); + customUnqKeyBtn.setData(MPPDBIDEConstants.SWTBOT_KEY, "ID_BUT_CONNECTION_CANCEL_001"); + + cancelBtn = createButton(parent, CANCEL, labelCancel, false); + cancelBtn.setData(MPPDBIDEConstants.SWTBOT_KEY, "ID_BUT_CONNECTION_CANCEL_001"); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/convert/CustomComboxDefaultDisplayConverter.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/convert/CustomComboxDefaultDisplayConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..dacd180515649ebc3eca0215967fe77fcd474eda --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/convert/CustomComboxDefaultDisplayConverter.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.convert; + +import java.util.Collection; + +import org.eclipse.nebula.widgets.nattable.data.convert.DefaultDisplayConverter; + +/** + * + * Title: class + * + * Description: The Class CustomComboxDefaultDisplayConverter. + * + * @since 3.0.0 + */ +public class CustomComboxDefaultDisplayConverter extends DefaultDisplayConverter { + + /** + * Instantiates a new custom combox default display converter. + */ + public CustomComboxDefaultDisplayConverter() { + super(); + } + + /** + * Canonical to display value. + * + * @param canonicalValue the canonical value + * @return the object + */ + @Override + public Object canonicalToDisplayValue(Object canonicalValue) { + if (canonicalValue instanceof Collection) { + String result = canonicalValue.toString(); + if (result.length() > 1) { + result = result.substring(1, result.length() - 1); + } + return result; + } + if (canonicalValue instanceof String) { + String result = (String) canonicalValue; + if (result.contains("[") && result.contains("]")) { + if (result.length() > 1) { + return result.substring(1, result.length() - 1); + } + } + } + return super.canonicalToDisplayValue(canonicalValue); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/convert/CustomDefaultDateDisplayConverter.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/convert/CustomDefaultDateDisplayConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..96b16d01e0c4204ff0cae615d43ba252f3419c22 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/convert/CustomDefaultDateDisplayConverter.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.convert; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.eclipse.nebula.widgets.nattable.data.convert.DefaultDateDisplayConverter; + +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class CustomDefaultDateDisplayConverter. + * + * @since 3.0.0 + */ +public class CustomDefaultDateDisplayConverter extends DefaultDateDisplayConverter { + private final SimpleDateFormat sdf; + private final Object LOCK = new Object(); + + /** + * Instantiates a new custom default date display converter. + * + * @param format the format + */ + public CustomDefaultDateDisplayConverter(String format) { + super(format); + this.sdf = new SimpleDateFormat(format); + } + + /** + * Canonical to display value. + * + * @param canonicalValue the canonical value + * @return the object + */ + @Override + public Object canonicalToDisplayValue(Object canonicalValue) { + if (canonicalValue == null) { + return canonicalValue; + } + + if (canonicalValue.toString().isEmpty()) { + return canonicalValue; + } + + if (canonicalValue instanceof String) { + Date date = null; + try { + synchronized (LOCK) { + date = sdf.parse(canonicalValue.toString()); + } + } catch (ParseException exception) { + MPPDBIDELoggerUtility.error("parse cell value fail", exception); + } + return super.canonicalToDisplayValue(date == null ? canonicalValue : date); + } else { + return super.canonicalToDisplayValue(canonicalValue); + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/convert/CustomDisplayConverterFactoryImpl.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/convert/CustomDisplayConverterFactoryImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..893d2bd471442a44901ae783553cf338717f68e0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/convert/CustomDisplayConverterFactoryImpl.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.convert; + +import org.eclipse.nebula.widgets.nattable.data.convert.DefaultDateDisplayConverter; +import org.eclipse.nebula.widgets.nattable.data.convert.DefaultDisplayConverter; + +/** + * + * Title: class + * + * Description: The Class CustomDisplayConverterFactoryImpl. + * + * @since 3.0.0 + */ +public class CustomDisplayConverterFactoryImpl implements DisplayConverterFactoryIf { + + /** + * Gets the custom default date display converter. + * + * @param format the format + * @return the custom default date display converter + */ + public DefaultDateDisplayConverter getCustomDefaultDateDisplayConverter(String format) { + return new CustomDefaultDateDisplayConverter(format); + + } + + /** + * Gets the custom combox default display converter. + * + * @return the custom combox default display converter + */ + public DefaultDisplayConverter getCustomComboxDefaultDisplayConverter() { + return new CustomComboxDefaultDisplayConverter(); + + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/convert/DisplayConverterFactoryIf.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/convert/DisplayConverterFactoryIf.java new file mode 100644 index 0000000000000000000000000000000000000000..2afc53a70ea4247d4f68f3eef448bada49a6f7bf --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/convert/DisplayConverterFactoryIf.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.convert; + +import org.eclipse.nebula.widgets.nattable.data.convert.DefaultDateDisplayConverter; +import org.eclipse.nebula.widgets.nattable.data.convert.DefaultDisplayConverter; + +/** + * + * Title: interface + * + * Description: The Interface DisplayConverterFactoryIf. + * + * @since 3.0.0 + */ +public interface DisplayConverterFactoryIf { + + /** + * Gets the custom default date display converter. + * + * @param format the format + * @return the custom default date display converter + */ + public DefaultDateDisplayConverter getCustomDefaultDateDisplayConverter(String format); + + /** + * Gets the custom combox default display converter. + * + * @return the custom combox default display converter + */ + public DefaultDisplayConverter getCustomComboxDefaultDisplayConverter(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/convert/DisplayConverterFactoryProvider.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/convert/DisplayConverterFactoryProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..389178d69118047a46fdb8bea8a561b06d93bffc --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/convert/DisplayConverterFactoryProvider.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.convert; + +/** + * + * Title: class + * + * Description: The Class DisplayConverterFactoryProvider. + * + * @since 3.0.0 + */ +public abstract class DisplayConverterFactoryProvider { + + /** + * Gets the display converter factory. + * + * @return the display converter factory + */ + public static DisplayConverterFactoryIf getDisplayConverterFactory() { + return new CustomDisplayConverterFactoryImpl(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/Animation.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/Animation.java new file mode 100644 index 0000000000000000000000000000000000000000..94666dae80c76b2e076ca6c97c9eea48d76b4bff --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/Animation.java @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.Thread.UncaughtExceptionHandler; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.DisposeEvent; +import org.eclipse.swt.events.DisposeListener; +import org.eclipse.swt.events.PaintEvent; +import org.eclipse.swt.events.PaintListener; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.ImageData; +import org.eclipse.swt.graphics.ImageLoader; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.widgets.Canvas; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; + +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: The Class Animation + * + * @since 3.0.0 + */ +public class Animation { + /** + * The display composite. + */ + private Composite displayComposite; + + /** + * The display. + */ + private Display display; + + /** + * The image streambytes. + */ + private byte[] imageStreambytes; + + /** + * Instantiates a new animation. + * + * @param displayComposite the display composite + * @param imageStreambytes the image streambytes + */ + public Animation(Composite displayComposite, byte[] imageStreambytes) { + this.displayComposite = displayComposite; + this.imageStreambytes = imageStreambytes.clone(); + this.display = displayComposite.getDisplay(); + } + + /** + * Gets the canvas. + * + * @return the canvas + */ + public Canvas getCanvas() { + final Canvas canvas = new Canvas(displayComposite, SWT.NULL); + GridData canvasGD = new GridData(SWT.FILL, SWT.FILL, true, true); + canvas.setLayoutData(canvasGD); + + ImageLoader imageLoader = new ImageLoader(); + try (InputStream inputStreamReader = new BufferedInputStream(new ByteArrayInputStream(imageStreambytes))) { + imageLoader.load(inputStreamReader); + } catch (IOException e) { + MPPDBIDELoggerUtility.error("failed to load an array of ImageData objects from the specified input stream"); + } + final ImageData[] imageDatas = imageLoader.data; + final Image image = new Image(display, imageDatas[0].width, imageDatas[0].height); + canvas.addPaintListener(new PaintListener() { + + /** + * the paintControl + * + * @param event the event + */ + public void paintControl(PaintEvent event) { + event.gc.drawImage(image, 0, 0); + } + }); + final GC gc = new GC(image); + final Thread thread = animationThread(canvas, imageDatas, gc); + uncaughtExeptionHandle(thread); + threadInterruptOnCloseListener(thread, canvas); + thread.start(); + return canvas; + } + + private Thread animationThread(final Canvas canvas, final ImageData[] imageDatas, final GC gc) { + final Thread thread = new Thread() { + int frameIndex = 0; + + /* + * (non-Javadoc) + * + * @see java.lang.Thread#run() + */ + public void run() { + while (!isInterrupted()) { + frameIndex %= imageDatas.length; + + final ImageData frameData = imageDatas[frameIndex]; + display.asyncExec(new Runnable() { + /* + * (non-Javadoc) + * + * @see java.lang.Runnable#run() + */ + public void run() { + Image frame = new Image(display, frameData); + gc.drawImage(frame, frameData.x, frameData.y); + frame.dispose(); + if (!canvas.isDisposed()) { + canvas.redraw(); + } + } + }); + try { + // delay + Thread.sleep(imageDatas[frameIndex].delayTime * 10L); + } catch (InterruptedException excep) { + MPPDBIDELoggerUtility.warn("Warning: InterruptedException occurs so returning"); + return; + } + frameIndex += 1; + } + } + }; + thread.setName("Gif_Animation_Thread"); + return thread; + } + + private void threadInterruptOnCloseListener(final Thread thread, final Canvas canvas) { + canvas.addDisposeListener(new DisposeListener() { + @Override + public void widgetDisposed(DisposeEvent event) { + thread.interrupt(); + } + }); + } + + private void uncaughtExeptionHandle(final Thread thread) { + thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { + + /** + * the uncaughtException + * + * @param thread the thread + * @param event the event + */ + public void uncaughtException(Thread thread, Throwable event) { + MPPDBIDELoggerUtility.error("Failed to show gif image frames"); + } + }); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSAbstractRegistryConfiguration.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSAbstractRegistryConfiguration.java new file mode 100644 index 0000000000000000000000000000000000000000..971260eb763bf803511cba75cad498dcf47492db --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSAbstractRegistryConfiguration.java @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import org.eclipse.nebula.widgets.cdatetime.CDT; +import org.eclipse.nebula.widgets.nattable.config.AbstractRegistryConfiguration; +import org.eclipse.nebula.widgets.nattable.config.CellConfigAttributes; +import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry; +import org.eclipse.nebula.widgets.nattable.edit.EditConfigAttributes; +import org.eclipse.nebula.widgets.nattable.edit.editor.ComboBoxCellEditor; +import org.eclipse.nebula.widgets.nattable.edit.editor.IComboBoxDataProvider; +import org.eclipse.nebula.widgets.nattable.layer.cell.ColumnOverrideLabelAccumulator; +import org.eclipse.nebula.widgets.nattable.painter.cell.ComboBoxPainter; +import org.eclipse.nebula.widgets.nattable.style.CellStyleAttributes; +import org.eclipse.nebula.widgets.nattable.style.DisplayMode; +import org.eclipse.nebula.widgets.nattable.style.HorizontalAlignmentEnum; +import org.eclipse.nebula.widgets.nattable.style.Style; +import org.eclipse.nebula.widgets.nattable.util.GUIHelper; + +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.presentation.objectproperties.PropertiesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.view.component.grid.IEditTableGridStyleLabelFactory; +import org.opengauss.mppdbide.view.component.grid.convert.DisplayConverterFactoryProvider; +import org.opengauss.mppdbide.view.component.grid.editor.CustomComboBoxCellEditor; +import org.opengauss.mppdbide.view.component.grid.editor.CustomDateCellEditor; + +/** + * + * Title: class + * + * Description: The Class DSAbstractRegistryConfiguration. + * + * @since 3.0.0 + */ +public abstract class DSAbstractRegistryConfiguration extends AbstractRegistryConfiguration + implements IEditTableGridStyleLabelFactory { + + /** + * Sets the column label accumulator. + * + * @param columnLabelAccumulator the new column label accumulator + */ + public abstract void setColumnLabelAccumulator(ColumnOverrideLabelAccumulator columnLabelAccumulator); + + /** + * Register config labels on columns. + * + * @param lblAccumulator the lbl accumulator + * @param colDataprovider the col dataprovider + */ + public abstract void registerConfigLabelsOnColumns(final ColumnOverrideLabelAccumulator lblAccumulator, + IDSGridColumnProvider colDataprovider); + + /** + * Register ui registry to each column. + * + * @param configRegistry the config registry + * @param columnDataProvider the column data provider + */ + public abstract void registerUiRegistryToEachColumn(IConfigRegistry configRegistry, + IDSGridColumnProvider columnDataProvider); + + /** + * Date str register. + * + * @param configRegistry the config registry + */ + public static void dateStrRegister(IConfigRegistry configRegistry) { + CustomDateCellEditor dateCellEditor = new CustomDateCellEditor(MPPDBIDEConstants.USER_ROLE_DATE_DISPLAY_FORMAT, + true, CDT.DROP_DOWN | CDT.DATE_SHORT); + + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, dateCellEditor, DisplayMode.EDIT, + DATE_DATA_TYPE); + configRegistry.registerConfigAttribute( + CellConfigAttributes.DISPLAY_CONVERTER, DisplayConverterFactoryProvider.getDisplayConverterFactory() + .getCustomDefaultDateDisplayConverter(MPPDBIDEConstants.USER_ROLE_DATE_DISPLAY_FORMAT), + DisplayMode.NORMAL, DATE_DATA_TYPE); + } + + /** + * Combo box registry. + * + * @param configRegistry the config registry + * @param comboBoxDataProvider the combo box data provider + */ + public static void comboBoxRegistry(IConfigRegistry configRegistry, IComboBoxDataProvider comboBoxDataProvider) { + CustomComboBoxCellEditor comboBoxCellEditor = new CustomComboBoxCellEditor(comboBoxDataProvider, + PropertiesConstants.COMBO_BOX_MAX_VISIBLE_ITEM); + comboBoxCellEditor.setMultiselect(true); + comboBoxCellEditor.setUseCheckbox(true); + + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, comboBoxCellEditor, DisplayMode.EDIT, + COMBO_BOX_DATA_TYPE); + configRegistry.registerConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER, + DisplayConverterFactoryProvider.getDisplayConverterFactory().getCustomComboxDefaultDisplayConverter(), + DisplayMode.NORMAL, COMBO_BOX_DATA_TYPE); + + Style cellStyle = new Style(); + cellStyle.setAttributeValue(CellStyleAttributes.BACKGROUND_COLOR, GUIHelper.COLOR_WHITE); + configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, cellStyle, DisplayMode.EDIT, + COMBO_BOX_DATA_TYPE); + } + + /** + * Drop down list registry. + * + * @param configRegistry the config registry + * @param comboBoxDataProvider the combo box data provider + * @param configLabel the config label + */ + public static void dropDownListRegistry(IConfigRegistry configRegistry, IComboBoxDataProvider comboBoxDataProvider, + String configLabel) { + ComboBoxCellEditor comboBoxCellEditor = new ComboBoxCellEditor(comboBoxDataProvider, + PropertiesConstants.COMBO_BOX_MAX_VISIBLE_ITEM); + + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, comboBoxCellEditor, DisplayMode.EDIT, + configLabel); + + configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, new ComboBoxPainter(), + DisplayMode.NORMAL, configLabel); + + Style cellStyle = new Style(); + cellStyle.setAttributeValue(CellStyleAttributes.HORIZONTAL_ALIGNMENT, HorizontalAlignmentEnum.LEFT); + configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, cellStyle, DisplayMode.NORMAL, + configLabel); + configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, cellStyle, DisplayMode.EDIT, + configLabel); + } + + /** + * the onPreDestroy + */ + protected abstract void onPreDestroy(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSBlobCellEditor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSBlobCellEditor.java new file mode 100644 index 0000000000000000000000000000000000000000..64805212a1b01a95b7ef6e77b1daea6b463f5147 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSBlobCellEditor.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +/** + * Title: DSBlobCellEditor + * + * @since 3.0.0 + */ +public class DSBlobCellEditor extends DSUnstructuredDataCellEditor { + +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSByteACellEditor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSByteACellEditor.java new file mode 100644 index 0000000000000000000000000000000000000000..8a859ab6bf064cf7e8755bcf77881aac66a94aa9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSByteACellEditor.java @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.KeyAdapter; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.widgets.Shell; + +/** + * Title: DSByteACellEditor + * + * @since 3.0.0 + */ +public class DSByteACellEditor extends DSUnstructuredDataCellEditor { + @Override + protected void getTableDataEditor(Object originalCanonicalValue, Shell shell) { + DSByteATableDataEditor dialog = new DSByteATableDataEditor(shell, this, originalCanonicalValue); + dialog.open(); + } + + /** + * The Class DSByteATableDataEditor. + */ + private static class DSByteATableDataEditor extends DSUnstructuredDataTableDataEditor { + /** + * Instantiates a new DS byte A table data editor. + * + * @param parentShell the parent shell + * @param cellEditor the cell editor + * @param originalCanonicalValue the original canonical value + */ + public DSByteATableDataEditor(Shell parentShell, DSUnstructuredDataCellEditor cellEditor, + Object originalCanonicalValue) { + super(parentShell, cellEditor, originalCanonicalValue); + } + + @Override + protected String getEditorText() { + return editor.getText(); + } + + @Override + protected void addEditorTextKeyListener() { + editor.addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent keyEvent) { + status.setText(""); + keyEvent.doit = false; + if (isSelectAll(keyEvent)) { + editor.selectAll(); + return; + } else if (editor.getText().startsWith("\\x")) { + actionOnHexEditor(keyEvent); + } else { + enableOkBtnWhenCellEditable(); + keyEvent.doit = true; + } + } + + private void actionOnHexEditor(KeyEvent keyEvent) { + if (String.valueOf(keyEvent.character).matches("[0-9A-Fa-f]+") || isBackSpace(keyEvent) + || isPaste(keyEvent)) { + enableOkBtnWhenCellEditable(); + keyEvent.doit = true; + } else if (isArrowKeys(keyEvent) || isCopy(keyEvent)) { + keyEvent.doit = true; + } else { + keyEvent.doit = false; + } + } + + private boolean isSelectAll(KeyEvent keyEvent) { + return keyEvent.stateMask == SWT.CTRL && keyEvent.keyCode == 'a'; + } + + private boolean isPaste(KeyEvent keyEvent) { + return keyEvent.stateMask == SWT.CTRL && keyEvent.keyCode == 'v'; + } + + private boolean isBackSpace(KeyEvent event) { + return event.character == '\b'; + } + + private boolean isCopy(KeyEvent keyEvent) { + return keyEvent.stateMask == SWT.CTRL && keyEvent.keyCode == 'c'; + } + + private boolean isArrowKeys(KeyEvent keyEvent) { + return keyEvent.keyCode == SWT.ARROW_UP || keyEvent.keyCode == SWT.ARROW_DOWN + || keyEvent.keyCode == SWT.ARROW_LEFT + || keyEvent.keyCode == SWT.ARROW_RIGHT; + } + + private void enableOkBtnWhenCellEditable() { + if (!cellEditor.isCellEditable()) { + clearBtn.setEnabled(true); + } + } + }); + } + + @Override + protected byte[] getBytesFromEditorText(String editorTxt) { + return editorDataToByteArray(editorTxt); + } + + @Override + protected String loadHexInEditorText() { + return DSUnstructuredDataConversionHelper.bytesToHexFormated(valueBytes); + } + + /** + * Editor data to byte array. + * + * @param editorData the editor data + * @return the byte[] + * @throws StringIndexOutOfBoundsException the string index out of + * bounds exception + */ + private byte[] editorDataToByteArray(String editorData) throws StringIndexOutOfBoundsException { + String hex = null; + if (editorData.startsWith("\\x")) { + hex = editorData.substring(2, editorData.length()); + } else { + hex = DSUnstructuredDataConversionHelper.convertStringToHex(editorData); + } + return DSUnstructuredDataConversionHelper.hexStringToByteArray(hex); + } + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSCopyDataCommandHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSCopyDataCommandHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..3e9745db08c51fd794274c8b20248fa817354b81 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSCopyDataCommandHandler.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import org.eclipse.nebula.widgets.nattable.copy.command.CopyDataCommandHandler; +import org.eclipse.nebula.widgets.nattable.copy.command.CopyDataToClipboardCommand; +import org.eclipse.nebula.widgets.nattable.copy.serializing.CopyFormattedTextToClipboardSerializer; +import org.eclipse.nebula.widgets.nattable.layer.ILayer; +import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell; +import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer; +import org.eclipse.nebula.widgets.nattable.serializing.ISerializer; + +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; + +/** + * + * Title: class + * + * Description: The Class DSCopyDataCommandHandler. + * + * @since 3.0.0 + */ +public class DSCopyDataCommandHandler extends CopyDataCommandHandler { + + private boolean copyFormattedText; + private IDSGridDataProvider dataProvider; + + /** + * Instantiates a new DS copy data command handler. + * + * @param selectionLayer the selection layer + * @param columnHeaderLayer the column header layer + * @param rowNumberLayer the row number layer + * @param dataProvider the data provider + */ + public DSCopyDataCommandHandler(SelectionLayer selectionLayer, ILayer columnHeaderLayer, ILayer rowNumberLayer, + IDSGridDataProvider dataProvider) { + super(selectionLayer, columnHeaderLayer, rowNumberLayer); + this.dataProvider = dataProvider; + } + + /** + * Do command. + * + * @param command the command + * @return true, if successful + */ + @Override + public boolean doCommand(CopyDataToClipboardCommand command) { + ILayerCell[][] selectedCells = assembleCopiedDataStructure(); + if (null != selectedCells) { + ISerializer serializer = this.copyFormattedText + ? new CopyFormattedTextToClipboardSerializer(selectedCells, command) + : new DSCopyDataToClipboardSerializer(selectedCells, command, dataProvider); + serializer.serialize(); + } + return true; + } + + /** + * Sets the copy formatted text. + * + * @param copyFormattedText the new copy formatted text + */ + public void setCopyFormattedText(boolean copyFormattedText) { + // Calling super to ensure the private copyFormattedText of parent class + // is updated + super.setCopyFormattedText(copyFormattedText); + this.copyFormattedText = copyFormattedText; + } + + /** + * Sets the data provider. + * + * @param dataProvider the new data provider + */ + public void setDataProvider(IDSGridDataProvider dataProvider) { + this.dataProvider = dataProvider; + } + + /** + * On pre destroy. + */ + public void onPreDestroy() { + dataProvider = null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSCopyDataToClipboardSerializer.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSCopyDataToClipboardSerializer.java new file mode 100644 index 0000000000000000000000000000000000000000..e46ee39fb612cf907799deaa9e509c7d383d2410 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSCopyDataToClipboardSerializer.java @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import java.util.List; + +import org.eclipse.nebula.widgets.nattable.copy.command.CopyDataToClipboardCommand; +import org.eclipse.nebula.widgets.nattable.copy.serializing.CopyDataToClipboardSerializer; +import org.eclipse.nebula.widgets.nattable.grid.layer.ColumnHeaderLayer; +import org.eclipse.nebula.widgets.nattable.grid.layer.DefaultColumnHeaderDataLayer; +import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell; +import org.eclipse.swt.dnd.Clipboard; +import org.eclipse.swt.dnd.TextTransfer; +import org.eclipse.swt.dnd.Transfer; +import org.eclipse.swt.widgets.Display; + +import org.opengauss.mppdbide.presentation.edittabledata.DSResultSetGridDataRow; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class DSCopyDataToClipboardSerializer. + * + * @since 3.0.0 + */ +public class DSCopyDataToClipboardSerializer extends CopyDataToClipboardSerializer { + + private final ILayerCell[][] copiedCells; + private final CopyDataToClipboardCommand command; + + private IDSGridDataProvider dataProvider; + private static final String BIT_ONE = "1"; + private static final String BIT_ZERO = "0"; + private static final String BIT_DATATYPE = "bit"; + private static final String NULL = "null"; + + /** + * Instantiates a new DS copy data to clipboard serializer. + * + * @param copiedCells the copied cells + * @param command the command + * @param dataProvider the data provider + */ + public DSCopyDataToClipboardSerializer(ILayerCell[][] copiedCells, CopyDataToClipboardCommand command, + IDSGridDataProvider dataProvider) { + super(copiedCells, command); + this.copiedCells = copiedCells.clone(); + this.command = command; + this.dataProvider = dataProvider; + } + + /** + * Serialize. + */ + @Override + public void serialize() { + final String cellDelim = this.command.getCellDelimeter(); + final String rowDelim = this.command.getRowDelimeter(); + + final TextTransfer textTransfer = TextTransfer.getInstance(); + final StringBuilder txtData = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + int currentRow = 0; + for (ILayerCell[] cells : this.copiedCells) { + int currentCell = 0; + for (ILayerCell cell : cells) { + final String delimeter = ++currentCell < cells.length ? cellDelim : ""; // $NON-NLS-1$ + if (cell != null) { + txtData.append(getTextForCell(cell) + delimeter); + } else { + txtData.append(delimeter); + } + } + if (++currentRow < this.copiedCells.length) { + txtData.append(rowDelim); + } + } + if (txtData.length() > 0) { + final Clipboard clipBoard = new Clipboard(Display.getDefault()); + try { + clipBoard.setContents(new Object[] {txtData.toString()}, new Transfer[] {textTransfer}); + } finally { + clipBoard.dispose(); + } + } else { + final Clipboard clipboard = new Clipboard(Display.getDefault()); + try { + clipboard.setContents(new Object[] {NULL}, new Transfer[] {textTransfer}); + clipboard.clearContents(); + } finally { + clipboard.dispose(); + } + } + } + + /** + * Gets the text for cell. + * + * @param cell the cell + * @return the text for cell + */ + @Override + protected String getTextForCell(ILayerCell cell) { + if (cell.getDataValue() == null) { + return ""; + } + String dataValue = super.getTextForCell(cell); + if (!(cell.getLayer().getUnderlyingLayerByPosition(cell.getColumnPosition(), + cell.getRowPosition()) instanceof DefaultColumnHeaderDataLayer + || cell.getLayer() instanceof ColumnHeaderLayer)) { + String columnDatatypeName = dataProvider.getColumnDataProvider() + .getColumnDataTypeName(cell.getColumnIndex()); + if (columnDatatypeName != null) { + switch (columnDatatypeName) { + case MPPDBIDEConstants.BLOB: { + return MPPDBIDEConstants.BLOB_WATERMARK; + } + case MPPDBIDEConstants.BYTEA: { + return MPPDBIDEConstants.BYTEA_WATERMARK; + } + default: { + break; + } + } + } + } + + if (cell.getRowPosition() > 0 && !dataProvider.getAllFetchedRows().isEmpty() + && cell.getRowPosition() < dataProvider.getAllFetchedRows().size() + && dataProvider.getAllFetchedRows().get(cell.getRowPosition()) != null) { + Object[] row = dataProvider.getAllFetchedRows().get(cell.getRowPosition()).getValues(); + if (row != null && cell.getColumnPosition() > 1 && cell.getColumnPosition() < row.length + && row[cell.getColumnPosition()] instanceof List) { + List dataGridobj = (List) row[cell.getColumnPosition()]; + if (dataGridobj.get(0) instanceof DSResultSetGridDataRow) { + return MPPDBIDEConstants.CURSOR_WATERMARK; + } + } + } + + String columnDataType = this.dataProvider.getColumnDataProvider().getColumnDataTypeName(cell.getColumnIndex()); + int precision = this.dataProvider.getColumnDataProvider().getPrecision(cell.getColumnIndex()); + return getConvertedColumnData(dataValue, columnDataType, precision); + } + + private String getConvertedColumnData(String dataValue, String columnDataType, int precisionValue) { + if (BIT_DATATYPE.equals(columnDataType) && precisionValue <= 1) { + if (Boolean.toString(true).equalsIgnoreCase(dataValue)) { + return BIT_ONE; + } else { + return BIT_ZERO; + } + } + return dataValue; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSCursorResultSetTable.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSCursorResultSetTable.java new file mode 100644 index 0000000000000000000000000000000000000000..573da936d73ca467f22729bb95685c370b61e840 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSCursorResultSetTable.java @@ -0,0 +1,274 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import java.sql.SQLException; +import java.util.List; +import java.util.Observer; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.nebula.widgets.nattable.edit.editor.AbstractCellEditor; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; + +import org.opengauss.mppdbide.presentation.edittabledata.DSCursorTableDataGridDataProvider; +import org.opengauss.mppdbide.presentation.edittabledata.DSResultSetGridDataRow; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSResultRowVisitor; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.utils.observer.IDSGridUIListenable; +import org.opengauss.mppdbide.utils.observer.IDSListener; +import org.opengauss.mppdbide.view.component.GridUIPreference; +import org.opengauss.mppdbide.view.component.IGridUIPreference; +import org.opengauss.mppdbide.view.component.grid.DSGridComponent; +import org.opengauss.mppdbide.view.component.grid.GridSelectionLayerPortData; +import org.opengauss.mppdbide.view.component.grid.GridViewPortData; +import org.opengauss.mppdbide.view.ui.terminal.resulttab.GridResultDataCurrentPageExport; +import org.opengauss.mppdbide.view.ui.terminal.resulttab.GridResultDataSelectedCopyToExcel; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * Title: DSCursorResultSetTable + * + * @since 3.0.0 + */ +public class DSCursorResultSetTable extends AbstractCellEditor { + @Override + protected Control activateCell(Composite parent, Object originalCanonicalValue) { + Shell shell = Display.getDefault().getActiveShell(); + DSCursorResultTableData dialog = null; + try { + if (originalCanonicalValue instanceof List) { + dialog = new DSCursorResultTableData(shell, (List) originalCanonicalValue); + dialog.open(); + } + } catch (SQLException | DatabaseOperationException | DatabaseCriticalException exe) { + MPPDBIDELoggerUtility.error("failed to get cursor dailog values", exe); + } + super.close(); + return getEditorControl(); + } + + private static class DSCursorResultTableData extends Dialog implements IDSListener { + private Object[] valueList; + /** + * the grid component + */ + protected DSGridComponent gridComponent; + private IGridUIPreference resultGridUIPref; + private IDSGridDataProvider dataProvider = null; + private IDSResultRowVisitor visitor = null; + private int formatIndex; + List cursorGridDataRow; + + public DSCursorResultTableData(Shell parentShell, List originalCanonicalValue) + throws SQLException, DatabaseOperationException, DatabaseCriticalException { + super(parentShell); + this.valueList = originalCanonicalValue.get(0).getValues(); + this.cursorGridDataRow = originalCanonicalValue; + this.resultGridUIPref = new CursorResultsGridUIPref(); + this.gridComponent = new DSGridComponent(resultGridUIPref, getCursorDataProvider()); + } + + private IDSGridDataProvider getCursorDataProvider() + throws DatabaseOperationException, DatabaseCriticalException, SQLException { + IDSResultRowVisitor rowVisitor = getVisitor(); + for (int index = 1; index < cursorGridDataRow.size(); index++) { + rowVisitor.visit(cursorGridDataRow.get(index)); + } + return this.dataProvider; + } + + private IDSResultRowVisitor getVisitor() throws DatabaseOperationException, DatabaseCriticalException { + if (null == this.visitor) { + DSCursorTableDataGridDataProvider cursorTableDataProvider = null; + cursorTableDataProvider = new DSCursorTableDataGridDataProvider(valueList); + this.dataProvider = cursorTableDataProvider; + this.visitor = cursorTableDataProvider.initByVisitor(valueList); + cursorTableDataProvider.setEndOfRecords(); + } + return this.visitor; + } + + @Override + protected void configureShell(Shell newShell) { + newShell.setSize(800, 400); + super.configureShell(newShell); + + newShell.setText(MessageConfigLoader.getProperty(IMessagesConstants.CURSOR_DATA_NODE)); + newShell.setImage(IconUtility.getIconImage(IiconPath.ICO_RESULTSET_WINDOW, this.getClass())); + shellAlignCenter(newShell); + } + + private void shellAlignCenter(Shell newShell) { + Rectangle bounds = newShell.getMonitor().getBounds(); + Rectangle rect = newShell.getBounds(); + int xCordination = bounds.x + (bounds.width - rect.width) / 2; + int yCordination = bounds.y + (bounds.height - rect.height) / 2; + newShell.setLocation(xCordination, yCordination); + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite maincomp = (Composite) super.createDialogArea(parent); + this.gridComponent.addListener(IDSGridUIListenable.LISTEN_TYPE_EXPORT_CURR_PAGE_DATA, this); + this.gridComponent.addListener(IDSGridUIListenable.LISTEN_COPY_TO_EXCEL_XLSX_RESULT_WINDOW_MENUITEM, this); + this.gridComponent.addListener(IDSGridUIListenable.LISTEN_COPY_TO_EXCEL_XLS_RESULT_WINDOW_MENUITEM, this); + + maincomp = this.gridComponent.cursorPopupComponents(maincomp, true); + maincomp.setLayout(new GridLayout(1, false)); + GridData maincompGD = new GridData(SWT.FILL, SWT.FILL, true, true); + maincomp.setLayoutData(maincompGD); + return maincomp; + } + + private static class CursorResultsGridUIPref extends GridUIPreference { + @Override + public boolean isShowQueryArea() { + return false; + } + + @Override + public boolean isSupportDataExport() { + return true; + } + + @Override + public boolean isEnableSort() { + return true; + } + + @Override + public boolean isShowLoadMoreRecordButton() { + return false; + } + + @Override + public boolean isShowRightClickMenu() { + return true; + } + + /** + * the isAddItemExportAll + * + * @return the false + */ + public boolean isAddItemExportAll() { + return false; + } + } + + @Override + public void handleEvent(DSEvent event) { + handleToolbarEvents(event); + + switch (event.getType()) { + case IDSGridUIListenable.LISTEN_COPY_TO_EXCEL_XLSX_RESULT_WINDOW_MENUITEM: { + listenOnResultWindowCopyToExcelXlsxMenu(event); + break; + } + case IDSGridUIListenable.LISTEN_COPY_TO_EXCEL_XLS_RESULT_WINDOW_MENUITEM: { + listenResultWindowCopyToExcelXlsMenu(event); + break; + } + default: { + break; + } + } + + } + + private void listenResultWindowCopyToExcelXlsMenu(DSEvent event) { + formatIndex = 1; + GridResultDataSelectedCopyToExcel resultCopyTOExcel = new GridResultDataSelectedCopyToExcel(getSelectData(), + formatIndex, null, null); + resultCopyTOExcel.addObserver((Observer) event.getObject()); + resultCopyTOExcel.export(); + } + + private void listenOnResultWindowCopyToExcelXlsxMenu(DSEvent event) { + formatIndex = 0; + GridResultDataSelectedCopyToExcel resultCopyTOExcel = new GridResultDataSelectedCopyToExcel(getSelectData(), + formatIndex, null, null); + resultCopyTOExcel.addObserver((Observer) event.getObject()); + resultCopyTOExcel.export(); + } + + private GridSelectionLayerPortData getSelectData() { + return this.gridComponent.getSelectDataIterator(); + } + + private void handleToolbarEvents(DSEvent event) { + switch (event.getType()) { + + case IDSGridUIListenable.LISTEN_TYPE_EXPORT_CURR_PAGE_DATA: { + listenOnExportCurrentPage(event); + break; + } + default: { + break; + } + } + } + + private void listenOnExportCurrentPage(DSEvent event) { + GridResultDataCurrentPageExport resultDataExporter = new GridResultDataCurrentPageExport(getUIData(), null, + null, MPPDBIDEConstants.RETURN_RESULT_COL_VALUE); + resultDataExporter.addObserver((Observer) event.getObject()); + + resultDataExporter.export(true); + + } + + private GridViewPortData getUIData() { + return this.gridComponent.getUIDataIterator(); + } + + } + + @Override + public Control createEditorControl(Composite parent) { + return null; + } + + @Override + public Control getEditorControl() { + return null; + } + + @Override + public void setEditorValue(Object value) { + + } + + @Override + public Object getEditorValue() { + return null; + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSNatTable.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSNatTable.java new file mode 100644 index 0000000000000000000000000000000000000000..183d6af1ea21e708fe8cd961a01e780dbf5a706e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSNatTable.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import org.eclipse.nebula.widgets.nattable.NatTable; +import org.eclipse.nebula.widgets.nattable.grid.command.ClientAreaResizeCommand; +import org.eclipse.nebula.widgets.nattable.grid.layer.GridLayer; +import org.eclipse.nebula.widgets.nattable.layer.event.ILayerEvent; +import org.eclipse.swt.widgets.Composite; + +/** + * + * Title: class + * + * Description: The Class DSNatTable. + * + * @since 3.0.0 + */ +public class DSNatTable extends NatTable { + + /** + * Instantiates a new DS nat table. + * + * @param parent the parent + * @param gridLayer the grid layer + * @param boolValue the b + */ + public DSNatTable(Composite parent, GridLayer gridLayer, boolean boolValue) { + super(parent, gridLayer, boolValue); + } + + /** + * Clear configurations. + */ + public void clearConfigurations() { + + this.configurations.clear(); + } + + /** + * Sets the layer. + * + * @param layer the new layer + */ + public void setLayer(GridLayer layer) { + super.setLayer(layer); + // done to enable scrollbar listeners + doCommand(new ClientAreaResizeCommand(this)); + } + + /** + * Handle layer event. + * + * @param event the event + */ + @Override + public void handleLayerEvent(ILayerEvent event) { + if (!this.isDisposed()) { + super.handleLayerEvent(event); + } + } + + /** + * clear Layers : to clear mem leak + */ + public void clearLayers() { + super.setLayerPainter(null); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSNewTextCellEditor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSNewTextCellEditor.java new file mode 100644 index 0000000000000000000000000000000000000000..bbeced85fde5b4ea4d9d4505c3c4dc3f5d48259f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSNewTextCellEditor.java @@ -0,0 +1,287 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import org.eclipse.jface.fieldassist.ContentProposalAdapter; +import org.eclipse.jface.layout.GridDataFactory; +import org.eclipse.nebula.widgets.nattable.edit.EditConfigAttributes; +import org.eclipse.nebula.widgets.nattable.edit.config.RenderErrorHandling; +import org.eclipse.nebula.widgets.nattable.edit.editor.EditorSelectionEnum; +import org.eclipse.nebula.widgets.nattable.edit.editor.IEditErrorHandler; +import org.eclipse.nebula.widgets.nattable.edit.editor.TextCellEditor; +import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer.MoveDirectionEnum; +import org.eclipse.nebula.widgets.nattable.style.DisplayMode; +import org.eclipse.nebula.widgets.nattable.style.HorizontalAlignmentEnum; +import org.eclipse.nebula.widgets.nattable.style.IStyle; +import org.eclipse.nebula.widgets.nattable.widget.EditModeEnum; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.KeyAdapter; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Text; + +import org.opengauss.mppdbide.view.component.grid.DSGridMenuManager; +import org.opengauss.mppdbide.view.component.grid.IEditTableGridStyleLabelFactory; + +/** + * + * Title: class + * + * Description: The Class DSNewTextCellEditor. + * + * @since 3.0.0 + */ +public class DSNewTextCellEditor extends TextCellEditor { + + /** + * Flag to configure whether the text control should enable automatic line + * wrap behaviour or not. By default this editor will support automatic line + * wrapping. + */ + private boolean lineWrap = true; + private Text text = null; + private IEditErrorHandler inputConversionErrorHandler = new RenderErrorHandling(this.decorationProvider); + private boolean isCellEditable = false; + + /** + * Instantiates a new DS new text cell editor. + */ + public DSNewTextCellEditor() { + this(true); + } + + /** + * Instantiates a new DS new text cell editor. + * + * @param lineWrap the line wrap + */ + public DSNewTextCellEditor(boolean lineWrap) { + this.commitOnEnter = true; + this.lineWrap = lineWrap; + } + + /** + * Activate cell. + * + * @param parent the parent + * @param originalCanonicalValue the original canonical value + * @return the control + */ + @Override + public Control activateCell(final Composite parent, Object originalCanonicalValue) { + + this.text = createEditorControl(parent); + isCellEditable = labelStack.hasLabel(IEditTableGridStyleLabelFactory.COL_LABEL_READONLY_CELL); + DSGridMenuManager.addContextMenuWithID(getEditorControl(), !isCellEditable); + // If the originalCanonicalValue is a Character it is possible the + // editor is activated by keypress + if (originalCanonicalValue instanceof Character) { + this.text.setText(originalCanonicalValue.toString()); + selectNewText(EditorSelectionEnum.END); + } + // if there is no initial value, handle the original canonical value to + // transfer it to the text control + else { + setCanonicalValue(originalCanonicalValue); + selectNewText(EditorSelectionEnum.ALL); + } + + this.text.setEditable(isEditable()); + + // show an error decoration if this is enabled + this.decorationProvider.createErrorDecorationIfRequired(this.text); + + // if the input error handlers are of type RenderErrorHandler (default) + // than we also check for a possible configured error styling in the + // configuration + // Note: this is currently only implemented in here, as the + // TextCellEditor is the only editor that supports just in time + // conversion/validation + + IStyle conversionErrorStyle = this.configRegistry.getConfigAttribute( + EditConfigAttributes.CONVERSION_ERROR_STYLE, DisplayMode.EDIT, this.labelStack.getLabels()); + + ((RenderErrorHandling) this.inputConversionErrorHandler).setErrorStyle(conversionErrorStyle); + + // if a IControlContentAdapter is registered, create and register a + // ContentProposalAdapter + if (this.controlContentAdapter != null) { + configureContentProposalAdapter(new ContentProposalAdapter(this.text, this.controlContentAdapter, + this.proposalProvider, this.keyStroke, this.autoActivationCharacters)); + } + + this.text.forceFocus(); + + return this.text; + + } + + /** + * Creates the editor control. + * + * @param parent the parent + * @return the text + */ + @Override + public Text createEditorControl(Composite parent) { + + boolean openInline = openInline(this.configRegistry, this.labelStack.getLabels()); + int style = HorizontalAlignmentEnum.getSWTStyle(this.cellStyle) | SWT.MULTI | SWT.BORDER; + + if (!openInline) { + // if the editor control is opened in a dialog, we add scrolling as + // the size of the control is dependent on the dialog size + style = style | SWT.V_SCROLL | SWT.H_SCROLL; + } else { + this.commitOnEnter = true; + } + + if (this.lineWrap) { + style = style | SWT.WRAP; + } + + final Text textControl = new Text(parent, style); + + textControl.forceFocus(); + if (!openInline) { + // add the layout data directly so it will not be layouted by the + // CellEditDialog + GridDataFactory.fillDefaults().grab(true, true).hint(100, 50).applyTo(textControl); + } + + // add a key listener that will commit or close the editor for special + // key strokes and executes conversion/validation on input to the editor + + textControl.addKeyListener(new KeyAdapter() { + + @Override + public void keyPressed(KeyEvent event) { + if (DSNewTextCellEditor.this.commitOnEnter + && (event.keyCode == SWT.CR || event.keyCode == SWT.KEYPAD_CR)) { + MoveDirectionEnum move = MoveDirectionEnum.NONE; + if (DSNewTextCellEditor.this.editMode == EditModeEnum.INLINE) { + move = MoveDirectionEnum.DOWN; + } + + if (openInline) { + commit(move); + } else { + event.doit = false; + } + + } + if (event.stateMask == SWT.CTRL && event.keyCode == 'a') { + textControl.selectAll(); + } + } + + }); + + return textControl; + } + + /** + * Calculate control bounds. + * + * @param cellBounds the cell bounds + * @return the rectangle + */ + @Override + public Rectangle calculateControlBounds(final Rectangle cellBounds) { + Point size = getEditorControl().computeSize(SWT.DEFAULT, SWT.DEFAULT); + + // add a listener that increases/decreases the size of the control if + // the text is modified as the calculateControlBounds method is only + // called in case of inline editing, this listener shouldn't hurt + // anybody else + getEditorControl().addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + Point point = getEditorControl().computeSize(SWT.DEFAULT, SWT.DEFAULT, true); + Point loc = getEditorControl().getLocation(); + getEditorControl().setBounds(loc.x, loc.y, cellBounds.width, Math.max(point.y, cellBounds.height)); + } + }); + + return new Rectangle(cellBounds.x, cellBounds.y, cellBounds.width, Math.max(size.y, cellBounds.height)); + } + + /** + * Sets the line wrap. + * + * @param lineWrap the new line wrap + */ + public void setLineWrap(boolean lineWrap) { + this.lineWrap = lineWrap; + } + + /** + * Gets the editor control. + * + * @return the editor control + */ + @Override + public Text getEditorControl() { + return this.text; + } + + /** + * Gets the editor value. + * + * @return the editor value + */ + @Override + public String getEditorValue() { + return this.text.getText(); + } + + /* + * * Will set the selection to the wrapped text control regarding the + * configured {@link EditorSelectionEnum}. + * + *

    This method is called + * + * Text#setSelection(int, int) + */ + private void selectNewText(EditorSelectionEnum editorSelectionMode) { + int textLength = this.text.getText().length(); + if (textLength > 0) { + if (editorSelectionMode == EditorSelectionEnum.ALL) { + this.text.setSelection(0, textLength); + } else if (editorSelectionMode == EditorSelectionEnum.END) { + this.text.setSelection(textLength, textLength); + } else if (editorSelectionMode == EditorSelectionEnum.START) { + this.text.setSelection(0); + } + } + } + + /** + * Sets the editor value. + * + * @param value the new editor value + */ + @Override + public void setEditorValue(Object value) { + this.text.setText(value != null && value.toString().length() > 0 ? value.toString() : ""); // $NON-NLS-1$ + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSTextCellEditor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSTextCellEditor.java new file mode 100644 index 0000000000000000000000000000000000000000..7e8590d3900fcceb5c160eeb23e2bb56c8f3d0e2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSTextCellEditor.java @@ -0,0 +1,216 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import java.util.List; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry; +import org.eclipse.nebula.widgets.nattable.edit.editor.TextCellEditor; +import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer.MoveDirectionEnum; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.KeyAdapter; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.events.KeyListener; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.component.grid.DSGridMenuManager; +import org.opengauss.mppdbide.view.component.grid.IEditTableGridStyleLabelFactory; +import org.opengauss.mppdbide.view.utils.consts.UIConstants; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs.MESSAGEDIALOGTYPE; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * + * Title: class + * + * Description: The Class DSTextCellEditor. + * + * @since 3.0.0 + */ +public class DSTextCellEditor extends TextCellEditor { + private boolean isCellEditable = false; + + /** + * Activate cell. + * + * @param parent the parent + * @param originalCanonicalValue the original canonical value + * @return the control + */ + @Override + protected Control activateCell(Composite parent, Object originalCanonicalValue) { + + super.activateCell(parent, originalCanonicalValue); + isCellEditable = labelStack.hasLabel(IEditTableGridStyleLabelFactory.COL_LABEL_READONLY_CELL); + DSGridMenuManager.addContextMenuWithID(getEditorControl(), !isCellEditable); + getEditorControl().addKeyListener(new KeyListener() { + @Override + public void keyReleased(KeyEvent event) { + if (isCellEditable + && !(event.stateMask == SWT.CTRL && event.keyCode == MPPDBIDEConstants.KEY_CODE_FOR_COPY)) { + event.doit = false; + } + } + + @Override + public void keyPressed(KeyEvent event) { + if (isCellEditable + && !(event.stateMask == SWT.CTRL && event.keyCode == MPPDBIDEConstants.KEY_CODE_FOR_COPY)) { + event.doit = false; + } + } + }); + + if (null != originalCanonicalValue + && originalCanonicalValue.toString().length() > IEditTableGridStyleLabelFactory.CANONICAL_LIMIT) { + Shell shell = Display.getDefault().getActiveShell(); + DSTableDataTextEditor dialog = new DSTableDataTextEditor(shell, originalCanonicalValue.toString()); + dialog.open(); + super.close(); + } + + return getEditorControl(); + } + + /** + * Support multi edit. + * + * @param configRegistry the config registry + * @param configLabels the config labels + * @return true, if successful + */ + @Override + public boolean supportMultiEdit(IConfigRegistry configRegistry, List configLabels) { + if (configLabels.contains(IEditTableGridStyleLabelFactory.COL_LABEL_NOT_SUPPORTED_MULTIDIALOG)) { + generateCellSizeExceededDialog(); + return false; + } + if (configLabels.contains(IEditTableGridStyleLabelFactory.COL_LABEL_READONLY_CELL)) { + return false; + } + return super.supportMultiEdit(configRegistry, configLabels); + } + + /** + * Generate cell size exceeded dialog. + */ + protected void generateCellSizeExceededDialog() { + MPPDBIDEDialogs.generateOKMessageDialog(MESSAGEDIALOGTYPE.WARNING, true, + MessageConfigLoader.getProperty(IMessagesConstants.DATA_TOO_LARGE_WARNING), + MessageConfigLoader.getProperty(IMessagesConstants.DATA_TOO_LARGE_DISPLAY_EDIT)); + } + + private class DSTableDataTextEditor extends Dialog { + private Text editor = null; + private String value = null; + private Button okBtn = null; + + /** + * Gets the editor text. + * + * @return the editor text + */ + public String getEditorText() { + return editor.getText(); + } + + /** + * Instantiates a new DS table data text editor. + * + * @param parentShell the parent shell + * @param originalCanonicalValue the original canonical value + */ + public DSTableDataTextEditor(Shell parentShell, String originalCanonicalValue) { + super(parentShell); + this.value = originalCanonicalValue; + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite maincomp = (Composite) super.createDialogArea(parent); + maincomp.setLayout(new GridLayout(1, false)); + GridData maincompGD = new GridData(SWT.FILL, SWT.FILL, true, true); + maincomp.setLayoutData(maincompGD); + + editor = new Text(maincomp, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL | SWT.WRAP); + GridData editorGD = new GridData(SWT.FILL, SWT.FILL, true, true); + editor.setLayoutData(editorGD); + editor.setText(value); + + editor.addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent event) { + if (event.stateMask == SWT.CTRL && event.keyCode == 'a') { + editor.selectAll(); + event.doit = false; + } + } + }); + + return maincomp; + } + + @Override + protected void createButtonsForButtonBar(Composite parent) { + String okLbl = " " + MessageConfigLoader.getProperty(IMessagesConstants.EXEC_PLAN_OK) + " "; + final String cancelLabel = " " + + MessageConfigLoader.getProperty(IMessagesConstants.MPPDBIDE_DIA_BTN_CANC) + " "; + okBtn = createButton(parent, UIConstants.OK_ID, okLbl, true); + createButton(parent, UIConstants.CANCEL_ID, cancelLabel, false); + + configureEditorAndButton(); + } + + private void configureEditorAndButton() { + editor.setEditable(!isCellEditable); + okBtn.setEnabled(!isCellEditable); + } + + @Override + protected void configureShell(Shell newShell) { + newShell.setSize(800, 400); + super.configureShell(newShell); + + newShell.setText(MessageConfigLoader.getProperty(IMessagesConstants.EDITOR_NODE)); + newShell.setImage(IconUtility.getIconImage(IiconPath.ICO_EDIT_EDIT, this.getClass())); + } + + @Override + protected void buttonPressed(int buttonId) { + + if (buttonId == UIConstants.OK_ID) { + setEditorValue(getEditorText()); + commit(MoveDirectionEnum.NONE, true); + close(); + } else { + close(); + } + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSUnstructuredDataCellEditor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSUnstructuredDataCellEditor.java new file mode 100644 index 0000000000000000000000000000000000000000..d241f9eaed4d257bb67a69322cad582caa277c3d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSUnstructuredDataCellEditor.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import java.util.List; + +import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry; +import org.eclipse.nebula.widgets.nattable.edit.editor.AbstractCellEditor; +import org.eclipse.nebula.widgets.nattable.edit.editor.IEditErrorHandler; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; + +import org.opengauss.mppdbide.view.component.grid.IEditTableGridStyleLabelFactory; + +/** + * Title: DSUnstructuredDataCellEditor + * + * @since 3.0.0 + */ +public class DSUnstructuredDataCellEditor extends AbstractCellEditor { + /** + * The is cell editable. + */ + private boolean isCellEditable = false; + + /** + * The byte value. + */ + private byte[] byteValue = null; + + /** + * Checks if is cell editable. + * + * @return true, if is cell editable + */ + public boolean isCellEditable() { + return isCellEditable; + } + + @Override + public Object getEditorValue() { + return byteValue; + } + + @Override + public void setEditorValue(Object value) { + + this.byteValue = (byte[]) value; + } + + @Override + public Control getEditorControl() { + return null; + } + + @Override + public Control createEditorControl(Composite parent) { + return null; + } + + @Override + public boolean supportMultiEdit(IConfigRegistry configRegistry, List configLabels) { + return false; + } + + /** + * Handle conversion. + * + * @param displayValue the display value + * @param conversionErrorHandler the conversion error handler + * @return the object + */ + protected Object handleConversion(Object displayValue, IEditErrorHandler conversionErrorHandler) { + return displayValue; + } + + @Override + protected Control activateCell(Composite parent, Object originalCanonicalValue) { + isCellEditable = labelStack.hasLabel(IEditTableGridStyleLabelFactory.COL_LABEL_READONLY_CELL); + Shell shell = Display.getDefault().getActiveShell(); + byteValue = convertObjectToBytes(originalCanonicalValue); + getTableDataEditor(originalCanonicalValue, shell); + super.close(); + return getEditorControl(); + } + + /** + * Gets the table data editor. + * + * @param originalCanonicalValue the original canonical value + * @param shell the shell + * @return the table data editor + */ + protected void getTableDataEditor(Object originalCanonicalValue, Shell shell) { + DSUnstructuredDataTableDataEditor dialog = new DSUnstructuredDataTableDataEditor(shell, this, + originalCanonicalValue); + dialog.open(); + } + + /** + * Convert object to bytes. + * + * @param value the value + * @return the byte[] + */ + public byte[] convertObjectToBytes(Object value) { + if (value instanceof byte[]) { + return (byte[]) value; + } + return null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSUnstructuredDataConversionHelper.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSUnstructuredDataConversionHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..e1fafe71e6a4f3ae9114a43bd239bb681d4a7d63 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSUnstructuredDataConversionHelper.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import java.util.Locale; + +import org.apache.commons.lang.StringUtils; + +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * Title: DSUnstructuredDataConversionHelper + * + * @since 3.0.0 + */ +public class DSUnstructuredDataConversionHelper { + + /** + * Bytes to hex. + * + * @param blobInBytes the blob in bytes + * @return the string + */ + public static String bytesToHex(byte[] bytes) { + if (null == bytes) { + return ""; + } + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + for (byte b : bytes) { + sb.append(String.format(Locale.ENGLISH, "%02x", b)); + } + return sb.toString().toUpperCase(Locale.ENGLISH); + } + + /** + * Hex string to byte array. + * + * @param str the str + * @return the byte[] + */ + public static byte[] hexStringToByteArray(String str) { + if (StringUtils.isEmpty(str)) { + return null; + } + int len = str.length(); + byte[] data = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + data[i / 2] = (byte) ((Character.digit(str.charAt(i), 16) << 4) + Character.digit(str.charAt(i + 1), 16)); + } + return data; + } + + /** + * Bytes to hex formated. + * + * @param byteA the byte A + * @return the string + */ + public static String bytesToHexFormated(byte[] bytes) { + if (null == bytes) { + return ""; + } + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + sb.append("\\x"); + for (byte b : bytes) { + sb.append(String.format(Locale.ENGLISH, "%02x", b)); + } + return sb.toString().toLowerCase(Locale.ENGLISH); + } + + /** + * Convert string to hex. + * + * @param str the str + * @return the string + */ + public static String convertStringToHex(String str) { + char[] chars = str.toCharArray(); + StringBuffer hex = new StringBuffer(); + for (int i = 0; i < chars.length; i++) { + hex.append(Integer.toHexString((int) chars[i])); + } + return hex.toString(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSUnstructuredDataTableDataEditor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSUnstructuredDataTableDataEditor.java new file mode 100644 index 0000000000000000000000000000000000000000..307a05004ec0df797cf0e878a05334721e5d45b4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DSUnstructuredDataTableDataEditor.java @@ -0,0 +1,859 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.Arrays; + +import org.apache.commons.io.FileUtils; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer.MoveDirectionEnum; +import org.eclipse.swt.SWT; +import org.eclipse.swt.SWTException; +import org.eclipse.swt.custom.ScrolledComposite; +import org.eclipse.swt.events.KeyAdapter; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.ImageData; +import org.eclipse.swt.graphics.ImageLoader; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Canvas; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.FileDialog; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.TabFolder; +import org.eclipse.swt.widgets.TabItem; +import org.eclipse.swt.widgets.Text; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.view.prefernces.PreferenceWrapper; +import org.opengauss.mppdbide.view.utils.Preferencekeys; +import org.opengauss.mppdbide.view.utils.consts.UIConstants; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs.MESSAGEDIALOGTYPE; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * Title: DSUnstructuredDataTableDataEditor + * + * @since 3.0.0 + */ +public class DSUnstructuredDataTableDataEditor extends Dialog { + /** + * The Constant FOUR_MB. + */ + private static final int FOUR_MB = 4194304; // 4*1024*2014 MB + + /** + * The loading. + */ + private String loading = MessageConfigLoader.getProperty(IMessagesConstants.LOADING_DATA); + + /** + * The loaded. + */ + private String loaded = MessageConfigLoader.getProperty(IMessagesConstants.LOADED_DATA); + + /** + * The size exceeded four. + */ + private String sizeExceededFour = MessageConfigLoader.getProperty(IMessagesConstants.FILE_SIZE_EXCEEDED_FOUR); + + /** + * The cell editor. + */ + protected DSUnstructuredDataCellEditor cellEditor = null; + + /** + * The editor. + */ + protected Text editor = null; + + /** + * The text view. + */ + private Text textView = null; + + /** + * The value bytes. + */ + protected byte[] valueBytes = null; + + /** + * The clear btn. + */ + protected Button clearBtn = null; + + /** + * The openfile. + */ + private Button openfile = null; + + /** + * The save file. + */ + private Button saveFile = null; + + /** + * The status. + */ + protected Label status = null; + + /** + * The folder. + */ + private TabFolder folder = null; + + /** + * The image tab. + */ + private TabItem imageTab = null; + + /** + * The data tab. + */ + private TabItem dataTab = null; + + /** + * The loader. + */ + private ImageLoader loader = null; + + private Canvas canvas = null; + + private byte[] originalBytes = null; + + /** + * Instantiates a new DS unstructured data table data editor. + * + * @param parentShell the parent shell + * @param cellEditor the cell editor + * @param originalCanonicalValue the original canonical value + */ + public DSUnstructuredDataTableDataEditor(Shell parentShell, DSUnstructuredDataCellEditor cellEditor, + Object originalCanonicalValue) { + super(parentShell); + this.cellEditor = cellEditor; + this.valueBytes = convertObjectToBytes(originalCanonicalValue); + this.originalBytes = valueBytes; + } + + /** + * Convert object to bytes. + * + * @param value the value + * @return the byte[] + */ + public byte[] convertObjectToBytes(Object value) { + if (value instanceof byte[]) { + return (byte[]) value; + } + return null; + } + + /** + * Gets the editor text. + * + * @return the editor text + */ + protected String getEditorText() { + return (editor.getText().length() % 2 == 0) ? editor.getText() : editor.getText() + '0'; + } + + @Override + protected void configureShell(Shell newShell) { + newShell.setSize(800, 500); + super.configureShell(newShell); + + newShell.setText(MessageConfigLoader.getProperty(IMessagesConstants.EDITOR_NODE)); + newShell.setImage(IconUtility.getIconImage(IiconPath.ICO_EDIT_TABLE, this.getClass())); + shellAlignCenter(newShell); + } + + @Override + protected boolean isResizable() { + return true; + } + + /** + * Shell align center. + * + * @param newShell the new shell + */ + private void shellAlignCenter(Shell newShell) { + Rectangle bounds = newShell.getMonitor().getBounds(); + Rectangle rect = newShell.getBounds(); + int xCordination = bounds.x + (bounds.width - rect.width) / 2; + int yCordination = bounds.y + (bounds.height - rect.height) / 2; + newShell.setLocation(xCordination, yCordination); + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite maincomp = (Composite) super.createDialogArea(parent); + maincomp.setLayout(new GridLayout(1, false)); + GridData maincompGD = new GridData(SWT.FILL, SWT.FILL, true, true); + maincomp.setLayoutData(maincompGD); + + Composite buttonComposite = new Composite(maincomp, SWT.NONE); + buttonComposite.setLayout(new GridLayout(2, false)); + GridData buttonCompositeGD = new GridData(SWT.FILL, SWT.NONE, true, false); + buttonComposite.setLayoutData(buttonCompositeGD); + openFileButton(buttonComposite); + saveFileButton(buttonComposite); + + folder = new TabFolder(maincomp, SWT.NONE); + folder.setLayout(new GridLayout(1, false)); + GridData folderGD = new GridData(SWT.FILL, SWT.FILL, true, true); + folder.setLayoutData(folderGD); + createDataTab(folder); + createImageTab(folder); + createTextTab(folder); + + addFolderItemListener(); + + createStatus(maincomp); + return maincomp; + } + + private void addFolderItemListener() { + folder.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent e) { + byte[] editorBytes = null; + if (MessageConfigLoader.getProperty(IMessagesConstants.EDITOR_IMAGE_TAB) + .equals(folder.getSelection()[0].getText())) { + disposeCanvas(); + editorBytes = folderSelectionGetEditorBytes(editorBytes); + if (editorBytes != null) { + imageTab.setControl(createImageComposite(folder, editorBytes)); + } else { + imageTab.setControl(new Composite(folder, SWT.NONE)); + } + } + if (MessageConfigLoader.getProperty(IMessagesConstants.EXEC_PLAN_TEXT) + .equals(folder.getSelection()[0].getText())) { + editorBytes = folderSelectionGetEditorBytes(editorBytes); + try { + textView.setText( + (editorBytes != null) ? new String(editorBytes, MPPDBIDEConstants.FILEENCODING_UTF) + : ""); + } catch (UnsupportedEncodingException exception) { + MPPDBIDELoggerUtility.error("unsupported encoding format", exception); + } + } + } + + private byte[] folderSelectionGetEditorBytes(byte[] editorBytes) { + try { + editorBytes = getBytesFromEditorText(getEditorText()); + } catch (StringIndexOutOfBoundsException excep) { + folder.setSelection(dataTab); + setStatusText(status, + MessageConfigLoader.getProperty(IMessagesConstants.EDITOR_DATA_INVALID_NUMBER_DIGITS), + false); + } + return editorBytes; + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + } + }); + } + + /** + * Creates the text tab. + * + * @param folder the folder + */ + private void createTextTab(TabFolder folder) { + TabItem textTab = new TabItem(folder, SWT.NONE); + textTab.setText(MessageConfigLoader.getProperty(IMessagesConstants.EXEC_PLAN_TEXT)); + Composite textViewComposite = new Composite(folder, SWT.NONE); + textViewComposite.setLayout(new GridLayout(1, false)); + GridData textViewCompositeGD = new GridData(SWT.FILL, SWT.FILL, true, true); + textViewComposite.setLayoutData(textViewCompositeGD); + createTextView(textViewComposite); + textTab.setControl(textViewComposite); + } + + /** + * Creates the image tab. + * + * @param folder the folder + */ + private void createImageTab(TabFolder folder) { + imageTab = new TabItem(folder, SWT.NONE); + imageTab.setText(MessageConfigLoader.getProperty(IMessagesConstants.EDITOR_IMAGE_TAB)); + } + + /** + * Creates the data tab. + * + * @param folder the folder + */ + private void createDataTab(TabFolder folder) { + dataTab = new TabItem(folder, SWT.NONE); + dataTab.setText(MessageConfigLoader.getProperty(IMessagesConstants.EDITOR_DATA_TAB)); + Composite editorTextComposite = new Composite(folder, SWT.NONE); + editorTextComposite.setLayout(new GridLayout(1, false)); + GridData editorTextCompositeGD = new GridData(SWT.FILL, SWT.FILL, true, true); + editorTextComposite.setLayoutData(editorTextCompositeGD); + createEditor(editorTextComposite); + dataTab.setControl(editorTextComposite); + } + + /** + * Creates the scrolled image. + * + * @param folder the folder + * @return the scrolled composite + */ + private Composite createImageComposite(TabFolder folder, byte[] bytes) { + Composite mainComposite = new Composite(folder, SWT.NONE); + mainComposite.setLayout(new GridLayout(1, false)); + GridData mainCompositeGD = new GridData(SWT.FILL, SWT.FILL, true, true); + mainComposite.setLayoutData(mainCompositeGD); + + createScrollableImage(bytes, mainComposite); + createImageProperties(mainComposite); + + return mainComposite; + } + + private void createImageProperties(Composite mainComposite) { + Composite imagePropertiesComposite = new Composite(mainComposite, SWT.NONE); + GridLayout imagePropertiesCompositeGL = new GridLayout(1, false); + imagePropertiesCompositeGL.marginHeight = 0; + imagePropertiesCompositeGL.marginWidth = 0; + imagePropertiesComposite.setLayout(imagePropertiesCompositeGL); + GridData imagePropertiesCompositeGD = new GridData(SWT.FILL, SWT.FILL, true, false); + imagePropertiesComposite.setLayoutData(imagePropertiesCompositeGD); + + Label imageProps = new Label(imagePropertiesComposite, SWT.RIGHT | SWT.WRAP); + GridData imagePropsGD = new GridData(SWT.FILL, SWT.NONE, true, false); + imageProps.setLayoutData(imagePropsGD); + if (loader != null) { + imageProps.setText(loader.data[0].width + " x " + loader.data[0].height); + } + } + + private void createScrollableImage(byte[] bytes, Composite mainComposite) { + ScrolledComposite mainSc = new ScrolledComposite(mainComposite, SWT.H_SCROLL | SWT.V_SCROLL); + mainSc.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + Composite parentComposite = new Composite(mainSc, SWT.NONE); + mainSc.setContent(parentComposite); + parentComposite.setLayout(new GridLayout(1, false)); + GridData parentCompositeGD = new GridData(SWT.FILL, SWT.FILL, true, true); + parentComposite.setLayoutData(parentCompositeGD); + if (loader != null) { + loader = null; + } + if (bytes != null && bytes.length <= FOUR_MB && !sizeExceededFour.equals(editor.getText())) { + loadImage(parentComposite, bytes); + } else { + loadTextExceededFour(parentComposite, bytes); + } + mainSc.setExpandHorizontal(true); + mainSc.setExpandVertical(true); + if (loader != null) { + mainSc.setMinSize(loader.data[0].width, loader.data[0].height); + } else { + mainSc.setMinSize(parentComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT)); + } + mainSc.pack(); + + addImageScrolledCompositeListener(mainSc); + } + + /** + * Adds the image scrolled composite listener for mouse wheel scroll. + * + * @param mainSc the main sc + */ + private void addImageScrolledCompositeListener(ScrolledComposite mainSc) { + mainSc.addListener(SWT.Activate, new Listener() { + @Override + public void handleEvent(Event e) { + mainSc.setFocus(); + } + }); + } + + /** + * Load text exceeded four. + * + * @param parentComposite the parent composite + */ + private void loadTextExceededFour(Composite parentComposite, byte[] bytes) { + Label textLabel = new Label(parentComposite, SWT.NONE); + GridData textLabelGD = new GridData(SWT.CENTER, SWT.CENTER, true, true); + textLabel.setLayoutData(textLabelGD); + // valueBytes length can be 0 for EMPTY_BLOB() + textLabel.setText((bytes != null && bytes.length != 0) ? sizeExceededFour : ""); + } + + /** + * Load image. + * + * @param parentComposite the parent composite + */ + private void loadImage(Composite parentComposite, byte[] bytes) { + try { + InputStream inputStreamReader = new BufferedInputStream(new ByteArrayInputStream(bytes)); + loader = new ImageLoader(); + loader.load(inputStreamReader); + /* + * Check for number of frames and based on it render in label or + * canvas + */ + if (loader.data.length > 1) { + loadImageInCanvas(parentComposite, bytes); + } else { + loadImageInLabel(parentComposite); + } + } catch (SWTException excep) { + loader = null; + loadTextNotSupported(parentComposite); + } + } + + /** + * Load text not supported. + * + * @param parentComposite the parent composite + */ + private void loadTextNotSupported(Composite parentComposite) { + Label textLabel = new Label(parentComposite, SWT.NONE); + GridData textLabelGD = new GridData(SWT.CENTER, SWT.CENTER, true, true); + textLabel.setLayoutData(textLabelGD); + textLabel.setText(MessageConfigLoader.getProperty(IMessagesConstants.EDITOR_IMAGE_NOT_SUPPORTED)); + } + + /** + * Load image in label. + * + * @param parentComposite the parent composite + */ + private void loadImageInLabel(Composite parentComposite) { + Label renderedImage = new Label(parentComposite, SWT.NONE); + GridData renderedImageGD = new GridData(SWT.CENTER, SWT.CENTER, true, true); + renderedImage.setLayoutData(renderedImageGD); + renderedImage.setImage(getFirstFrameImageFromLoader()); + } + + /** + * Gets the first frame image from loader. + * + * @return the first frame image from loader + */ + private Image getFirstFrameImageFromLoader() { + ImageData firstFrameData = loader.data[0]; + Image firstFrameImage = new Image(Display.getCurrent(), firstFrameData); + return firstFrameImage; + } + + /** + * Load image in canvas. + * + * @param parentComposite the parent composite + */ + private void loadImageInCanvas(Composite parentComposite, byte[] bytes) { + Animation canvasAnimation = new Animation(parentComposite, bytes); + canvas = canvasAnimation.getCanvas(); + } + + /** + * Dispose canvas. + */ + private void disposeCanvas() { + if (canvas != null && !canvas.isDisposed()) { + canvas.dispose(); + } + canvas = null; + } + + /** + * Open file button. + * + * @param maincomp the maincomp + */ + private void openFileButton(Composite maincomp) { + openfile = new Button(maincomp, SWT.PUSH); + openfile.setImage(IconUtility.getIconImage(IiconPath.ICO_OPEN_SQL, this.getClass())); + openfile.setToolTipText(MessageConfigLoader.getProperty(IMessagesConstants.MENU_OPEN)); + + openfile.addSelectionListener(addOpenFileSelectionListener()); + } + + /** + * Adds the open file selection listener. + * + * @return the selection listener + */ + private SelectionListener addOpenFileSelectionListener() { + return new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent e) { + String fileName = openFileDialogAndGetFilename(); + if (fileName == null) { + return; + } + + File file = new File(fileName); + double fileSizeLimit = PreferenceWrapper.getInstance().getPreferenceStore() + .getInt(Preferencekeys.FILE_LIMIT_FOR_BYTEA); + + double fileSizeInMB = FileUtils.sizeOf(file) / (double) (1024 * 1024); + if (fileSizeLimit != 0 && fileSizeInMB > fileSizeLimit) { + MPPDBIDEDialogs.generateOKMessageDialog(MESSAGEDIALOGTYPE.ERROR, true, + MessageConfigLoader.getProperty(IMessagesConstants.FILE_LIMIT_HEADER), + MessageConfigLoader.getProperty(IMessagesConstants.FILE_LIMIT_WARNING_MESSAGE)); + return; + } + editor.setEnabled(true); + editor.setText(""); + setStatusText(status, loading, true); + readDataANdShowPreview(file); + } + + private String openFileDialogAndGetFilename() { + FileDialog dialog = new FileDialog(Display.getDefault().getActiveShell(), SWT.OPEN); + String[] filterExt = {"*.*", "*.txt;*.rtf", "*.xml", "*.htm;*.html", "*.jpg;*.bmp;*.png;*.gif", + "*.wmf;*.emf"}; + String[] filterNames = {"All Files (*.*)", "Text (*.txt,*.rtf)", "XML (*.xml)", "HTML (*.htm,*.html)", + "Images (*.jpg,*.bmp,*.png,*.gif)", "Images (*.wmf,*.emf)"}; + dialog.setFilterExtensions(filterExt); + dialog.setFilterNames(filterNames); + + String fileName = dialog.open(); + return fileName; + } + + private void readDataANdShowPreview(File file) { + Display.getDefault().asyncExec(new Runnable() { + + /** + * Run. + */ + public void run() { + try { + valueBytes = Files.readAllBytes(Paths.get(file.getCanonicalPath())); + folder.setSelection(dataTab); + disposeCanvas(); + if (valueBytes.length > FOUR_MB) { + editor.setText(sizeExceededFour); + editor.setEnabled(false); + status.setText(""); + } else { + editor.setText(loadHexInEditorText()); + setStatusText(status, loaded + " (" + valueBytes.length + " Bytes)", true); + } + clearBtn.setEnabled(true); + } catch (IOException excep) { + MPPDBIDELoggerUtility.error("Exception occured while reading file", excep); + status.setText(""); + } + } + }); + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + + } + }; + } + + /** + * Save file button. + * + * @param maincomp the maincomp + */ + private void saveFileButton(Composite maincomp) { + saveFile = new Button(maincomp, SWT.PUSH); + saveFile.setImage(IconUtility.getIconImage(IiconPath.ICO_SAVE_SQL, this.getClass())); + saveFile.setToolTipText(MessageConfigLoader.getProperty(IMessagesConstants.MENU_SAVE)); + + saveFile.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent e) { + String editorTxt = getEditorText(); + if (!sizeExceededFour.equals(editorTxt)) { + try { + valueBytes = getBytesFromEditorText(editorTxt); + } catch (StringIndexOutOfBoundsException excep) { + setStatusText(status, + MessageConfigLoader.getProperty(IMessagesConstants.EDITOR_DATA_INVALID_NUMBER_DIGITS), + false); + return; + } + } + if (valueBytes == null) { + return; + } + FileDialog dialog = new FileDialog(Display.getDefault().getActiveShell(), SWT.SAVE); + String[] filterExt = {"*.*", "*.txt;*.rtf", "*.xml", "*.htm;*.html", "*.jpg;*.bmp;*.png;*.gif", + "*.wmf;*.emf"}; + String[] filterNames = {"All Files (*.*)", "Text (*.txt,*.rtf)", "XML (*.xml)", "HTML (*.htm,*.html)", + "Images (*.jpg,*.bmp,*.png,*.gif)", "Images (*.wmf,*.emf)"}; + dialog.setFilterExtensions(filterExt); + dialog.setFilterNames(filterNames); + + handleFileOperation(dialog); + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + + } + }); + } + + private void handleFileOperation(FileDialog dialog) { + String fileName = dialog.open(); + if (fileName == null) { + return; + } + File file = null; + boolean isFileCreated = false; + boolean isFileDeleted = false; + try { + file = new File(fileName); + if (!file.exists()) { + isFileCreated = file.createNewFile(); + } + if (isFileCreated) { + MPPDBIDELoggerUtility.info("file created successfully"); + } + Files.write(Paths.get(file.getCanonicalPath()), valueBytes, StandardOpenOption.TRUNCATE_EXISTING); + } catch (IOException excep) { + if (file.exists()) { + isFileDeleted = file.delete(); + } + if (isFileDeleted) { + MPPDBIDELoggerUtility.info("file deleted successfully"); + } + MPPDBIDELoggerUtility.error("Exception occured while saving the file data", excep); + } + } + + /** + * Creates the editor. + * + * @param maincomp the maincomp + */ + private void createEditor(Composite maincomp) { + editor = new Text(maincomp, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL); + GridData editorGD = new GridData(SWT.FILL, SWT.FILL, true, true); + editor.setLayoutData(editorGD); + + if (valueBytes == null) { + editor.setText(""); + } else if (valueBytes.length > FOUR_MB) { + editor.setText(sizeExceededFour); + editor.setEnabled(false); + } else { + // convert the bytes to HEX and Display + Display.getDefault().asyncExec(new Runnable() { + /** + * Run. + */ + public void run() { + setStatusText(status, loading, true); + editor.setText(loadHexInEditorText()); + setStatusText(status, loaded + " (" + valueBytes.length + " Bytes)", true); + } + }); + } + + addEditorTextKeyListener(); + } + + /** + * Creates the text view. + * + * @param maincomp the maincomp + */ + private void createTextView(Composite maincomp) { + textView = new Text(maincomp, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL); + GridData editorGD = new GridData(SWT.FILL, SWT.FILL, true, true); + textView.setLayoutData(editorGD); + textView.setEditable(false); + } + + /** + * Load hex in editor text. + * + * @return the string + */ + protected String loadHexInEditorText() { + return DSUnstructuredDataConversionHelper.bytesToHex(valueBytes); + } + + /** + * Adds the editor text key listener. + */ + protected void addEditorTextKeyListener() { + editor.addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent keyEvent) { + status.setText(""); + keyEvent.doit = false; + if (String.valueOf(keyEvent.character).matches("[0-9A-Fa-f]+") || keyEvent.character == '\b' + || (keyEvent.stateMask == SWT.CTRL && keyEvent.keyCode == 'v')) { + if (!cellEditor.isCellEditable()) { + clearBtn.setEnabled(true); + } + keyEvent.doit = true; + } else if (keyEvent.keyCode == SWT.ARROW_UP || keyEvent.keyCode == SWT.ARROW_DOWN + || keyEvent.keyCode == SWT.ARROW_LEFT || keyEvent.keyCode == SWT.ARROW_RIGHT) { + keyEvent.doit = true; + + } else if ((keyEvent.stateMask == SWT.CTRL && keyEvent.keyCode == 'c')) { + keyEvent.doit = true; + } else if (keyEvent.stateMask == SWT.CTRL && keyEvent.keyCode == 'a') { + editor.selectAll(); + editor.selectAll(); + keyEvent.doit = false; + keyEvent.doit = false; + } else { + keyEvent.doit = false; + } + } + }); + } + + /** + * Creates the status. + * + * @param maincomp the maincomp + */ + private void createStatus(Composite maincomp) { + status = new Label(maincomp, SWT.RIGHT | SWT.WRAP); + GridData statusGD = new GridData(SWT.FILL, SWT.NONE, true, false); + statusGD.heightHint = 20; + statusGD.horizontalAlignment = SWT.FILL; + status.setLayoutData(statusGD); + } + + /** + * Sets the status text. + * + * @param status the status + * @param message the message + * @param type the type + */ + private void setStatusText(Label status, String message, boolean type) { + status.setText(message); + if (type) { + status.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLUE)); + } else { + status.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_RED)); + } + } + + @Override + protected void createButtonsForButtonBar(Composite parent) { + String clearLbl = " " + MessageConfigLoader.getProperty(IMessagesConstants.CLEAR_CONSOLE) + " "; + String okLbl = " " + MessageConfigLoader.getProperty(IMessagesConstants.EXEC_PLAN_OK) + " "; + final String cancelLabel = " " + MessageConfigLoader.getProperty(IMessagesConstants.MPPDBIDE_DIA_BTN_CANC) + + " "; + clearBtn = createButton(parent, UIConstants.CLEAR_ID, clearLbl, false); + createButton(parent, UIConstants.OK_ID, okLbl, true); + createButton(parent, UIConstants.CANCEL_ID, cancelLabel, false); + + configureEditorAndButton(); + } + + /** + * Configure editor and button. + */ + private void configureEditorAndButton() { + openfile.setEnabled(!cellEditor.isCellEditable()); + editor.setEditable(!cellEditor.isCellEditable()); + clearBtn.setEnabled(!cellEditor.isCellEditable() && valueBytes != null); + } + + @Override + protected void buttonPressed(int buttonId) { + if (buttonId == UIConstants.OK_ID) { + String editorText = getEditorText(); + if (!sizeExceededFour.equals(editorText)) { + try { + valueBytes = getBytesFromEditorText(editorText); + } catch (StringIndexOutOfBoundsException excep) { + setStatusText(status, + MessageConfigLoader.getProperty(IMessagesConstants.EDITOR_DATA_INVALID_NUMBER_DIGITS), + false); + return; + } + } + if (valueBytes == null) { + cellEditor.setEditorValue(null); + } else if (Arrays.equals(originalBytes, valueBytes)) { + close(); + return; + } else { + cellEditor.setEditorValue(valueBytes); + } + cellEditor.commit(MoveDirectionEnum.NONE, true); + close(); + } else if (buttonId == UIConstants.CLEAR_ID) { + valueBytes = null; + editor.setText(""); + editor.setEnabled(true); + status.setText(""); + folder.setSelection(dataTab); + } else { + close(); + } + } + + /** + * Gets the bytes from editor text. + * + * @param editorTxt the editor txt + * @return the bytes from editor text + */ + protected byte[] getBytesFromEditorText(String editorTxt) { + return DSUnstructuredDataConversionHelper.hexStringToByteArray(editorTxt); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DataGrid.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DataGrid.java new file mode 100644 index 0000000000000000000000000000000000000000..8e8ad643d90f724bf60e0ad65232989c0476c227 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DataGrid.java @@ -0,0 +1,2835 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Observable; +import java.util.Observer; +import java.util.Properties; +import java.util.regex.Pattern; + +import org.apache.commons.lang.StringEscapeUtils; +import org.eclipse.jface.layout.GridDataFactory; +import org.eclipse.nebula.widgets.nattable.NatTable; +import org.eclipse.nebula.widgets.nattable.command.ILayerCommand; +import org.eclipse.nebula.widgets.nattable.config.AbstractRegistryConfiguration; +import org.eclipse.nebula.widgets.nattable.config.AbstractUiBindingConfiguration; +import org.eclipse.nebula.widgets.nattable.config.CellConfigAttributes; +import org.eclipse.nebula.widgets.nattable.config.ConfigRegistry; +import org.eclipse.nebula.widgets.nattable.coordinate.PositionCoordinate; +import org.eclipse.nebula.widgets.nattable.copy.action.CopyDataAction; +import org.eclipse.nebula.widgets.nattable.copy.action.PasteDataAction; +import org.eclipse.nebula.widgets.nattable.copy.command.CopyDataToClipboardCommand; +import org.eclipse.nebula.widgets.nattable.data.ListDataProvider; +import org.eclipse.nebula.widgets.nattable.edit.action.KeyEditAction; +import org.eclipse.nebula.widgets.nattable.edit.action.MouseEditAction; +import org.eclipse.nebula.widgets.nattable.edit.command.EditCellCommand; +import org.eclipse.nebula.widgets.nattable.edit.command.EditSelectionCommand; +import org.eclipse.nebula.widgets.nattable.edit.command.UpdateDataCommand; +import org.eclipse.nebula.widgets.nattable.edit.command.UpdateDataCommandHandler; +import org.eclipse.nebula.widgets.nattable.edit.editor.ICellEditor; +import org.eclipse.nebula.widgets.nattable.export.command.ExportCommand; +import org.eclipse.nebula.widgets.nattable.extension.glazedlists.GlazedListsEventLayer; +import org.eclipse.nebula.widgets.nattable.extension.glazedlists.GlazedListsSortModel; +import org.eclipse.nebula.widgets.nattable.extension.nebula.richtext.RegexMarkupValue; +import org.eclipse.nebula.widgets.nattable.grid.GridRegion; +import org.eclipse.nebula.widgets.nattable.grid.data.DefaultRowHeaderDataProvider; +import org.eclipse.nebula.widgets.nattable.grid.layer.ColumnHeaderLayer; +import org.eclipse.nebula.widgets.nattable.grid.layer.CornerLayer; +import org.eclipse.nebula.widgets.nattable.grid.layer.DefaultColumnHeaderDataLayer; +import org.eclipse.nebula.widgets.nattable.grid.layer.DefaultRowHeaderDataLayer; +import org.eclipse.nebula.widgets.nattable.grid.layer.GridLayer; +import org.eclipse.nebula.widgets.nattable.grid.layer.RowHeaderLayer; +import org.eclipse.nebula.widgets.nattable.grid.layer.config.DefaultGridLayerConfiguration; +import org.eclipse.nebula.widgets.nattable.group.ColumnGroupHeaderLayer; +import org.eclipse.nebula.widgets.nattable.group.ColumnGroupModel; +import org.eclipse.nebula.widgets.nattable.group.command.ViewportSelectColumnGroupCommand; +import org.eclipse.nebula.widgets.nattable.group.command.ViewportSelectRowGroupCommand; +import org.eclipse.nebula.widgets.nattable.layer.CompositeLayer; +import org.eclipse.nebula.widgets.nattable.layer.DataLayer; +import org.eclipse.nebula.widgets.nattable.layer.ILayer; +import org.eclipse.nebula.widgets.nattable.layer.ILayerListener; +import org.eclipse.nebula.widgets.nattable.layer.cell.ColumnLabelAccumulator; +import org.eclipse.nebula.widgets.nattable.layer.cell.ColumnOverrideLabelAccumulator; +import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell; +import org.eclipse.nebula.widgets.nattable.painter.NatTableBorderOverlayPainter; +import org.eclipse.nebula.widgets.nattable.print.command.PrintCommand; +import org.eclipse.nebula.widgets.nattable.reorder.ColumnReorderLayer; +import org.eclipse.nebula.widgets.nattable.resize.action.ColumnResizeCursorAction; +import org.eclipse.nebula.widgets.nattable.resize.command.AutoResizeColumnsCommand; +import org.eclipse.nebula.widgets.nattable.resize.command.AutoResizeRowsCommand; +import org.eclipse.nebula.widgets.nattable.resize.command.ColumnResizeCommand; +import org.eclipse.nebula.widgets.nattable.resize.command.ColumnSizeConfigurationCommand; +import org.eclipse.nebula.widgets.nattable.resize.command.ColumnWidthResetCommand; +import org.eclipse.nebula.widgets.nattable.resize.command.InitializeAutoResizeColumnsCommand; +import org.eclipse.nebula.widgets.nattable.resize.command.InitializeAutoResizeRowsCommand; +import org.eclipse.nebula.widgets.nattable.resize.command.MultiColumnResizeCommand; +import org.eclipse.nebula.widgets.nattable.resize.command.MultiRowResizeCommand; +import org.eclipse.nebula.widgets.nattable.resize.command.RowHeightResetCommand; +import org.eclipse.nebula.widgets.nattable.resize.command.RowResizeCommand; +import org.eclipse.nebula.widgets.nattable.resize.command.RowSizeConfigurationCommand; +import org.eclipse.nebula.widgets.nattable.resize.event.ColumnResizeEventMatcher; +import org.eclipse.nebula.widgets.nattable.resize.mode.ColumnResizeDragMode; +import org.eclipse.nebula.widgets.nattable.search.command.SearchCommand; +import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer; +import org.eclipse.nebula.widgets.nattable.selection.command.MoveSelectionCommand; +import org.eclipse.nebula.widgets.nattable.selection.command.ScrollSelectionCommand; +import org.eclipse.nebula.widgets.nattable.selection.command.SelectCellCommand; +import org.eclipse.nebula.widgets.nattable.selection.command.SelectColumnCommand; +import org.eclipse.nebula.widgets.nattable.selection.command.SelectRegionCommand; +import org.eclipse.nebula.widgets.nattable.selection.command.SelectRowsCommand; +import org.eclipse.nebula.widgets.nattable.sort.ISortModel; +import org.eclipse.nebula.widgets.nattable.sort.SortConfigAttributes; +import org.eclipse.nebula.widgets.nattable.sort.SortDirectionEnum; +import org.eclipse.nebula.widgets.nattable.sort.SortHeaderLayer; +import org.eclipse.nebula.widgets.nattable.sort.command.SortColumnCommand; +import org.eclipse.nebula.widgets.nattable.tickupdate.command.TickUpdateCommand; +import org.eclipse.nebula.widgets.nattable.ui.NatEventData; +import org.eclipse.nebula.widgets.nattable.ui.action.IKeyAction; +import org.eclipse.nebula.widgets.nattable.ui.binding.UiBindingRegistry; +import org.eclipse.nebula.widgets.nattable.ui.matcher.KeyEventMatcher; +import org.eclipse.nebula.widgets.nattable.ui.matcher.MouseEventMatcher; +import org.eclipse.nebula.widgets.nattable.ui.menu.IMenuItemProvider; +import org.eclipse.nebula.widgets.nattable.ui.menu.MenuItemProviders; +import org.eclipse.nebula.widgets.nattable.ui.menu.PopupMenuAction; +import org.eclipse.nebula.widgets.nattable.ui.menu.PopupMenuBuilder; +import org.eclipse.nebula.widgets.nattable.viewport.command.RecalculateScrollBarsCommand; +import org.eclipse.nebula.widgets.nattable.viewport.command.ShowCellInViewportCommand; +import org.eclipse.nebula.widgets.nattable.viewport.command.ShowColumnInViewportCommand; +import org.eclipse.nebula.widgets.nattable.viewport.command.ShowRowInViewportCommand; +import org.eclipse.nebula.widgets.nattable.viewport.command.ViewportDragCommand; +import org.eclipse.nebula.widgets.nattable.viewport.command.ViewportSelectColumnCommand; +import org.eclipse.nebula.widgets.nattable.viewport.command.ViewportSelectRowCommand; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.DisposeEvent; +import org.eclipse.swt.events.DisposeListener; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.events.MenuEvent; +import org.eclipse.swt.events.MenuListener; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.events.MouseListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.MenuItem; +import org.eclipse.swt.widgets.Text; + +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.presentation.edittabledata.DSResultSetGridDataProvider; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableRecordStates; +import org.opengauss.mppdbide.presentation.edittabledata.IDSGridEditDataRow; +import org.opengauss.mppdbide.presentation.grid.IDSEditGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnGroupProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.presentation.grid.batchdrop.BatchDropDataProvider; +import org.opengauss.mppdbide.presentation.objectproperties.DSObjectPropertiesGridDataProvider; +import org.opengauss.mppdbide.presentation.objectproperties.PropertiesUserRoleImpl; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.utils.observer.DSEventTable; +import org.opengauss.mppdbide.utils.observer.IDSGridUIListenable; +import org.opengauss.mppdbide.utils.observer.IDSListener; +import org.opengauss.mppdbide.view.component.DSGridStateMachine; +import org.opengauss.mppdbide.view.component.IGridUIPreference; +import org.opengauss.mppdbide.view.component.grid.BatchDropGridStyleConfiguration; +import org.opengauss.mppdbide.view.component.grid.DSGridToolTipProvider; +import org.opengauss.mppdbide.view.component.grid.DSHTMLAwareRegexMarkupValue; +import org.opengauss.mppdbide.view.component.grid.EditTableGridStyleConfiguration; +import org.opengauss.mppdbide.view.component.grid.GridScrollEventDataLoadListener; +import org.opengauss.mppdbide.view.component.grid.GridSelectionLayerPortData; +import org.opengauss.mppdbide.view.component.grid.GridUIUtils; +import org.opengauss.mppdbide.view.component.grid.GridViewPortData; +import org.opengauss.mppdbide.view.component.grid.IDataGridContext; +import org.opengauss.mppdbide.view.component.grid.SEARCHOPTIONS; +import org.opengauss.mppdbide.view.component.grid.ServerObjectTypeForDialog; +import org.opengauss.mppdbide.view.component.grid.TableGridStyleConfiguration; +import org.opengauss.mppdbide.view.handler.IHandlerUtilities; +import org.opengauss.mppdbide.view.prefernces.PreferenceWrapper; +import org.opengauss.mppdbide.view.prefernces.UserEncodingOption; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; + +import ca.odell.glazedlists.EventList; +import ca.odell.glazedlists.FilterList; +import ca.odell.glazedlists.GlazedLists; +import ca.odell.glazedlists.SortedList; +import ca.odell.glazedlists.TextFilterator; +import ca.odell.glazedlists.matchers.TextMatcherEditor; + +/** + * + * Title: class + * + * Description: The Class DataGrid. + * + * @since 3.0.0 + */ +public class DataGrid { + + /** + * The ui pref. + */ + protected IGridUIPreference uiPref; + + /** + * The state machine. + */ + protected DSGridStateMachine stateMachine; + + /** + * The data provider. + */ + protected IDSGridDataProvider dataProvider; + + /** + * Gets the data provider. + * + * @return the data provider + */ + public IDSGridDataProvider getDataProvider() { + return dataProvider; + } + + /** + * The data event list. + */ + protected EventList dataEventList; + + /** + * The data filter list. + */ + protected FilterList dataFilterList; + + /** + * The data sorted list. + */ + protected SortedList dataSortedList; + + /** + * The col prop accessor. + */ + protected GridColumnValueAccessor colPropAccessor; + + /** + * The config registry. + */ + protected ConfigRegistry configRegistry; + + /** + * The regex matcher. + */ + protected RegexMarkupValue regexMatcher = null; + private TextMatcherEditor matcherEditor; + private GridScrollEventDataLoadListener scrollDataLoadListener; + private SortRegistryConfiguration sortRegistrConfiguration; + + /** + * The event table. + */ + protected DSEventTable eventTable; + + /** + * The body data layer. + */ + protected DataLayer bodyDataLayer; + + /** + * The body data provider. + */ + protected ListDataProvider bodyDataProvider; + + /** + * The reorder layer. + */ + protected ColumnReorderLayer reorderLayer; + + /** + * The selection layer. + */ + protected SelectionLayer selectionLayer; + + /** + * The viewport layer. + */ + protected GridViewPortLayer viewportLayer; + + // Nattable Column Stack + private SortHeaderLayer sortHeaderLayer; + + /** + * The column header data provider. + */ + protected GridColHeaderDataProvider columnHeaderDataProvider; + + /** + * The column header data layer. + */ + protected DefaultColumnHeaderDataLayer columnHeaderDataLayer; + + /** + * The selection col header layer. + */ + protected SelectionLayer selectionColHeaderLayer; + + /** + * The row header data provider. + */ + protected DefaultRowHeaderDataProvider rowHeaderDataProvider; + + /** + * The row header data layer. + */ + protected DefaultRowHeaderDataLayer rowHeaderDataLayer; + + /** + * The row header layer. + */ + protected RowHeaderLayer rowHeaderLayer; + + /** + * The selection row header layer. + */ + protected SelectionLayer selectionRowHeaderLayer; + + /** + * The corner data provider. + */ + protected GridCornerLayerDataProvider cornerDataProvider; + + /** + * the corner DataLayer + */ + protected DataLayer cornerDataLayer; + + /** + * The corner layer. + */ + protected CornerLayer cornerLayer; + + /** + * The grid layer. + */ + protected GridLayer gridLayer; + + /** + * The data grid. + */ + protected volatile DSNatTable dataGrid; + + /** + * The column header layer. + */ + protected ILayer columnHeaderLayer; + + /** + * The edit table config. + */ + protected AbstractRegistryConfiguration editTableConfig; + private BatchDropGridStyleConfiguration batchDropTableConfig; + + /** + * The col label accumulator. + */ + protected ColumnOverrideLabelAccumulator colLabelAccumulator; + + /** + * The ds grid tool tip provider. + */ + protected DSGridToolTipProvider dsGridToolTipProvider; + + /** + * The column group model. + */ + protected ColumnGroupModel columnGroupModel; + + /** + * The column group header layer. + */ + protected ColumnGroupHeaderLayer columnGroupHeaderLayer; + + /** + * The datatype column accumulator. + */ + protected DSAbstractRegistryConfiguration datatypeColumnAccumulator; + + /** + * The col header label accumulator. + */ + protected ColumnLabelAccumulator colHeaderLabelAccumulator; + + /** + * The parent. + */ + protected Composite parent; + + /** + * The data context. + */ + protected IDataGridContext dataContext; + + /** + * The save sort store. + */ + protected GridSaveSortState saveSortStore; + + /** + * The copy handler. + */ + protected DSCopyDataCommandHandler copyHandler; + + /** + * The reorder properties. + */ + protected Properties reorderProperties; + + /** + * The reorder prefix. + */ + protected String reorderPrefix = "reorderState"; + private GridPasteHandler pasteCommandHandler; + private TableGridStyleConfiguration tableGridStyleconfiguration; + private RightClickShowMenuConfiguration rightClickShowMenuconfiguration; + private NatTableBorderOverlayPainter borderOverlayPainter; + private MouseListener mouseListenerForSort; + private int currentScrolledRow = 0; + private int pageRowSize = 0; + + /** + * Instantiates a new data grid. + * + * @param uiPref the ui pref + * @param dataProvider the data provider + * @param eventTable the event table + * @param stateMachine the state machine + */ + public DataGrid(IGridUIPreference uiPref, IDSGridDataProvider dataProvider, DSEventTable eventTable, + DSGridStateMachine stateMachine) { + this.uiPref = uiPref; + dataContext = new DataGridContext(); + this.dataProvider = dataProvider; + this.eventTable = eventTable; + this.stateMachine = stateMachine; + this.saveSortStore = new GridSaveSortState(); + this.reorderProperties = new Properties(); + this.borderOverlayPainter = new NatTableBorderOverlayPainter(); + } + + /** + * Sets the data provider. + * + * @param dataProvider the new data provider + */ + protected void setDataProvider(IDSGridDataProvider dataProvider) { + + if (this.dataProvider != dataProvider) { + if (null != this.dataProvider) { + this.dataProvider.preDestroy(); + } + this.dataProvider = dataProvider; + } + + dataContext.setDataProvider(this.dataProvider); + if (this.dataProvider instanceof IDSEditGridDataProvider) { + this.dataEventList = GlazedLists + .eventList(((IDSEditGridDataProvider) this.dataProvider).getConsolidatedRows()); + } else { + this.dataEventList = GlazedLists.eventList(this.dataProvider.getAllFetchedRows()); + } + this.dataFilterList = new FilterList(GlazedLists.threadSafeList(this.dataEventList)); + if (null != this.dataSortedList) { + this.dataSortedList.clear(); + } + this.dataSortedList = new SortedList(this.dataFilterList, null); + if (uiPref.isEnableEdit()) { + setColumnValueAccessor(); + } else { + this.colPropAccessor = new GridNonEditableColumnValueAccessor(this.dataProvider); + } + + if (null != this.copyHandler) { + // Anyway will reset during next execution. But to clearup the + // reference to old dataprovider (memory leak), better to reset. + this.copyHandler.setDataProvider(this.dataProvider); + } + } + + /** + * Sets the column value accessor. + */ + protected void setColumnValueAccessor() { + this.colPropAccessor = new GridColumnValueAccessor(this.dataProvider); + } + + /** + * Gets the data grid. + * + * @return the data grid + */ + public DSNatTable getDataGrid() { + return this.dataGrid; + } + + /** + * Gets the list of rows. + * + * @return the list of rows + */ + public EventList getListOfRows() { + return this.dataEventList; + } + + /** + * On pre destroy. + */ + public void onPreDestroy() { + if (null != getDataGrid() && null != mouseListenerForSort) { + getDataGrid().removeMouseListener(mouseListenerForSort); + } + cleanDataProviderInfo(); + clearColumnDataTypesInfo(); + clearConfiguration(); + clearColHeaderLabelInfo(); + clearCopyPasteCommandHandler(); + clearGridLayerInfo(); + clearRowHeaderDataLayerCommands(); + clearSelectionRowHeaderLayerCommands(); + clearCornerDataLayerCommands(); + clearColumnHeaderDataLayerCommands(); + clearViewPortLayerCommands(); + clearToolTipInfo(); + clearRightClickConfigInfo(); + clearDataList(); + cleanDataGridRegistry(); + + /* Remove all local reference variables. */ + if (null != this.saveSortStore) { + saveSortStore.cleanUp(); + saveSortStore = null; + } + + if (this.dataContext != null) { + dataContext.onPreDestroy(); + } + + if (this.stateMachine != null && this.stateMachine.countObservers() > 0) { + this.stateMachine.deleteObservers(); + } + + if (this.cornerDataProvider != null) { + cornerDataProvider.onPreDestroy(); + } + setUsedObjectToNull(); + } + + private void clearRightClickConfigInfo() { + if (this.rightClickShowMenuconfiguration != null) { + rightClickShowMenuconfiguration.preDestroy(); + rightClickShowMenuconfiguration = null; + } + } + + private void clearToolTipInfo() { + if (dsGridToolTipProvider != null) { + dsGridToolTipProvider.onPreDestroy(); + dsGridToolTipProvider = null; + } + } + + private void clearGridLayerInfo() { + if (this.gridLayer != null) { + gridLayer.unregisterCommandHandler(AutoResizeRowsCommand.class); + gridLayer.unregisterCommandHandler(AutoResizeColumnsCommand.class); + gridLayer.unregisterCommandHandler(PrintCommand.class); + gridLayer.unregisterCommandHandler(ExportCommand.class); + gridLayer.unregisterCommandHandler(EditCellCommand.class); + gridLayer.clearConfiguration(); + } + } + + private void clearColHeaderLabelInfo() { + if (this.colHeaderLabelAccumulator != null + && colHeaderLabelAccumulator instanceof GridColumnHeaderAccumulator) { + ((GridColumnHeaderAccumulator) colHeaderLabelAccumulator).onPreDestroy(); + } + } + + private void clearCopyPasteCommandHandler() { + if (null != gridLayer) { + if (this.copyHandler != null) { + this.gridLayer.unregisterCommandHandler((Class) copyHandler.getCommandClass()); + copyHandler.onPreDestroy(); + } + + if (this.pasteCommandHandler != null) { + this.gridLayer.unregisterCommandHandler( + (Class) pasteCommandHandler.getCommandClass()); + pasteCommandHandler.onPreDestroy(); + } + } + } + + private void clearViewPortLayerCommands() { + if (viewportLayer != null) { + viewportLayer.unregisterCommandHandler((Class) RecalculateScrollBarsCommand.class); + viewportLayer.unregisterCommandHandler((Class) ScrollSelectionCommand.class); + viewportLayer.unregisterCommandHandler((Class) ShowCellInViewportCommand.class); + viewportLayer.unregisterCommandHandler((Class) ShowColumnInViewportCommand.class); + viewportLayer.unregisterCommandHandler((Class) ShowRowInViewportCommand.class); + viewportLayer.unregisterCommandHandler((Class) ViewportSelectColumnCommand.class); + viewportLayer + .unregisterCommandHandler((Class) ViewportSelectColumnGroupCommand.class); + viewportLayer.unregisterCommandHandler((Class) ViewportSelectRowCommand.class); + viewportLayer + .unregisterCommandHandler((Class) ViewportSelectRowGroupCommand.class); + viewportLayer.unregisterCommandHandler((Class) ViewportDragCommand.class); + viewportLayer.clearConfiguration(); + } + } + + private void clearColumnHeaderDataLayerCommands() { + if (null != bodyDataLayer) { + bodyDataLayer.unregisterCommandHandler(ColumnResizeCommand.class); + bodyDataLayer.unregisterCommandHandler(MultiRowResizeCommand.class); + bodyDataLayer.unregisterCommandHandler(RowResizeCommand.class); + bodyDataLayer.unregisterCommandHandler(MultiColumnResizeCommand.class); + bodyDataLayer.unregisterCommandHandler(ColumnWidthResetCommand.class); + bodyDataLayer.unregisterCommandHandler(RowSizeConfigurationCommand.class); + bodyDataLayer.unregisterCommandHandler(ColumnSizeConfigurationCommand.class); + bodyDataLayer.unregisterCommandHandler(RowHeightResetCommand.class); + } + if (null != columnHeaderDataLayer) { + columnHeaderDataLayer.setConfigLabelAccumulator(null); + columnHeaderDataLayer.clearConfiguration(); + } + } + + private void clearCornerDataLayerCommands() { + if (cornerDataLayer != null) { + cornerDataLayer.unregisterCommandHandler(ColumnResizeCommand.class); + cornerDataLayer.unregisterCommandHandler(MultiRowResizeCommand.class); + cornerDataLayer.unregisterCommandHandler(RowResizeCommand.class); + cornerDataLayer.unregisterCommandHandler(MultiColumnResizeCommand.class); + cornerDataLayer.unregisterCommandHandler(ColumnWidthResetCommand.class); + cornerDataLayer.unregisterCommandHandler(RowSizeConfigurationCommand.class); + cornerDataLayer.unregisterCommandHandler(ColumnSizeConfigurationCommand.class); + cornerDataLayer.unregisterCommandHandler(RowHeightResetCommand.class); + cornerDataLayer.unregisterCommandHandler(UpdateDataCommand.class); + cornerDataLayer.clearConfiguration(); + } + } + + private void clearSelectionRowHeaderLayerCommands() { + if (selectionRowHeaderLayer != null) { + selectionRowHeaderLayer.unregisterCommandHandler(SelectColumnCommand.class); + selectionRowHeaderLayer.unregisterCommandHandler(SelectRowsCommand.class); + selectionRowHeaderLayer.unregisterCommandHandler(SelectCellCommand.class); + selectionRowHeaderLayer.unregisterCommandHandler(InitializeAutoResizeColumnsCommand.class); + selectionRowHeaderLayer.unregisterCommandHandler(MoveSelectionCommand.class); + selectionRowHeaderLayer.unregisterCommandHandler(EditSelectionCommand.class); + selectionRowHeaderLayer.unregisterCommandHandler(SearchCommand.class); + selectionRowHeaderLayer.unregisterCommandHandler(CopyDataToClipboardCommand.class); + selectionRowHeaderLayer.unregisterCommandHandler(InitializeAutoResizeRowsCommand.class); + selectionRowHeaderLayer.unregisterCommandHandler(SelectRegionCommand.class); + selectionRowHeaderLayer.unregisterCommandHandler(TickUpdateCommand.class); + selectionColHeaderLayer.clearConfiguration(); + } + } + + private void clearRowHeaderDataLayerCommands() { + if (rowHeaderDataLayer != null) { + rowHeaderDataLayer.unregisterCommandHandler(ColumnResizeCommand.class); + rowHeaderDataLayer.unregisterCommandHandler(MultiRowResizeCommand.class); + rowHeaderDataLayer.unregisterCommandHandler(RowResizeCommand.class); + rowHeaderDataLayer.unregisterCommandHandler(MultiColumnResizeCommand.class); + rowHeaderDataLayer.unregisterCommandHandler(ColumnWidthResetCommand.class); + rowHeaderDataLayer.unregisterCommandHandler(RowSizeConfigurationCommand.class); + rowHeaderDataLayer.unregisterCommandHandler(ColumnSizeConfigurationCommand.class); + rowHeaderDataLayer.unregisterCommandHandler(RowHeightResetCommand.class); + rowHeaderDataLayer.unregisterCommandHandler(UpdateDataCommand.class); + rowHeaderDataLayer.clearConfiguration(); + } + } + + private void clearColumnDataTypesInfo() { + if (null != this.colLabelAccumulator && null != bodyDataLayer) { + bodyDataLayer.setConfigLabelAccumulator(null); + ((GridColumnLabelAccumulator) colLabelAccumulator).onPreDestroy(); + } + + if (this.datatypeColumnAccumulator != null) { + EditTableGridStyleConfiguration.getDatatypeColumnAccumulator(colLabelAccumulator, dataContext, uiPref) + .onPreDestroy(); + } + } + + private void setUsedObjectToNull() { + colHeaderLabelAccumulator = null; + datatypeColumnAccumulator = null; + columnGroupHeaderLayer = null; + columnGroupModel = null; + dsGridToolTipProvider = null; + colLabelAccumulator = null; + batchDropTableConfig = null; + editTableConfig = null; + gridLayer = null; + cornerDataProvider = null; + cornerLayer = null; + selectionRowHeaderLayer = null; + rowHeaderLayer = null; + rowHeaderDataLayer = null; + rowHeaderDataProvider = null; + selectionColHeaderLayer = null; + columnHeaderDataLayer = null; + columnHeaderDataProvider = null; + sortHeaderLayer = null; + tableGridStyleconfiguration = null; + sortRegistrConfiguration = null; + scrollDataLoadListener = null; + bodyDataLayer = null; + bodyDataProvider = null; + reorderLayer = null; + selectionLayer = null; + viewportLayer = null; + configRegistry = null; + copyHandler = null; + columnHeaderLayer = null; + dataGrid = null; + reorderProperties = null; + reorderPrefix = null; + dataContext = null; + eventTable = null; + regexMatcher = null; + uiPref = null; + pasteCommandHandler = null; + stateMachine = null; + cornerDataLayer = null; + } + + private void cleanDataGridRegistry() { + if (null != this.dataGrid) { + // No issue even if this.dataGrid.isDisposed() is equalto true + if (uiPref.isNeedAdvancedCopy()) { + this.dataGrid.getUiBindingRegistry() + .unregisterKeyBinding(new KeyEventMatcher(SWT.MOD1 | SWT.MOD2, 'c')); + } + this.dataGrid.getUiBindingRegistry().unregisterKeyBinding(new KeyEventMatcher(SWT.MOD1, 'c')); + if (uiPref.isEnableEdit()) { + this.dataGrid.getUiBindingRegistry().unregisterKeyBinding(new KeyEventMatcher(SWT.MOD1, 'v')); + } + this.dataGrid.getUiBindingRegistry().unregisterSingleClickBinding(new MouseEventMatcher(GridRegion.CORNER)); + this.dataGrid.setUiBindingRegistry(null); + this.dataGrid.clearConfigurations(); + this.dataGrid.getConfigRegistry().unregisterConfigAttribute(SortConfigAttributes.SORT_COMPARATOR); + this.dataGrid.getConfigRegistry().unregisterConfigAttribute(CellConfigAttributes.CELL_PAINTER); + if (this.scrollDataLoadListener != null) { + scrollDataLoadListener.onPreDestroy(); + this.dataGrid.getVerticalBar().removeListener(SWT.Selection, scrollDataLoadListener); + this.dataGrid.removeKeyListener(this.scrollDataLoadListener); + } + ConfigRegistry tempRegistry = new ConfigRegistry(); + this.dataGrid.setConfigRegistry(tempRegistry); + tempRegistry = null; + dataGrid.clearLayers(); + } + } + + private void clearDataList() { + if (null != this.dataEventList) { + this.dataEventList.clear(); + } + if (null != dataFilterList) { + this.dataFilterList.clear(); + } + if (null != dataSortedList) { + this.dataSortedList.clear(); + } + } + + private void clearConfiguration() { + if (tableGridStyleconfiguration != null) { + tableGridStyleconfiguration.preDestroy(); + } + if (this.sortRegistrConfiguration != null) { + this.sortRegistrConfiguration.onPreDestroy(); + } + if (this.gridLayer != null) { + gridLayer.unregisterCommandHandler((Class) DSCopyDataCommandHandler.class); + gridLayer.clearConfiguration(); + } + if (this.dataGrid != null) { + dataGrid.clearConfigurations(); + dataGrid.removeOverlayPainter(borderOverlayPainter); + } + } + + private void cleanDataProviderInfo() { + if (null != this.dataProvider) { + // Close the statement and rollback the transaction. + this.dataProvider.preDestroy(); + this.dataProvider = null; + } + if (null != colPropAccessor) { + this.colPropAccessor.onPreDestroy(); + this.colPropAccessor = null; + } + if (this.columnHeaderDataProvider != null) { + this.columnHeaderDataProvider.onPreDestroy(); + } + } + + /** + * Creates the component. + * + * @param gridParent the grid parent + */ + public void createComponent(Composite gridParent) { + this.parent = gridParent; + parent.setLayout(new GridLayout(1, false)); + setDataProvider(getDataProvider()); + createAllLayerDataProviders(); + createDataStackLayer(); + createColumnHeaderStackLayer(); + createRowHeaderStackLayer(); + createCornerLayerStack(); + + createTableGrid(parent); + if (uiPref.isEnableSort()) { + addListenersforSort(); + } + } + + /** + * Do hide grid. + * + * @param composite the composite + */ + public void doHideGrid(Composite composite) { + + GridUIUtils.toggleCompositeSectionVisibility(composite, true, null, false); + } + + /** + * Do show grid. + * + * @param composite the composite + */ + public void doShowGrid(Composite composite) { + + GridUIUtils.toggleCompositeSectionVisibility(composite, false, null, false); + } + + private MouseListener getMouseListenerForSort() { + return new MouseListener() { + + @Override + public void mouseUp(MouseEvent event) { + + } + + @Override + public void mouseDown(MouseEvent event) { + if ((event.stateMask & SWT.MOD3) == SWT.MOD3) { + return; + } + int colPos = getDataGrid().getColumnPositionByX(event.x); + int rowPos = getDataGrid().getRowPositionByY(event.y); + ILayerCell cell = getDataGrid().getCellByPosition(colPos, rowPos); + int columnWidth = getDataGrid().getColumnWidthByPosition(colPos); + int columnHeight = getDataGrid().getRowHeightByPosition(0); + int startXOfColumn = getDataGrid().getStartXOfColumnPosition(colPos); + int startYOfColumn = getDataGrid().getStartYOfRowPosition(0); + Image myImage = IconUtility.getIconSmallImage(IconUtility.ICO_SORT_NONE, getClass()); + int sortImageWidth = myImage.getBounds().width; + + if (null != cell && event.x >= startXOfColumn + columnWidth - sortImageWidth - 3 + && event.x <= startXOfColumn + columnWidth - 3 && event.y >= startYOfColumn + && event.y <= startYOfColumn + columnHeight) { + ISortModel sortModel = sortHeaderLayer.getSortModel(); + getDataGrid().doCommand(new SortColumnCommand(getDataGrid(), cell.getColumnPosition(), false, + sortModel.getSortDirection(cell.getColumnIndex()).getNextSortDirection())); + } + } + + @Override + public void mouseDoubleClick(MouseEvent event) { + + } + }; + } + + private void addListenersforSort() { + if (null != getDataGrid()) { + this.mouseListenerForSort = getMouseListenerForSort(); + getDataGrid().addMouseListener(mouseListenerForSort); + } + } + + /** + * Creates the all layer data providers. + */ + protected void createAllLayerDataProviders() { + this.bodyDataProvider = new ListDataProvider(this.dataSortedList, this.colPropAccessor); + this.columnHeaderDataProvider = new GridColHeaderDataProvider(this.dataProvider); + this.rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider); + this.cornerDataProvider = new GridCornerLayerDataProvider(dataContext); + if (null != this.scrollDataLoadListener) { + // Will be applicable only when altering dataprovider, incase of + // scroll load, reexecute etc. + this.scrollDataLoadListener.setDataProvider(this.dataProvider); + } + } + + /** + * Creates the row header stack layer. + */ + protected void createRowHeaderStackLayer() { + this.rowHeaderDataLayer = new DefaultRowHeaderDataLayer(rowHeaderDataProvider); + this.selectionRowHeaderLayer = new SelectionLayer(this.rowHeaderDataLayer); + this.rowHeaderLayer = new RowHeaderLayer(this.selectionRowHeaderLayer, viewportLayer, selectionLayer); + RowHeaderColumnLabelAccumulator rowHeaderColumnLabelAccumulator = new RowHeaderColumnLabelAccumulator( + this.bodyDataLayer); + this.rowHeaderDataLayer.setConfigLabelAccumulator(rowHeaderColumnLabelAccumulator); + } + + /** + * Creates the column header stack layer. + */ + protected void createColumnHeaderStackLayer() { + this.columnHeaderDataLayer = new DefaultColumnHeaderDataLayer(columnHeaderDataProvider); + this.selectionColHeaderLayer = new SelectionLayer(this.columnHeaderDataLayer); + this.columnHeaderLayer = new ColumnHeaderLayer(this.selectionColHeaderLayer, viewportLayer, selectionLayer); + + this.colHeaderLabelAccumulator = getColumnHeaderAccumulator(); + this.columnHeaderDataLayer.setConfigLabelAccumulator(colHeaderLabelAccumulator); + + if (uiPref.isEnableSort()) { + this.sortHeaderLayer = new SortHeaderLayer(columnHeaderLayer, + new GlazedListsSortModel(this.dataSortedList, this.colPropAccessor, + getConfigRegistry(), selectionColHeaderLayer), + false); + + } + + if (null != this.dataProvider.getColumnGroupProvider()) { + columnGroupModel = new ColumnGroupModel(); + columnGroupHeaderLayer = new ColumnGroupHeaderLayer( + null != this.sortHeaderLayer ? this.sortHeaderLayer : this.columnHeaderLayer, + this.selectionColHeaderLayer, this.columnGroupModel); + configureColumnGroup(this.dataProvider.getColumnGroupProvider()); + } + } + + /** + * Gets the column header accumulator. + * + * @return the column header accumulator + */ + protected ColumnLabelAccumulator getColumnHeaderAccumulator() { + return new GridColumnHeaderAccumulator(dataContext); + } + + private void configureColumnGroup(IDSGridColumnGroupProvider columnGroupProvider) { + int count = columnGroupProvider.getGroupCount(); + // Looping for every column, + // Column not in group, then make it sum of static column & row count as + // 2 + // Column in group, addcolumnsindexestogroup. + + for (int element = 0; element < count; element++) { + columnGroupHeaderLayer.addColumnsIndexesToGroup(columnGroupProvider.getColumnGroupName(element), + columnGroupProvider.getColumnIndexInGroup(element)); + } + + columnGroupHeaderLayer.setStaticColumnIndexesByGroup(columnGroupProvider.getColumnGroupName(0), 0); + columnGroupHeaderLayer.setGroupUnbreakable(1); + } + + /** + * Creates the corner layer stack. + */ + protected void createCornerLayerStack() { + this.cornerDataLayer = new DataLayer(this.cornerDataProvider); + this.cornerLayer = new CornerLayer(cornerDataLayer, rowHeaderLayer, + null != this.sortHeaderLayer ? this.sortHeaderLayer : this.columnHeaderLayer); + + } + + /** + * Creates the data stack layer. + */ + protected void createDataStackLayer() { + bodyDataLayer = new DataLayer(bodyDataProvider); + GlazedListsEventLayer eventLayer = new GlazedListsEventLayer(bodyDataLayer, + this.dataSortedList); + + if (uiPref.isAllowColumnReorder()) { + this.reorderLayer = addColumnReorderLayer(eventLayer); + this.selectionLayer = new SelectionLayer(this.reorderLayer); + } else { + this.selectionLayer = new SelectionLayer(eventLayer); + } + // Commenting Reorder, to avoid issues during copy of reordered columns + // : Reordered columns doesn't copy correct headers + this.viewportLayer = new GridViewPortLayer(selectionLayer); + } + + /** + * Adds the column reorder layer. + * + * @param eventLayer the event layer + * @return the column reorder layer + */ + protected ColumnReorderLayer addColumnReorderLayer(GlazedListsEventLayer eventLayer) { + return new ColumnReorderLayer(eventLayer); + } + + /** + * + * Title: class + * + * Description: The Class DSGridLayerConfiguration. + */ + static final class DSGridLayerConfiguration extends DefaultGridLayerConfiguration { + + /** + * Instantiates a new DS grid layer configuration. + * + * @param gridLayer the grid layer + */ + DSGridLayerConfiguration(CompositeLayer gridLayer) { + super(gridLayer); + } + + /** + * Configure ui bindings. + * + * @param uiBindingRegistry the ui binding registry + */ + @Override + public void configureUiBindings(UiBindingRegistry uiBindingRegistry) { + + uiBindingRegistry.registerDoubleClickBinding(new MouseEventMatcher(), new MouseEditAction()); + uiBindingRegistry.registerKeyBinding(new KeyEventMatcher(SWT.F2), new KeyEditAction()); + } + + } + + /** + * Creates the table grid. + * + * @param tableparent the tableparent + */ + protected void createTableGrid(Composite tableparent) { + // build the grid layer + gridLayer = new GridLayer(this.viewportLayer, + null != this.sortHeaderLayer ? this.sortHeaderLayer : this.columnHeaderLayer, this.rowHeaderLayer, + this.cornerLayer, false); + configureSelectionCopyWithPref(gridLayer); + + this.dataGrid = new DSNatTable(tableparent, gridLayer, false); + GridDataFactory.fillDefaults().grab(true, true).applyTo(this.dataGrid); + this.dataGrid.setConfigRegistry(getConfigRegistry()); + if (this.uiPref.isShowRightClickMenu()) { + rightClickShowMenuconfiguration = new RightClickShowMenuConfiguration(this.dataGrid); + this.dataGrid.addConfiguration(rightClickShowMenuconfiguration); + } + + configureGridStyle(); + + enableCornerClickSelectAll(); + enableHeaderToolTip(); + configureCopyByPref(); + + configureColumnDatatypes(); + + gridLayer.addConfiguration(new DSGridLayerConfiguration(gridLayer)); + + if (!uiPref.isEnableEdit()) { + if (dataProvider instanceof DSResultSetGridDataProvider) { + ((DSResultSetGridDataProvider) dataProvider).setEditSupported(false); + } else if (dataProvider instanceof BatchDropDataProvider) { + ((BatchDropDataProvider) dataProvider).setEditSupported(false); + } + } + + if (uiPref.isEnableEdit()) { + + coanfigurePasteConfiguration(); + } + + this.dataGrid.configure(); + this.dataGrid.addOverlayPainter(borderOverlayPainter); + + // Set size for each column. + + /* + * Display without horizontal space bar. I.e., squeeze records to + * available space with equal percentage of data, + */ + if (uiPref.isFitToOnePage()) { + this.bodyDataLayer.setColumnPercentageSizing(true); + } + + registerDisposedListener(); + } + + /** + * Coanfigure paste configuration. + */ + public void coanfigurePasteConfiguration() { + pasteCommandHandler = new GridPasteHandler(selectionLayer); + this.gridLayer.registerCommandHandler(pasteCommandHandler); + } + + /** + * Configure column datatypes. + */ + protected void configureColumnDatatypes() { + colLabelAccumulator = new GridColumnLabelAccumulator(this.bodyDataLayer, this.dataProvider); + bodyDataLayer.setConfigLabelAccumulator(colLabelAccumulator); + + datatypeColumnAccumulator = EditTableGridStyleConfiguration.getDatatypeColumnAccumulator(colLabelAccumulator, + dataContext, this.uiPref); + this.dataGrid.addConfiguration(datatypeColumnAccumulator); + + if (uiPref.isAddBatchDropTool()) { + datatypeColumnAccumulator = BatchDropGridStyleConfiguration.getColumnAccumulator(colLabelAccumulator, + dataContext); + this.dataGrid.addConfiguration(datatypeColumnAccumulator); + } + } + + /** + * Register disposed listener. + */ + protected void registerDisposedListener() { + this.dataGrid.addDisposeListener(new DisposeListener() { + @Override + public void widgetDisposed(DisposeEvent event) { + onPreDestroy(); + } + }); + + } + + /** + * Configure copy by pref. + */ + protected void configureCopyByPref() { + if (uiPref.isNeedAdvancedCopy()) { + this.dataGrid.getUiBindingRegistry().registerKeyBinding(new KeyEventMatcher(SWT.MOD1 | SWT.MOD2, 'c'), + new CopyDataWithPrefAction()); + } + + this.dataGrid.getUiBindingRegistry().registerKeyBinding(new KeyEventMatcher(SWT.MOD1, 'c'), + new CopyDataWithoutPrefAction()); + + if (uiPref.isEnableEdit()) { + this.dataGrid.getUiBindingRegistry().registerKeyBinding(new KeyEventMatcher(SWT.MOD1, 'v'), + new PasteDataWithPrefAction()); + } + } + + /** + * Save sort state. + */ + public void saveSortState() { + ISortModel sortModel = this.sortHeaderLayer.getSortModel(); + if (null != sortModel) { + this.saveSortStore.cleanUp(); + List sortedColList = sortModel.getSortedColumnIndexes(); + if (!sortedColList.isEmpty()) { + List sortPriorityList = new ArrayList<>(10); + GridSaveSortState tempSortStore = new GridSaveSortState(); + for (int cnt = 0; cnt < sortedColList.size(); cnt++) { + int sortedColIndex = sortedColList.get(cnt); + sortPriorityList.add(sortModel.getSortOrder(sortedColIndex)); + SortDirectionEnum sortDir = sortModel.getSortDirection(sortedColIndex); + String sortedColName = this.dataProvider.getColumnDataProvider().getColumnName(sortedColIndex); + SortEntryData entry = new SortEntryData(sortedColName, sortDir); + tempSortStore.saveSortEntry(entry); + } + + for (int elmnt = 0; elmnt < sortPriorityList.size(); elmnt++) { + this.saveSortStore.saveSortEntry(tempSortStore.getSavedSortList().get(sortPriorityList.get(elmnt))); + } + } + } + /* + * In future if performance of this function is bad, then can use below + * code snippet. At the expense of some anamolies mentioned in + * restoreLastSortState() function + */ + + } + + /** + * Restore last sort state. + * + * @param sortSnapshot the sort snapshot + */ + public void restoreLastSortState(GridSaveSortState sortSnapshot) { + boolean isInputSortSnapshot = null != sortSnapshot; + + if (!isInputSortSnapshot && this.saveSortStore == null) { + return; + } + + if (isInputSortSnapshot ? sortSnapshot.hasSortKeys() : this.saveSortStore.hasSortKeys()) { + List sortList = isInputSortSnapshot ? sortSnapshot.getSavedSortList() + : saveSortStore.getSavedSortList(); + List colNames = Arrays.asList(this.dataProvider.getColumnDataProvider().getColumnNames()); + SortEntryData entry = null; + boolean needClearSort = true; + + if (colNames.isEmpty()) { + return; + } + + for (int cnt = 0; cnt < sortList.size(); cnt++) { + entry = sortList.get(cnt); + + if (colNames.contains(entry.getColumnName())) { + ISortModel sortModel = this.sortHeaderLayer.getSortModel(); + if (needClearSort) { + sortModel.clear(); + needClearSort = false; + } + if (null != sortModel) { + sortModel.sort(colNames.indexOf(entry.getColumnName()), entry.getSortDirection(), true); + } + } + } + getDataGrid().refresh(); + } + /* + * Chose not to use below method because when a column is changed from + * sorted state to non sorted state and refreshed immediately, the + * column appears sorted again. NO-SORT state is not preserved And if a + * sorted column is dropped, then next column appears as sorted, which + * is wrong + */ + + } + + /** + * Clear sort. + */ + public void clearSort() { + /* + * clear all sorting fire a sort command on 1st column with do not + * accumulate and sort state as NONE to clear all sorting + */ + this.getDataGrid().doCommand(new SortColumnCommand(this.getDataGrid(), 1, false, SortDirectionEnum.NONE)); + + } + + /** + * Gets the current sort snapshot. + * + * @return the current sort snapshot + */ + public GridSaveSortState getCurrentSortSnapshot() { + saveReorderState(); + saveSortState(); + return this.saveSortStore.getClone(); + } + + /** + * Apply sort snapshot. + * + * @param sortSnapshot the sort snapshot + */ + public void applySortSnapshot(GridSaveSortState sortSnapshot) { + restoreLastSortState(sortSnapshot); + /* + * If columns were reordered then they should be restored after sort is + * applied + */ + restoreReorderState(); + } + + /** + * Save reorder state. + */ + public void saveReorderState() { + if (null != this.reorderLayer) { + this.reorderLayer.saveState(reorderPrefix, reorderProperties); + } + } + + /** + * Restore reorder state. + */ + public void restoreReorderState() { + if (null != this.reorderLayer) { + this.reorderLayer.loadState(reorderPrefix, reorderProperties); + } + } + + /** + * Configure grid style. + */ + protected void configureGridStyle() { + tableGridStyleconfiguration = new TableGridStyleConfiguration(getRegexMarkup(), uiPref, dataContext); + this.dataGrid.addConfiguration(tableGridStyleconfiguration); + + configureColumnHeaderResizeable(); + + // configuration of NatTable when User is in edit mode + editTableConfig = new EditTableGridStyleConfiguration(); + + this.dataGrid.addConfiguration(editTableConfig); + + if (uiPref.isAddBatchDropTool()) { + batchDropTableConfig = new BatchDropGridStyleConfiguration(); + this.dataGrid.addConfiguration(batchDropTableConfig); + } + + if (uiPref.isEnableSort()) { + if (null != this.sortRegistrConfiguration) { + this.sortRegistrConfiguration.setDataProvider(null); + } + this.dataGrid.addConfiguration(new SortAwareSelectionUIBindings()); + this.sortRegistrConfiguration = new SortRegistryConfiguration(this.dataProvider, this.uiPref); + this.dataGrid.addConfiguration(sortRegistrConfiguration); + } + + // Set fixed column width. Data will be truncated from view. + // Expand to see the data. + this.bodyDataLayer.setDefaultColumnWidth(this.uiPref.getColumnWidth()); + } + + private void configureColumnHeaderResizeable() { + this.gridLayer.addConfiguration(new AbstractUiBindingConfiguration() { + @Override + public void configureUiBindings(UiBindingRegistry uiBindingRegistry) { + uiBindingRegistry.registerFirstMouseMoveBinding( + new ColumnResizeEventMatcher(SWT.NONE, GridRegion.ROW_HEADER, 0), + new ColumnResizeCursorAction()); + + uiBindingRegistry.registerFirstMouseDragMode( + new ColumnResizeEventMatcher(SWT.NONE, GridRegion.ROW_HEADER, 1), new ColumnResizeDragMode()); + + uiBindingRegistry.registerFirstMouseMoveBinding( + new ColumnResizeEventMatcher(SWT.NONE, GridRegion.CORNER, 0), new ColumnResizeCursorAction()); + + uiBindingRegistry.registerFirstMouseDragMode( + new ColumnResizeEventMatcher(SWT.NONE, GridRegion.CORNER, 1), new ColumnResizeDragMode()); + } + }); + + } + + /** + * Configure load on scroll. + * + * @param eventTbl the event tbl + */ + public void configureLoadOnScroll(final DSEventTable eventTbl) { + preventConcurrentDataLoad(eventTbl); + scrollDataLoadListener = new GridScrollEventDataLoadListener(this.viewportLayer, this.dataProvider, eventTbl, + this.stateMachine, this); + this.dataGrid.getVerticalBar().addListener(SWT.Selection, scrollDataLoadListener); + this.dataGrid.addKeyListener(scrollDataLoadListener); + } + + private void preventConcurrentDataLoad(DSEventTable eventTbl) { + eventTbl.hook(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_CHANGED, new IDSListener() { + @Override + public void handleEvent(DSEvent event) { + DataGrid.this.scrollDataLoadListener.resetLoadingStatus(); + } + }); + eventTbl.hook(IDSGridUIListenable.LISTEN_TYPE_ON_ERROR, new IDSListener() { + @Override + public void handleEvent(DSEvent event) { + DataGrid.this.scrollDataLoadListener.resetLoadingStatus(); + } + }); + } + + /** + * Enable header tool tip. + */ + protected void enableHeaderToolTip() { + dsGridToolTipProvider = new DSGridToolTipProvider(this.dataGrid, + new String[] {GridRegion.COLUMN_HEADER, GridRegion.BODY}, dataContext, this.bodyDataProvider, + uiPref.isEnableEdit()); + } + + private void enableCornerClickSelectAll() { + this.cornerDataProvider.enableCornerClickSelectAll(this.dataGrid.getUiBindingRegistry(), this.selectionLayer); + } + + private void configureSelectionCopy(GridLayer gridLyr, boolean isCopyWithColumnHeader, + boolean isCopyWithRowheader) { + // register a CopyDataCommandHandler that also copies the headers and + // uses the configured IDisplayConverters + ILayer columnHeaderLyr = null; + ILayer rowNumberLayer = null; + if (isCopyWithColumnHeader) { + columnHeaderLyr = (null != this.selectionColHeaderLayer && !uiPref.isAllowColumnReorder()) + ? this.selectionColHeaderLayer + : this.columnHeaderLayer; + } + + if (isCopyWithRowheader) { + rowNumberLayer = this.selectionRowHeaderLayer; + } + + copyHandler = new DSCopyDataCommandHandler(selectionLayer, columnHeaderLyr, rowNumberLayer, dataProvider); + + copyHandler.setCopyFormattedText(false); + gridLyr.registerCommandHandler(copyHandler); + } + + /** + * Configure selection copy with pref. + * + * @param gridLyr the grid lyr + */ + protected void configureSelectionCopyWithPref(GridLayer gridLyr) { + configureSelectionCopy(gridLyr, this.uiPref.isCopyWithColumnHeader(), this.uiPref.isCopywithRowHeader()); + } + + /** + * Gets the config registry. + * + * @return the config registry + */ + protected ConfigRegistry getConfigRegistry() { + if (this.configRegistry == null) { + this.configRegistry = new ConfigRegistry(); + } + + return this.configRegistry; + } + + /** + * Do advanced copy. + */ + public void doAdvancedCopy() { + setFocus(); + + // update copy configuration based on user preference + configureSelectionCopyWithPref(this.gridLayer); + + // Trigger copy command + this.dataGrid + .doCommand(new CopyDataToClipboardCommand("\t", MPPDBIDEConstants.LINE_SEPARATOR, getConfigRegistry())); + } + + /** + * Do copy. + */ + public void doCopy() { + setFocus(); + + ICellEditor activeEditableCell = dataGrid.getActiveCellEditor(); + if (activeEditableCell != null) { + if (activeEditableCell.getEditorControl() instanceof Text) { + Text textControl = (Text) activeEditableCell.getEditorControl(); + textControl.copy(); + } + } else { + // update copy configuration to copy just cells + configureSelectionCopy(this.gridLayer, false, false); + + // Trigger copy command + this.dataGrid.doCommand( + new CopyDataToClipboardCommand("\t", MPPDBIDEConstants.LINE_SEPARATOR, getConfigRegistry())); + } + } + + /** + * Do sort. + */ + public void doSort() { + int selectedCol = -1; + int[] selectedCols = this.selectionLayer.getSelectedColumnPositions(); + if (selectedCols.length == 1) { + selectedCol = this.selectionLayer.getColumnIndexByPosition(selectedCols[0]); + ISortModel sortModel = this.sortHeaderLayer.getSortModel(); + if (null == sortModel) { + return; + } + sortModel.sort(selectedCol, sortModel.getSortDirection(selectedCol).getNextSortDirection(), false); + } + } + + /** + * Do search. + * + * @param searchText the search text + * @param searchOptions the search options + */ + public void doSearch(String searchText, SEARCHOPTIONS searchOptions) { + saveReorderState(); + TextMatcherEditor rowsMatcher = getMatcherEditor(); + switch (searchOptions) { + case SRCH_CONTAINS: { + searchContains(rowsMatcher, searchText); + break; + } + case SRCH_EQUALS: { + searchEquals(rowsMatcher, searchText); + break; + } + case SRCH_STARTS_WITH: { + searchStartsWith(rowsMatcher, searchText); + break; + } + case SRCH_NULL: { + searchRegex(rowsMatcher, searchText); + break; + } + default: { + // Commented feature: Not working for user input: 1*3 + // Need to be debugged. + break; + } + } + + this.dataGrid.refresh(true); + // : Not a clean fix to set search string from here. + // But no other design choice as of now, so making an + // Ugly fix. To be reviewed, later. + if (null != this.scrollDataLoadListener) { + this.scrollDataLoadListener.setSearchString(searchText); + } + if (searchText.length() > 0) { + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_SEARCH_DONE, null)); + } else { + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_SEARCH_CLEARED, null)); + } + restoreReorderState(); + } + + private void searchRegex(TextMatcherEditor rowsMatcher, String searchText) { + String[] strArray = new String[] {searchText}; + rowsMatcher.setFilterText(strArray); + rowsMatcher.setMode(TextMatcherEditor.REGULAR_EXPRESSION); + if (null != dataFilterList) { + this.dataFilterList.setMatcherEditor(rowsMatcher); // String + } + this.getRegexMarkup().setRegexValue(isStrEmpty(searchText) ? "" : searchText); + } + + private void search(TextMatcherEditor rowsMatcher, String searchText, int mode, String quotedStr) { + rowsMatcher.setMode(mode); + String[] strArray = new String[] {searchText}; + rowsMatcher.setFilterText(strArray); + if (null != dataFilterList) { + this.dataFilterList.setMatcherEditor(rowsMatcher); + } + this.getRegexMarkup().setRegexValue(StringEscapeUtils.escapeHtml(isStrEmpty(searchText) ? "" : quotedStr)); + } + + private void searchStartsWith(TextMatcherEditor rowsMatcher, String searchText) { + String quotedStr = isStrEmpty(searchText) ? "" : ("(?i)(^" + Pattern.quote(searchText) + ')'); + search(rowsMatcher, searchText, TextMatcherEditor.STARTS_WITH, quotedStr); + } + + /** + * Search for text exactly matching the given words. + * + * @param rowsMatcher the rows matcher + * @param searchText the search text + */ + private void searchEquals(TextMatcherEditor rowsMatcher, String searchText) { + String quotedStr = isStrEmpty(searchText) ? "" : ("(?i)(^" + Pattern.quote(searchText) + "$)"); + search(rowsMatcher, searchText, TextMatcherEditor.EXACT, quotedStr); + } + + /** + * Search the text which contains the given words. + * + * @param rowsMatcher the rows matcher + * @param searchText the search text + */ + private void searchContains(TextMatcherEditor rowsMatcher, String searchText) { + String quotedStr = isStrEmpty(searchText) ? "" : "(?i)(" + Pattern.quote(searchText) + ")"; + search(rowsMatcher, searchText, TextMatcherEditor.CONTAINS, quotedStr); + } + + /** + * Is the given text really empty. + * + * @param searchText the search text + * @return true, if is str empty + */ + private boolean isStrEmpty(String searchText) { + return null == searchText || searchText.isEmpty(); + } + + /** + * Gets the regex markup. + * + * @return the regex markup + */ + protected RegexMarkupValue getRegexMarkup() { + if (this.regexMatcher == null) { + this.regexMatcher = new DSHTMLAwareRegexMarkupValue("", + "", ""); + } + return this.regexMatcher; + } + + private TextMatcherEditor getMatcherEditor() { + if (this.matcherEditor == null) { + this.matcherEditor = new TextMatcherEditor(new DSGridTextFilterator()); + } + + return this.matcherEditor; + } + + /** + * Clear matcher. + */ + public void clearMatcher() { + this.matcherEditor = null; + } + + /** + * Input changed. + * + * @param newDataProvider the new data provider + * @param preserveScrollPos the preserve scroll pos + */ + public void inputChanged(IDSGridDataProvider newDataProvider, boolean preserveScrollPos) { + if (null == this.dataGrid || this.dataGrid.isDisposed()) { + /* nattable is already disposed, skip this function call */ + return; + } + setDataProvider(newDataProvider); + createAllLayerDataProviders(); + + dsGridToolTipProvider.setBodyDataProvider(this.bodyDataProvider); + bodyDataLayer.setDataProvider(this.bodyDataProvider); + columnHeaderDataLayer.setDataProvider(this.columnHeaderDataProvider); + rowHeaderDataLayer.setDataProvider(this.rowHeaderDataProvider); + colLabelAccumulator = new GridColumnLabelAccumulator(this.bodyDataLayer, this.dataProvider); + + bodyDataLayer.setConfigLabelAccumulator(colLabelAccumulator); + if (datatypeColumnAccumulator != null) { + datatypeColumnAccumulator.setColumnLabelAccumulator(colLabelAccumulator); + } + + if (uiPref.isEnableSort()) { + this.sortHeaderLayer = new SortHeaderLayer(columnHeaderLayer, + new GlazedListsSortModel(this.dataSortedList, this.colPropAccessor, + getConfigRegistry(), selectionColHeaderLayer), + false); + gridLayer.setColumnHeaderLayer(this.sortHeaderLayer); + this.dataGrid.setLayer(gridLayer); + } + this.cornerLayer.setVerticalLayerDependency( + null != this.sortHeaderLayer ? this.sortHeaderLayer : this.columnHeaderLayer); + configureGridStyle(); + this.dataGrid.configure(); + this.dataGrid.refresh(); + this.eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_POST_GRID_DATA_LOAD, newDataProvider)); + this.eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_CHANGED, newDataProvider)); + + } + + /** + * Gets the selection layer data iterator. + * + * @return the selection layer data iterator + */ + public GridSelectionLayerPortData getSelectionLayerDataIterator() { + return new GridSelectionLayerPortData(this.selectionLayer, this.dataProvider); + } + + /** + * Gets the view layer data iterator. + * + * @return the view layer data iterator + */ + public GridViewPortData getViewLayerDataIterator() { + return new GridViewPortData(this.gridLayer); + } + + /** + * Sets the focus. + */ + public void setFocus() { + if (0 == this.selectionLayer.getSelectedCells().size()) { + this.selectionLayer.setSelectedCell(0, 0); + } + this.dataGrid.setFocus(); + } + + /** + * Sets the focus. + * + * @param columnIndex the column index + * @param rowIndex the row index + */ + public void setFocus(int columnIndex, int rowIndex) { + this.selectionLayer.setLastSelectedCell(columnIndex, rowIndex); + this.dataGrid.setFocus(); + } + + /** + * + * Title: class + * + * Description: The Class DSGridTextFilterator. + */ + private final class DSGridTextFilterator implements TextFilterator { + private String encoding; + private String convertedValue; + + @Override + public void getFilterStrings(List baseList, IDSGridDataRow row) { + // Use cloned values to avoid accidental/unknown updates. + Object[] values = row.getClonedValues(); + for (int colIndex = 0; colIndex < values.length; colIndex++) { + Object value = values[colIndex]; + + if (null != value) { + String columnDataType = dataProvider.getColumnDataProvider().getColumnDataTypeName(colIndex); + if (uiPref.isIncludeEncoding()) { + if (dataProvider instanceof DSResultSetGridDataProvider) { + encoding = ((DSResultSetGridDataProvider) dataProvider).getEncoding(); + if ("".equals(encoding)) { + encoding = uiPref.getDefaultEncoding(); + } + if (value instanceof byte[]) { + byte[] valu1 = (byte[]) value; + + try { + convertedValue = new String(valu1, encoding); + } catch (UnsupportedEncodingException exception) { + MPPDBIDELoggerUtility.error("DSGridTextFilterator: text filterator failed.", + exception); + } + } else { + convertedValue = value.toString(); + } + + } + } else { + convertedValue = value.toString(); + } + baseList.add(getConvertedColumnData(convertedValue, columnDataType)); + } else { + // this is important for null value search + baseList.add(""); + } + } + } + + private String getConvertedColumnData(String dataValue, String columnDataType) { + if ("bit".equals(columnDataType)) { + if (Boolean.toString(true).equalsIgnoreCase(dataValue)) { + return "1"; + } else { + return "0"; + } + } + return dataValue; + } + + } + + /** + * Insert empty row. + * + * @param isSearched the is searched + * @param serverObject the server object + */ + public void insertEmptyRow(boolean isSearched, ServerObject serverObject) { + IDSGridEditDataRow newRow = null; + saveReorderState(); + if (dataGrid.getActiveCellEditor() != null) { + dataGrid.commitAndCloseActiveCellEditor(); + } + + // if Searched then add it to the beginning. + int insertedRowIndex = 0; + + if (!isSearched) { + insertedRowIndex = getSelectedRowPosition(); + if (insertedRowIndex >= 0) { + insertedRowIndex++; + } else if (insertedRowIndex == -1) { + insertedRowIndex = 0; + } + } + if (serverObject == null) { + IDSEditGridDataProvider dp = (IDSEditGridDataProvider) dataProvider; + newRow = dp.getEmptyRowForInsert(insertedRowIndex); + } else { + newRow = ((DSObjectPropertiesGridDataProvider) dataProvider).createNewRow(serverObject, insertedRowIndex); + } + if (newRow == null) { + return; + } + this.dataEventList.add(insertedRowIndex, newRow); + dataGrid.refresh(); + setFocus(0, newRow.getRowIndex()); + restoreReorderState(); + } + + /** + * Delete row. + */ + public void deleteRow() { + saveReorderState(); + setFocus(); + int[] cellPosForDelete = getSelectedRowsForDelete(); + Arrays.sort(cellPosForDelete); + int numDeleted = 0; + boolean isInserted = true; + IDSGridEditDataRow row = null; + if (!this.dataEventList.isEmpty()) { + + for (int position = 0; position < cellPosForDelete.length; position++) { + row = (IDSGridEditDataRow) this.bodyDataProvider.getRowObject(cellPosForDelete[position] - numDeleted); + if (row.getUpdatedState() == EditTableRecordStates.INSERT) { + isInserted = true; + int index = cellPosForDelete[position] - numDeleted; + this.dataEventList.remove(index); + ((IDSEditGridDataProvider) dataProvider).deleteRecord(row, isInserted); + + numDeleted++; + } else { + isInserted = false; + ((IDSEditGridDataProvider) dataProvider).deleteRecord(row, isInserted); + } + + } + + dataGrid.refresh(); + } + restoreReorderState(); + } + + private int[] getSelectedRowsForDelete() { + ArrayList selectedRows = new ArrayList(); + int colCount = this.selectionLayer.getColumnCount(); + HashMap map = new HashMap(); + PositionCoordinate[] selectedCell = this.selectionLayer.getSelectedCellPositions(); + for (int cnt = 0; cnt < selectedCell.length; cnt++) { + if (map.containsKey(selectedCell[cnt].rowPosition)) { + map.put(selectedCell[cnt].rowPosition, map.get(selectedCell[cnt].rowPosition) + 1); + } else { + map.put(selectedCell[cnt].rowPosition, 1); + } + } + + for (Map.Entry entry : map.entrySet()) { + int key = entry.getKey(); + int value = entry.getValue(); + if (value == colCount) { + selectedRows.add(key); + } + } + + int[] selectedRowArray = new int[selectedRows.size()]; + int rowId = 0; + for (Integer rowIdx : selectedRows) { + selectedRowArray[rowId] = rowIdx; + rowId++; + } + + return selectedRowArray; + } + + /** + * Roll back changes. + */ + public void rollBackChanges() { + setFocus(); + if (dataProvider instanceof IDSEditGridDataProvider) { + IDSEditGridDataProvider editDP = (IDSEditGridDataProvider) dataProvider; + editDP.rollBackProvider(); + } + this.dataEventList.clear(); + + this.dataEventList.addAll(dataProvider.getAllFetchedRows()); + dataGrid.refresh(); + } + + /** + * Gets the selected row position. + * + * @return the selected row position + */ + public int getSelectedRowPosition() { + int index = -1; + PositionCoordinate position = this.selectionLayer.getLastSelectedCellPosition(); + if (position != null) { + ILayerCell cell = this.selectionLayer.getCellByPosition(position.getColumnPosition(), + position.getRowPosition()); + if (cell != null) { + index = cell.getRowPosition(); + } + + } + return index; + } + + /** + * + * Title: class + * + * Description: The Class CopyDataWithPrefAction. + */ + private class CopyDataWithPrefAction extends CopyDataAction { + @Override + public void run(NatTable natTable, KeyEvent event) { + // Call customized Copy action. + doAdvancedCopy(); + } + } + + /** + * + * Title: class + * + * Description: The Class CopyDataWithoutPrefAction. + */ + private class CopyDataWithoutPrefAction extends CopyDataAction { + @Override + public void run(NatTable natTable, KeyEvent event) { + // Call customized Copy action. + doCopy(); + } + } + + /** + * Update grid data. + */ + public void updateGridData() { + dataGrid.refresh(); + } + + /** + * Refresh. + */ + public void refresh() { + setFocus(); + if ((dataProvider instanceof IDSEditGridDataProvider + && !((IDSEditGridDataProvider) dataProvider).isGridDataEdited()) + || dataProvider instanceof IDSGridDataProvider) { + if (!stateMachine.isLoading()) { + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_ON_REFRESH_QUERY, dataProvider)); + } + + } + } + + /** + * Paste. + */ + public void paste() { + setFocus(); + dataGrid.doCommand(new GridPasteCommand(getConfigRegistry())); + } + + /** + * + * Title: class + * + * Description: The Class PasteDataWithPrefAction. + */ + private class PasteDataWithPrefAction extends PasteDataAction { + @Override + public void run(NatTable natTable, KeyEvent event) { + // Call customized paste action. + paste(); + } + } + + /** + * Gets the commit status listener. + * + * @return the commit status listener + */ + public IDSListener getCommitStatusListener() { + return new IDSListener() { + @Override + public void handleEvent(DSEvent event) { + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + DataGrid.this.dataGrid.refresh(); + } + }); + + } + }; + } + + /** + * Commit and close active cell editor. + */ + public void commitAndCloseActiveCellEditor() { + dataGrid.commitAndCloseActiveCellEditor(); + + } + + /** + * Close editor. + */ + public void closeEditor() { + ICellEditor cellEditor = dataGrid.getActiveCellEditor(); + if (null != cellEditor && !cellEditor.isClosed()) { + // Force close with the cost of losing the data. + cellEditor.close(); + } + } + + /** + * Checks if is modified records saveable. + * + * @return true, if is modified records saveable + */ + public boolean isModifiedRecordsSaveable() { + if (dataGrid.getActiveCellEditor() != null) { + // If cell is in edit mode, attempt to close the cell and do not + // allow to commit + // as the data entered might be invalid. + commitAndCloseActiveCellEditor(); + return false; + } + setFocus(); + return !this.dataEventList.isEmpty(); + } + + /** + * Adds the grid layer listener. + * + * @param iLayerListener the i layer listener + */ + public void addGridLayerListener(ILayerListener iLayerListener) { + dataGrid.addLayerListener(iLayerListener); + } + + /** + * Checks if is rows only selected. + * + * @return true, if is rows only selected + */ + public boolean isRowsOnlySelected() { + /* + * Null check on selectionLayer for ignoring discard changes call on + * closing of Edit Table window + */ + if (this.selectionLayer != null) { + int rowCount = this.selectionLayer.getSelectedRowCount(); + int fullySelectedRowsCount = getSelectedRowsForDelete().length; + return fullySelectedRowsCount > 0 && fullySelectedRowsCount == rowCount; + } + return false; + } + + /** + * + * Title: class + * + * Description: The Class DataGridContext. + */ + private static class DataGridContext implements IDataGridContext { + private IDSGridDataProvider dp; + + @Override + public IDSGridDataProvider getDataProvider() { + return dp; + } + + @Override + public void setDataProvider(IDSGridDataProvider dataProvider) { + this.dp = dataProvider; + } + + @Override + public List getColumnMetaDataList() { + TableMetaData table = (TableMetaData) dp.getTable(); + if (table != null) { + return table.getColumnMetaDataList(); + } + return null; + } + + /** + * On pre destroy. + */ + public void onPreDestroy() { + dp = null; + } + } + + /** + * Checks if is properties grid.need to check if it can be differentiated + * with uipref + * + * @return true, if is properties grid + */ + public boolean isPropertiesGrid() { + + if (this.dataProvider.getClass() == DSObjectPropertiesGridDataProvider.class) { + return true; + } + return false; + } + + /** + * Checks if is user role properties grid. + * + * @return true, if is user role properties grid + */ + public boolean isUserRolePropertiesGrid() { + if (dataProvider instanceof DSObjectPropertiesGridDataProvider + && ((DSObjectPropertiesGridDataProvider) dataProvider) + .getObjectPropertyObject() instanceof PropertiesUserRoleImpl) { + return true; + } + return false; + } + + /** + * Gets the type of dialog required. + * + * @return the type of dialog required + */ + public ServerObjectTypeForDialog getTypeOfDialogRequired() { + if (!(this.dataProvider instanceof DSObjectPropertiesGridDataProvider)) { + return null; + } + String objectPropertyName = ((DSObjectPropertiesGridDataProvider) dataProvider).getObjectPropertyName(); + switch (objectPropertyName) { + case "General": { + return ServerObjectTypeForDialog.GENERAL; + } + case "Columns": { + return ServerObjectTypeForDialog.COLUMNS; + } + case "Constraints": { + return ServerObjectTypeForDialog.CONSTRAINTS; + } + case "Index": { + return ServerObjectTypeForDialog.INDEX; + } + default: { + break; + } + + } + return null; + + } + + /** + * Gets the parent. + * + * @return the parent + */ + public Composite getParent() { + return this.parent; + } + + /** + * Sets the parent. + * + * @param composite the new parent + */ + public void setParent(Composite composite) { + this.parent = composite; + } + + /** + * + * Title: class + * + * Description: The Class RightClickShowMenuConfiguration. + */ + class RightClickShowMenuConfiguration extends AbstractUiBindingConfiguration { + private Menu menu; + private Menu showMenu; + private MenuItem copyToExcelMenuItem; + private MenuItem copyToxlsMenuItem; + private MenuItem copyToxlsxMenuItem; + private MenuItem copyToclipboardMenuItem; + private MenuItem advancedCopyMenuItem; + private MenuItem copyMenuItem; + private MenuItem searchMenuItem; + private MenuItem setNullMenuItem; + private MenuItem exportMenuItem; + private MenuItem exportCurrentPageItem; + private MenuItem exportAllDataMenuItem; + private MenuItem generateInsertMenuItem; + private MenuItem generateSelectedRowInsertMenuItem; + private MenuItem generateCurrentInsertMenuItem; + private MenuItem generateAllInsertMenuItem; + + private ShowCopyToExcelMenuItemProvider showCopyToExcelMenuItemProvider; + private ShowSearchItemProvider showSearchItemProvider; + private ShowGenerateInsertItemProvider showGenerateInsertItemProvider; + private ShowExpotDataItemProvider showExpotDataItemProvider; + private ShowCopyMenuItemProvider menuItemProvider; + private ShowSetNullItemProvider showsetNullItemProvider; + + /** + * Instantiates a new right click show menu configuration. + * + * @param dsNatTable the ds nat table + */ + public RightClickShowMenuConfiguration(DSNatTable dsNatTable) { + + this.showCopyToExcelMenuItemProvider = new ShowCopyToExcelMenuItemProvider(); + this.showGenerateInsertItemProvider = new ShowGenerateInsertItemProvider(); + this.showSearchItemProvider = new ShowSearchItemProvider(); + this.showExpotDataItemProvider = new ShowExpotDataItemProvider(); + if (uiPref.isShowGenerateInsert()) { + menuItemProvider = new ShowCopyMenuItemProvider(); + showsetNullItemProvider = new ShowSetNullItemProvider(); + + PopupMenuBuilder builder = new PopupMenuBuilder(dsNatTable).withMenuItemProvider(menuItemProvider); + builder.withMenuItemProvider(showCopyToExcelMenuItemProvider); + menu = builder.withMenuItemProvider(showExpotDataItemProvider) + .withMenuItemProvider(showGenerateInsertItemProvider) + .withMenuItemProvider(showsetNullItemProvider).withMenuItemProvider(showSearchItemProvider) + .build(); + } else { + ShowCopyMenuItemProvider showCopyMenuItemProvider = new ShowCopyMenuItemProvider(); + showsetNullItemProvider = new ShowSetNullItemProvider(); + PopupMenuBuilder builder = new PopupMenuBuilder(dsNatTable) + .withMenuItemProvider(showCopyMenuItemProvider); + builder.withMenuItemProvider(showCopyToExcelMenuItemProvider); + menu = builder.withMenuItemProvider(showExpotDataItemProvider) + .withMenuItemProvider(showsetNullItemProvider).withMenuItemProvider(showSearchItemProvider) + .build(); + } + + this.menu.addMenuListener(new ShowMenuConditional()); + } + + /** + * + * Title: class + * + * Description: The Class ShowMenuConditional. + */ + private class ShowMenuConditional implements MenuListener { + + @Override + public void menuHidden(MenuEvent event) { + + } + + @Override + public void menuShown(MenuEvent event) { + getCopyToExcelMenu(); + getSearchMenu(); + setNullMenu(); + getGenerateInsertItem(); + showMenuItemForOpenConnection(); + + if (copyToclipboardMenuItem != null && !copyToclipboardMenuItem.isDisposed()) { + copyToclipboardMenuItem.setEnabled(IHandlerUtilities.getExportDataSelectionOptions()); + } + + if (showExpotDataItemProvider.getExportMenuItem() != null + && !showExpotDataItemProvider.getExportMenuItem().isDisposed()) { + showExpotDataItemProvider.getExportMenuItem() + .setEnabled(IHandlerUtilities.getExportDataSelectionOptions()); + } + + IHandlerUtilities.setMenuItemEnabled(showCopyToExcelMenuItemProvider.getCopyToExcelMenuItem(), + IHandlerUtilities.getExportDataSelectionOptions()); + IHandlerUtilities.setMenuItemEnabled(showGenerateInsertItemProvider.getGenerateInsertMenuItem(), + IHandlerUtilities.getExportDataSelectionOptions()); + + } + + private void showMenuItemForOpenConnection() { + if (!uiPref.isClosedConnection()) { + if (uiPref.isShowGenerateInsert()) { + showExpotDataItemProvider.getExportAllDataMenuItem().setEnabled(false); + showGenerateInsertItemProvider.getGenerateAllInsertMenuItem().setEnabled(false); + } else { + showExpotDataItemProvider.getExportAllDataMenuItem().setEnabled(false); + } + } else { + if (uiPref.isShowGenerateInsert()) { + showExpotDataItemProvider.getExportAllDataMenuItem() + .setEnabled(!dataProvider.isFuncProcExport()); + showGenerateInsertItemProvider.getGenerateAllInsertMenuItem().setEnabled(true); + } else { + showExpotDataItemProvider.getExportAllDataMenuItem() + .setEnabled(!dataProvider.isFuncProcExport()); + } + } + } + + private void getGenerateInsertItem() { + if (!uiPref.isStartSelectQuery() && uiPref.isShowGenerateInsert()) { + showGenerateInsertItemProvider.getGenerateInsertMenuItem().setEnabled(false); + } else if (showGenerateInsertItemProvider.getGenerateInsertMenuItem() != null) { + showGenerateInsertItemProvider.getGenerateInsertMenuItem().setEnabled(true); + } else { + // do nothing + } + } + + private void setNullMenu() { + if (uiPref.isEnableEdit() && ((IDSEditGridDataProvider) dataProvider).isEditSupported()) { + if (null != uiPref.getSelectedEncoding() && uiPref.getSelectedEncoding().equals(PreferenceWrapper + .getInstance().getPreferenceStore().getString(UserEncodingOption.DATA_STUDIO_ENCODING))) { + setNullMenuItem.setEnabled(true); + } else { + setNullMenuItem.setEnabled(false); + } + + } else { + setNullMenuItem.setEnabled(false); + } + } + + private void getSearchMenu() { + if (selectionLayer.getSelectedCells().size() > 1) { + showSearchItemProvider.getSearchMenuItem().setEnabled(false); + } else { + handleSearchMenuEnableForSingleSelection(); + } + } + + private void handleSearchMenuEnableForSingleSelection() { + if (selectionLayer.getSelectedCellPositions().length == 0 + || (dataProvider != null && isSelectedCellColumnUnstrucredDatatype())) { + searchMenuItem.setEnabled(false); + } else { + searchMenuItem.setEnabled(true); + } + } + + private boolean isSelectedCellColumnUnstrucredDatatype() { + String datatypeName = dataProvider.getColumnDataProvider() + .getColumnDataTypeName(selectionLayer.getSelectedCellPositions()[0].columnPosition); + if (datatypeName == null) { + return false; + } + switch (datatypeName) { + case MPPDBIDEConstants.BLOB: + case MPPDBIDEConstants.BYTEA: { + return true; + } + default: { + return false; + } + } + } + + private void getCopyToExcelMenu() { + if (0 == selectionLayer.getSelectedCells().size()) { + showCopyToExcelMenuItemProvider.getCopyToExcelMenuItem().setEnabled(false); + } else { + showCopyToExcelMenuItemProvider.getCopyToExcelMenuItem().setEnabled(true); + } + } + + } + + /** + * Configure ui bindings. + * + * @param uiBindingRegistry the ui binding registry + */ + @Override + public void configureUiBindings(UiBindingRegistry uiBindingRegistry) { + uiBindingRegistry.registerMouseDownBinding( + new MouseEventMatcher(SWT.NONE, GridRegion.BODY, MouseEventMatcher.RIGHT_BUTTON), + new PopupMenuAction(this.menu)); + uiBindingRegistry.registerKeyBinding(new KeyEventMatcher(SWT.MOD2, SWT.F9), new IKeyAction() { + @Override + public void run(NatTable nattable, KeyEvent keyevent) { + menu.setVisible(true); + } + }); + } + + /** + * + * Title: class + * + * Description: The Class ShowCopyToExcelMenuItemProvider. + */ + private class ShowCopyToExcelMenuItemProvider implements IMenuItemProvider { + + @Override + public void addMenuItem(NatTable natTable, Menu popupMenu) { + copyToExcelMenuItem = new MenuItem(popupMenu, SWT.CASCADE); + copyToExcelMenuItem + .setText(MessageConfigLoader.getProperty(IMessagesConstants.COPY_TO_EXCEL_RESULT_WINDOW_MENU)); + showMenu = new Menu(popupMenu); + copyToExcelMenuItem.setMenu(showMenu); + copyToxlsMenuItem = new MenuItem(showMenu, SWT.PUSH); + copyToxlsMenuItem.setText( + MessageConfigLoader.getProperty(IMessagesConstants.COPY_TO_EXCEL_XLS_RESULT_WINDOW_MENUITEM)); + copyToxlsxMenuItem = new MenuItem(showMenu, SWT.PUSH); + copyToxlsxMenuItem.setText( + MessageConfigLoader.getProperty(IMessagesConstants.COPY_TO_EXCEL_XLSX_RESULT_WINDOW_MENUITEM)); + + // copy to xls + copyToxlsMenuItem.addSelectionListener(new SelectionAdapter() { + + @Override + public void widgetSelected(SelectionEvent event) { + + if (stateMachine.set(DSGridStateMachine.State.EXPORTING)) { + eventTable.sendEvent( + new DSEvent(IDSGridUIListenable.LISTEN_COPY_TO_EXCEL_XLS_RESULT_WINDOW_MENUITEM, + new Observer() { + @Override + public void update(Observable observable, Object obj) { + if (obj instanceof Boolean && ((boolean) obj)) { + stateMachine.set(DSGridStateMachine.State.IDLE); + } + + } + })); + } + + } + + }); + // copy to xlsx + copyToxlsxMenuItem.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + if (stateMachine.set(DSGridStateMachine.State.EXPORTING)) { + eventTable.sendEvent( + new DSEvent(IDSGridUIListenable.LISTEN_COPY_TO_EXCEL_XLSX_RESULT_WINDOW_MENUITEM, + new Observer() { + @Override + public void update(Observable observable, Object obj) { + if (obj instanceof Boolean && ((boolean) obj)) { + if (stateMachine != null) { + stateMachine.set(DSGridStateMachine.State.IDLE); + } + } + + } + })); + } + } + + }); + + } + + /** + * Gets the copy to excel menu item. + * + * @return the copy to excel menu item + */ + public MenuItem getCopyToExcelMenuItem() { + return copyToExcelMenuItem; + } + + } + + /** + * + * Title: class + * + * Description: The Class ShowCopyMenuItemProvider. + */ + private class ShowCopyMenuItemProvider implements IMenuItemProvider { + @Override + public void addMenuItem(NatTable natTable, Menu popupMenu) { + copyToclipboardMenuItem = new MenuItem(popupMenu, SWT.CASCADE); + copyToclipboardMenuItem.setText(MessageConfigLoader + .getProperty(IMessagesConstants.RIGHT_CLICK_COPY_TO_CLIPBOARD_RESULT_WINDOW_CONTENTS)); + showMenu = new Menu(popupMenu); + copyToclipboardMenuItem.setMenu(showMenu); + copyMenuItem = new MenuItem(showMenu, SWT.PUSH); + String toolTipMsg = MessageConfigLoader + .getProperty(IMessagesConstants.RIGHT_CLICK_COPY_RESULT_WINDOW_CONTENTS); + copyMenuItem.setText(toolTipMsg); + + copyMenuItem.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + doCopy(); + } + + }); + advancedCopyMenuItem = new MenuItem(showMenu, SWT.PUSH); + String copyToolTipMsg = MessageConfigLoader + .getProperty(IMessagesConstants.RIGHT_CLICK_COPY_ADVANCED_RESULT_WINDOW_CONTENTS); + advancedCopyMenuItem.setText(copyToolTipMsg); + advancedCopyMenuItem.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + + doAdvancedCopy(); + + } + + }); + } + + } + + /** + * + * Title: class + * + * Description: The Class ShowSearchItemProvider. + */ + private class ShowSearchItemProvider implements IMenuItemProvider { + + @Override + public void addMenuItem(NatTable natTable, Menu popupMenu) { + + searchMenuItem = new MenuItem(popupMenu, SWT.PUSH); + String toolTipMsg = MessageConfigLoader.getProperty(IMessagesConstants.SEARCH_RESULT_WINDOW_CONTENTS); + searchMenuItem.setText(toolTipMsg); + searchMenuItem.addSelectionListener(new SelectionAdapter() { + + @Override + public void widgetSelected(SelectionEvent event) { + Object dataValueByPosition = null; + if (0 == selectionLayer.getSelectedCells().size()) { + NatEventData natEventData = MenuItemProviders.getNatEventData(event); + int rowPosition = natEventData == null ? 0 : natEventData.getRowPosition(); + int columnPosition = natEventData == null ? 0 : natEventData.getColumnPosition(); + dataValueByPosition = natTable.getDataValueByPosition(columnPosition, rowPosition); + } + eventTable.sendEvent(new DSEvent( + IDSGridUIListenable.LISTEN_TYPE_ON_RESULT_WINDOW_MENUITEM_SEARCH, dataValueByPosition)); + } + + }); + } + + /** + * Gets the search menu item. + * + * @return the search menu item + */ + public MenuItem getSearchMenuItem() { + return searchMenuItem; + } + + } + + /** + * + * Title: class + * + * Description: The Class ShowSetNullItemProvider. + */ + private class ShowSetNullItemProvider implements IMenuItemProvider { + + @Override + public void addMenuItem(NatTable natTable, Menu popupMenu) { + setNullMenuItem = new MenuItem(popupMenu, SWT.PUSH); + String toolTipMsg = MessageConfigLoader.getProperty(IMessagesConstants.SET_NULL_RESULT_WINDOW_CONTENTS); + setNullMenuItem.setText(toolTipMsg); + setNullMenuItem.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + if (0 == selectionLayer.getSelectedCells().size()) { + NatEventData natEventData = MenuItemProviders.getNatEventData(event); + int rowPosition = natEventData == null ? 0 : natEventData.getRowPosition(); + int columnPosition = natEventData == null ? 0 : natEventData.getColumnPosition(); + natTable.doCommand(new UpdateDataCommand(natTable, columnPosition, rowPosition, null)); + } else { + UpdateDataCommandHandler updateHandler = new UpdateDataCommandHandler(bodyDataLayer); + PositionCoordinate[] selectedCellPositions = selectionLayer.getSelectedCellPositions(); + for (PositionCoordinate positionCoordinate : selectedCellPositions) { + int columnPosition = positionCoordinate.getColumnPosition(); + int rowPosition = positionCoordinate.getRowPosition(); + updateHandler.doCommand(natTable, + new UpdateDataCommand(natTable, columnPosition, rowPosition, null)); + } + + } + + } + }); + } + + } + + /** + * + * Title: class + * + * Description: The Class ShowGenerateInsertItemProvider. + */ + private class ShowGenerateInsertItemProvider implements IMenuItemProvider { + + @Override + public void addMenuItem(NatTable natTable, Menu popupMenu) { + generateInsertMenuItem = new MenuItem(popupMenu, SWT.CASCADE); + generateInsertMenuItem.setText(MessageConfigLoader + .getProperty(IMessagesConstants.RIGHT_CLICK_GENERATE_INSERT_RESULT_WINDOW_CONTENTS)); + showMenu = new Menu(popupMenu); + generateInsertMenuItem.setMenu(showMenu); + generateSelectedRowInsertMenuItem = new MenuItem(showMenu, SWT.PUSH); + String toolTipMsg = MessageConfigLoader + .getProperty(IMessagesConstants.RIGHT_CLICK_SELECTED_ROW_INSERT_RESULT_WINDOW_CONTENTS); + generateSelectedRowInsertMenuItem.setText(toolTipMsg); + generateSelectedRowInsertMenuItem.addSelectionListener(selectedRowInsertMenuSelectionListener()); + generateCurrentInsertMenuItem = new MenuItem(showMenu, SWT.PUSH); + String toolTipMsgCurrentInsert = MessageConfigLoader + .getProperty(IMessagesConstants.RIGHT_CLICK_CURRENT_INSERT_RESULT_WINDOW_CONTENTS); + generateCurrentInsertMenuItem.setText(toolTipMsgCurrentInsert); + generateCurrentInsertMenuItem.addSelectionListener(currentInsertMenuSelectionListener()); + generateAllInsertMenuItem = new MenuItem(showMenu, SWT.PUSH); + String toolTipMsgAllData = MessageConfigLoader + .getProperty(IMessagesConstants.RIGHT_CLICK_ALL_DATA_INSERT_RESULT_WINDOW_CONTENTS); + generateAllInsertMenuItem.setText(toolTipMsgAllData); + generateAllInsertMenuItem.addSelectionListener(allInsertMenuSelectionListener()); + } + + private SelectionAdapter allInsertMenuSelectionListener() { + return new SelectionAdapter() { + + @Override + public void widgetSelected(SelectionEvent event) { + eventTable.sendEvent(new DSEvent( + IDSGridUIListenable.LISTEN_TYPE_ON_RESULT_MENUITEM_GERERATE_ALL_INSERT, new Observer() { + @Override + public void update(Observable observable, Object obj) { + if (obj instanceof Boolean && ((boolean) obj)) { + stateMachine.set(DSGridStateMachine.State.IDLE); + } + + } + })); + } + + }; + } + + private SelectionAdapter currentInsertMenuSelectionListener() { + return new SelectionAdapter() { + + @Override + public void widgetSelected(SelectionEvent event) { + eventTable.sendEvent(new DSEvent( + IDSGridUIListenable.LISTEN_TYPE_ON_RESULT_MENUITEM_GERERATE_CURRENT_PAGE_INSERT, + new Observer() { + @Override + public void update(Observable observable, Object obj) { + if (obj instanceof Boolean && ((boolean) obj)) { + stateMachine.set(DSGridStateMachine.State.IDLE); + } + + } + })); + } + + }; + } + + private SelectionAdapter selectedRowInsertMenuSelectionListener() { + return new SelectionAdapter() { + + @Override + public void widgetSelected(SelectionEvent event) { + setFocus(); + eventTable.sendEvent(new DSEvent( + IDSGridUIListenable.LISTEN_TYPE_ON_RESULT_MENUITEM_GERERATE_SELECT_LINE_INSERT, + new Observer() { + @Override + public void update(Observable observable, Object obj) { + if (obj instanceof Boolean && ((boolean) obj)) { + stateMachine.set(DSGridStateMachine.State.IDLE); + } + + } + })); + } + + }; + } + + /** + * Gets the generate insert menu item. + * + * @return the generate insert menu item + */ + public MenuItem getGenerateInsertMenuItem() { + return generateInsertMenuItem; + } + + /** + * Gets the generate all insert menu item. + * + * @return the generate all insert menu item + */ + public MenuItem getGenerateAllInsertMenuItem() { + return generateAllInsertMenuItem; + } + + } + + /** + * + * Title: class + * + * Description: The Class ShowExpotDataItemProvider. + */ + private class ShowExpotDataItemProvider implements IMenuItemProvider { + + @Override + public void addMenuItem(NatTable natTable, Menu popupMenu) { + exportMenuItem = new MenuItem(popupMenu, SWT.CASCADE); + exportMenuItem.setText( + MessageConfigLoader.getProperty(IMessagesConstants.RIGHT_CLICK_EXPORT_RESULT_WINDOW_CONTENTS)); + showMenu = new Menu(popupMenu); + exportMenuItem.setMenu(showMenu); + exportCurrentPageItem = new MenuItem(showMenu, SWT.PUSH); + String toolTipMsg1 = MessageConfigLoader + .getProperty(IMessagesConstants.RIGHT_CLICK_EXPORT_CURRENT_PAGE_DATA_RESULT_WINDOW_CONTENTS); + exportCurrentPageItem.setText(toolTipMsg1); + exportCurrentPageItem.addSelectionListener(new SelectionAdapter() { + + @Override + public void widgetSelected(SelectionEvent event) { + if (stateMachine.set(DSGridStateMachine.State.EXPORTING)) { + eventTable.sendEvent( + new DSEvent(IDSGridUIListenable.LISTEN_TYPE_EXPORT_CURR_PAGE_DATA, new Observer() { + @Override + public void update(Observable observable, Object obj) { + if (obj instanceof Boolean && ((boolean) obj)) { + stateMachine.set(DSGridStateMachine.State.IDLE); + } + + } + })); + } + } + }); + exportAllDataMenuItem = new MenuItem(showMenu, SWT.PUSH); + String toolTipMsg2 = MessageConfigLoader + .getProperty(IMessagesConstants.RIGHT_CLICK_EXPORT_ALL_DATA_RESULT_WINDOW_CONTENTS); + exportAllDataMenuItem.setText(toolTipMsg2); + exportAllDataMenuItem.setEnabled(!dataProvider.isFuncProcExport()); + exportAllDataMenuItem.addSelectionListener(new SelectionAdapter() { + + @Override + public void widgetSelected(SelectionEvent event) { + if (stateMachine.set(DSGridStateMachine.State.EXPORTING)) { + eventTable.sendEvent( + new DSEvent(IDSGridUIListenable.LISTEN_TYPE_EXPORT_ALL_DATA, new Observer() { + @Override + public void update(Observable observable, Object obj) { + if (obj instanceof Boolean && !((boolean) obj)) { + stateMachine.set(DSGridStateMachine.State.IDLE); + } + + } + })); + } + } + + }); + + } + + /** + * Gets the export all data menu item. + * + * @return the export all data menu item + */ + public MenuItem getExportAllDataMenuItem() { + return exportAllDataMenuItem; + } + + /** + * Gets the export parent menu item. + * + * @return the export parent menu item + */ + public MenuItem getExportMenuItem() { + return exportMenuItem; + } + + } + + /** + * Pre destroy. + */ + public void preDestroy() { + showCopyToExcelMenuItemProvider = null; + showSearchItemProvider = null; + showGenerateInsertItemProvider = null; + showExpotDataItemProvider = null; + menuItemProvider = null; + showsetNullItemProvider = null; + } + } + + /** + * update scrolled row info and page size + * + * @param position the ui position + * @param pageRowSize the page size + */ + public void updateScrolledInfo(int position, int pageRowSize) { + if (pageRowSize > 0) { + this.currentScrolledRow = selectionLayer.getRowPositionByY(position); + this.pageRowSize = pageRowSize; + } else { + this.currentScrolledRow = position; + } + } + + /** + * return current scrolled row + * + * @return int the scrolled row + */ + public int getCurScrolledRow() { + return this.currentScrolledRow; + } + + /** + * return current need setted scroll row + * + * @param scrolledRow the row to scroll to + * @return then grid mode scrolled row + */ + public int getCurrentScrolledBeginRow(int scrolledRow) { + return scrolledRow + pageRowSize - 1; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DataText.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DataText.java new file mode 100644 index 0000000000000000000000000000000000000000..bd57733384c762a941343793a40c7a280d8af140 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DataText.java @@ -0,0 +1,1957 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import java.io.UnsupportedEncodingException; +import java.nio.charset.Charset; +import java.sql.Timestamp; +import java.sql.Types; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.eclipse.jface.resource.JFaceResources; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StyleRange; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.dnd.Clipboard; +import org.eclipse.swt.dnd.TextTransfer; +import org.eclipse.swt.dnd.Transfer; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.events.KeyListener; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.events.MouseListener; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.MenuItem; +import org.eclipse.swt.widgets.Shell; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.presentation.edittabledata.DSResultSetGridDataRow; +import org.opengauss.mppdbide.presentation.edittabledata.IDSGridEditDataRow; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.ProgressBarLabelFormatter; +import org.opengauss.mppdbide.utils.messaging.StatusMessage; +import org.opengauss.mppdbide.utils.messaging.StatusMessageList; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.utils.observer.DSEventTable; +import org.opengauss.mppdbide.utils.observer.IDSGridUIListenable; +import org.opengauss.mppdbide.utils.observer.IDSListener; +import org.opengauss.mppdbide.view.component.DSGridStateMachine; +import org.opengauss.mppdbide.view.component.IGridUIPreference; +import org.opengauss.mppdbide.view.component.grid.DSGridComponent; +import org.opengauss.mppdbide.view.component.grid.GridSearchArea; +import org.opengauss.mppdbide.view.component.grid.GridUIUtils; +import org.opengauss.mppdbide.view.component.grid.TextScrollEventDataLoadListener; +import org.opengauss.mppdbide.view.handler.IHandlerUtilities; +import org.opengauss.mppdbide.view.ui.dialog.TextCellDialog; +import org.opengauss.mppdbide.view.ui.terminal.SQLTerminal; +import org.opengauss.mppdbide.view.utils.BottomStatusBar; +import org.opengauss.mppdbide.view.utils.DateFormatUtils; +import org.opengauss.mppdbide.view.utils.UIElement; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs.MESSAGEDIALOGTYPE; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; +import org.opengauss.mppdbide.view.workerjob.UIWorkerJob; + +/** + * + * Title: class + * + * Description: The Class DataText. + * + * @since 3.0.0 + */ +public class DataText { + + /** + * The Constant FIRST_ROW_LINE. + */ + public static final int FIRST_ROW_LINE = 2; + + /** + * The Constant FOUR_MB. + */ + private TextScrollEventDataLoadListener scrollDataLoadListener; + private String cellText; + private int cellTextColumnNumber; + private int cellTextLineNumber; + private String[] cloNames; + private IDSGridColumnProvider colPro; + private List allRows; + private int maxColumnSize; + private int[] colWidths; + private StyledText styledText; + private StyledText styledSearchText; + private int replaceTab; + + private int horOffsetBegin; + private int horOffsetEnd; + private int lineOffset; + private int offset = -1; + private Composite textParent; + private Composite searchParent; + private IGridUIPreference uiPref; + + /** + * The event table. + */ + protected DSEventTable eventTable; + private DSGridStateMachine stateMachine; + + /** + * The data provider. + */ + protected IDSGridDataProvider dataProvider; + private boolean searchHideOrShowFlag; + private StyleRange curLineRange; + private DSGridComponent gridComponent; + private MenuItem searchItem; + private MenuItem copyItem; + private MenuItem refreshItem; + + private MenuItem searchItemForSearchText; + + private boolean showOrHiderefFlag; + private String defaultEncod; + private String selEncod; + private boolean endLineFlag; + private boolean refreshFlag; + private boolean endodingFlag; + private List styleTextList = new ArrayList(); + private List searchMatchLineList; + private GridSearchArea searchArea; + private boolean searchStatus; + private boolean successWorkerFlag; + private boolean initDataTextFlag; + + private boolean partloaded; + private int loadedRowCnt; + + private List cursorGridRowList; + private int scrolledRow = 0; + + /** + * Instantiates a new data text. + * + * @param uiPref the ui pref + * @param dataProvider the data provider + * @param eventTable the event table + * @param stateMachine the state machine + * @param gridComponent the grid component + */ + public DataText(IGridUIPreference uiPref, IDSGridDataProvider dataProvider, DSEventTable eventTable, + DSGridStateMachine stateMachine, DSGridComponent gridComponent) { + this.uiPref = uiPref; + this.eventTable = eventTable; + this.stateMachine = stateMachine; + this.dataProvider = dataProvider; + this.gridComponent = gridComponent; + this.replaceTab = uiPref.replaceTab(); + } + + /** + * Creates the component. + * + * @param parent the parent + */ + + public void createComponent(Composite parent) { + this.textParent = parent; + GridUIUtils.createHorizontalLine(parent); + parent.setLayout(new GridLayout(1, false)); + styledText = new StyledText(parent, SWT.READ_ONLY | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); + styledText.setBlockSelection(false); + styledText.setCursor(parent.getDisplay().getSystemCursor(SWT.CURSOR_IBEAM)); + styledText.setMargins(4, 4, 4, 4); + styledText.setFont(JFaceResources.getFont(JFaceResources.TEXT_FONT)); + styledText.setLayoutData(new GridData(GridData.FILL_BOTH)); + getEncoding(); + styledText.setMenu(createEditPopup()); + styledText.addCaretListener(event -> onCursorChange(event.caretOffset)); + addListenerMourseClick(); + addListenerKeyClick(); + loadTextData(); + } + + /** + * set the begin show index line + * + * @param index then row of styletext + */ + public void setTopIndex(int index) { + scrolledRow = index; + styledText.setTopIndex(scrolledRow + 2); + } + + /** + * return current text mode scrolled row + * + * @return int the scrolled row + */ + public int getTopIndex() { + return scrolledRow; + } + + /** + * update scrolled line info + */ + public void updateScrolledInfo() { + scrolledRow = styledText.getTopIndex() - 2; + } + + private void addListenerKeyClick() { + + styledText.addKeyListener(new KeyListener() { + @Override + public void keyReleased(KeyEvent event) { + + } + + @Override + public void keyPressed(KeyEvent event) { + if (event.stateMask == SWT.SHIFT && event.keyCode == SWT.F9) { + styledText.getMenu().setVisible(true); + } + } + }); + } + + private void addListenerMourseClick() { + styledText.addMouseListener(new MouseListener() { + @Override + public void mouseDoubleClick(MouseEvent event) { + + } + + @Override + public void mouseDown(MouseEvent event) { + + } + + @Override + public void mouseUp(MouseEvent event) { + boolean selFlag = isStrEmpty(styledText.getSelectionText()); + int[] selTextRange = styledText.getSelectionRanges(); + if (!selFlag && selTextRange.length == 2 && searchArea.isSearchButEnable()) { + searchItem.setEnabled(true); + } else { + searchItem.setEnabled(false); + } + if (isShowOrHiderefFlag()) { + if (gridComponent.isRefreshButEnable()) { + refreshItem.setEnabled(true); + } else { + refreshItem.setEnabled(false); + } + } + if (event.button == 1 && selFlag) { + if (checkCursorDataDailog() && validateCellText()) { + showCursorDataDailog(cursorGridRowList); + } else { + showDataTextCellDialog(); + } + } + copyItem.setEnabled(IHandlerUtilities.getExportDataSelectionOptions()); + } + }); + } + + private boolean checkCursorDataDailog() { + IDSGridDataRow dataRowObject = null; + for (int i = 0; i < allRows.size(); i++) { + dataRowObject = allRows.get(i); + Object[] row = dataRowObject.getValues(); + if (cellTextColumnNumber <= row.length && row[cellTextColumnNumber] != null + && row[cellTextColumnNumber] instanceof List) { + this.cursorGridRowList = (List) row[cellTextColumnNumber]; + return true; + } + } + return false; + } + + private void showCursorDataDailog(List cursorGridRowList) { + DSCursorResultSetTable cursorResultSetTable = new DSCursorResultSetTable(); + cursorResultSetTable.activateCell(null, cursorGridRowList); + } + + private void showDataTextCellDialog() { + Shell shell = Display.getDefault().getActiveShell(); + TextCellDialog dialog = new TextCellDialog(maxColumnSize, shell); + if (null != cellText) { + showDataTextDialog(dialog); + } + } + + private void showDataTextDialog(TextCellDialog dialog) { + if (validateCellText()) { + dialog.setTextValue(cellText); + dialog.open(); + } else if (validateCellDataLength()) { + Clipboard cb = new Clipboard(Display.getDefault()); + Object[] objArray = new Object[] {cellText}; + Transfer[] transArray = new Transfer[] {TextTransfer.getInstance()}; + cb.setContents(objArray, transArray); + MPPDBIDEDialogs.generateOKMessageDialog(MESSAGEDIALOGTYPE.WARNING, true, + MessageConfigLoader.getProperty(IMessagesConstants.RESULT_WINDOW_TEXT_CELL_INVISIBLE_VALUE_TITLE), + MessageConfigLoader.getProperty(IMessagesConstants.RESULT_WINDOW_TEXT_CELL_INVISIBLE_VALUE_BODY)); + } + } + + private boolean validateCellDataLength() { + return cellText.length() > MPPDBIDEConstants.TEXT_MODE_CELL_DIALOG_MAXINUM; + } + + private boolean validateCellText() { + return isSpecialCell() + || (cellText.length() > maxColumnSize + && cellText.length() <= MPPDBIDEConstants.TEXT_MODE_CELL_DIALOG_MAXINUM) + || (MPPDBIDEConstants.BLOB + .equals(dataProvider.getColumnDataProvider().getColumnDataTypeName(cellTextColumnNumber)) + && cellText.length() <= maxColumnSize && cellTextLineNumber > 1) + || (MPPDBIDEConstants.BYTEA + .equals(dataProvider.getColumnDataProvider().getColumnDataTypeName(cellTextColumnNumber)) + && cellText.length() <= maxColumnSize && cellTextLineNumber > 1) + || cellText.length() <= maxColumnSize && cellTextLineNumber > 1 + && MPPDBIDEConstants.CURSOR_WATERMARK.equals(cellText); + } + + /** + * Reset text data. + * + * @param provider the provider + */ + + public void resetTextData(IDSGridDataProvider provider) { + this.setDataProvider(provider); + this.getEncoding(); + if (validateForRefresh()) { + updateStatusBarForDataText(); + setDataTextFocusAndLoadData(); + } else if (validateForEncoding()) { + setDataTextFocusAndLoadData(); + } else { + setDataTextFocusAndLoadData(); + scrollDataLoadListener.setDataProvider(provider); + updateStatusBarForPartLoaded(); + } + } + + private void updateStatusBarForPartLoaded() { + if (partloaded) { + gridComponent.updateGridStatusBarForDataText(this.partloaded, this.loadedRowCnt); + } + } + + private void updateStatusBarForDataText() { + if (!gridComponent.isShowGridOrShowTextSelect()) { + gridComponent.updateGridStatusBarForDataText(this.partloaded, this.loadedRowCnt); + } + } + + private void setDataTextFocusAndLoadData() { + boolean searchStr = isStrEmpty(gridComponent.getSearchTxtString()); + if (searchStr) { + this.styledText.setFocus(); + } + loadTextData(); + } + + /** + * Configure load on scroll. + * + * @param eventTbl the event tbl + */ + public void configureLoadOnScroll(final DSEventTable eventTbl) { + preventConcurrentDataLoad(eventTbl); + this.scrollDataLoadListener = new TextScrollEventDataLoadListener(this.styledText, this.dataProvider, eventTbl, + this.stateMachine, this); + // Add a listener to the text scrollbar + this.styledText.getVerticalBar().addListener(SWT.Selection, scrollDataLoadListener); + this.styledText.addKeyListener(scrollDataLoadListener); + } + + private void preventConcurrentDataLoad(DSEventTable eventTbl) { + eventTbl.hook(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_CHANGED, new IDSListener() { + @Override + public void handleEvent(DSEvent event) { + DataText.this.scrollDataLoadListener.resetLoadingStatus(); + } + }); + eventTbl.hook(IDSGridUIListenable.LISTEN_TYPE_ON_ERROR, new IDSListener() { + @Override + public void handleEvent(DSEvent event) { + DataText.this.scrollDataLoadListener.resetLoadingStatus(); + } + }); + } + + /** + * Do hide text. + * + * @param composite the composite + */ + public void doHideText(Composite composite) { + GridUIUtils.toggleCompositeSectionVisibility(composite, true, null, false); + } + + /** + * Do show text. + * + * @param composite the composite + */ + public void doShowText(Composite composite) { + GridUIUtils.toggleCompositeSectionVisibility(composite, false, null, false); + } + + /** + * Load text data. + */ + private void loadTextData() { + String progressBarLabel; + if (validateForRefresh()) { + progressBarLabel = getProgressBarLabel(IMessagesConstants.RESULT_WINDOW_SQL_REFRESH_EXECUTE); + } else if (validateForEncoding()) { + progressBarLabel = getProgressBarLabel(IMessagesConstants.RESULT_WINDOW_SQL_ENCODING_EXECUTE); + } else { + progressBarLabel = getProgressBarLabel(IMessagesConstants.RESULT_WINDOW_SQL_LOADING_EXECUTE); + } + this.setSuccessWorkerFlag(false); + setScrollStatus(); + ReloadTextDataWorker initJob = new ReloadTextDataWorker(progressBarLabel); + activateStatusbar(); + initJob.schedule(); + } + + private void setScrollStatus() { + if (isInitDataTextFlag()) { + setScrollStatusOnInitOrLoad(true); + } else { + gridComponent.updataButStatusOnLoadDataText(false); + setScrollStatusOnInitOrLoad(true); + } + } + + private boolean validateForEncoding() { + return gridComponent.getDataText().isEncodingFlag(); + } + + private boolean validateForRefresh() { + return gridComponent.getDataText().isRefreshFlag(); + } + + /** + * Replace specal char. + * + * @param objRow the obj row + * @param num the num + * @return the string + */ + private String replaceSpecalChar(Object[] objRow, int num) { + if (MPPDBIDEConstants.BLOB.equals(dataProvider.getColumnDataProvider().getColumnDataTypeName(num))) { + if (objRow[num] != null) { + return MPPDBIDEConstants.BLOB_WATERMARK; + } + return ""; + } + if (Types.OTHER == (dataProvider.getColumnDataProvider().getColumnDatatype(num))) { + if (objRow[num] != null && objRow[num] instanceof List) { + this.cellText = MPPDBIDEConstants.CURSOR_WATERMARK; + return MPPDBIDEConstants.CURSOR_WATERMARK; + } + } + if (MPPDBIDEConstants.BYTEA.equals(dataProvider.getColumnDataProvider().getColumnDataTypeName(num))) { + if (objRow[num] != null) { + return MPPDBIDEConstants.BYTEA_WATERMARK; + } + return ""; + } + if (Types.TIMESTAMP == dataProvider.getColumnDataProvider().getColumnDatatype(num) + || Types.TIMESTAMP_WITH_TIMEZONE == dataProvider.getColumnDataProvider().getColumnDatatype(num)) { + if (objRow[num] != null && objRow[num] instanceof Timestamp) { + Timestamp timestamp = (Timestamp) objRow[num]; + return DateFormatUtils.handleTimeStampValues(timestamp); + } + } + if (Types.TIME == dataProvider.getColumnDataProvider().getColumnDatatype(num) + || Types.TIME_WITH_TIMEZONE == dataProvider.getColumnDataProvider().getColumnDatatype(num)) { + if (objRow[num] != null && objRow[num] instanceof Timestamp) { + Timestamp timestamp = (Timestamp) objRow[num]; + return DateFormatUtils.handleTimeValues(timestamp); + } + } + Object str = null; + str = getEncodedValue(objRow, num); + String displayString = this.isStrEmpty(str) ? "" : String.valueOf(str); + Pattern pattern = Pattern.compile("\t"); + Matcher matcher = pattern.matcher(displayString); + displayString = replaceOnTab(displayString, matcher); + Pattern p1 = Pattern.compile(System.lineSeparator()); + Matcher m1 = p1.matcher(displayString); + displayString = replaceLineSeperator(displayString, m1); + return displayString; + } + + private String replaceLineSeperator(String displayStringParam, Matcher m1) { + String displayString = displayStringParam; + if (m1.find()) { + displayString = m1.replaceAll(""); + } + return displayString; + } + + private String replaceOnTab(String displayStringParam, Matcher matcher) { + String displayString = displayStringParam; + if (matcher.find()) { + displayString = matcher.replaceAll(this.getTabStr(replaceTab)); + } + return displayString; + } + + private Object getEncodedValue(Object[] objRow, int num) { + Object str; + if (validateSelectedEncoding()) { + str = getEncodedValue(objRow[num], defaultEncod); + } else { + str = getEncodedValue(objRow[num], selEncod); + } + return str; + } + + private boolean validateSelectedEncoding() { + return null == selEncod || MPPDBIDEConstants.SPACE_CHAR.equals(selEncod); + } + + /** + * Show row. + * + * @param dataRow the data row + * @param rowSB the row SB + */ + private void showRow(List dataRow, StringBuilder rowSB) { + if (validateDataRow(dataRow)) { + setRowLength(dataRow, rowSB); + } + rowSB.setLength(rowSB.length() - System.lineSeparator().length()); + } + + private void setRowLength(List dataRow, StringBuilder rowSB) { + for (int cnt = 0; cnt < dataRow.size(); cnt++) { + IDSGridDataRow row = dataRow.get(cnt); + + getTruncatedString(rowSB, row); + rowSB.append("|"); + rowSB.append(System.lineSeparator()); + + // maximal characters validation + + if (validateRowLength(rowSB)) { + partloaded = true; + loadedRowCnt = cnt + 1; + break; + } + } + } + + private boolean validateRowLength(StringBuilder rowSB) { + return rowSB.length() > MPPDBIDEConstants.TEXT_MODE_LOAD_MAXIMUM; + } + + private boolean validateDataRow(List dataRow) { + return null != dataRow && dataRow.size() != 0; + } + + private void getTruncatedString(StringBuilder rowSB, IDSGridDataRow row) { + Object[] obj = null; + for (int elmnt = 0; elmnt < cloNames.length; elmnt++) { + appendSeperator(rowSB, elmnt); + obj = row.getValues(); + String displayString = replaceSpecalChar(obj, elmnt); + + displayString = truncateString(elmnt, displayString); + rowSB.append(displayString); + + appendEmptySpace(rowSB, elmnt, displayString); + } + } + + private String truncateString(int count, String displayStringParam) { + String displayString = displayStringParam; + if (displayString.length() >= colWidths[count] - 1) { + displayString = GridUIUtils.truncateString(displayString, colWidths[count] - 1); + } + return displayString; + } + + private void appendSeperator(StringBuilder rowSB, int count) { + if (count > 0) { + rowSB.append("|"); + } + } + + private void appendEmptySpace(StringBuilder rowSB, int item, String displayString) { + for (int ele = colWidths[item] - displayString.length(); ele > 0; ele--) { + rowSB.append(" "); + } + } + + private void getStyledTextList() { + + this.setSearchHideOrShowFlag(false); + styleTextList.clear(); + for (int ele = 0; ele < styledText.getLineCount(); ele++) { + styleTextList.add(styledText.getLine(ele)); + } + } + + /** + * Gets the selected row position. + * + * @return the selected row position + */ + public int getSelectedRowPosition() { + return this.styledText.getSelectionCount(); + } + + /** + * Gets the data provider. + * + * @return the data provider + */ + public IDSGridDataProvider getDataProvider() { + return dataProvider; + } + + /** + * Sets the data provider. + * + * @param dataProvider the new data provider + */ + public void setDataProvider(IDSGridDataProvider dataProvider) { + this.dataProvider = dataProvider; + this.allRows = dataProvider.getAllFetchedRows(); + this.maxColumnSize = uiPref.getColumnWidth(); + this.allRows = dataProvider.getAllFetchedRows(); + this.colPro = dataProvider.getColumnDataProvider(); + this.cloNames = colPro.getColumnNames(); + } + + /** + * Do copy. + */ + public void doCopy() { + if (this.textParent.isVisible()) { + this.styledText.copy(); + } else { + styledSearchText.copy(); + } + + } + + /** + * Do search. + * + * @param searchText the search text + * @param searchOptions the search options + */ + + public void setSearchStringForScrollBar(String searchText) { + if (null != this.scrollDataLoadListener) { + this.scrollDataLoadListener.setSearchString(searchText); + } + } + + /** + * Enable disable refresh button. + * + * @param searchText the search text + */ + public void enableDisableRefreshButton(String searchText) { + if (searchText.length() > 0) { + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_SEARCH_DONE, null)); + } else { + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_SEARCH_CLEARED, null)); + } + } + + /** + * Gets the text parent. + * + * @return the text parent + */ + public Composite getTextParent() { + return textParent; + } + + /** + * Sets the parent. + * + * @param parent the new parent + */ + public void setParent(Composite parent) { + this.textParent = parent; + } + + /** + * Gets the search parent. + * + * @return the search parent + */ + public Composite getSearchParent() { + return searchParent; + } + + /** + * Sets the search parent. + * + * @param parent the new search parent + */ + public void setSearchParent(Composite parent) { + this.searchParent = parent; + } + + private boolean isStrEmpty(Object searchText) { + return null == searchText || String.valueOf(searchText).isEmpty(); + } + + /** + * Search reg. + * + * @param searText the sear text + */ + public void searchReg(String searText) { + this.getStyledTextList(); + this.changeButStatus(false); + this.setSearchStatus(true); + this.setSuccessWorkerFlag(false); + DataTextSearchNullWorker nullJobWorker = new DataTextSearchNullWorker( + getProgressBarLabel(IMessagesConstants.RESULT_WINDOW_SQL_SEARCH_EXECUTE)); + activateStatusbar(); + nullJobWorker.schedule(); + } + + private void activateStatusbar() { + final BottomStatusBar bttmStatusBar = UIElement.getInstance().getProgressBarOnTop(); + StatusMessage statMssage = new StatusMessage( + MessageConfigLoader.getProperty(IMessagesConstants.TITLE_EXPORT_IN_PROGRESS)); + StatusMessageList.getInstance().push(statMssage); + if (bttmStatusBar != null) { + bttmStatusBar.activateStatusbar(); + } + } + + /** + * Search contains. + * + * @param searchText the search text + */ + public void searchContains(String searchText) { + String quotedStr = isStrEmpty(searchText) ? "" : "(?i)(" + Pattern.quote(searchText) + ")"; + search(quotedStr); + } + + /** + * Search equals. + * + * @param searchText the search text + */ + public void searchEquals(String searchText) { + String quotedStr = isStrEmpty(searchText) ? "" : ("(?i)(^" + Pattern.quote(searchText) + "$)"); + search(quotedStr); + } + + /** + * Search starts with. + * + * @param searchText the search text + */ + public void searchStartsWith(String searchText) { + String quotedStr = isStrEmpty(searchText) ? "" : ("(?i)(^" + Pattern.quote(searchText) + ')'); + search(quotedStr); + } + + /* + * Cancel search + */ + private void searchClear() { + this.setSearchHideOrShowFlag(false); + this.gridComponent.hideStatusBar(); + this.doHideText(this.searchParent); + this.doShowText(this.textParent); + this.gridComponent.showStatusBar(); + if (this.offset != -1) { + this.setHigtLight(lineOffset + horOffsetBegin, horOffsetEnd - horOffsetBegin - 1, SWT.COLOR_WHITE); + } + } + + private void search(String quotedStr) { + if ("".equals(quotedStr)) { + searchClear(); + return; + } + changeButStatus(false); + getStyledTextList(); + this.setSearchStatus(true); + this.setSuccessWorkerFlag(false); + DataTextSearchWorker job = new DataTextSearchWorker( + getProgressBarLabel(IMessagesConstants.RESULT_WINDOW_SQL_SEARCH_EXECUTE), quotedStr); + activateStatusbar(); + job.schedule(); + } + + /** + * Creates the search component. + */ + public void createSearchComponent() { + GridUIUtils.createHorizontalLine(searchParent); + searchParent.setLayout(new GridLayout(1, false)); + styledSearchText = new StyledText(searchParent, SWT.READ_ONLY | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); + styledSearchText.setBlockSelection(false); + styledSearchText.setCursor(searchParent.getDisplay().getSystemCursor(SWT.CURSOR_IBEAM)); + styledSearchText.setMargins(4, 4, 4, 4); + styledSearchText.setFont(JFaceResources.getFont(JFaceResources.TEXT_FONT)); + styledSearchText.setLayoutData(new GridData(GridData.FILL_BOTH)); + styledSearchText.setMenu(createEditPopupForSearchText()); + styledSearchText.addCaretListener(event -> onCursorChange(event.caretOffset)); + addListenerMourseClickForSearchText(); + addListenerKeyClickForSearchText(); + } + + private void addListenerKeyClickForSearchText() { + + styledSearchText.addKeyListener(new KeyListener() { + @Override + public void keyReleased(KeyEvent event) { + + } + + @Override + public void keyPressed(KeyEvent event) { + if (event.stateMask == SWT.SHIFT && event.keyCode == SWT.F9) { + styledSearchText.getMenu().setVisible(true); + } + } + }); + } + + private void addListenerMourseClickForSearchText() { + styledSearchText.addMouseListener(new MouseListener() { + @Override + public void mouseDoubleClick(MouseEvent event) { + } + + @Override + public void mouseDown(MouseEvent event) { + } + + @Override + public void mouseUp(MouseEvent event) { + boolean selFlag = isStrEmpty(styledSearchText.getSelectionText()); + int[] selTextRange = styledSearchText.getSelectionRanges(); + if (!selFlag && selTextRange.length == 2 && searchArea.isSearchButEnable()) { + searchItemForSearchText.setEnabled(true); + } else { + searchItemForSearchText.setEnabled(false); + } + if (event.button == 1 && selFlag) { + showDataTextCellDialog(); + } + } + }); + } + + private Menu createEditPopupForSearchText() { + Menu popMenu = new Menu(this.searchParent); + MenuItem copyItemForSearchText = new MenuItem(popMenu, SWT.PUSH); + copyItemForSearchText.setText(MessageConfigLoader.getProperty(IMessagesConstants.COPY_RESULT_WINDOW_CONTENTS)); + searchItemForSearchText = new MenuItem(popMenu, SWT.PUSH); + searchItemForSearchText.setText(MessageConfigLoader.getProperty(IMessagesConstants.SEARCH_GRID)); + searchItemForSearchText.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent arg0) { + if (gridComponent.validateSearchOption()) { + gridComponent.getTriggerSearch("", true); + } else { + String seleText = styledSearchText.getSelectionText(); + gridComponent.setTxtSeatrchText(seleText); + gridComponent.getTriggerSearch(seleText, true); + } + } + + @Override + public void widgetDefaultSelected(SelectionEvent arg0) { + + } + }); + + copyItemForSearchText.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent arg0) { + doCopy(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent arg0) { + + } + }); + return popMenu; + } + + /** + * Checks if is search hide or show flag. + * + * @return true, if is search hide or show flag + */ + public boolean isSearchHideOrShowFlag() { + return searchHideOrShowFlag; + } + + /** + * Sets the search hide or show flag. + * + * @param searchHideOrShowFlag the new search hide or show flag + */ + public void setSearchHideOrShowFlag(boolean searchHideOrShowFlag) { + this.searchHideOrShowFlag = searchHideOrShowFlag; + } + + private String getTabStr(int spaceNum) { + StringBuffer buf = new StringBuffer(); + for (int index = 0; index < spaceNum; ++index) { + buf.append(" "); + } + String str = buf.toString(); + return str; + } + + /** + * On cursor change. + * + * @param off the off + */ + private void onCursorChange(int off) { + int columNum = 0; + int lineNum = 0; + this.offset = off; + lineNum = getOffSetAtLine(off); + int horizontalOffset = off - lineOffset; + horOffsetBegin = 0; + horOffsetEnd = 0; + columNum = getColumnNumber(horizontalOffset); + setTextCell(lineNum, columNum, lineOffset, horOffsetBegin, horOffsetEnd); + // Highlight row + setHighLightRow(); + + } + + private void setHighLightRow() { + if (this.textParent.isVisible()) { + setHigtLight(lineOffset + horOffsetBegin, horOffsetEnd - horOffsetBegin - 1, SWT.COLOR_GRAY); + } + } + + private int getColumnNumber(int horizontalOffset) { + int columNum = 0; + for (int index = 0; index < colWidths.length; index++) { + horOffsetBegin = horOffsetEnd; + horOffsetEnd += colWidths[index] + 1; + columNum = index; + if (horizontalOffset < horOffsetEnd) { + columNum = index; + break; + } + } + return columNum; + } + + private int getOffSetAtLine(int off) { + int lineNum; + if (this.textParent.isVisible()) { + lineNum = styledText.getLineAtOffset(off); + lineOffset = styledText.getOffsetAtLine(lineNum); + } else { + lineNum = styledSearchText.getLineAtOffset(off); + lineOffset = styledSearchText.getOffsetAtLine(lineNum); + } + return lineNum; + } + + /** + * Sets the text cell. + * + * @param lineCount the line count + * @param coluCount the colu count + * @param lineOffsetCount the line offset count + * @param horOffsetBeginCount the hor offset begin count + * @param horOffsetEndCount the hor offset end count + */ + private void setTextCell(int lineCount, int coluCount, int lineOffsetCount, int horOffsetBeginCount, + int horOffsetEndCount) { + cellText = getCellText(lineCount, coluCount, lineOffsetCount, horOffsetBeginCount, horOffsetEndCount); + cellTextColumnNumber = coluCount; + cellTextLineNumber = lineCount; + } + + private String getCellText(int lineCount, int coluCount, int lineOffsetCount, int horOffsetBeginCount, + int horOffsetEndCount) { + if (lineCount < FIRST_ROW_LINE) { + return styledText.getText(lineOffsetCount + horOffsetBeginCount, + lineOffsetCount + horOffsetEndCount - FIRST_ROW_LINE); + } + + if (this.textParent.isVisible()) { + return getCellTextIfLineCountIsLess(lineCount, coluCount); + } else { + return getCellTextIfSearchLinesIsLess(lineCount, coluCount); + } + } + + private String getCellTextIfSearchLinesIsLess(int lineCount, int coluCount) { + if (allRows.size() >= searchMatchLineList.size() && searchMatchLineList.size() > lineCount - FIRST_ROW_LINE) { + return getCellTextForVisibleParent(lineCount, coluCount); + } + return null; + } + + private String getCellTextIfLineCountIsLess(int lineCount, int coluCount) { + if (allRows.size() > lineCount - FIRST_ROW_LINE) { + return getCellTextForVisibleParent(lineCount, coluCount); + + } + return null; + } + + private String getCellTextForVisibleParent(int lineCount, int coluCount) { + int fourMb = 4194304; // 4*1024*1024 MB + IDSGridDataRow dataRow = allRows.get(lineCount - FIRST_ROW_LINE); + if (MPPDBIDEConstants.BLOB.equals(dataProvider.getColumnDataProvider().getColumnDataTypeName(coluCount))) { + if (dataRow instanceof IDSGridEditDataRow) { + IDSGridEditDataRow dataEditRow = (IDSGridEditDataRow) dataRow; + byte[] byteValue = (byte[]) dataEditRow.getOriginalValue(coluCount); + if (byteValue != null) { + if (byteValue.length > fourMb) { + return MessageConfigLoader.getProperty(IMessagesConstants.FILE_SIZE_EXCEEDED_FOUR); + } + return DSUnstructuredDataConversionHelper.bytesToHex(byteValue); + } + } + return null; + } + if (MPPDBIDEConstants.BYTEA.equals(dataProvider.getColumnDataProvider().getColumnDataTypeName(coluCount))) { + if (dataRow instanceof IDSGridEditDataRow) { + IDSGridEditDataRow dataEditRow = (IDSGridEditDataRow) dataRow; + byte[] byteValue = (byte[]) dataEditRow.getOriginalValue(coluCount); + if (byteValue != null) { + if (byteValue.length > fourMb) { + return MessageConfigLoader.getProperty(IMessagesConstants.FILE_SIZE_EXCEEDED_FOUR); + } + return DSUnstructuredDataConversionHelper.bytesToHexFormated(byteValue); + } + } + return null; + } + if (dataRow instanceof IDSGridEditDataRow) { + IDSGridEditDataRow dataEditRow = (IDSGridEditDataRow) dataRow; + return String.valueOf(getEncodedValue(dataEditRow.getOriginalValue(coluCount), selEncod)); + } else if (dataRow instanceof DSResultSetGridDataRow) { + Object[] rowObject = dataRow.getValues(); + if (rowObject[coluCount] != null && rowObject[coluCount] instanceof List) { + List gridObj = (List) rowObject[coluCount]; + if (gridObj.get(0) instanceof DSResultSetGridDataRow) { + return MPPDBIDEConstants.CURSOR_WATERMARK; + } + } + } else { + Object[] obj = dataRow.getValues(); + if (obj.length > coluCount) { + return String.valueOf(getEncodedValue(obj[coluCount], selEncod)); + } + } + return null; + } + + /** + * Creates the edit popup. + * + * @return the menu + */ + private Menu createEditPopup() { + Menu popMenu = new Menu(this.textParent); + copyItem = new MenuItem(popMenu, SWT.PUSH); + copyItem.setText(MessageConfigLoader.getProperty(IMessagesConstants.COPY_RESULT_WINDOW_CONTENTS)); + if (this.isShowOrHiderefFlag()) { + + refreshItem = new MenuItem(popMenu, SWT.PUSH); + refreshItem.setText(MessageConfigLoader.getProperty(IMessagesConstants.REFRESH_TABLE_TOOLTIP)); + refreshItem.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent arg0) { + gridComponent.refreshDataGrid(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent arg0) { + + } + }); + + } + searchItem = new MenuItem(popMenu, SWT.PUSH); + searchItem.setText(MessageConfigLoader.getProperty(IMessagesConstants.SEARCH_GRID)); + searchItem.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent arg0) { + if (gridComponent.validateSearchOption()) { + gridComponent.getTriggerSearch("", true); + } else { + String seleText = styledText.getSelectionText(); + gridComponent.setTxtSeatrchText(seleText); + gridComponent.getTriggerSearch(seleText, true); + } + } + + @Override + public void widgetDefaultSelected(SelectionEvent arg0) { + + } + }); + + copyItem.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent arg0) { + doCopy(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent arg0) { + + } + }); + return popMenu; + } + + /* + * Get transcoded value + */ + private Object getEncodedValue(Object value, String encoding) { + if (value instanceof byte[]) { + byte[] byteVal = (byte[]) value; + try { + return getValue(encoding, byteVal); + } catch (UnsupportedEncodingException e) { + // Ignore. nothing can be done here. + MPPDBIDELoggerUtility.debug("Encoding failed"); + } + } + return value; + } + + private Object getValue(String encoding, byte[] byteVal) throws UnsupportedEncodingException { + if (null != encoding && !encoding.isEmpty()) { + return new String(byteVal, encoding); + } + return new String(byteVal, Charset.defaultCharset()); + } + + private void setHigtLight(int start, int length, int style) { + curLineRange = new StyleRange(start, length, null, Display.getCurrent().getSystemColor(style)); + StyleRange[] styleRange = new StyleRange[] {curLineRange}; + Display.getDefault().syncExec(() -> styledText.setStyleRanges(styleRange)); + } + + /** + * Update text data. + */ + public void updateTextData() { + getEncoding(); + loadTextData(); + } + + /** + * Sets the end line flag. + * + * @param endLineFlag the new end line flag + */ + public void setEndLineFlag(boolean endLineFlag) { + this.endLineFlag = endLineFlag; + } + + /** + * Gets the end line flag. + * + * @return the end line flag + */ + public boolean getEndLineFlag() { + return this.endLineFlag; + } + + /** + * Checks if is refresh flag. + * + * @return true, if is refresh flag + */ + public boolean isRefreshFlag() { + return refreshFlag; + } + + /** + * Sets the refresh flag. + * + * @param refreshFlag the new refresh flag + */ + public void setRefreshFlag(boolean refreshFlag) { + this.refreshFlag = refreshFlag; + } + + /** + * Checks if is encoding flag. + * + * @return true, if is encoding flag + */ + public boolean isEncodingFlag() { + return endodingFlag; + } + + /** + * Sets the endoding flag. + * + * @param endodingFlag the new endoding flag + */ + public void setEndodingFlag(boolean endodingFlag) { + this.endodingFlag = endodingFlag; + } + + private boolean isSpecialCell() { + if (this.isStrEmpty(cellText)) { + return false; + } + String regEx = System.lineSeparator() + "|\r|\t"; + Pattern pattern = Pattern.compile(regEx); + Matcher matcher = pattern.matcher(cellText); + return matcher.find(); + } + + /** + * Sets the sear area. + * + * @param area the new sear area + */ + public void setSearArea(GridSearchArea area) { + this.searchArea = area; + } + + /** + * Change but status. + * + * @param status the status + */ + public void changeButStatus(boolean status) { + searchArea.updataButStatusOnDataTextSearch(status); + } + + private String getProgressBarLabel(String executeMessage) { + Database database = this.dataProvider.getDatabse(); + SQLTerminal sqlTerminal = UIElement.getInstance().getSqlTerminalModel(); + String sqlTerminalPartLabel = ""; + + database = setDataBaseinTerminal(database, sqlTerminal); + + sqlTerminalPartLabel = getPartLabel(sqlTerminal, sqlTerminalPartLabel); + return ProgressBarLabelFormatter.getProgressLabelForTextModeLoading(getDatabaseName(database), + getServerName(database), sqlTerminalPartLabel, executeMessage); + } + + private String getPartLabel(SQLTerminal sqlTerminal, String sqlTerminalPartLabelParam) { + String sqlTerminalPartLabel = sqlTerminalPartLabelParam; + if (sqlTerminal != null) { + sqlTerminalPartLabel = sqlTerminal.getPartLabel(); + } + return sqlTerminalPartLabel; + } + + private String getServerName(Database database) { + return null == database ? "" : database.getServerName(); + } + + private String getDatabaseName(Database database) { + return null == database ? "" : database.getName(); + } + + private Database setDataBaseinTerminal(Database databaseParam, SQLTerminal sqlTerminal) { + Database database = databaseParam; + if (database == null) { + if (null != sqlTerminal) { + database = sqlTerminal.getSelectedDatabase(); + } + } + return database; + } + + /** + * Checks if is search status. + * + * @return true, if is search status + */ + public boolean isSearchStatus() { + return searchStatus; + } + + /** + * Sets the search status. + * + * @param searchStatus the new search status + */ + public void setSearchStatus(boolean searchStatus) { + this.searchStatus = searchStatus; + } + + /** + * Checks if is show or hideref flag. + * + * @return true, if is show or hideref flag + */ + public boolean isShowOrHiderefFlag() { + return showOrHiderefFlag; + } + + /** + * Sets the show or hideref flag. + * + * @param showOrHiderefFlag the new show or hideref flag + */ + public void setShowOrHiderefFlag(boolean showOrHiderefFlag) { + this.showOrHiderefFlag = showOrHiderefFlag; + } + + /** + * Checks if is success worker flag. + * + * @return true, if is success worker flag + */ + public boolean isSuccessWorkerFlag() { + return successWorkerFlag; + } + + /** + * Sets the success worker flag. + * + * @param successWorkerFlag the new success worker flag + */ + public void setSuccessWorkerFlag(boolean successWorkerFlag) { + this.successWorkerFlag = successWorkerFlag; + } + + /** + * Checks if is inits the data text flag. + * + * @return true, if is inits the data text flag + */ + public boolean isInitDataTextFlag() { + return initDataTextFlag; + } + + /** + * Sets the inits the data text flag. + * + * @param initDataTextFlag the new inits the data text flag + */ + public void setInitDataTextFlag(boolean initDataTextFlag) { + this.initDataTextFlag = initDataTextFlag; + } + + /** + * Checks if is partloaded. + * + * @return true, if is partloaded + */ + public boolean isPartloaded() { + return partloaded; + } + + /** + * Sets the partloaded. + * + * @param partloaded the new partloaded + */ + public void setPartloaded(boolean partloaded) { + this.partloaded = partloaded; + } + + /** + * Gets the loaded row cnt. + * + * @return the loaded row cnt + */ + public int getLoadedRowCnt() { + return loadedRowCnt; + } + + /** + * Sets the loaded row cnt. + * + * @param loadedRowCnt the new loaded row cnt + */ + public void setLoadedRowCnt(int loadedRowCnt) { + this.loadedRowCnt = loadedRowCnt; + } + + /** + * On pre destroy. + */ + public void onPreDestroy() { + colWidths = null; + colPro = null; + this.cloNames = null; + styledSearchText = null; + searchParent = null; + textParent = null; + uiPref = null; + eventTable = null; + curLineRange = null; + searchItem = null; + copyItem = null; + refreshItem = null; + searchArea = null; + eventTable = null; + uiPref = null; + this.allRows = null; + removeKeyListner(); + styledText = null; + deleteObserver(); + } + + private void deleteObserver() { + if (this.stateMachine != null && this.stateMachine.countObservers() > 0) { + this.stateMachine.deleteObservers(); + } + } + + private void removeKeyListner() { + if (this.scrollDataLoadListener != null && styledText != null) { + scrollDataLoadListener.onPreDestroy(); + this.styledText.removeKeyListener(this.scrollDataLoadListener); + } + } + + private void getEncoding() { + defaultEncod = uiPref.getDefaultEncoding(); + selEncod = gridComponent.getSelectedEncoding(); + } + + /** + * Creates the initial data model. + * + * @return the string + */ + private String createInitialDataModel() { + StringBuilder loadDateSB = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + maxColumnSize = uiPref.getColumnWidth(); + allRows = dataProvider.getAllFetchedRows(); + colPro = dataProvider.getColumnDataProvider(); + cloNames = colPro.getColumnNames(); + colWidths = new int[cloNames.length]; + setMaxColumnWidth(); + setColumnSize(); + + // Add text header + addTextHeader(loadDateSB); + loadDateSB.append("|"); + loadDateSB.append(System.lineSeparator()); + // Add separator + addSeperator(loadDateSB); + // Add text line + loadDateSB.append(System.lineSeparator()); + showRow(allRows, loadDateSB); + return String.valueOf(loadDateSB); + + } + + private void setMaxColumnWidth() { + Object[] objRow = null; + for (int index = 0; index < cloNames.length; index++) { + colWidths[index] = cloNames[index].length(); + for (IDSGridDataRow row : allRows) { + objRow = row.getValues(); + String displayString = replaceSpecalChar(objRow, index); + colWidths[index] = Math.max(colWidths[index], displayString.length()); + } + } + } + + private void setColumnSize() { + for (int cnt = 0; cnt < colWidths.length; cnt++) { + colWidths[cnt]++; + if (colWidths[cnt] > maxColumnSize) { + colWidths[cnt] = maxColumnSize; + } + } + } + + private void addTextHeader(StringBuilder loadDateSB) { + for (int index = 0; index < cloNames.length; index++) { + appendSeperator(loadDateSB, index); + String attrName = cloNames[index]; + attrName = GridUIUtils.truncateString(attrName, colWidths[index] - 1); + loadDateSB.append(attrName); + appendEmptySpace(loadDateSB, index, attrName); + } + } + + private void addSeperator(StringBuilder loadDateSB) { + for (int cnt = 0; cnt < cloNames.length; cnt++) { + appendSeperator(loadDateSB, cnt); + for (int k = colWidths[cnt]; k > 0; k--) { + loadDateSB.append("-"); + } + } + loadDateSB.append("|"); + } + + private void handleUIstatusOnInitDataTextFail() { + if (isInitDataTextFlag()) { + setUIstatusOnInitDataTextCancelOrException(); + } else { + gridComponent.getToolbar().updataButStatusOnLoadDataTextException(); + if (gridComponent.isShowGridOrShowTextSelect()) { + setScrollStatusOnInitOrLoad(false); + } else { + setScrollStatusOnInitOrLoad(true); + } + } + } + + private void setUIstatusOnInitDataTextCancelOrException() { + setInitDataTextFlag(true); + setScrollStatusOnInitOrLoad(false); + gridComponent.getToolbar().updataButStatusOnInitDataTextCancelOrException(); + } + + private void setScrollStatusOnInitOrLoad(boolean scrollStatus) { + if (null != scrollDataLoadListener) { + scrollDataLoadListener.setCurrentInitDataTextSatatu(scrollStatus); + } + } + + /** + * + * Title: class + * + * Description: The Class DataTextSearchWorker. + */ + private final class DataTextSearchWorker extends TerminalWorker { + private String quotedStr; + private List styleList = new ArrayList(); + private StringBuilder matchTextSB = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + Color colorStyle = Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW); + + /** + * Instantiates a new data text search worker. + * + * @param message the message + * @param quotedStr the quoted str + */ + public DataTextSearchWorker(String message, String quotedStr) { + super(message, MPPDBIDEConstants.CANCELABLEJOB); + this.quotedStr = quotedStr; + } + + @Override + public Object doJob() + throws DatabaseOperationException, DatabaseCriticalException, MPPDBIDEException, Exception { + searchTextMatch(); + return null; + } + + @Override + public void onOutOfMemoryError(OutOfMemoryError exception) { + MPPDBIDELoggerUtility.error("DataText: OutofMemory error occurred.", exception); + MPPDBIDEDialogs.generateOKMessageDialogInUI(MESSAGEDIALOGTYPE.ERROR, true, getWindowImage(), + MessageConfigLoader.getProperty(IMessagesConstants.TITLE_OUT_OF_MEMORY), + MessageConfigLoader.getProperty(IMessagesConstants.ERR_OUT_OF_MEMORY_SEARCH_OCCURED)); + } + + private void searchTextMatch() throws MPPDBIDEException { + searchMatchLineList = new ArrayList(); + int lineLenth = getLineLength(); + int searchLineCount = 1; + formMatchTextSB(); + for (int item = 0; item < styleTextList.size() - FIRST_ROW_LINE; item++) { + Object[] objRow = allRows.get(item).getValues(); + int serchCount = 0; + int lineMark = 0; + for (int rowIndex = 0; rowIndex < objRow.length; rowIndex++) { + if (null == objRow[rowIndex]) { + continue; + } + String str = replaceSpecalChar(objRow, rowIndex); + Pattern pattern = Pattern.compile(quotedStr); + Matcher matcher = pattern.matcher(String.valueOf(str)); + while (matcher.find()) { + serchCount++; + lineMark++; + if (serchCount == 1) { + handleMatchTextAndSearchMatchLine(item, lineMark); + searchLineCount++; + } + + /* + * Get the number of matches before the matching letter + */ + int lineCount = 0; + if (rowIndex > 0) { + for (int cnt = 0; cnt < rowIndex; cnt++) { + lineCount = colWidths[cnt] + lineCount; + } + } + lineCount = lineCount + rowIndex; + String displayString = GridUIUtils.truncateString(String.valueOf(str), colWidths[rowIndex] - 1); + + addCurLineRangeToStyleList(lineLenth, searchLineCount, matcher, lineCount, displayString); + + } + } + } + Display.getDefault().syncExec(() -> { + styledSearchText.setText(matchTextSB.toString()); + }); + StyleRange[] styleArray = styleList.toArray(new StyleRange[0] ); + Display.getDefault().asyncExec(() -> styledSearchText.setStyleRanges(styleArray)); + } + + private void addCurLineRangeToStyleList(int lineLenth, int searchLineCount, Matcher matcher, int lineCount, + String displayString) { + if (displayString.length() >= matcher.end()) { + int start = lineCount + matcher.start() + lineLenth * searchLineCount; + int end = lineCount + matcher.end() + lineLenth * searchLineCount; + curLineRange = new StyleRange(start, end - start, null, colorStyle); + styleList.add(curLineRange); + } else if (displayString.length() > matcher.start() && displayString.length() <= matcher.end()) { + int start = lineCount + matcher.start() + lineLenth * searchLineCount; + int end = lineCount + displayString.length() + lineLenth * searchLineCount; + curLineRange = new StyleRange(start, end - start, null, colorStyle); + styleList.add(curLineRange); + } + } + + private void handleMatchTextAndSearchMatchLine(int index, int lineMark) { + if (lineMark == 1) { + if (styleTextList.size() > FIRST_ROW_LINE) { + matchTextSB.append(System.lineSeparator() + styleTextList.get(index + FIRST_ROW_LINE)); + searchMatchLineList.add(index); + } + } + } + + private void formMatchTextSB() { + if (styleTextList.size() >= FIRST_ROW_LINE) { + for (int row = 0; row < FIRST_ROW_LINE; row++) { + if (row == 0) { + matchTextSB.append(styleTextList.get(row)); + } else { + matchTextSB.append(System.lineSeparator() + styleTextList.get(row)); + } + } + } + } + + private int getLineLength() { + int lineLenth = System.lineSeparator().length(); + if (styleTextList.size() > 0) { + lineLenth = styleTextList.get(0).length() + lineLenth; + } + return lineLenth; + } + + @Override + public void onSuccessUIAction(Object obj) { + doHideText(textParent); + doShowText(searchParent); + setSearchHideOrShowFlag(true); + setSuccessWorkerFlag(true); + setSearchStatus(false); + changeButStatus(true); + } + + @Override + public void finalCleanupUI() { + + cleanList(); + } + + @Override + protected void canceling() { + super.canceling(); + if (!isSuccessWorkerFlag()) { + changeButStatus(true); + } + } + + private void cleanList() { + styleList.clear(); + styleTextList.clear(); + matchTextSB.delete(0, matchTextSB.length()); + } + } + + /** + * + * Title: class + * + * Description: The Class DataTextSearchNullWorker. + */ + private final class DataTextSearchNullWorker extends TerminalWorker { + private StringBuilder matchTextSB = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + /** + * Instantiates a new data text search null worker. + * + * @param message the message + */ + public DataTextSearchNullWorker(String message) { + super(message, MPPDBIDEConstants.CANCELABLEJOB); + } + + @Override + public Object doJob() + throws DatabaseOperationException, DatabaseCriticalException, MPPDBIDEException, Exception { + searchNullMatch(); + return null; + } + + @Override + public void onOutOfMemoryError(OutOfMemoryError exception) { + MPPDBIDELoggerUtility.error("DataText: OutofMemory error occurred.", exception); + MPPDBIDEDialogs.generateOKMessageDialogInUI(MESSAGEDIALOGTYPE.ERROR, true, getWindowImage(), + MessageConfigLoader.getProperty(IMessagesConstants.TITLE_OUT_OF_MEMORY), + MessageConfigLoader.getProperty(IMessagesConstants.ERR_OUT_OF_MEMORY_SEARCH_OCCURED)); + + } + + private void searchNullMatch() { + searchMatchLineList = new ArrayList(); + if (styleTextList.size() >= FIRST_ROW_LINE) { + for (int rwcnt = 0; rwcnt < FIRST_ROW_LINE; rwcnt++) { + if (rwcnt == 0) { + matchTextSB.append(styleTextList.get(rwcnt)); + } else { + matchTextSB.append(System.lineSeparator() + styleTextList.get(rwcnt)); + } + } + } + if (styleTextList.size() > FIRST_ROW_LINE) { + for (int index = 0; index < styleTextList.size() - FIRST_ROW_LINE; index++) { + Object[] objRow = allRows.get(index).getValues(); + for (int cnt = 0; cnt < objRow.length; cnt++) { + if (null == objRow[cnt]) { + matchTextSB.append(System.lineSeparator() + styleTextList.get(index + FIRST_ROW_LINE)); + searchMatchLineList.add(index); + break; + } + } + } + } + Display.getDefault().asyncExec(() -> styledSearchText.setText(matchTextSB.toString())); + } + + @Override + public void onSuccessUIAction(Object obj) { + doHideText(textParent); + doShowText(searchParent); + setSearchHideOrShowFlag(true); + setSuccessWorkerFlag(true); + changeButStatus(true); + setSearchStatus(false); + } + + @Override + public void finalCleanupUI() { + cleanList(); + } + + private void cleanList() { + styleTextList.clear(); + searchMatchLineList.clear(); + matchTextSB.delete(0, matchTextSB.length()); + } + + @Override + protected void canceling() { + super.canceling(); + if (!isSuccessWorkerFlag()) { + changeButStatus(true); + } + } + + } + + /** + * + * Title: class + * + * Description: The Class ReloadTextDataWorker. + */ + private final class ReloadTextDataWorker extends TerminalWorker { + + /** + * Instantiates a new reload text data worker. + * + * @param execuMessage the execu message + */ + public ReloadTextDataWorker(String execuMessage) { + super(execuMessage, MPPDBIDEConstants.CANCELABLEJOB); + + } + + @Override + public Object doJob() + throws DatabaseOperationException, DatabaseCriticalException, MPPDBIDEException, Exception { + return createInitialDataModel(); + } + + @Override + public void onSuccessUIAction(Object objParam) { + Object obj = objParam; + try { + if (null != styledText) { + styledText.setText(String.valueOf(obj)); + styledText.setTopIndex(scrolledRow + 2); + if (isInitDataTextFlag() && styledText.getLineCount() > FIRST_ROW_LINE) { + int start = (styledText.getLine(0).length() + System.lineSeparator().length()) * 2; + setHigtLight(start, colWidths[0], SWT.COLOR_GRAY); + } + } + // let gc collect + obj = null; + } catch (OutOfMemoryError exception) { + handleUIstatusOnInitDataTextFail(); + onOutOfMemoryError(exception); + } + setSuccessWorkerFlag(true); + if (isInitDataTextFlag()) { + setInitDataTextFlag(false); + setScrollStatusOnInitOrLoad(false); + if (null != gridComponent && null != gridComponent.getToolbar()) { + gridComponent.getToolbar().updataButStatusOnInitDataText(); + } + } else { + if (isRefreshFlag()) { + setRefreshFlag(false); + } + if (isEncodingFlag()) { + setEndodingFlag(false); + } + if (null != gridComponent && null != gridComponent.getToolbar()) { + gridComponent.getToolbar().updataButStatusOnLoadDataText(true); + } + setScrollStatusOnInitOrLoad(false); + } + } + + @Override + public void finalCleanupUI() { + + } + + @Override + protected void canceling() { + super.canceling(); + if (!isSuccessWorkerFlag()) { + if (isInitDataTextFlag()) { + setUIstatusOnInitDataTextCancelOrException(); + } else { + if (null != gridComponent && null != gridComponent.getToolbar()) { + gridComponent.getToolbar().updataButStatusOnLoadDataText(true); + } + setScrollStatusOnInitOrLoad(false); + } + + } + } + } + + /** + * + * Title: class + * + * Description: The Class TerminalWorker. + */ + private abstract class TerminalWorker extends UIWorkerJob { + + /** + * Instantiates a new terminal worker. + * + * @param name the name + * @param family the family + */ + public TerminalWorker(String name, Object family) { + super(name, family); + + } + + @Override + public void onCriticalExceptionUIAction(DatabaseCriticalException exception) { + return; + } + + @Override + public void onOperationalExceptionUIAction(DatabaseOperationException exception) { + return; + } + + @Override + public void finalCleanup() throws MPPDBIDEException { + return; + } + + @Override + public void onOutOfMemoryError(OutOfMemoryError exception) { + MPPDBIDEDialogs.generateOKMessageDialogInUI(MESSAGEDIALOGTYPE.ERROR, true, getWindowImage(), + MessageConfigLoader.getProperty(IMessagesConstants.TITLE_OUT_OF_MEMORY), + MessageConfigLoader.getProperty(IMessagesConstants.ERR_OUT_OF_MEMORY_SEARCH_OCCURED)); + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_UI_SEARCH_ERROR), + exception); + } + + /** + * Gets the window image. + * + * @return the window image + */ + protected Image getWindowImage() { + return IconUtility.getIconImage(IiconPath.ICO_TOOL_32X32, this.getClass()); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DsGridRichTextPainter.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DsGridRichTextPainter.java new file mode 100644 index 0000000000000000000000000000000000000000..f81a0ce03da5ebb05aefbaf378041523e326b387 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/DsGridRichTextPainter.java @@ -0,0 +1,758 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Deque; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.Locale; +import java.util.Map; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLEventReader; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.events.Attribute; +import javax.xml.stream.events.Characters; +import javax.xml.stream.events.EntityReference; +import javax.xml.stream.events.StartElement; +import javax.xml.stream.events.XMLEvent; + +import org.eclipse.nebula.widgets.richtext.RichTextPainter; +import org.eclipse.nebula.widgets.richtext.painter.AlignmentStyle; +import org.eclipse.nebula.widgets.richtext.painter.DefaultEntityReplacer; +import org.eclipse.nebula.widgets.richtext.painter.EntityReplacer; +import org.eclipse.nebula.widgets.richtext.painter.LinePainter; +import org.eclipse.nebula.widgets.richtext.painter.ResourceHelper; +import org.eclipse.nebula.widgets.richtext.painter.SpanElement; +import org.eclipse.nebula.widgets.richtext.painter.SpanElement.SpanType; +import org.eclipse.nebula.widgets.richtext.painter.TagProcessingState; +import org.eclipse.nebula.widgets.richtext.painter.TagProcessingState.TextAlignment; +import org.eclipse.nebula.widgets.richtext.painter.instructions.BoldPaintInstruction; +import org.eclipse.nebula.widgets.richtext.painter.instructions.FontMetricsProvider; +import org.eclipse.nebula.widgets.richtext.painter.instructions.ItalicPaintInstruction; +import org.eclipse.nebula.widgets.richtext.painter.instructions.ListInstruction; +import org.eclipse.nebula.widgets.richtext.painter.instructions.NewLineInstruction; +import org.eclipse.nebula.widgets.richtext.painter.instructions.PaintInstruction; +import org.eclipse.nebula.widgets.richtext.painter.instructions.ParagraphInstruction; +import org.eclipse.nebula.widgets.richtext.painter.instructions.ResetFontPaintInstruction; +import org.eclipse.nebula.widgets.richtext.painter.instructions.ResetParagraphInstruction; +import org.eclipse.nebula.widgets.richtext.painter.instructions.ResetSpanStylePaintInstruction; +import org.eclipse.nebula.widgets.richtext.painter.instructions.SpanStylePaintInstruction; +import org.eclipse.nebula.widgets.richtext.painter.instructions.TextPaintInstruction; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.widgets.Display; + +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class DsGridRichTextPainter. + * + * @since 3.0.0 + */ +public class DsGridRichTextPainter extends RichTextPainter { + + /** + * The input factory. + */ + XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + { + // as there is no well-formed XML document, we have taken care of + // entity references here + inputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.FALSE); + } + + private boolean isWordWrap; + private final Point preferedSize = new Point(0, 0); + private EntityReplacer entityReplcer = new DefaultEntityReplacer(); + + /** + * Instantiates a new ds grid rich text painter. + * + * @param wordWrap the word wrap + */ + public DsGridRichTextPainter(boolean wordWrap) { + this.isWordWrap = wordWrap; + } + + /** + * Paint HTML. + * + * @param html the html + * @param gc the gc + * @param bounds the bounds + * @param render the render + */ + @Override + protected void paintHTML(String html, GC gc, Rectangle bounds, boolean render) { + + final TagProcessingState tagState = new TagProcessingState(); + tagState.setStartingPoint(bounds.x, bounds.y); + tagState.setRendering(render); + + Deque spanEleStack = new LinkedList<>(); + + ArrayList lines = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + + // we are ignoring contol character as we only care about html tags + String cleanHtml = html.replaceAll(CONTROL_CHARACTER_REGEX, ""); + + // we need to introduce a fake root tag, because otherwise we will get + // invalid XML exceptions + cleanHtml = FAKE_ROOT_TAG_START + cleanHtml + FAKE_ROOT_TAG_END; + + gc.setAntialias(SWT.DEFAULT); + gc.setTextAntialias(SWT.DEFAULT); + + XMLEventReader xmlParser = null; + + Deque listIndentation = new LinkedList(); + + GC tempGC = new GC(gc.getDevice()); + try { + xmlParser = inputFactory.createXMLEventReader(new StringReader(cleanHtml)); + getPainter(bounds, tagState, spanEleStack, lines, xmlParser, listIndentation, tempGC); + } catch (XMLStreamException exception) { + MPPDBIDELoggerUtility.error("DsGridRichTextPainter: XMLStreamException occurred.", exception); + } finally { + tempGC.dispose(); + if (xmlParser != null) { + try { + xmlParser.close(); + } catch (XMLStreamException exception) { + MPPDBIDELoggerUtility.error("DsGridRichTextPainter: XMLStreamException occurred.", exception); + } + } + } + + // initialize the state which is able to iterate over the line + // instructions + tagState.setLineIterator(lines.iterator()); + + preferedSize.x = 0; + preferedSize.y = 0; + + // perform the painting here + for (LinePainter linePainter : lines) { + linePainter.paint(gc, bounds); + + preferedSize.x = Math.max(preferedSize.x, linePainter.getContentWidth()); + preferedSize.y += linePainter.getLineHeight(); + } + // add paragraphSpace on top and bottom + preferedSize.y += 2 * tagState.getParagraphCount() * getParagraphSpace(); + + preferedSize.y = Math.max(preferedSize.y, bounds.height); + + } + + private void getPainter(Rectangle bounds, final TagProcessingState tagState, Deque spanEleStack, + ArrayList lines, XMLEventReader xmlParser, Deque listIndentation, GC tempGC) + throws XMLStreamException { + boolean isListOpened = false; + int availablWidth = bounds.width; + LinePainter currntLine = null; + while (xmlParser != null && xmlParser.hasNext()) { + XMLEvent event = xmlParser.nextEvent(); + currntLine = getPainter1(event, currntLine, tagState, lines, tempGC, availablWidth); + switch (event.getEventType()) { + case XMLStreamConstants.START_ELEMENT: { + final StartElement startElement = event.asStartElement(); + String elementStr = startElement.getName().toString(); + if (TAG_PARAGRAPH.equals(elementStr)) { + AlignmentStyle alignment = handleAlignmentConfiguration(startElement); + currntLine = getCurrentLineForTagParagraph(tagState, lines, tempGC, availablWidth, alignment); + availablWidth -= alignment.marginLeft; + } else if (TAG_UNORDERED_LIST.equals(elementStr) || TAG_ORDERED_LIST.equals(elementStr)) { + isListOpened = true; + int indentn = calculateListIndentation(tempGC); + availablWidth -= indentn; + listIndentation.add(indentn); + AlignmentStyle alignment = handleAlignmentConfiguration(startElement); + availablWidth -= alignment.marginLeft; + currntLine = getCurrentLineForTagList(tagState, spanEleStack, lines, tempGC, availablWidth, + startElement, elementStr, indentn, alignment); + } else if (TAG_LIST_ITEM.equals(elementStr)) { + // if a list was opened before, the list tag created a + // new line + // otherwise we create a new line for the new list item + if (!isListOpened) { + currntLine = getCurrentLineForTagItemIfListNotOpeaned(tagState, lines, tempGC, + availablWidth); + } else { + isListOpened = false; + } + currntLine = addInstructionForTagListItem(tagState, lines, tempGC, availablWidth, currntLine, + startElement); + } else { + currntLine = getCurrentElementForStartLine(tagState, spanEleStack, lines, tempGC, availablWidth, + currntLine, startElement, elementStr); + } + break; + } + case XMLStreamConstants.END_ELEMENT: { + if (event.asEndElement() != null) { + String endElementString = getEndEleString(event); + currntLine = getCurrentLineForEndElement1(tagState, spanEleStack, lines, tempGC, availablWidth, + currntLine, endElementString); + availablWidth = getAvailableWidthForEndElement(bounds, listIndentation, availablWidth, + endElementString); + } + break; + } + default: { + break; + } + } + } + } + + private String getEndEleString(XMLEvent event) { + QName name = event.asEndElement().getName(); + String endElementString = name != null ? name.toString() : ""; + return endElementString; + } + + private LinePainter addInstructionForTagListItem(final TagProcessingState tagState, ArrayList lines, + GC tempGC, int availablWidth, LinePainter currntLine, final StartElement startElement) { + final AlignmentStyle alignment = handleAlignmentConfiguration(startElement); + + // paint number/bullets + currntLine = addInstruction(tempGC, availablWidth, lines, currntLine, tagState, + getPaintInstructionForTagItem(tagState, alignment)); + return currntLine; + } + + private LinePainter getPainter1(XMLEvent event, LinePainter currntLine, TagProcessingState tagState, + ArrayList lines, GC tempGC, int availablWidth) { + switch (event.getEventType()) { + case XMLStreamConstants.END_DOCUMENT: { + break; + } + case XMLStreamConstants.CHARACTERS: { + currntLine = getCurrentLineForCharacters(tagState, lines, tempGC, availablWidth, currntLine, event); + break; + } + case XMLStreamConstants.ENTITY_REFERENCE: { + currntLine = getCurrentLIneForEntityReference(tagState, lines, tempGC, availablWidth, currntLine, + event); + break; + } + case XMLStreamConstants.ATTRIBUTE: { + break; + } + } + return currntLine; + } + + private LinePainter getCurrentLineForTagItemIfListNotOpeaned(final TagProcessingState tagState, + ArrayList lines, GC tempGC, int availablWidth) { + LinePainter currntLine; + currntLine = createNewLine(lines); + currntLine = addInstruction(tempGC, availablWidth, lines, currntLine, tagState, + new NewLineInstruction(tagState)); + return currntLine; + } + + private LinePainter getCurrentLineForTagParagraph(final TagProcessingState tagState, ArrayList lines, + GC tempGC, int availablWidth, AlignmentStyle alignment) { + LinePainter currntLine; + currntLine = createNewLine(lines); + currntLine = addInstruction(tempGC, availablWidth, lines, currntLine, tagState, + new ParagraphInstruction(alignment, getParagraphSpace(), tagState)); + return currntLine; + } + + private LinePainter getCurrentLineForEndElement1(final TagProcessingState tagState, Deque spanEleStack, + ArrayList lines, GC tempGC, int availablWidth, LinePainter currntLine, + String endElementString) { + if (TAG_PARAGRAPH.equals(endElementString)) { + currntLine = addInstruction(tempGC, availablWidth, lines, currntLine, tagState, + new ResetParagraphInstruction(getParagraphSpace(), tagState)); + + } else if (validateForTagList(endElementString)) { + currntLine = addInstruction(tempGC, availablWidth, lines, currntLine, tagState, + getPaintInstructionForTagList(tagState)); + + } else { + currntLine = getCurrentLineForEndElement(tagState, spanEleStack, lines, tempGC, availablWidth, currntLine, + endElementString); + } + return currntLine; + } + + private int getAvailableWidthForEndElement(Rectangle bounds, Deque listIndentation, int availablWidthParam, + String endElementString) { + int availablWidth = availablWidthParam; + if (TAG_PARAGRAPH.equals(endElementString)) { + availablWidth = bounds.width; + } else if (validateForTagList(endElementString)) { + if (!listIndentation.isEmpty()) { + availablWidth += listIndentation.removeLast(); + } + } + return availablWidth; + } + + private LinePainter getCurrentElementForStartLine(final TagProcessingState tagState, + Deque spanEleStack, ArrayList lines, GC tempGC, int availablWidth, + LinePainter currntLine, final StartElement startElement, String elementStr) { + if (TAG_BR.equals(elementStr)) { + currntLine = getCurrentLineForTagItemIfListNotOpeaned(tagState, lines, tempGC, availablWidth); + } else if (TAG_SPAN.equals(elementStr)) { + PaintInstruction styleInstruction = handleStyleConfiguration(startElement, spanEleStack, tagState); + currntLine = addInstruction(tempGC, availablWidth, lines, currntLine, tagState, styleInstruction); + } else if (TAG_STRONG.equals(elementStr)) { + currntLine = addInstruction(tempGC, availablWidth, lines, currntLine, tagState, + new BoldPaintInstruction(tagState)); + } else if (TAG_EM.equals(elementStr)) { + currntLine = addInstruction(tempGC, availablWidth, lines, currntLine, tagState, + new ItalicPaintInstruction(tagState)); + } else if (TAG_UNDERLINE.equals(elementStr)) { + currntLine = addInstruction(tempGC, availablWidth, lines, currntLine, tagState, new PaintInstruction() { + + @Override + public void paint(GC gc, Rectangle area) { + tagState.setUnderlineActive(true); + } + }); + } else if (TAG_STRIKETHROUGH.equals(elementStr)) { + currntLine = addInstruction(tempGC, availablWidth, lines, currntLine, tagState, + getPaintInstructionForTagStrikeThrough1(tagState)); + } + return currntLine; + } + + private LinePainter getCurrentLineForTagList(final TagProcessingState tagState, Deque spanEleStack, + ArrayList lines, GC tempGC, int availablWidth, final StartElement startElement, + String elementStr, int indentn, AlignmentStyle alignment) { + LinePainter currntLine; + boolean isOrderedList = TAG_ORDERED_LIST.equals(elementStr); + + currntLine = createNewLine(lines); + currntLine = addInstruction(tempGC, availablWidth, lines, currntLine, tagState, + new ListInstruction(indentn, isOrderedList, alignment, getParagraphSpace(), tagState)); + + // inspect font attributes here + PaintInstruction styleInstruction = handleStyleConfiguration(startElement, spanEleStack, tagState); + currntLine = addInstruction(tempGC, availablWidth, lines, currntLine, tagState, styleInstruction); + return currntLine; + } + + private PaintInstruction getPaintInstructionForTagItem(final TagProcessingState tagState, + final AlignmentStyle alignment) { + return new PaintInstruction() { + + @Override + public void paint(GC gc, Rectangle area) { + tagState.resetX(); + + String bullet = getBulletCharacter(tagState.getListDepth()) + "\u00a0"; + if (tagState.isOrderedList()) { + bullet = "" + tagState.getCurrentListNumber() + ". "; + } + int extend = gc.textExtent(bullet).x; + gc.drawText(bullet, tagState.getPointer().x - extend, tagState.getPointer().y, + tagState.hasPreviousBgColor()); + + tagState.setTextAlignment(alignment.alignment); + tagState.calculateX(area.width); + } + }; + } + + private LinePainter getCurrentLineForEndElement(final TagProcessingState tagState, Deque spanEleStack, + ArrayList lines, GC tempGC, int availablWidth, LinePainter currntLine, + String endElementString) { + if (TAG_SPAN.equals(endElementString)) { + SpanElement spanElement = spanEleStack.pollLast(); + currntLine = addInstruction(tempGC, availablWidth, lines, currntLine, tagState, + new ResetSpanStylePaintInstruction(tagState, spanElement)); + } else if (TAG_STRONG.equals(endElementString) || TAG_EM.equals(endElementString)) { + currntLine = addInstruction(tempGC, availablWidth, lines, currntLine, tagState, + new ResetFontPaintInstruction(tagState)); + } else if (TAG_UNDERLINE.equals(endElementString)) { + currntLine = addInstruction(tempGC, availablWidth, lines, currntLine, tagState, + getPaintInstructionForTagUnderline(tagState)); + } else if (TAG_STRIKETHROUGH.equals(endElementString)) { + currntLine = addInstruction(tempGC, availablWidth, lines, currntLine, tagState, + getPaintInstructionForTagStrikeThrough(tagState)); + } else if (TAG_LIST_ITEM.equals(endElementString)) { + currntLine = addInstruction(tempGC, availablWidth, lines, currntLine, tagState, + getPaintInstructionForTagItem(tagState)); + } + return currntLine; + } + + private PaintInstruction getPaintInstructionForTagUnderline(final TagProcessingState tagState) { + return new PaintInstruction() { + + @Override + public void paint(GC gc, Rectangle area) { + tagState.setUnderlineActive(false); + } + }; + } + + private PaintInstruction getPaintInstructionForTagStrikeThrough(final TagProcessingState tagState) { + return new PaintInstruction() { + + @Override + public void paint(GC gc, Rectangle area) { + tagState.setStrikethroughActive(false); + } + }; + } + + private PaintInstruction getPaintInstructionForTagStrikeThrough1(final TagProcessingState tagState) { + return new PaintInstruction() { + + @Override + public void paint(GC gc, Rectangle area) { + tagState.setStrikethroughActive(true); + } + }; + } + + private PaintInstruction getPaintInstructionForTagItem(final TagProcessingState tagState) { + return new PaintInstruction() { + + @Override + public void paint(GC gc, Rectangle area) { + tagState.increaseCurrentListNumber(); + tagState.setTextAlignment(TextAlignment.LEFT); + } + }; + } + + private boolean validateForTagList(String endElementString) { + return TAG_ORDERED_LIST.equals(endElementString) || TAG_UNORDERED_LIST.equals(endElementString); + } + + private PaintInstruction getPaintInstructionForTagList(final TagProcessingState tagState) { + return new PaintInstruction() { + + @Override + public void paint(GC gc, Rectangle area) { + tagState.resetListConfiguration(); + + // if the last list layer was + // finished, increase the line + // height like in paragraph + if (tagState.getListDepth() == 0) { + tagState.setMarginLeft(0); + tagState.increaseY(tagState.getCurrentLineHeight()); + tagState.increaseY(getParagraphSpace()); + } + + tagState.resetX(); + tagState.setTextAlignment(TextAlignment.LEFT); + } + }; + } + + private LinePainter getCurrentLineForCharacters(final TagProcessingState tagState, ArrayList lines, + GC tempGC, int availablWidth, LinePainter currntLine, XMLEvent event) { + Characters charactrs = event.asCharacters(); + String text = charactrs != null ? charactrs.getData() : ""; + if (text != null) { + currntLine = addInstruction(tempGC, availablWidth, lines, currntLine, tagState, + new TextPaintInstruction(tagState, text)); + } + return currntLine; + } + + private LinePainter getCurrentLIneForEntityReference(final TagProcessingState tagState, + ArrayList lines, GC tempGC, int availablWidth, LinePainter currntLine, XMLEvent event) { + String value = entityReplcer.getEntityReferenceValue((EntityReference) event); + currntLine = addInstruction(tempGC, availablWidth, lines, currntLine, tagState, + new TextPaintInstruction(tagState, value)); + return currntLine; + } + + private LinePainter addInstruction(GC gc, int availableWidth, Collection lines, + LinePainter currntLineParam, final TagProcessingState tagProgState, PaintInstruction instructionParam) { + LinePainter currntLine = currntLineParam; + PaintInstruction instruction = instructionParam; + if (instruction instanceof FontMetricsProvider) { + // applying the font to the temp GC + ((FontMetricsProvider) instruction).getFontMetrics(gc); + } + + // if currentLine is null at this point, there is no spanning p tag and + // we create a new line + // for convenience to support also simple text + currntLine = createNewLine(lines, currntLine, tagProgState); + + LinePainter lineToUse = currntLine; + TextPaintInstruction txtInstr = null; + if (instruction instanceof TextPaintInstruction) { + lineToUse = addTextPaintInstruction(gc, availableWidth, lines, tagProgState, currntLine, instruction, + lineToUse); + } else { + lineToUse.addInstruction(instruction); + } + + return lineToUse; + } + + private LinePainter addTextPaintInstruction(GC gc, int availableWidth, Collection lines, + final TagProcessingState tagProgState, LinePainter currntLine, PaintInstruction instructionParam, + LinePainter lineToUseParam) { + LinePainter lineToUse = lineToUseParam; + PaintInstruction instruction = instructionParam; + TextPaintInstruction txtInstr = (TextPaintInstruction) instruction; + int txtLength = txtInstr.getTextLength(gc); + int trimmedTxtLength = txtInstr.getTrimmedTextLength(gc); + + if ((currntLine.getContentWidth() + txtLength) > availableWidth) { + + if (this.isWordWrap) { + // if word wrapping is enabled, split the text and create + // new lines by making several + // TextPaintInstructions with substrings + + Deque wordsToProcess = new LinkedList<>(Arrays.asList(txtInstr.getText().split("\\s+"))); + String subStr = ""; + int subStrLength = 0; + while (!wordsToProcess.isEmpty()) { + String word = wordsToProcess.removeFirst(); + int wordLength = gc.textExtent(word).x; + subStrLength += wordLength; + if ((lineToUse.getContentWidth() + subStrLength) > availableWidth) { + boolean newLine = true; + if (!subStr.trim().isEmpty()) { + // right side trimmed + subStr = ResourceHelper.rtrim(subStr); + + txtInstr = new TextPaintInstruction(tagProgState, subStr); + txtLength = txtInstr.getTextLength(gc); + trimmedTxtLength = txtInstr.getTrimmedTextLength(gc); + + increaseWindth(lineToUse, txtInstr, txtLength, trimmedTxtLength); + + subStr = word; + subStrLength = wordLength; + } else if (lineToUse.getContentWidth() == 0) { + // no content already but text width greater + // than available width + // 0.2 - modifed text to show ... + // 0.2 - add trim to avoid empty lines + // because of spaces + subStr = word; + subStrLength = wordLength; + newLine = false; + } + + lineToUse = addOnNewLine(lines, tagProgState, lineToUse, newLine); + } else { + subStr += word; + } + } + + if (!subStr.trim().isEmpty()) { + txtInstr = new TextPaintInstruction(tagProgState, subStr); + txtLength = txtInstr.getTextLength(gc); + trimmedTxtLength = txtInstr.getTrimmedTextLength(gc); + instruction = txtInstr; + } + } + + } + + increateContentWidth(instruction, lineToUse, txtLength, trimmedTxtLength); + return lineToUse; + } + + private void increateContentWidth(PaintInstruction instruction, LinePainter lineToUse, int txtLength, + int trimmedTxtLength) { + lineToUse.addInstruction(instruction); + lineToUse.increaseContentWidth(txtLength); + lineToUse.increaseTrimmedContentWidth(trimmedTxtLength); + } + + private void increaseWindth(LinePainter lineToUse, TextPaintInstruction txtInstr, int txtLength, + int trimmedTxtLength) { + lineToUse.addInstruction(txtInstr); + + lineToUse.increaseContentWidth(txtLength); + lineToUse.increaseTrimmedContentWidth(trimmedTxtLength); + } + + private LinePainter addOnNewLine(Collection lines, final TagProcessingState tagProgState, + LinePainter lineToUseParam, boolean newLine) { + LinePainter lineToUse = lineToUseParam; + if (newLine) { + lineToUse = createNewLine(lines); + lineToUse.addInstruction(new NewLineInstruction(tagProgState)); + } + return lineToUse; + } + + private LinePainter createNewLine(Collection lines, LinePainter currntLineParam, + final TagProcessingState tagProgState) { + LinePainter currntLine = currntLineParam; + if (currntLine == null) { + currntLine = createNewLine(lines); + currntLine.addInstruction(new PaintInstruction() { + @Override + public void paint(GC gc, Rectangle area) { + tagProgState.activateNextLine(); + tagProgState.increaseY(getParagraphSpace()); + tagProgState.increaseParagraphCount(); + } + }); + } + return currntLine; + } + + private LinePainter createNewLine(Collection lines) { + LinePainter currntLine = new LinePainter(); + lines.add(currntLine); + return currntLine; + } + + private AlignmentStyle handleAlignmentConfiguration(StartElement element) { + AlignmentStyle resultStyle = new AlignmentStyle(); + for (Iterator attributes = element.getAttributes(); attributes.hasNext();) { + Attribute attribute = (Attribute) attributes.next(); + if (attribute != null && ATTRIBUTE_STYLE.equals(attribute.getName().toString())) { + Map styleProperties = getStyleProperties(attribute.getValue()); + for (Map.Entry entry : styleProperties.entrySet()) { + if (ATTRIBUTE_PARAGRAPH_MARGIN_LEFT.equals(entry.getKey())) { + String pixlValue = entry.getValue().replace("px", ""); + try { + int pixel = Integer.parseInt(pixlValue.trim()); + resultStyle.marginLeft = pixel; + } catch (NumberFormatException exception) { + MPPDBIDELoggerUtility.error("Failed to parser integer", exception); + // if the value is not a valid number value + // we simply ignore it + } + } else if (ATTRIBUTE_PARAGRAPH_TEXT_ALIGN.equals(entry.getKey())) { + try { + TextAlignment alignment = TextAlignment + .valueOf(entry.getValue().toUpperCase(Locale.ENGLISH)); + resultStyle.alignment = alignment; + } catch (IllegalArgumentException exception) { + MPPDBIDELoggerUtility.error("Failed to align text in paragraph", exception); + // if the value is not a valid txt-aligment + // we simply ignore it + } + } + } + } + } + return resultStyle; + } + + private PaintInstruction handleStyleConfiguration(StartElement element, Deque spanStack, + TagProcessingState state) { + // creating the span element with reset info on tag close + SpanElement spanElemt = new SpanElement(); + // creating span style paint instruction that should be performed on + // painting + SpanStylePaintInstruction styleInstruction = new SpanStylePaintInstruction(state); + + // inspect the attributes here + for (Iterator attributes = element.getAttributes(); attributes.hasNext();) { + Attribute attribt = (Attribute) attributes.next(); + if (attribt != null && ATTRIBUTE_STYLE.equals(attribt.getName().toString())) { + Map styleProperties = getStyleProperties(attribt.getValue()); + for (Map.Entry entry : styleProperties.entrySet()) { + if (ATTRIBUTE_STYLE_COLOR.equals(entry.getKey())) { + // update span element to know what to reset on tag + // close + spanElemt.types.add(SpanType.COLOR); + // update the style paint instruction here + styleInstruction.setForegroundColor(ResourceHelper.getColor(entry.getValue())); + } else if (ATTRIBUTE_STYLE_BACKGROUND_COLOR.equals(entry.getKey())) { + // update span element to know what to reset on tag + // close + spanElemt.types.add(SpanType.BG_COLOR); + // update the style paint instruction + styleInstruction.setBackgroundColor(ResourceHelper.getColor(entry.getValue())); + } else if (ATTRIBUTE_STYLE_FONT_SIZE.equals(entry.getKey())) { + // update span element to know what to reset on tag + // close + spanElemt.types.add(SpanType.FONT); + // update the style paint instruction + String pixlValue = entry.getValue().replace("px", ""); + try { + int pixel = Integer.parseInt(pixlValue.trim()); + // size in pixels specified in HTML + // so we have to convert it to point + int xCoordinate = Display.getDefault().getDPI().x; + if (xCoordinate != 0) { + int pointSize = 72 * pixel / xCoordinate; + styleInstruction.setFontSize(pointSize); + } + } catch (NumberFormatException exception) { + MPPDBIDELoggerUtility.error("Error while parsing invalid number string", exception); + // ignore error. + } + } else if (ATTRIBUTE_STYLE_FONT_FAMILY.equals(entry.getKey())) { + // update span element to know what to reset on tag + // close + spanElemt.types.add(SpanType.FONT); + // update style paint instruction + styleInstruction.setFontType(entry.getValue().split(",")[0]); + } + } + } + } + + spanStack.add(spanElemt); + return styleInstruction; + } + + private Map getStyleProperties(String styleString) { + Map resultMap = new HashMap<>(); + + String[] configs = styleString.split(";"); + for (String config : configs) { + String[] keyValuePair = config.split(":"); + if (keyValuePair.length > 1) { + resultMap.put(keyValuePair[0].trim(), keyValuePair[1].trim()); + } + } + + return resultMap; + } + + /** + * Gets the preferred size. + * + * @return the preferred size + */ + public Point getPreferredSize() { + return preferedSize; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/ExecutionPlanNodeTypeConfiguration.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/ExecutionPlanNodeTypeConfiguration.java new file mode 100644 index 0000000000000000000000000000000000000000..9bf088f62c8c244845db55eefb301c54341fab29 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/ExecutionPlanNodeTypeConfiguration.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import org.eclipse.nebula.widgets.nattable.config.AbstractRegistryConfiguration; +import org.eclipse.nebula.widgets.nattable.config.CellConfigAttributes; +import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry; +import org.eclipse.nebula.widgets.nattable.painter.cell.BackgroundPainter; +import org.eclipse.nebula.widgets.nattable.painter.cell.ICellPainter; +import org.eclipse.nebula.widgets.nattable.style.CellStyleAttributes; +import org.eclipse.nebula.widgets.nattable.style.DisplayMode; +import org.eclipse.nebula.widgets.nattable.style.IStyle; +import org.eclipse.nebula.widgets.nattable.style.Style; +import org.eclipse.nebula.widgets.nattable.tree.TreeLayer; +import org.eclipse.swt.graphics.Color; + +import org.opengauss.mppdbide.explainplan.ui.model.TreeGridColumnHeader; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; + +/** + * + * Title: class + * + * Description: The Class ExecutionPlanNodeTypeConfiguration. + * + * @since 3.0.0 + */ +public class ExecutionPlanNodeTypeConfiguration extends AbstractRegistryConfiguration { + private IDSGridDataProvider dataProvider; + private ICellPainter cellPaintr; + + /** + * Pre destroy. + */ + public void preDestroy() { + this.dataProvider = null; + this.cellPaintr = null; + } + + /** + * Configure registry. + * + * @param configRegistry the config registry + */ + @Override + public void configureRegistry(IConfigRegistry configRegistry) { + if (null == getDataProvider()) { + return; + } + + configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, + new BackgroundPainter(this.cellPaintr), DisplayMode.NORMAL, TreeLayer.TREE_COLUMN_CELL); + + IStyle costlyCellStyle = new Style(); + costlyCellStyle.setAttributeValue(CellStyleAttributes.BACKGROUND_COLOR, new Color(null, 255, 200, 100)); + configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, costlyCellStyle, DisplayMode.NORMAL, + TreeGridColumnHeader.COLUMN_LABEL_HEAVIEST); + configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, costlyCellStyle, DisplayMode.NORMAL, + TreeGridColumnHeader.COLUMN_LABEL_SLOWEST); + configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, costlyCellStyle, DisplayMode.NORMAL, + TreeGridColumnHeader.COLUMN_LABEL_COSTLIEST); + } + + /** + * Instantiates a new execution plan node type configuration. + * + * @param dataProvider the data provider + */ + public ExecutionPlanNodeTypeConfiguration(IDSGridDataProvider dataProvider) { + this.dataProvider = dataProvider; + this.cellPaintr = new ExplainPlanTreeTablePainterWrapper(); + } + + /** + * Gets the data provider. + * + * @return the data provider + */ + public IDSGridDataProvider getDataProvider() { + return dataProvider; + } + + /** + * Sets the data provider. + * + * @param dataProvider the new data provider + */ + public void setDataProvider(IDSGridDataProvider dataProvider) { + this.dataProvider = dataProvider; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/ExplainPlanTreeTablePainterWrapper.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/ExplainPlanTreeTablePainterWrapper.java new file mode 100644 index 0000000000000000000000000000000000000000..487c2b033b7786608c66825db5f070028781d99c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/ExplainPlanTreeTablePainterWrapper.java @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry; +import org.eclipse.nebula.widgets.nattable.extension.nebula.richtext.RichTextCellPainter; +import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell; +import org.eclipse.nebula.widgets.nattable.painter.cell.ImagePainter; +import org.eclipse.nebula.widgets.nattable.painter.cell.TextPainter; +import org.eclipse.nebula.widgets.nattable.painter.cell.decorator.BeveledBorderDecorator; +import org.eclipse.nebula.widgets.nattable.painter.cell.decorator.CellPainterDecorator; +import org.eclipse.nebula.widgets.nattable.ui.util.CellEdgeEnum; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Rectangle; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; + +/** + * + * Title: class + * + * Description: The Class ExplainPlanTreeTablePainterWrapper. + * + * @since 3.0.0 + */ +public class ExplainPlanTreeTablePainterWrapper extends CellPainterDecorator { + private CellPainterDecorator planNodePainter; + + private String getImagePath(String nodeCategory) { + String iconPath = null; + if (nodeCategory == null) { + iconPath = IconUtility.ICON_EXPLAIN_PLAN_NODE_UNKNOWN; // unknown + return iconPath; + } + + iconPath = getImagePathInitial(nodeCategory); + + if (null == iconPath) { + iconPath = getImagePathSec(nodeCategory); + } + + if (null == iconPath) { + iconPath = getImagePathThi(nodeCategory); + } + + return iconPath; + } + + private String getImagePathThi(String nodeCategory) { + String iconPath; + if (nodeCategory.contains(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_SETOP))) { + iconPath = IconUtility.ICON_EXPLAIN_PLAN_NODE_SETOP; + } else if (nodeCategory + .contains(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_SORT))) { + iconPath = IconUtility.ICON_EXPLAIN_PLAN_NODE_SORT; + } else if (nodeCategory + .contains(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_STREAM))) { + iconPath = IconUtility.ICON_EXPLAIN_PLAN_NODE_STREAM; + } else if (nodeCategory + .contains(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_UNION))) { + iconPath = IconUtility.ICON_EXPLAIN_PLAN_NODE_UNION; + } else { + iconPath = IconUtility.ICON_EXPLAIN_PLAN_NODE_UNKNOWN; // unknown + } + return iconPath; + } + + private String getImagePathSec(String nodeCategory) { + String iconPath = null; + if (nodeCategory + .contains(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_MODIFYTABLE))) { + iconPath = IconUtility.ICON_EXPLAIN_PLAN_NODE_MODIFYTABLE; + } else if (nodeCategory + .contains(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_NESTLOOPJOIN))) { + iconPath = IconUtility.ICON_EXPLAIN_PLAN_NODE_NESTEDLOOPJOIN; + } else if (nodeCategory + .contains(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_NESTEDLOOP))) { + iconPath = IconUtility.ICON_EXPLAIN_PLAN_NODE_NESTEDLOOP; + } else if (nodeCategory.contains( + MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_PARTITIONITERATOR))) { + iconPath = IconUtility.ICON_EXPLAIN_PLAN_NODE_PARTITIONITERATOR; + } else if (nodeCategory + .contains(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_ROWADAPTER))) { + iconPath = IconUtility.ICON_EXPLAIN_PLAN_NODE_ROWADAPTOR; + } else if (nodeCategory + .contains(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_SCAN))) { + iconPath = IconUtility.ICON_EXPLAIN_PLAN_NODE_SCAN; + } + + return iconPath; + } + + private String getImagePathInitial(String nodeCategory) { + String iconPath = null; + if (nodeCategory + .contains(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_AGGREGATE))) { + iconPath = IconUtility.ICON_EXPLAIN_PLAN_NODE_AGGREGATE; + } else if (nodeCategory + .contains(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_FUNCTION))) { + iconPath = IconUtility.ICON_EXPLAIN_PLAN_NODE_FUNCTION; + } else if (nodeCategory + .contains(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_GROUPAGGREGATE))) { + iconPath = IconUtility.ICON_EXPLAIN_PLAN_NODE_AGGREGATEGRP; + } else if (nodeCategory + .equals(MessageConfigLoader.getProperty(IMessagesConstants.VIS_EXPLAIN_NODCATEGORY_HASH))) { + iconPath = IconUtility.ICON_EXPLAIN_PLAN_NODE_HASH; + } else if (nodeCategory.startsWith("Hash") && nodeCategory.endsWith("Join")) { + iconPath = IconUtility.ICON_EXPLAIN_PLAN_NODE_HASHJOIN; + } + + return iconPath; + } + + /** + * Instantiates a new explain plan tree table painter wrapper. + */ + public ExplainPlanTreeTablePainterWrapper() { + super(new BeveledBorderDecorator(new TextPainter()), CellEdgeEnum.RIGHT, 100, null, false, true); + } + + /** + * Paint cell. + * + * @param cell the cell + * @param gc the gc + * @param adjustedCellBounds the adjusted cell bounds + * @param configRegistry the config registry + */ + @Override + public void paintCell(ILayerCell cell, GC gc, Rectangle adjustedCellBounds, IConfigRegistry configRegistry) { + String value = cell.getDataValue().toString(); + ImagePainter imagepainter = new ImagePainter(IconUtility.getIconImage(getImagePath(value), getClass()), false); + + this.planNodePainter = new CellPainterDecorator(new RichTextCellPainter(), CellEdgeEnum.LEFT, imagepainter); + this.planNodePainter.paintCell(cell, gc, adjustedCellBounds, configRegistry); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridColHeaderDataProvider.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridColHeaderDataProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..b6e0dfd6e53de3a6710d9ecd79bbffe4b37458de --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridColHeaderDataProvider.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import org.eclipse.nebula.widgets.nattable.data.IDataProvider; + +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; + +/** + * + * Title: class + * + * Description: The Class GridColHeaderDataProvider. + * + * @since 3.0.0 + */ +public class GridColHeaderDataProvider implements IDataProvider { + private IDSGridDataProvider dataProvider; + + /** + * Instantiates a new grid col header data provider. + * + * @param dataProvider the data provider + */ + public GridColHeaderDataProvider(IDSGridDataProvider dataProvider) { + this.dataProvider = dataProvider; + } + + /** + * Gets the data value. + * + * @param columnIndex the column index + * @param rowIndex the row index + * @return the data value + */ + @Override + public Object getDataValue(int columnIndex, int rowIndex) { + return this.dataProvider.getColumnDataProvider().getColumnName(columnIndex); + } + + /** + * Sets the data value. + * + * @param columnIndex the column index + * @param rowIndex the row index + * @param newValue the new value + */ + @Override + public void setDataValue(int columnIndex, int rowIndex, Object newValue) { + // Ignore. Column Name set would not be supported + } + + /** + * Gets the column count. + * + * @return the column count + */ + @Override + public int getColumnCount() { + return this.dataProvider.getColumnDataProvider().getColumnCount(); + } + + /** + * Gets the row count. + * + * @return the row count + */ + @Override + public int getRowCount() { + // Assumption: only 1 record for table header as we donot support merged + // column header feature now. + return 1; + } + + /** + * On pre destroy. + */ + public void onPreDestroy() { + this.dataProvider = null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridColumnHeaderAccumulator.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridColumnHeaderAccumulator.java new file mode 100644 index 0000000000000000000000000000000000000000..0796546f26828c53768d9169e844c0007cf3a635 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridColumnHeaderAccumulator.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import org.eclipse.nebula.widgets.nattable.layer.LabelStack; +import org.eclipse.nebula.widgets.nattable.layer.cell.ColumnLabelAccumulator; + +import org.opengauss.mppdbide.presentation.grid.IDSEditGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.objectproperties.DSObjectPropertiesGridDataProvider; +import org.opengauss.mppdbide.view.component.grid.GridUIUtils; +import org.opengauss.mppdbide.view.component.grid.IDataGridContext; +import org.opengauss.mppdbide.view.component.grid.IEditTableGridStyleLabelFactory; + +/** + * + * Title: class + * + * Description: The Class GridColumnHeaderAccumulator. + * + * @since 3.0.0 + */ +public class GridColumnHeaderAccumulator extends ColumnLabelAccumulator { + private IDataGridContext dataGridContext; + + /** + * Instantiates a new grid column header accumulator. + * + * @param dataGridContext the data grid context + */ + public GridColumnHeaderAccumulator(IDataGridContext dataGridContext) { + this.dataGridContext = dataGridContext; + } + + /** + * Accumulate config labels. + * + * @param configLabels the config labels + * @param columnPosition the column position + * @param rowPosition the row position + */ + @Override + public void accumulateConfigLabels(LabelStack configLabels, int columnPosition, int rowPosition) { + super.accumulateConfigLabels(configLabels, columnPosition, rowPosition); + + handleColumnHeaderLabels(configLabels, columnPosition); + } + + /** + * Handle column header labels. + * + * @param configLabels the config labels + * @param columnPosition the column position + */ + protected void handleColumnHeaderLabels(LabelStack configLabels, int columnPosition) { + IDSGridDataProvider dataProvider = this.dataGridContext.getDataProvider(); + if (dataProvider instanceof IDSEditGridDataProvider) { + IDSEditGridDataProvider editDP = (IDSEditGridDataProvider) dataProvider; + String columnDTName = editDP.getColumnDataProvider().getColumnDataTypeName(columnPosition); + int precisionVal = editDP.getColumnDataProvider().getPrecision(columnPosition); + if (dataProvider instanceof DSObjectPropertiesGridDataProvider) { + return; + } + + if (!GridUIUtils.isDatatypeEditSupported(columnDTName, precisionVal) + || editDP.isDistributionColumn(columnPosition)) { + configLabels.addLabel(IEditTableGridStyleLabelFactory.COL_HEADER_LABEL_READONLY_CELL); + } + handleHeadersForProperties(dataProvider, columnPosition, configLabels); + + } + } + + private void handleHeadersForProperties(IDSGridDataProvider dataProvider, int columnPosition, + LabelStack configLabels) { + if (dataProvider instanceof DSObjectPropertiesGridDataProvider) { + String objectPropertyName = ((DSObjectPropertiesGridDataProvider) dataProvider).getObjectPropertyName(); + IDSGridColumnProvider columnDataProvider = dataProvider.getColumnDataProvider(); + if (null != columnDataProvider) { + + String columnName = columnDataProvider.getColumnName(columnPosition); + if (columnName != null + && GridUIUtils.isEditablePropertiesAttributes(objectPropertyName, columnName, null)) { + configLabels.addLabel(IEditTableGridStyleLabelFactory.COL_HEADER_LABEL_READONLY_CELL); + } + } else { + return; + } + } + } + + /** + * the onPreDestroy + */ + public void onPreDestroy() { + dataGridContext = null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridColumnLabelAccumulator.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridColumnLabelAccumulator.java new file mode 100644 index 0000000000000000000000000000000000000000..42ac4c77988e02b892071153747b478e6ce92c50 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridColumnLabelAccumulator.java @@ -0,0 +1,391 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import java.util.List; + +import org.eclipse.nebula.widgets.nattable.data.IDataProvider; +import org.eclipse.nebula.widgets.nattable.data.ListDataProvider; +import org.eclipse.nebula.widgets.nattable.layer.DataLayer; +import org.eclipse.nebula.widgets.nattable.layer.LabelStack; +import org.eclipse.nebula.widgets.nattable.layer.cell.ColumnOverrideLabelAccumulator; +import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell; + +import org.opengauss.mppdbide.presentation.edittabledata.DSResultSetGridDataProvider; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableCellState; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableRecordExecutionStatus; +import org.opengauss.mppdbide.presentation.edittabledata.IDSGridEditDataRow; +import org.opengauss.mppdbide.presentation.grid.IDSEditGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.batchdrop.BatchDropDataProvider; +import org.opengauss.mppdbide.presentation.objectproperties.DSObjectPropertiesGridDataProvider; +import org.opengauss.mppdbide.presentation.objectproperties.PropertiesConstants; +import org.opengauss.mppdbide.presentation.objectproperties.PropertiesUserRoleImpl; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.view.component.grid.EditTableGridStyleConfiguration; +import org.opengauss.mppdbide.view.component.grid.GridUIUtils; +import org.opengauss.mppdbide.view.component.grid.IEditTableGridStyleLabelFactory; + +/** + * + * Title: class + * + * Description: The Class GridColumnLabelAccumulator. + * + * @since 3.0.0 + */ +public class GridColumnLabelAccumulator extends ColumnOverrideLabelAccumulator { + private DataLayer gridBodyDataLayer; + private IDSGridDataProvider dataProvider; + + /** + * Instantiates a new grid column label accumulator. + * + * @param layer the layer + * @param dataProvider the data provider + */ + public GridColumnLabelAccumulator(DataLayer layer, IDSGridDataProvider dataProvider) { + super(layer); + this.gridBodyDataLayer = layer; + this.dataProvider = dataProvider; + } + + /** + * Accumulate config labels. + * + * @param configLabels the config labels + * @param columnPosition the column position + * @param rowPosition the row position + */ + @Override + public void accumulateConfigLabels(LabelStack configLabels, int columnPosition, int rowPosition) { + super.accumulateConfigLabels(configLabels, columnPosition, rowPosition); + + try { + if ((dataProvider instanceof DSResultSetGridDataProvider + && !((DSResultSetGridDataProvider) dataProvider).isEditSupported()) + || (dataProvider instanceof BatchDropDataProvider + && !((BatchDropDataProvider) dataProvider).isEditSupported())) { + configLabels.addLabel(IEditTableGridStyleLabelFactory.COL_LABEL_READONLY_CELL); + } + + accumulateEditConfigLabels(configLabels, columnPosition, rowPosition); + + // user role management + if (dataProvider instanceof DSObjectPropertiesGridDataProvider) { + accumulatePropertiesConfigLabels(configLabels, columnPosition, rowPosition); + } + } catch (MPPDBIDEException exception) { + MPPDBIDELoggerUtility.error("Error while accumulating config labels for columns", exception); + } + } + + /** + * Accumulate properties config labels. + * + * @param configLabels the config labels + * @param columnPosition the column position + * @param rowPosition the row position + */ + private void accumulatePropertiesConfigLabels(LabelStack configLabels, int columnPosition, int rowPosition) { + DSObjectPropertiesGridDataProvider objectPropertiesGridDataProvider = (DSObjectPropertiesGridDataProvider) dataProvider; + if (objectPropertiesGridDataProvider.getObjectPropertyObject() instanceof PropertiesUserRoleImpl) { + String objectPropertyName = objectPropertiesGridDataProvider.getObjectPropertyName(); + if (PropertiesConstants.USER_ROLE_PROPERTY_TAB_GENERAL.equals(objectPropertyName)) { + if (columnPosition == 1) { + switch (rowPosition) { + case 3: + case 4: { + configLabels.addLabel(IEditTableGridStyleLabelFactory.DATE_DATA_TYPE); + break; + } + case 5: { + configLabels.addLabel(IEditTableGridStyleLabelFactory.DROP_DOWN_LIST_DATA_TYPE); + break; + } + default: { + break; + } + } + } + } + + if (PropertiesConstants.USER_ROLE_PROPERTY_TAB_PRIVILEGE.equals(objectPropertyName)) { + if (columnPosition == 1) { + configLabels.addLabel(IEditTableGridStyleLabelFactory.COL_LABEL_BOOLEAN_DATATYPE); + } + } + + if (PropertiesConstants.USER_ROLE_PROPERTY_TAB_MEMBERSHIP.equals(objectPropertyName)) { + if (columnPosition == 1) { + configLabels.addLabel(IEditTableGridStyleLabelFactory.COMBO_BOX_DATA_TYPE); + } + } + } + + String name = objectPropertiesGridDataProvider.getObjectPropertyName(); + if ("General".equals(name)) { + if (columnPosition == 1) { + if (rowPosition == 11) { + configLabels.addLabel(EditTableGridStyleConfiguration.COL_LABEL_BOOLEAN_DATATYPE); + } + } + } + + } + + /** + * Adds the non editable label on cells. + * + * @param configLabels the config labels + * @param columnPosition the column position + * @param rowPosition the row position + * @throws MPPDBIDEException the MPPDBIDE exception + */ + protected void addNonEditableLabelOnCells(LabelStack configLabels, int columnPosition, int rowPosition) + throws MPPDBIDEException { + if (this.dataProvider instanceof IDSEditGridDataProvider) { + IDSEditGridDataProvider editDataProvider = (IDSEditGridDataProvider) this.dataProvider; + /* + * below if check is handled for properties window + */ + if (this.dataProvider instanceof DSResultSetGridDataProvider + && ((DSResultSetGridDataProvider) dataProvider).isIncludeEncoding() + && ((DSResultSetGridDataProvider) dataProvider).isEncodingChanged()) { + configLabels.addLabel(IEditTableGridStyleLabelFactory.COL_LABEL_READONLY_CELL); + } + if (this.dataProvider instanceof DSObjectPropertiesGridDataProvider) { + verifyReadOnlyCellForPropeties(configLabels, columnPosition, rowPosition); + } else if (isMultiEditSupported(columnPosition, rowPosition)) { + configLabels.addLabel(IEditTableGridStyleLabelFactory.COL_LABEL_NOT_SUPPORTED_MULTIDIALOG); + } else { + if (isDistributedColumn(columnPosition) + || !checkIfDatatypeSupported(columnPosition, editDataProvider)) { + configLabels.addLabel(IEditTableGridStyleLabelFactory.COL_LABEL_READONLY_CELL); + } + } + } + + } + + // To check if multiEdit is supported + private boolean isMultiEditSupported(int columnPosition, int rowPosition) { + ILayerCell cellByPosition = gridBodyDataLayer.getCellByPosition(columnPosition, rowPosition); + Object dataValue = cellByPosition != null ? cellByPosition.getDataValue() : null; + return dataValue != null && dataValue instanceof String + && ((String) dataValue).length() > IEditTableGridStyleLabelFactory.CANONICAL_LIMIT; + } + + /** + * Adds the non editable label on cells for insert. + * + * @param configLabels the config labels + * @param columnPosition the column position + * @param rowPosition the row position + * @throws MPPDBIDEException the MPPDBIDE exception + */ + protected void addNonEditableLabelOnCellsForInsert(LabelStack configLabels, int columnPosition, int rowPosition) + throws MPPDBIDEException { + if (this.dataProvider instanceof IDSEditGridDataProvider) { + IDSEditGridDataProvider editDataProvider = (IDSEditGridDataProvider) this.dataProvider; + if (this.dataProvider instanceof DSObjectPropertiesGridDataProvider) { + verifyReadOnlyCellForPropeties(configLabels, columnPosition, rowPosition); + } else { + if (!checkIfDatatypeSupported(columnPosition, editDataProvider)) { + configLabels.addLabel(IEditTableGridStyleLabelFactory.COL_LABEL_READONLY_CELL); + } + } + } + + } + + private boolean checkIfDatatypeSupported(int colPosition, IDSEditGridDataProvider editDataProvider) { + String columnDataTypeName = editDataProvider.getColumnDataProvider().getColumnDataTypeName(colPosition); + int colPrecisionValue = editDataProvider.getColumnDataProvider().getPrecision(colPosition); + return GridUIUtils.isDatatypeEditSupported(columnDataTypeName, colPrecisionValue); + } + + /* + * The code for adding readonly label for table properties cells + */ + private void verifyReadOnlyCellForPropeties(LabelStack configLabels, int columnPosition, int rowPosition) { + String columnName = dataProvider.getColumnDataProvider().getColumnName(columnPosition); + if (null != columnName) { + + if (!((IDSEditGridDataProvider) dataProvider).isEditSupported()) { + configLabels.addLabel(IEditTableGridStyleLabelFactory.COL_LABEL_READONLY_CELL); + return; + } + // dataValue is used to make only description value editable in + // general tab + Object dataValue = this.gridBodyDataLayer.getDataValue(0, rowPosition); + String propName = ((DSObjectPropertiesGridDataProvider) dataProvider).getObjectPropertyName(); + + if (dataValue != null + && !GridUIUtils.isEditablePropertiesAttributes(propName, columnName, dataValue.toString())) { + configLabels.addLabel(IEditTableGridStyleLabelFactory.COL_LABEL_READONLY_CELL); + } + } + } + + /** + * Accumulate edit config labels. + * + * @param configLabels the config labels + * @param columnPosition the column position + * @param rowPosition the row position + * @throws MPPDBIDEException the MPPDBIDE exception + */ + protected void accumulateEditConfigLabels(LabelStack configLabels, int columnPosition, int rowPosition) + throws MPPDBIDEException { + IDataProvider gridBodyDataProvider = this.gridBodyDataLayer.getDataProvider(); + if (gridBodyDataProvider.getDataValue(columnPosition, rowPosition) == null) { + configLabels.addLabel(IEditTableGridStyleLabelFactory.COL_LABEL_NULL_VALUES); + } + + if (columnPosition > 0 && gridBodyDataProvider.getDataValue(columnPosition - 1, rowPosition) != null) { + if (gridBodyDataProvider.getDataValue(columnPosition - 1, rowPosition).equals(MPPDBIDEConstants.OUT)) { + configLabels.addLabel(IEditTableGridStyleLabelFactory.COL_LABEL_OUT_PARA_TYPE_CELL); + } + } + + IDSGridEditDataRow editRow = getEditedRow(gridBodyDataProvider, rowPosition); + + if (editRow != null) { + switch (editRow.getUpdatedState(columnPosition)) { + case INSERT: { + configLabels.addLabel(editRow.getExecutionStatus() == EditTableRecordExecutionStatus.FAILED + ? IEditTableGridStyleLabelFactory.COL_LABEL_CHANGE_FAILED + : IEditTableGridStyleLabelFactory.COL_LABEL_INSERT); + addNonEditableLabelOnCellsForInsert(configLabels, columnPosition, rowPosition); + + break; + } + case DELETE: { + configLabels.addLabel(editRow.getExecutionStatus() == EditTableRecordExecutionStatus.FAILED + ? IEditTableGridStyleLabelFactory.COL_LABEL_CHANGE_FAILED + : IEditTableGridStyleLabelFactory.COL_LABEL_DELETE); + configLabels.addLabel(IEditTableGridStyleLabelFactory.COL_LABEL_READONLY_CELL); + break; + } + case UPDATE: { + addLabelForUpdatedCell(configLabels, columnPosition, editRow); + + break; + } + default: { + addNonEditableLabelOnCells(configLabels, columnPosition, rowPosition); + break; + } + } + } + } + + private void addLabelForUpdatedCell(LabelStack configLabels, int columnPosition, IDSGridEditDataRow editRow) { + switch (editRow.getExecutionStatus()) { + case NOT_EXECUTED: { + configLabels.addLabel(IEditTableGridStyleLabelFactory.COL_LABEL_UPDATE); + break; + } + case FAILED: { + configLabels.addLabel(IEditTableGridStyleLabelFactory.COL_LABEL_CHANGE_FAILED); + break; + } + case SUCCESS: { + break; + } + case FAILED_AND_MODIFIED: { + modifyDataForFailedAndModified(configLabels, columnPosition, editRow); + break; + } + + default: { + break; + } + } + } + + private void modifyDataForFailedAndModified(LabelStack configLabels, int columnPosition, + IDSGridEditDataRow editRow) { + EditTableCellState cellStatus = editRow.getCellStatus(columnPosition); + if (cellStatus == null) { + return; + } + modifiedDataStatus(configLabels, cellStatus); + } + + private void modifiedDataStatus(LabelStack configLabels, EditTableCellState cellStatus) { + switch (cellStatus) { + case MODIFIED: { + configLabels.addLabel(IEditTableGridStyleLabelFactory.COL_LABEL_FAILED_AND_MODIFIED); + break; + } + case MODIFIED_FAILED: { + configLabels.addLabel(IEditTableGridStyleLabelFactory.COL_LABEL_CHANGE_FAILED); + break; + } + default: { + break; + } + + } + } + + private IDSGridEditDataRow getEditedRow(IDataProvider gridDataProvider, int rowPosition) { + if (gridDataProvider instanceof ListDataProvider) { + ListDataProvider dp = (ListDataProvider) gridDataProvider; + + Object row = dp.getRowObject(rowPosition); + if (row instanceof IDSGridEditDataRow) { + return (IDSGridEditDataRow) row; + } + } + + return null; + } + + private boolean isDistributedColumn(int columnPosition) throws MPPDBIDEException { + + List distributedRows = ((IDSEditGridDataProvider) this.dataProvider).getDistributedColumnList(); + String columnName = ((IDSEditGridDataProvider) this.dataProvider).getColumnDataProvider() + .getColumnName(columnPosition); + if (null != distributedRows && distributedRows.contains(columnName)) { + return true; + } + + return false; + + } + + /** + * Sets the data provider. + * + * @param dataProvider the new data provider + */ + public void setDataProvider(IDSGridDataProvider dataProvider) { + this.dataProvider = dataProvider; + } + + /** + * On pre destroy. + */ + public void onPreDestroy() { + gridBodyDataLayer = null; + dataProvider = null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridColumnValueAccessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridColumnValueAccessor.java new file mode 100644 index 0000000000000000000000000000000000000000..62d132f6102f7339a344d91ad97a0a8e58889275 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridColumnValueAccessor.java @@ -0,0 +1,564 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import java.io.UnsupportedEncodingException; +import java.math.BigDecimal; +import java.sql.Timestamp; +import java.sql.Types; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Comparator; +import java.util.Date; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.eclipse.nebula.widgets.nattable.data.IColumnPropertyAccessor; + +import org.opengauss.mppdbide.presentation.edittabledata.DSEditTableDataGridRow; +import org.opengauss.mppdbide.presentation.edittabledata.DSResultSetGridDataRow; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableCellState; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableRecordExecutionStatus; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableRecordStates; +import org.opengauss.mppdbide.presentation.edittabledata.IDSGridEditDataRow; +import org.opengauss.mppdbide.presentation.grid.IDSEditGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.presentation.objectproperties.DSObjectPropertiesGridDataProvider; +import org.opengauss.mppdbide.presentation.objectproperties.DSObjectPropertiesGridDataRow; +import org.opengauss.mppdbide.presentation.objectproperties.IObjectPropertyData; +import org.opengauss.mppdbide.presentation.util.DataTypeUtility; +import org.opengauss.mppdbide.utils.ConvertTimeStampValues; +import org.opengauss.mppdbide.utils.ConvertTimeValues; +import org.opengauss.mppdbide.utils.DateTimeFormatValidator; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.view.component.grid.GridUIUtils; +import org.opengauss.mppdbide.view.component.grid.ITableGridStyleLabelFactory; +import org.opengauss.mppdbide.view.prefernces.PreferenceWrapper; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs.MESSAGEDIALOGTYPE; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * + * Title: class + * + * Description: The Class GridColumnValueAccessor. + * + * @since 3.0.0 + */ +public class GridColumnValueAccessor implements IColumnPropertyAccessor { + private static final String GENERAL = "General"; + private static final String INDEX = "Index"; + private static final String CONSTRAINTS = "Constraints"; + private static final String COLUMNS = "Columns"; + + /** + * The data provider. + */ + protected IDSGridDataProvider dataProvider; + private static final String TRUE_VALUE = "true"; + private static final String FALSE_VALUE = "false"; + private static final String BIT_ONE = "1"; + private static final String BIT_ZERO = "0"; + private static final String NULL_VALUE = ""; + private String objectName; + + /** + * Instantiates a new grid column value accessor. + * + * @param dataProvider the data provider + */ + public GridColumnValueAccessor(IDSGridDataProvider dataProvider) { + this.dataProvider = dataProvider; + } + + /** + * Gets the data value. + * + * @param rowObject the row object + * @param columnIndex the column index + * @return the data value + */ + @Override + public Object getDataValue(IDSGridDataRow rowObject, int columnIndex) { + int columnDataType = dataProvider.getColumnDataProvider().getColumnDatatype(columnIndex); + Object value = null; + switch (columnDataType) { + case Types.TIMESTAMP: { + value = getTimestampTypeDataValue(rowObject, columnIndex); + break; + } + case Types.TIME: { + value = getTimeTypeDataValue(rowObject, columnIndex); + break; + } + case Types.DATE: { + value = getDateTypeDataValue(rowObject, columnIndex); + break; + } + default: { + value = rowObject.getValue(columnIndex); + break; + } + } + return value; + } + + private Object getTimestampTypeDataValue (IDSGridDataRow rowObject, int columnIndex) { + String columnDataTypeName = dataProvider.getColumnDataProvider().getColumnDataTypeName(columnIndex); + if ("timestamptz".equals(columnDataTypeName)) { + return rowObject.getValue(columnIndex); + } + Object objVal = rowObject.getValue(columnIndex); + Timestamp timestamp = null; + if (objVal instanceof String) { + try { + timestamp = Timestamp.valueOf(objVal.toString()); + } catch (IllegalArgumentException exp) { + return null; + } + } else if (objVal instanceof Timestamp) { + timestamp = (Timestamp) objVal; + } else { + return timestamp; + } + ConvertTimeStampValues value = null; + String dateFormat = PreferenceWrapper.getInstance().getPreferenceStore() + .getString(MPPDBIDEConstants.DATE_FORMAT_VALUE); + String timeFormat = PreferenceWrapper.getInstance().getPreferenceStore() + .getString(MPPDBIDEConstants.TIME_FORMAT_VALUE); + if (null != timestamp) { + value = new ConvertTimeStampValues(timestamp.getTime(), + DateTimeFormatValidator.getDatePlusTimeFormat(dateFormat, timeFormat)); + } + return value; + } + + private Object getTimeTypeDataValue (IDSGridDataRow rowObject, int columnIndex) { + String columnDataTypeName = dataProvider.getColumnDataProvider().getColumnDataTypeName(columnIndex); + if ("timetz".equals(columnDataTypeName)) { + return rowObject.getValue(columnIndex); + } + Object obj = rowObject.getValue(columnIndex); + Timestamp timestamp = null; + if (obj instanceof Timestamp) { + timestamp = (Timestamp) obj; + } + ConvertTimeValues value = null; + String timeFormat = PreferenceWrapper.getInstance().getPreferenceStore() + .getString(MPPDBIDEConstants.TIME_FORMAT_VALUE); + if (null != timestamp) { + value = new ConvertTimeValues(timestamp.getTime(), timeFormat); + } + return value; + } + + private Object getDateTypeDataValue (IDSGridDataRow rowObject, int columnIndex) { + Object obj = rowObject.getValue(columnIndex); + Date date = null; + if (obj instanceof Date) { + date = (Date) obj; + } + ConvertTimeStampValues value = null; + String dateFormat = PreferenceWrapper.getInstance().getPreferenceStore() + .getString(MPPDBIDEConstants.DATE_FORMAT_VALUE); + if (null != date) { + value = new ConvertTimeStampValues(date.getTime(), dateFormat); + } + return value; + } + + /** + * Sets the data value. + * + * @param rowObject the row object + * @param columnIndex the column index + * @param newValue the new value + */ + @Override + public void setDataValue(IDSGridDataRow rowObject, int columnIndex, Object newValue) { + if (rowObject.getClass() == DSObjectPropertiesGridDataRow.class) { + if ((((IObjectPropertyData) dataProvider).getObjectPropertyName()).equals(COLUMNS) && (columnIndex == 2)) { + try { + + if (newValue instanceof String) { + convertToBoolean(newValue.toString()); + } + } catch (IllegalArgumentException e) { + invalidBooleanValueErrDialog(MessageConfigLoader.getProperty( + IMessagesConstants.TABLE_PROPERTIES_INVALID_BOOLEAN_DATATYPE), IiconPath.ICO_TABLE); + return; + } + } + + performSetValueForObjProps(rowObject, columnIndex, newValue); + } else { + performSetValueForEditTableRow(rowObject, columnIndex, newValue); + } + } + + private void invalidBooleanValueErrDialog(String errorMessage, String iconPath) { + // Executes in Async Thread + // Removing will lead to two popups + MPPDBIDEDialogs.generateOKMessageDialogInUI(MESSAGEDIALOGTYPE.ERROR, true, + IconUtility.getIconImage(iconPath, this.getClass()), + MessageConfigLoader.getProperty(IMessagesConstants.QUERY_EXECUTION_FAILURE_ERROR_TITLE), errorMessage); + } + + private void performSetValueForObjProps(IDSGridDataRow rowObject, int columnIndex, Object newValue) { + + if (!((IDSEditGridDataProvider) dataProvider).isEditSupported()) { + return; + } + + Object oldValue = rowObject.getValue(columnIndex); + if (!isEditablePropertiesColumn(columnIndex, rowObject)) { + return; + } + + if (dataProvider instanceof IObjectPropertyData) { + String errorMessage = ((DSObjectPropertiesGridDataProvider) dataProvider).isValidObjectName(columnIndex, + newValue, rowObject); + + if (errorMessage != null) { + + MPPDBIDEDialogs.generateOKMessageDialogInUI(MESSAGEDIALOGTYPE.ERROR, true, + IconUtility.getIconImage(IiconPath.ICO_TABLE, this.getClass()), + MessageConfigLoader.getProperty(IMessagesConstants.QUERY_EXECUTION_FAILURE_ERROR_TITLE), + errorMessage); + return; + } + } + Comparator comparator = dataProvider.getColumnDataProvider().getComparator(columnIndex); + if (!isNullValue(columnIndex, newValue)) { + if (isValueChanged(newValue, oldValue, comparator)) { + + ((DSObjectPropertiesGridDataRow) rowObject).setValue(columnIndex, newValue); + } + } else { + + MPPDBIDEDialogs.generateOKMessageDialogInUI(MESSAGEDIALOGTYPE.ERROR, true, + IconUtility.getIconImage(IiconPath.ICO_TABLE, this.getClass()), + MessageConfigLoader.getProperty(IMessagesConstants.QUERY_EXECUTION_FAILURE_ERROR_TITLE), + objectName); + } + return; + } + + private boolean isEditablePropertiesColumn(int columnIndex, IDSGridDataRow rowObject) { + String objName = ((IObjectPropertyData) dataProvider).getObjectPropertyName(); + String colName = dataProvider.getColumnDataProvider().getColumnName(columnIndex); + String rowData = null; + if (objName.equals(GENERAL)) { + rowData = rowObject.getValue(0).toString(); + } + if (null != colName && GridUIUtils.isEditablePropertiesAttributes(objName, colName, rowData)) { + return true; + } + return false; + } + + private boolean isNullValue(int columnIndex, Object newValue) { + String propertyName = ((IObjectPropertyData) this.dataProvider).getObjectPropertyName(); + boolean flag = false; + switch (propertyName) { + case GENERAL: { + return false; + } + case COLUMNS: { + objectName = MessageConfigLoader.getProperty(IMessagesConstants.ERR_COLUMN_NAME_EMPTY); + flag = true; + break; + } + case INDEX: { + objectName = MessageConfigLoader.getProperty(IMessagesConstants.ERR_INDEX_NAME_EMPTY); + flag = true; + break; + } + case CONSTRAINTS: { + objectName = MessageConfigLoader.getProperty(IMessagesConstants.ERR_CONSTRAINT_NAME_EMPTY); + flag = true; + break; + } + + default: { + break; + } + } + + if (flag && columnIndex == 0 && newValue == null) { + return true; + } + return false; + } + + private void performSetValueForEditTableRow(IDSGridDataRow rowObject, int columnIndex, Object newValueParam) { + Object newValue = newValueParam; + Object oldValue = rowObject.getValue(columnIndex); + EditTableRecordStates updatedState = ((IDSGridEditDataRow) rowObject).getUpdatedState(); + List distributedCols = ((IDSEditGridDataProvider) dataProvider).getDistributedColumnList(); + + String columnDataTypeName = dataProvider.getColumnDataProvider().getColumnDataTypeName(columnIndex); + int colPrecisionVal = dataProvider.getColumnDataProvider().getPrecision(columnIndex); + if (!GridUIUtils.isDatatypeEditSupported(columnDataTypeName, colPrecisionVal)) { + return; + } + if (distributedCols != null + && distributedCols.contains(dataProvider.getColumnDataProvider().getColumnName(columnIndex)) + && updatedState != EditTableRecordStates.INSERT) { + return; + } + try { + + newValue = convertValueAsPerDataType(rowObject, columnIndex, newValue); + + oldValue = convertValueAsPerDataType(rowObject, columnIndex, oldValue); + + Comparator comparator = dataProvider.getColumnDataProvider().getComparator(columnIndex); + updateCellStatusOnValueChange(rowObject, columnIndex, newValue, oldValue, comparator); + } catch (NumberFormatException e) { + // Executes in Async Thread + // Removing will lead to two popups + MPPDBIDEDialogs.generateOKMessageDialogInUI(MESSAGEDIALOGTYPE.ERROR, true, + IconUtility.getIconImage(IiconPath.ICO_EDIT_EDIT, this.getClass()), + MessageConfigLoader.getProperty(IMessagesConstants.QUERY_EXECUTION_FAILURE_ERROR_TITLE), + MessageConfigLoader.getProperty(IMessagesConstants.EDIT_TABLE_INVALID_NUMBER_DATATYPE)); + + } catch (IllegalArgumentException e) { + invalidBooleanValueErrDialog( + MessageConfigLoader.getProperty(IMessagesConstants.EDIT_TABLE_INVALID_BOOLEAN_DATATYPE), + IiconPath.ICO_EDIT_EDIT); + } catch (ParseException e) { + MPPDBIDEDialogs.generateOKMessageDialogInUI(MESSAGEDIALOGTYPE.ERROR, true, + IconUtility.getIconImage(IiconPath.ICO_EDIT_EDIT, this.getClass()), + MessageConfigLoader.getProperty(IMessagesConstants.QUERY_EXECUTION_FAILURE_ERROR_TITLE), + MessageConfigLoader.getProperty(IMessagesConstants.EDIT_TABLE_INVALID_DATE_DATATYPE)); + + } + } + + private void updateCellStatusOnValueChange(IDSGridDataRow rowObject, int columnIndex, Object newValue, + Object oldValue, Comparator comparator) { + if (isValueChanged(newValue, oldValue, comparator)) { + ((DSEditTableDataGridRow) rowObject).setValue(columnIndex, newValue); + EditTableRecordExecutionStatus executionStatus = ((IDSGridEditDataRow) rowObject).getExecutionStatus(); + // FAILED_AND_MODIFIED is checked when the row has more than one + // failed cell value + if (executionStatus == EditTableRecordExecutionStatus.FAILED + || executionStatus == EditTableRecordExecutionStatus.FAILED_AND_MODIFIED) { + ((IDSGridEditDataRow) rowObject).setExecutionStatus(EditTableRecordExecutionStatus.FAILED_AND_MODIFIED); + ((IDSGridEditDataRow) rowObject).setCellSatus(EditTableCellState.MODIFIED, columnIndex); + } + } + } + + private Object convertValueAsPerDataType(IDSGridDataRow rowObject, int columnIndex, Object newValue) + throws ParseException { + if (newValue instanceof String) { + newValue = convertStringToObject(rowObject, (String) newValue, columnIndex); + + } else if (newValue instanceof Date) { + newValue = convertDateToTimeStamp((Date) newValue, columnIndex); + } + return newValue; + } + + private boolean isValueChanged(Object newValue, Object oldValue, Comparator comparator) { + if (null == newValue && null == oldValue) { + return false; + } + + return (null == newValue) || (null == oldValue) + || (comparator != null && comparator.compare(oldValue, newValue) != 0); + } + + /** + * Gets the data provider. + * + * @return the data provider + */ + public IDSGridDataProvider getDataProvider() { + return dataProvider; + } + + /** + * Gets the column count. + * + * @return the column count + */ + @Override + public int getColumnCount() { + IDSGridColumnProvider columnDataProvider = getColumnDataProvider(); + if (null != columnDataProvider) { + return columnDataProvider.getColumnCount(); + } + return 0; + } + + /** + * Gets the column property. + * + * @param columnIndex the column index + * @return the column property + */ + @Override + public String getColumnProperty(int columnIndex) { + IDSGridColumnProvider columnDataProvider = getColumnDataProvider(); + if (null != columnDataProvider) { + return columnDataProvider.getColumnName(columnIndex); + } + return ""; + } + + /** + * Gets the column data provider. + * + * @return the column data provider + */ + protected IDSGridColumnProvider getColumnDataProvider() { + if (null != this.dataProvider) { + return this.dataProvider.getColumnDataProvider(); + } + return null; + } + + /** + * Gets the column index. + * + * @param propertyName the property name + * @return the column index + */ + @Override + public int getColumnIndex(String propertyName) { + IDSGridColumnProvider columnDataProvider = getColumnDataProvider(); + if (null != columnDataProvider) { + return columnDataProvider.getColumnIndex(propertyName); + } + return 0; + } + + /** + * On pre destroy. + */ + public void onPreDestroy() { + this.dataProvider = null; + } + + /** + * Convert string to object. + * + * @param rowObject the row object + * @param value the value + * @param columIdx the colum idx + * @return the object + * @throws ParseException the parse exception + */ + public Object convertStringToObject(IDSGridDataRow rowObject, String value, int columIdx) throws ParseException { + Date dateValue = null; + // set null if the value is empty + + if (StringUtils.isEmpty(value)) { + return null; + } + + switch (dataProvider.getColumnDataProvider().getColumnDatatype(columIdx)) { + case Types.TINYINT: + case Types.SMALLINT: { + return Short.parseShort(value); + } + case Types.INTEGER: { + return Integer.parseInt(value); + } + case Types.BIGINT: { + return Long.parseLong(value); + } + case Types.REAL: { + return Float.parseFloat(value); + } + case Types.FLOAT: + case Types.DOUBLE: { + return Double.parseDouble(value); + } + case Types.NUMERIC: { + BigDecimal decimal = new BigDecimal(value); + return decimal; + } + case Types.TIMESTAMP: + case Types.TIMESTAMP_WITH_TIMEZONE: { + dateValue = DataTypeUtility.convertToDateObj(value, + ITableGridStyleLabelFactory.COMMON_GRID_DATE_FORMAT); + return new Timestamp(dateValue.getTime()); + } + case Types.TIME: + case Types.TIME_WITH_TIMEZONE: { + dateValue = DataTypeUtility.convertToTimeObj(value, + ITableGridStyleLabelFactory.COMMON_GRID_TIME_FORMAT); + return new Timestamp(dateValue.getTime()); + } + case Types.BIT: + case Types.BOOLEAN: { + return convertToBoolean(value); + } + default: { + return getDefaultValue(rowObject, value); + } + } + + } + + private Object getDefaultValue(IDSGridDataRow rowObject, String value) { + if (rowObject instanceof DSResultSetGridDataRow && ((DSResultSetGridDataRow) rowObject).isIncludeEncoding()) { + DSResultSetGridDataRow row = (DSResultSetGridDataRow) rowObject; + String encoding = row.getEncoding(); + if (null != encoding && !encoding.isEmpty()) { + try { + return value.getBytes(encoding); + } catch (UnsupportedEncodingException e) { + // Ignore. Nothing can be done. + MPPDBIDELoggerUtility.debug("Unable to convert input by encoding."); + } + } + } + return value; + } + + private Object convertToBoolean(String value) { + if (NULL_VALUE.equals(value)) { + return false; + } + if (TRUE_VALUE.equalsIgnoreCase(value) || value.equals(BIT_ONE)) { + return true; + } + if (FALSE_VALUE.equalsIgnoreCase(value) || value.equals(BIT_ZERO)) { + return false; + } + throw new IllegalArgumentException(); + + } + + private Object convertDateToTimeStamp(Date dateObj, int columnIndex) throws ParseException { + SimpleDateFormat datetimeFormatter1 = new SimpleDateFormat(ITableGridStyleLabelFactory.COMMON_GRID_DATE_FORMAT); + Date trimmedDate = datetimeFormatter1.parse(datetimeFormatter1.format(dateObj)); + + return new Timestamp(trimmedDate.getTime()); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridCornerLayerDataProvider.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridCornerLayerDataProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..62a6082b1e6897e64debaf926647302099db24cc --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridCornerLayerDataProvider.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import org.eclipse.nebula.widgets.nattable.NatTable; +import org.eclipse.nebula.widgets.nattable.data.IDataProvider; +import org.eclipse.nebula.widgets.nattable.grid.GridRegion; +import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer; +import org.eclipse.nebula.widgets.nattable.ui.action.IMouseAction; +import org.eclipse.nebula.widgets.nattable.ui.binding.UiBindingRegistry; +import org.eclipse.nebula.widgets.nattable.ui.matcher.MouseEventMatcher; +import org.eclipse.swt.events.MouseEvent; + +import org.opengauss.mppdbide.view.component.grid.IDataGridContext; + +/** + * + * Title: class + * + * Description: The Class GridCornerLayerDataProvider. + * + * @since 3.0.0 + */ +public class GridCornerLayerDataProvider implements IDataProvider { + private int columncount; + private int rowCount; + private IDataGridContext dataGridContext; + + /** + * Instantiates a new grid corner layer data provider. + * + * @param dataGridContext the data grid context + */ + public GridCornerLayerDataProvider(IDataGridContext dataGridContext) { + this.dataGridContext = dataGridContext; + } + + /** + * Gets the data value. + * + * @param columnIndex the column index + * @param rowIndex the row index + * @return the data value + */ + @Override + public Object getDataValue(int columnIndex, int rowIndex) { + // Empty string. Will use image. + return ""; + } + + /** + * Sets the data value. + * + * @param columnIndex the column index + * @param rowIndex the row index + * @param newValue the new value + */ + @Override + public void setDataValue(int columnIndex, int rowIndex, Object newValue) { + // Ignore. Corner cell not part of data. So, never be allowed to set. + } + + /** + * Gets the column count. + * + * @return the column count + */ + @Override + public int getColumnCount() { + columncount = this.dataGridContext.getDataProvider().getColumnDataProvider().getColumnCount(); + return columncount; + } + + /** + * Gets the row count. + * + * @return the row count + */ + @Override + public int getRowCount() { + rowCount = this.dataGridContext.getDataProvider().getRecordCount(); + return rowCount; + } + + /** + * Enable corner click select all. + * + * @param uiBindingRegistry the ui binding registry + * @param selectionLayer the selection layer + */ + public void enableCornerClickSelectAll(UiBindingRegistry uiBindingRegistry, SelectionLayer selectionLayer) { + uiBindingRegistry.registerSingleClickBinding(new MouseEventMatcher(GridRegion.CORNER), + new SelectAllEventListener(selectionLayer)); + + } + + /** + * The listener interface for receiving selectAllEvent events. The class + * that is interested in processing a selectAllEvent event implements this + * interface, and the object created with that class is registered with a + * component using the component's addSelectAllEventListener + * method. When the selectAllEvent event occurs, that object's appropriate + * method is invoked. + * + * SelectAllEventEvent + */ + private static final class SelectAllEventListener implements IMouseAction { + private SelectionLayer selectionLayer; + + private SelectAllEventListener(SelectionLayer selectionLayer) { + this.selectionLayer = selectionLayer; + } + + @Override + public void run(NatTable natTable, MouseEvent event) { + selectionLayer.selectAll(); + } + } + + /** + * the onPreDestroy + */ + public void onPreDestroy() { + dataGridContext = null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridNonEditableColumnValueAccessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridNonEditableColumnValueAccessor.java new file mode 100644 index 0000000000000000000000000000000000000000..218c09f0af85cf44d2b58e91c16dff09afed57e3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridNonEditableColumnValueAccessor.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; + +/** + * + * Title: class + * + * Description: The Class GridNonEditableColumnValueAccessor. + * + * @since 3.0.0 + */ +public class GridNonEditableColumnValueAccessor extends GridColumnValueAccessor { + + /** + * Instantiates a new grid non editable column value accessor. + * + * @param dataProvider the data provider + */ + public GridNonEditableColumnValueAccessor(IDSGridDataProvider dataProvider) { + super(dataProvider); + + } + + /** + * Sets the data value. + * + * @param rowObject the row object + * @param columnIndex the column index + * @param newValue the new value + */ + @Override + public void setDataValue(IDSGridDataRow rowObject, int columnIndex, Object newValue) { + return; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridPasteCommand.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridPasteCommand.java new file mode 100644 index 0000000000000000000000000000000000000000..69c844507499146b7821138da14c02503907c773 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridPasteCommand.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import org.eclipse.nebula.widgets.nattable.command.AbstractContextFreeCommand; +import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry; +import org.eclipse.nebula.widgets.nattable.copy.command.PasteDataCommand; +import org.eclipse.nebula.widgets.nattable.layer.ILayer; + +/** + * + * Title: class + * + * Description: The Class GridPasteCommand. + * + * @since 3.0.0 + */ +public class GridPasteCommand extends PasteDataCommand { + + /** + * Instantiates a new grid paste command. + * + * @param configRegistry the config registry + */ + public GridPasteCommand(IConfigRegistry configRegistry) { + super(configRegistry); + } + + /** + * Convert to target layer. + * + * @param targetLayer the target layer + * @return true, if successful + */ + @Override + public boolean convertToTargetLayer(ILayer targetLayer) { + return super.convertToTargetLayer(targetLayer); + } + + /** + * Clone command. + * + * @return the abstract context free command + */ + @Override + public AbstractContextFreeCommand cloneCommand() { + return super.cloneCommand(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridPasteHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridPasteHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..24e7bdd42b7dca62052601776165eec083342279 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridPasteHandler.java @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import java.awt.Toolkit; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.io.IOException; +import java.io.StringReader; +import java.util.ArrayList; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVRecord; +import org.eclipse.nebula.widgets.nattable.command.AbstractLayerCommandHandler; +import org.eclipse.nebula.widgets.nattable.coordinate.PositionCoordinate; +import org.eclipse.nebula.widgets.nattable.copy.command.PasteDataCommand; +import org.eclipse.nebula.widgets.nattable.edit.command.UpdateDataCommand; +import org.eclipse.nebula.widgets.nattable.layer.LabelStack; +import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.view.component.grid.IEditTableGridStyleLabelFactory; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs.MESSAGEDIALOGTYPE; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * + * Title: class + * + * Description: The Class GridPasteHandler. + * + * @since 3.0.0 + */ +public class GridPasteHandler extends AbstractLayerCommandHandler { + private SelectionLayer selectionLayer; + private PositionCoordinate[] posCoordinate; + private LabelStack configLabelsByPosition; + + /** + * Instantiates a new grid paste handler. + * + * @param selectionLayer the selection layer + */ + public GridPasteHandler(SelectionLayer selectionLayer) { + this.selectionLayer = selectionLayer; + } + + /** + * Gets the command class. + * + * @return the command class + */ + @Override + public Class getCommandClass() { + return PasteDataCommand.class; + } + + /** + * Do command. + * + * @param command the command + * @return true, if successful + */ + @Override + protected boolean doCommand(PasteDataCommand command) { + + String[][] pasteableString = convertToPastable(); + posCoordinate = getPostionCoordinates(); + PositionCoordinate positionCoordinate = null; + + // check when nothing is selected from the external source to copy in + // the nattable + if (null == pasteableString) { + + return false; + } + int counter = noOfElementsInString(pasteableString); + + if ((posCoordinate.length) == counter) { + + if (validateCells(pasteableString)) { + int row = pasteableString.length; + int col = 0; + int cnt = 0; + if (row > 0) { + col = pasteableString[0].length; + } + for (int colIndex = 0; colIndex < col; colIndex++) { + for (int rowIndex = 0; rowIndex < row; rowIndex++) { + + positionCoordinate = posCoordinate[colIndex + rowIndex + cnt]; + configLabelsByPosition = selectionLayer.getConfigLabelsByPosition( + positionCoordinate.columnPosition, positionCoordinate.rowPosition); + /* + * Handling of paste for complex datatype in properties + * window + */ + if (configLabelsByPosition.hasLabel(IEditTableGridStyleLabelFactory.COL_LABEL_CUSTOM_DIALOG) + || configLabelsByPosition + .hasLabel(IEditTableGridStyleLabelFactory.COL_LABEL_READONLY_CELL)) { + continue; + } + + this.selectionLayer + .doCommand(new UpdateDataCommand(this.selectionLayer, positionCoordinate.columnPosition, + positionCoordinate.rowPosition, pasteableString[rowIndex][colIndex])); + } + cnt = cnt + pasteableString.length - 1; + } + return true; + } + + } else { + MPPDBIDEDialogs.generateMessageDialog(MESSAGEDIALOGTYPE.INFORMATION, true, + IconUtility.getIconImage(IiconPath.ICO_TOOL_32X32, this.getClass()), + MessageConfigLoader.getProperty(IMessagesConstants.PASTE_INVALID_SELECTION_DIALOG_TITLE), + MessageConfigLoader.getProperty(IMessagesConstants.PASTE_INVALID_SELECTION_DIALOG_MSG), + MessageConfigLoader.getProperty(IMessagesConstants.BTN_OK)); + + } + return false; + } + + private int noOfElementsInString(String[][] pasteableString) { + int counter = 0; + + for (int index = 0; index < pasteableString.length; index++) { + counter = counter + pasteableString[index].length; + } + return counter; + } + + private PositionCoordinate[] getPostionCoordinates() { + return this.selectionLayer.getSelectedCellPositions(); + + } + + private String[][] convertToPastable() { + String trstring = null; + Clipboard system = Toolkit.getDefaultToolkit().getSystemClipboard(); + + try { + if (system != null) { + trstring = (String) (system.getContents(this).getTransferData(DataFlavor.stringFlavor)); + } + + } catch (UnsupportedFlavorException exp) { + MPPDBIDELoggerUtility.error("UnsupportedFlavorException in GridPasteHandler.", exp); + } catch (IOException ex) { + MPPDBIDELoggerUtility.error("IOException in GridPasteHandler while converting data from clipboard.", ex); + } + if (null == trstring) { + return new String[0][0]; + } + return parseTSV(new StringReader(trstring)); + } + + private boolean validateCells(String[][] pastedValue) { + return true; + } + + private String[][] parseTSV(StringReader stringReader) { + ArrayList recBuffer = new ArrayList(5); + String[] row = null; + int index = 0; + try { + for (CSVRecord record : CSVFormat.TDF.withQuote(null).parse(stringReader)) { + row = new String[record.size()]; + index = 0; + + for (String field : record) { + row[index++] = field; + } + recBuffer.add(row); + } + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("Error while TSV parsing.", exception); + } + + int recordCount = recBuffer.size(); + String[][] retArray = new String[recordCount][]; + return recBuffer.toArray(retArray); + } + + /** + * the onPreDestroy + */ + public void onPreDestroy() { + this.selectionLayer = null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridSaveSortState.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridSaveSortState.java new file mode 100644 index 0000000000000000000000000000000000000000..e804c4b4a42a00c11a7d2d94928531411fa147d9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridSaveSortState.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import java.util.ArrayList; +import java.util.List; + +/** + * + * Title: class + * + * Description: The Class GridSaveSortState. + * + * @since 3.0.0 + */ +public class GridSaveSortState { + private List saveSortList; + + /** + * Instantiates a new grid save sort state. + */ + public GridSaveSortState() { + saveSortList = new ArrayList(10); + } + + /** + * Gets the clone. + * + * @return the clone + */ + public GridSaveSortState getClone() { + + GridSaveSortState dup = new GridSaveSortState(); + + for (SortEntryData str : this.saveSortList) { + dup.saveSortEntry(str); + } + return dup; + } + + /** + * Checks for sort keys. + * + * @return true, if successful + */ + public boolean hasSortKeys() { + return this.saveSortList.size() > 0; + } + + /** + * Save sort entry. + * + * @param entry the entry + */ + public void saveSortEntry(SortEntryData entry) { + saveSortList.add(entry); + } + + /** + * Gets the saved sort list. + * + * @return the saved sort list + */ + public List getSavedSortList() { + return this.saveSortList; + } + + /** + * Clean up. + */ + public void cleanUp() { + if (null != this.saveSortList) { + this.saveSortList.clear(); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridViewPortLayer.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridViewPortLayer.java new file mode 100644 index 0000000000000000000000000000000000000000..1cafe30cd1ef0fba8db7414ff980e04b8df70c2e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/GridViewPortLayer.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import org.eclipse.nebula.widgets.nattable.layer.IUniqueIndexLayer; +import org.eclipse.nebula.widgets.nattable.viewport.ViewportLayer; + +/** + * + * Title: class + * + * Description: The Class GridViewPortLayer. + * + * @since 3.0.0 + */ +public class GridViewPortLayer extends ViewportLayer { + + /** + * Instantiates a new grid view port layer. + * + * @param underlyingLayer the underlying layer + */ + public GridViewPortLayer(IUniqueIndexLayer underlyingLayer) { + super(underlyingLayer); + } + + /** + * Checks if is scrolled to end of page. + * + * @return true, if is scrolled to end of page + */ + public boolean isScrolledToEndOfPage() { + return isLastRowCompletelyDisplayed(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/RowHeaderColumnLabelAccumulator.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/RowHeaderColumnLabelAccumulator.java new file mode 100644 index 0000000000000000000000000000000000000000..cfdb639a67778f544bb255b9aa87916e9a5b9862 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/RowHeaderColumnLabelAccumulator.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import org.eclipse.nebula.widgets.nattable.data.IDataProvider; +import org.eclipse.nebula.widgets.nattable.data.ListDataProvider; +import org.eclipse.nebula.widgets.nattable.layer.DataLayer; +import org.eclipse.nebula.widgets.nattable.layer.LabelStack; +import org.eclipse.nebula.widgets.nattable.layer.cell.ColumnLabelAccumulator; + +import org.opengauss.mppdbide.presentation.edittabledata.EditTableRecordExecutionStatus; +import org.opengauss.mppdbide.presentation.edittabledata.IDSGridEditDataRow; +import org.opengauss.mppdbide.view.component.grid.IEditTableGridStyleLabelFactory; + +/** + * + * Title: class + * + * Description: The Class RowHeaderColumnLabelAccumulator. + * + * @since 3.0.0 + */ +public class RowHeaderColumnLabelAccumulator extends ColumnLabelAccumulator { + private DataLayer gridBodyDataLayer; + + /** + * Instantiates a new row header column label accumulator. + * + * @param layer the layer + */ + public RowHeaderColumnLabelAccumulator(DataLayer layer) { + this.gridBodyDataLayer = layer; + } + + /** + * Accumulate config labels. + * + * @param configLabels the config labels + * @param columnPosition the column position + * @param rowPosition the row position + */ + @Override + public void accumulateConfigLabels(LabelStack configLabels, int columnPosition, int rowPosition) { + super.accumulateConfigLabels(configLabels, columnPosition, rowPosition); + + IDataProvider dataProvider = this.gridBodyDataLayer.getDataProvider(); + + IDSGridEditDataRow editRow = getEditedRow(dataProvider, rowPosition); + if (editRow != null && editRow.getExecutionStatus() == EditTableRecordExecutionStatus.FAILED) { + configLabels.addLabel(IEditTableGridStyleLabelFactory.COL_LABEL_CHANGE_FAILED); + } + } + + private IDSGridEditDataRow getEditedRow(IDataProvider dataProvider, int rowPosition) { + if (dataProvider instanceof ListDataProvider) { + ListDataProvider dp = (ListDataProvider) dataProvider; + + Object row = dp.getRowObject(rowPosition); + if (row instanceof IDSGridEditDataRow) { + return (IDSGridEditDataRow) row; + } + } + + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/SortAwareSelectionUIBindings.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/SortAwareSelectionUIBindings.java new file mode 100644 index 0000000000000000000000000000000000000000..d243dfc28f7583b7ea99f1757d100eb01a1a97d1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/SortAwareSelectionUIBindings.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import org.eclipse.nebula.widgets.nattable.config.AbstractUiBindingConfiguration; +import org.eclipse.nebula.widgets.nattable.ui.binding.UiBindingRegistry; +import org.eclipse.nebula.widgets.nattable.ui.matcher.MouseEventMatcher; +import org.eclipse.swt.SWT; + +/** + * + * Title: class + * + * Description: The Class SortAwareSelectionUIBindings. + * + * @since 3.0.0 + */ +public class SortAwareSelectionUIBindings extends AbstractUiBindingConfiguration { + + /** + * Configure ui bindings. + * + * @param uiBindingRegistry the ui binding registry + */ + @Override + public void configureUiBindings(UiBindingRegistry uiBindingRegistry) { + /* + * Unregister 3 times because rowSelectionLayer, columnSelectionLayer + * and bodySelectionLayer all register UI Bindings + */ + for (int i = 0; i < 3; i++) { + uiBindingRegistry.unregisterSingleClickBinding(MouseEventMatcher.columnHeaderLeftClick(SWT.NONE)); + uiBindingRegistry.unregisterSingleClickBinding(MouseEventMatcher.columnHeaderLeftClick(SWT.MOD2)); + uiBindingRegistry.unregisterSingleClickBinding(MouseEventMatcher.columnHeaderLeftClick(SWT.MOD1)); + uiBindingRegistry + .unregisterSingleClickBinding(MouseEventMatcher.columnHeaderLeftClick(SWT.MOD2 | SWT.MOD1)); + } + + uiBindingRegistry.registerSingleClickBinding(MouseEventMatcher.columnHeaderLeftClick(SWT.NONE), + new ViewportSelectColumnActionWrapper(false, false)); + uiBindingRegistry.registerSingleClickBinding(MouseEventMatcher.columnHeaderLeftClick(SWT.MOD2), + new ViewportSelectColumnActionWrapper(true, false)); + uiBindingRegistry.registerSingleClickBinding(MouseEventMatcher.columnHeaderLeftClick(SWT.MOD1), + new ViewportSelectColumnActionWrapper(false, true)); + uiBindingRegistry.registerSingleClickBinding(MouseEventMatcher.columnHeaderLeftClick(SWT.MOD2 | SWT.MOD1), + new ViewportSelectColumnActionWrapper(true, true)); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/SortEntryData.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/SortEntryData.java new file mode 100644 index 0000000000000000000000000000000000000000..4c49adcc6ea85b8a2b4e11805ad0b0d718546f68 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/SortEntryData.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import org.eclipse.nebula.widgets.nattable.sort.SortDirectionEnum; + +/** + * + * Title: class + * + * Description: The Class SortEntryData. + * + * @since 3.0.0 + */ +public class SortEntryData { + private String sortedColumnName; + private SortDirectionEnum sortDirection; + + /** + * Instantiates a new sort entry data. + * + * @param sortedColumnName the sorted column name + * @param sortDirection the sort direction + */ + public SortEntryData(String sortedColumnName, SortDirectionEnum sortDirection) { + this.sortedColumnName = sortedColumnName; + this.sortDirection = sortDirection; + } + + /** + * Gets the column name. + * + * @return the column name + */ + public String getColumnName() { + return this.sortedColumnName; + } + + /** + * Gets the sort direction. + * + * @return the sort direction + */ + public SortDirectionEnum getSortDirection() { + return this.sortDirection; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/SortRegistryConfiguration.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/SortRegistryConfiguration.java new file mode 100644 index 0000000000000000000000000000000000000000..45d0078f26e564b80888ee24f9ff1042563138b8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/SortRegistryConfiguration.java @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import java.util.Comparator; + +import org.eclipse.nebula.widgets.nattable.config.AbstractRegistryConfiguration; +import org.eclipse.nebula.widgets.nattable.config.CellConfigAttributes; +import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry; +import org.eclipse.nebula.widgets.nattable.config.NullComparator; +import org.eclipse.nebula.widgets.nattable.grid.GridRegion; +import org.eclipse.nebula.widgets.nattable.layer.cell.ColumnLabelAccumulator; +import org.eclipse.nebula.widgets.nattable.painter.cell.ICellPainter; +import org.eclipse.nebula.widgets.nattable.sort.SortConfigAttributes; +import org.eclipse.nebula.widgets.nattable.sort.action.SortColumnAction; +import org.eclipse.nebula.widgets.nattable.style.DisplayMode; +import org.eclipse.nebula.widgets.nattable.ui.binding.UiBindingRegistry; +import org.eclipse.nebula.widgets.nattable.ui.matcher.MouseEventMatcher; +import org.eclipse.swt.SWT; + +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.view.component.IGridUIPreference; +import org.opengauss.mppdbide.view.component.grid.IEditTableGridStyleLabelFactory; + +/** + * + * Title: class + * + * Description: The Class SortRegistryConfiguration. + * + * @since 3.0.0 + */ +public class SortRegistryConfiguration extends AbstractRegistryConfiguration { + private IDSGridDataProvider dataProvider; + private IGridUIPreference pref; + + /** + * The Constant CONFIG_TYPE_SORT. + */ + public static final String CONFIG_TYPE_SORT = "SORT"; // $NON-NLS-1$ + + /** + * The Constant CONFIG_TYPE_SORT_DOWN. + */ + public static final String CONFIG_TYPE_SORT_DOWN = "SORT_DOWN"; // $NON-NLS-1$ + + /** + * The Constant CONFIG_TYPE_SORT_UP. + */ + public static final String CONFIG_TYPE_SORT_UP = "SORT_UP"; // $NON-NLS-1$ + + /** + * The Constant CONFIG_TYPE_SORT_SEQ. + */ + public static final String CONFIG_TYPE_SORT_SEQ = "SORT_SEQ_"; // $NON-NLS-1$ + + private ICellPainter cellPaintr; + + /** + * Instantiates a new sort registry configuration. + * + * @param dataProvider the data provider + * @param uiPref the ui pref + */ + public SortRegistryConfiguration(IDSGridDataProvider dataProvider, IGridUIPreference uiPref) { + this.dataProvider = dataProvider; + this.pref = uiPref; + this.cellPaintr = new SortablePainterWrapper(); + } + + /** + * Configure registry. + * + * @param configuredRegistry the configured registry + */ + @Override + public void configureRegistry(IConfigRegistry configuredRegistry) { + if (null == getDataProvider()) { + return; + } + + int columnCount = getDataProvider().getColumnDataProvider().getColumnCount(); + columnCount = handleDisableSortForFunctionProcExeResult(columnCount); + for (int i = 0; i < columnCount; i++) { + configuredRegistry.registerConfigAttribute(SortConfigAttributes.SORT_COMPARATOR, + getComparator(i, pref.isEnableSort()), DisplayMode.NORMAL, + ColumnLabelAccumulator.COLUMN_LABEL_PREFIX + i); + } + + configuredRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, this.cellPaintr, + DisplayMode.NORMAL, GridRegion.COLUMN_HEADER); + configuredRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, this.cellPaintr, + DisplayMode.NORMAL, IEditTableGridStyleLabelFactory.COL_HEADER_LABEL_READONLY_CELL); + configuredRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, this.cellPaintr, + DisplayMode.NORMAL, CONFIG_TYPE_SORT_DOWN); + configuredRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, this.cellPaintr, + DisplayMode.NORMAL, CONFIG_TYPE_SORT_UP); + } + + /** + * Handle disable sort for function proc exe result. + * + * @param columnCount the column count + * @return the int + */ + private int handleDisableSortForFunctionProcExeResult(int columnCount) { + int cnt = columnCount; + if (getDataProvider().isFuncProcExport()) { + cnt = cnt - 1; + } + return cnt; + } + + /** + * Configure ui bindings. + * + * @param uiBindRegistry the ui bind registry + */ + @Override + public void configureUiBindings(UiBindingRegistry uiBindRegistry) { + // Register new bindings + uiBindRegistry.unregisterSingleClickBinding(MouseEventMatcher.columnHeaderLeftClick(SWT.MOD3)); + uiBindRegistry.registerSingleClickBinding(MouseEventMatcher.columnHeaderLeftClick(SWT.MOD3), + new SortColumnAction(false)); + } + + /** + * Gets the comparator. + * + * @param colIndex the col index + * @param isSortSupported the is sort supported + * @return the comparator + */ + public Comparator getComparator(int colIndex, boolean isSortSupported) { + return isSortSupported ? getDataProvider().getColumnDataProvider().getComparator(colIndex) + : new NullComparator(); + } + + /** + * Gets the data provider. + * + * @return the data provider + */ + public IDSGridDataProvider getDataProvider() { + return dataProvider; + } + + /** + * Sets the data provider. + * + * @param dataProvider the new data provider + */ + public void setDataProvider(IDSGridDataProvider dataProvider) { + this.dataProvider = dataProvider; + } + + /** + * On pre destroy. + */ + public void onPreDestroy() { + this.dataProvider = null; + if (this.cellPaintr != null) { + ((SortablePainterWrapper) cellPaintr).onPreDestroy(); + } + this.cellPaintr = null; + this.pref = null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/SortablePainterWrapper.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/SortablePainterWrapper.java new file mode 100644 index 0000000000000000000000000000000000000000..6d623c231d1a6d633dedf3f8ae4c5e6bdfe1db38 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/SortablePainterWrapper.java @@ -0,0 +1,283 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry; +import org.eclipse.nebula.widgets.nattable.layer.LabelStack; +import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell; +import org.eclipse.nebula.widgets.nattable.painter.cell.ImagePainter; +import org.eclipse.nebula.widgets.nattable.painter.cell.TextPainter; +import org.eclipse.nebula.widgets.nattable.painter.cell.decorator.BeveledBorderDecorator; +import org.eclipse.nebula.widgets.nattable.painter.cell.decorator.CellPainterDecorator; +import org.eclipse.nebula.widgets.nattable.ui.util.CellEdgeEnum; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Rectangle; + +import org.opengauss.mppdbide.view.component.grid.IEditTableGridStyleLabelFactory; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; + +/** + * + * Title: class + * + * Description: The Class SortablePainterWrapper. + * + * @since 3.0.0 + */ +public class SortablePainterWrapper extends CellPainterDecorator { + private ImagePainter imagePainterLock; + private ImagePainter imagePainterSortNone; + private ImagePainter imagePainterSortDes; + private ImagePainter imagePainterSortDesSmaller; + private ImagePainter imagePainterSortDesSmallest; + private ImagePainter imagePainterSortAsc; + private ImagePainter imagePainterSortAscSmaller; + private ImagePainter imagePainterSortAscSmallest; + private CellPainterDecorator noLockNoSort; + private CellPainterDecorator noLockAscSort; + private CellPainterDecorator noLockAscSortSmaller; + private CellPainterDecorator noLockAscSortSmallest; + private CellPainterDecorator noLockDesSort; + private CellPainterDecorator noLockDesSortSmaller; + private CellPainterDecorator noLockDesSortSmallest; + private CellPainterDecorator lockNoSort; + private CellPainterDecorator lockAscSort; + private CellPainterDecorator lockAscSortSmaller; + private CellPainterDecorator lockAscSortSmallest; + private CellPainterDecorator lockDesSort; + private CellPainterDecorator lockDesSortSmaller; + private CellPainterDecorator lockDesSortSmallest; + + /** + * Config label that is added if a column is sorted descending. + */ + private static final String SORT_DOWN_CONFIG_TYPE = "SORT_DOWN"; // $NON-NLS-1$ + /** + * Config label that is added if a column is sorted ascending. + */ + private static final String SORT_UP_CONFIG_TYPE = "SORT_UP"; // $NON-NLS-1$ + /** + * Sort sequence can be appended to this base + */ + private static final String CONFIG_TYPE_SORT_SEQ = "SORT_SEQ_"; // $NON-NLS-1$ + + /** + * Instantiates a new sortable painter wrapper. + */ + public SortablePainterWrapper() { + super(new BeveledBorderDecorator(new TextPainter()), CellEdgeEnum.RIGHT, 100, null, false, true); + createImagePainters(); + createCellPainters(); + } + + private void createCellPainters() { + /* No lock + no sort */ + noLockNoSort = new CellPainterDecorator(new BeveledBorderDecorator(new TextPainter()), CellEdgeEnum.RIGHT, 100, + imagePainterSortNone, false, true); + + /* No lock + asc sort */ + noLockAscSort = new CellPainterDecorator(new BeveledBorderDecorator(new TextPainter()), CellEdgeEnum.RIGHT, 100, + imagePainterSortAsc, false, true); + + /* No lock + asc smaller sort */ + noLockAscSortSmaller = new CellPainterDecorator(new BeveledBorderDecorator(new TextPainter()), + CellEdgeEnum.RIGHT, 100, imagePainterSortAscSmaller, false, true); + + /* No lock + asc smallest sort */ + noLockAscSortSmallest = new CellPainterDecorator(new BeveledBorderDecorator(new TextPainter()), + CellEdgeEnum.RIGHT, 100, imagePainterSortAscSmallest, false, true); + + /* No lock + des sort */ + noLockDesSort = new CellPainterDecorator(new BeveledBorderDecorator(new TextPainter()), CellEdgeEnum.RIGHT, 100, + imagePainterSortDes, false, true); + + /* No lock + des smaller sort */ + noLockDesSortSmaller = new CellPainterDecorator(new BeveledBorderDecorator(new TextPainter()), + CellEdgeEnum.RIGHT, 100, imagePainterSortDesSmaller, false, true); + + /* No lock + des smallest sort */ + noLockDesSortSmallest = new CellPainterDecorator(new BeveledBorderDecorator(new TextPainter()), + CellEdgeEnum.RIGHT, 100, imagePainterSortDesSmallest, false, true); + + /* lock + no sort */ + lockNoSort = new CellPainterDecorator(noLockNoSort, CellEdgeEnum.LEFT, 100, imagePainterLock, false, true); + + /* lock + asc sort */ + lockAscSort = new CellPainterDecorator(noLockAscSort, CellEdgeEnum.LEFT, 100, imagePainterLock, false, true); + + /* lock + asc smaller sort */ + lockAscSortSmaller = new CellPainterDecorator(noLockAscSortSmaller, CellEdgeEnum.LEFT, 100, imagePainterLock, + false, true); + + /* lock + asc smallest sort */ + lockAscSortSmallest = new CellPainterDecorator(noLockAscSortSmallest, CellEdgeEnum.LEFT, 100, imagePainterLock, + false, true); + + /* lock + des sort */ + lockDesSort = new CellPainterDecorator(noLockDesSort, CellEdgeEnum.LEFT, 100, imagePainterLock, false, true); + + /* lock + des smaller sort */ + lockDesSortSmaller = new CellPainterDecorator(noLockDesSortSmaller, CellEdgeEnum.LEFT, 100, imagePainterLock, + false, true); + + /* lock + des smallest sort */ + lockDesSortSmallest = new CellPainterDecorator(noLockDesSortSmallest, CellEdgeEnum.LEFT, 100, imagePainterLock, + false, true); + } + + private void createImagePainters() { + Image imageSortAsc = IconUtility.getIconImage(IconUtility.ICO_SORT_ASC, getClass()); + imagePainterSortAsc = new ImagePainter(imageSortAsc, false); + Image imageSortAscSmaller = IconUtility.getIconImage(IconUtility.ICO_SORT_ASC_SMALLER, getClass()); + imagePainterSortAscSmaller = new ImagePainter(imageSortAscSmaller, false); + Image imageSortAscSmallest = IconUtility.getIconImage(IconUtility.ICO_SORT_ASC_SMALLEST, getClass()); + imagePainterSortAscSmallest = new ImagePainter(imageSortAscSmallest, false); + Image imageSortDes = IconUtility.getIconImage(IconUtility.ICO_SORT_DES, getClass()); + imagePainterSortDes = new ImagePainter(imageSortDes, false); + Image imageSortDesSmaller = IconUtility.getIconImage(IconUtility.ICO_SORT_DES_SMALLER, getClass()); + imagePainterSortDesSmaller = new ImagePainter(imageSortDesSmaller, false); + Image imageSortDesSmallest = IconUtility.getIconImage(IconUtility.ICO_SORT_DES_SMALLEST, getClass()); + imagePainterSortDesSmallest = new ImagePainter(imageSortDesSmallest, false); + Image imageSortNone = IconUtility.getIconImage(IconUtility.ICO_SORT_NONE, getClass()); + imagePainterSortNone = new ImagePainter(imageSortNone, false); + Image imageLock = IconUtility.getIconSmallImage(IconUtility.ICON_COLUMN_EDIT_LOCK, getClass()); + imagePainterLock = new ImagePainter(imageLock); + } + + /** + * Paint cell. + * + * @param cell the cell + * @param gc the gc + * @param adjustedCellBounds the adjusted cell bounds + * @param configRegistry the config registry + */ + @Override + public void paintCell(ILayerCell cell, GC gc, Rectangle adjustedCellBounds, IConfigRegistry configRegistry) { + + LabelStack configLabels = cell.getConfigLabels(); + + boolean hasLock = configLabels.hasLabel(IEditTableGridStyleLabelFactory.COL_HEADER_LABEL_READONLY_CELL); + boolean hasSortAsc = configLabels.hasLabel(SORT_UP_CONFIG_TYPE); + boolean hasSortDes = configLabels.hasLabel(SORT_DOWN_CONFIG_TYPE); + boolean isSortPriorityOne = configLabels.hasLabel(CONFIG_TYPE_SORT_SEQ + 0); + boolean isSortPriorityTwo = configLabels.hasLabel(CONFIG_TYPE_SORT_SEQ + 1); + + if (hasLock) { + paintCellLock(cell, gc, adjustedCellBounds, configRegistry, hasSortAsc, hasSortDes, isSortPriorityOne, + isSortPriorityTwo); + } else { + paintCellNoLock(cell, gc, adjustedCellBounds, configRegistry, hasSortAsc, hasSortDes, isSortPriorityOne, + isSortPriorityTwo); + } + } + + private void paintCellNoLock(ILayerCell cell, GC gc, Rectangle adjustedCellBounds, IConfigRegistry configRegistry, + boolean hasSortAsc, boolean hasSortDes, boolean isSortPriorityOne, boolean isSortPriorityTwo) { + if (hasSortAsc) { + paintCellNoLockAsc(cell, gc, adjustedCellBounds, configRegistry, isSortPriorityOne, isSortPriorityTwo); + } else if (hasSortDes) { + paintCellNoLockDesc(cell, gc, adjustedCellBounds, configRegistry, isSortPriorityOne, isSortPriorityTwo); + } else { + this.noLockNoSort.paintCell(cell, gc, adjustedCellBounds, configRegistry); + } + } + + private void paintCellLock(ILayerCell cell, GC gc, Rectangle adjustedCellBounds, IConfigRegistry configRegistry, + boolean hasSortAsc, boolean hasSortDes, boolean isSortPriorityOne, boolean isSortPriorityTwo) { + if (hasSortAsc) { + paintCellLockAsc(cell, gc, adjustedCellBounds, configRegistry, isSortPriorityOne, isSortPriorityTwo); + } else if (hasSortDes) { + paintCellLockDesc(cell, gc, adjustedCellBounds, configRegistry, isSortPriorityOne, isSortPriorityTwo); + } else { + this.lockNoSort.paintCell(cell, gc, adjustedCellBounds, configRegistry); + } + } + + private void paintCellNoLockDesc(ILayerCell cell, GC gc, Rectangle adjustedCellBounds, + IConfigRegistry configRegistry, boolean isSortPriorityOne, boolean isSortPriorityTwo) { + if (isSortPriorityOne) { + this.noLockDesSort.paintCell(cell, gc, adjustedCellBounds, configRegistry); + } else if (isSortPriorityTwo) { + this.noLockDesSortSmaller.paintCell(cell, gc, adjustedCellBounds, configRegistry); + } else { + this.noLockDesSortSmallest.paintCell(cell, gc, adjustedCellBounds, configRegistry); + } + } + + private void paintCellNoLockAsc(ILayerCell cell, GC gc, Rectangle adjustedCellBounds, + IConfigRegistry configRegistry, boolean isSortPriorityOne, boolean isSortPriorityTwo) { + if (isSortPriorityOne) { + this.noLockAscSort.paintCell(cell, gc, adjustedCellBounds, configRegistry); + } else if (isSortPriorityTwo) { + this.noLockAscSortSmaller.paintCell(cell, gc, adjustedCellBounds, configRegistry); + } else { + this.noLockAscSortSmallest.paintCell(cell, gc, adjustedCellBounds, configRegistry); + } + } + + private void paintCellLockDesc(ILayerCell cell, GC gc, Rectangle adjustedCellBounds, IConfigRegistry configRegistry, + boolean isSortPriorityOne, boolean isSortPriorityTwo) { + if (isSortPriorityOne) { + this.lockDesSort.paintCell(cell, gc, adjustedCellBounds, configRegistry); + } else if (isSortPriorityTwo) { + this.lockDesSortSmaller.paintCell(cell, gc, adjustedCellBounds, configRegistry); + } else { + this.lockDesSortSmallest.paintCell(cell, gc, adjustedCellBounds, configRegistry); + } + } + + private void paintCellLockAsc(ILayerCell cell, GC gc, Rectangle adjustedCellBounds, IConfigRegistry configRegistry, + boolean isSortPriorityOne, boolean isSortPriorityTwo) { + if (isSortPriorityOne) { + this.lockAscSort.paintCell(cell, gc, adjustedCellBounds, configRegistry); + } else if (isSortPriorityTwo) { + this.lockAscSortSmaller.paintCell(cell, gc, adjustedCellBounds, configRegistry); + } else { + this.lockAscSortSmallest.paintCell(cell, gc, adjustedCellBounds, configRegistry); + } + } + + /** + * On pre destroy. + */ + public void onPreDestroy() { + imagePainterLock = null; + imagePainterSortNone = null; + imagePainterSortDes = null; + imagePainterSortDesSmaller = null; + imagePainterSortDesSmallest = null; + imagePainterSortAsc = null; + imagePainterSortAscSmaller = null; + imagePainterSortAscSmallest = null; + noLockNoSort = null; + noLockAscSort = null; + noLockAscSortSmaller = null; + noLockAscSortSmallest = null; + noLockDesSort = null; + noLockDesSortSmaller = null; + noLockDesSortSmallest = null; + lockNoSort = null; + lockAscSort = null; + lockAscSortSmaller = null; + lockAscSortSmallest = null; + lockDesSort = null; + lockDesSortSmaller = null; + lockDesSortSmallest = null; + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/SystemClipboardWrapper.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/SystemClipboardWrapper.java new file mode 100644 index 0000000000000000000000000000000000000000..cc2b450bf4ee671a742bf5dffff5164e26804900 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/SystemClipboardWrapper.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import org.eclipse.nebula.widgets.nattable.copy.InternalCellClipboard; +import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell; + +/** + * + * Title: class + * + * Description: The Class SystemClipboardWrapper. + * + * @since 3.0.0 + */ +public class SystemClipboardWrapper extends InternalCellClipboard { + + /** + * Gets the copied cells. + * + * @return the copied cells + */ + @Override + public ILayerCell[][] getCopiedCells() { + return super.getCopiedCells(); + } + + /** + * Sets the copied cells. + * + * @param copiedCells the new copied cells + */ + @Override + public void setCopiedCells(ILayerCell[][] copiedCells) { + super.setCopiedCells(copiedCells); + } + + /** + * Clear. + */ + @Override + public void clear() { + super.clear(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/TreeDataGrid.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/TreeDataGrid.java new file mode 100644 index 0000000000000000000000000000000000000000..56a6c85b88e7429e406600d0ea5e596e45e240b5 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/TreeDataGrid.java @@ -0,0 +1,510 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import java.util.List; +import java.util.Map; + +import org.eclipse.jface.layout.GridDataFactory; +import org.eclipse.nebula.widgets.nattable.data.IColumnPropertyAccessor; +import org.eclipse.nebula.widgets.nattable.data.IDataProvider; +import org.eclipse.nebula.widgets.nattable.data.ListDataProvider; +import org.eclipse.nebula.widgets.nattable.data.ReflectiveColumnPropertyAccessor; +import org.eclipse.nebula.widgets.nattable.extension.glazedlists.GlazedListsEventLayer; +import org.eclipse.nebula.widgets.nattable.extension.glazedlists.tree.GlazedListTreeData; +import org.eclipse.nebula.widgets.nattable.extension.glazedlists.tree.GlazedListTreeRowModel; +import org.eclipse.nebula.widgets.nattable.grid.GridRegion; +import org.eclipse.nebula.widgets.nattable.grid.data.DefaultRowHeaderDataProvider; +import org.eclipse.nebula.widgets.nattable.grid.layer.ColumnHeaderLayer; +import org.eclipse.nebula.widgets.nattable.grid.layer.CornerLayer; +import org.eclipse.nebula.widgets.nattable.grid.layer.DefaultColumnHeaderDataLayer; +import org.eclipse.nebula.widgets.nattable.grid.layer.DefaultRowHeaderDataLayer; +import org.eclipse.nebula.widgets.nattable.grid.layer.GridLayer; +import org.eclipse.nebula.widgets.nattable.grid.layer.RowHeaderLayer; +import org.eclipse.nebula.widgets.nattable.layer.AbstractLayerTransform; +import org.eclipse.nebula.widgets.nattable.layer.DataLayer; +import org.eclipse.nebula.widgets.nattable.layer.LabelStack; +import org.eclipse.nebula.widgets.nattable.layer.cell.ColumnLabelAccumulator; +import org.eclipse.nebula.widgets.nattable.painter.NatTableBorderOverlayPainter; +import org.eclipse.nebula.widgets.nattable.reorder.ColumnReorderLayer; +import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer; +import org.eclipse.nebula.widgets.nattable.tree.ITreeRowModel; +import org.eclipse.nebula.widgets.nattable.tree.TreeLayer; +import org.eclipse.nebula.widgets.nattable.tree.config.TreeLayerExpandCollapseKeyBindings; +import org.eclipse.swt.widgets.Composite; + +import org.opengauss.mppdbide.explainplan.ui.model.ExplainAnalyzePlanNodeTreeDisplayData; +import org.opengauss.mppdbide.explainplan.ui.model.ExplainAnalyzePlanNodeTreeDisplayDataTreeFormat; +import org.opengauss.mppdbide.explainplan.ui.model.TreeGridColumnHeader; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.utils.observer.DSEventTable; +import org.opengauss.mppdbide.utils.observer.IDSGridUIListenable; +import org.opengauss.mppdbide.view.component.DSGridStateMachine; +import org.opengauss.mppdbide.view.component.IGridUIPreference; +import org.opengauss.mppdbide.view.component.grid.DSGridToolTipProvider; +import org.opengauss.mppdbide.view.component.grid.TableGridStyleConfiguration; + +import ca.odell.glazedlists.EventList; +import ca.odell.glazedlists.FilterList; +import ca.odell.glazedlists.GlazedLists; +import ca.odell.glazedlists.SortedList; +import ca.odell.glazedlists.TransformedList; +import ca.odell.glazedlists.TreeList; + +/** + * + * Title: class + * + * Description: The Class TreeDataGrid. + * + * @since 3.0.0 + */ +public class TreeDataGrid extends DataGrid { + private Map columnLabelMap; + private List modelData; + private Composite shell; + private BodyLayerStack bodyLayerStack; + private IColumnPropertyAccessor columnPropertyAccessor; + private ExecutionPlanNodeTypeConfiguration planNodeStyleConfig; + + /** + * On pre destroy. + */ + @Override + public void onPreDestroy() { + if (this.planNodeStyleConfig != null) { + this.planNodeStyleConfig.preDestroy(); + } + this.columnPropertyAccessor = null; + if (this.bodyLayerStack != null) { + this.bodyLayerStack.preDestroy(); + } + this.bodyLayerStack = null; + + if (this.modelData != null) { + this.modelData.clear(); + } + if (this.columnLabelMap != null) { + this.columnLabelMap.clear(); + } + this.modelData = null; + this.columnLabelMap = null; + super.onPreDestroy(); + } + + /** + * Gets the model data. + * + * @return the model data + */ + public List getModelData() { + return modelData; + } + + /** + * Sets the model data. + * + * @param modelData the new model data + */ + public void setModelData(List modelData) { + if (this.modelData != null) { + this.modelData.clear(); + } + this.modelData = modelData; + } + + /** + * Gets the column label map. + * + * @return the column label map + */ + public Map getColumnLabelMap() { + return this.columnLabelMap; + } + + /** + * Sets the column label map. + * + * @param columnLabelMap the column label map + */ + public void setColumnLabelMap(Map columnLabelMap) { + this.columnLabelMap = columnLabelMap; + } + + /** + * Instantiates a new tree data grid. + * + * @param uiPref the ui pref + * @param dataProvider the data provider + * @param eventTable the event table + * @param stateMachine the state machine + */ + public TreeDataGrid(IGridUIPreference uiPref, ExplainAnalyzePlanNodeTreeDisplayDataTreeFormat dataProvider, + DSEventTable eventTable, DSGridStateMachine stateMachine) { + super(uiPref, dataProvider, eventTable, stateMachine); + this.dataGrid = null; + this.modelData = dataProvider.getNodes(); + } + + /** + * Sets the focus. + */ + public void setFocus() { + this.dataGrid.setFocus(); + } + + /** + * Gets the data grid. + * + * @return the data grid + */ + public DSNatTable getDataGrid() { + return this.dataGrid; + } + + /** + * Update grid data. + */ + public void updateGridData() { + refresh(); + } + + /** + * Creates the all layer data providers. + */ + @Override + protected void createAllLayerDataProviders() { + columnPropertyAccessor = new ReflectiveColumnPropertyAccessor<>( + this.dataProvider.getColumnDataProvider().getColumnNames()); + + this.bodyLayerStack = new BodyLayerStack<>(this.modelData, columnPropertyAccessor, + (ExplainAnalyzePlanNodeTreeDisplayDataTreeFormat) this.dataProvider); + + // build the column header layer + columnHeaderDataProvider = new GridColHeaderDataProvider(this.dataProvider); + columnHeaderDataLayer = new DefaultColumnHeaderDataLayer(columnHeaderDataProvider); + columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, bodyLayerStack, + bodyLayerStack.getSelectionLayer()); + + // build the row header layer + rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyLayerStack.getBodyDataProvider()); + rowHeaderDataLayer = new DefaultRowHeaderDataLayer(rowHeaderDataProvider); + rowHeaderLayer = new RowHeaderLayer(rowHeaderDataLayer, bodyLayerStack, bodyLayerStack.getSelectionLayer()); + + // build the corner layer + this.cornerDataProvider = new GridCornerLayerDataProvider(dataContext); + bodyDataLayer = new DataLayer(bodyLayerStack.getBodyDataProvider()); + + cornerLayer = new CornerLayer(bodyDataLayer, rowHeaderLayer, columnHeaderLayer); + + gridLayer = new GridLayer(bodyLayerStack, columnHeaderLayer, rowHeaderLayer, cornerLayer); + + this.dataEventList = bodyLayerStack.getEventList(); + this.dataFilterList = bodyLayerStack.getFilterList(); + this.reorderLayer = bodyLayerStack.getReorderLayer(); + this.selectionLayer = bodyLayerStack.getSelectionLayer(); + this.viewportLayer = bodyLayerStack.getViewportLayer(); + + configureSelectionCopyWithPref(gridLayer); + } + + /** + * Enable header tool tip. + */ + @Override + protected void enableHeaderToolTip() { + dsGridToolTipProvider = new DSGridToolTipProvider(this.dataGrid, new String[] {GridRegion.BODY}, dataContext, + this.bodyDataProvider, uiPref.isEnableEdit()); + } + + /** + * + * Title: class + * + * Description: The Class BodyLayerStack. + * + * @param the generic type + */ + static class BodyLayerStack extends AbstractLayerTransform { + + private final IDataProvider bodyDataProvider; + + private final SelectionLayer selectionLayer; + + private final TreeLayer treeLayer; + + private EventList eventList; + + private TransformedList rowObjectsGlazedList; + + private ColumnReorderLayer reorderLayer; + + private GridViewPortLayer viewportLayer; + + /** + * Pre destroy. + */ + public void preDestroy() { + if (this.eventList != null) { + this.eventList.clear(); + } + this.eventList = null; + this.rowObjectsGlazedList = null; + this.reorderLayer = null; + this.viewportLayer = null; + } + + /** + * Instantiates a new body layer stack. + * + * @param values the values + * @param columnPropertyAccessor the column property accessor + * @param treeFormat the tree format + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + public BodyLayerStack(List values, IColumnPropertyAccessor columnPropertyAccessor, + TreeList.Format treeFormat) { + + eventList = GlazedLists.eventList(values); + rowObjectsGlazedList = GlazedLists.threadSafeList(eventList); + + SortedList sortedList = new SortedList<>(rowObjectsGlazedList, null); + + TreeList treeList = new TreeList(sortedList, treeFormat, TreeList.NODES_START_EXPANDED); + + this.bodyDataProvider = new ListDataProvider<>(treeList, columnPropertyAccessor); + DataLayer bodyDataLayer = new DataLayer(this.bodyDataProvider); + + TreeGridColumnAccumulator columnLabelAccumulator = new TreeGridColumnAccumulator(this.bodyDataProvider, + (ReflectiveColumnPropertyAccessor) columnPropertyAccessor); + bodyDataLayer.setConfigLabelAccumulator(columnLabelAccumulator); + + bodyDataLayer.setDefaultColumnWidthByPosition(0, 150); + // lets keep the node type column little wider + + GlazedListsEventLayer glazedListsEventLayer = new GlazedListsEventLayer<>(bodyDataLayer, treeList); + + GlazedListTreeData treeData = new GlazedListTreeData<>(treeList); + ITreeRowModel treeRowModel = new GlazedListTreeRowModel<>(treeData); + + this.reorderLayer = new ColumnReorderLayer(glazedListsEventLayer); + + this.selectionLayer = new SelectionLayer(this.reorderLayer); + + this.treeLayer = new TreeLayer(this.selectionLayer, treeRowModel); + this.treeLayer.setUseTreeColumnIndex(true); + viewportLayer = new GridViewPortLayer(this.treeLayer); + + setUnderlyingLayer(viewportLayer); + } + + private GridViewPortLayer getViewportLayer() { + return this.viewportLayer; + } + + private SelectionLayer getSelectionLayer() { + return this.selectionLayer; + } + + private TreeLayer getTreeLayer() { + return this.treeLayer; + } + + private IDataProvider getBodyDataProvider() { + return this.bodyDataProvider; + } + + private ColumnReorderLayer getReorderLayer() { + return reorderLayer; + } + + @SuppressWarnings("unchecked") + private EventList getEventList() { + return (EventList) eventList; + } + + /** + * Gets the filter list. + * + * @return the filter list + */ + @SuppressWarnings("unchecked") + public FilterList getFilterList() { + return (FilterList) new FilterList(rowObjectsGlazedList); + } + } + + /** + * Input changed. + * + * @param newDataProvider the new data provider + * @param preserveScrollPos the preserve scroll pos + */ + public void inputChanged(IDSGridDataProvider newDataProvider, boolean preserveScrollPos) { + saveReorderState(); + super.setDataProvider(newDataProvider); + setModelData(((ExplainAnalyzePlanNodeTreeDisplayDataTreeFormat) newDataProvider).getNodes()); + + createAllLayerDataProviders(); + + gridLayer.addConfiguration(new DSGridLayerConfiguration(gridLayer)); + dataGrid.setLayer(gridLayer); + + configureGridStyle(); + + enableHeaderToolTip(); + + dataGrid.configure(); + refresh(); + GridDataFactory.fillDefaults().grab(true, true).applyTo(dataGrid); + + restoreReorderState(); + + this.eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_POST_GRID_DATA_LOAD, this.dataProvider)); + this.eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_CHANGED, this.dataProvider)); + + } + + /** + * Refresh. + */ + @Override + public void refresh() { + this.dataGrid.refresh(true); + } + + /** + * Creates the component. + * + * @param gridAreaComposite the grid area composite + */ + @Override + public void createComponent(Composite gridAreaComposite) { + this.shell = gridAreaComposite; + setDataProvider(getDataProvider()); + + createAllLayerDataProviders(); + + dataGrid = new DSNatTable(this.shell, gridLayer, false); + + GridDataFactory.fillDefaults().grab(true, true).applyTo(dataGrid); + // create a new ConfigRegistry which will be needed for GlazedLists + // handling + dataGrid.setConfigRegistry(getConfigRegistry()); + + configureGridStyle(); + + enableHeaderToolTip(); + + gridLayer.addConfiguration(new DSGridLayerConfiguration(gridLayer)); + dataGrid.configure(); + this.dataGrid.addOverlayPainter(new NatTableBorderOverlayPainter()); + + registerDisposedListener(); + } + + /** + * Configure grid style. + */ + @Override + protected void configureGridStyle() { + this.dataGrid.addConfiguration(new TableGridStyleConfiguration(getRegexMarkup(), uiPref, dataContext)); + + this.planNodeStyleConfig = new ExecutionPlanNodeTypeConfiguration(dataProvider); + dataGrid.addConfiguration(planNodeStyleConfig); + + dataGrid.addConfiguration(new TreeLayerExpandCollapseKeyBindings(bodyLayerStack.getTreeLayer(), + bodyLayerStack.getSelectionLayer())); + } + + /** + * + * Title: class + * + * Description: The Class TreeGridColumnAccumulator. + */ + @SuppressWarnings("rawtypes") + public static class TreeGridColumnAccumulator extends ColumnLabelAccumulator { + + /** + * The list data. + */ + ListDataProvider listData; + + /** + * The column prop accessor. + */ + ReflectiveColumnPropertyAccessor columnPropAccessor; + + /** + * Instantiates a new tree grid column accumulator. + * + * @param bodyDataProvider the body data provider + * @param columnPropertyAccessor the column property accessor + */ + public TreeGridColumnAccumulator(IDataProvider bodyDataProvider, + ReflectiveColumnPropertyAccessor columnPropertyAccessor) { + this.listData = (ListDataProvider) bodyDataProvider; + this.columnPropAccessor = columnPropertyAccessor; + } + + /** + * Accumulate config labels. + * + * @param configLabels the config labels + * @param columnPosition the column position + * @param rowPosition the row position + */ + @Override + public void accumulateConfigLabels(LabelStack configLabels, int columnPosition, int rowPosition) { + super.accumulateConfigLabels(configLabels, columnPosition, rowPosition); + try { + addPlanAnalysisLabelOnCells(configLabels, columnPosition, rowPosition); + } catch (MPPDBIDEException exception) { + MPPDBIDELoggerUtility.error("error while assigning column labels", exception); + } + } + + private void addPlanAnalysisLabelOnCells(LabelStack configLabels, int columnPosition, int rowPosition) + throws MPPDBIDEException { + + ExplainAnalyzePlanNodeTreeDisplayData rowData = (ExplainAnalyzePlanNodeTreeDisplayData) this.listData + .getRowObject(rowPosition); + + if (rowData.isHeaviest()) { + if (columnPropAccessor.getColumnProperty(columnPosition) + .equals(TreeGridColumnHeader.PROP_ACTUAL_ROWS)) { + configLabels.addLabel(TreeGridColumnHeader.COLUMN_LABEL_HEAVIEST); + } + } + if (rowData.isCostliest()) { + if (columnPropAccessor.getColumnProperty(columnPosition).equals(TreeGridColumnHeader.PROP_TOTAL_COST)) { + configLabels.addLabel(TreeGridColumnHeader.COLUMN_LABEL_COSTLIEST); + } + } + if (rowData.isSlowest()) { + if (columnPropAccessor.getColumnProperty(columnPosition) + .equals(TreeGridColumnHeader.PROP_ACTUAL_TOTAL_TIME)) { + configLabels.addLabel(TreeGridColumnHeader.COLUMN_LABEL_SLOWEST); + } + } + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/ViewportSelectColumnActionWrapper.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/ViewportSelectColumnActionWrapper.java new file mode 100644 index 0000000000000000000000000000000000000000..c0c7ecc0f7857c8b6eb8494b103a209d3f102c17 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/core/ViewportSelectColumnActionWrapper.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.core; + +import org.eclipse.nebula.widgets.nattable.NatTable; +import org.eclipse.nebula.widgets.nattable.viewport.action.ViewportSelectColumnAction; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.graphics.Image; + +import org.opengauss.mppdbide.view.utils.icon.IconUtility; + +/** + * + * Title: class + * + * Description: The Class ViewportSelectColumnActionWrapper. + * + * @since 3.0.0 + */ +public class ViewportSelectColumnActionWrapper extends ViewportSelectColumnAction { + + /** + * Instantiates a new viewport select column action wrapper. + * + * @param withShiftMask the with shift mask + * @param withControlMask the with control mask + */ + public ViewportSelectColumnActionWrapper(boolean withShiftMask, boolean withControlMask) { + super(withShiftMask, withControlMask); + } + + /** + * Run. + * + * @param natTable the nat table + * @param event the event + */ + @Override + public void run(NatTable natTable, MouseEvent event) { + if ((event.stateMask & SWT.MOD3) == SWT.MOD3) { + return; + } else if (((event.stateMask & SWT.MOD1) == SWT.MOD1) || ((event.stateMask & SWT.MOD2) == SWT.MOD2)) { + super.run(natTable, event); + } else { + int colPos = natTable.getColumnPositionByX(event.x); + int columnWidth = natTable.getColumnWidthByPosition(colPos); + int columnHeight = natTable.getRowHeightByPosition(0); + int startXOfColumn = natTable.getStartXOfColumnPosition(colPos); + int startYOfColumn = natTable.getStartYOfRowPosition(0); + /* Dimension of all sort images is same */ + Image myImage = IconUtility.getIconSmallImage(IconUtility.ICO_SORT_NONE, getClass()); + int sortImageWidth = myImage.getBounds().width; + + /* + * A buffer of 3 pixel is added between image right edge and cell + * edge to avoid sorting during cell resize + */ + if ((event.x >= startXOfColumn + columnWidth - sortImageWidth - 3) + && (event.x <= startXOfColumn + columnWidth - 3) && (event.y >= startYOfColumn) + && (event.y <= startYOfColumn + columnHeight)) { + return; + } else { + super.run(natTable, event); + } + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/editor/CustomComboBoxCellEditor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/editor/CustomComboBoxCellEditor.java new file mode 100644 index 0000000000000000000000000000000000000000..9d6c88b6ee1084e7084fbfe0ff95fd9c0c2a1e4f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/editor/CustomComboBoxCellEditor.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.editor; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.nebula.widgets.nattable.edit.editor.ComboBoxCellEditor; +import org.eclipse.nebula.widgets.nattable.edit.editor.IComboBoxDataProvider; + +import org.opengauss.mppdbide.presentation.objectproperties.PropertiesConstants; + +/** + * + * Title: class + * + * Description: The Class CustomComboBoxCellEditor. + * + * @since 3.0.0 + */ +public class CustomComboBoxCellEditor extends ComboBoxCellEditor implements ICustomComboBoxCellEditor { + + /** + * Instantiates a new custom combo box cell editor. + * + * @param comboBoxDataProvider the combo box data provider + * @param maxVisibleItems the max visible items + */ + public CustomComboBoxCellEditor(IComboBoxDataProvider comboBoxDataProvider, int maxVisibleItems) { + super(comboBoxDataProvider, maxVisibleItems); + } + + /** + * Gets the canonical value. + * + * @return the canonical value + */ + @Override + public Object getCanonicalValue() { + Object canonicalValue = super.getCanonicalValue(); + if (canonicalValue instanceof List) { + List list = (List) canonicalValue; + if (1 == list.size() && null == list.get(0)) { + return ""; + } + } + return canonicalValue == null ? null : canonicalValue.toString(); + } + + /** + * Sets the canonical value. + * + * @param canonicalValue the new canonical value + */ + @Override + public void setCanonicalValue(Object canonicalValue) { + List list = new ArrayList<>(); + String valueStr = ""; + if (canonicalValue instanceof String) { + valueStr = (String) canonicalValue; + if (valueStr.contains("[") && valueStr.contains("]")) { + valueStr = valueStr.substring(1, valueStr.length() - 1); + String[] splitStr = valueStr.split(PropertiesConstants.SPLIT_STR); + for (int i = 0; i < splitStr.length; i++) { + list.add(splitStr[i].trim()); + } + } + } + super.setCanonicalValue(list.isEmpty() ? valueStr.trim() : list); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/editor/CustomDateCellEditor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/editor/CustomDateCellEditor.java new file mode 100644 index 0000000000000000000000000000000000000000..6722a48cc9bb111c3ee5a490d7c43b31dafe3ad9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/editor/CustomDateCellEditor.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.editor; + +import java.text.SimpleDateFormat; + +import org.eclipse.nebula.widgets.nattable.extension.nebula.cdatetime.CDateTimeCellEditor; + +/** + * + * Title: class + * + * Description: The Class CustomDateCellEditor. + * + * @since 3.0.0 + */ +public class CustomDateCellEditor extends CDateTimeCellEditor implements ICustomDateCellEditor { + + private final SimpleDateFormat sdf; + private final Object INSTANCE_LOCK = new Object(); + + /** + * Instantiates a new custom date cell editor. + * + * @param format the format + * @param moveSelectionOnEnter the move selection on enter + * @param style the style + */ + public CustomDateCellEditor(String format, boolean moveSelectionOnEnter, int style) { + super(moveSelectionOnEnter, style); + this.sdf = new SimpleDateFormat(format); + } + + /** + * Sets the canonical value. + * + * @param canonicalValue the new canonical value + */ + @Override + public void setCanonicalValue(Object canonicalValue) { + // canonicalValue is the current value of editor + super.setCanonicalValue(canonicalValue); + } + + /** + * Gets the canonical value. + * + * @return the canonical value + */ + @Override + public Object getCanonicalValue() { + Object canonicalVal = null; + synchronized (INSTANCE_LOCK) { + canonicalVal = getEditorValue() == null ? "" : this.sdf.format(getEditorValue()); + } + // dataValue is the old value at the NatTable + Object dataValue = this.layerCell.getDataValue(); + if (dataValue instanceof String) { + return canonicalVal; + } + return super.getCanonicalValue(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/editor/ICustomComboBoxCellEditor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/editor/ICustomComboBoxCellEditor.java new file mode 100644 index 0000000000000000000000000000000000000000..2d7748fdab9218971e3bf83edb1db3d5e6d3fe1a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/editor/ICustomComboBoxCellEditor.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.editor; + +/** + * + * Title: interface + * + * Description: The Interface ICustomComboBoxCellEditor. + * + * @since 3.0.0 + */ +public interface ICustomComboBoxCellEditor { + + /** + * Gets the canonical value. + * + * @return the canonical value + */ + Object getCanonicalValue(); + + /** + * Sets the canonical value. + * + * @param canonicalValue the new canonical value + */ + void setCanonicalValue(Object canonicalValue); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/editor/ICustomDateCellEditor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/editor/ICustomDateCellEditor.java new file mode 100644 index 0000000000000000000000000000000000000000..92406646f60e0367ae2ed0ea3899e08095542eee --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/editor/ICustomDateCellEditor.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.editor; + +/** + * + * Title: interface + * + * Description: The Interface ICustomDateCellEditor. + * + * @since 3.0.0 + */ +public interface ICustomDateCellEditor { + + /** + * Sets the canonical value. + * + * @param canonicalValue the new canonical value + */ + void setCanonicalValue(Object canonicalValue); + + /** + * Gets the canonical value. + * + * @return the canonical value + */ + Object getCanonicalValue(); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/listeners/MultiColumnSortPoUpListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/listeners/MultiColumnSortPoUpListener.java new file mode 100644 index 0000000000000000000000000000000000000000..208242851c9c6c4ce5dff11cd567f9f2552bc33c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/listeners/MultiColumnSortPoUpListener.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.listeners; + +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; + +import org.opengauss.mppdbide.view.component.grid.core.DataGrid; +import org.opengauss.mppdbide.view.component.grid.sort.SortPopUpDialog; + +/** + * Title: MultiColumnSortPoUpListener + * + * Description:The listener interface for receiving multiColumnSortPoUp events. + * The class that is interested in processing a multiColumnSortPoUp event + * implements this interface, and the object created with that class is + * registered with a component using the component's + * addMultiColumnSortPoUpListener method. When the + * multiColumnSortPoUp event occurs, that object's appropriate method is + * invoked. + * + * @since 3.0.0 + */ +public class MultiColumnSortPoUpListener implements SelectionListener { + + /** + * The grid. + */ + DataGrid grid; + + /** + * Gets the data grid. + * + * @return the data grid + */ + public DataGrid getDataGrid() { + return grid; + } + + /** + * Instantiates a new multi column sort po up listener. + * + * @param grid the grid + */ + public MultiColumnSortPoUpListener(DataGrid grid) { + this.grid = grid; + } + + /** + * Widget selected. + * + * @param e the e + */ + @Override + public void widgetSelected(SelectionEvent e) { + SortPopUpDialog dialog = new SortPopUpDialog(getDataGrid()); + dialog.open(); + + } + + /** + * Widget default selected. + * + * @param e the e + */ + @Override + public void widgetDefaultSelected(SelectionEvent e) { + + } + + /** + * On pre destroy. + */ + public void onPreDestroy() { + this.grid = null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/sort/MulticolumnSortConstants.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/sort/MulticolumnSortConstants.java new file mode 100644 index 0000000000000000000000000000000000000000..a1599aac6cf045f6c6cf646babde0dc09292efe6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/sort/MulticolumnSortConstants.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.sort; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: interface + * + * Description: The Interface MulticolumnSortConstants. + * + * @since 3.0.0 + */ +public interface MulticolumnSortConstants { + + /** + * The Constant PRIORITY_INDEX. + */ + public static final int PRIORITY_INDEX = 0; + + /** + * The Constant COLUMN_INDEX. + */ + public static final int COLUMN_INDEX = 1; + + /** + * The Constant DATATYPE_INDEX. + */ + public static final int DATATYPE_INDEX = 2; + + /** + * The Constant ORDER_INDEX. + */ + public static final int ORDER_INDEX = 3; + + /** + * The Constant BUFFER_LEN. + */ + public static final int BUFFER_LEN = 10; + + /** + * The Constant PRIORITY_COL_LEN. + */ + public static final int PRIORITY_COL_LEN = 5 * BUFFER_LEN; + + /** + * The Constant COLNAME_COL_LEN. + */ + public static final int COLNAME_COL_LEN = MessageConfigLoader.getProperty(IMessagesConstants.COMBO_TEXT_SORT_COLUMN) + .length() * BUFFER_LEN; + + /** + * The Constant ORDER_COL_LEN. + */ + public static final int ORDER_COL_LEN = MessageConfigLoader.getProperty(IMessagesConstants.COMBO_TEXT_SORT_OREDER) + .length() * BUFFER_LEN; + + /** + * The Constant DATATYPE_COL_LEN. + */ + public static final int DATATYPE_COL_LEN = MessageConfigLoader.getProperty(IMessagesConstants.COLUMN_DATATYPE) + .length() * BUFFER_LEN; + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/sort/SortColumnComboEditingSupport.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/sort/SortColumnComboEditingSupport.java new file mode 100644 index 0000000000000000000000000000000000000000..45c6978522f41c25852230770b4c4cdca1723f4f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/sort/SortColumnComboEditingSupport.java @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.sort; + +import java.util.Arrays; + +import org.eclipse.jface.viewers.CellEditor; +import org.eclipse.jface.viewers.ComboBoxCellEditor; +import org.eclipse.jface.viewers.EditingSupport; +import org.eclipse.jface.viewers.TableViewer; +import org.eclipse.swt.SWT; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class SortColumnComboEditingSupport.implements + * ITableColorProvider + * + * @since 3.0.0 + */ +public class SortColumnComboEditingSupport extends EditingSupport { + private final TableViewer viewer; + private final CellEditor editor; + private String[] comboOptions = null; + private String defaultComboText = null; + private String[] datatypes = null; + private static final String[] SORT_ORDER = { + MessageConfigLoader.getProperty(IMessagesConstants.COMBO_OPTION_ASCENDING), + MessageConfigLoader.getProperty(IMessagesConstants.COMBO_OPTION_DESCENDING)}; + + /** + * Instantiates a new sort column combo editing support. + * + * @param viewer the viewer + * @param options the options + * @param datatypes the datatypes + * @param noSelText the no sel text + */ + public SortColumnComboEditingSupport(TableViewer viewer, String[] options, String[] datatypes, String noSelText) { + // used for column name combo. Datatype will get filled when column name + // is chosen + super(viewer); + this.viewer = viewer; + this.editor = new ComboBoxCellEditor(this.viewer.getTable(), options, SWT.READ_ONLY); + this.comboOptions = options.clone(); + this.defaultComboText = noSelText; + this.datatypes = datatypes.clone(); + } + + /** + * Instantiates a new sort column combo editing support. + * + * @param viewer the viewer + */ + public SortColumnComboEditingSupport(TableViewer viewer) { + // used by sort order combo. No other field is dependent on it + super(viewer); + this.viewer = viewer; + this.comboOptions = SORT_ORDER; + this.editor = new ComboBoxCellEditor(this.viewer.getTable(), comboOptions, SWT.READ_ONLY); + this.defaultComboText = MessageConfigLoader.getProperty(IMessagesConstants.COMBO_TEXT_SORT_OREDER); + } + + /** + * Gets the cell editor. + * + * @param element the element + * @return the cell editor + */ + @Override + protected CellEditor getCellEditor(Object element) { + return editor; + } + + /** + * Can edit. + * + * @param element the element + * @return true, if successful + */ + @Override + protected boolean canEdit(Object element) { + return true; + } + + /** + * Gets the value. + * + * @param element the element + * @return the value + */ + @Override + protected Object getValue(Object element) { + if (datatypes != null) { + return Arrays.asList(comboOptions).indexOf(((SortColumnSetting) element).getColumnName()); + } else { + return Arrays.asList(comboOptions).indexOf(((SortColumnSetting) element).getSortOrder()); + } + } + + /** + * Sets the value. + * + * @param element the element + * @param value the value + */ + @Override + protected void setValue(Object element, Object value) { + String setVal = ((Integer) value == -1) ? defaultComboText : comboOptions[(int) value]; + + if (datatypes != null) { + ((SortColumnSetting) element).setColumnName(setVal, comboOptions, datatypes); + // datatype and sort_dir gets automatically filled if column name + // chosen + } else { + ((SortColumnSetting) element).setSortOrder(setVal); + } + viewer.update(element, null); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/sort/SortColumnSetting.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/sort/SortColumnSetting.java new file mode 100644 index 0000000000000000000000000000000000000000..71cc2ef3786596e7d34fa2bace3a79d261b0f1f7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/sort/SortColumnSetting.java @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.sort; + +import java.util.Arrays; + +import org.eclipse.nebula.widgets.nattable.sort.SortDirectionEnum; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class SortColumnSetting. + * + * @since 3.0.0 + */ +public class SortColumnSetting { + + /** + * The priority. + */ + String priority; // convert the number to string and store + + /** + * The column name. + */ + String columnName; + + /** + * The data type. + */ + String dataType; + + /** + * The order. + */ + String order; + + /** + * Instantiates a new sort column setting. + */ + public SortColumnSetting() { + this.priority = "0"; + setDefaultSettings(); + } + + private void setDefaultSettings() { + this.columnName = MessageConfigLoader.getProperty(IMessagesConstants.COMBO_TEXT_SORT_COLUMN); + this.dataType = ""; + this.order = MessageConfigLoader.getProperty(IMessagesConstants.COMBO_TEXT_SORT_OREDER); + } + + /** + * Instantiates a new sort column setting. + * + * @param priority the priority + */ + public SortColumnSetting(String priority) { + this.priority = priority; + setDefaultSettings(); + } + + /** + * Instantiates a new sort column setting. + * + * @param priority the priority + * @param columnName the column name + * @param dataType the data type + * @param sortOrder the sort order + */ + public SortColumnSetting(String priority, String columnName, String dataType, String sortOrder) { + this.priority = priority; + this.columnName = columnName; + this.dataType = dataType; + this.order = sortOrder; + } + + /** + * Gets the priority. + * + * @return the priority + */ + public String getPriority() { + return priority; + } + + /** + * Sets the priority. + * + * @param priority the new priority + */ + public void setPriority(String priority) { + this.priority = priority; + } + + /** + * Gets the column name. + * + * @return the column name + */ + public String getColumnName() { + return columnName; + } + + /** + * Sets the column name. + * + * @param colName the col name + * @param cols the cols + * @param datatypes the datatypes + */ + public void setColumnName(String colName, String[] cols, String[] datatypes) { + this.columnName = colName; + int index = Arrays.asList(cols).indexOf((String) columnName); + if (index != -1) { + this.setDataType(datatypes[index]); + if (MessageConfigLoader.getProperty(IMessagesConstants.COMBO_TEXT_SORT_OREDER).equals(getSortOrder())) { + // if no dir chosen, set ascending + this.setSortOrder(MessageConfigLoader.getProperty(IMessagesConstants.COMBO_OPTION_ASCENDING)); + } + } + } + + /** + * Gets the data type. + * + * @return the data type + */ + public String getDataType() { + return dataType; + } + + /** + * Sets the data type. + * + * @param dataType the new data type + */ + public void setDataType(String dataType) { + this.dataType = dataType; + } + + /** + * Gets the sort order. + * + * @return the sort order + */ + public String getSortOrder() { + return order; + } + + /** + * Sets the sort order. + * + * @param sortOrder the new sort order + */ + public void setSortOrder(String sortOrder) { + this.order = sortOrder; + } + + /** + * Gets the sort direction enum from combo text. + * + * @param text the text + * @return the sort direction enum from combo text + */ + public static SortDirectionEnum getSortDirectionEnumFromComboText(String text) { + SortDirectionEnum sortEnum = null; + if (MessageConfigLoader.getProperty(IMessagesConstants.COMBO_OPTION_DESCENDING).equals(text)) { + sortEnum = SortDirectionEnum.DESC; + } else { + sortEnum = SortDirectionEnum.ASC; // keep it default + } + return sortEnum; + } + + /** + * Gets the combo text from sort direction enum. + * + * @param dir the dir + * @return the combo text from sort direction enum + */ + public static String getComboTextFromSortDirectionEnum(SortDirectionEnum dir) { + // return ascending index by default + String text = MessageConfigLoader.getProperty(IMessagesConstants.COMBO_OPTION_ASCENDING); + + if (dir == SortDirectionEnum.DESC) { + text = MessageConfigLoader.getProperty(IMessagesConstants.COMBO_OPTION_DESCENDING); + } + return text; + } + + /** + * Gets the priority text. + * + * @return the priority text + */ + public String getPriorityText() { + return String.valueOf(Integer.parseInt(this.priority) + 1); + } + + /** + * Reduce priority. + */ + public void reducePriority() { + this.priority = String.valueOf(Integer.parseInt(this.priority) - 1); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/sort/SortColumnSettingModifier.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/sort/SortColumnSettingModifier.java new file mode 100644 index 0000000000000000000000000000000000000000..ac407639fe75aee29d56b6e7d45a4a50f0925eab --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/sort/SortColumnSettingModifier.java @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.sort; + +import org.eclipse.jface.viewers.ICellModifier; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.swt.widgets.Item; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class SortColumnSettingModifier. + * + * @since 3.0.0 + */ +public class SortColumnSettingModifier implements ICellModifier { + private Viewer viewer; + private String[] cols = null; + private String[] datatypes = null; + private static final String[] COLUMN_HEADERS = {MessageConfigLoader.getProperty(IMessagesConstants.COLUMN_PRIORITY), + MessageConfigLoader.getProperty(IMessagesConstants.COLUMN_COLUMN_NAME), + MessageConfigLoader.getProperty(IMessagesConstants.COLUMN_DATATYPE), + MessageConfigLoader.getProperty(IMessagesConstants.COLUMN_SORT_ORDER)}; + + /** + * Instantiates a new sort column setting modifier. + * + * @param view the view + * @param cols the cols + * @param datatypes the datatypes + */ + public SortColumnSettingModifier(Viewer view, String[] cols, String[] datatypes) { + this.viewer = view; + this.cols = cols.clone(); + this.datatypes = datatypes.clone(); + } + + /** + * Can modify. + * + * @param element the element + * @param property the property + * @return true, if successful + */ + @Override + public boolean canModify(Object element, String property) { + return COLUMN_HEADERS[MulticolumnSortConstants.COLUMN_INDEX].equals(property) + || COLUMN_HEADERS[MulticolumnSortConstants.ORDER_INDEX].equals(property); + } + + /** + * Gets the value. + * + * @param element the element + * @param property the property + * @return the value + */ + @Override + public Object getValue(Object element, String property) { + SortColumnSetting data = (SortColumnSetting) element; + if (COLUMN_HEADERS[MulticolumnSortConstants.COLUMN_INDEX].equals(property)) { + return data.getColumnName(); + } else if (COLUMN_HEADERS[MulticolumnSortConstants.ORDER_INDEX].equals(property)) { + return data.getSortOrder(); + } else if (COLUMN_HEADERS[MulticolumnSortConstants.DATATYPE_INDEX].equals(property)) { + return data.getDataType(); + } else if (COLUMN_HEADERS[MulticolumnSortConstants.PRIORITY_INDEX].equals(property)) { + return data.getPriority(); + } else { + return null; + } + } + + /** + * Modify. + * + * @param elementParam the element param + * @param property the property + * @param value the value + */ + @Override + public void modify(Object elementParam, String property, Object value) { + Object element = elementParam; + if (element instanceof Item) { + element = ((Item) element).getData(); + } + SortColumnSetting data = (SortColumnSetting) element; + if (COLUMN_HEADERS[MulticolumnSortConstants.COLUMN_INDEX].equals(property)) { + data.setColumnName((String) value, cols, datatypes); + } else if (COLUMN_HEADERS[MulticolumnSortConstants.ORDER_INDEX].equals(property)) { + data.setSortOrder((String) value); + } else if (COLUMN_HEADERS[MulticolumnSortConstants.PRIORITY_INDEX].equals(property)) { + data.setPriority((String) value); + } + viewer.refresh(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/sort/SortErrors.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/sort/SortErrors.java new file mode 100644 index 0000000000000000000000000000000000000000..c39e5f145ad29163570b6eab217b846bc3555d9b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/sort/SortErrors.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.sort; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs.MESSAGEDIALOGTYPE; + +/** + * + * Title: class + * + * Description: The Class SortErrors. + * + * @since 3.0.0 + */ +public class SortErrors { + + /** + * + * Title: enum + * + * Description: The Enum SORTERRORTYPE. + */ + public enum SORTERRORTYPE { + + /** + * The blank column. + */ + BLANK_COLUMN, + /** + * The duplicate column. + */ + DUPLICATE_COLUMN, + /** + * The no error. + */ + NO_ERROR; + }; + + /** + * Generate error dialog. + * + * @param err the err + * @param columnDetails the column details + */ + public static void generateErrorDialog(SORTERRORTYPE err, String[] columnDetails) { + String msgDialogTitle = MessageConfigLoader.getProperty(IMessagesConstants.SORT_ERROR_WINDOW_TITLE); + String msg = null; + switch (err) { + case BLANK_COLUMN: { + msg = MessageConfigLoader.getProperty(IMessagesConstants.SORT_ERROR_BLANK_COLUMN, columnDetails[0]); + break; + } + case DUPLICATE_COLUMN: { + msg = MessageConfigLoader.getProperty(IMessagesConstants.SORT_ERROR_DUPLICATE_COLUMN, columnDetails[0], + columnDetails[1]); + break; + } + default: { + break; + } + } + + MPPDBIDEDialogs.generateOKMessageDialogInUI(MESSAGEDIALOGTYPE.ERROR, true, msgDialogTitle, msg); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/sort/SortPopUpDialog.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/sort/SortPopUpDialog.java new file mode 100644 index 0000000000000000000000000000000000000000..192de7c54cc815d055b7b55100bb8c262ddbcc7c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/sort/SortPopUpDialog.java @@ -0,0 +1,559 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.sort; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.EventObject; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.viewers.ColumnLabelProvider; +import org.eclipse.jface.viewers.ColumnViewerEditor; +import org.eclipse.jface.viewers.ColumnViewerEditorActivationEvent; +import org.eclipse.jface.viewers.ColumnViewerEditorActivationStrategy; +import org.eclipse.jface.viewers.ColumnViewerToolTipSupport; +import org.eclipse.jface.viewers.FocusCellOwnerDrawHighlighter; +import org.eclipse.jface.viewers.TableViewer; +import org.eclipse.jface.viewers.TableViewerColumn; +import org.eclipse.jface.viewers.TableViewerEditor; +import org.eclipse.jface.viewers.TableViewerFocusCellManager; +import org.eclipse.nebula.widgets.nattable.sort.SortDirectionEnum; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.TableColumn; + +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.view.component.grid.core.DataGrid; +import org.opengauss.mppdbide.view.component.grid.core.GridSaveSortState; +import org.opengauss.mppdbide.view.component.grid.core.SortEntryData; +import org.opengauss.mppdbide.view.component.grid.sort.SortErrors.SORTERRORTYPE; +import org.opengauss.mppdbide.view.ui.table.IDialogWorkerInteraction; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * + * Title: class + * + * Description: The Class SortPopUpDialog. + * + * @since 3.0.0 + */ +public class SortPopUpDialog extends Dialog implements IDialogWorkerInteraction { + private DataGrid grid; + private Table table; + private TableViewer viewer; + + private String[] colNames = null; + private String[] dataTypes = null; + private List sortColumnsModel = new ArrayList(1); + private static final String[] COLUMN_HEADERS = {MessageConfigLoader.getProperty(IMessagesConstants.COLUMN_PRIORITY), + MessageConfigLoader.getProperty(IMessagesConstants.COLUMN_COLUMN_NAME), + MessageConfigLoader.getProperty(IMessagesConstants.COLUMN_DATATYPE), + MessageConfigLoader.getProperty(IMessagesConstants.COLUMN_SORT_ORDER)}; + private TableViewerFocusCellManager focusCellManager; + + /** + * Instantiates a new sort pop up dialog. + * + * @param grid the grid + */ + public SortPopUpDialog(DataGrid grid) { + super(grid.getDataGrid().getShell()); + this.grid = grid; + this.colNames = grid.getDataProvider().getColumnDataProvider().getColumnNames(); + setDataTypes(grid.getDataProvider()); + } + + private void setDataTypes(IDSGridDataProvider dataProvider) { + this.dataTypes = new String[this.colNames.length]; + for (int index = 0; index < this.colNames.length; index++) { + this.dataTypes[index] = dataProvider.getColumnDataProvider().getColumnDataTypeName(index); + } + } + + /** + * Sets the shell style. + * + * @param arg0 the new shell style + */ + @Override + protected void setShellStyle(int arg0) { + super.setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL | getDefaultOrientation() | SWT.RESIZE); + } + + /** + * Configure shell. + * + * @param shell the shell + */ + @Override + protected void configureShell(Shell shell) { + super.configureShell(shell); + shell.setText(MessageConfigLoader.getProperty(IMessagesConstants.MULTISORT_POPUP_WINDOW_TITLE)); + shell.setImage(IconUtility.getIconImage(IiconPath.ICO_SORT, this.getClass())); + } + + private void swapItems(int selIndex, int otherIndex) { + String selPriority = sortColumnsModel.get(selIndex).getPriority(); + sortColumnsModel.get(selIndex).setPriority(sortColumnsModel.get(otherIndex).getPriority()); + sortColumnsModel.get(otherIndex).setPriority(selPriority); + + Collections.swap(sortColumnsModel, selIndex, otherIndex); + viewer.refresh(); + } + + @SuppressWarnings("rawtypes") + private GridSaveSortState prepareSortSetting() { + if (sortColumnsModel.size() == 0) { + SortErrors.generateErrorDialog(SORTERRORTYPE.BLANK_COLUMN, new String[] {"1"}); + return null; + } + + Object viewerInput = viewer.getInput(); + Object[] inputArray = null; + if (!(viewerInput instanceof ArrayList)) { + return null; + } + inputArray = ((ArrayList) viewerInput).toArray(); + SortColumnSetting[] sortColumns = Arrays.copyOf(inputArray, inputArray.length, SortColumnSetting[].class); + + GridSaveSortState sortState = new GridSaveSortState(); + List columns = new ArrayList(sortColumnsModel.size()); + + for (SortColumnSetting sort : sortColumns) { + int index = Integer.parseInt(sort.getPriority()); + + if (-1 == Arrays.asList(colNames).indexOf(sort.getColumnName())) { + /* + * priority starts from 0 in code, but starts from 1 in + * multicolumn sort popup. So adding 1 in error dialog. + */ + SortErrors.generateErrorDialog(SORTERRORTYPE.BLANK_COLUMN, new String[] {String.valueOf(index + 1)}); + return null; + } + columns.add(sort.getColumnName()); + Set uniqList = new HashSet(columns); + if (uniqList.size() < columns.size()) { + /* + * priority starts from 0 in code, but starts from 1 in + * multicolumn sort popup. So adding 1 in error dialog. + */ + SortErrors.generateErrorDialog(SORTERRORTYPE.DUPLICATE_COLUMN, + new String[] {sort.getColumnName(), String.valueOf(index + 1)}); + return null; + } + SortDirectionEnum sortEnum = SortColumnSetting.getSortDirectionEnumFromComboText(sort.getSortOrder()); + SortEntryData entryData = new SortEntryData(sort.getColumnName(), sortEnum); + sortState.saveSortEntry(entryData); + } + + getShell().close(); // close pop-up only in success case + + return sortState; + } + + private void configureColumnCursor() { + focusCellManager = new TableViewerFocusCellManager(viewer, new FocusCellOwnerDrawHighlighter(viewer)); + ColumnViewerEditorActivationStrategy activationSupport = new ColumnViewerEditorActivationStrategy(viewer) { + + /** + * Checks if is editor activation event. + * + * @param event the event + * @return true, if is editor activation event + */ + protected boolean isEditorActivationEvent(ColumnViewerEditorActivationEvent event) { + if (event.eventType == ColumnViewerEditorActivationEvent.MOUSE_CLICK_SELECTION) { + EventObject source = event.sourceEvent; + if (source instanceof MouseEvent && ((MouseEvent) source).button == 3) { + return false; + + } + } + return super.isEditorActivationEvent(event) + || (event.eventType == ColumnViewerEditorActivationEvent.KEY_PRESSED + && event.keyCode == SWT.CR); + } + }; + + TableViewerEditor.create(viewer, focusCellManager, activationSupport, + ColumnViewerEditor.TABBING_HORIZONTAL | ColumnViewerEditor.TABBING_MOVE_TO_ROW_NEIGHBOR + | ColumnViewerEditor.TABBING_VERTICAL | ColumnViewerEditor.KEYBOARD_ACTIVATION); + } + + /** + * Creates the contents. + * + * @param parent the parent + * @return the control + */ + @Override + protected Control createContents(Composite parent) { + parent.setLayout(new GridLayout(2, false)); + + viewer = new TableViewer(parent, SWT.BORDER | SWT.FULL_SELECTION | SWT.V_SCROLL | SWT.RESIZE | SWT.H_SCROLL); + viewer.setContentProvider(new SortSettingTableContentProvider()); + ColumnViewerToolTipSupport.enableFor(viewer); + addUIColumns(); + loadSavedSortState(); + + table = viewer.getTable(); + table.setLayoutData(new GridData(GridData.FILL_BOTH)); + table.setHeaderVisible(true); + table.setLinesVisible(true); + configureColumnCursor(); + + Composite buttonSet = new Composite(parent, SWT.NONE); + buttonSet.setLayout(new GridLayout()); + buttonSet.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + + createAddColumnButton(buttonSet); + + Composite upDown = new Composite(buttonSet, SWT.NONE); + GridLayout upDownLayout = new GridLayout(2, true); + upDownLayout.marginHeight = 0; + upDownLayout.marginWidth = 0; + upDown.setLayout(upDownLayout); + + createUpColumnButton(upDown); + createDownColumnButton(upDown); + createDeleteColumnButton(buttonSet); + createApplySortButton(buttonSet); + + viewer.setColumnProperties(COLUMN_HEADERS); + viewer.setCellModifier(new SortColumnSettingModifier(viewer, colNames, dataTypes)); + + return parent; + } + + private void loadSavedSortState() { + GridSaveSortState sortState = grid.getCurrentSortSnapshot(); + + if (!sortState.hasSortKeys()) { + sortColumnsModel.add(new SortColumnSetting()); + } else { + List savedSortList = sortState.getSavedSortList(); + for (int index = 0; index < savedSortList.size(); index++) { + SortEntryData sortComboNames = savedSortList.get(index); + int columnIndex = Arrays.asList(colNames).indexOf(sortComboNames.getColumnName()); + sortColumnsModel.add(new SortColumnSetting(String.valueOf(index), sortComboNames.getColumnName(), + dataTypes[columnIndex], + SortColumnSetting.getComboTextFromSortDirectionEnum(sortComboNames.getSortDirection()))); + } + } + + viewer.setInput(sortColumnsModel); + } + + private TableViewerColumn createTableViewerColumn(String title, final int bound, final int colNumber) { + final TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE, colNumber); + final TableColumn column = viewerColumn.getColumn(); + column.setText(title); + column.setToolTipText(title); + column.setWidth(bound); + column.setResizable(true); + column.setMoveable(true); + return viewerColumn; + } + + private void addUIColumns() { + TableViewerColumn vColumn1 = createTableViewerColumn( + MessageConfigLoader.getProperty(IMessagesConstants.COLUMN_PRIORITY), + MulticolumnSortConstants.PRIORITY_COL_LEN, MulticolumnSortConstants.PRIORITY_INDEX); + vColumn1.setLabelProvider(vColumn1ColumnLabelProvider()); + + TableViewerColumn vColumn2 = createTableViewerColumn( + MessageConfigLoader.getProperty(IMessagesConstants.COLUMN_COLUMN_NAME), + MulticolumnSortConstants.COLNAME_COL_LEN, MulticolumnSortConstants.COLUMN_INDEX); + + vColumn2.setLabelProvider(vColumn2ColumnLabelProvider()); + + vColumn2.setEditingSupport(new SortColumnComboEditingSupport(viewer, colNames, dataTypes, + MessageConfigLoader.getProperty(IMessagesConstants.COMBO_TEXT_SORT_COLUMN))); + + TableViewerColumn vColumn3 = createTableViewerColumn( + MessageConfigLoader.getProperty(IMessagesConstants.COLUMN_DATATYPE), + MulticolumnSortConstants.DATATYPE_COL_LEN, MulticolumnSortConstants.DATATYPE_INDEX); + vColumn3.setLabelProvider(vColumn3ColumnLabelProvider()); + + TableViewerColumn vColumn4 = createTableViewerColumn( + MessageConfigLoader.getProperty(IMessagesConstants.COLUMN_SORT_ORDER), + MulticolumnSortConstants.ORDER_COL_LEN, MulticolumnSortConstants.ORDER_INDEX); + vColumn4.setLabelProvider(vColumn4ColumnLabelProvider()); + vColumn4.setEditingSupport(new SortColumnComboEditingSupport(viewer)); + + } + + private ColumnLabelProvider vColumn4ColumnLabelProvider() { + return new ColumnLabelProvider() { + @Override + public String getText(Object element) { + SortColumnSetting ele = (SortColumnSetting) element; + return ele.getSortOrder(); + } + + @Override + public String getToolTipText(Object element) { + SortColumnSetting elmnt = (SortColumnSetting) element; + return elmnt.getSortOrder(); + } + }; + } + + private ColumnLabelProvider vColumn3ColumnLabelProvider() { + return new ColumnLabelProvider() { + @Override + public String getText(Object element) { + SortColumnSetting ele = (SortColumnSetting) element; + return ele.getDataType(); + } + + @Override + public String getToolTipText(Object element) { + SortColumnSetting ele = (SortColumnSetting) element; + return ele.getDataType(); + } + }; + } + + private ColumnLabelProvider vColumn2ColumnLabelProvider() { + return new ColumnLabelProvider() { + @Override + public String getText(Object element) { + SortColumnSetting ele = (SortColumnSetting) element; + return ele.getColumnName(); + } + + @Override + public String getToolTipText(Object element) { + SortColumnSetting ele = (SortColumnSetting) element; + return ele.getColumnName(); + } + + }; + } + + private ColumnLabelProvider vColumn1ColumnLabelProvider() { + return new ColumnLabelProvider() { + @Override + public String getText(Object element) { + SortColumnSetting ele = (SortColumnSetting) element; + return ele.getPriorityText(); + } + + @Override + public String getToolTipText(Object element) { + SortColumnSetting ele = (SortColumnSetting) element; + return ele.getPriorityText(); + } + }; + } + + private void createApplySortButton(Composite buttonSet) { + Button btnApplySort = new Button(buttonSet, SWT.NONE); + GridData gdBtnApplySort = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); + btnApplySort.setLayoutData(gdBtnApplySort); + btnApplySort.setText(MessageConfigLoader.getProperty(IMessagesConstants.BUTTON_APPLY_SORT)); + btnApplySort.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent event) { + GridSaveSortState state = prepareSortSetting(); + if (null != state) { + grid.applySortSnapshot(state); + } + } + + @Override + public void widgetDefaultSelected(SelectionEvent event) { + + } + }); + } + + private void createDeleteColumnButton(Composite buttonSet) { + Button btnDelColumn = new Button(buttonSet, SWT.NONE); + GridData gdBtnDelCol = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); + btnDelColumn.setLayoutData(gdBtnDelCol); + btnDelColumn.setText(MessageConfigLoader.getProperty(IMessagesConstants.BUTTON_DELETE_COLUMN)); + btnDelColumn.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent event) { + int selIndex = table.getSelectionIndex(); + + if (selIndex == -1) { + return; + } + + sortColumnsModel.remove(selIndex); + + // update priority of the columns that are after the deleted + // column + for (int i = selIndex; i < sortColumnsModel.size(); i++) { + sortColumnsModel.get(i).reducePriority(); + } + + if (selIndex == 0 && table.getItemCount() > 0) { + table.setSelection(selIndex); + } else { + table.setSelection(selIndex - 1); + } + viewer.refresh(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent event) { + + } + + }); + } + + private void createDownColumnButton(Composite upDown) { + Button btnDwn = new Button(upDown, SWT.NONE); + GridData gdBtnDwn = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); + btnDwn.setLayoutData(gdBtnDwn); + btnDwn.setText(MessageConfigLoader.getProperty(IMessagesConstants.BUTTON_DOWN_COULMN)); + btnDwn.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent event) { + int selIndex = table.getSelectionIndex(); + if (selIndex == table.getItemCount() - 1 || selIndex == -1) { + return; + } + int otherIndex = selIndex + 1; + swapItems(selIndex, otherIndex); + table.setSelection(otherIndex); + } + + @Override + public void widgetDefaultSelected(SelectionEvent event) { + + } + }); + } + + private void createUpColumnButton(Composite upDown) { + Button btnUp = new Button(upDown, SWT.NONE); + GridData gdBtnUp = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); + btnUp.setLayoutData(gdBtnUp); + btnUp.setText(MessageConfigLoader.getProperty(IMessagesConstants.BUTTON_UP_COLUMN)); + btnUp.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent event) { + int selIndex = table.getSelectionIndex(); + if (selIndex == 0 || selIndex == -1) { + return; + } + int otherIndex = selIndex - 1; + swapItems(selIndex, otherIndex); + table.setSelection(otherIndex); + } + + @Override + public void widgetDefaultSelected(SelectionEvent event) { + + } + }); + } + + private void createAddColumnButton(Composite buttonSet) { + Button btnAddColumn = new Button(buttonSet, SWT.NONE); + GridData gdBtnAddColumn = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); + btnAddColumn.setLayoutData(gdBtnAddColumn); + btnAddColumn.setText(MessageConfigLoader.getProperty(IMessagesConstants.BUTTON_ADD_COLUMN)); + btnAddColumn.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent event) { + SortColumnSetting newSortCol = new SortColumnSetting(String.valueOf(sortColumnsModel.size())); + sortColumnsModel.add(newSortCol); + viewer.editElement(newSortCol, MulticolumnSortConstants.COLUMN_INDEX); + viewer.editElement(newSortCol, MulticolumnSortConstants.ORDER_INDEX); + viewer.refresh(); + table.setSelection(table.getItemCount()); + } + + @Override + public void widgetDefaultSelected(SelectionEvent event) { + + } + }); + } + + /** + * On success UI action. + * + * @param obj the obj + */ + @Override + public void onSuccessUIAction(Object obj) { + MPPDBIDELoggerUtility.trace("multicolumn sort setting succesful"); + } + + /** + * On critical exception UI action. + * + * @param exception the exception + */ + @Override + public void onCriticalExceptionUIAction(DatabaseCriticalException exception) { + MPPDBIDELoggerUtility.trace("Exception: multicolumn sort setting"); + + } + + /** + * On operational exception UI action. + * + * @param exception the exception + */ + @Override + public void onOperationalExceptionUIAction(DatabaseOperationException exception) { + MPPDBIDELoggerUtility.trace("Exception: multicolumn sort setting"); + + } + + /** + * On presetup failure UI action. + * + * @param exception the exception + */ + @Override + public void onPresetupFailureUIAction(MPPDBIDEException exception) { + MPPDBIDELoggerUtility.trace("pre-setup fail: multicolumn sort setting"); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/sort/SortSettingTableContentProvider.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/sort/SortSettingTableContentProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..101b509437dfc0d6b3680017e5c660c6076f5c1e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/component/grid/sort/SortSettingTableContentProvider.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.component.grid.sort; + +import java.util.List; + +import org.eclipse.jface.viewers.IStructuredContentProvider; +import org.eclipse.jface.viewers.Viewer; + +/** + * + * Title: class + * + * Description: The Class SortSettingTableContentProvider. + * + * @since 3.0.0 + */ +public class SortSettingTableContentProvider implements IStructuredContentProvider { + + /** + * Dispose. + */ + @Override + public void dispose() { + + } + + /** + * Input changed. + * + * @param viewer the viewer + * @param oldInput the old input + * @param newInput the new input + */ + @Override + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + + } + + /** + * Gets the elements. + * + * @param inputElement the input element + * @return the elements + */ + @SuppressWarnings("unchecked") + @Override + public Object[] getElements(Object inputElement) { + return ((List) inputElement).toArray(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/configregistory/DSConfigurationColumnsList.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/configregistory/DSConfigurationColumnsList.java new file mode 100644 index 0000000000000000000000000000000000000000..c2bb860e5227e79136eba89835a1dc488c9f9aba --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/configregistory/DSConfigurationColumnsList.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.configregistory; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: interface + * + * Description: The Interface DSConfigurationColumnsList. + * + * @since 3.0.0 + */ +public interface DSConfigurationColumnsList { + + /** + * The Constant CHECKTAB_ENABLED. + */ + public static final String CHECKTAB_ENABLED = MessageConfigLoader + .getProperty(IMessagesConstants.OLAP_PROP_CHECKTAB_ENABLED); + + /** + * The Constant CHECKTAB_DEFERRABLE. + */ + public static final String CHECKTAB_DEFERRABLE = MessageConfigLoader + .getProperty(IMessagesConstants.OLAP_PROP_CHECKTAB_DEFERRABLE); + + /** + * The Constant CHECKTAB_DEFERRED. + */ + public static final String CHECKTAB_DEFERRED = MessageConfigLoader + .getProperty(IMessagesConstants.OLAP_PROP_CHECKTAB_DEFERRED); + + /** + * The Constant CHECKTAB_VALIDATED. + */ + public static final String CHECKTAB_VALIDATED = MessageConfigLoader + .getProperty(IMessagesConstants.OLAP_PROP_CHECKTAB_VALIDATED); + + /** + * The Constant CHECKTAB_CONDITION. + */ + public static final String CHECKTAB_CONDITION = MessageConfigLoader + .getProperty(IMessagesConstants.OLAP_PROP_CHECKTAB_CONDITION); + + /** + * The Constant COLUMNTABIS_NULLABLE. + */ + public static final String COLUMNTABIS_NULLABLE = MessageConfigLoader + .getProperty(IMessagesConstants.OLAP_PROP_COLUMNTAB_ISNULLABLE); + + /** + * The Constant COLUMNTAB_DATATYPE. + */ + public static final String COLUMNTAB_DATATYPE = MessageConfigLoader + .getProperty(IMessagesConstants.OLAP_PROP_COLUMNTAB_DATATYPE); + + /** + * The Constant COLUMNTAB_IS_DEFAULT_EXPRESSION. + */ + public static final String COLUMNTAB_IS_DEFAULT_EXPRESSION = MessageConfigLoader + .getProperty(IMessagesConstants.COLUMN_DEFAULT_VALUE_EXPRESSION); + + /** + * The Constant GEN_VALUE. + */ + public static final String GEN_VALUE = MessageConfigLoader.getProperty(IMessagesConstants.PROPERTIES_WID_VALUE); + + /** + * The Constant KEYTAB_DEFERRABLE. + */ + public static final String KEYTAB_DEFERRABLE = MessageConfigLoader + .getProperty(IMessagesConstants.OLAP_PROP_KEYTAB_DEFERRABLE); + + /** + * The Constant KEYTAB_DEFERRED. + */ + public static final String KEYTAB_DEFERRED = MessageConfigLoader + .getProperty(IMessagesConstants.OLAP_PROP_KEYTAB_DEFERRED); + + /** + * The Constant KEYTAB_VALIDATED. + */ + public static final String KEYTAB_VALIDATED = MessageConfigLoader + .getProperty(IMessagesConstants.OLAP_PROP_KEYTAB_VALIDATED); + + /** + * The Constant KEYTAB_TYPE. + */ + public static final String KEYTAB_TYPE = MessageConfigLoader.getProperty(IMessagesConstants.OLAP_PROP_KEYTAB_TYPE); + + /** + * The Constant KEYTAB_REFERENCING_TABLE. + */ + public static final String KEYTAB_REFERENCING_TABLE = MessageConfigLoader + .getProperty(IMessagesConstants.OLAP_PROP_KEYTAB_REFERENCINGTABLE); + + /** + * The Constant KEYTAB_REFERENCING_CLM. + */ + public static final String KEYTAB_REFERENCING_CLM = MessageConfigLoader + .getProperty(IMessagesConstants.OLAP_PROP_KEYTAB_REFERENCINGCOL); + + /** + * The Constant KEYTAB_ON_DELETE. + */ + public static final String KEYTAB_ON_DELETE = MessageConfigLoader + .getProperty(IMessagesConstants.OLAP_PROP_KEYTAB_ONDELETE); + + /** + * The Constant KEYTAB_COLUMNS. + */ + public static final String KEYTAB_COLUMNS = MessageConfigLoader + .getProperty(IMessagesConstants.OLAP_PROP_KEYTAB_COLUMNS); + + /** + * The Constant PARTITION_VALUES. + */ + public static final String PARTITION_VALUES = MessageConfigLoader + .getProperty(IMessagesConstants.OLAP_PROP_PARTITIONTAB_PARTITIONVALUE); + + /** + * The Constant PARTITION_TABLESPACE. + */ + public static final String PARTITION_TABLESPACE = MessageConfigLoader + .getProperty(IMessagesConstants.OLAP_PROP_PARTITIONTAB_TABLESPACENAME); + + /** + * The Constant PARTITION_TYPE. + */ + public static final String PARTITION_TYPE = MessageConfigLoader + .getProperty(IMessagesConstants.OLAP_PROP_PARTITIONTAB_TYPE); + + /** + * The Constant PARTITION_KEYS. + */ + public static final String PARTITION_KEYS = MessageConfigLoader + .getProperty(IMessagesConstants.OLAP_PROP_PARTITIONTAB_KEYS); + + /** + * The Constant INDEXIS_UNIQUE. + */ + public static final String INDEXIS_UNIQUE = MessageConfigLoader + .getProperty(IMessagesConstants.OLAP_PROP_INDEXTAB_ISUNIQUE); + + /** + * The Constant INDEX_COLUMNS. + */ + public static final String INDEX_COLUMNS = MessageConfigLoader + .getProperty(IMessagesConstants.OLAP_PROP_INDEXTAB_COLUMNS); + + /** + * The Constant INDEX_TABLESPACE. + */ + public static final String INDEX_TABLESPACE = MessageConfigLoader + .getProperty(IMessagesConstants.OLAP_PROP_INDEXTAB_TABLESPACE); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/configregistory/RegistryTableConfiguration.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/configregistory/RegistryTableConfiguration.java new file mode 100644 index 0000000000000000000000000000000000000000..97732244a0b744a98aaa770dceaa185abafe4ebd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/configregistory/RegistryTableConfiguration.java @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.configregistory; + +import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry; +import org.eclipse.nebula.widgets.nattable.layer.cell.ColumnOverrideLabelAccumulator; + +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.view.component.IGridUIPreference; +import org.opengauss.mppdbide.view.component.grid.EditTableGridStyleConfiguration; +import org.opengauss.mppdbide.view.component.grid.IDataGridContext; +import org.opengauss.mppdbide.view.component.grid.core.DSAbstractRegistryConfiguration; + +/** + * + * Title: class + * + * Description: The Class RegistryTableConfiguration. + * + * @since 3.0.0 + */ +public abstract class RegistryTableConfiguration extends DSAbstractRegistryConfiguration + implements DSConfigurationColumnsList { + + /** + * The column label accumulator. + */ + protected ColumnOverrideLabelAccumulator columnLabelAccumulator; + + /** + * The data grid context. + */ + protected IDataGridContext dataGridContext; + + /** + * The ui pref. + */ + protected IGridUIPreference uiPref; + + /** + * Instantiates a new registry table configuration. + * + * @param columnLabelAccumulator the column label accumulator + * @param dataGridContext the data grid context + * @param uiPref the ui pref + */ + public RegistryTableConfiguration(ColumnOverrideLabelAccumulator columnLabelAccumulator, + IDataGridContext dataGridContext, IGridUIPreference uiPref) { + this.columnLabelAccumulator = columnLabelAccumulator; + this.dataGridContext = dataGridContext; + this.uiPref = uiPref; + } + + /** + * Gets the UI preference. + * + * @return the UI preference + */ + public IGridUIPreference getUIPreference() { + return uiPref; + } + + /** + * Configure registry. + * + * @param configRegistry the config registry + */ + @Override + public void configureRegistry(IConfigRegistry configRegistry) { + IDSGridColumnProvider columnDataProvider = dataGridContext.getDataProvider().getColumnDataProvider(); + registerConfigLabelsOnColumns(columnLabelAccumulator, columnDataProvider); + registerUiRegistryToEachColumn(configRegistry, columnDataProvider); + } + + /** + * Sets the column label accumulator. + * + * @param columnLabelAccumulator the new column label accumulator + */ + @Override + public void setColumnLabelAccumulator(ColumnOverrideLabelAccumulator columnLabelAccumulator) { + this.columnLabelAccumulator = columnLabelAccumulator; + + } + + /** + * Register config labels on columns. + * + * @param lblAccumulator the lbl accumulator + * @param colDataprovider the col dataprovider + */ + @Override + public void registerConfigLabelsOnColumns(ColumnOverrideLabelAccumulator lblAccumulator, + IDSGridColumnProvider colDataprovider) { + int colCount = colDataprovider.getColumnCount(); + for (int cnt = 0; cnt < colCount; cnt++) { + registorLabel(lblAccumulator, colDataprovider, cnt); + } + } + + /** + * Register ui registry to each column. + * + * @param configRegistry the config registry + * @param columnDataProvider the column data provider + */ + @Override + public void registerUiRegistryToEachColumn(IConfigRegistry configRegistry, + IDSGridColumnProvider columnDataProvider) { + int colCount = columnDataProvider.getColumnCount(); + for (int index = 0; index < colCount; index++) { + registerUiRegistory(configRegistry, columnDataProvider, index); + } + } + + /** + * Sets the default labels. + * + * @param lblAccumulator the lbl accumulator + * @param index the index + */ + protected void setDefaultLabels(ColumnOverrideLabelAccumulator lblAccumulator, int index) { + lblAccumulator.registerColumnOverrides(index, EditTableGridStyleConfiguration.COL_LABEL_COPY_READONLY_CELL); + setReadOnlyLabel(lblAccumulator, index); + } + + /** + * Sets the read only label. + * + * @param lblAccumulator the lbl accumulator + * @param cnt the cnt + */ + protected void setReadOnlyLabel(ColumnOverrideLabelAccumulator lblAccumulator, int cnt) { + lblAccumulator.registerColumnOverrides(cnt, EditTableGridStyleConfiguration.COL_LABEL_READONLY_CELL); + } + + /** + * Registor label. + * + * @param lblAccumulator the lbl accumulator + * @param colDataprovider the col dataprovider + * @param count the count + */ + protected abstract void registorLabel(ColumnOverrideLabelAccumulator lblAccumulator, + IDSGridColumnProvider colDataprovider, int count); + + /** + * Register ui registory. + * + * @param configRegistry the config registry + * @param columnDataProvider the column data provider + * @param cnt the cnt + */ + protected abstract void registerUiRegistory(IConfigRegistry configRegistry, + IDSGridColumnProvider columnDataProvider, int cnt); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/AboutMPPDBIDEDialog.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/AboutMPPDBIDEDialog.java new file mode 100644 index 0000000000000000000000000000000000000000..c1d1add8597cb874dda649c1c032376e53716c9a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/AboutMPPDBIDEDialog.java @@ -0,0 +1,331 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.program.Program; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; + +import org.opengauss.mppdbide.utils.EnvirnmentVariableValidator; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.dto.version.UIVersionDO; +import org.opengauss.mppdbide.view.init.LifeCycleManager; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * + * Title: class + * + * Description: The Class AboutMPPDBIDEDialog. + * + * @since 3.0.0 + */ +public class AboutMPPDBIDEDialog extends Dialog { + private static final String ALIGN_SPACES = " "; + + /** + * Instantiates a new about MPPDBIDE dialog. + * + * @param parentShell the parent shell + */ + public AboutMPPDBIDEDialog(Shell parentShell) { + super(parentShell); + setBlockOnOpen(true); + } + + /** + * Configure shell. + * + * @param shell the shell + */ + @Override + protected void configureShell(Shell shell) { + super.configureShell(shell); + shell.setImage(IconUtility.getIconImage(IiconPath.ICO_TOOL_32X32, getClass())); + shell.setText(MessageConfigLoader.getProperty(IMessagesConstants.ABOUT_DATA_STUDIO_MSG)); + } + + /** + * Creates the buttons for button bar. + * + * @param parent the parent + */ + @Override + protected void createButtonsForButtonBar(Composite parent) { + Button button = createButton(parent, IDialogConstants.OK_ID, + MessageConfigLoader.getProperty(IMessagesConstants.MPPDBIDE_DIA_BTN_CLOSE), true); + button.setFocus(); + } + + /** + * Creates the dialog area. + * + * @param parent the parent + * @return the control + */ + @Override + protected Control createDialogArea(Composite parent) { + int commonBorderStyle = SWT.NONE; + int intend = 15; + + addBannerLabel(parent, commonBorderStyle); + + Composite container = getComposite(parent, commonBorderStyle); + // Print empty space + Color fontColor = addEmptySpace(commonBorderStyle, intend, container); + // Print DS version + addDsVersion(commonBorderStyle, intend, container, fontColor); + + // Print Java version + addJavaVersion(commonBorderStyle, intend, container, fontColor); + // Print Java Home Information + addJavaHomeInformation(commonBorderStyle, intend, container, fontColor); + + // Print Build Time + addBuildTime(commonBorderStyle, intend, container, fontColor); + return container; + } + + /** + * Adds the build time. + * + * @param commonBorderStyle the common border style + * @param intend the intend + * @param container the container + * @param fontColor the font color + */ + private void addBuildTime(int commonBorderStyle, int intend, Composite container, Color fontColor) { + GridData gridData; + Label buildTimeLabel = new Label(container, commonBorderStyle); + buildTimeLabel.setText(MessageConfigLoader.getProperty(IMessagesConstants.BUILD_TIME)); + buildTimeLabel.setForeground(fontColor); + gridData = new GridData(); + gridData.horizontalIndent = intend; + buildTimeLabel.setLayoutData(gridData); + + String buildTime = getBuildTime(); + Label buildTimeValue = new Label(container, commonBorderStyle); + buildTimeValue.setText(ALIGN_SPACES + + (null == buildTime ? MessageConfigLoader.getProperty(IMessagesConstants.BUILD_TIME_UNKNOWN) + : buildTime)); + } + + /** + * Adds the java home information. + * + * @param commonBorderStyle the common border style + * @param intend the intend + * @param container the container + * @param fontColor the font color + */ + private void addJavaHomeInformation(int commonBorderStyle, int intend, Composite container, Color fontColor) { + GridData gridData; + Label javaHomeLabel = new Label(container, commonBorderStyle); + javaHomeLabel.setText(MessageConfigLoader.getProperty(IMessagesConstants.JAVA_HOME_MSG)); + javaHomeLabel.setForeground(fontColor); + gridData = new GridData(); + gridData.horizontalIndent = intend; + javaHomeLabel.setLayoutData(gridData); + + String javaHomeStr = EnvirnmentVariableValidator.validateAndGetJavaPath(); + Label javaHomeValue = new Label(container, commonBorderStyle); + if (null == javaHomeStr) { + javaHomeValue.setText(ALIGN_SPACES + MessageConfigLoader.getProperty(IMessagesConstants.JAVA_HOME_NOT_SET)); + } else { + javaHomeValue.setText(ALIGN_SPACES + javaHomeStr); + } + javaHomeValue.setForeground(fontColor); + } + + /** + * Adds the java version. + * + * @param commonBorderStyle the common border style + * @param intend the intend + * @param container the container + * @param fontColor the font color + */ + private void addJavaVersion(int commonBorderStyle, int intend, Composite container, Color fontColor) { + GridData gridData; + Label javaVersionLabel = new Label(container, commonBorderStyle); + javaVersionLabel.setText(MessageConfigLoader.getProperty(IMessagesConstants.JAVA_VERSION_NO_MSG)); + javaVersionLabel.setForeground(fontColor); + gridData = new GridData(); + gridData.horizontalIndent = intend; + javaVersionLabel.setLayoutData(gridData); + + Label javaVersionValue = new Label(container, commonBorderStyle); + javaVersionValue.setText(ALIGN_SPACES + EnvirnmentVariableValidator.validateJavaVersion()); + javaVersionValue.setForeground(fontColor); + } + + /** + * Adds the ds version. + * + * @param commonBorderStyle the common border style + * @param intend the intend + * @param container the container + * @param fontColor the font color + */ + private void addDsVersion(int commonBorderStyle, int intend, Composite container, Color fontColor) { + GridData gridData; + Label versionLabel = new Label(container, commonBorderStyle); + versionLabel.setText(MessageConfigLoader.getProperty(IMessagesConstants.VERSION_NO_MSG)); + versionLabel.setForeground(fontColor); + gridData = new GridData(); + gridData.horizontalIndent = intend; + versionLabel.setLayoutData(gridData); + + Label versionValue = new Label(container, commonBorderStyle); + versionValue.setText(ALIGN_SPACES + UIVersionDO.getUIVersion()); + versionValue.setForeground(fontColor); + } + + /** + * Adds the empty space. + * + * @param commonBorderStyle the common border style + * @param intend the intend + * @param container the container + * @return the color + */ + private Color addEmptySpace(int commonBorderStyle, int intend, Composite container) { + GridData gridData; + Label emptyLabel = new Label(container, commonBorderStyle); + gridData = new GridData(); + gridData.horizontalIndent = intend; + emptyLabel.setLayoutData(gridData); + Label emptyLabel1 = new Label(container, commonBorderStyle); + emptyLabel1.setText(""); + Color fontColor = new Color(Display.getDefault(), 17, 17, 17); + return fontColor; + } + + /** + * Gets the composite. + * + * @param parent the parent + * @param commonBorderStyle the common border style + * @return the composite + */ + private Composite getComposite(Composite parent, int commonBorderStyle) { + Composite container = new Composite(parent, commonBorderStyle); + GridLayout gridLayout = new GridLayout(); + gridLayout.numColumns = 2; + gridLayout.makeColumnsEqualWidth = false; + gridLayout.marginRight = 0; + gridLayout.marginLeft = 0; + gridLayout.marginTop = 0; + container.setLayout(gridLayout); + return container; + } + + /** + * Adds the banner label. + * + * @param parent the parent + * @param commonBorderStyle the common border style + */ + private void addBannerLabel(Composite parent, int commonBorderStyle) { + Label banner = new Label(parent, commonBorderStyle); + banner.setImage(IconUtility.getIconImage(IiconPath.ICO_ABOUT_DS, this.getClass())); + GridData gridData = new GridData(); + gridData.verticalAlignment = GridData.FILL; + gridData.verticalSpan = 4; + gridData.horizontalSpan = 2; + gridData.grabExcessVerticalSpace = true; + gridData.horizontalAlignment = GridData.FILL; + gridData.grabExcessHorizontalSpace = true; + banner.setLayoutData(gridData); + } + + /** + * The listener interface for receiving linkSelection events. The class that + * is interested in processing a linkSelection event implements this + * interface, and the object created with that class is registered with a + * component using the component's addLinkSelectionListener + * method. When the linkSelection event occurs, that object's appropriate + * method is invoked. + * + * LinkSelectionEvent + */ + private static class LinkSelectionListener implements SelectionListener { + @Override + public void widgetSelected(SelectionEvent exception) { + Program.launch(MessageConfigLoader.getProperty(IMessagesConstants.WEB_HUAWEI_LINK)); + } + + @Override + public void widgetDefaultSelected(SelectionEvent exception) { + + } + + } + + /** + * Gets the builds the time. + * + * @return the builds the time + */ + private String getBuildTime() { + URL path = getVersionFilePath(); + if (null == path) { + return null; + } + + Properties prop = new Properties(); + try { + prop.load(path.openStream()); + Object buildTime = prop.get("data.studio.buildTime"); + return (null == buildTime) ? null : buildTime.toString(); + } catch (IOException exception) { + return null; + } + } + + /** + * Gets the version file path. + * + * @return the version file path + */ + private URL getVersionFilePath() { + URL propertiesURL = null; + ClassLoader classLoader = LifeCycleManager.class.getClassLoader(); + if (null != classLoader) { + propertiesURL = classLoader.getResource("version.txt"); + return propertiesURL; + } + return propertiesURL; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/AbstarctObjectBrowserLabelProvider.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/AbstarctObjectBrowserLabelProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..48e5fc7a8c3ea5afb38c2ac2d46a7350b003f7d9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/AbstarctObjectBrowserLabelProvider.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import org.eclipse.jface.viewers.ColumnLabelProvider; + +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.utils.CustomStringUtility; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class AbstarctObjectBrowserLabelProvider. + * + * @since 3.0.0 + */ +public abstract class AbstarctObjectBrowserLabelProvider extends ColumnLabelProvider { + + /** + * Gets the tool tip text helper. + * + * @param serv the serv + * @return the tool tip text helper + */ + protected String getToolTipTextHelper(Server serv) { + String serverVersion = CustomStringUtility.parseServerVersion(serv.getServerVersion(true)); + String serverIp = serv.getServerIP2(); + String tooltipText = tooltipCheck(serverVersion, serverIp); + return tooltipText != null ? tooltipText + : MessageConfigLoader.getProperty(IMessagesConstants.SERVERIP_TOOLTIP, serverIp) + + MPPDBIDEConstants.LINE_SEPARATOR + + MessageConfigLoader.getProperty(IMessagesConstants.SERVERVERSION_TOOLTIP, serverVersion); + } + + /** + * Tooltip check. + * + * @param serverVersion the server version + * @param serverIp the server ip + * @return the string + */ + private String tooltipCheck(String serverVersion, String serverIp) { + if (serverVersion.isEmpty() && serverIp.isEmpty()) { + return MessageConfigLoader.getProperty(IMessagesConstants.SERVERIP_TOOLTIP, + MessageConfigLoader.getProperty(IMessagesConstants.SERVERIP_TOOLTIP_FAIL)) + + MPPDBIDEConstants.LINE_SEPARATOR + + MessageConfigLoader.getProperty(IMessagesConstants.SERVERVERSION_TOOLTIP, + MessageConfigLoader.getProperty(IMessagesConstants.CONNECTION_VERSION_NUMBER_FAILED_MSG)); + } else if (serverVersion.isEmpty()) { + return MessageConfigLoader.getProperty(IMessagesConstants.SERVERIP_TOOLTIP, serverIp) + + MPPDBIDEConstants.LINE_SEPARATOR + + MessageConfigLoader.getProperty(IMessagesConstants.SERVERVERSION_TOOLTIP, + MessageConfigLoader.getProperty(IMessagesConstants.CONNECTION_VERSION_NUMBER_FAILED_MSG)); + } else if (serverIp.isEmpty()) { + return MessageConfigLoader.getProperty(IMessagesConstants.SERVERIP_TOOLTIP, + MessageConfigLoader.getProperty(IMessagesConstants.SERVERIP_TOOLTIP_FAIL)) + + MPPDBIDEConstants.LINE_SEPARATOR + + MessageConfigLoader.getProperty(IMessagesConstants.SERVERVERSION_TOOLTIP, serverVersion); + } + return null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/AbstractObjectBrowserLazyContentProvider.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/AbstractObjectBrowserLazyContentProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..b6a6d44bea10114fe40174913f3cb935490bd2b6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/AbstractObjectBrowserLazyContentProvider.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import org.eclipse.jface.viewers.ILazyTreeContentProvider; +import org.eclipse.jface.viewers.Viewer; + +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; + +/** + * + * Title: class + * + * Description: The Class AbstractObjectBrowserLazyContentProvider. + * + * @since 3.0.0 + */ +public abstract class AbstractObjectBrowserLazyContentProvider implements ILazyTreeContentProvider { + + /** + * Dispose. + */ + @Override + public void dispose() { + + } + + /** + * Input changed. + * + * @param viewr the viewr + * @param oldInput the old input + * @param newInput the new input + */ + @Override + public void inputChanged(Viewer viewr, Object oldInput, Object newInput) { + + } + + /** + * Update element. + * + * @param parent the parent + * @param index the index + */ + @Override + public abstract void updateElement(Object parent, int index); + + /** + * Update server object. + * + * @param obj the obj + * @param index the index + * @return the object + */ + protected Object updateServerObject(ServerObject obj, int index) { + if (obj.isLoadingInProgress()) { + return new LoadingUIElement(); + } else { + return obj.getChildren()[index]; + } + } + + /** + * Update child count. + * + * @param element the element + * @param currentChildCount the current child count + */ + @Override + public abstract void updateChildCount(Object element, int currentChildCount); + + /** + * Gets the parent. + * + * @param element the element + * @return the parent + */ + @Override + public abstract Object getParent(Object element); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ConnectionNotification.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ConnectionNotification.java new file mode 100644 index 0000000000000000000000000000000000000000..11e919124b2dc2ad37182e2d08898dc8add4ab93 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ConnectionNotification.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; + +/** + * + * Title: class + * + * Description: The Class ConnectionNotification. + * + * @since 3.0.0 + */ +public class ConnectionNotification { + + private Database db; + + /** + * Instantiates a new connection notification. + * + * @param db the db + */ + public ConnectionNotification(Database db) { + this.db = db; + } + + /** + * Loadnotification. + */ + public void loadnotification() { + LastLoginSecurityPopupJob loginWorker = new LastLoginSecurityPopupJob(db); + loginWorker.schedule(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ConsoleCoreWindow.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ConsoleCoreWindow.java new file mode 100644 index 0000000000000000000000000000000000000000..05b26193aa9c9d3d11448904655f8edf6d3704b2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ConsoleCoreWindow.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import org.opengauss.mppdbide.utils.messaging.GlobaMessageQueueUtil; +import org.opengauss.mppdbide.utils.messaging.Message; +import org.opengauss.mppdbide.utils.messaging.MessageQueue; + +/** + * + * Title: class + * + * Description: The Class ConsoleCoreWindow. + * + * @since 3.0.0 + */ +public final class ConsoleCoreWindow extends ConsoleMessageWindow { + private static volatile ConsoleCoreWindow instance; + private MessageQueue queue; + private static final Object LOCK = new Object(); + + /** + * Instantiates a new console core window. + */ + private ConsoleCoreWindow() { + this.queue = GlobaMessageQueueUtil.getInstance().getMessageQueue(); + } + + /** + * Gets the single instance of ConsoleCoreWindow. + * + * @return single instance of ConsoleCoreWindow + */ + public static ConsoleCoreWindow getInstance() { + if (null == instance) { + synchronized (LOCK) { + if (null == instance) { + instance = new ConsoleCoreWindow(); + } + } + } + return instance; + } + + /** + * Log error. + * + * @param logMessage the log message + */ + @Override + public void logError(String logMessage) { + this.queue.push(Message.getError(logMessage)); + } + + /** + * Log error in UI. + * + * @param logMessage the log message + */ + @Override + public void logErrorInUI(String logMessage) { + logError(logMessage); + } + + /** + * Log warning. + * + * @param logMessage the log message + */ + @Override + public void logWarning(String logMessage) { + this.queue.push(Message.getWarn(logMessage)); + } + + /** + * Log warning in UI. + * + * @param logMessage the log message + */ + @Override + public void logWarningInUI(String logMessage) { + logWarning(logMessage); + } + + /** + * Log fatal. + * + * @param logMessage the log message + */ + @Override + public void logFatal(String logMessage) { + this.queue.push(Message.getError(logMessage)); + } + + /** + * Log fatal in UI. + * + * @param logMessage the log message + */ + @Override + public void logFatalInUI(String logMessage) { + logFatal(logMessage); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ConsoleMessageWindow.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ConsoleMessageWindow.java new file mode 100644 index 0000000000000000000000000000000000000000..33831de26de0dedf7ba4246a3e7316c9684715cc --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ConsoleMessageWindow.java @@ -0,0 +1,753 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +import javax.annotation.PreDestroy; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.ITextOperationTarget; +import org.eclipse.jface.text.TextSelection; +import org.eclipse.jface.text.TextViewer; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.MenuEvent; +import org.eclipse.swt.events.MenuListener; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.MenuItem; +import org.eclipse.swt.widgets.ToolBar; +import org.eclipse.swt.widgets.ToolItem; +import org.eclipse.ui.progress.UIJob; + +import org.opengauss.mppdbide.presentation.resultsetif.IConsoleResult; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.IMessageQueue; +import org.opengauss.mppdbide.utils.messaging.Message; +import org.opengauss.mppdbide.utils.messaging.MessageQueue; +import org.opengauss.mppdbide.utils.messaging.MessageType; +import org.opengauss.mppdbide.view.ui.DBAssistantWindow; +import org.opengauss.mppdbide.view.utils.IDEMemoryAnalyzer; +import org.opengauss.mppdbide.view.utils.UserPreference; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * Title: class Description: The Class ConsoleMessageWindow. + * + * @since 3.0.0 + */ +public class ConsoleMessageWindow extends SelectMenuItem { + private TextViewer textViewer; + + private Document doc; + + private boolean hasTableSkippingNotice; + + private MenuItem menuClear; + + private MessageQueue msgQueue; + + /** + * Title: enum Description: The Enum LOGTYPE. + */ + private enum LOGTYPE { + ERROR, WARNING, INFO, FATAL, NOTICE, LOGTYPE_BUTT + } + + /** + * Instantiates a new console message window. + */ + public ConsoleMessageWindow() { + doc = new Document(""); + doc.set(""); + msgQueue = new MessageQueue(); + } + + /** + * Creates the console window. + * + * @param parent the parent + */ + + public void createConsoleWindow(Composite parent) { + + /* setting parent layout */ + GridLayout gridlayout = new GridLayout(); + parent.setLayout(gridlayout); + /* handler control */ + Composite handlerComposite = getHandlerComposite(parent); + + // create ToolBar + GridData toolbargriddata = new GridData(); + toolbargriddata.horizontalAlignment = SWT.FILL; + + ToolBar toolbar = new ToolBar(handlerComposite, SWT.FLAT | SWT.FOCUSED); + toolbar.setLayoutData(toolbargriddata); + toolbar.pack(); + + addClearToolItem(toolbar); + + textViewer = new TextViewer(parent, SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL); + textViewer.getTextWidget().setData(MPPDBIDEConstants.SWTBOT_KEY, "ID_TXT_CONSOLE_TEXT_001"); + textViewer.setDocument(doc); + textViewer.setEditable(false); + + addGridDataToTextViewer(); + + // Add select all key binding + textViewer.getTextWidget().addKeyListener(new SourceEditorKeyListener(textViewer)); + + Menu menu = new Menu(getControl()); + textViewer.getTextWidget().setMenu(menu); + + textViewer.getTextWidget().setMenu(menu); + textViewer.addSelectionChangedListener(addTextViewerSelectionListener()); + + addCopyMenuItem(menu); + addSelectAllMenuItem(menu); + addClearMenuItem(menu); + menu.addMenuListener(addMenuListenerOnMenu()); + + // nested class to print message from queue + + LazyloadConsoleMessages loadConsoleMsg = new LazyloadConsoleMessages(Display.getDefault(), + "Console msg loading", this); + loadConsoleMsg.schedule(); + } + + private Composite getHandlerComposite(Composite parent) { + Composite handlerComposite = new Composite(parent, SWT.NONE); + GridLayout handlerGridLayout = new GridLayout(2, false); + handlerGridLayout.marginTop = -4; + handlerComposite.setLayout(handlerGridLayout); + GridData handlerGridData = new GridData(); + handlerGridData.heightHint = 22; + handlerComposite.setLayoutData(handlerGridData); + return handlerComposite; + } + + private void addGridDataToTextViewer() { + GridData textViewerGridData = new GridData(); + textViewerGridData.verticalAlignment = GridData.FILL; + textViewerGridData.grabExcessHorizontalSpace = true; + textViewerGridData.grabExcessVerticalSpace = true; + textViewerGridData.horizontalAlignment = GridData.FILL; + textViewer.getControl().setLayoutData(textViewerGridData); + } + + private void addClearToolItem(ToolBar toolbar) { + ToolItem btnClear = new ToolItem(toolbar, SWT.NONE); + btnClear.setData(MPPDBIDEConstants.SWTBOT_KEY, "SQL_CONSOLE"); + btnClear.setImage(IconUtility.getIconImage(IiconPath.ICO_CLEAR, getClass())); + btnClear.setToolTipText(MessageConfigLoader.getProperty(IMessagesConstants.CLEAR_CONSOLE)); + btnClear.addSelectionListener(new ClearSelectionListener()); + } + + private MenuListener addMenuListenerOnMenu() { + return new MenuListener() { + + @Override + public void menuShown(MenuEvent event) { + contextMenuAboutToShow(); + } + + @Override + public void menuHidden(MenuEvent event) { + + } + }; + } + + private ISelectionChangedListener addTextViewerSelectionListener() { + return new ISelectionChangedListener() { + @Override + public void selectionChanged(SelectionChangedEvent event) { + ISelection selection = event.getSelection(); + + String selectionStr = ((TextSelection) selection).getText(); + + if (selectionStr != null && !"".equals(selectionStr)) { + DBAssistantWindow.execErr(selectionStr); + } + } + }; + } + + /** + * Context menu about to show. + */ + private void contextMenuAboutToShow() { + + if (textViewer.getDocument().get().isEmpty()) { + menuClear.setEnabled(false); + getMenuSelectAll().setEnabled(false); + } else { + menuClear.setEnabled(true); + getMenuSelectAll().setEnabled(true); + } + if (textViewer.getTextWidget().getSelectionText().isEmpty()) { + getMenuCopy().setEnabled(false); + } else { + getMenuCopy().setEnabled(true); + } + + } + + /** + * The listener interface for receiving clearSelection events. The class + * that is interested in processing a clearSelection event implements this + * interface, and the object created with that class is registered with a + * component using the component's addClearSelectionListener + * method. When the clearSelection event occurs, that object's appropriate + * method is invoked. ClearSelectionEvent + */ + private final class ClearSelectionListener implements SelectionListener { + @Override + public void widgetSelected(SelectionEvent event) { + clear(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent event) { + + } + } + + /** + * Log msgs on console window. + * + * @param logMsg the log msg + */ + private void logMsgsOnConsoleWindow(String logMsg) { + if (textViewer == null || textViewer.getControl().isDisposed()) { + return; + } + String newLog = doc.get() + logMsg; + doc.set(newLog); + + int numberOfLines = doc.getNumberOfLines(); + int docLength = doc.getLength(); + + if (numberOfLines > UserPreference.getInstance().getConsoleLineCount()) { + int offset = 0; + + try { + offset = doc.getLineOffset(numberOfLines - UserPreference.getInstance().getConsoleLineCount()); + doc.set(doc.get(offset, docLength - offset)); + } catch (BadLocationException e) { + // Logically this should not be hit + // Can this scenario be logged again? Will it be valid? + String errLogMsg = MessageConfigLoader.getProperty(IMessagesConstants.CONSOLE_WINDOW_ERROR_MSG); + if (MPPDBIDELoggerUtility.isDebugEnabled()) { + MPPDBIDELoggerUtility.debug(errLogMsg + ";" + + MessageConfigLoader.getProperty(IMessagesConstants.CONSOLE_WINDOW_LINE_NUMBER_MSG) + + numberOfLines + + MessageConfigLoader.getProperty(IMessagesConstants.CONSOLE_WINDOW_OFFSET_MSG) + offset + + ";" + MessageConfigLoader.getProperty(IMessagesConstants.CONSOLE_WINDOW_LENGTH_MSG) + + docLength); + } + + newLog = generateLogEntry(newLog, errLogMsg, LOGTYPE.ERROR); + doc.set(newLog); + } finally { + numberOfLines = doc.getNumberOfLines(); + docLength = doc.getLength(); + } + } + + /* + * Only if console window is open display it otherwise populate it. + */ + + try { + textViewer.revealRange(doc.getLineOffset(numberOfLines - 1), docLength); + + // Fix for: Console window cursor position will not + // be updated along with the contents. + textViewer.setSelectedRange(docLength, 0); + } catch (BadLocationException ex) { + // Logically this should not be hit + // Can this scenario be logged again? Will it be valid? + String errLogMsg = MessageConfigLoader.getProperty(IMessagesConstants.CONSOLE_WINDOW_ERROR_SCROLLING_MSG); + if (MPPDBIDELoggerUtility.isDebugEnabled()) { + MPPDBIDELoggerUtility.debug(errLogMsg + "; " + + MessageConfigLoader.getProperty(IMessagesConstants.CONSOLE_WINDOW_LINE_NUMBER_MSG) + + numberOfLines + ";" + + MessageConfigLoader.getProperty(IMessagesConstants.CONSOLE_WINDOW_LENGTH_MSG) + docLength); + } + + doc.set(generateLogEntry(newLog, errLogMsg, LOGTYPE.ERROR)); + } + } + + /** + * Append log entry. + * + * @param logMessage the log message + * @param logtype the logtype + * @param strBlder the str blder + */ + private void appendLogEntry(String logMessage, LOGTYPE logtype, StringBuilder strBlder) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(MPPDBIDEConstants.DATE_FORMAT); + if (logtype != null) { + strBlder.append(MPPDBIDEConstants.LINE_SEPARATOR).append('[').append(simpleDateFormat.format(new Date())) + .append("] : ").append('[').append(logtype.name()).append("] ").append(logMessage); + } + } + + /** + * Log msg on display thread. + * + * @param logMsg the log msg + */ + private void logMsgOnDisplayThread(String logMsg) { + Display.getDefault().asyncExec(new LogMsgOnUICallback(logMsg)); + } + + /** + * Title: class Description: The Class LogMsgOnUICallback. + */ + private class LogMsgOnUICallback implements Runnable { + private String logMessage; + + /** + * Instantiates a new log msg on UI callback. + * + * @param logMsg the log msg + */ + public LogMsgOnUICallback(String logMsg) { + this.logMessage = logMsg; + } + + @Override + public void run() { + logMsgsOnConsoleWindow(this.logMessage); + } + } + + /** + * Log. + * + * @param logMessage the log message + * @param logtype the logtype + */ + public void log(String logMessage, LOGTYPE logtype) { + StringBuilder logMsgBlr = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + appendLogEntry(logMessage, logtype, logMsgBlr); + logMsgsOnConsoleWindow(logMsgBlr.toString()); + } + + /** + * Log info. + * + * @param logMessage the log message + */ + public void logInfo(String logMessage) { + log(logMessage, LOGTYPE.INFO); + } + + /** + * Log warning. + * + * @param logMessage the log message + */ + public void logWarning(String logMessage) { + log(logMessage, LOGTYPE.WARNING); + } + + /** + * Log fatal. + * + * @param logMessage the log message + */ + public void logFatal(String logMessage) { + log(logMessage, LOGTYPE.FATAL); + } + + /** + * Log error. + * + * @param logMessage the log message + */ + public void logError(String logMessage) { + log(logMessage, LOGTYPE.ERROR); + } + + /** + * Log notice. + * + * @param logMessage the log message + */ + public void logNotice(String logMessage) { + log(logMessage, LOGTYPE.NOTICE); + } + + /** + * Log info in UI. + * + * @param logMessage the log message + */ + + public void logInfoInUI(final String logMessage) { + prepareAndLogMsgOnUI(logMessage, LOGTYPE.INFO); + } + + /** + * Log warning in UI. + * + * @param logMessage the log message + */ + public void logWarningInUI(final String logMessage) { + prepareAndLogMsgOnUI(logMessage, LOGTYPE.WARNING); + } + + /** + * Log fatal in UI. + * + * @param logMessage the log message + */ + public void logFatalInUI(final String logMessage) { + prepareAndLogMsgOnUI(logMessage, LOGTYPE.FATAL); + } + + /** + * Log error in UI. + * + * @param logMessage the log message + */ + public void logErrorInUI(final String logMessage) { + prepareAndLogMsgOnUI(logMessage, LOGTYPE.ERROR); + } + + /** + * Prepare and log msg on UI. + * + * @param logMessage the log message + * @param type the type + */ + private void prepareAndLogMsgOnUI(String logMessage, LOGTYPE type) { + StringBuilder blr = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + appendLogEntry(logMessage, type, blr); + logMsgOnDisplayThread(blr.toString()); + if (IDEMemoryAnalyzer.is90PercentReached()) { + logWarning(MessageConfigLoader.getProperty(IMessagesConstants.CONSOLE_WINDOW_MEMORY_MSG) + + IDEMemoryAnalyzer.getTotalUsedMemoryPercentage() + '%'); + } + } + + /** + * Log notice in UI. + * + * @param logMessage the log message + */ + public void logNoticeInUI(final String logMessage) { + prepareAndLogMsgOnUI(logMessage, LOGTYPE.NOTICE); + } + + /** + * Adds the clear menu item. + * + * @param menu the menu + */ + private void addClearMenuItem(Menu menu) { + menuClear = new MenuItem(menu, SWT.PUSH); + + menuClear.setText(MessageConfigLoader.getProperty(IMessagesConstants.CLEAR_CONSOLE)); + menuClear.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent event) { + clear(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent event) { + + } + }); + menuClear.setImage(IconUtility.getIconImage(IiconPath.ICO_CLEAR, this.getClass())); + } + + /** + * Clear. + */ + public void clear() { + doc.set(""); + } + + /** + * Checks if is doc empty. + * + * @return true, if is doc empty + */ + public boolean isDocEmpty() { + return 0 == doc.getLength(); + } + + /** + * On focus. + */ + public void onFocus() { + textViewer.getControl().setFocus(); + } + + /** + * Select all doc text. + */ + public void selectAllDocText() { + textViewer.doOperation(ITextOperationTarget.SELECT_ALL); + } + + /** + * Copy doc text. + */ + public void copyDocText() { + textViewer.doOperation(ITextOperationTarget.COPY); + } + + /** + * Gets the control. + * + * @return the control + */ + public Control getControl() { + return textViewer.getControl(); + } + + /** + * Prints the BL queue messages to console. + * + * @param msgQueue2 the msg queue 2 + */ + private void printBLQueueMessagesToConsole(MessageQueue msgQueue2) { + IMessageQueue messageQueue = msgQueue2; + int batch = UserPreference.getInstance().getBatchMsgSize(); + int printableSize = UserPreference.getInstance().getConsoleLineCount(); + int totalMsgInQueue = messageQueue.size(); + final int printBatchSize = 10; + + hasTableSkippingNotice = false; + + if (totalMsgInQueue > printableSize) { + for (int i = 0; i < (totalMsgInQueue - printableSize); i++) { + messageQueue.pop(); + } + + totalMsgInQueue = printableSize; + } + + batch = findBatchSize(totalMsgInQueue, batch); + StringBuilder logBldr = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + Message msg; + + for (int cnt = 0; cnt < batch; cnt++) { + msg = messageQueue.pop(); + if (null != msg) { + appendLogEntry(msg.getMessage(), getLogTypeForMessageType(msg.getType()), logBldr); + + if (cnt % printBatchSize == 0) { + logMsgOnDisplayThread(logBldr.toString()); + logBldr = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + } + } + + if (logBldr.length() > 0) { + logMsgOnDisplayThread(logBldr.toString()); + logBldr = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + } + } + + } + + /** + * Find batch size. + * + * @param size the size + * @param batch the batch + * @return the int + */ + private int findBatchSize(int size, int batch) { + int batchSize; + + if (0 == size) { + batchSize = 0; + } else if (size > batch) { + batchSize = batch; + } else { + batchSize = size; + } + + return batchSize; + } + + /** + * Gets the log type for message type. + * + * @param msgType the msg type + * @return the log type for message type + */ + private LOGTYPE getLogTypeForMessageType(MessageType msgType) { + LOGTYPE logtype = null; + + switch (msgType) { + case INFO: { + logtype = LOGTYPE.INFO; + break; + } + case WARN: { + logtype = LOGTYPE.WARNING; + break; + } + case NOTICE: { + logtype = LOGTYPE.NOTICE; + break; + } + case ERROR: { + logtype = LOGTYPE.ERROR; + break; + } + } + + return logtype; + } + + /** + * Checks for table skipping notice. + * + * @return true, if successful + */ + public boolean hasTableSkippingNotice() { + return hasTableSkippingNotice; + } + + /** + * Generate log message to the standard format. + * + * @param currentLog the current log + * @param logMessage the log message + * @param logtype the logtype + * @return the string + */ + private String generateLogEntry(String currentLog, String logMessage, LOGTYPE logtype) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(MPPDBIDEConstants.DATE_FORMAT); + StringBuilder strBlder = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + strBlder.append(currentLog); + strBlder.append(MPPDBIDEConstants.LINE_SEPARATOR).append('[').append(simpleDateFormat.format(new Date())) + .append("] : ").append('[').append(logtype.name()).append("] ").append(logMessage); + + return strBlder.toString(); + } + + /** + * Gets the text viewer. + * + * @return the text viewer + */ + public TextViewer getTextViewer() { + return textViewer; + } + + /** + * Gets the msg queue. + * + * @return the msg queue + */ + public MessageQueue getMsgQueue() { + return msgQueue; + } + + /** + * Title: class Description: The Class LazyloadConsoleMessages. + */ + private final class LazyloadConsoleMessages extends UIJob { + private static final int SCHEDULE_TIME = 250; + + private ConsoleMessageWindow consolewin; + + private MessageQueue msgQueue; + + /** + * Instantiates a new lazyload console messages. + * + * @param jobDisplay the job display + * @param name the name + * @param consoleMessageWindow the console message window + */ + private LazyloadConsoleMessages(Display jobDisplay, String name, ConsoleMessageWindow consoleMessageWindow) { + super(jobDisplay, name); + this.consolewin = consoleMessageWindow; + this.msgQueue = consolewin.getMsgQueue(); + } + + @Override + public IStatus runInUIThread(IProgressMonitor arg0) { + if (!msgQueue.isEmpty()) { + consolewin.printBLQueueMessagesToConsole(msgQueue); + } + if (!getTextViewer().getControl().isDisposed()) { + schedule(SCHEDULE_TIME); + } + return Status.OK_STATUS; + } + + } + + /** + * Log info. + * + * @param consoleMsgsToShow the console msgs to show + */ + public void logInfo(IConsoleResult consoleMsgsToShow) { + logByType(LOGTYPE.INFO, consoleMsgsToShow); + logByType(LOGTYPE.NOTICE, consoleMsgsToShow.getHintMessages()); + } + + private void logByType(LOGTYPE logType, List messages) { + StringBuilder sb = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + for (String str : messages) { + appendLogEntry(str, logType, sb); + } + this.logMsgsOnConsoleWindow(sb.toString()); + } + + /** + * Pre destroy. + */ + @PreDestroy + public void preDestroy() { + this.doc = null; + this.msgQueue = null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ConsoleMessageWindowDummy.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ConsoleMessageWindowDummy.java new file mode 100644 index 0000000000000000000000000000000000000000..8c53ddd9af0cf62a7bdb5783b5d83e31224b8927 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ConsoleMessageWindowDummy.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class ConsoleMessageWindowDummy. + * + * @since 3.0.0 + */ +public class ConsoleMessageWindowDummy extends ConsoleMessageWindow { + + /** + * Log msgs on console window. + * + * @param logMsg the log msg + */ + public void logMsgsOnConsoleWindowDummy(String logMsg) { + MPPDBIDELoggerUtility.none(logMsg); + } + + /** + * Log error. + * + * @param logMsg the log msg + */ + public void logError(String logMsg) { + MPPDBIDELoggerUtility.none(logMsg); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ExcuteSQLObjectTable.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ExcuteSQLObjectTable.java new file mode 100644 index 0000000000000000000000000000000000000000..6f4290c35207fc2c24dd2c80e8f7176090f4d064 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ExcuteSQLObjectTable.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import org.eclipse.swt.widgets.Shell; + +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * + * Title: class + * + * Description: The Class ExcuteSQLObjectTable. + * + * @since 3.0.0 + */ +public class ExcuteSQLObjectTable extends ParameterInputDialog { + + /** + * Instantiates a new excute SQL object table. + * + * @param parentShell the parent shell + */ + public ExcuteSQLObjectTable(Shell parentShell) { + super(parentShell); + setDefaultImage(IconUtility.getIconImage(IiconPath.ICO_TOOL_128X128, this.getClass())); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ExecDialog.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ExecDialog.java new file mode 100644 index 0000000000000000000000000000000000000000..ddf296b3f796e98bc130fea98dac2e1c9a6f5a19 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ExecDialog.java @@ -0,0 +1,491 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ITextListener; +import org.eclipse.jface.text.ITextOperationTarget; +import org.eclipse.jface.text.TextEvent; +import org.eclipse.jface.text.source.CompositeRuler; +import org.eclipse.jface.text.source.ISharedTextColors; +import org.eclipse.jface.text.source.LineNumberRulerColumn; +import org.eclipse.jface.text.source.SourceViewer; +import org.eclipse.jface.viewers.CellEditor; +import org.eclipse.jface.viewers.ColumnLabelProvider; +import org.eclipse.jface.viewers.EditingSupport; +import org.eclipse.jface.viewers.TableViewer; +import org.eclipse.jface.viewers.TableViewerColumn; +import org.eclipse.jface.viewers.TextCellEditor; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.KeyAdapter; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.internal.editors.text.EditorsPlugin; + +import org.opengauss.mppdbide.adapter.keywordssyntax.SQLSyntax; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.IDebugObject; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.ObjectParameter; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.Message; +import org.opengauss.mppdbide.utils.messaging.StatusMessage; +import org.opengauss.mppdbide.view.core.sourceeditor.SQLDocumentPartitioner; +import org.opengauss.mppdbide.view.core.sourceeditor.SQLSourceViewerConfig; +import org.opengauss.mppdbide.view.core.sourceeditor.SQLSourceViewerDecorationSupport; +import org.opengauss.mppdbide.view.core.statusbar.ObjectBrowserStatusBarProvider; +import org.opengauss.mppdbide.view.handler.HandlerUtilities; +import org.opengauss.mppdbide.view.ui.terminal.SQLTerminal; +import org.opengauss.mppdbide.view.utils.IUserPreference; +import org.opengauss.mppdbide.view.utils.UIElement; +import org.opengauss.mppdbide.view.utils.consts.UIConstants; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * Title: ExecDialog + * + * @since 3.0.0 + */ +public class ExecDialog extends Dialog { + + // Parent container + private Composite container; + + // Place holder for execution template + private SourceViewer sourceViewer; + private CompositeRuler fCompositeRuler; + private static final int SPACE_BETWEEN_RULER = 1; + private SQLSourceViewerDecorationSupport fSourceViewerDecorationSupport; + private IDebugObject debugObject; + + // Dialog height and width + private static final int TRIG_DIALOG_WIDTH = 450; + private static final int TRIG_DIALOG_HEIGHT = 250; + + // Execution template usage hint label + private Label lblUsageHint; + + + private Button okBtn; + private Button cancelBtn; + + private StatusMessage statusMessage; + private SQLSyntax syntax; + + /** + * Instantiates a new exec dialog. + * + * @param parentShell the parent shell + * @param isDebug the is debug + */ + public ExecDialog(Shell parentShell) { + super(parentShell); + setDefaultImage(IconUtility.getIconImage(IiconPath.ICO_FUNCTION_FOLDER, this.getClass())); + this.setShellStyle(SWT.TITLE | SWT.APPLICATION_MODAL); + } + + /** + * Creates the contents. + * + * @param parent the parent + * @return the control + */ + @Override + protected Control createContents(Composite parent) { + + Rectangle bounds = Display.getDefault().getActiveShell().getBounds(); + + parent.getShell().setBounds(bounds.width / 2 - TRIG_DIALOG_WIDTH / 2, + bounds.height / 2 - TRIG_DIALOG_HEIGHT / 2, TRIG_DIALOG_WIDTH, TRIG_DIALOG_HEIGHT); + + // create the top level composite for the dialog + container = new Composite(parent, SWT.NONE); + + GridLayout layout = new GridLayout(); + layout.verticalSpacing = 0; + container.setLayout(layout); + container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + applyDialogFont(container); + // initialize the dialog units + initializeDialogUnits(container); + + lblUsageHint = new Label(container, SWT.NULL); + lblUsageHint.setText(""); + + sourceViewer = new SourceViewer(container, getCompositeRuler(), null, false, + SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.WRAP); + sourceViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + + sourceViewer.setEditable(true); + + setDocument(new Document("")); + + setDecoration(); + SQLDocumentPartitioner.connectDocument(sourceViewer.getDocument(), 0); + + sourceViewer.configure(new SQLSourceViewerConfig(getSyntax())); + sourceViewer.addTextListener(new ITextListener() { + + @Override + public void textChanged(TextEvent event) { + if (sourceViewer != null && sourceViewer.getDocument() != null + && sourceViewer.getDocument().get().trim().length() < 1) { + okBtn.setEnabled(false); + } else { + okBtn.setEnabled(true); + } + } + }); + sourceViewer.getTextWidget().addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + if (e.keyCode == 'a' && (e.stateMask & SWT.MODIFIER_MASK) == SWT.CTRL) { + sourceViewer.doOperation(ITextOperationTarget.SELECT_ALL); + } + } + }); + + // create the button bar + buttonBar = createButtonBar(container); + + displayTemplateFromDebugObject(debugObject); + + if (null != debugObject.getTemplateParameters()) { + debugObject.clearTemplateParameterValues(); + } + + debugObject.setTemplateParameters(debugObject.getTemplateParameters()); + + return container; + } + + /** + * Sets the debug object. + * + * @param debugObj the debug obj + * @return true, if successful + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + public boolean setDebugObject(IDebugObject debugObj) throws DatabaseOperationException, DatabaseCriticalException { + HandlerUtilities.getSourceForDbgObj(debugObj); + + this.debugObject = debugObj; + debugObj.generateExecutionTemplate(); + + return true; + } + + /** + * Checks if is resizable. + * + * @return true, if is resizable + */ + @Override + protected boolean isResizable() { + return true; + } + + /** + * Gets the composite ruler. + * + * @return the composite ruler + */ + public CompositeRuler getCompositeRuler() { + fCompositeRuler = new CompositeRuler(SPACE_BETWEEN_RULER); + fCompositeRuler.addDecorator(1, new LineNumberRulerColumn()); + + return fCompositeRuler; + } + + /** + * Sets the document. + * + * @param document the new document + */ + public void setDocument(IDocument document) { + sourceViewer.setDocument(document); + } + + /** + * Set decoration for source viewer. + */ + private void setDecoration() { + ISharedTextColors sharedTextColors = EditorsPlugin.getDefault().getSharedTextColors(); + + fSourceViewerDecorationSupport = new SQLSourceViewerDecorationSupport(sourceViewer, null, null, + sharedTextColors); + + fSourceViewerDecorationSupport.setCursorLinePainterPreferenceKeys(IUserPreference.CURRENT_LINE_VISIBILITY, + IUserPreference.CURRENTLINE_COLOR); + + fSourceViewerDecorationSupport.installDecorations(); + } + + /** + * Display template from debug object. + * + * @param object the object + */ + public void displayTemplateFromDebugObject(IDebugObject object) { + sourceViewer.getDocument().set(debugObject.getExecuteTemplate()); + setUsageHint(debugObject.getUsagehint()); + MPPDBIDELoggerUtility.debug("GUI: DebugSQLObjectCore: Display execution template to debug."); + } + + /** + * Creates the buttons for button bar. + * + * @param parent the parent + */ + @Override + protected void createButtonsForButtonBar(Composite parent) { + // Added for remembering PSWD/PORT to change button label start + final String okLabel = " " + MessageConfigLoader.getProperty(IMessagesConstants.EXEC_PLAN_OK) + " "; + final String cancelLabel = " " + MessageConfigLoader.getProperty(IMessagesConstants.MPPDBIDE_DIA_BTN_CANC) + + " "; + okBtn = createButton(parent, UIConstants.OK_ID, okLabel, true); + cancelBtn = createButton(parent, UIConstants.CANCEL_ID, cancelLabel, false); + } + + /** + * Button pressed. + * + * @param buttonId the button id + */ + @Override + protected void buttonPressed(int buttonId) { + if (UIConstants.OK_ID == buttonId) { + okBtn.setEnabled(false); + cancelBtn.setEnabled(false); + executePressed(); + } else if (UIConstants.CANCEL_ID == buttonId) { + cancelPressed(); + } + + } + + /** + * Execute pressed. + */ + public void executePressed() { + Database db = debugObject.getDatabase(); + + // Create new terminal to execute the PL + SQLTerminal terminal = UIElement.getInstance().createNewTerminal(db); + if (terminal == null) { + close(); + return; + } + try { + // If no IN parameter, then get the query from debug object directly + if (null == sourceViewer) { + terminal.getTerminalCore().getDocument().set(debugObject.prepareExecutionQueryString()); + } else { + terminal.getTerminalCore().getDocument().set(sourceViewer.getDocument().get()); + } + + terminal.handleExecution(); + } catch (DatabaseOperationException e) { + terminal.getConsoleMessageWindow(true).logError(e.getMessage()); + } finally { + close(); + } + } + + /** + * Close dialog from UI. + */ + public void closeDialogFromUI() { + Display.getDefault().asyncExec(new Runnable() { + + @Override + public void run() { + close(); + } + }); + } + + /** + * Gets the status message. + * + * @return the status message + */ + public StatusMessage getStatusMessage() { + return statusMessage; + } + + /** + * Sets the status message. + * + * @param statMessage the new status message + */ + public void setStatusMessage(StatusMessage statMessage) { + this.statusMessage = statMessage; + } + + /** + * Set execution template usage hint. + * + * @param hint execution template usage hint text + */ + private void setUsageHint(String hint) { + StringBuilder builder = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + if (debugObject.getObjectType() == OBJECTTYPE.PLSQLFUNCTION) { + + builder.append(MessageConfigLoader.getProperty(IMessagesConstants.EXECDIALOG_PARAMETER_VALUE) + + MPPDBIDEConstants.LINE_SEPARATOR); + builder.append(null != hint && hint.length() > 0 + ? MessageConfigLoader.getProperty(IMessagesConstants.EXECDIALOG_HINT) + hint + : ""); + builder.append(MPPDBIDEConstants.LINE_SEPARATOR); + } + + lblUsageHint.setText(builder.toString()); + } + + /** + * Cancel pressed. + */ + @Override + protected void cancelPressed() { + // Sets this window's return code. The return code is automatically + // returned by open if block on open is enabled. + setReturnCode(UIConstants.CANCEL_ID); + close(); + } + + /** + * Configure shell. + * + * @param shell the shell + */ + @Override + protected void configureShell(Shell shell) { + super.configureShell(shell); + shell.setText(MessageConfigLoader.getProperty(IMessagesConstants.EXECDIALOG_EXEC_PL_SQL)); + } + + + private static class ValueEditingSupport extends EditingSupport { + private final TableViewer viewer; + + ValueEditingSupport(TableViewer viewer) { + super(viewer); + this.viewer = viewer; + } + + @Override + protected CellEditor getCellEditor(Object element) { + TextCellEditor cellEditor = new TextCellEditor(viewer.getTable()); + Control textControl = cellEditor.getControl(); + + // Suppress the context menu + textControl.addListener(SWT.MenuDetect, new ExecDialogListener()); + + return cellEditor; + } + + /** + * Added for findbugs Static inner class creation check + */ + private static class ExecDialogListener implements Listener { + @Override + public void handleEvent(Event event) { + event.doit = false; + } + } + + @Override + protected void setValue(Object element, Object value) { + ((ObjectParameter) element).setValue(value.toString()); + viewer.refresh(); + } + + @Override + protected boolean canEdit(Object element) { + return true; + } + + @Override + protected Object getValue(Object element) { + if (element instanceof ObjectParameter) { + Object value = ((ObjectParameter) element).getValue(); + if (null != value) { + return value; + } + } + + return ""; + } + } + + + /** + * Close. + * + * @return true, if successful + */ + @Override + public boolean close() { + if (fSourceViewerDecorationSupport != null) { + fSourceViewerDecorationSupport.uninstall(); + } + if (sourceViewer != null) { + sourceViewer.unconfigure(); + } + syntax = null; + return super.close(); + } + + /** + * Gets the syntax. + * + * @return the syntax + */ + public SQLSyntax getSyntax() { + return syntax; + } + + /** + * Sets the syntax. + * + * @param syntax the new syntax + */ + public void setSyntax(SQLSyntax syntax) { + this.syntax = syntax; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LastLoginSecurityPopupJob.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LastLoginSecurityPopupJob.java new file mode 100644 index 0000000000000000000000000000000000000000..8766126229c7f2ccfd3509774d42cad1f6e0d3b9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LastLoginSecurityPopupJob.java @@ -0,0 +1,205 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.swt.widgets.Display; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.serverdatacache.NotificationData; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.DBTYPE; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.Message; +import org.opengauss.mppdbide.utils.messaging.ProgressBarLabelFormatter; +import org.opengauss.mppdbide.view.core.statusbar.ObjectBrowserStatusBarProvider; +import org.opengauss.mppdbide.view.workerjob.UIWorkerJob; + +/** + * + * Title: class + * + * Description: The Class LastLoginSecurityPopupJob. + * + * @since 3.0.0 + */ +public class LastLoginSecurityPopupJob extends UIWorkerJob { + private Database db; + + private StringBuilder successfulLoginTxt; + private List failureLoginTxt; + + private NotificationData lastSuccessfullLogin = null; + private JobCancelStatus status = null; + + /** + * Instantiates a new last login security popup job. + * + * @param db the db + */ + public LastLoginSecurityPopupJob(Database db) { + super(ProgressBarLabelFormatter.getProgressLabelForDatabase(db.getDbName(), db.getServerName(), + IMessagesConstants.LAST_LOGIN_MESSAGE), MPPDBIDEConstants.CANCELABLEJOB); + this.db = db; + successfulLoginTxt = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + failureLoginTxt = new ArrayList(MPPDBIDEConstants.RECORD_ARRAY_SIZE); + setTaskDB(db); + this.status = new JobCancelStatus(); + } + + /** + * Do job. + * + * @return the object + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + @Override + public Object doJob() throws DatabaseOperationException, DatabaseCriticalException { + + lastSuccessfullLogin = this.db.getLoginNotifyManager().getLastSuccessfullLogin(); + if (lastSuccessfullLogin != null) { + successfulLoginTxt.append(lastSuccessfullLogin.getTime()); + successfulLoginTxt.append(" "); + successfulLoginTxt.append(lastSuccessfullLogin.getClientInfo()); + + List failureLoginAttempts = this.db.getLoginNotifyManager().getFailureLoginAttempts(); + + for (int cnt = 0; cnt < failureLoginAttempts.size(); cnt++) { + failureLoginTxt.add( + failureLoginAttempts.get(cnt).getTime() + " " + failureLoginAttempts.get(cnt).getClientInfo()); + } + + } + return null; + } + + /** + * Canceling. + */ + @Override + protected void canceling() { + super.canceling(); + if (!db.isConnected()) { + return; + } + + status.setCancel(true); + + db.getLoginNotifyManager().cancelLastSuccessfulLoginRetrieval(); + ObjectBrowserStatusBarProvider.getStatusBar().displayMessage( + Message.getInfo(MessageConfigLoader.getProperty(IMessagesConstants.CANCEL_OPERATION_IN_PROGRESS))); + } + + /** + * On success UI action. + * + * @param obj the obj + */ + @Override + public void onSuccessUIAction(Object obj) { + if (status.getCancel()) { + ObjectBrowserStatusBarProvider.getStatusBar().displayMessage( + Message.getInfo(MessageConfigLoader.getProperty(IMessagesConstants.USER_CANCEL_MSG))); + return; + } + SystemNotificationPopUI popup = new SystemNotificationPopUI(Display.getCurrent(), lastSuccessfullLogin != null); + + popup.setDatabaseName(db.getDbName()); + popup.setConName(db.getServerName()); + + if (lastSuccessfullLogin != null) { + popup.setSuccessLoginInfo(successfulLoginTxt.toString()); + popup.setFailureLoginInfo(failureLoginTxt); + } + + popup.open(); + } + + /** + * On critical exception UI action. + * + * @param exception the exception + */ + @Override + public void onCriticalExceptionUIAction(DatabaseCriticalException exception) { + if (!db.isConnected()) { + MPPDBIDELoggerUtility.error("Database critical exception occurred as database has been disconnected", + exception); + return; + } + MPPDBIDELoggerUtility.error("Database critical exception occurred while getting last login information ", + exception); + ObjectBrowserStatusBarProvider.getStatusBar() + .displayMessage(Message.getErrorFromConst(IMessagesConstants.LAST_LOGIN_UNAVAILABE)); + } + + /** + * On operational exception UI action. + * + * @param exception the exception + */ + @Override + public void onOperationalExceptionUIAction(DatabaseOperationException exception) { + if (status.getCancel()) { + ObjectBrowserStatusBarProvider.getStatusBar().displayMessage( + Message.getInfo(MessageConfigLoader.getProperty(IMessagesConstants.USER_CANCEL_MSG))); + return; + } else if (!db.isConnected()) { + MPPDBIDELoggerUtility.error("Database operation exception occurred as database has been disconnected", + exception); + return; + } else { + SystemNotificationPopUI popup = new SystemNotificationPopUI(Display.getCurrent(), + lastSuccessfullLogin != null); + + popup.setDatabaseName(db.getDbName()); + popup.setConName(db.getServerName()); + popup.open(); + return; + } + + } + + /** + * Final cleanup. + */ + @Override + public void finalCleanup() { + if (null != db && db.getDBType() == DBTYPE.OPENGAUSS) { + DBConnection successfullLogin = db.getConnectionManager().getSuccessfullLogin(); + if (null != successfullLogin) { + successfullLogin.disconnect(); + } + } + } + + /** + * Final cleanup UI. + */ + @Override + public void finalCleanupUI() { + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LazyBackendLoader.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LazyBackendLoader.java new file mode 100644 index 0000000000000000000000000000000000000000..1ee1c5a6336055132b3f0552cd2ad98dd646e366 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LazyBackendLoader.java @@ -0,0 +1,278 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.util.IExecTimer; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.Message; +import org.opengauss.mppdbide.utils.messaging.StatusMessage; +import org.opengauss.mppdbide.view.core.statusbar.ObjectBrowserStatusBarProvider; +import org.opengauss.mppdbide.view.uidisplay.UIDisplayFactoryProvider; +import org.opengauss.mppdbide.view.utils.BottomStatusBar; +import org.opengauss.mppdbide.view.utils.UIElement; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs.MESSAGEDIALOGTYPE; +import org.opengauss.mppdbide.view.workerjob.UIWorkerJob; + +/** + * + * Title: class + * + * Description: The Class LazyBackendLoader. + * + * @since 3.0.0 + */ +public abstract class LazyBackendLoader extends UIWorkerJob { + + private DBConnection conn; + private Database db; + + private boolean isFailed = false; + private StatusMessage statusMsg; + private IExecTimer timer; + + /** + * Checks if is failed. + * + * @return true, if is failed + */ + public boolean isFailed() { + return isFailed; + } + + /** + * Instantiates a new lazy backend loader. + * + * @param name the name + * @param family the family + * @param statusMsg the status msg + * @param timer the timer + */ + LazyBackendLoader(String name, Object family, StatusMessage statusMsg, IExecTimer timer) { + super(name, family); + + this.statusMsg = statusMsg; + this.timer = timer; + } + + /** + * Do job. + * + * @return the object + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws MPPDBIDEException the MPPDBIDE exception + * @throws Exception the exception + */ + @Override + public Object doJob() throws DatabaseOperationException, DatabaseCriticalException, MPPDBIDEException, Exception { + return null; + } + + /** + * On MPPDBIDE exception UI action. + * + * @param exception the exception + */ + @Override + public void onMPPDBIDEExceptionUIAction(MPPDBIDEException exception) { + ObjectBrowserStatusBarProvider.getStatusBar().displayMessage(Message.getError(getErrorMessage())); + setLoadFailed(); + } + + /** + * Sets the load failed. + */ + void setLoadFailed() { + isFailed = true; + } + + /** + * Gets the error message. + * + * @return the error message + */ + String getErrorMessage() { + return MessageConfigLoader.getProperty(IMessagesConstants.NAMESPACE_RETRIVE_ERROR); + } + + /** + * On MPPDBIDE exception. + * + * @param exception the exception + */ + @Override + public void onMPPDBIDEException(MPPDBIDEException exception) { + super.onMPPDBIDEException(exception); + setLoadFailed(); + } + + /** + * On critical exception UI action. + * + * @param exception the exception + */ + @Override + public void onCriticalExceptionUIAction(DatabaseCriticalException exception) { + MPPDBIDELoggerUtility.error("Database critical exception occured while lazy loading..", exception); + setLoadFailed(); + if (getDb().isConnected()) { + UIDisplayFactoryProvider.getUIDisplayStateIf().handleDBCriticalError(exception, getDb()); + } else { + MPPDBIDEDialogs.generateOKMessageDialog(MESSAGEDIALOGTYPE.ERROR, true, getMessageDialogTitle(), + MessageConfigLoader.getProperty(IMessagesConstants.NAMESPACE_RETRIVE_CRITICAL_ERROR) + + MPPDBIDEConstants.LINE_SEPARATOR + exception.getServerMessage()); + } + } + + /** + * Gets the message dialog message. + * + * @return the message dialog message + */ + String getMessageDialogMessage() { + return MessageConfigLoader.getProperty(IMessagesConstants.ERR_LAZY_BACKEND_LOAD_TITLE); + } + + /** + * Gets the message dialog title. + * + * @return the message dialog title + */ + String getMessageDialogTitle() { + return MessageConfigLoader.getProperty(IMessagesConstants.ERR_TITLE_DB_CRITICAL_ERROR); + } + + /** + * On operational exception UI action. + * + * @param exception the exception + */ + @Override + public void onOperationalExceptionUIAction(DatabaseOperationException exception) { + setLoadFailed(); + MPPDBIDELoggerUtility.error("Database operation exception occured while lazy loading..", exception); + ObjectBrowserStatusBarProvider.getStatusBar().displayMessage(Message.getError(getMessageDialogMessage())); + } + + /** + * On out of memory UI error. + * + * @param error the error + */ + @Override + public void onOutOfMemoryUIError(OutOfMemoryError error) { + MPPDBIDELoggerUtility.error("Out of memory occured while lazy loading..", error); + setLoadFailed(); + MPPDBIDEDialogs.generateOKMessageDialogInUI(MESSAGEDIALOGTYPE.ERROR, true, + MessageConfigLoader.getProperty(IMessagesConstants.TITLE_OUT_OF_MEMORY), + + MessageConfigLoader.getProperty(IMessagesConstants.ERR_OUT_OF_MEMORY_OCCURED)); + + } + + /** + * On exception. + * + * @param exception the exception + */ + @Override + public void onException(Exception exception) { + setLoadFailed(); + super.onException(exception); + } + + /** + * Final cleanup. + */ + @Override + public void finalCleanup() { + getDb().setLoadingNamespaceInProgress(false); + try { + timer.stopAndLog(); + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("Exception while getting elapsed time", exception); + } + } + + /** + * Final cleanup UI. + */ + @Override + public void finalCleanupUI() { + if (null != statusMsg) { + final BottomStatusBar bottomStatusBar = UIElement.getInstance().getProgressBarOnTop(); + if (bottomStatusBar != null) { + bottomStatusBar.hideStatusbar(statusMsg); + } + } + } + + /** + * On success UI action. + * + * @param obj the obj + */ + @Override + public void onSuccessUIAction(Object obj) { + + } + + /** + * Gets the db. + * + * @return the db + */ + public Database getDb() { + return db; + } + + /** + * Sets the db. + * + * @param db the new db + */ + public void setDb(Database db) { + this.db = db; + } + + /** + * Gets the conn. + * + * @return the conn + */ + public DBConnection getConn() { + return conn; + } + + /** + * Sets the conn. + * + * @param conn the new conn + */ + public void setConn(DBConnection conn) { + this.conn = conn; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LazyLoadNamespace.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LazyLoadNamespace.java new file mode 100644 index 0000000000000000000000000000000000000000..6432ce5a1b49fdb4297b8a095873341ab3aa3dda --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LazyLoadNamespace.java @@ -0,0 +1,219 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.viewers.TreeViewer; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.progress.UIJob; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ILazyLoadObject; +import org.opengauss.mppdbide.bl.serverdatacache.SystemNamespace; +import org.opengauss.mppdbide.bl.serverdatacache.UserNamespace; +import org.opengauss.mppdbide.bl.util.IExecTimer; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.messaging.ProgressBarLabelFormatter; +import org.opengauss.mppdbide.utils.messaging.StatusMessage; +import org.opengauss.mppdbide.view.ui.ObjectBrowser; +import org.opengauss.mppdbide.view.utils.BottomStatusBar; +import org.opengauss.mppdbide.view.utils.UIElement; + +/** + * + * Title: class + * + * Description: The Class LazyLoadNamespace. + * + * @since 3.0.0 + */ +public class LazyLoadNamespace extends UIJob { + private List namespaces; + private List toBeLoaded; + private TreeViewer viewer; + private Map loadStatus; + + private static final int LOAD_RECHECK_SCHEDULE_TIME = 500; + private LazyBackendLoader loader; + private StatusMessage statusMsg; + private String objectName; + private IExecTimer timer; + private boolean needExpandViewer; + private boolean isUserSchema; + private Database db; + + /** + * Instantiates a new lazy load namespace. + * + * @param jobDisplay the job display + * @param name the name + * @param namespaceList the namespace list + * @param viewer the viewer + * @param statusMsg the status msg + * @param objectName the object name + * @param timer the timer + * @param expandObjectInViewer the expand object in viewer + * @param isUserSchema the is user schema + */ + public LazyLoadNamespace(Display jobDisplay, String name, List namespaceList, TreeViewer viewer, + StatusMessage statusMsg, String objectName, IExecTimer timer, boolean expandObjectInViewer, + boolean isUserSchema) { + super(jobDisplay, name); + this.namespaces = namespaceList; + this.viewer = viewer; + this.statusMsg = statusMsg; + this.loadStatus = new HashMap(5); + this.objectName = objectName; + this.timer = timer; + this.needExpandViewer = expandObjectInViewer; + this.isUserSchema = isUserSchema; + } + + /** + * Run in UI thread. + * + * @param monitor the monitor + * @return the i status + */ + @Override + public IStatus runInUIThread(IProgressMonitor monitor) { + toBeLoaded = new ArrayList(namespaces.size()); + boolean isAllLoaded = true; + + for (ILazyLoadObject ns : namespaces) { + if (ns == null || viewer == null) { + return Status.OK_STATUS; + } + db = ns.getDatabase(); + if (ns.isNotLoaded()) { + loadSettingByUserScheme(ns); + ns.setLoadingInProgress(); + handleExpandState(ns, true); + + viewer.refresh(ns, true); + toBeLoaded.add(ns); + isAllLoaded = false; + this.loadStatus.put(ns, false); + } else if (ns.isLoadingInProgress()) { + handleExpandState(ns, true); + isAllLoaded = false; + + } else if (validateNamespace(ns)) { + handleExpandState(ns, true); + + viewer.refresh(ns, true); + updateObjectBrowserNameSpace(ns); + this.loadStatus.put(ns, true); + } + } + + if (null != loader && loader.isFailed()) { + return Status.OK_STATUS; + } + + if (toBeLoaded.size() > 0) { + String progressLabel = ProgressBarLabelFormatter.getProgressLabelForSchema(objectName, db.getDbName(), + db.getServerName(), IMessagesConstants.LAZYLOAD_NAMESPACE_PROGRESS_NAME); + loader = new LazyNamespaceBackendLoader(progressLabel, toBeLoaded, statusMsg, objectName, timer); + loader.setTaskDB(db); + loader.schedule(); + } else { + updateBottomStatusBar(); + } + + scheduleLoadWhenAllNotLoaded(isAllLoaded); + + return Status.OK_STATUS; + } + + private boolean validateNamespace(ILazyLoadObject ns) { + return this.loadStatus != null && ns != null && (ns.isLoaded() || ns.isLoadFailed()) + && !this.loadStatus.isEmpty() && this.loadStatus.get(ns) != null && !this.loadStatus.get(ns); + } + + /** + * Update bottom status bar. + */ + private void updateBottomStatusBar() { + // Remove the progress bar on the bottom status bar as there are no + // namespaces to be loaded + if (null != statusMsg) { + final BottomStatusBar bottomStatusBar = UIElement.getInstance().getProgressBarOnTop(); + if (bottomStatusBar != null) { + bottomStatusBar.hideStatusbar(statusMsg); + } + } + } + + /** + * Update object browser name space. + * + * @param ns the ns + */ + private void updateObjectBrowserNameSpace(ILazyLoadObject ns) { + ObjectBrowser objectBrowserModel = UIElement.getInstance().getObjectBrowserModel(); + if (null != objectBrowserModel) { + if (ns instanceof UserNamespace) { + objectBrowserModel.updatObject(ns.getDatabase().getUserNamespaceGroup()); + } else if (ns instanceof SystemNamespace) { + objectBrowserModel.updatObject(ns.getDatabase().getSystemNamespaceGroup()); + } + } + } + + /** + * Load setting by user scheme. + * + * @param ns the ns + */ + private void loadSettingByUserScheme(ILazyLoadObject ns) { + if (isUserSchema) { + ns.getDatabase().setLoadingUserNamespaceInProgress(true); + } else { + ns.getDatabase().setLoadingSystemNamespaceInProgress(true); + } + } + + /** + * Handle expand state. + * + * @param ns the ns + * @param expanded the expanded + */ + private void handleExpandState(ILazyLoadObject ns, boolean expanded) { + if (this.needExpandViewer) { + viewer.setExpandedState(ns, expanded); + } + } + + /** + * Schedule load when all not loaded. + * + * @param isAllLoaded the is all loaded + */ + private void scheduleLoadWhenAllNotLoaded(boolean isAllLoaded) { + if (!isAllLoaded) { + schedule(LOAD_RECHECK_SCHEDULE_TIME); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LazyLoadServerObjectUIJob.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LazyLoadServerObjectUIJob.java new file mode 100644 index 0000000000000000000000000000000000000000..2ae88b6c988989fa2f249e0e7d2ed61a8bc8ea91 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LazyLoadServerObjectUIJob.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.viewers.TreeViewer; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.progress.UIJob; + +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.util.IExecTimer; +import org.opengauss.mppdbide.utils.messaging.StatusMessage; + +/** + * + * Title: class + * + * Description: The Class LazyLoadServerObjectUIJob. + * + * @since 3.0.0 + */ +public class LazyLoadServerObjectUIJob extends UIJob { + private TreeViewer viewer; + private ServerObject obj; + private boolean isFirst = true; + private LazyBackendLoader loader; + private IExecTimer timer; + private StatusMessage statusMsg; + private static final int LOAD_RECHECK_SCHEDULE_TIME = 300; + + /** + * Instantiates a new lazy load server object UI job. + * + * @param jobDisplay the job display + * @param jobName the job name + * @param serverObject the server object + * @param viewer the viewer + * @param statusMsg the status msg + * @param timer the timer + */ + public LazyLoadServerObjectUIJob(Display jobDisplay, String jobName, Object serverObject, TreeViewer viewer, + StatusMessage statusMsg, IExecTimer timer) { + super(jobDisplay, jobName); + obj = (ServerObject) serverObject; + this.viewer = viewer; + this.timer = timer; + this.statusMsg = statusMsg; + } + + /** + * Run in UI thread. + * + * @param monitor the monitor + * @return the i status + */ + @Override + public IStatus runInUIThread(IProgressMonitor monitor) { + boolean isAllLoaded = false; + if (!obj.isLoaded()) { + if (isFirst) { + loader = new LazyServerObjectBackendLoader(obj, statusMsg, timer); + loader.schedule(); + isFirst = false; + } + } else { + isAllLoaded = true; + } + + viewer.setExpandedState(obj, true); + viewer.refresh(obj, true); + + if (null != loader && loader.isFailed()) { + return Status.OK_STATUS; + } + + if (!isAllLoaded) { + schedule(LOAD_RECHECK_SCHEDULE_TIME); + } + + return Status.OK_STATUS; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LazyNamespaceBackendLoader.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LazyNamespaceBackendLoader.java new file mode 100644 index 0000000000000000000000000000000000000000..b302ddb91b00d8641aebf3ee3a7387cf54a33126 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LazyNamespaceBackendLoader.java @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import java.util.List; + +import org.eclipse.swt.widgets.Display; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.IDebugObject; +import org.opengauss.mppdbide.bl.serverdatacache.ILazyLoadObject; +import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; +import org.opengauss.mppdbide.bl.util.IExecTimer; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.StatusMessage; +import org.opengauss.mppdbide.view.handler.HandlerUtilities; +import org.opengauss.mppdbide.view.ui.PLSourceEditor; +import org.opengauss.mppdbide.view.utils.UIElement; + +/** + * + * Title: class + * + * Description: The Class LazyNamespaceBackendLoader. + * + * @since 3.0.0 + */ +public class LazyNamespaceBackendLoader extends LazyBackendLoader { + private List namespaces; + private ILazyLoadObject currentNameSpace = null; + private JobCancelStatus status = null; + + /** + * Instantiates a new lazy namespace backend loader. + * + * @param name the name + * @param toBeLoaded the to be loaded + * @param statusMsg the status msg + * @param objectName the object name + * @param timer the timer + */ + LazyNamespaceBackendLoader(String name, List toBeLoaded, StatusMessage statusMsg, + String objectName, IExecTimer timer) { + super(name, MPPDBIDEConstants.CANCELABLEJOB, statusMsg, timer); + this.namespaces = toBeLoaded; + this.status = new JobCancelStatus(); + } + + /** + * Do job. + * + * @return the object + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws MPPDBIDEException the MPPDBIDE exception + * @throws Exception the exception + */ + @Override + public Object doJob() throws DatabaseOperationException, DatabaseCriticalException, MPPDBIDEException, Exception { + for (ILazyLoadObject namespace : namespaces) { + currentNameSpace = namespace; + setDb(namespace.getDatabase()); + setConn(getDb().getConnectionManager().getObjBrowserConn()); + getDb().setLoadingNamespaceInProgress(true); + namespace.getAllObjects(getConn(), status); + refreshSourceEditorUIAction(currentNameSpace); + } + // Namespace load flag set by getAllObjects(). No need to set again. + return null; + } + + /** + * Refresh source editor UI action. + * + * @param object the object + */ + public void refreshSourceEditorUIAction(final Object object) { + Display.getDefault().asyncExec(new Runnable() { + private PLSourceEditor editorUIObject; + private IDebugObject editorObject; + + @Override + public void run() { + ILazyLoadObject ns = (ILazyLoadObject) object; + try { + List plSourceEditors = UIElement.getInstance().getAllOpenedSourceViewer(); + int noOfEditors = plSourceEditors.size(); + int cnt = 0; + for (; cnt < noOfEditors; cnt++) { + editorUIObject = plSourceEditors.get(cnt); + editorObject = editorUIObject.getDebugObject(); + + if (null == editorObject || editorObject.getNamespace() == null + || editorObject.getNameSpaceId() != ns.getOid()) { + continue; + } + + handleNamespace(getDb(), editorObject); + + } + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("Database operation exception occured while plsourceviewer refresh ..", + exception); + } catch (DatabaseCriticalException exception) { + MPPDBIDELoggerUtility.error("Database critical exception occured while plsourceviewer refresh ..", + exception); + } + UIElement.getInstance().updateTextEditorsIconAndConnButtons(ns.getServer()); + } + }); + + } + + /** + * Handle namespace. + * + * @param db the db + * @param editorObject the editor object + * @return true, if successful + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + private boolean handleNamespace(Database db, IDebugObject editorObject) + throws DatabaseOperationException, DatabaseCriticalException { + + if (null != editorObject) { + IDebugObject newSqlObject = db.getDebugObjectById(editorObject.getOid(), editorObject.getNameSpaceId()); + + if (newSqlObject != null) { + HandlerUtilities.displaySourceCodeInEditorFromUI(newSqlObject, true); + } + } + + return true; + } + + /** + * Canceling. + */ + @Override + protected void canceling() { + super.canceling(); + if (!status.getCancel()) { + status.setCancel(true); + DBConnection conn = getConn(); + if (null != conn) { + try { + conn.cancelQuery(); + } catch (DatabaseCriticalException exception) { + MPPDBIDELoggerUtility.error("Database critical exception occured while cancel query...", exception); + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("Database operation exception occured while cancel query...", + exception); + } + } + } + } + + /** + * Gets the error message. + * + * @return the error message + */ + @Override + String getErrorMessage() { + return MessageConfigLoader.getProperty(IMessagesConstants.NAMESPACE_RETRIVE_ERROR); + } + + /** + * Sets the load failed. + */ + @Override + void setLoadFailed() { + currentNameSpace.setLoadFailed(); + super.setLoadFailed(); + } + + /** + * Gets the message dialog title. + * + * @return the message dialog title + */ + @Override + String getMessageDialogTitle() { + return MessageConfigLoader.getProperty(IMessagesConstants.ERR_TITLE_DB_CRITICAL_ERROR); + } + + /** + * Gets the message dialog message. + * + * @return the message dialog message + */ + @Override + String getMessageDialogMessage() { + return MessageConfigLoader.getProperty(IMessagesConstants.NAMESPACE_RETRIVE_ERROR, currentNameSpace.getName()); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LazyServerObjectBackendLoader.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LazyServerObjectBackendLoader.java new file mode 100644 index 0000000000000000000000000000000000000000..c074898c20e5dd744fd39b5d1150be8f0e26530e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LazyServerObjectBackendLoader.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.util.IExecTimer; +import org.opengauss.mppdbide.presentation.objectbrowser.ObjectBrowserObjectRefreshPresentation; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.messaging.StatusMessage; + +/** + * + * Title: class + * + * Description: The Class LazyServerObjectBackendLoader. + * + * @since 3.0.0 + */ +public class LazyServerObjectBackendLoader extends LazyBackendLoader { + private ServerObject objToLoad; + + /** + * Instantiates a new lazy server object backend loader. + * + * @param tableToLoad the table to load + * @param statusMsg the status msg + * @param timer the timer + */ + LazyServerObjectBackendLoader(ServerObject tableToLoad, StatusMessage statusMsg, IExecTimer timer) { + super("Backend Lazy load Table-", null, statusMsg, timer); + this.objToLoad = tableToLoad; + setDb(tableToLoad.getDatabase()); + } + + /** + * Do job. + * + * @return the object + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws MPPDBIDEException the MPPDBIDE exception + * @throws Exception the exception + */ + @Override + public Object doJob() throws DatabaseOperationException, DatabaseCriticalException, MPPDBIDEException, Exception { + ObjectBrowserObjectRefreshPresentation.refreshSeverObject(objToLoad); + return null; + } + + /** + * Gets the error message. + * + * @return the error message + */ + @Override + String getErrorMessage() { + return MessageConfigLoader.getProperty(IMessagesConstants.TABLE_RETRIVE_ERROR); + } + + /** + * Sets the load failed. + */ + @Override + void setLoadFailed() { + super.setLoadFailed(); + } + + /** + * Gets the message dialog title. + * + * @return the message dialog title + */ + @Override + String getMessageDialogTitle() { + return MessageConfigLoader.getProperty(IMessagesConstants.ERR_LAZY_LOADING_TABLE); + } + + /** + * Gets the message dialog message. + * + * @return the message dialog message + */ + @Override + String getMessageDialogMessage() { + return MessageConfigLoader.getProperty(IMessagesConstants.TABLE_RETRIVE_ERROR, objToLoad.getName()); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LoadLevel1Objects.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LoadLevel1Objects.java new file mode 100644 index 0000000000000000000000000000000000000000..d829505e4b19d78d6f663bddb1639fcf44812edd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LoadLevel1Objects.java @@ -0,0 +1,423 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.swt.widgets.Display; + +import org.opengauss.mppdbide.bl.serverdatacache.AccessMethod; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.ILazyLoadObject; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.UserNamespace; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.DBTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; +import org.opengauss.mppdbide.bl.serverdatacache.groups.DatabaseObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.SystemNamespaceObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.UserNamespaceObjectGroup; +import org.opengauss.mppdbide.bl.util.ExecTimer; +import org.opengauss.mppdbide.bl.util.IExecTimer; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.StatusMessage; +import org.opengauss.mppdbide.utils.messaging.StatusMessageList; +import org.opengauss.mppdbide.view.ui.ObjectBrowser; +import org.opengauss.mppdbide.view.utils.BottomStatusBar; +import org.opengauss.mppdbide.view.utils.UIElement; + +/** + * + * Title: class + * + * Description: The Class LoadLevel1Objects. + * + * @since 3.0.0 + */ +public class LoadLevel1Objects { + private Object obj; + private StatusMessage statusMsg; + private IExecTimer timer; + private static final Object LOCK = new Object(); + private static final String OLAP_PG_CATALOG = "pg_catalog"; + + /** + * Instantiates a new load level 1 objects. + * + * @param object the object + * @param statusMessege the status messege + */ + public LoadLevel1Objects(Object object, StatusMessage statusMessege) { + this.obj = object; + this.statusMsg = statusMessege; + this.timer = null; + } + + /** + * Load objects. + * + * @throws DatabaseCriticalException the database critical exception + */ + public void loadObjects() throws DatabaseCriticalException { + loadTableAndViewObjects(); + + if (obj instanceof Server) { + loadServerObjects(); + } else if (obj instanceof DatabaseObjectGroup) { + loadDatabaseObjectGroup(); + } else if (obj instanceof Database) { + loadDatabaseObjects(); + } else if (obj instanceof Namespace) { + loadNamespaceObjects(); + } else if (obj instanceof UserNamespaceObjectGroup) { + loadUserNamespaceObjectGroup(); + } else if (obj instanceof SystemNamespaceObjectGroup) { + loadSystemNamespaceObjectGroup(); + } + + } + + /** + * Load database objects. + */ + private void loadDatabaseObjects() { + Database db = (Database) obj; + timer = new ExecTimer("Refresh DB:" + db.getName()).start(); + loadDataBasesObjects(db, db.getName()); + db.setLoadingNamespaceInProgress(false); + } + + /** + * Load system namespace object group. + */ + private void loadSystemNamespaceObjectGroup() { + List nsList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + SystemNamespaceObjectGroup sysNsGroup = (SystemNamespaceObjectGroup) obj; + timer = new ExecTimer("Refresh User Namespace Group: " + sysNsGroup.getName()).start(); + Namespace ns = null; + Set inclusion = this.getFastLoadNamespaceList(sysNsGroup.getDatabase()); + for (String searchPath : inclusion) { + ns = sysNsGroup.get(searchPath); + if (null != ns) { + ns.setNotLoaded(); + nsList.add(ns); + } + } + loadNameSpaceObjects(nsList, sysNsGroup.getDatabase().getName(), false, false); + sysNsGroup.getDatabase().setLoadingSystemNamespaceInProgress(false); + } + + /** + * Load user namespace object group. + */ + private void loadUserNamespaceObjectGroup() { + List nsList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + UserNamespaceObjectGroup userNsGroup = (UserNamespaceObjectGroup) obj; + timer = new ExecTimer("Refresh User Namespace Group: " + userNsGroup.getName()).start(); + Namespace ns = null; + Set inclusion = this.getFastLoadNamespaceList(userNsGroup.getDatabase()); + for (String searchPath : inclusion) { + ns = userNsGroup.get(searchPath); + if (null != ns) { + ns.setNotLoaded(); + nsList.add(ns); + } + } + + loadNameSpaceObjects(nsList, userNsGroup.getDatabase().getName(), false, true); + userNsGroup.getDatabase().setLoadingUserNamespaceInProgress(false); + } + + /** + * Load namespace objects. + */ + private void loadNamespaceObjects() { + /* + * On refresh of namespace, if that selected namespace is there in + * exclusion list, it should be removed from it + */ + updateSchemaExclusionList(); + + List nsList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + Namespace ns = (Namespace) obj; + timer = new ExecTimer("Refresh Namespace : " + ns.getName()).start(); + ns.setNotLoaded(); + nsList.add(ns); + if (obj instanceof UserNamespace) { + loadNameSpaceObjects(nsList, ns.getDatabaseName(), true, true); + ns.getDatabase().setLoadingUserNamespaceInProgress(false); + } else { + loadNameSpaceObjects(nsList, ns.getDatabaseName(), true, false); + ns.getDatabase().setLoadingSystemNamespaceInProgress(false); + } + } + + /** + * Load database object group. + * + * @throws DatabaseCriticalException the database critical exception + */ + private void loadDatabaseObjectGroup() throws DatabaseCriticalException { + /* + * There is lot of duplication between this block and above + * block(Server) But This is a much cleaner setting because in future + * load logic of server will change + */ + boolean dbHasNext = false; + DatabaseObjectGroup dbg = (DatabaseObjectGroup) obj; + timer = new ExecTimer("Refresh Database Group : " + dbg.getName()).start(); + Database database = null; + Iterator databases = dbg.getServer().getAllDatabases().iterator(); + dbHasNext = databases.hasNext(); + int dbCount = 0; + while (dbHasNext) { + database = databases.next(); + if (database.isConnected() && !database.isLoadingNamespaceInProgress()) { + statusBarManager(dbCount); + loadDataBasesObjects(database, database.getName()); + dbCount++; + } + dbHasNext = databases.hasNext(); + } + dbg.setLoadingDatabaseGroupInProgress(false); + if (dbCount == 0) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_NO_CONNECTION_AVAILABLE)); + throw new DatabaseCriticalException( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_NO_CONNECTION_AVAILABLE)); + } + } + + /** + * Load server objects. + * + * @throws DatabaseCriticalException the database critical exception + */ + private void loadServerObjects() throws DatabaseCriticalException { + boolean dbHasNext = false; + Server server = (Server) obj; + timer = new ExecTimer("Refresh Server : " + server.getName()).start(); + Database database = null; + Iterator databases = server.getAllDatabases().iterator(); + dbHasNext = databases.hasNext(); + int dbCount = 0; + while (dbHasNext) { + database = databases.next(); + if (database.isConnected() && !database.isLoadingNamespaceInProgress()) { + statusBarManager(dbCount); + loadDataBasesObjects(database, database.getName()); + dbCount++; + } + dbHasNext = databases.hasNext(); + } + server.setServerInProgress(false); + if (dbCount == 0) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_NO_CONNECTION_AVAILABLE)); + throw new DatabaseCriticalException(IMessagesConstants.ERR_NO_CONNECTION_AVAILABLE); + } + } + + /** + * Load table and view objects. + */ + private void loadTableAndViewObjects() { + if (obj instanceof TableMetaData || obj instanceof ViewMetaData) { + timer = new ExecTimer("Refresh Object Details : " + ((ServerObject) obj).getName()).start(); + startServerObjectLoadUIJob(); + } + } + + /** + * Update schema exclusion list. + */ + private void updateSchemaExclusionList() { + Database db = ((Namespace) obj).getDatabase(); + Server server = db.getServer(); + IServerConnectionInfo serverConnectionInfo = server.getServerConnectionInfo(); + Set newExcludeList = serverConnectionInfo.getModifiedSchemaExclusionList(); + newExcludeList.remove(((Namespace) obj).getName()); + serverConnectionInfo.setModifiedSchemaExclusionList(newExcludeList); + } + + /** + * Start server object load UI job. + */ + private void startServerObjectLoadUIJob() { + synchronized (LOCK) { + ObjectBrowser objectBrowser = UIElement.getInstance().getObjectBrowserModel(); + if (null != objectBrowser) { + + LazyLoadServerObjectUIJob loadNameSpace = new LazyLoadServerObjectUIJob(Display.getDefault(), + "Server object Loading", obj, objectBrowser.getTreeViewer(), statusMsg, timer); + loadNameSpace.schedule(); + } + } + } + + /** + * Load name space objects. + * + * @param namespaceList the namespace list + * @param objectName the object name + * @param isDBLoad the is DB load + * @param isUserSchema the is user schema + */ + private void loadNameSpaceObjects(List namespaceList, String objectName, boolean isDBLoad, + boolean isUserSchema) { + ObjectBrowser objectBrowser = UIElement.getInstance().getObjectBrowserModel(); + String jobName = "Loading NameSpace objects of Database: " + objectName; + if (objectBrowser != null) { + LazyLoadNamespace loadNameSpace = new LazyLoadNamespace(Display.getDefault(), jobName, namespaceList, + objectBrowser.getTreeViewer(), statusMsg, objectName, timer, isDBLoad, isUserSchema); + loadNameSpace.schedule(); + } + } + + /** + * Gets the fast load namespace list. + * + * @param db the db + * @return the fast load namespace list + */ + private Set getFastLoadNamespaceList(Database db) { + List namespaces = db.getSearchPathHelper().getSearchPath(); + Set inclusions = new HashSet(namespaces); + List defaultSchemasToLoad = getDefaultSchemasToLoad(); + Server server = db.getServer(); + IServerConnectionInfo serverConnectionInfo = server.getServerConnectionInfo(); + inclusions.addAll(defaultSchemasToLoad); + inclusions.addAll(serverConnectionInfo.getModifiedSchemaInclusionList()); + inclusions.removeAll(serverConnectionInfo.getModifiedSchemaExclusionList()); + + return inclusions; + } + + /** + * Gets the default schemas to load. + * + * @return the default schemas to load + */ + private List getDefaultSchemasToLoad() { + List schema = new ArrayList(); + schema.add(OLAP_PG_CATALOG); + return schema; + } + + /** + * Load data bases objects. + * + * @param db the db + * @param objectName the object name + */ + private void loadDataBasesObjects(final Database db, final String objectName) { + final List userNsList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + final List systemNsList = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + Set inclusions = this.getFastLoadNamespaceList(db); + Namespace userNameSapces = null; + Namespace systemNameSpaces = null; + for (String searchPath : inclusions) { + if (db.getDBType() == DBTYPE.OPENGAUSS) { + userNameSapces = db.getUserNamespaceGroup().get(searchPath); + if (null != userNameSapces) { + userNameSapces.setNotLoaded(); + userNsList.add(userNameSapces); + } + systemNameSpaces = db.getSystemNamespaceGroup().get(searchPath); + if (null != systemNameSpaces) { + systemNameSpaces.setNotLoaded(); + systemNsList.add(systemNameSpaces); + } + } + } + final boolean expandObjectInViewer = false; + String jobName = "Load Database Objects: " + db.getDbName(); + Job job = loadDatabaseObjects(db, objectName, userNsList, systemNsList, expandObjectInViewer, jobName); + job.schedule(); + if (userNsList.size() == 0 && systemNsList.size() == 0) { + try { + timer.stopAndLog(); + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("Exception while getting elapsed time", exception); + } + } + } + + private Job loadDatabaseObjects(final Database db, final String objectName, final List userNsList, + final List SystemNsList, final boolean expandObjectInViewer, String jobName) { + Job job = new Job(jobName) { + @Override + protected IStatus run(IProgressMonitor monitor) { + + try { + db.fetchAllTablespace(); + AccessMethod.fetchAllAccessMethods(db); + db.fetchAllDatatypes(); + + } catch (DatabaseCriticalException exception) { + MPPDBIDELoggerUtility.error("Loading TableSpace/AccessMethod/Datatype failed.", exception); + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("Loading TableSpace/AccessMethod/Datatype failed.", exception); + } + + if (db.getDBType() == DBTYPE.OPENGAUSS) { + loadNameSpaceObjects(userNsList, objectName, expandObjectInViewer, true); + loadNameSpaceObjects(SystemNsList, objectName, expandObjectInViewer, false); + } + return Status.OK_STATUS; + } + }; + return job; + } + + /** + * Status bar manager. + * + * @param dbCount the db count + */ + /* + * To add status message to statusBarif server have more than one database + * connected initialy messasge would be added inRefreshObjectBrowserItem + */ + private void statusBarManager(int dbCount) { + statusMsg = new StatusMessage(MessageConfigLoader.getProperty(IMessagesConstants.MSG_GUI_REFRESH_STATUSBAR)); + if (dbCount > 0) { + StatusMessageList.getInstance().push(statusMsg); + + final BottomStatusBar bottomStatusBar = UIElement.getInstance().getProgressBarOnTop(); + if (bottomStatusBar != null) { + bottomStatusBar.activateStatusbar(); + } + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LoadingUIElement.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LoadingUIElement.java new file mode 100644 index 0000000000000000000000000000000000000000..695337b849bdb8b63bcbe43facf843c6b0577b1f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/LoadingUIElement.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import org.eclipse.swt.graphics.Image; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; + +/** + * + * Title: class + * + * Description: The Class LoadingUIElement. + * + * @since 3.0.0 + */ +public class LoadingUIElement { + private static final String DISPLAY_NAME = MessageConfigLoader.getProperty(IMessagesConstants.LOADING_NS); + private static final Image DISPLAY_IMAGE = IconUtility.getIconImage(IconUtility.ICO_LOAD, LoadingUIElement.class); + + /** + * Gets the display name. + * + * @return the display name + */ + public String getDisplayName() { + return DISPLAY_NAME; + } + + /** + * Gets the displayimage. + * + * @return the displayimage + */ + public Image getDisplayimage() { + return DISPLAY_IMAGE; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/MaximumRecordsValidator.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/MaximumRecordsValidator.java new file mode 100644 index 0000000000000000000000000000000000000000..4cac9ba2721d5250651d19856f722672ac85749f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/MaximumRecordsValidator.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import org.eclipse.swt.events.VerifyEvent; +import org.eclipse.swt.events.VerifyListener; +import org.eclipse.swt.widgets.Text; + +import org.opengauss.mppdbide.view.utils.IUserPreference; + +/** + * + * Title: class + * + * Description: The Class MaximumRecordsValidator. + * + * @since 3.0.0 + */ +public class MaximumRecordsValidator implements VerifyListener { + /** + * The port number provided by the user. + */ + private Text listenerMaxRecords; + + private static final int MIN_RECORDS_ALLOWED = 0; + + /** + * Instantiates a new maximum records validator. + * + * @param maxRecords the max records + */ + public MaximumRecordsValidator(Text maxRecords) { + listenerMaxRecords = maxRecords; + } + + /** + * Verify text. + * + * @param event the event + */ + @Override + public void verifyText(VerifyEvent event) { + final String oldMaxRecords = listenerMaxRecords.getText(); + final String newMaxRecords = oldMaxRecords.substring(0, event.start) + event.text + + oldMaxRecords.substring(event.end); + + if (0 != newMaxRecords.length()) { + try { + // Validates the input is integer value only. + if (Integer.parseInt(newMaxRecords) < MIN_RECORDS_ALLOWED) { + event.doit = false; + } + else if (Integer.parseInt(newMaxRecords) > IUserPreference.MAX_RESULTSET_FETCH_COUNT) { + event.doit = false; + } + } catch (final NumberFormatException numberFormatException) { + event.doit = false; + } + } + + } + + /** + * Gets the min allowed records. + * + * @return the min allowed records + */ + public int getMinAllowedRecords() { + return MIN_RECORDS_ALLOWED; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ObjectBrowserContentProvider.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ObjectBrowserContentProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..82f802deafa9d495478598d5db15410572f60237 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ObjectBrowserContentProvider.java @@ -0,0 +1,201 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import java.util.Collection; + +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.TreeViewer; +import org.eclipse.jface.viewers.Viewer; + +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.IndexMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.PartitionTable; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.groups.DebugObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ForeignTableGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.IndexList; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ObjectList; +import org.opengauss.mppdbide.bl.serverdatacache.groups.SequenceObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.TableObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.TablespaceObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ViewColumnList; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ViewObjectGroup; + +/** + * Title: class Description: The Class ObjectBrowserContentProvider. + * + * @since 3.0.0 + */ +public class ObjectBrowserContentProvider implements ITreeContentProvider { + private TreeViewer viewer = null; + + /** + * Dispose. + */ + @Override + public void dispose() { + // No Cleanup activity as of now. May have to add. + } + + /** + * Input changed. + * + * @param treeViewer the tree viewer + * @param oldInput the old input + * @param newInput the new input + */ + @Override + public void inputChanged(Viewer treeViewer, Object oldInput, Object newInput) { + + this.viewer = (TreeViewer) treeViewer; + + } + + /** + * Gets the elements. + * + * @param connectionProfiles the connection profiles + * @return the elements + */ + @Override + public Object[] getElements(Object connectionProfiles) { + return ((Collection) connectionProfiles).toArray(); + } + + /** + * Gets the children. + * + * @param parentElement the parent element + * @return the children + */ + @Override + public Object[] getChildren(Object parentElement) { + if (!loadNextLevelData(parentElement, viewer)) { + return new Object[] {new LoadingUIElement()}; + } + + if (parentElement instanceof ObjectGroup) { + ObjectGroup groupObject = (ObjectGroup) parentElement; + return getObjectGroupChildList(groupObject); + } + + if (parentElement instanceof ServerObject) { + ServerObject obj = (ServerObject) parentElement; + if (obj.isLoadingInProgress()) { + return new Object[] {new LoadingUIElement()}; + } + if (obj instanceof Namespace) { + Namespace ns = (Namespace) obj; + if (ns.isNotLoaded()) { + return new Object[0]; + } + } + + return obj.getChildren(); + } + + else if (parentElement instanceof ObjectList) { + return ((ObjectList) parentElement).getList().toArray(); + } + + if (parentElement instanceof ViewColumnList) { + ViewColumnList colList = (ViewColumnList) parentElement; + return colList.getList().toArray(); + } + + if (parentElement instanceof Server) { + Server node = (Server) parentElement; + return node.getChildren(); + } + + return new Object[0]; + } + + /** + * to get the Child Object List of Object Group + * + * @param groupObject object group whose child object need to be get + * @return return object group child + */ + protected Object[] getObjectGroupChildList(ObjectGroup groupObject) { + return groupObject.getChildren(); + } + + /** + * Gets the parent. + * + * @param element the element + * @return the parent + */ + @Override + public Object getParent(Object element) { + return null; + } + + /** + * Checks for children. + * + * @param element the element + * @return true, if successful + */ + @Override + public boolean hasChildren(Object element) { + + boolean isElmntHasChildren = checkElementHasChildren(element); + + boolean isElementHasChildren = element instanceof DebugObjectGroup || element instanceof Namespace + || element instanceof TableMetaData || element instanceof IndexList + || element instanceof TableObjectGroup || isElmntHasChildren; + + if (element instanceof Server || element instanceof Database || element instanceof ObjectList + || isElementHasChildren || element instanceof ObjectGroup) { + return true; + } + return false; + } + + private boolean checkElementHasChildren(Object element) { + return element instanceof PartitionTable || element instanceof TablespaceObjectGroup + || element instanceof ViewObjectGroup || element instanceof ForeignTableGroup + || element instanceof ViewMetaData || element instanceof SequenceObjectGroup; + } + + /** + * loadNextLevelData - Load Next level data like Level 2, Level 3 etc. + * + * @param obj the obj + * @param currViewer the curr viewer + * @return true, if successful + */ + private boolean loadNextLevelData(final Object obj, TreeViewer currViewer) { + if (obj instanceof ColumnMetaData && !((ColumnMetaData) obj).isLoaded()) { + return false; + } else if (obj instanceof ConstraintMetaData && !((ConstraintMetaData) obj).isLoaded()) { + return false; + } else if (obj instanceof IndexMetaData && !((IndexMetaData) obj).isLoaded()) { + return false; + } + return true; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ObjectBrowserLabelProvider.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ObjectBrowserLabelProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..c8e6b81573e904f9e862135670f7e1182164e614 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ObjectBrowserLabelProvider.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import org.eclipse.jface.viewers.ColumnLabelProvider; +import org.eclipse.swt.graphics.Image; + +import org.opengauss.mppdbide.bl.serverdatacache.GaussOLAPDBMSObject; +import org.opengauss.mppdbide.bl.serverdatacache.ShowMoreObject; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class ObjectBrowserLabelProvider. + * + * @since 3.0.0 + */ +public class ObjectBrowserLabelProvider extends ColumnLabelProvider { + private ObjectBrowserLabelProviderForGaussOLAP gaussOlapLp = null; + + /** + * Instantiates a new object browser label provider. + */ + public ObjectBrowserLabelProvider() { + gaussOlapLp = new ObjectBrowserLabelProviderForGaussOLAP(); + } + + /** + * Gets the text. + * + * @param element the element + * @return the text + */ + @Override + public String getText(Object element) { + if (element instanceof GaussOLAPDBMSObject) { + if (gaussOlapLp != null) { + return gaussOlapLp.getText(element); + } + } + if (element instanceof LoadingUIElement) { + return ((LoadingUIElement) element).getDisplayName(); + } else if (element instanceof ShowMoreObject && gaussOlapLp != null) { + return gaussOlapLp.getText(element); + } + + // Will be hit only when new datatypes are displayed in further + // iterations + return MessageConfigLoader.getProperty(IMessagesConstants.OBJECT_BROWSER_LABEL_MSG); + } + + /** + * Gets the tool tip text. + * + * @param element the element + * @return the tool tip text + */ + @Override + public String getToolTipText(Object element) { + if (element instanceof GaussOLAPDBMSObject) { + if (gaussOlapLp != null) { + return gaussOlapLp.getToolTipText(element); + } + } else if (element instanceof ShowMoreObject) { + return gaussOlapLp.getToolTipText(element); + } + return null; + } + + /** + * Gets the image. + * + * @param element the element + * @return the image + */ + @Override + public Image getImage(Object element) { + if (element instanceof GaussOLAPDBMSObject) { + if (gaussOlapLp != null) { + return gaussOlapLp.getImage(element); + } + } else if (element instanceof LoadingUIElement) { + return ((LoadingUIElement) element).getDisplayimage(); + } else if (element instanceof ShowMoreObject) { + return gaussOlapLp.getImage(element); + } + return null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ObjectBrowserLabelProviderForGaussOLAP.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ObjectBrowserLabelProviderForGaussOLAP.java new file mode 100644 index 0000000000000000000000000000000000000000..b0c867dfe3ae40139c80e808888d0561e0a65731 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ObjectBrowserLabelProviderForGaussOLAP.java @@ -0,0 +1,328 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import org.eclipse.swt.graphics.Image; + +import org.opengauss.mppdbide.bl.serverdatacache.ColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ConstraintMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DebugObjects; +import org.opengauss.mppdbide.bl.serverdatacache.IndexMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.SequenceMetadata; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.ShowMoreObject; +import org.opengauss.mppdbide.bl.serverdatacache.SynonymMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.Tablespace; +import org.opengauss.mppdbide.bl.serverdatacache.TriggerMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.UserRole; +import org.opengauss.mppdbide.bl.serverdatacache.ViewColumnMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.ViewMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.groups.DatabaseObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.DebugObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ForeignTableGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.IndexList; +import org.opengauss.mppdbide.bl.serverdatacache.groups.OLAPObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.OLAPObjectList; +import org.opengauss.mppdbide.bl.serverdatacache.groups.SequenceObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.SynonymObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.SystemNamespaceObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.TableObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.TablespaceObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.TriggerObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.UserNamespaceObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.UserRoleObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ViewObjectGroup; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * + * Title: class + * + * Description: The Class ObjectBrowserLabelProviderForGaussOLAP. + * + * @since 3.0.0 + */ +public class ObjectBrowserLabelProviderForGaussOLAP extends AbstarctObjectBrowserLabelProvider { + + /** + * Gets the text. + * + * @param element the element + * @return the text + */ + @Override + public String getText(Object element) { + if (element instanceof ServerObject) { + return ((ServerObject) element).getObjectBrowserLabel(); + } else if (element instanceof Server) { + Server node = (Server) element; + return node.getDisplayNameForDomain(); + } else if (element instanceof OLAPObjectGroup) { + return ((OLAPObjectGroup) element).getObjectBrowserLabel(); + } else if (element instanceof OLAPObjectList) { + return ((OLAPObjectList) element).getName(); + } + + // Will be hit only when new datatypes are displayed in further + // iterations + return MessageConfigLoader.getProperty(IMessagesConstants.OBJECT_BROWSER_LABEL_MSG); + } + + /** + * Gets the tool tip text. + * + * @param element the element + * @return the tool tip text + */ + @Override + public String getToolTipText(Object element) { + if (element instanceof Server) { + Server serv = (Server) element; + return getToolTipTextHelper(serv); + } + return null; + } + + /** + * Gets the image. + * + * @param element the element + * @return the image + */ + @Override + public Image getImage(Object element) { + Image retImage = getImageOne(element); + + if (null == retImage) { + retImage = getImageTwo(element); + } + + if (null == retImage) { + retImage = getImageThree(element); + } + + if (null == retImage) { + return getImagePart2(element); + } else { + return retImage; + } + + } + + /** + * Gets the image three. + * + * @param element the element + * @return the image three + */ + private Image getImageThree(Object element) { + Image retImage = null; + if (element instanceof ViewObjectGroup) { + retImage = IconUtility.getIconImage(IiconPath.ICO_VIEWS, getClass()); + } else if (element instanceof TablespaceObjectGroup) { + retImage = IconUtility.getIconImage(IiconPath.TABLESPACE_GROUP, getClass()); + } else if (element instanceof DatabaseObjectGroup) { + retImage = IconUtility.getIconImage(IiconPath.DATABASE_GROUP, getClass()); + } else if (element instanceof IndexList) { + retImage = IconUtility.getIconImage(IiconPath.ICO_INDEXES, getClass()); + } + + else if (element instanceof Tablespace) { + retImage = IconUtility.getIconImage(IiconPath.TABLESPACE, getClass()); + } else if (element instanceof UserRoleObjectGroup) { + retImage = IconUtility.getIconImage(IiconPath.USER_ROLE_GROUP, getClass()); + } else if (element instanceof UserRole) { + if (((UserRole) element).getRolCanLogin()) { + retImage = IconUtility.getIconImage(IiconPath.USER_ROLE_CAN_LOGIN, getClass()); + } else { + retImage = IconUtility.getIconImage(IiconPath.USER_ROLE_CAN_NOT_LOGIN, getClass()); + } + } + return retImage; + } + + /** + * Gets the image two. + * + * @param element the element + * @return the image two + */ + private Image getImageTwo(Object element) { + Image retImage = null; + if (element instanceof Namespace) { + retImage = IconUtility.getIconImage(IiconPath.ICO_NAMESPACE, getClass()); + } else if (element instanceof DebugObjectGroup) { + retImage = IconUtility.getIconForDebugObjectType(((DebugObjectGroup) element).getObjectGroupType()); + } else if (element instanceof DebugObjects) { + retImage = IconUtility.getIconForDebugObjectType(((DebugObjects) element).getObjectType()); + } else if (element instanceof ForeignTableGroup) { + retImage = IconUtility.getIconImage(IiconPath.FOREIGN_TABLE_GROUP, getClass()); + } else if (element instanceof SequenceObjectGroup) { + retImage = IconUtility.getIconImage(IiconPath.SEQUENCE_OBJECT_GROUP, getClass()); + } else if (element instanceof SequenceMetadata) { + retImage = IconUtility.getIconImage(IiconPath.SEQUENCE_OBJECT, getClass()); + } else if (element instanceof SynonymObjectGroup) { + retImage = IconUtility.getIconImage(IiconPath.ICO_SYNONYMS, getClass()); + } else if (element instanceof SynonymMetaData) { + retImage = IconUtility.getIconImage(IiconPath.ICO_SYNONYM, getClass()); + } else if (element instanceof TriggerObjectGroup) { + retImage = IconUtility.getIconImage(IiconPath.ICO_TRIGGERS, getClass()); + } else if (element instanceof TriggerMetaData) { + TriggerMetaData metaData = (TriggerMetaData) element; + String path = metaData.getEnable() ? IiconPath.ICO_TRIGGER_ENABLE : + IiconPath.ICO_TRIGGER_DISABLE; + retImage = IconUtility.getIconImage(path, getClass()); + } else if (element instanceof TableObjectGroup) { + retImage = IconUtility.getIconImage(IiconPath.ICO_TABLES, getClass()); + } + + return retImage; + } + + /** + * Gets the image one. + * + * @param element the element + * @return the image one + */ + private Image getImageOne(Object element) { + Image retImage = null; + + if (element instanceof TableMetaData) { + retImage = getTablemetaDataImage(element); + + } else if (element instanceof ViewMetaData) { + retImage = IconUtility.getIconImage(IiconPath.ICO_VIEW, getClass()); + } else if (element instanceof Server) { + retImage = IconUtility.getIconImage(IiconPath.ICO_SERVER, getClass()); + } else if (element instanceof Database) { + retImage = getDatabaseImage(element); + } else if (element instanceof UserNamespaceObjectGroup) { + retImage = IconUtility.getIconImage(IiconPath.ICO_USER_NAMESPACE_GROUP, getClass()); + } else if (element instanceof SystemNamespaceObjectGroup) { + retImage = IconUtility.getIconImage(IiconPath.ICO_SYSTEM_NAMESPACE_GROUP, getClass()); + } else if (element instanceof ShowMoreObject) { + retImage = IconUtility.getIconImage(IiconPath.ICO_LOAD, getClass()); + } else if (element instanceof TableObjectGroup) { + return IconUtility.getIconImage(IiconPath.ICO_TABLES, getClass()); + } else if (element instanceof ViewObjectGroup) { + return IconUtility.getIconImage(IiconPath.ICO_VIEWS, getClass()); + } else if (element instanceof Tablespace) { + return IconUtility.getIconImage(IiconPath.TABLESPACE, getClass()); + } + + return retImage; + } + + /** + * Gets the database image. + * + * @param element the element + * @return the database image + */ + private Image getDatabaseImage(Object element) { + Database db = (Database) element; + String icon = IiconPath.ICO_DISCONNECTED_DB; + if (db.isConnected()) { + icon = IiconPath.ICO_CONNECTED_DB; + } + + return IconUtility.getIconImage(icon, getClass()); + } + + /** + * Gets the tablemeta data image. + * + * @param element the element + * @return the tablemeta data image + */ + private Image getTablemetaDataImage(Object element) { + TableMetaData tData = (TableMetaData) element; + OBJECTTYPE tableType = tData.getType(); + String iconName = null; + + switch (tableType) { + + case TABLEMETADATA: { + iconName = IiconPath.ICO_TABLE; + break; + } + case FOREIGN_TABLE_GDS: { + iconName = IiconPath.FOREIGN_TABLE_GDS; + break; + } + case FOREIGN_TABLE_HDFS: { + iconName = IiconPath.FOREIGN_TABLE_HDFS; + break; + } + case PARTITION_TABLE: { + iconName = IiconPath.PARTITION_TABLE; + break; + } + case FOREIGN_PARTITION_TABLE: { + iconName = IiconPath.ICO_FOREIGN_PARTITION_TABLE; + break; + } + default: { + iconName = IiconPath.ICO_TABLE; + } + + } + return IconUtility.getIconImage(iconName, this.getClass()); + } + + /** + * Gets the image part 2. + * + * @param element the element + * @return the image part 2 + */ + private Image getImagePart2(Object element) { + if (element instanceof OLAPObjectList) { + OBJECTTYPE type = ((OLAPObjectList) element).getType(); + switch (type) { + case COLUMN_GROUP: + case VIEW_COLUMN_GROUP: { + return IconUtility.getIconImage(IiconPath.ICO_COLUMNS, getClass()); + } + case CONSTRAINT_GROUP: { + return IconUtility.getIconImage(IiconPath.ICO_CONSTRAINTS, getClass()); + } + default: { + break; + } + } + } else if (element instanceof ConstraintMetaData) { + return IconUtility.getIconImage(IiconPath.ICO_CONSTRAINTS, getClass()); + } else if (element instanceof IndexMetaData) { + return IconUtility.getIconImage(IiconPath.ICO_INDEX, getClass()); + } else if (element instanceof ColumnMetaData || element instanceof ViewColumnMetaData) { + return IconUtility.getIconImage(IiconPath.ICO_COLUMN, getClass()); + } else if (element instanceof OLAPObjectGroup) { + return IconUtility.getIconImage(IiconPath.ICO_CLOUD_NODES, getClass()); + } + + return IconUtility.getIconImage(IiconPath.ICO_TABLESPACE, getClass()); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ObjectBrowserLazyContentProvider.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ObjectBrowserLazyContentProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..22b6bbf8e55ff698eb17badc707c6f3e7544bcc4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ObjectBrowserLazyContentProvider.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import java.util.Collection; + +import org.eclipse.jface.viewers.ILazyTreeContentProvider; +import org.eclipse.jface.viewers.TreeViewer; +import org.eclipse.jface.viewers.Viewer; + +import org.opengauss.mppdbide.bl.serverdatacache.GaussOLAPDBMSObject; + +/** + * + * Title: class + * + * Description: The Class ObjectBrowserLazyContentProvider. + * + * @since 3.0.0 + */ +public class ObjectBrowserLazyContentProvider implements ILazyTreeContentProvider { + private TreeViewer viewer; + private ObjectBrowserLazyContentProviderForGaussOLAP gaussOlapCp = null; + + /** + * Instantiates a new object browser lazy content provider. + * + * @param viewer the viewer + */ + public ObjectBrowserLazyContentProvider(TreeViewer viewer) { + this.viewer = viewer; + gaussOlapCp = new ObjectBrowserLazyContentProviderForGaussOLAP(viewer); + } + + /** + * Dispose. + */ + @Override + public void dispose() { + + } + + /** + * Input changed. + * + * @param viewerInput the viewer input + * @param oldInput the old input + * @param newInput the new input + */ + @Override + public void inputChanged(Viewer viewerInput, Object oldInput, Object newInput) { + + } + + /** + * Update element. + * + * @param parent the parent + * @param index the index + */ + @Override + public void updateElement(Object parent, int index) { + Object element = null; + + if (parent instanceof Collection) { + Collection node = (Collection) parent; + element = node.toArray()[index]; + if (element != null) { + viewer.replace(parent, index, element); + updateChildCount(element, -1); + } + } else if (parent instanceof GaussOLAPDBMSObject) { + if (gaussOlapCp != null) { + gaussOlapCp.updateElement(parent, index); + } + return; + } + + } + + /** + * Update child count. + * + * @param element the element + * @param currentChildCount the current child count + */ + @Override + public void updateChildCount(Object element, int currentChildCount) { + int length = 0; + + if (element instanceof Collection) { + Collection node = (Collection) element; + length = node.size(); + viewer.setChildCount(element, length); + } else if (element instanceof GaussOLAPDBMSObject) { + if (gaussOlapCp != null) { + gaussOlapCp.updateChildCount(element, currentChildCount); + } + return; + } + } + + /** + * Gets the parent. + * + * @param element the element + * @return the parent + */ + @Override + public Object getParent(Object element) { + if (element instanceof GaussOLAPDBMSObject) { + if (gaussOlapCp != null) { + return gaussOlapCp.getParent(element); + } + } + return null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ObjectBrowserLazyContentProviderForGaussOLAP.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ObjectBrowserLazyContentProviderForGaussOLAP.java new file mode 100644 index 0000000000000000000000000000000000000000..dbf9dbd485d6948e28f0c0f3ff6e8bc2f7dec3c9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ObjectBrowserLazyContentProviderForGaussOLAP.java @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import org.eclipse.jface.viewers.TreeViewer; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.serverdatacache.groups.OLAPObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.OLAPObjectList; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class ObjectBrowserLazyContentProviderForGaussOLAP. + * + * @since 3.0.0 + */ +public class ObjectBrowserLazyContentProviderForGaussOLAP extends AbstractObjectBrowserLazyContentProvider { + + /** + * The viewer. + */ + protected TreeViewer viewer; + + /** + * Update element. + * + * @param parent the parent + * @param index the index + */ + @Override + public void updateElement(Object parent, int index) { + try { + Object element = null; + + if (parent instanceof ServerObject) { + ServerObject objct = (ServerObject) parent; + element = updateServerObject(objct, index); + if (objct instanceof Namespace) { + Namespace ns = (Namespace) objct; + if (ns.isNotLoaded()) { + element = new LoadingUIElement(); + } + } + + } else if (parent instanceof OLAPObjectGroup) { + element = ((OLAPObjectGroup) parent).getChildren()[index]; + } else if (parent instanceof Server) { + Server node = (Server) parent; + element = node.getChildren()[index]; + } else if (parent instanceof OLAPObjectList) { + element = ((OLAPObjectList) parent).getList().get(index); + } + + if (element != null) { + viewer.replace(parent, index, element); + updateChildCount(element, -1); + } + + } catch (ArrayIndexOutOfBoundsException exception) { + MPPDBIDELoggerUtility.error("Index Out Of Bound Exception, Error while Refreshing Tablespace", exception); + } + + } + + /** + * Instantiates a new object browser lazy content provider for gauss OLAP. + * + * @param viewer the viewer + */ + public ObjectBrowserLazyContentProviderForGaussOLAP(TreeViewer viewer) { + this.viewer = viewer; + } + + /** + * Update child count. + * + * @param element the element + * @param currentChildCount the current child count + */ + @Override + public void updateChildCount(Object element, int currentChildCount) { + int length = 0; + + if (element instanceof OLAPObjectGroup) { + OLAPObjectGroup groupObject = (OLAPObjectGroup) element; + length = groupObject.getChildren().length; + } else if (element instanceof ServerObject) { + ServerObject obj = (ServerObject) element; + if (obj.isLoadingInProgress()) { + length = 1; // loading UI + } else { + length = obj.getChildren().length; + } + if (obj instanceof Namespace) { + Namespace ns = (Namespace) obj; + if (ns.isNotLoaded()) { + length = -1; // loading UI + } + } else if (obj instanceof Database) { + if (!((Database) obj).isConnected()) { + length = 0; + } + } + } else if (element instanceof Server) { + Server node = (Server) element; + length = node.getChildren().length; + + } else if (element instanceof OLAPObjectList) { + length = ((OLAPObjectList) element).getList().size(); + } + + viewer.setChildCount(element, length); + + } + + /** + * Gets the parent. + * + * @param element the element + * @return the parent + */ + @Override + public Object getParent(Object element) { + if (element instanceof ServerObject) { + ServerObject obj = (ServerObject) element; + return obj.getParent(); + } else if (element instanceof OLAPObjectList) { + return ((OLAPObjectList) element).getParent(); + } + return null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ParameterInputDialog.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ParameterInputDialog.java new file mode 100644 index 0000000000000000000000000000000000000000..471b26e555bfe0800b7414f13c9accccd15934ac --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/ParameterInputDialog.java @@ -0,0 +1,605 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.eclipse.jface.resource.JFaceResources; +import org.eclipse.nebula.widgets.nattable.NatTable; +import org.eclipse.nebula.widgets.nattable.config.AbstractRegistryConfiguration; +import org.eclipse.nebula.widgets.nattable.config.CellConfigAttributes; +import org.eclipse.nebula.widgets.nattable.config.DefaultNatTableStyleConfiguration; +import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry; +import org.eclipse.nebula.widgets.nattable.config.IEditableRule; +import org.eclipse.nebula.widgets.nattable.copy.command.CopyDataCommandHandler; +import org.eclipse.nebula.widgets.nattable.copy.command.CopyDataToClipboardCommand; +import org.eclipse.nebula.widgets.nattable.edit.EditConfigAttributes; +import org.eclipse.nebula.widgets.nattable.edit.command.EditCellCommand; +import org.eclipse.nebula.widgets.nattable.grid.layer.DefaultGridLayer; +import org.eclipse.nebula.widgets.nattable.layer.DataLayer; +import org.eclipse.nebula.widgets.nattable.layer.cell.ColumnOverrideLabelAccumulator; +import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell; +import org.eclipse.nebula.widgets.nattable.style.CellStyleAttributes; +import org.eclipse.nebula.widgets.nattable.style.DisplayMode; +import org.eclipse.nebula.widgets.nattable.style.HorizontalAlignmentEnum; +import org.eclipse.nebula.widgets.nattable.style.Style; +import org.eclipse.nebula.widgets.nattable.ui.binding.UiBindingRegistry; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; + +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DefaultParameter; +import org.opengauss.mppdbide.bl.serverdatacache.IDebugObject; +import org.opengauss.mppdbide.bl.serverdatacache.INamespace; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.ObjectParameter; +import org.opengauss.mppdbide.bl.serverdatacache.ObjectParameter.PARAMETERTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.Message; +import org.opengauss.mppdbide.view.component.grid.core.DSNewTextCellEditor; +import org.opengauss.mppdbide.view.core.statusbar.ObjectBrowserStatusBarProvider; +import org.opengauss.mppdbide.view.ui.terminal.SQLTerminal; +import org.opengauss.mppdbide.view.uidisplay.UIDisplayUtil; +import org.opengauss.mppdbide.view.utils.UIElement; +import org.opengauss.mppdbide.view.utils.consts.UIConstants; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs; + +/** + * + * Title: class + * + * Description: The Class ParameterInputDialog. + * + * @since 3.0.0 + */ +public class ParameterInputDialog extends ExecDialog { + private static final String PARAMETER_NAME_LABEL = "parameterNameLabel"; + private static final String PARAMETER_TYPE_LABEL = "parameterTypeLabel"; + + /** + * The Constant PARAMETER_VALUE_LABEL. + */ + public static final String PARAMETER_VALUE_LABEL = "parameterValueLabel"; + private static final String EXEC = "EXEC "; + private static final String SELECT = "SELECT "; + + private IDebugObject debugObject; + private Server server; + private long debugObjectOid; + + private NatTable parameterInputNatTable; + private Button okBtn; + private Button cancelBtn; + private Button clearBtn; + + private ArrayList valueList = new ArrayList<>(); + + /** + * Instantiates a new parameter input dialog. + * + * @param parentShell the parent shell + * @param isDebug the is debug + */ + protected ParameterInputDialog(Shell parentShell) { + super(parentShell); + this.setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); + } + + /** + * Creates the contents. + * + * @param parent the parent + * @return the control + */ + @Override + protected Control createContents(Composite parent) { + Shell shell = getShell(); + shell.setText(MessageConfigLoader.getProperty(IMessagesConstants.EXECUTE_DEBUGE)); + + Composite container = new Composite(parent, SWT.BORDER); + container.setLayout(new GridLayout(1, false)); + GridData containerGD = new GridData(SWT.FILL, SWT.FILL, true, true); + container.setLayoutData(containerGD); + + DefaultGridLayer gridLayer = getGridLayer(valueList); + // automation need select first record of Value column + gridLayer.getBodyLayer().getSelectionLayer().setSelectedCell(2, 0); + parameterInputNatTable = new NatTable(container, gridLayer, false); + parameterInputNatTable.setLayout(new GridLayout(1, false)); + GridData parameterInputNatTableGD = new GridData(SWT.FILL, SWT.FILL, true, true); + parameterInputNatTableGD.widthHint = 565; + parameterInputNatTableGD.heightHint = 220; + parameterInputNatTable.setLayoutData(parameterInputNatTableGD); + parameterInputNatTable.addConfiguration(new DefaultNatTableStyleConfiguration()); + parameterInputNatTable.addConfiguration(new ParameterInputRegistryConfiguration()); + parameterInputNatTable.configure(); + super.buttonBar = createButtonBar(shell); + // automation need focus + parameterInputNatTable.setFocus(); + return container; + } + + /** + * Default parameter values. + */ + public void defaultParameterValues() { + List parameters = this.debugObject.getTemplateParameters(); + HashMap> valueMap = server.getDefaulParametertMap(); + + // no cache for parameter value + if (valueMap == null || valueMap.get(this.debugObjectOid) == null) { + parameters.stream().forEach(param -> valueList.add( + new DefaultParameter(param.getName(), param.getDataType(), param.getValue(), param.getType()))); + } else { + ArrayList oldValueList = valueMap.get(this.debugObjectOid); + ArrayList cloneValueList = new ArrayList(oldValueList.size()); + oldValueList.stream() + .forEach(oldValue -> cloneValueList.add( + new DefaultParameter(oldValue.getDefaultParameterName(), oldValue.getDefaultParameterType(), + oldValue.getDefaultParameterValue(), oldValue.getDefaultParameterMode()))); + valueList = cloneValueList; + } + } + + /** + * Creates the button bar. + * + * @param parent the parent + * @return the control + */ + @Override + protected Control createButtonBar(Composite parent) { + Composite composite = new Composite(parent, SWT.NONE); + composite.setLayout(new GridLayout(4, false)); + GridData compositeGD = new GridData(SWT.FILL, SWT.FILL, true, true); + composite.setLayoutData(compositeGD); + composite.setFont(parent.getFont()); + + // Add buttons to the button bar. + createButtonsForButtonBar(composite); + return composite; + } + + /** + * Creates the buttons for button bar. + * + * @param parent the parent + */ + @Override + protected void createButtonsForButtonBar(Composite parent) { + String tab = " "; + String okLabel = tab + MessageConfigLoader.getProperty(IMessagesConstants.BTN_OK) + tab; + String claerLabel = tab + MessageConfigLoader.getProperty(IMessagesConstants.BTN_CLEAR) + tab; + String cancelLabel = tab + MessageConfigLoader.getProperty(IMessagesConstants.BTN_CANCEL) + tab; + + Label outModeParamHintLabel = new Label(parent, SWT.NONE); + GridData outModeParamHintLabelGD = new GridData(SWT.FILL, SWT.FILL, true, true); + outModeParamHintLabel.setLayoutData(outModeParamHintLabelGD); + outModeParamHintLabel.setText(this.debugObject.getUsagehint()); + outModeParamHintLabel.setFont(JFaceResources.getTextFont()); + + clearBtn = createButton(parent, UIConstants.CLEAR_ID, claerLabel, 310); + okBtn = createButton(parent, UIConstants.OK_ID, okLabel, 400); + cancelBtn = createButton(parent, UIConstants.CANCEL_ID, cancelLabel, 490); + + } + + /** + * Creates the button. + * + * @param parent the parent + * @param id the id + * @param label the label + * @param space the space + * @return the button + */ + protected Button createButton(Composite parent, int id, String label, int space) { + Button button = new Button(parent, SWT.PUSH); + GridData buttonGD = new GridData(SWT.FILL, SWT.FILL, true, true); + button.setLayoutData(buttonGD); + button.setText(label); + button.setFont(JFaceResources.getDialogFont()); + button.setData(Integer.valueOf(id)); + setButtonLayoutData(button); + + button.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + buttonPressed(((Integer) event.widget.getData()).intValue()); + } + }); + + return button; + } + + /** + * Button pressed. + * + * @param buttonId the button id + */ + @Override + protected void buttonPressed(int buttonId) { + + if (UIConstants.OK_ID == buttonId) { + okBtn.setEnabled(false); + cancelBtn.setEnabled(false); + clearBtn.setEnabled(false); + + server.setDefaulParametertMap(this.debugObjectOid, valueList); + + this.executePressed(); + + close(); + } else if (UIConstants.CANCEL_ID == buttonId) { + this.cancelPressedValue(); + } else if (UIConstants.CLEAR_ID == buttonId) { + clearPressed(); + + } + } + + /** + * Sets the debug object. + * + * @param debugObj the debug obj + * @return true, if successful + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + */ + @Override + public boolean setDebugObject(IDebugObject debugObj) throws DatabaseOperationException, DatabaseCriticalException { + this.debugObject = debugObj; + this.debugObjectOid = debugObj.getOid(); + this.server = debugObject.getDatabase().getServer(); + + return super.setDebugObject(debugObj); + } + + /** + * Execute pressed. + */ + @Override + public void executePressed() { + Database db = this.debugObject.getDatabase(); + + String executionStatement = ""; + try { + executionStatement = getProcedureExecutionStatement(); + } catch (DatabaseOperationException exception) { + ObjectBrowserStatusBarProvider.getStatusBar().displayMessage(Message.getError(MessageConfigLoader + .getProperty(IMessagesConstants.OPERATION_CANNOT_BE_PERFOREMD, exception.getMessage()))); + MPPDBIDEDialogs.generateDSErrorDialog(MessageConfigLoader.getProperty(IMessagesConstants.EXECUTE_DEBUGE), + MessageConfigLoader.getProperty(IMessagesConstants.OPERATION_CANNOT_BE_PERFOREMD_TITLE), + MessageConfigLoader.getProperty(IMessagesConstants.OPERATION_CANNOT_BE_PERFOREMD, + exception.getServerMessage()), + exception); + UIDisplayUtil.getDebugConsole() + .logError(MessageConfigLoader.getProperty(IMessagesConstants.OPERATION_CANNOT_BE_PERFOREMD) + + exception.getMessage()); + return; + } + + SQLTerminal terminal = null; + // Create new terminal to execute the debug object if it is not current + // terminal + if (!debugObject.getCurrentTerminal()) { + terminal = UIElement.getInstance().createNewTerminal(db); + + } else { + terminal = UIElement.getInstance().getVisibleTerminal(); + } + + if (terminal == null) { + return; + } + + ArrayList inOutParaValueList = new ArrayList(); + ArrayList outParaValueList = this.debugObject.getOutParameters(); + + inOutParaValueList.addAll(valueList); + if (outParaValueList != null) { + inOutParaValueList.addAll(outParaValueList); + } + debugObject.setIsEditTerminalInputValues(true); + terminal.setDebugObject(debugObject); + terminal.setInputDailogValueTerminal(inOutParaValueList); + terminal.getTerminalCore().getDocument().set(executionStatement); + if (valueList != null && !valueList.isEmpty()) { + terminal.enableEditInputValueButton(true); + } + + terminal.getTerminalCore().setEditable(false); + terminal.handleExecution(); + } + + /** + * Clear pressed. + */ + private void clearPressed() { + valueList.stream().forEach(param -> param.setDefaultParameterValue("")); + parameterInputNatTable.refresh(); + } + + /** + * Gets the procedure execution statement. + * + * @return the procedure execution statement + * @throws DatabaseOperationException the database operation exception + */ + private String getProcedureExecutionStatement() throws DatabaseOperationException { + String sqlString = ""; + sqlString = generateExecutionTemplate(debugObject.getNamespace(), debugObject.getName(), + parameterInputNatTable == null ? null : server.getDefaulParametertMap().get(this.debugObjectOid), + debugObject.getType()); + return sqlString; + } + + /** + * Cancel pressed value. + */ + protected void cancelPressedValue() { + this.getShell().close(); + } + + /** + * Generate execution template. + * + * @param nameSpace the name space + * @param dbgObjName the dbg obj name + * @param params the params + * @param type the type + * @return the string + * @throws DatabaseOperationException the database operation exception + */ + public String generateExecutionTemplate(INamespace nameSpace, String dbgObjName, ArrayList params, + OBJECTTYPE type) throws DatabaseOperationException { + StringBuilder template = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + template.append(SELECT); + + if (nameSpace != null) { + template.append(nameSpace.getQualifiedObjectName()).append("."); + } + + template.append(ServerObject.getQualifiedObjectName(dbgObjName)); + + template.append(MPPDBIDEConstants.LINE_SEPARATOR); + template.append(MPPDBIDEConstants.LEFT_PARENTHESIS); + template.append(MPPDBIDEConstants.LINE_SEPARATOR); + createTemplateForParams(params, template); + + template.append(MPPDBIDEConstants.LINE_SEPARATOR); + template.append(MPPDBIDEConstants.RIGHT_PARENTHESIS); + template.append(MPPDBIDEConstants.LINE_SEPARATOR); + + return template.toString(); + } + + /** + * Creates the template for params. + * + * @param params the params + * @param template the template + * @throws DatabaseOperationException the database operation exception + */ + private void createTemplateForParams(ArrayList params, StringBuilder template) + throws DatabaseOperationException { + if (null != params) { + boolean isFirstParam = true; + boolean isEmptyParam = true; + + String argType = null; + String argName = null; + String argValue = null; + + DefaultParameter param = null; + int paramSize = params.size(); + + StringBuilder templateTemp = new StringBuilder(); + for (int cnt = 0; cnt < paramSize; cnt++) { + param = params.get(cnt); + + if (PARAMETERTYPE.IN.equals(param.getDefaultParameterMode()) + || PARAMETERTYPE.INOUT.equals(param.getDefaultParameterMode())) { + if (!isFirstParam) { + templateTemp.append(MPPDBIDEConstants.LINE_SEPARATOR); + } + + argType = param.getDefaultParameterType(); + argName = param.getDefaultParameterName(); + String defaultParameterValue = param.getDefaultParameterValue(); + if (StringUtils.isNotEmpty(defaultParameterValue)) { + isEmptyParam = false; + argValue = defaultParameterValue; + }else { + argValue = ""; + } + + + if (null != argType) { + if ("refcursor".equals(argType)) { + MPPDBIDELoggerUtility.error(MessageConfigLoader + .getProperty(IMessagesConstants.ERR_BL_REFCUR_EXECUTION_TEMPLATE_FAILURE)); + throw new DatabaseOperationException( + IMessagesConstants.ERR_BL_REFCUR_EXECUTION_TEMPLATE_FAILURE); + } else { + templateTemp.append(MPPDBIDEConstants.TAB); + templateTemp.append(argValue); + if (cnt < paramSize - 1) { + templateTemp.append(MPPDBIDEConstants.COMMA_SEPARATE); + } + templateTemp.append(MPPDBIDEConstants.TAB); + templateTemp.append(MPPDBIDEConstants.SEPARATOR); + templateTemp.append(MPPDBIDEConstants.SEPARATOR); + templateTemp.append(argName); + templateTemp.append(MPPDBIDEConstants.SPACE_CHAR); + templateTemp.append(argType); + } + } + + isFirstParam = false; + } + } + + if (!isEmptyParam) { + template.append(templateTemp); + } + } + } + + /** + * Register editors. + * + * @param configRegistry the config registry + */ + private void registerEditors(IConfigRegistry configRegistry) { + EditorText editorText = new EditorText(); + editorText.registerColumnThreeTextEditor(configRegistry); + } + + /** + * + * Title: class + * + * Description: The Class ParameterInputRegistryConfiguration. + */ + private class ParameterInputRegistryConfiguration extends AbstractRegistryConfiguration { + + @Override + public void configureRegistry(IConfigRegistry configRegistry) { + + Style cellStyle = new Style(); + cellStyle.setAttributeValue(CellStyleAttributes.HORIZONTAL_ALIGNMENT, HorizontalAlignmentEnum.LEFT); + + configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, cellStyle); + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, + IEditableRule.ALWAYS_EDITABLE, DisplayMode.EDIT, PARAMETER_VALUE_LABEL); + + registerEditors(configRegistry); + } + + @Override + public void configureUiBindings(UiBindingRegistry uiBindingRegistry) { + parameterInputNatTable.unregisterCommandHandler(EditCellCommand.class); + parameterInputNatTable.registerCommandHandler(new TableCellCommand()); + } + } + + /** + * + * Title: class + * + * Description: The Class EditorText. + */ + private static class EditorText { + + /** + * Register column three text editor. + * + * @param configRegistry the config registry + */ + private void registerColumnThreeTextEditor(IConfigRegistry configRegistry) { + // configure the multi line text editor for parameter value column + configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, + + new DSNewTextCellEditor(false), DisplayMode.EDIT, PARAMETER_VALUE_LABEL); + } + } + + /** + * Gets the grid layer. + * + * @param valueList the value list + * @return the grid layer + */ + private DefaultGridLayer getGridLayer(ArrayList valueList) { + final String parameterName = "defaultParameterName"; + final String parameterType = "defaultParameterType"; + final String parameterValue = "defaultParameterValue"; + + Map propertyToLabels = new HashMap(); + propertyToLabels.put(parameterName, + MessageConfigLoader.getProperty(IMessagesConstants.PARAMETER_INPUT_TABLE_PARAM_NAME_COLUMN)); + propertyToLabels.put(parameterType, + MessageConfigLoader.getProperty(IMessagesConstants.PARAMETER_INPUT_TABLE_PARAM_TYPE_COLUMN)); + propertyToLabels.put(parameterValue, + MessageConfigLoader.getProperty(IMessagesConstants.PARAMETER_INPUT_TABLE_PARAM_VALUE_COLUMN)); + + String[] propertyNames = new String[] {parameterName, parameterType, parameterValue}; + + DefaultGridLayer gridLayer = new DefaultGridLayer(valueList, propertyNames, propertyToLabels); + DataLayer bodyDataLayer = (DataLayer) gridLayer.getBodyDataLayer(); + // When too many parameters, ensure that won't appear around the slider + int cloumnWidth = 0; + // Number of list lines + int rows = 9; + if (valueList.size() > rows) { + cloumnWidth = 323; + } else { + cloumnWidth = 340; + } + bodyDataLayer.setColumnWidthByPosition(2, cloumnWidth, true); + + final ColumnOverrideLabelAccumulator columnLabelAccumulator = new ColumnOverrideLabelAccumulator(bodyDataLayer); + bodyDataLayer.setConfigLabelAccumulator(columnLabelAccumulator); + registerColumnLabels(columnLabelAccumulator); + + gridLayer.registerCommandHandler(new CopyDataCommandHandler(gridLayer.getBodyLayer().getSelectionLayer()) { + @Override + public boolean doCommand(CopyDataToClipboardCommand cmd) { + ILayerCell[][] assembleCopiedDataStruct = assembleCopiedDataStructure(); + if (null == assembleCopiedDataStruct) { + return true; + } else { + internalDoCommand(cmd, assembleCopiedDataStruct); + } + return true; + } + }); + + return gridLayer; + } + + /** + * Register column labels. + * + * @param columnLabelAccumulator the column label accumulator + */ + private void registerColumnLabels(ColumnOverrideLabelAccumulator columnLabelAccumulator) { + columnLabelAccumulator.registerColumnOverrides(0, PARAMETER_NAME_LABEL); + columnLabelAccumulator.registerColumnOverrides(1, PARAMETER_TYPE_LABEL); + columnLabelAccumulator.registerColumnOverrides(2, PARAMETER_VALUE_LABEL); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/SelectMenuItem.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/SelectMenuItem.java new file mode 100644 index 0000000000000000000000000000000000000000..794ff8951f83eb066ca308cf4f470127f0b916a1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/SelectMenuItem.java @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.MenuItem; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * + * Title: class + * + * Description: The Class SelectMenuItem. + * + * @since 3.0.0 + */ +public abstract class SelectMenuItem { + + /** + * The menu select all. + */ + protected MenuItem menuSelectAll; + + /** + * The menu copy. + */ + protected MenuItem menuCopy; + + /** + * Gets the menu select all. + * + * @return the menu select all + */ + public MenuItem getMenuSelectAll() { + return menuSelectAll; + } + + /** + * Gets the menu copy. + * + * @return the menu copy + */ + public MenuItem getMenuCopy() { + return menuCopy; + } + + /** + * Adds the select all menu item. + * + * @param menu the menu + */ + protected void addSelectAllMenuItem(Menu menu) { + menuSelectAll = new MenuItem(menu, SWT.PUSH); + menuSelectAll.setText(MessageConfigLoader.getProperty(IMessagesConstants.STATUS_MSG_PLVIEWER_OPTION_SELECTALL)); + menuSelectAll.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent event) { + selectAllDocText(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent event) { + + } + }); + } + + /** + * Adds the copy menu item. + * + * @param menu the menu + */ + protected void addCopyMenuItem(Menu menu) { + menuCopy = new MenuItem(menu, SWT.PUSH); + menuCopy.setText(MessageConfigLoader.getProperty(IMessagesConstants.STATUS_MSG_PLVIEWER_OPTION_COPY)); + menuCopy.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent event) { + copyDocText(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent event) { + + } + }); + menuCopy.setImage(IconUtility.getIconImage(IiconPath.ICO_COPY, this.getClass())); + } + + /** + * Select all doc text. + */ + protected abstract void selectAllDocText(); + + /** + * Gets the control. + * + * @return the control + */ + protected abstract Control getControl(); + + /** + * Copy doc text. + */ + protected abstract void copyDocText(); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/SourceEditorKeyListener.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/SourceEditorKeyListener.java new file mode 100644 index 0000000000000000000000000000000000000000..81b5e61e34e0cfc44b4265505cd69b2c4bcf8443 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/SourceEditorKeyListener.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import org.eclipse.jface.text.ITextOperationTarget; +import org.eclipse.jface.text.TextViewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.events.KeyListener; + +/** + * Title: SourceEditorKeyListener + * + * Description:The listener interface for receiving sourceEditorKey events. The + * class that is interested in processing a sourceEditorKey event implements + * this interface, and the object created with that class is registered with a + * component using the component's addSourceEditorKeyListener + * method. When the sourceEditorKey event occurs, that object's appropriate + * method is invoked. + * + * @since 3.0.0 + */ +public class SourceEditorKeyListener implements KeyListener { + private TextViewer viewer; + private boolean disableUndoRedo; + + /** + * Instantiates a new source editor key listener. + * + * @param viewer the viewer + */ + public SourceEditorKeyListener(TextViewer viewer) { + this(viewer, false); + } + + /** + * Instantiates a new source editor key listener. + * + * @param viewer the viewer + * @param disableUndoRedo the disable undo redo + */ + public SourceEditorKeyListener(TextViewer viewer, boolean disableUndoRedo) { + this.viewer = viewer; + this.disableUndoRedo = disableUndoRedo; + } + + /** + * Key pressed. + * + * @param event the event + */ + @Override + public void keyPressed(KeyEvent event) { + if (isUndoKeyPress(event) && !disableUndoRedo) { + viewer.doOperation(ITextOperationTarget.UNDO); + } else if (isRedoKeyPress(event) && !disableUndoRedo) { + viewer.doOperation(ITextOperationTarget.REDO); + } else if (isSelectAllKeyPress(event)) { + viewer.doOperation(ITextOperationTarget.SELECT_ALL); + } + } + + /** + * Key released. + * + * @param keyEvent the key event + */ + @Override + public void keyReleased(KeyEvent keyEvent) { + + } + + /** + * Undo keybinding handler. + * + * @param keyEvent the e + * @return true, if is undo key press + */ + private boolean isUndoKeyPress(KeyEvent keyEvent) { + // CTRL + z + return ((keyEvent.stateMask & SWT.CONTROL) != 0) && ((keyEvent.keyCode == 'z') || (keyEvent.keyCode == 'Z')); + } + + /** + * Redo keybinding handler. + * + * @param keyEvent the e + * @return true, if is redo key press + */ + private boolean isRedoKeyPress(KeyEvent keyEvent) { + // CTRL + y + return ((keyEvent.stateMask & SWT.CONTROL) != 0) && ((keyEvent.keyCode == 'y') || (keyEvent.keyCode == 'Y')); + } + + /** + * Select all keybinding handler. + * + * @param event the e + * @return true, if is select all key press + */ + private boolean isSelectAllKeyPress(KeyEvent event) { + // CTRL + a + return ((event.stateMask & SWT.CONTROL) != 0) && ((event.keyCode == 'a') || (event.keyCode == 'A')); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/SystemNotificationPopUI.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/SystemNotificationPopUI.java new file mode 100644 index 0000000000000000000000000000000000000000..1cff6c4940ad9d1114ab00b04551cbee571430a0 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/SystemNotificationPopUI.java @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.mylyn.commons.ui.dialogs.AbstractNotificationPopup; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.FontData; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Text; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class SystemNotificationPopUI. + * + * @since 3.0.0 + */ +public class SystemNotificationPopUI extends AbstractNotificationPopup { + private String successLoginMsg; + private List failureLoginMsg; + private String dbName; + private String conName; + + private Label label; + private boolean isLastLoginSuccess; + private static final String ELLIPSES = "..."; + private static final int MAXLENGTH = 30; + + /** + * Instantiates a new system notification pop UI. + * + * @param display the display + * @param isLastLoginSuccess the is last login success + */ + public SystemNotificationPopUI(Display display, boolean isLastLoginSuccess) { + super(display); + successLoginMsg = ""; + failureLoginMsg = new ArrayList(MPPDBIDEConstants.RECORD_ARRAY_SIZE); + this.isLastLoginSuccess = isLastLoginSuccess; + } + + /** + * Creates the content area. + * + * @param parent the parent + */ + @Override + protected void createContentArea(Composite parent) { + + Composite body = new Composite(parent, SWT.FILL); + + body.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true)); + GridLayout bodyLayout = new GridLayout(1, true); + bodyLayout.horizontalSpacing = 8; + + bodyLayout.marginHeight = 10; + bodyLayout.verticalSpacing = 8; + + body.setLayout(bodyLayout); + body.setBackgroundMode(SWT.INHERIT_FORCE); + + Display display = Display.getDefault(); + + Color black = display.getSystemColor(SWT.COLOR_BLACK); + label = new Label(body, SWT.BORDER_SOLID); + + FontData fontData = label.getFont().getFontData()[0]; + + fontData.setStyle(SWT.BOLD); + Font font = new Font(Display.getCurrent(), new FontData(fontData.getName(), fontData.getHeight(), SWT.BOLD)); + label.setFont(font); + label.setForeground(black); + label.setText(MessageConfigLoader.getProperty(IMessagesConstants.DATABASE_NAME_NOTIFICATION, + getTruncatedName(dbName))); + + label = new Label(body, SWT.BORDER_SOLID); + label.setFont(font); + label.setText(MessageConfigLoader.getProperty(IMessagesConstants.LASTLOGIN_CONNECTION_NAME, + getTruncatedName(conName))); + + label = new Label(body, SWT.BORDER_SOLID); + label.setFont(font); + + if (isLastLoginSuccess) { + label.setText(MessageConfigLoader.getProperty(IMessagesConstants.LAST_SUCCESSFULL_LOGIN_MESSAGE)); + label = new Label(body, SWT.FILL); + + label.setText(this.successLoginMsg); + + } else { + label.setText(MessageConfigLoader.getProperty(IMessagesConstants.LAST_LOGIN_UNAVAILABE)); + + } + + label = new Label(body, SWT.FILL); + if (!this.failureLoginMsg.isEmpty()) { + label = new Label(body, SWT.BORDER_SOLID); + label.setFont(font); + + if (isLastLoginSuccess) { + label.setText(MessageConfigLoader.getProperty(IMessagesConstants.LAST_FAILURE_LOGIN_MESSAGE)); + + } else { + label.setText(MessageConfigLoader.getProperty(IMessagesConstants.LAST_LOGIN_UNAVAILABE)); + } + Text text = new Text(body, SWT.MULTI); + + for (int cnt = 0; cnt < failureLoginMsg.size(); cnt++) { + text.append(failureLoginMsg.get(cnt) + MPPDBIDEConstants.NEW_LINE_SIGN); + } + + } + } + + /** + * Sets the database name. + * + * @param databaseName the new database name + */ + public void setDatabaseName(String databaseName) { + this.dbName = databaseName; + } + + /** + * Sets the con name. + * + * @param conName the new con name + */ + public void setConName(String conName) { + this.conName = conName; + } + + /** + * Gets the truncated name. + * + * @param name the name + * @return the truncated name + */ + public String getTruncatedName(String name) { + if (name.length() > MAXLENGTH) { + String truncatedName = name.substring(0, 30) + ELLIPSES; + return truncatedName; + } + + return name; + } + + /** + * Gets the popup shell title. + * + * @return the popup shell title + */ + @Override + protected String getPopupShellTitle() { + + return MessageConfigLoader.getProperty(IMessagesConstants.DATA_STUDIO_NOTIFIFICATIONS); + } + + /** + * Sets the success login info. + * + * @param msg the new success login info + */ + public void setSuccessLoginInfo(String msg) { + this.successLoginMsg = msg; + } + + /** + * Sets the failure login info. + * + * @param failureLoginTxt the new failure login info + */ + public void setFailureLoginInfo(List failureLoginTxt) { + this.failureLoginMsg = failureLoginTxt; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/TableCellCommand.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/TableCellCommand.java new file mode 100644 index 0000000000000000000000000000000000000000..0381195ae4877fbe645cb2ba3e941fb64cf447c3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/TableCellCommand.java @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core; + +import java.util.HashMap; +import java.util.Map; + +import org.eclipse.nebula.widgets.nattable.command.AbstractLayerCommandHandler; +import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry; +import org.eclipse.nebula.widgets.nattable.config.IEditableRule; +import org.eclipse.nebula.widgets.nattable.edit.EditConfigAttributes; +import org.eclipse.nebula.widgets.nattable.edit.EditController; +import org.eclipse.nebula.widgets.nattable.edit.command.EditCellCommand; +import org.eclipse.nebula.widgets.nattable.edit.gui.ICellEditDialog; +import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell; +import org.eclipse.nebula.widgets.nattable.style.DisplayMode; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.component.grid.IEditTableGridStyleLabelFactory; + +/** + * + * Title: class + * + * Description: The Class TableCellCommand. + * + * @since 3.0.0 + */ +public class TableCellCommand extends AbstractLayerCommandHandler { + + /** + * Gets the command class. + * + * @return the command class + */ + @Override + public Class getCommandClass() { + return EditCellCommand.class; + } + + /** + * Do command. + * + * @param command the command + * @return true, if successful + */ + @Override + public boolean doCommand(EditCellCommand command) { + ILayerCell cell = command.getCell(); + Composite parent = command.getParent(); + IConfigRegistry configRegistry = command.getConfigRegistry(); + if (cell != null && configRegistry != null) { + + // check if the cell is editable + IEditableRule rule = configRegistry.getConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, + DisplayMode.EDIT, cell.getConfigLabels().getLabels()); + Object originalCanonicalValue = cell.getDataValue(); + if (null != originalCanonicalValue + && originalCanonicalValue.toString().length() > IEditTableGridStyleLabelFactory.CANONICAL_LIMIT) { + configRegistry.registerConfigAttribute(EditConfigAttributes.OPEN_IN_DIALOG, Boolean.TRUE, + DisplayMode.EDIT, ParameterInputDialog.PARAMETER_VALUE_LABEL); + Display display = Display.getCurrent(); + // Set the multiline text window style + Map editDialogSettings = new HashMap<>(); + editDialogSettings.put(ICellEditDialog.DIALOG_SHELL_TITLE, + MessageConfigLoader.getProperty(IMessagesConstants.STATUS_MSG_VARIABLE_COLUMN_THREE)); + editDialogSettings.put(ICellEditDialog.DIALOG_SHELL_ICON, display.getSystemImage(SWT.ICON_SEARCH)); + editDialogSettings.put(ICellEditDialog.DIALOG_SHELL_RESIZABLE, Boolean.TRUE); + Point size = new Point(400, 300); + editDialogSettings.put(ICellEditDialog.DIALOG_SHELL_SIZE, size); + + int screenWidth = display.getBounds().width; + int screenHeight = display.getBounds().height; + int monitorsAttached = display.getMonitors().length; + if (monitorsAttached != 0) { + Point location = new Point((screenWidth / (2 * monitorsAttached)) - (size.x / 2), + (screenHeight / 2) - (size.y / 2)); + editDialogSettings.put(ICellEditDialog.DIALOG_SHELL_LOCATION, location); + } + // add custum message + editDialogSettings.put(ICellEditDialog.DIALOG_MESSAGE, + MessageConfigLoader.getProperty(IMessagesConstants.WRITE_HERE)); + + configRegistry.registerConfigAttribute(EditConfigAttributes.EDIT_DIALOG_SETTINGS, editDialogSettings, + DisplayMode.EDIT, ParameterInputDialog.PARAMETER_VALUE_LABEL); + + } else { + configRegistry.unregisterConfigAttribute(EditConfigAttributes.OPEN_IN_DIALOG, DisplayMode.EDIT, + ParameterInputDialog.PARAMETER_VALUE_LABEL); + configRegistry.unregisterConfigAttribute(EditConfigAttributes.EDIT_DIALOG_SETTINGS, DisplayMode.EDIT, + ParameterInputDialog.PARAMETER_VALUE_LABEL); + } + + if (rule.isEditable(cell, configRegistry)) { + EditController.editCell(cell, parent, cell.getDataValue(), configRegistry); + } + } + + // successful or not + return true; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/edittabledata/AbstractEditTableDataResultDisplayUIManager.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/edittabledata/AbstractEditTableDataResultDisplayUIManager.java new file mode 100644 index 0000000000000000000000000000000000000000..c0112983785f134ad5ee269a68bedd4e1cec34a6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/edittabledata/AbstractEditTableDataResultDisplayUIManager.java @@ -0,0 +1,1292 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.edittabledata; + +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Observer; + +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.e4.core.services.events.IEventBroker; +import org.eclipse.e4.ui.model.application.ui.MDirtyable; +import org.eclipse.e4.ui.model.application.ui.basic.MPart; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.sqlhistory.IQueryExecutionSummary; +import org.opengauss.mppdbide.presentation.IEditTableDataCore; +import org.opengauss.mppdbide.presentation.IWindowDetail; +import org.opengauss.mppdbide.presentation.edittabledata.DSEditTableDataGridDataProvider; +import org.opengauss.mppdbide.presentation.edittabledata.DSResultSetGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSEditGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IRowEffectedConfirmation; +import org.opengauss.mppdbide.presentation.resultsetif.IConsoleResult; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.StatusMessage; +import org.opengauss.mppdbide.utils.messaging.StatusMessageList; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.utils.observer.IDSGridUIListenable; +import org.opengauss.mppdbide.utils.observer.IDSListener; +import org.opengauss.mppdbide.view.component.GridUIPreference; +import org.opengauss.mppdbide.view.component.grid.CommitInputData; +import org.opengauss.mppdbide.view.component.grid.CommitRecordEventData; +import org.opengauss.mppdbide.view.component.grid.DSGridComponent; +import org.opengauss.mppdbide.view.component.grid.GridSearchAreaToDataGrid; +import org.opengauss.mppdbide.view.component.grid.GridSelectionLayerPortData; +import org.opengauss.mppdbide.view.component.grid.GridToolbar; +import org.opengauss.mppdbide.view.component.grid.GridViewPortData; +import org.opengauss.mppdbide.view.component.grid.RowEffectedConfirmationPrompt; +import org.opengauss.mppdbide.view.component.grid.SEARCHOPTIONS; +import org.opengauss.mppdbide.view.core.ConsoleMessageWindow; +import org.opengauss.mppdbide.view.core.ConsoleMessageWindowDummy; +import org.opengauss.mppdbide.view.prefernces.PreferenceWrapper; +import org.opengauss.mppdbide.view.prefernces.UserEncodingOption; +import org.opengauss.mppdbide.view.terminal.TerminalQueryExecutionWorker; +import org.opengauss.mppdbide.view.terminal.executioncontext.EditTableDataExecutionContext; +import org.opengauss.mppdbide.view.ui.EditTableDataUIWindow; +import org.opengauss.mppdbide.view.ui.terminal.AbstractResultDisplayUIManager; +import org.opengauss.mppdbide.view.ui.terminal.ViewOrEditTableDataResultSetConfigData; +import org.opengauss.mppdbide.view.ui.terminal.resulttab.GridDataExportAllWorker; +import org.opengauss.mppdbide.view.ui.terminal.resulttab.GridDataGenerateInsertAllWorker; +import org.opengauss.mppdbide.view.ui.terminal.resulttab.GridResultDataCurrentPageExport; +import org.opengauss.mppdbide.view.ui.terminal.resulttab.GridResultDataSelectedCopyToExcel; +import org.opengauss.mppdbide.view.ui.terminal.resulttab.GridResultGenerateSelectedLineInsertSql; +import org.opengauss.mppdbide.view.utils.BottomStatusBar; +import org.opengauss.mppdbide.view.utils.UIElement; +import org.opengauss.mppdbide.view.utils.UserPreference; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs.MESSAGEDIALOGTYPE; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; +import org.opengauss.mppdbide.view.workerjob.UIWorkerJob; + +/** + * + * Title: class + * + * Description: The Class AbstractEditTableDataResultDisplayUIManager. + * + * @since 3.0.0 + */ +public abstract class AbstractEditTableDataResultDisplayUIManager extends AbstractResultDisplayUIManager + implements IDSListener { + + /** + * The core. + */ + protected IEditTableDataCore core; + + /** + * The result. + */ + protected IDSGridDataProvider result; + + /** + * The grid component. + */ + protected volatile DSGridComponent editTableGridComponent; + + /** + * The result grid UI pref. + */ + protected EditTableDataGridUIPref resultGridUIPref; + + /** + * The console message window dummy. + */ + protected ConsoleMessageWindowDummy consoleMessageWindowDummy; + + /** + * The dirty handler. + */ + protected MDirtyable dirtyHandler; + + /** + * The remembered user options. + */ + protected CommitInputData rememberedUserOptions; + + /** + * The part. + */ + protected MPart part; + + /** + * The row effected confirm. + */ + protected RowEffectedConfirmation rowEffectedConfirm; + + /** + * The query exec summary. + */ + protected IQueryExecutionSummary queryExecSummary; + + /** + * Instantiates a new abstract edit table data result display UI manager. + * + * @param core1 the core 1 + */ + public AbstractEditTableDataResultDisplayUIManager(IEditTableDataCore core1) { + super(core1.getTermConnection()); + this.core = core1; + } + + /** + * Sets the core. + * + * @param newCore the new core + */ + public void setCore(IEditTableDataCore newCore) { + this.core = newCore; + } + + /** + * Gets the event broker. + * + * @return the event broker + */ + @Override + public IEventBroker getEventBroker() { + + return null; + } + + /** + * Reset display UI manager. + */ + @Override + public void resetDisplayUIManager() { + + } + + /** + * Handle event. + * + * @param event the event + */ + @Override + public void handleEvent(DSEvent event) { + switch (event.getType()) { + case IDSGridUIListenable.LISTEN_EDITTABLE_ROLLBACK_DATA: { + this.editTableGridComponent.saveReorderState(); + break; + } + case IDSGridUIListenable.LISTEN_EDITTABLE_ROLLBACK_DATA_COMPLETE: { + this.editTableGridComponent.restoreLastReorderState(); + break; + } + case IDSGridUIListenable.LISTEN_EDITTABLE_USER_FORGET_OPTION: { + this.rememberedUserOptions = null; + this.rowEffectedConfirm = null; + break; + } + case IDSGridUIListenable.LISTEN_TYPE_SEARCH_CLEARED: { + listenSearchCleared(); + break; + } + default: { + handleEventLevelOne(event); + } + } + + } + + private void handleReExecuteQuery() { + this.editTableGridComponent.saveSortState(); + this.editTableGridComponent.saveReorderState(); + + EditTableDataExecutionContext executionContext = new EditTableDataExecutionContext(this.core, this, + this.core.getTable(), + new ViewOrEditTableDataResultSetConfigData(queryExecSummary.getNumRecordsFetched())); + + TerminalQueryExecutionWorker worker = new TerminalQueryExecutionWorker(executionContext); + worker.setTaskDB(executionContext.getTermConnection().getDatabase()); + worker.schedule(); + + editTableGridComponent.getToolbar().resetLoadMoreRecordStatus(); + } + + private void handleEventLevelOne(DSEvent event) { + switch (event.getType()) { + case IDSGridUIListenable.LISTEN_TYPE_SEARCH_DONE: { + listenOnSearchDone(); + break; + } + case IDSGridUIListenable.LISTEN_DATA_CHANGE_ENCODING: { + listenOnDataChangeEncoding(event); + break; + } + case IDSGridUIListenable.LISTEN_TYPE_ON_REEXECUTE_QUERY: { + if (dirtyHandler.isDirty()) { + showPopUpOnDirtyTableFetchNextRecords(); + editTableGridComponent.setLoadingStatus(false); + return; + } + handleReExecuteQuery(); + break; + } + case IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_EDITED: { + IDSEditGridDataProvider provider = (IDSEditGridDataProvider) result; + dirtyHandler.setDirty(provider.isGridDataEdited()); + break; + } + default: { + handleEventLevelTwo(event); + } + } + } + + private void handleEventLevelTwo(DSEvent event) { + switch (event.getType()) { + case IDSGridUIListenable.LISTEN_TYPE_ON_REFRESH_QUERY: { + listenRefreshQuery(); + break; + } + + case IDSGridUIListenable.LISTEN_EDITTABLE_COMMIT_DATA: { + listenOnEditableCommitData(event); + break; + } + + case IDSGridUIListenable.LISTEN_DATABASE_CONNECT_DISCONNECT_STATUS: { + listenDbConnectDisConnect(event); + break; + } + + case IDSGridUIListenable.LISTEN_TYPE_POST_GRID_DATA_LOAD: { + handlePostGridDataLoadEvent(); + break; + } + default: { + handleEventLevelThree(event); + } + } + } + + private void handleEventLevelThree(DSEvent event) { + switch (event.getType()) { + case IDSGridUIListenable.LISTEN_EDITTABLE_COMMIT_DATA_COMPLETE: { + handleCommitDataCompleteEvent(); + dirtyHandler.setDirty(((IDSEditGridDataProvider) result).isGridDataEdited()); + break; + } + case IDSGridUIListenable.LISTEN_TYPE_EXPORT_CURR_PAGE_DATA: { + listenOnExportCurrentPage(event); + break; + } + case IDSGridUIListenable.LISTEN_TYPE_EXPORT_ALL_DATA: { + listenOnExportAllData(event); + break; + } + case IDSGridUIListenable.LISTEN_COPY_TO_EXCEL_XLSX_RESULT_WINDOW_MENUITEM: { + listenOnEditTableDataWindowCopyToExcelXlsxMenu(event); + break; + } + default: { + handleEventLevelFour(event); + } + } + } + + private void handleEventLevelFour(DSEvent event) { + switch (event.getType()) { + case IDSGridUIListenable.LISTEN_COPY_TO_EXCEL_XLS_RESULT_WINDOW_MENUITEM: { + listenEditTableDataWindowCopyToExcelXlsMenu(event); + break; + } + case IDSGridUIListenable.LISTEN_TYPE_ON_RESULT_MENUITEM_GERERATE_ALL_INSERT: { + listenOnEditTableDataWindowGenerateAllInsert(event); + break; + } + case IDSGridUIListenable.LISTEN_TYPE_ON_RESULT_MENUITEM_GERERATE_SELECT_LINE_INSERT: { + listenOnEditTableDataWindowGenerateSelectLineInsert(event); + break; + } + case IDSGridUIListenable.LISTEN_TYPE_ON_RESULT_MENUITEM_GERERATE_CURRENT_PAGE_INSERT: { + listenOnEditTableDataWindowGenerateCurrentPageInsert(event); + break; + } + case IDSGridUIListenable.LISTEN_TYPE_ON_RESULT_WINDOW_MENUITEM_SEARCH: { + listenOnEditTableDataWindowMenuSearch(event); + break; + } + default: { + break; + } + } + } + + private void listenOnEditTableDataWindowMenuSearch(DSEvent event) { + Object editTableFocusData = event.getObject(); + Object editTableSelectSearchData = getSelectData().getCellData(); + if (SEARCHOPTIONS.SRCH_NULL.getDisplayName().equals(getSearchArea().getCmbSearchOpt().getText())) { + getSearchArea().getTxtSearchStr().setEnabled(false); + if (null == editTableSelectSearchData || editTableSelectSearchData.toString().isEmpty()) { + if (editTableFocusData != null) { + getSearchArea().getTxtSearchStr().setEnabled(true); + getSearchArea().getCmbSearchOpt().setText(SEARCHOPTIONS.SRCH_CONTAINS.getDisplayName()); + getSearchArea().getTxtSearchStr().setText(editTableFocusData.toString()); + getSearchArea().getTriggerSearch(editTableFocusData.toString(), true); + } else { + getSearchArea().getTriggerSearch(true); + } + } else { + getSearchArea().getTxtSearchStr().setEnabled(true); + getSearchArea().getCmbSearchOpt().setText(SEARCHOPTIONS.SRCH_CONTAINS.getDisplayName()); + getSearchArea().getTxtSearchStr().setText(editTableSelectSearchData.toString()); + getSearchArea().getTriggerSearch(editTableSelectSearchData.toString(), true); + + } + } else { + if (null == editTableSelectSearchData || editTableSelectSearchData.toString().isEmpty()) { + if (editTableFocusData != null) { + getSearchArea().getTxtSearchStr().setText(editTableFocusData.toString()); + getSearchArea().getTriggerSearch(editTableFocusData.toString(), true); + } else { + getSearchArea().getTxtSearchStr().setText(""); + getSearchArea().getTxtSearchStr().setEnabled(false); + getSearchArea().getCmbSearchOpt().setText(SEARCHOPTIONS.SRCH_NULL.getDisplayName()); + getSearchArea().getTriggerSearch(true); + } + + } else { + getSearchArea().getTxtSearchStr().setText(editTableSelectSearchData.toString()); + getSearchArea().getTriggerSearch(editTableSelectSearchData.toString(), true); + + } + } + } + + /** + * Gets the search area. + * + * @return the search area + */ + public GridSearchAreaToDataGrid getSearchArea() { + return this.editTableGridComponent.getSearchArea(); + } + + private void listenOnEditTableDataWindowGenerateCurrentPageInsert(DSEvent event) { + GridResultGenerateSelectedLineInsertSql generateCurrentPageInsertSql = new GridResultGenerateSelectedLineInsertSql( + this.termConnection, getSelectData(), null, this.result, queryExecSummary, core.getWindowTitle(), true); + generateCurrentPageInsertSql.addObserver((Observer) event.getObject()); + if (this.dirtyHandler.isDirty()) { + if (!isExportDirtyData()) { + generateCurrentPageInsertSql.endOfGenerate(); + return; + } + } + generateCurrentPageInsertSql.generate(); + } + + private void listenOnEditTableDataWindowGenerateSelectLineInsert(DSEvent event) { + GridResultGenerateSelectedLineInsertSql generateSelectedLineInsertSql = new GridResultGenerateSelectedLineInsertSql( + this.termConnection, getSelectData(), null, this.result, queryExecSummary, core.getWindowTitle(), + false); + generateSelectedLineInsertSql.addObserver((Observer) event.getObject()); + if (this.dirtyHandler.isDirty()) { + if (!isExportDirtyData()) { + generateSelectedLineInsertSql.endOfGenerate(); + return; + } + } + generateSelectedLineInsertSql.generate(); + } + + private void listenOnEditTableDataWindowGenerateAllInsert(DSEvent event) { + String progressLabel = MessageConfigLoader + .getProperty(IMessagesConstants.GENERATE_INSERT_ALL_RESULTDATA_PROGRESS_NAME, core.getWindowTitle()); + StatusMessage statusMessage = new StatusMessage( + MessageConfigLoader.getProperty(IMessagesConstants.TITLE_EXPORT_IN_PROGRESS)); + BottomStatusBar bottomStatusBar = UIElement.getInstance().getProgressBarOnTop(); + if (bottomStatusBar != null) { + bottomStatusBar.setStatusMessage(statusMessage.getMessage()); + } + GridDataGenerateInsertAllWorker editTableWorker = new GridDataGenerateInsertAllWorker(this.termConnection, null, + core.getWindowTitle(), progressLabel, this.result, (Observer) event.getObject(), false, bottomStatusBar, + statusMessage, getFileEncoding()); + StatusMessageList.getInstance().push(statusMessage); + if (editTableWorker.isSaveSqlFileDialog()) { + if (bottomStatusBar != null) { + bottomStatusBar.activateStatusbar(); + } + editTableWorker.setTaskDB(termConnection.getDatabase()); + editTableWorker.schedule(); + } + } + + /** + * Gets the file encoding. + * + * @return the file encoding + */ + public String getFileEncoding() { + String fileEncoding = UserPreference.getInstance().getFileEncoding().isEmpty() ? Charset.defaultCharset().name() + : UserPreference.getInstance().getFileEncoding(); + + return fileEncoding; + } + + private void listenEditTableDataWindowCopyToExcelXlsMenu(DSEvent event) { + int formatIndex = 1; + GridResultDataSelectedCopyToExcel resultCopyTOExcel = new GridResultDataSelectedCopyToExcel(getSelectData(), + formatIndex, null, null); + + resultCopyTOExcel.addObserver((Observer) event.getObject()); + + if (this.dirtyHandler.isDirty()) { + if (!isExportDirtyData()) { + resultCopyTOExcel.endOfCopyToEXCEL(); + return; + } + } + + resultCopyTOExcel.export(); + } + + private void listenOnEditTableDataWindowCopyToExcelXlsxMenu(DSEvent event) { + int formatIndex = 0; + GridResultDataSelectedCopyToExcel editTableResultCopyTOExcel = new GridResultDataSelectedCopyToExcel( + getSelectData(), formatIndex, null, null); + + editTableResultCopyTOExcel.addObserver((Observer) event.getObject()); + + if (this.dirtyHandler.isDirty()) { + if (!isExportDirtyData()) { + editTableResultCopyTOExcel.endOfCopyToEXCEL(); + return; + } + } + + editTableResultCopyTOExcel.export(); + } + + /** + * Gets the select data. + * + * @return the select data + */ + public GridSelectionLayerPortData getSelectData() { + return this.editTableGridComponent.getSelectDataIterator(); + } + + private void listenOnExportAllData(DSEvent event) { + if (!isTableExist()) { + return; + } + String progressLabel = MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_ALL_DATA_PROGRESS_NAME, + core.getWindowTitle()); + StatusMessage statusMessage = new StatusMessage( + MessageConfigLoader.getProperty(IMessagesConstants.TITLE_EXPORT_IN_PROGRESS)); + BottomStatusBar editTableBottomStatusBar = UIElement.getInstance().getProgressBarOnTop(); + if (editTableBottomStatusBar != null) { + editTableBottomStatusBar.setStatusMessage(statusMessage.getMessage()); + } + GridDataExportAllWorker editTableWorker = new GridDataExportAllWorker(this.termConnection, null, + core.getWindowTitle(), progressLabel, this.result, (Observer) event.getObject(), false, + editTableBottomStatusBar, statusMessage); + StatusMessageList.getInstance().push(statusMessage); + if (editTableWorker.isExportDialog()) { + if (editTableBottomStatusBar != null) { + editTableBottomStatusBar.activateStatusbar(); + } + editTableWorker.setTaskDB(termConnection.getDatabase()); + editTableWorker.schedule(); + } + } + + private void listenOnExportCurrentPage(DSEvent event) { + GridResultDataCurrentPageExport editTableResultDataExporter = new GridResultDataCurrentPageExport(getUIData(), + null, null, core.getWindowTitle()); + editTableResultDataExporter.addObserver((Observer) event.getObject()); + + if (dirtyHandler.isDirty()) { + if (!isExportDirtyData()) { + editTableResultDataExporter.endOfExport(); + return; + } + } + + editTableResultDataExporter.export(false); + } + + /** + * Gets the UI data. + * + * @return the UI data + */ + public GridViewPortData getUIData() { + return this.editTableGridComponent.getUIDataIterator(); + } + + /** + * Checks if is export dirty data. + * + * @return true, if is export dirty data + */ + public boolean isExportDirtyData() { + String title = MessageConfigLoader.getProperty(IMessagesConstants.TITLE_EXPORT_DATA); + String message = MessageConfigLoader.getProperty(IMessagesConstants.EXPORT_DIRTY_DATA_BODY); + String cancel = MessageConfigLoader.getProperty(IMessagesConstants.MPPDBIDE_DIA_BTN_CANC); + String export = MessageConfigLoader.getProperty(IMessagesConstants.TITLE_EXPORT_DATA); + int userChoice = MPPDBIDEDialogs.generateMessageDialog(MESSAGEDIALOGTYPE.QUESTION, true, + IconUtility.getIconImage(IiconPath.ICO_EDIT_EDIT, this.getClass()), title, message, + new String[] {export, cancel}, 1); + + if (0 == userChoice) { + return true; + } + + return false; + } + + private void handleCommitDataCompleteEvent() { + editTableGridComponent.restoreLastReorderState(); + editTableGridComponent.enableDisableGrid(true); + editTableGridComponent.getToolbar().handleDataEditEvent(true); + } + + /** + * Handle post grid data load event. + */ + public void handlePostGridDataLoadEvent() { + if (null != editTableGridComponent) { + editTableGridComponent.setLoadingStatus(false); + editTableGridComponent.enableDisableGrid(true); + editTableGridComponent.restoreLastSortState(); + editTableGridComponent.restoreLastReorderState(); + } + } + + /** + * Listen on data change encoding. + * + * @param event the event + */ + private void listenOnDataChangeEncoding(DSEvent event) { + this.editTableGridComponent.saveSortState(); + this.editTableGridComponent.saveReorderState(); + IDSGridDataProvider dataProvider = editTableGridComponent.getDataProvider(); + if (dataProvider != null && dataProvider instanceof DSEditTableDataGridDataProvider) { + DSEditTableDataGridDataProvider dp = (DSEditTableDataGridDataProvider) dataProvider; + String encoding = event.getObject().toString(); + dp.changeEncoding(encoding); + editTableGridComponent.updateGridData(); + editTableGridComponent.getToolbar() + .handleDataEditEvent(core.getTermConnection().getDatabase().isConnected()); + } + editTableGridComponent.restoreLastSortState(); + editTableGridComponent.restoreLastReorderState(); + } + + /** + * Listen on search done. + */ + private void listenOnSearchDone() { + if (resultGridUIPref.isEnableEdit()) { + editTableGridComponent.getToolbar().enableDisableOnSearch(true, + core.getTermConnection().getDatabase().isConnected()); + } + } + + /** + * Listen search cleared. + */ + private void listenSearchCleared() { + if (resultGridUIPref.isEnableEdit()) { + editTableGridComponent.getToolbar().enableDisableOnSearch(false, + core.getTermConnection().getDatabase().isConnected()); + } + } + + /** + * Listen db connect dis connect. + * + * @param event the event + */ + private void listenDbConnectDisConnect(DSEvent event) { + GridToolbar toolbar = (GridToolbar) event.getObject(); + toolbar.setDataProvider(this.result); + if (resultGridUIPref.isEnableEdit()) { + toolbar.handleDataEditEvent(core.getTermConnection().getDatabase().isConnected()); + } + } + + /** + * Listen on editable commit data. + * + * @param event the event + */ + /** + * Listen on editable commit data. + * + * @param event the event + */ + private void listenOnEditableCommitData(DSEvent event) { + if (!isTableExist()) { + return; + } + if (rowEffectedConfirm == null) { + + rowEffectedConfirm = new RowEffectedConfirmation(); + } + IDSEditGridDataProvider dataProvider = (IDSEditGridDataProvider) result; + + CommitInputData saveUserOptions = getSaveConditionalInput(dataProvider); + + if (null == saveUserOptions) { + editTableGridComponent.getToolbar().handleDataEditEvent(true); + return; + } + editTableGridComponent.saveReorderState(); + editTableGridComponent.enableDisableGrid(false); + editTableGridComponent.getToolbar().handleDataEditEvent(false); + CommitRecordEventData commitEventData = (CommitRecordEventData) event.getObject(); + + StatusMessage statusMessage = new StatusMessage( + MessageConfigLoader.getProperty(IMessagesConstants.COMMITING_DATA)); + BottomStatusBar bottomStatusBar = UIElement.getInstance().getProgressBarOnTop(); + commitEventData.setCommitData(saveUserOptions); + if (bottomStatusBar != null) { + bottomStatusBar.setStatusMessage(statusMessage.getMessage()); + } + String progressLabel = getProgressLabel(); + + EditTableUIWorker editTableUIWorker = new EditTableUIWorker(progressLabel, "", core.getTermConnection(), + commitEventData.getDataGrid(), commitEventData.getDataText(), this.result, + commitEventData.getCommitData().getUniqueKeys(), commitEventData.getCommitData().isAtomic(), + commitEventData.getEventTable(), bottomStatusBar, statusMessage, rowEffectedConfirm, false); + + StatusMessageList.getInstance().push(statusMessage); + if (bottomStatusBar != null) { + bottomStatusBar.activateStatusbar(); + } + editTableUIWorker.schedule(); + } + + /** + * Gets the progress label. + * + * @return the progress label + */ + protected abstract String getProgressLabel(); + + /** + * Listen refresh query. + */ + private void listenRefreshQuery() { + if (!isTableExist()) { + return; + } + editTableGridComponent.setLoadingStatus(true); + editTableGridComponent.enableDisableGrid(false); + this.editTableGridComponent.saveSortState(); + this.editTableGridComponent.saveReorderState(); + RefreshEditTableMetaDataWorker refreshmetadataworker = new RefreshEditTableMetaDataWorker(core); + refreshmetadataworker.schedule(); + } + + /** + * Checks if is table exist.checks if the table being accessed is not + * dropped from backend + * + * @return true, if is table exist + */ + public boolean isTableExist() { + if (core.isTableDropped()) { + + MPPDBIDEDialogs.generateMessageDialog(MESSAGEDIALOGTYPE.ERROR, true, + IconUtility.getIconImage(IiconPath.ICO_TOOL_32X32, this.getClass()), + MessageConfigLoader.getProperty(IMessagesConstants.EDIT_TABLE_DATA_ERROR_POPUP_HEADER), + MessageConfigLoader.getProperty(IMessagesConstants.EDIT_TABLE_DATA_DROPPED_REFRESH_ERROR), + new String[] {MessageConfigLoader.getProperty(IMessagesConstants.BTN_OK)}); + return false; + } else { + return true; + } + } + + /** + * Check window details. + */ + private void checkWindowDetails() { + MPart oldPart = this.getPart(); + String oldLabel = oldPart.getLabel(); + String oldID = oldPart.getElementId(); + String newLabel = core.getWindowDetails().getTitle(); + String newID = core.getWindowDetails().getUniqueID(); + if (!oldLabel.equals(newLabel)) { + oldPart.setLabel(newLabel); + } + if (null != oldID && !oldID.equals(newID)) { + oldPart.setElementId(newID); + + } + } + + /** + * Sets the remembered user options. + * + * @param rememberedUserOptions the new remembered user options + */ + public void setRememberedUserOptions(CommitInputData rememberedUserOptions) { + this.rememberedUserOptions = rememberedUserOptions; + } + + /** + * Gets the save conditional input. + * + * @param dataProvider the data provider + * @return the save conditional input + */ + protected abstract CommitInputData getSaveConditionalInput(IDSEditGridDataProvider dataProvider); + + /** + * Sets the part. + * + * @param part the new part + */ + public void setPart(MPart part) { + this.part = part; + } + + /** + * Gets the part. + * + * @return the part + */ + public MPart getPart() { + return this.part; + } + + /** + * Handle exception display. + * + * @param obj the obj + */ + @Override + public void handleExceptionDisplay(Object obj) { + if (editTableGridComponent != null) { + editTableGridComponent.setLoadingStatus(false); + editTableGridComponent.enableDisableGrid(true); + } + if (isDisposed()) { + return; + } + MPPDBIDEException exception = (MPPDBIDEException) obj; + StringBuilder customErrorMsg = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + if (null != exception && exception.getServerMessage() != null) { + if (exception.getServerMessage().contains("does not exist")) { + customErrorMsg.append(MessageConfigLoader.getProperty(IMessagesConstants.ERR_EDIT_TABLE_DROP_TABLE)); + } else { + customErrorMsg.append(exception.getServerMessage()); + } + } + String strServerError = customErrorMsg.toString(); + if (strServerError.contains("Position:")) { + strServerError = strServerError.split("Position:")[0]; + } + + String msgString = MessageConfigLoader.getProperty(IMessagesConstants.EDIT_TABLE_DATA_ERROR_POPUP_MESSAGE); + + String hintMsg = ""; + if (null != exception && exception.getDBErrorMessage().contains("No matching")) { + hintMsg = MessageConfigLoader.getProperty(IMessagesConstants.CHECK_FILE_ENCODE_SET); + } + + if (!strServerError + .contains(MessageConfigLoader.getProperty(IMessagesConstants.ERR_BL_SERVER_CONNECTION_FAILED))) { + MPPDBIDEDialogs.generateErrorPopup( + MessageConfigLoader.getProperty(IMessagesConstants.EDIT_TABLE_DATA_ERROR_POPUP_HEADER), + Display.getDefault().getActiveShell(), exception, hintMsg, msgString, strServerError); + } + } + // CHECKTYLE: ON + + /** + * Gets the part ID. + * + * @return the part ID + */ + @Override + protected String getPartID() { + + return null; + } + + /** + * Gets the console message window. + * + * @param bringOnTop the bring on top + * @return the console message window + */ + @Override + protected ConsoleMessageWindow getConsoleMessageWindow(boolean bringOnTop) { + if (null == this.consoleMessageWindowDummy) { + this.consoleMessageWindowDummy = new ConsoleMessageWindowDummy(); + } + + return this.consoleMessageWindowDummy; + } + + /** + * Can dislay result. + * + * @return true, if successful + */ + @Override + protected boolean canDislayResult() { + + return !UIElement.getInstance().isWindowLimitReached(); + } + + /** + * Creates the result new. + * + * @param resultsetDisplaydata the resultset displaydata + * @param consoledata the consoledata + * @param queryExecSummary the query exec summary + */ + @Override + protected void createResultNew(IDSGridDataProvider resultsetDisplaydata, IConsoleResult consoledata, + IQueryExecutionSummary queryExecSummary) { + if (this.isDisposed()) { + return; + } + + setResultData(resultsetDisplaydata, queryExecSummary); + + IWindowDetail windowDetails = core.getWindowDetails(); + boolean isEditTableWindowExists = UIElement.getInstance().isWindowExists(windowDetails); + EditTableDataUIWindow editTableDataWindow = (EditTableDataUIWindow) UIElement.getInstance() + .getEditTableDataWindow(windowDetails, this); + + // Check if the window is null. This will be due to the number of + // windows open is more than the threshold. + if (editTableDataWindow == null) { + return; + } + if (null != editTableDataWindow.getResultDisplayUIManager() && isEditTableWindowExists) { + // If old manager is being used, then reset the new result and + // summary. + editTableDataWindow.getResultDisplayUIManager().setResultData(result, queryExecSummary); + editTableDataWindow.resetData(); + UIElement.getInstance().bringOnTopViewTableDataWindow(windowDetails); + } + } + + /** + * Sets the result data. + * + * @param resultsetDisplaydata the resultset displaydata + * @param queryExecSummary the query exec summary + */ + protected void setResultData(IDSGridDataProvider resultsetDisplaydata, IQueryExecutionSummary queryExecSummary) { + this.queryExecSummary = queryExecSummary; + this.result = resultsetDisplaydata; + if (result instanceof DSResultSetGridDataProvider) { + DSResultSetGridDataProvider editDataProvider = (DSResultSetGridDataProvider) result; + editDataProvider.addListener(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_EDITED, this); + } + } + + /** + * Show result. + * + * @param parentComposite the parent composite + */ + public void showResult(Composite parentComposite) { + if (editTableGridComponent == null) { + this.resultGridUIPref = new EditTableDataGridUIPref(); + this.editTableGridComponent = new DSGridComponent(resultGridUIPref, this.result); + this.editTableGridComponent.createComponents(parentComposite); + this.editTableGridComponent.addListener(IDSGridUIListenable.LISTEN_TYPE_ON_REFRESH_QUERY, this); + this.editTableGridComponent.addListener(IDSGridUIListenable.LISTEN_EDITTABLE_COMMIT_DATA, this); + this.editTableGridComponent.addListener(IDSGridUIListenable.LISTEN_EDITTABLE_ROLLBACK_DATA, this); + this.editTableGridComponent.addListener(IDSGridUIListenable.LISTEN_EDITTABLE_ROLLBACK_DATA_COMPLETE, this); + this.editTableGridComponent.addListener(IDSGridUIListenable.LISTEN_DATABASE_CONNECT_DISCONNECT_STATUS, + this); + this.editTableGridComponent.addListener(IDSGridUIListenable.LISTEN_TYPE_POST_GRID_DATA_LOAD, this); + this.editTableGridComponent.addListener(IDSGridUIListenable.LISTEN_EDITTABLE_USER_FORGET_OPTION, this); + this.editTableGridComponent.addListener(IDSGridUIListenable.LISTEN_EDITTABLE_COMMIT_DATA_COMPLETE, this); + this.editTableGridComponent.addListener(IDSGridUIListenable.LISTEN_TYPE_SEARCH_CLEARED, this); + this.editTableGridComponent.addListener(IDSGridUIListenable.LISTEN_TYPE_SEARCH_DONE, this); + this.editTableGridComponent.addListener(IDSGridUIListenable.LISTEN_DATA_CHANGE_ENCODING, this); + this.editTableGridComponent.addListener(IDSGridUIListenable.LISTEN_TYPE_ON_REEXECUTE_QUERY, this); + this.editTableGridComponent.addListener(IDSGridUIListenable.LISTEN_TYPE_EXPORT_CURR_PAGE_DATA, this); + this.editTableGridComponent.addListener(IDSGridUIListenable.LISTEN_TYPE_EXPORT_ALL_DATA, this); + this.editTableGridComponent + .addListener(IDSGridUIListenable.LISTEN_COPY_TO_EXCEL_XLSX_RESULT_WINDOW_MENUITEM, this); + this.editTableGridComponent.addListener(IDSGridUIListenable.LISTEN_COPY_TO_EXCEL_XLS_RESULT_WINDOW_MENUITEM, + this); + this.editTableGridComponent + .addListener(IDSGridUIListenable.LISTEN_TYPE_ON_RESULT_MENUITEM_GERERATE_SELECT_LINE_INSERT, this); + this.editTableGridComponent + .addListener(IDSGridUIListenable.LISTEN_TYPE_ON_RESULT_MENUITEM_GERERATE_CURRENT_PAGE_INSERT, this); + this.editTableGridComponent + .addListener(IDSGridUIListenable.LISTEN_TYPE_ON_RESULT_MENUITEM_GERERATE_ALL_INSERT, this); + this.editTableGridComponent.addListener(IDSGridUIListenable.LISTEN_TYPE_ON_RESULT_WINDOW_MENUITEM_SEARCH, + this); + registerDataProviderEditListener(); + } + } + + /** + * Register data provider edit listener. + */ + private void registerDataProviderEditListener() { + if (null != result && result instanceof DSResultSetGridDataProvider) { + DSResultSetGridDataProvider editDataProvider = (DSResultSetGridDataProvider) result; + editDataProvider.addListener(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_EDITED, + editTableGridComponent.getDataEditListener()); + } + } + + /** + * + * Title: class + * + * Description: The Class EditTableDataGridUIPref. + */ + public class EditTableDataGridUIPref extends GridUIPreference { + /** + * Checks if is enable edit. + * + * @return true, if is enable edit + */ + @Override + public boolean isEnableEdit() { + + return true; + } + + /** + * Checks if is unique remembered. + * + * @return true, if is unique remembered + */ + public boolean isUniqueRemembered() { + return null != AbstractEditTableDataResultDisplayUIManager.this.rememberedUserOptions; + } + + /** + * Checks if is enable sort. + * + * @return true, if is enable sort + */ + @Override + public boolean isEnableSort() { + return true; + } + + /** + * Checks if is edits the query results flow. + * + * @return true, if is edits the query results flow + */ + @Override + public boolean isEditQueryResultsFlow() { + return true; + } + + /** + * Checks if is show load more record button. + * + * @return true, if is show load more record button + */ + @Override + public boolean isShowLoadMoreRecordButton() { + return true; + } + + /** + * Is refresh enabled. + * + * @return true, if refresh is supported + */ + @Override + public boolean isRefreshSupported() { + return true; + } + + @Override + public boolean isShowRightClickMenu() { + return true; + } + + /** + * Checks if is closed connection. + * + * @return true, if is closed connection + */ + @Override + public boolean isClosedConnection() { + return termConnection.getDatabase().isConnected(); + } + + /** + * Checks if is show generate insert. + * + * @return true, if is show generate insert + */ + @Override + public boolean isShowGenerateInsert() { + Boolean isOlap = true; + switch (termConnection.getDatabase().getDBType()) { + case OPENGAUSS: { + isOlap = true; + break; + } + default: { + break; + } + } + return isOlap; + } + + @Override + public boolean isStartSelectQuery() { + return true; + } + + /** + * Gets the selected encoding. + * + * @return the selected encoding + */ + @Override + public String getSelectedEncoding() { + String encoding = editTableGridComponent.getSelectedEncoding(); + + if (MPPDBIDEConstants.SPACE_CHAR.equals(encoding) || null == encoding) { + encoding = PreferenceWrapper.getInstance().getPreferenceStore() + .getString(UserEncodingOption.DATA_STUDIO_ENCODING); + } + + return encoding; + + } + } + + /** + * Reset data result. + */ + public void resetDataResult() { + registerDataProviderEditListener(); + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + if (editTableGridComponent != null && !editTableGridComponent.isDisposed()) { + editTableGridComponent.setDataProvider(AbstractEditTableDataResultDisplayUIManager.this.result); + } + } + }); + } + + /** + * On focus. + */ + public void onFocus() { + this.editTableGridComponent.focus(); + } + + /** + * Sets the dirty handler. + * + * @param terminalDirty the new dirty handler + */ + public void setDirtyHandler(MDirtyable terminalDirty) { + this.dirtyHandler = terminalDirty; + } + + /** + * Sets the disposed. + */ + @Override + public void setDisposed() { + super.setDisposed(); + if (result instanceof DSResultSetGridDataProvider) { + ((DSResultSetGridDataProvider) result).removeListener(IDSGridUIListenable.LISTEN_TYPE_GRID_DATA_EDITED, + this); + } + } + + /** + * + * Title: class + * + * Description: The Class RefreshEditTableMetaDataWorker. + */ + private class RefreshEditTableMetaDataWorker extends UIWorkerJob { + + private IEditTableDataCore editTableCore; + private DBConnection dbconn; + + /** + * Instantiates a new refresh edit table meta data worker. + * + * @param core the core + */ + private RefreshEditTableMetaDataWorker(IEditTableDataCore core) { + super("Refresh Edit Core", null); + this.editTableCore = core; + } + + @Override + public Object doJob() + throws DatabaseOperationException, DatabaseCriticalException, MPPDBIDEException, Exception { + // oid Before refresh to check availability in cache + dbconn = editTableCore.getTermConnection().getDatabase().getConnectionManager().getObjBrowserConn(); + editTableCore.refreshTable(dbconn); + if (editTableCore.isTableDropped()) { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_EDITTABLE_REFRESH_FAILED)); + throw new DatabaseOperationException(IMessagesConstants.ERR_EDITTABLE_REFRESH_FAILED); + } + return null; + } + + @Override + public void onSuccessUIAction(Object object) { + checkWindowDetails(); + if (isDisposed()) { + return; + } + AbstractEditTableDataResultDisplayUIManager.this.setCore(editTableCore); + EditTableDataExecutionContext context = new EditTableDataExecutionContext(editTableCore, + AbstractEditTableDataResultDisplayUIManager.this, editTableCore.getTable()); + + TerminalQueryExecutionWorker terminalQueryWorker = new TerminalQueryExecutionWorker(context); + terminalQueryWorker.setTaskDB(editTableCore.getTermConnection().getDatabase()); + terminalQueryWorker.schedule(); + } + + @Override + public void onCriticalExceptionUIAction(DatabaseCriticalException excep) { + handleExceptionDisplay(excep); + MPPDBIDELoggerUtility.error("Refresh edit table metadata failed.", excep); + } + + @Override + public void onOperationalExceptionUIAction(DatabaseOperationException excep) { + handleExceptionDisplay(excep); + if (excep.getMessage().equalsIgnoreCase( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_EDITTABLE_REFRESH_FAILED))) { + MPPDBIDEDialogs.generateMessageDialog(MESSAGEDIALOGTYPE.ERROR, true, + IconUtility.getIconImage(IiconPath.ICO_TOOL_32X32, this.getClass()), + MessageConfigLoader.getProperty(IMessagesConstants.EDIT_TABLE_DATA_ERROR_POPUP_HEADER), + MessageConfigLoader.getProperty(IMessagesConstants.EDIT_TABLE_DATA_DROPPED_REFRESH_ERROR), + new String[] {MessageConfigLoader.getProperty(IMessagesConstants.BTN_OK)}); + } + MPPDBIDELoggerUtility.error("Refresh edit table metadata failed.", excep); + } + + @Override + public void finalCleanup() throws MPPDBIDEException { + MPPDBIDELoggerUtility.info("Table metaData refreshed for Edit Table Wndow"); + } + + @Override + public void finalCleanupUI() { + MPPDBIDELoggerUtility.info("Table metaData refreshed for Edit Table Wndow"); + } + + } + + /** + * + * Title: class + * + * Description: The Class RowEffectedConfirmation. + */ + public static class RowEffectedConfirmation implements IRowEffectedConfirmation { + + /** + * Prompt uer confirmation. + */ + @Override + public void promptUerConfirmation() { + Display.getDefault().syncExec(new Runnable() { + + @Override + public void run() { + RowEffectedConfirmationPrompt promptMsg = new RowEffectedConfirmationPrompt( + Display.getDefault().getActiveShell(), + MessageConfigLoader.getProperty(IMessagesConstants.EDIT_DUPLICATE_MODIFICATION_TITLE), + IconUtility.getIconImage(IiconPath.ICO_TOOL_32X32, this.getClass()), + MessageConfigLoader.getProperty(IMessagesConstants.EDIT_DUPLICATE_MODIFICATION_MSG), + MessageDialog.INFORMATION, null, 1); + + promptMsg.open(); + } + }); + + } + } + + /** + * Gets the single query array. + * + * @param queryArray the query array + * @param query the query + * @return the single query array + */ + @Override + public void getSingleQueryArray(ArrayList queryArray, String query) { + + } + + /** + * Sets the cursor offset. + * + * @param offset the new cursor offset + */ + @Override + public void setCursorOffset(int offset) { + + } + + /** + * Handle grid component on dialog cancel. + */ + @Override + public void handleGridComponentOnDialogCancel() { + Display.getDefault().syncExec(new Runnable() { + @Override + public void run() { + if (null != editTableGridComponent && !editTableGridComponent.isDisposed()) { + editTableGridComponent.setLoadingStatus(false); + editTableGridComponent.enableDisableGrid(true); + } + } + }); + } + + private void showPopUpOnDirtyTableFetchNextRecords() { + MPPDBIDEDialogs.generateOKMessageDialog(MESSAGEDIALOGTYPE.INFORMATION, true, + MessageConfigLoader.getProperty(IMessagesConstants.SAVE_CHANGES_TITLE), + MessageConfigLoader.getProperty(IMessagesConstants.SAVE_CHANGES_DATA_BODY)); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/edittabledata/CellEdit.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/edittabledata/CellEdit.java new file mode 100644 index 0000000000000000000000000000000000000000..20bd7383faf8e1d8ba52484ffdca3f28cfbc0f6c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/edittabledata/CellEdit.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.edittabledata; + +import org.eclipse.e4.core.di.annotations.CanExecute; +import org.eclipse.e4.core.di.annotations.Execute; + +/** + * + * Title: class + * + * Description: The Class CellEdit. + * + * @since 3.0.0 + */ +public class CellEdit { + private static boolean isColEditSelect = false; + + /** + * Execute. + */ + @Execute + public void execute() { + CellEdit.setEditSelect(true); + } + + /** + * Can execute. + * + * @return true, if successful + */ + @CanExecute + public boolean canExecute() { + return true; + } + + /** + * Checks if is edits the select. + * + * @return true, if is edits the select + */ + public static boolean isEditSelect() { + return isColEditSelect; + } + + /** + * Sets the edits the select. + * + * @param isColEditSelec the new edits the select + */ + public static void setEditSelect(boolean isColEditSelec) { + CellEdit.isColEditSelect = isColEditSelec; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/edittabledata/EditTableDataResultDisplayUIManager.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/edittabledata/EditTableDataResultDisplayUIManager.java new file mode 100644 index 0000000000000000000000000000000000000000..89570d4eb9e1f3e51907dc59b2354ba9b1ee4516 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/edittabledata/EditTableDataResultDisplayUIManager.java @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.edittabledata; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; + +import org.opengauss.mppdbide.bl.serverdatacache.ITableMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.TableMetaData; +import org.opengauss.mppdbide.presentation.IEditTableDataCore; +import org.opengauss.mppdbide.presentation.grid.IDSEditGridDataProvider; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.messaging.ProgressBarLabelFormatter; +import org.opengauss.mppdbide.view.component.grid.CommitInputData; +import org.opengauss.mppdbide.view.component.grid.UserPromptMessageForUnqCons; +import org.opengauss.mppdbide.view.prefernces.EditTableOptionProviderForPreferences; +import org.opengauss.mppdbide.view.prefernces.PreferenceWrapper; +import org.opengauss.mppdbide.view.ui.terminal.ColumnsListDialog; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * + * Title: class + * + * Description: The Class EditTableDataResultDisplayUIManager. + * + * @since 3.0.0 + */ +public class EditTableDataResultDisplayUIManager extends AbstractEditTableDataResultDisplayUIManager { + + /** + * Instantiates a new edits the table data result display UI manager. + * + * @param core1 the core 1 + */ + public EditTableDataResultDisplayUIManager(IEditTableDataCore core1) { + super(core1); + + } + + /** + * Gets the progress label. + * + * @return the progress label + */ + protected String getProgressLabel() { + String progressLabel = null; + if (core.getTable() instanceof TableMetaData) { + TableMetaData tableMetaData = (TableMetaData) core.getTable(); + progressLabel = ProgressBarLabelFormatter.getProgressLabelForTableWithMsg(tableMetaData.getName(), + tableMetaData.getNamespace().getName(), tableMetaData.getDatabaseName(), + tableMetaData.getServerName(), IMessagesConstants.EDIT_TABLE_COMMIT_PROGRESS_NAME); + } + return progressLabel; + } + + /** + * Gets the save conditional input. + * + * @param dataProvider the data provider + * @return the save conditional input + */ + protected CommitInputData getSaveConditionalInput(IDSEditGridDataProvider dataProvider) { + if (null != super.rememberedUserOptions) { + return super.rememberedUserOptions; + } + + CommitInputData saveUserOptions = null; + if (core.getTable() instanceof TableMetaData) { + saveUserOptions = getSaveOptions(dataProvider); + } + if (null == saveUserOptions) { + return null; + } else if (saveUserOptions.getRemember()) { + super.rememberedUserOptions = saveUserOptions; + this.editTableGridComponent.savedUserOption(); + // Send event -> remembered user option. + } + return saveUserOptions; + } + + /** + * Gets the save options. + * + * @param dataProvider the data provider + * @return the save options + */ + public static CommitInputData getSaveOptions(IDSEditGridDataProvider dataProvider) { + final int optionSelectedZero = 0; + final int optionSelectedOne = 1; + Shell activeShell = Display.getDefault().getActiveShell(); + CommitInputData commitData = new CommitInputData(); + + List selectedColnames = null; + selectedColnames = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + if (dataProvider.isDistributionColumnsRequired()) { + boolean uniqueConsPresent = ((IDSEditGridDataProvider) dataProvider).isUniqueKeyPresent(); + TableMetaData tableMetaData = (TableMetaData) ((IDSEditGridDataProvider) dataProvider).getTable(); + if (!uniqueConsPresent) { + UserPromptMessageForUnqCons promptMsg = getPromptMsgDialog(dataProvider, activeShell, tableMetaData); + int optionSelected = promptMsg.open(); + + switch (optionSelected) { + case optionSelectedZero: { + handleOnOptionSelectedZero(dataProvider, selectedColnames, tableMetaData); + break; + } + case optionSelectedOne: { + ColumnsListDialog colListDlg = new ColumnsListDialog(activeShell, tableMetaData, + dataProvider.getTableName(), dataProvider.getColumnNames(), + dataProvider.getColumnDataTypeNames()); + colListDlg.open(); + if (colListDlg.getOkPressed()) { + selectedColnames = colListDlg.getUserSelectedColumnNames(); + } else { + return null; + } + break; + } + default: { + return null; + } + } + commitData.setRemember(promptMsg.isUserSelectionOfRemember()); + } + + } + boolean isAtomic = !PreferenceWrapper.getInstance().getPreferenceStore() + .getBoolean(EditTableOptionProviderForPreferences.EDITTABLE_COMMIT_ON_FAILURE); + commitData.setAtomic(isAtomic); + commitData.setUniqueKeys(selectedColnames); + return commitData; + } + + private static UserPromptMessageForUnqCons getPromptMsgDialog(IDSEditGridDataProvider dataProvider, + Shell activeShell, TableMetaData table) { + UserPromptMessageForUnqCons promptMsg = new UserPromptMessageForUnqCons(activeShell, + MessageConfigLoader.getProperty(IMessagesConstants.EDIT_DATA_WIZARD_TITLE), + IconUtility.getIconImage(IiconPath.ICO_TOOL_32X32, EditTableDataResultDisplayUIManager.class), + MessageConfigLoader.getProperty(IMessagesConstants.NO_PHYSICAL_UNQ_KEY_MSG) + + (table != null ? table.getDisplayName() : dataProvider.getTableName()) + + MPPDBIDEConstants.LINE_SEPARATOR + + MessageConfigLoader.getProperty(IMessagesConstants.DEFINE_UNQ_KEY_MSG), + MessageDialog.WARNING, null, 1); + return promptMsg; + } + + private static void handleOnOptionSelectedZero(IDSEditGridDataProvider dataProvider, List selectedColnames, + ITableMetaData table) { + if (table != null) { + if (table instanceof TableMetaData) { + int columnMetadaListSize = ((TableMetaData) table).getColumnMetaDataList().size(); + for (int cnt = 0; cnt < columnMetadaListSize; cnt++) { + selectedColnames.add(((TableMetaData) table).getColumnMetaDataList().get(cnt).getName()); + } + } + + } else { + selectedColnames.addAll(dataProvider.getColumnNames()); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/edittabledata/EditTableDataStates.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/edittabledata/EditTableDataStates.java new file mode 100644 index 0000000000000000000000000000000000000000..f95a1f252dbb1544631ff987936758fdd4d42fbe --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/edittabledata/EditTableDataStates.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.edittabledata; + +/** + * + * Title: enum + * + * Description: The Enum EditTableDataStates. + * + * @since 3.0.0 + */ +public enum EditTableDataStates { + + /** + * The init. + */ + INIT, + /** + * The executing. + */ + EXECUTING, + /** + * The executed. + */ + EXECUTED, + /** + * The editing. + */ + EDITING, + /** + * The edited. + */ + EDITED, + /** + * The posting. + */ + POSTING, + /** + * The posted. + */ + POSTED, + /** + * The commiting. + */ + COMMITING, + /** + * The commited. + */ + COMMITED, + /** + * The rollingback. + */ + ROLLINGBACK, + /** + * The rolledback. + */ + ROLLEDBACK, +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/edittabledata/EditTableUIWorker.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/edittabledata/EditTableUIWorker.java new file mode 100644 index 0000000000000000000000000000000000000000..e44b9e317e63caad6f213575c19a139dd113285d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/edittabledata/EditTableUIWorker.java @@ -0,0 +1,353 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.edittabledata; + +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; +import org.opengauss.mppdbide.presentation.TerminalExecutionConnectionInfra; +import org.opengauss.mppdbide.presentation.TerminalExecutionSQLConnectionInfra; +import org.opengauss.mppdbide.presentation.edittabledata.CommitStatus; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableCellState; +import org.opengauss.mppdbide.presentation.edittabledata.EditTableRecordStates; +import org.opengauss.mppdbide.presentation.edittabledata.IDSGridEditDataRow; +import org.opengauss.mppdbide.presentation.grid.IDSEditGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridColumnProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataProvider; +import org.opengauss.mppdbide.presentation.grid.IDSGridDataRow; +import org.opengauss.mppdbide.presentation.grid.IRowEffectedConfirmation; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.messaging.StatusMessage; +import org.opengauss.mppdbide.utils.observer.DSEvent; +import org.opengauss.mppdbide.utils.observer.DSEventTable; +import org.opengauss.mppdbide.utils.observer.IDSGridUIListenable; +import org.opengauss.mppdbide.view.component.grid.core.DataGrid; +import org.opengauss.mppdbide.view.component.grid.core.DataText; +import org.opengauss.mppdbide.view.handler.connection.PromptPasswordUIWorkerJob; +import org.opengauss.mppdbide.view.ui.terminal.SQLTerminal; +import org.opengauss.mppdbide.view.utils.BottomStatusBar; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs.MESSAGEDIALOGTYPE; + +import ca.odell.glazedlists.EventList; + +/** + * + * Title: class + * + * Description: The Class EditTableUIWorker. + * + * @since 3.0.0 + */ +public class EditTableUIWorker extends PromptPasswordUIWorkerJob { + private IDSGridDataProvider dataProvider; + private DataGrid dataGrid; + private DataText dataText; + private List colNames; + private boolean isAtomic; + private DSEventTable eventTable; + private CommitStatus commitStatus; + private BottomStatusBar statusBar; + + private StatusMessage statusMessage; + private TerminalExecutionConnectionInfra terminalConnection; + private IRowEffectedConfirmation rowEffectedConfirm; + private boolean isResultTabFlow; + private DBConnection conn; + private SQLTerminal terminal; + + /** + * Instantiates a new edits the table UI worker. + * + * @param name the name + * @param family the family + * @param termConnection the term connection + * @param dataGrid the data grid + * @param dataText the data text + * @param dataProvider the data provider + * @param columnNames the column names + * @param isAtomic the is atomic + * @param eventTable the event table + * @param statusBar the status bar + * @param statusMessage the status message + * @param rowEffectedConfirm the row effected confirm + * @param isResultTabFlow the is result tab flow + */ + public EditTableUIWorker(String name, Object family, TerminalExecutionConnectionInfra termConnection, + DataGrid dataGrid, DataText dataText, IDSGridDataProvider dataProvider, List columnNames, + boolean isAtomic, DSEventTable eventTable, BottomStatusBar statusBar, StatusMessage statusMessage, + IRowEffectedConfirmation rowEffectedConfirm, boolean isResultTabFlow) { + super(name, MPPDBIDEConstants.CANCELABLEJOB, IMessagesConstants.EDIT_TABLE_DATA_ERROR_POPUP_HEADER); + this.terminalConnection = termConnection; + this.dataGrid = dataGrid; + this.dataText = dataText; + this.dataProvider = dataProvider; + this.colNames = columnNames; + this.isAtomic = isAtomic; + this.eventTable = eventTable; + this.statusBar = statusBar; + this.statusMessage = statusMessage; + this.rowEffectedConfirm = rowEffectedConfirm; + this.isResultTabFlow = isResultTabFlow; + this.conn = null; + } + + /** + * Do job. + * + * @return the object + * @throws DatabaseOperationException the database operation exception + * @throws DatabaseCriticalException the database critical exception + * @throws MPPDBIDEException the MPPDBIDE exception + * @throws Exception the exception + */ + @Override + public Object doJob() throws DatabaseOperationException, DatabaseCriticalException, MPPDBIDEException, Exception { + if (isResultTabFlow) { + TerminalExecutionSQLConnectionInfra sqlConnection = (TerminalExecutionSQLConnectionInfra) terminalConnection; + if (null == sqlConnection) { + return null; + } + setServerPwd(!sqlConnection.getReuseConnectionFlag() + && sqlConnection.getDatabase().getServer().getSavePrdOption().equals(SavePrdOptions.DO_NOT_SAVE)); + conn = sqlConnection.getSecureConnection(this); + while (conn == null) { + Thread.sleep(SQL_TERMINAL_THREAD_SLEEP_TIME); + if (this.isCancel()) { + return null; + } + if (this.isNotified()) { + conn = this.terminalConnection.getConnection(); + } + } + } + + Database db = getDatabase(); + if (null != db && db.getServer().getSavePrdOption().equals(SavePrdOptions.DO_NOT_SAVE) + && getEncrpytedProfilePrd() != null) { + db.getServer().setPrd(getEncrpytedProfilePrd()); + } + // local variable to be used in future + // CommitStatus commitStatus + ((IDSEditGridDataProvider) dataProvider).setCancel(false); + commitStatus = ((IDSEditGridDataProvider) dataProvider).commit(colNames, isAtomic, rowEffectedConfirm, conn); + + return null; + } + + /** + * On success UI action. + * + * @param obj the obj + */ + @Override + public void onSuccessUIAction(Object obj) { + if (null == this.dataGrid.getDataGrid()) { + return; + } + + EventList listOfRows = this.dataGrid.getListOfRows(); + Map failedInsertsMap = new TreeMap(); + int index = 0; + Integer rowIndex; + IDSGridDataRow row = null; + + if (null != commitStatus) { + List listOfFailureRows = commitStatus.getListOfFailureRows(); + + for (Iterator iterator = listOfFailureRows.iterator(); iterator.hasNext();) { + IDSGridEditDataRow idsGridEditDataRow = (IDSGridEditDataRow) iterator.next(); + if (idsGridEditDataRow.getUpdatedState() == EditTableRecordStates.INSERT) { + index = listOfRows.indexOf(idsGridEditDataRow); + failedInsertsMap.put(index, idsGridEditDataRow); + } + } + } + + listOfRows.clear(); + listOfRows.addAll(dataProvider.getAllFetchedRows()); + + for (Map.Entry entry : failedInsertsMap.entrySet()) { + row = entry.getValue(); + rowIndex = entry.getKey(); + listOfRows.add(rowIndex, row); + + } + + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_EDITTABLE_COMMIT_STATUS, dataProvider)); + if (null != commitStatus && commitStatus.getListOfFailureRows().size() > 0) { + MPPDBIDEDialogs.generateOKMessageDialog(MESSAGEDIALOGTYPE.ERROR, true, + MessageConfigLoader.getProperty(IMessagesConstants.QUERY_EXECUTION_FAILURE_ERROR_TITLE), + MessageConfigLoader.getProperty(IMessagesConstants.QUERY_EXECUTION_FAILURE_ERROR)); + resetCellValues(commitStatus.getListOfFailureRows()); + } + + if (null != dataText && null != commitStatus && commitStatus.getListOfSuccessRows().size() > 0) { + this.dataText.updateTextData(); + } + } + + /** + * Reset cell values. + * + * @param listOfFailureRows the list of failure rows + */ + private void resetCellValues(List listOfFailureRows) { + IDSGridColumnProvider columnDataProvider = dataProvider.getColumnDataProvider(); + if (null != columnDataProvider) { + int length = columnDataProvider.getColumnCount(); + // CHECKSTYLE:OFF + for (IDSGridEditDataRow row : listOfFailureRows) { + for (int cnt = 0; cnt < length; cnt++) { + row.setCellSatus(EditTableCellState.MODIFIED_FAILED, cnt); + } + } + } + // CHECKSTYLE:ON + } + + /** + * On operational exception UI action. + * + * @param exception the exception + */ + @Override + public void onOperationalExceptionUIAction(DatabaseOperationException exception) { + exceptionEventCall(exception); + } + + /** + * Final cleanup. + */ + @Override + public void finalCleanup() { + super.finalCleanup(); + if (isResultTabFlow) { + ((TerminalExecutionSQLConnectionInfra) terminalConnection).releaseSecureConnection(this.conn); + } + } + + /** + * Final cleanup UI. + */ + @Override + public void finalCleanupUI() { + if (null != commitStatus && commitStatus.getListOfSuccessRows().size() > 0) { + if (terminal != null) { + terminal.resetCommitAndRollbackButton(); + } + } + statusBar.hideStatusbar(statusMessage); + if (eventTable != null) { + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_EDITTABLE_COMMIT_DATA_COMPLETE, null)); + } + + } + + /** + * Pre UI setup. + * + * @param preHandlerObject the pre handler object + * @return true, if successful + */ + @Override + public boolean preUISetup(Object preHandlerObject) { + if (isResultTabFlow) { + TerminalExecutionSQLConnectionInfra sqlConnection = (TerminalExecutionSQLConnectionInfra) terminalConnection; + if (sqlConnection.getReuseConnectionFlag()) { + return true; + } + } + return promptAndValidatePassword(); + } + + /** + * On critical exception UI action. + * + * @param exception the exception + */ + @Override + public void onCriticalExceptionUIAction(DatabaseCriticalException exception) { + exceptionEventCall(exception); + } + + /** + * Exception event call. + * + * @param exception the exception + */ + public void exceptionEventCall(MPPDBIDEException exception) { + MPPDBIDEDialogs.generateOKMessageDialog(MESSAGEDIALOGTYPE.ERROR, true, + MessageConfigLoader.getProperty(IMessagesConstants.QUERY_EXECUTION_FAILURE_ERROR_TITLE), + exception.getServerMessage()); + eventTable.sendEvent(new DSEvent(IDSGridUIListenable.LISTEN_EDITTABLE_COMMIT_STATUS, dataProvider)); + CommitStatus lastCommitStatus = ((IDSEditGridDataProvider) dataProvider).getLastCommitStatus(); + if (lastCommitStatus != null) { + resetCellValues(lastCommitStatus.getListOfFailureRows()); + } + } + + /** + * Canceling. + */ + @Override + protected void canceling() { + super.canceling(); + try { + ((IDSEditGridDataProvider) dataProvider).setCancel(true); + + ((IDSEditGridDataProvider) dataProvider).cancelCommit(); + + if (isResultTabFlow) { + ((TerminalExecutionSQLConnectionInfra) terminalConnection).releaseSecureConnection(this.conn); + } + } catch (DatabaseCriticalException exception) { + exceptionEventCall(exception); + } catch (DatabaseOperationException exception) { + exceptionEventCall(exception); + } + + } + + /** + * Gets the database. + * + * @return the database + */ + @Override + protected Database getDatabase() { + return terminalConnection.getDatabase(); + } + + /** + * Sets the terminal. + * + * @param terminal the new terminal + */ + public void setTerminal(SQLTerminal terminal) { + this.terminal = terminal; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/edittabledata/IModifiedRows.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/edittabledata/IModifiedRows.java new file mode 100644 index 0000000000000000000000000000000000000000..7bfa08b5853939603dfc6cf1b82b3c112c812aad --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/edittabledata/IModifiedRows.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.edittabledata; + +import java.util.ArrayList; +import java.util.Vector; + +/** + * + * Title: interface + * + * Description: The Interface IModifiedRows. + * + * @since 3.0.0 + */ +public interface IModifiedRows { + + /** + * Gets the ui row index. + * + * @return the ui row index + */ + int getUiRowIndex(); + + /** + * Gets the node id. + * + * @return the node id + */ + String getNodeId(); + + /** + * Gets the ctid. + * + * @return the ctid + */ + String getCtid(); + + /** + * Gets the original values. + * + * @return the original values + */ + ArrayList getOriginalValues(); + + /** + * Gets the display row vector. + * + * @return the display row vector + */ + Vector getDisplayRowVector(); + + /** + * Gets the modified values. + * + * @return the modified values + */ + ArrayList getModifiedValues(); + + /** + * Gets the operation type. + * + * @return the operation type + */ + String getOperationType(); + + /** + * Gets the failure msg. + * + * @return the failure msg + */ + String getFailureMsg(); + + /** + * Gets the table oid. + * + * @return the table oid + */ + String getTableOid(); + + /** + * Gets the modified columns. + * + * @return the modified columns + */ + ArrayList getModifiedColumns(); + + /** + * Gets the updated column values. + * + * @return the updated column values + */ + ArrayList getUpdatedColumnValues(); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/edittabledata/ModifiedRows.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/edittabledata/ModifiedRows.java new file mode 100644 index 0000000000000000000000000000000000000000..b1088bc3000f0cdd8716454d3ed3d7e79f8c2052 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/edittabledata/ModifiedRows.java @@ -0,0 +1,291 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.edittabledata; + +import java.util.ArrayList; +import java.util.Vector; + +/** + * + * Title: class + * + * Description: The Class ModifiedRows. + * + * @since 3.0.0 + */ +public class ModifiedRows implements IModifiedRows { + private int uiRowIndex; + private String tableOid; + private String nodeId; + private String ctid; + private ArrayList originalValues; + private ArrayList modifiedValues; + private ArrayList modifiedColumns; + private ArrayList updatedColumnValues; + + // Can be used if only modified columns can be identified for Update. + private String operationType; + + private boolean isPostSuccess; + private String failureMsg; + + /** + * Instantiates a new modified rows. + */ + public ModifiedRows() { + nodeId = ""; + tableOid = ""; + ctid = ""; + originalValues = new ArrayList(10); + modifiedValues = new ArrayList(10); + modifiedColumns = new ArrayList(10); + updatedColumnValues = new ArrayList(10); + operationType = ""; + isPostSuccess = false; + failureMsg = ""; + } + + /** + * Gets the ui row index. + * + * @return the ui row index + */ + @Override + public int getUiRowIndex() { + return uiRowIndex; + } + + /** + * Sets the ui row index. + * + * @param index the new ui row index + */ + public void setUiRowIndex(int index) { + this.uiRowIndex = index; + } + + /** + * Gets the node id. + * + * @return the node id + */ + @Override + public String getNodeId() { + return nodeId; + } + + /** + * Sets the node id. + * + * @param nodeId the new node id + */ + public void setNodeId(String nodeId) { + this.nodeId = nodeId; + } + + /** + * Gets the ctid. + * + * @return the ctid + */ + @Override + public String getCtid() { + return ctid; + } + + /** + * Sets the ctid. + * + * @param ctid the new ctid + */ + public void setCtid(String ctid) { + this.ctid = ctid; + } + + /** + * Gets the original values. + * + * @return the original values + */ + @Override + public ArrayList getOriginalValues() { + return originalValues; + } + + /** + * Gets the display row vector. + * + * @return the display row vector + */ + @Override + public Vector getDisplayRowVector() { + if (originalValues.size() != 0) { + Vector row = new Vector(originalValues); + return row; + } + return null; + } + + /** + * Sets the original values. + * + * @param originalValues the new original values + */ + public void setOriginalValues(ArrayList originalValues) { + this.originalValues = originalValues; + } + + /** + * Gets the modified values. + * + * @return the modified values + */ + @Override + public ArrayList getModifiedValues() { + return modifiedValues; + } + + /** + * Sets the modified values. + * + * @param modifiedValues the new modified values + */ + public void setModifiedValues(ArrayList modifiedValues) { + this.modifiedValues = modifiedValues; + } + + /** + * Gets the operation type. + * + * @return the operation type + */ + @Override + public String getOperationType() { + return operationType; + } + + /** + * Sets the operation type. + * + * @param operationType the new operation type + */ + public void setOperationType(String operationType) { + this.operationType = operationType; + } + + /** + * Checks if is post success. + * + * @return true, if is post success + */ + public boolean isPostSuccess() { + return isPostSuccess; + } + + /** + * Sets the post success. + * + * @param isPostSucess the new post success + */ + public void setPostSuccess(boolean isPostSucess) { + this.isPostSuccess = isPostSucess; + } + + /** + * Gets the failure msg. + * + * @return the failure msg + */ + @Override + public String getFailureMsg() { + return failureMsg; + } + + /** + * Sets the failure msg. + * + * @param failureMsg the new failure msg + */ + public void setFailureMsg(String failureMsg) { + this.failureMsg = failureMsg; + } + + /** + * Sets the table oid. + * + * @param oid the new table oid + */ + public void setTableOid(String oid) { + this.tableOid = oid; + } + + /** + * Gets the table oid. + * + * @return the table oid + */ + @Override + public String getTableOid() { + return this.tableOid; + } + + /** + * Gets the modified columns. + * + * @return the modified columns + */ + @Override + public ArrayList getModifiedColumns() { + return modifiedColumns; + } + + /** + * Sets the modified columns. + * + * @param modifiedColumns the new modified columns + */ + public void setModifiedColumns(ArrayList modifiedColumns) { + this.modifiedColumns = modifiedColumns; + } + + /** + * Gets the updated column values. + * + * @return the updated column values + */ + @Override + public ArrayList getUpdatedColumnValues() { + return updatedColumnValues; + } + + /** + * Sets the updated column values. + * + * @param updatedColumnValues the new updated column values + */ + public void setUpdatedColumnValues(ArrayList updatedColumnValues) { + this.updatedColumnValues = updatedColumnValues; + } + + /** + * Copy original to modified. + */ + public void copyOriginalToModified() { + for (String val : originalValues) { + modifiedValues.add(val); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/AbstractAnnotationMarkerAccess.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/AbstractAnnotationMarkerAccess.java new file mode 100644 index 0000000000000000000000000000000000000000..610b5c3b40455d71bd923dbdbffc959835068353 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/AbstractAnnotationMarkerAccess.java @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import org.eclipse.jface.text.source.Annotation; +import org.eclipse.jface.text.source.IAnnotationAccess; +import org.eclipse.jface.text.source.IAnnotationAccessExtension; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.widgets.Canvas; + +/** + * + * Title: class + * + * Description: The Class AbstractAnnotationMarkerAccess. + * + * @since 3.0.0 + */ +public abstract class AbstractAnnotationMarkerAccess implements IAnnotationAccess, IAnnotationAccessExtension { + + /** + * Gets the type label. + * + * @param annotation the annotation + * @return the type label + */ + @Override + public abstract String getTypeLabel(Annotation annotation); + + /** + * Gets the layer. + * + * @param annotation the annotation + * @return the layer + */ + @Override + public abstract int getLayer(Annotation annotation); + + /** + * Paint. + * + * @param annotation the annotation + * @param gc the gc + * @param canvas the canvas + * @param bounds the bounds + */ + @Override + public abstract void paint(Annotation annotation, GC gc, Canvas canvas, Rectangle bounds); + + /** + * Checks if is paintable. + * + * @param annotation the annotation + * @return true, if is paintable + */ + @Override + public boolean isPaintable(Annotation annotation) { + return false; + } + + /** + * Checks if is subtype. + * + * @param annotationType the annotation type + * @param potentialSupertype the potential supertype + * @return true, if is subtype + */ + @Override + public boolean isSubtype(Object annotationType, Object potentialSupertype) { + if (annotationType.equals(potentialSupertype)) { + return true; + } + + return false; + } + + /** + * Gets the supertypes. + * + * @param annotationType the annotation type + * @return the supertypes + */ + @Override + public Object[] getSupertypes(Object annotationType) { + return new Object[0]; + } + + /** + * Gets the type. + * + * @param annotation the annotation + * @return the type + */ + @Override + public Object getType(Annotation annotation) { + return annotation.getType(); + } + + /** + * Checks if is multi line. + * + * @param annotation the annotation + * @return true, if is multi line + */ + @Override + public abstract boolean isMultiLine(Annotation annotation); + + /** + * Checks if is temporary. + * + * @param annotation the annotation + * @return true, if is temporary + */ + @Override + public boolean isTemporary(Annotation annotation) { + return !annotation.isPersistent(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/AnnotationHelper.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/AnnotationHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..41858e3f5f1c80e5c2cf830362c3ed0299316a83 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/AnnotationHelper.java @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import org.eclipse.swt.graphics.RGB; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * Title: class + * Description: The Class DebugEditorItem. + * + * @since 3.0.0 + */ +public class AnnotationHelper { + /** + * break point annotation layer + */ + public static final int BREAKPOINT_LAYER = 1; + /** + * break point annotation type label + */ + public static final String BREAKPOINIT_TYPE_LABEL = IMessagesConstants.BREAKPOINT_ANNOTATION_LABEL; + /** + * break point annotation strategy id + */ + public static final String BREAKPOINT_STRATEGY_ID = "PLSQL_DEBUGGER_BREAKPOINT"; + /** + * break point annotation rgb + */ + public static final RGB BREAKPOINT_RGB = new RGB(188, 188, 222); + + /** + * debug position annotation layer + */ + public static final int DEBUG_POSITION_LAYER = 2; + /** + * debug position annotation type label + */ + public static final String DEBUG_POSITION_TYPE_LABEL = IMessagesConstants.DEBUG_POSITION_LABEL; + /** + * debug position annotation strategy id + */ + public static final String DEBUG_POSITION_STRATEGY_ID = "PLSQL_DEBUGGER_DEBUG_POSITION"; + /** + * debug position annotation rgb + */ + public static final RGB DEBUG_POSITION_RGB = new RGB(255, 153, 51); + + /** + * error annotation layer + */ + public static final int ERROR_LAYER = 3; + /** + * error annotation type label + */ + public static final String ERROR_TYPE_LABEL = IMessagesConstants.ERROR_ANNOTATION_LABEL; + /** + * error annotation strategy id + */ + public static final String ERROR_STRATEGY_ID = "error.type"; + /** + * error annotation rgb + */ + public static final RGB ERROR_RGB = new RGB(255, 0, 0); + + /** + * error position annotation layer + */ + public static final int ERROR_POSITION_LAYER = 2; + /** + * error position annotation type label + */ + public static final String ERROR_POSITION_TYPE_LABEL = IMessagesConstants.ERROR_POSITION_LABEL; + /** + * error position annotation strategy id + */ + public static final String ERROR_POSITION_STRATEGY_ID = "PLSQL_ERROR_POSITION"; + /** + * error position annotation rgb + */ + public static final RGB ERROR_POSITION_RGB = new RGB(255, 255, 0); + + /** + * Title: AnnotationType enum this enum assocate with AnnotationWithLineNumber's instance + * Description: The Class AnnotationType + */ + public static enum AnnotationType { + BREAKPOINT(BREAKPOINT_LAYER, BREAKPOINIT_TYPE_LABEL, BREAKPOINT_STRATEGY_ID, + BREAKPOINT_RGB), + DEBUG_POSITION(DEBUG_POSITION_LAYER, DEBUG_POSITION_TYPE_LABEL, DEBUG_POSITION_STRATEGY_ID, + DEBUG_POSITION_RGB), + ERROR(ERROR_LAYER, ERROR_TYPE_LABEL, ERROR_STRATEGY_ID, + ERROR_RGB), + ERROR_POSITION(ERROR_POSITION_LAYER, ERROR_POSITION_TYPE_LABEL, ERROR_POSITION_STRATEGY_ID, + ERROR_POSITION_RGB); + private final int layer; + private final String typeLabel; + private final String stragety; + private final RGB rgbShow; + AnnotationType(int layer, String typeLabel, String strategy, RGB rgbShow) { + this.layer = layer; + String tmpTypeLabel = ""; + if (!"".equals(typeLabel)) { + tmpTypeLabel = MessageConfigLoader.getProperty(typeLabel); + } + this.typeLabel = tmpTypeLabel; + this.stragety = strategy; + this.rgbShow = rgbShow; + } + + /** + * get layer + * + * @return int layer + * */ + public int getLayer() { + return layer; + } + + /** + * get type label + * + * @return String type label + * */ + public String getTypeLabel() { + return typeLabel; + } + + /** + * get stragegy + * + * @return String strategy id + * */ + public String getStrategy() { + return stragety; + } + + /** + * get rgb + * + * @return RGB get rgb + * */ + public RGB getRGB() { + return rgbShow; + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/AnnotationHover.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/AnnotationHover.java new file mode 100644 index 0000000000000000000000000000000000000000..0b9c7d6e54201d0c3a5e8c0e90a73ebfca4e6d0b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/AnnotationHover.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextHover; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.source.Annotation; +import org.eclipse.jface.text.source.AnnotationModel; +import org.eclipse.jface.text.source.IAnnotationHover; +import org.eclipse.jface.text.source.ISourceViewer; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * + * Title: class + * + * Description: The Class AnnotationHover. + * + * @since 3.0.0 + */ +public class AnnotationHover implements IAnnotationHover, ITextHover { + private AnnotationModel fAnnotationModel; + + /** + * Instantiates a new annotation hover. + * + * @param annotationModel the annotation model + */ + public AnnotationHover(AnnotationModel annotationModel) { + super(); + this.fAnnotationModel = annotationModel; + } + + /** + * Gets the hover info. + * + * @param textViewer the text viewer + * @param hoverRegion the hover region + * @return the hover info + */ + @Override + public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { + // Skip this + return null; + } + + /** + * Gets the hover region. + * + * @param textViewer the text viewer + * @param offset the offset + * @return the hover region + */ + @Override + public IRegion getHoverRegion(ITextViewer textViewer, int offset) { + // Skip this + return null; + } + + /** + * Gets the hover info. + * + * @param sourceViewer the source viewer + * @param lineNumber the line number + * @return the hover info + */ + @Override + public String getHoverInfo(ISourceViewer sourceViewer, int lineNumber) { + List hoverStr = new ArrayList(); + Iterator iterator = fAnnotationModel.getAnnotationIterator(); + Annotation annotation = null; + boolean doNotOverride = false; + boolean iteratorHasNext = iterator.hasNext(); + while (iteratorHasNext) { + annotation = iterator.next(); + if (annotation instanceof AnnotationWithLineNumber) { + AnnotationWithLineNumber annotationWithLineNumber = (AnnotationWithLineNumber) annotation; + if (annotation instanceof BreakpointAnnotation) { + if (!doNotOverride && lineNumber == annotationWithLineNumber.getLine()) { + hoverStr.add(annotation.getText()); + } + } else { + if (lineNumber + 1 == annotationWithLineNumber.getLine()) { + hoverStr.add(annotation.getText()); + } + if (annotationWithLineNumber instanceof ErrorPositionAnnotation) { + doNotOverride = true; + } + } + } + iteratorHasNext = iterator.hasNext(); + } + StringBuilder hoverInfo = new StringBuilder(); + if (hoverStr.size() > 1) { + hoverInfo.append(MessageConfigLoader.getProperty(IMessagesConstants.MUTIPLE_MARKERS)) + .append(MPPDBIDEConstants.LINE_SEPARATOR); + } + for (int i = 0; i < hoverStr.size(); i++) { + hoverInfo.append("-").append(hoverStr.get(i)).append(MPPDBIDEConstants.LINE_SEPARATOR); + } + return hoverInfo.toString(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/AnnotationWithLineNumber.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/AnnotationWithLineNumber.java new file mode 100644 index 0000000000000000000000000000000000000000..ab2854998900239e6418b81bd6eb12ed8e1ffb6c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/AnnotationWithLineNumber.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import java.util.Optional; + +import org.eclipse.jface.text.source.Annotation; +import org.eclipse.swt.graphics.Image; + +import org.opengauss.mppdbide.view.utils.icon.IconUtility; + +/** + * + * Title: class + * + * Description: The Class AnnotationWithLineNumber. + * + * @since 3.0.0 + */ +public abstract class AnnotationWithLineNumber extends Annotation { + /** + * the annotation line + */ + protected int line; + + public AnnotationWithLineNumber(String strategyId, boolean isPersistent, String info, int line) { + super(strategyId, isPersistent, info); + this.line = line; + } + + public AnnotationWithLineNumber(int line) { + super(); + this.line = line; + } + + /** + * description: get annotationType + * + * @return AnnotationType the type + */ + public abstract AnnotationHelper.AnnotationType getAnnotationType(); + + /** + * Gets the image. + * + * @return Optional the image + */ + public Optional getImage() { + return Optional.empty(); + } + + /** + * Gets the line. + * + * @return int the line + */ + public int getLine() { + return this.line; + } + + /** + * set line + * + * @param line line to set + * @return void + */ + public void setLine(int line) { + this.line = line; + } + + /** + * Equals. + * + * @param obj the obj + * @return boolean true if successful + */ + @Override + public boolean equals(Object obj) { + return this.getClass().isInstance(obj); + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * description: load image from path + * + * @param imagePath the image path + * @return Image image instance + */ + public static Image loadImage(String imagePath) { + return IconUtility.getIconImage(imagePath, AnnotationWithLineNumber.class); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/BreakpointAnnotation.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/BreakpointAnnotation.java new file mode 100644 index 0000000000000000000000000000000000000000..54a697d17ba4ba01e93abff753f9652e054dab35 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/BreakpointAnnotation.java @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import java.util.Optional; + +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.RGB; + +import org.opengauss.mppdbide.view.core.sourceeditor.AnnotationHelper.AnnotationType; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * Title: class + * Description: The Class BreakpointAnnotation. + * + * @since 3.0.0 + */ +public class BreakpointAnnotation extends AnnotationWithLineNumber { + private static final AnnotationHelper.AnnotationType ANNOTATION_TYPE = AnnotationType.BREAKPOINT; + private static final RGB BREAKPOINT_RGB = new RGB(188, 188, 222); + private int breakpointId; + private boolean enable = true; + + /** + * Instantiates a new breakpoint annotation. + * + * @param info the info + * @param line the line + */ + public BreakpointAnnotation(String info, int line) { + super(ANNOTATION_TYPE.getStrategy(), false, info, line); + } + + @Override + public AnnotationHelper.AnnotationType getAnnotationType() { + return ANNOTATION_TYPE; + } + + /** + * Gets the layer. + * + * @return the layer + */ + public static int getLayer() { + return ANNOTATION_TYPE.getLayer(); + } + + /** + * Gets the image. + * + * @return the image + */ + @Override + public Optional getImage() { + String imgPath = enable ? IiconPath.ICO_BREAKPOINT_ENABLED : + IiconPath.ICO_BREAKPOINT_DISABLED; + return Optional.ofNullable(loadImage(imgPath)); + } + + /** + * Gets the breakpoint rgb. + * + * @return the breakpoint rgb + */ + public static RGB getBreakpointRgb() { + return BREAKPOINT_RGB; + } + + /** + * Gets the strategyid. + * + * @return the strategyid + */ + public static String getStrategyid() { + return ANNOTATION_TYPE.getStrategy(); + } + + /** + * Gets the breakpoint id. + * + * @return the breakpoint id + */ + public int getBreakpointId() { + return breakpointId; + } + + /** + * Sets the breakpoint id. + * + * @param breakpointId the new breakpoint id + */ + public void setBreakpointId(int breakpointId) { + this.breakpointId = breakpointId; + } + + /** + * Gets the typelabel. + * + * @return the typelabel + */ + public static String getTypelabel() { + return ANNOTATION_TYPE.getTypeLabel(); + } + + /** + * Sets the disabled. + * + * @param isDisabld the new disabled + */ + public void setEnable(boolean enable) { + this.enable = enable; + } + + /** + * Sets the disabled. + * + * @param isDisabld the new disabled + * @return boolean true is enable + */ + public boolean getEnable() { + return this.enable; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/DSDefaultCharacterPairMatcher.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/DSDefaultCharacterPairMatcher.java new file mode 100644 index 0000000000000000000000000000000000000000..b94d29c65cc177c8ca2f2b2c790e002b4baf4613 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/DSDefaultCharacterPairMatcher.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import org.eclipse.core.runtime.Assert; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IDocumentExtension3; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.source.DefaultCharacterPairMatcher; +import org.eclipse.jface.text.source.ICharacterPairMatcher; + +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.view.utils.CharPairsUtil; +import org.opengauss.mppdbide.view.utils.DSDefaultCharacterPairMatcherUtil; +import org.opengauss.mppdbide.view.utils.DSRegion; + +/** + * + * Title: class + * + * Description: The Class DSDefaultCharacterPairMatcher. + * + * @since 3.0.0 + */ +public class DSDefaultCharacterPairMatcher extends DefaultCharacterPairMatcher { + private CharPairsUtil fPairs; + private int fAnchor = -1; + private String fPartitioning; + private boolean fCaretEitherSideOfBracket; + + /** + * Instantiates a new DS default character pair matcher. + * + * @param chars the chars + * @param partitioning the partitioning + */ + public DSDefaultCharacterPairMatcher(char[] chars, String partitioning) { + this(chars, partitioning, false); + } + + /** + * Instantiates a new DS default character pair matcher. + * + * @param chars the chars + * @param partitioning the partitioning + * @param caretEitherSideOfBracket the caret either side of bracket + */ + public DSDefaultCharacterPairMatcher(char[] chars, String partitioning, boolean caretEitherSideOfBracket) { + super(chars, partitioning, caretEitherSideOfBracket); + Assert.isLegal(chars.length % 2 == 0); + Assert.isNotNull(partitioning); + fPairs = new CharPairsUtil(chars); + fPartitioning = partitioning; + fCaretEitherSideOfBracket = caretEitherSideOfBracket; + } + + /** + * Instantiates a new DS default character pair matcher. + * + * @param chars the chars + */ + public DSDefaultCharacterPairMatcher(char[] chars) { + this(chars, IDocumentExtension3.DEFAULT_PARTITIONING); + } + + /** + * Match. + * + * @param document the document + * @param offset the offset + * @param length the length + * @return the i region + */ + @Override + public IRegion match(IDocument document, int offset, int length) { + if (document == null || offset < 0 || offset > document.getLength() || Math.abs(length) > 1) { + return null; + } + + try { + int sourceCaretOffset = offset + length; + if (Math.abs(length) == 1) { + char ch = length > 0 ? document.getChar(offset) : document.getChar(sourceCaretOffset); + if (!fPairs.contains(ch) && !DSDefaultCharacterPairMatcherUtil.isQuote(ch)) { + return null; + } + } + int adjustment = getOffSetAdjustment(document, sourceCaretOffset, length); + sourceCaretOffset += adjustment; + return match(document, sourceCaretOffset); + } catch (BadLocationException e) { + return null; + } + } + + /** + * Match. + * + * @param doc the doc + * @param offset the offset + * @return the i region + */ + @Override + public IRegion match(IDocument doc, int offset) { + if (doc == null || offset < 0 || offset > doc.getLength()) { + return null; + } + try { + return performDsMatch(doc, offset); + } catch (BadLocationException ble) { + return null; + } + } + + /** + * Gets the offset adjustment. + * + * @param document the document + * @param offset the offset + * @param length the length + * @return the offset adjustment + */ + private int getOffSetAdjustment(IDocument document, int offset, int length) { + if (length == 0 || Math.abs(length) > 1 || offset >= document.getLength()) { + return 0; + } + try { + if (length < 0) { + if (fPairs.isStartPunctuation(document.getChar(offset)) + || (!fCaretEitherSideOfBracket && fPairs.isEndPunctuation(document.getChar(offset)))) { + return 1; + } + } else { + if (fCaretEitherSideOfBracket && fPairs.isEndPunctuation(document.getChar(offset - 1))) { + return -1; + } + } + } catch (BadLocationException exception) { + // do nothing + MPPDBIDELoggerUtility.error( + "DSDefaultCharacterPairMatcher.getOffsetAdjustment(): BadLocationException occurred.", exception); + } + return 0; + } + + /** + * Perform match. + * + * @param doc the doc + * @param caretOffset the caret offset + * @return the i region + * @throws BadLocationException the bad location exception + */ + public IRegion performDsMatch(IDocument doc, int caretOffset) throws BadLocationException { + + boolean isForward = true; + DSRegion retRegion = (DSRegion) DSDefaultCharacterPairMatcherUtil.getRegion(doc, caretOffset, fPairs, isForward, + fPartitioning, fCaretEitherSideOfBracket, false); + if (null != retRegion) { + fAnchor = retRegion.getForward() ? ICharacterPairMatcher.LEFT : ICharacterPairMatcher.RIGHT; + } + return retRegion; + } + + /** + * Checks if is matched char. + * + * @param ch the ch + * @return true, if is matched char + */ + @Override + public boolean isMatchedChar(char ch) { + return fPairs.contains(ch); + } + + /** + * Checks if is matched char. + * + * @param ch the ch + * @param document the document + * @param offset the offset + * @return true, if is matched char + */ + @Override + public boolean isMatchedChar(char ch, IDocument document, int offset) { + return isMatchedChar(ch); + } + + /** + * Clear. + */ + @Override + public void clear() { + fAnchor = -1; + } + + /** + * Gets the anchor. + * + * @return the anchor + */ + @Override + public int getAnchor() { + return fAnchor; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/DebugPositionAnnotation.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/DebugPositionAnnotation.java new file mode 100644 index 0000000000000000000000000000000000000000..d84deac34fc73fe22b6288ae30031a2efc6b5e87 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/DebugPositionAnnotation.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import java.util.Optional; + +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.RGB; + +import org.opengauss.mppdbide.view.core.sourceeditor.AnnotationHelper.AnnotationType; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * Title: class + * Description: The Class DebugPositionAnnotation. + * + * @since 3.0.0 + */ +public class DebugPositionAnnotation extends AnnotationWithLineNumber { + private static final AnnotationType ANNOTATION_TYPE = AnnotationType.DEBUG_POSITION; + private static final RGB DEBUGPOSITION_RGB = new RGB(255, 153, 51); + + /** + * Instantiates a new debug position annotation. + * + * @param line the line + */ + public DebugPositionAnnotation(int line) { + super(ANNOTATION_TYPE.getStrategy(), false, "[Line : " + line, line); + } + + /** + * Gets the layer. + * + * @return the layer + */ + public static int getLayer() { + return ANNOTATION_TYPE.getLayer(); + } + + /** + * Gets the image. + * + * @return the image + */ + public Optional getImage() { + return Optional.of( + loadImage(IiconPath.ICO_BREAKPOINT_ARROW) + ); + } + + /** + * Gets the breakpoint rgb. + * + * @return the breakpoint rgb + */ + public static RGB getBreakpointRgb() { + return DEBUGPOSITION_RGB; + } + + /** + * Gets the strategyid. + * + * @return the strategyid + */ + public static String getStrategyid() { + return ANNOTATION_TYPE.getStrategy(); + } + + /** + * Gets the typelabel. + * + * @return the typelabel + */ + public static String getTypelabel() { + return ANNOTATION_TYPE.getTypeLabel(); + } + + @Override + public AnnotationType getAnnotationType() { + return ANNOTATION_TYPE; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/ErrorAnnotation.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/ErrorAnnotation.java new file mode 100644 index 0000000000000000000000000000000000000000..123595b9c659d080f988264fc542d4668a23c0fd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/ErrorAnnotation.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import java.util.Optional; + +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.RGB; + +import org.opengauss.mppdbide.view.core.sourceeditor.AnnotationHelper.AnnotationType; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * Title: class + * Description: The Class ErrorAnnotation. + * + * @since 3.0.0 + */ +public class ErrorAnnotation extends AnnotationWithLineNumber { + private static final AnnotationType ANNOTATION_TYPE = AnnotationType.ERROR; + /** + * The Constant STRATEGY_ID. + */ + + private static final Object LOCK = new Object(); + private static volatile RGB errorRGB; + + /** + * Instantiates a new error annotation. + * + * @param line the line + * @param info the info + */ + public ErrorAnnotation(int line, String info) { + super(ANNOTATION_TYPE.getStrategy(), false, info, line); + } + + /** + * Gets the layer. + * + * @return the layer + */ + public static int getLayer() { + return ANNOTATION_TYPE.getLayer(); + } + + /** + * Gets the image. + * + * @return the image + */ + public Optional getImage() { + return Optional.of(loadImage(IiconPath.ICO_ERROR)); + } + + /** + * Gets the error rgb. + * + * @return the error rgb + */ + public static RGB getErrorRgb() { + if (null == errorRGB) { + synchronized (LOCK) { + if (null == errorRGB) { + errorRGB = ANNOTATION_TYPE.getRGB(); + } + } + } + return errorRGB; + } + + /** + * Gets the strategyid. + * + * @return the strategyid + */ + public static String getStrategyid() { + return ANNOTATION_TYPE.getStrategy(); + } + + /** + * Gets the typelabel. + * + * @return the typelabel + */ + public static String getTypelabel() { + return ANNOTATION_TYPE.getTypeLabel(); + } + + @Override + public AnnotationType getAnnotationType() { + return ANNOTATION_TYPE; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/ErrorAnnotationMarkerAccess.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/ErrorAnnotationMarkerAccess.java new file mode 100644 index 0000000000000000000000000000000000000000..1f53f9d9896bb10a5529d4c66ab80a55231bc47e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/ErrorAnnotationMarkerAccess.java @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import java.util.Optional; + +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.source.Annotation; +import org.eclipse.jface.text.source.AnnotationModel; +import org.eclipse.jface.text.source.ImageUtilities; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.widgets.Canvas; +import org.eclipse.ui.texteditor.DefaultMarkerAnnotationAccess; + +/** + * + * Title: class + * + * Description: The Class ErrorAnnotationMarkerAccess. + * + * @since 3.0.0 + */ +public class ErrorAnnotationMarkerAccess extends DefaultMarkerAnnotationAccess { + + private AnnotationModel fAnnotationModel; + private IDocument document; + + /** + * Instantiates a new error annotation marker access. + * + * @param fAnnotationModel the f annotation model + */ + public ErrorAnnotationMarkerAccess(AnnotationModel fAnnotationModel) { + this.fAnnotationModel = fAnnotationModel; + } + + /** + * Instantiates a new error annotation marker access. + * + * @param fAnnotationModel the f annotation model + * @param document the document + */ + public ErrorAnnotationMarkerAccess(AnnotationModel fAnnotationModel, IDocument document) { + this.fAnnotationModel = fAnnotationModel; + this.document = document; + } + + /** + * Gets the type label. + * + * @param annotation the annotation + * @return the type label + */ + @Override + public String getTypeLabel(Annotation annotation) { + if (annotation instanceof AnnotationWithLineNumber) { + return ((AnnotationWithLineNumber) annotation) + .getAnnotationType() + .getTypeLabel(); + } else { + return super.getTypeLabel(annotation); + } + } + + /** + * Gets the layer. + * + * @param annotation the annotation + * @return the layer + */ + @Override + public int getLayer(Annotation annotation) { + if (annotation instanceof AnnotationWithLineNumber) { + return ErrorAnnotation.getLayer(); + } + return super.getLayer(annotation); + } + + /** + * Paint. + * + * @param annotation the annotation + * @param gc the gc + * @param canvas the canvas + * @param bounds the bounds + */ + @Override + public void paint(Annotation annotation, GC gc, Canvas canvas, Rectangle bounds) { + if (annotation instanceof ErrorAnnotation) { + Optional paintImg = ((ErrorAnnotation) annotation).getImage(); + if (paintImg.isPresent()) { + ImageUtilities.drawImage(paintImg.get(), gc, canvas, bounds, SWT.CENTER, SWT.TOP); + } + + // Update the line number of the modified ErrorAnnotation. + Position position = fAnnotationModel.getPosition(annotation); + if (position != null) { + int offset = position.getOffset(); + int lineOfOffset = -1; + try { + if (document != null) { + lineOfOffset = document.getLineOfOffset(offset); + } + } catch (BadLocationException e) { + lineOfOffset = -1; + } + if (lineOfOffset != -1) { + // Line number starts from 0. Increment to get the actual + // number. + lineOfOffset++; + ((ErrorAnnotation) annotation).setLine(lineOfOffset); + } + } + } else { + super.paint(annotation, gc, canvas, bounds); + } + + } + + /** + * Checks if is paintable. + * + * @param annotation the annotation + * @return true, if is paintable + */ + @Override + public boolean isPaintable(Annotation annotation) { + if (annotation instanceof ErrorAnnotation) { + return ((ErrorAnnotation) annotation).getImage().isPresent(); + } else { + return super.isPaintable(annotation); + } + + } + + /** + * Checks if is multi line. + * + * @param annotation the annotation + * @return true, if is multi line + */ + @Override + public boolean isMultiLine(Annotation annotation) { + return true; + } + + /** + * Sets the document. + * + * @param document the new document + */ + public void setDocument(IDocument document) { + this.document = document; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/ErrorPositionAnnotation.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/ErrorPositionAnnotation.java new file mode 100644 index 0000000000000000000000000000000000000000..12152bdbf2e4a68845933c967c4fe5326f425d0b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/ErrorPositionAnnotation.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import java.util.Optional; + +import org.eclipse.swt.graphics.Image; + +import org.opengauss.mppdbide.view.core.sourceeditor.AnnotationHelper.AnnotationType; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * + * Title: class + * + * Description: The Class ErrorPositionAnnotation. + * + * @since 3.0.0 + */ +public class ErrorPositionAnnotation extends AnnotationWithLineNumber { + private static final AnnotationType ANNOTATION_TYPE = AnnotationType.ERROR_POSITION; + + /** + * Instantiates a new debug position annotation. + * + * @param errorMessage the line + */ + public ErrorPositionAnnotation(String errorMessage, int line) { + super(ANNOTATION_TYPE.getStrategy(), false, errorMessage, line); + } + + /** + * Gets the layer. + * + * @return the layer + */ + public static int getLayer() { + return ANNOTATION_TYPE.getLayer(); + } + + /** + * Gets the image. + * + * @return the image + */ + public Optional getImage() { + return Optional.of(loadImage(IiconPath.ICO_ERROR)); + } + + /** + * Gets the strategyid. + * + * @return the strategyid + */ + public static String getStrategyid() { + return ANNOTATION_TYPE.getStrategy(); + } + + /** + * Gets the typelabel. + * + * @return the typelabel + */ + public static String getTypelabel() { + return ANNOTATION_TYPE.getTypeLabel(); + } + + @Override + public AnnotationType getAnnotationType() { + return ANNOTATION_TYPE; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/ExecuteSourceEditor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/ExecuteSourceEditor.java new file mode 100644 index 0000000000000000000000000000000000000000..4f71398e4105875be29a323471f2dd58c5872b58 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/ExecuteSourceEditor.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import org.eclipse.swt.widgets.Shell; + +import org.opengauss.mppdbide.presentation.ContextExecutionOperationType; +import org.opengauss.mppdbide.view.terminal.executioncontext.FuncProcEditorTerminalExecutionContext; +import org.opengauss.mppdbide.view.ui.PLSourceEditor; + +/** + * + * Title: class + * + * Description: The Class ExecuteSourceEditor. + * + * @since 3.0.0 + */ +public class ExecuteSourceEditor { + + /** + * The exec context. + */ + FuncProcEditorTerminalExecutionContext execContext; + + /** + * The shell. + */ + Shell shell; + + /** + * The pl source editor. + */ + PLSourceEditor plSourceEditor; + + /** + * Instantiates a new execute source editor. + * + * @param shell the shell + * @param plSourceEditor the pl source editor + */ + public ExecuteSourceEditor(Shell shell, PLSourceEditor plSourceEditor) { + this.shell = shell; + this.plSourceEditor = plSourceEditor; + } + + /** + * Gets the context for new editor. + * + * @return the context for new editor + */ + public FuncProcEditorTerminalExecutionContext getContextForNewEditor() { + execContext = new FuncProcEditorTerminalExecutionContext(shell, plSourceEditor); + execContext.init(); + execContext.setCurrentExecution(ContextExecutionOperationType.CONTEXT_OPERATION_TYPE_NEW_PL_SQL_CREATION); + plSourceEditor.setExecutionContext(execContext); + return execContext; + } + + /** + * Gets the context for exitsing editor. + * + * @return the context for exitsing editor + */ + public FuncProcEditorTerminalExecutionContext getContextForExitsingEditor() { + execContext = new FuncProcEditorTerminalExecutionContext(shell, plSourceEditor); + execContext.init(); + execContext.setCurrentExecution(ContextExecutionOperationType.CONTEXT_OPERATION_TYPE_PL_SQL_COMPILATION); + plSourceEditor.setExecutionContext(execContext); + return execContext; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/FakeCompletionProposal.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/FakeCompletionProposal.java new file mode 100644 index 0000000000000000000000000000000000000000..c74dd19afab5e27f1d65ccecd2d23b7af7d7910d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/FakeCompletionProposal.java @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.contentassist.ICompletionProposal; +import org.eclipse.jface.text.contentassist.ICompletionProposalExtension; +import org.eclipse.jface.text.contentassist.ICompletionProposalExtension4; +import org.eclipse.jface.text.contentassist.IContextInformation; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Point; + +/** + * + * Title: class + * + * Description: The Class FakeCompletionProposal. + * + * @since 3.0.0 + */ +public class FakeCompletionProposal + implements ICompletionProposal, ICompletionProposalExtension, ICompletionProposalExtension4 { + + /** + * The display string. + */ + String fDisplayString = null; + + /** + * The offset. + */ + int fOffset = 0; + + /** + * Instantiates a new fake completion proposal. + * + * @param dispString the disp string + * @param offset the offset + */ + public FakeCompletionProposal(String dispString, int offset) { + fDisplayString = dispString; + fOffset = offset; + } + + /** + * Gets the selection. + * + * @param document the document + * @return the selection + */ + public Point getSelection(IDocument document) { + return new Point(fOffset, 0); + } + + /** + * Checks if is valid for. + * + * @param document the document + * @param offset the offset + * @return true, if is valid for + */ + public boolean isValidFor(IDocument document, int offset) { + return false; + } + + /** + * Gets the trigger characters. + * + * @return the trigger characters + */ + public char[] getTriggerCharacters() { + return new char[0]; + } + + /** + * Gets the display string. + * + * @return the display string + */ + public String getDisplayString() { + return fDisplayString; + } + + /** + * Gets the additional proposal info. + * + * @return the additional proposal info + */ + public String getAdditionalProposalInfo() { + return null; + } + + /** + * Gets the context information position. + * + * @return the context information position + */ + public int getContextInformationPosition() { + return -1; + } + + /** + * Checks if is auto insertable. + * + * @return true, if is auto insertable + */ + @Override + public boolean isAutoInsertable() { + return false; + } + + /** + * Apply. + * + * @param document the document + */ + public void apply(IDocument document) { + } + + /** + * Gets the image. + * + * @return the image + */ + public Image getImage() { + return null; + } + + /** + * Apply. + * + * @param document the document + * @param trigger the trigger + * @param offset the offset + */ + public void apply(IDocument document, char trigger, int offset) { + // Ignore + } + + /** + * Gets the context information. + * + * @return the context information + */ + public IContextInformation getContextInformation() { + return null; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/PLAnnotationMarkerAccess.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/PLAnnotationMarkerAccess.java new file mode 100644 index 0000000000000000000000000000000000000000..975f7b084693fe67c3e43c2376ce09ff68caf814 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/PLAnnotationMarkerAccess.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import java.util.Optional; + +import org.eclipse.jface.text.source.Annotation; +import org.eclipse.jface.text.source.ImageUtilities; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.widgets.Canvas; +import org.eclipse.ui.texteditor.DefaultMarkerAnnotationAccess; + +/** + * + * Title: class + * + * Description: The Class PLAnnotationMarkerAccess. + * + * @since 3.0.0 + */ +public class PLAnnotationMarkerAccess extends DefaultMarkerAnnotationAccess { + + /** + * Gets the type label. + * + * @param annotation the annotation + * @return the type label + */ + @Override + public String getTypeLabel(Annotation annotation) { + if (annotation instanceof AnnotationWithLineNumber) { + return ((AnnotationWithLineNumber)annotation).getAnnotationType().getTypeLabel(); + } else { + return super.getTypeLabel(annotation); + } + } + + /** + * Gets the layer. + * + * @param annotation the annotation + * @return the layer + */ + @Override + public int getLayer(Annotation annotation) { + if (annotation instanceof AnnotationWithLineNumber) { + return ((AnnotationWithLineNumber)annotation).getAnnotationType().getLayer(); + } + return super.getLayer(annotation); + } + + /** + * Paint. + * + * @param annotation the annotation + * @param gc the gc + * @param canvas the canvas + * @param bounds the bounds + */ + @Override + public void paint(Annotation annotation, GC gc, Canvas canvas, Rectangle bounds) { + Optional paintImage = Optional.empty(); + if (annotation instanceof AnnotationWithLineNumber) { + paintImage = ((AnnotationWithLineNumber) annotation).getImage(); + } + + if (paintImage.isPresent()) { + ImageUtilities.drawImage(paintImage.get(), gc, canvas, bounds, SWT.CENTER, SWT.CENTER); + } else { + super.paint(annotation, gc, canvas, bounds); + } + + } + + /** + * Checks if is paintable. + * + * @param annotation the annotation + * @return true, if is paintable + */ + @Override + public boolean isPaintable(Annotation annotation) { + if (annotation instanceof AnnotationWithLineNumber) { + return ((AnnotationWithLineNumber) annotation).getImage().isPresent(); + } + return super.isPaintable(annotation); + } + + /** + * Checks if is multi line. + * + * @param annotation the annotation + * @return true, if is multi line + */ + @Override + public boolean isMultiLine(Annotation annotation) { + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/PLSQLFormatter.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/PLSQLFormatter.java new file mode 100644 index 0000000000000000000000000000000000000000..392c634c34f8d11641fb8c85cde9ea4758ad8beb --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/PLSQLFormatter.java @@ -0,0 +1,426 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; + +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.SQLKeywords; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class PLSQLFormatter. + * + * @since 3.0.0 + */ +public class PLSQLFormatter { + private int beginCounter = 0; + + private static final int IGNORE_FULL_LINE = 1; + private static final int VALID_LINE = 2; + private static final int COMMENT_CLOSE_PENDING = 4; + + private static List indentSQLWords = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + private static List newSQLWords = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + private static List keywords = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + + static { + keywords.addAll(Arrays.asList(SQLKeywords.getRESERVEDWORDS())); + keywords.add("INSERT"); + keywords.add("DELETE"); + keywords.add("UPDATE"); + + indentSQLWords.add("begin"); + + newSQLWords.add("select"); + newSQLWords.add("insert"); + newSQLWords.add("update"); + newSQLWords.add("delete"); + newSQLWords.add("return"); + } + + /** + * Checks if is key word. + * + * @param currentKeyWord the current key word + * @return true, if is key word + */ + private boolean isKeyWord(String currentKeyWord) { + if (keywords.contains(currentKeyWord.toUpperCase(Locale.ENGLISH))) { + if (indentSQLWords.contains(currentKeyWord.toLowerCase(Locale.ENGLISH)) + || currentKeyWord.toLowerCase(Locale.ENGLISH).matches("end\\s*;*\\$$*") + || currentKeyWord.toLowerCase(Locale.ENGLISH).matches("end\\s*;*\\$function\\$*")) { + return false; + } + return true; + } + + return false; + } + + /** + * Format. + * + * @param input the input + * @return the string + */ + public String format(String input) { + + StringBuilder formattedQuery = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + + int cnt = 0; + int start = 0; + + int indention = 0; + String currentKeyword = null; + + int lastKeyLength = -1; + int minKeyStart = 0; + + String[] everyLine = input.replaceAll("\r\n", "\n").split("\n"); + int[] startln = new int[everyLine.length]; + int rule = 0; + boolean commentClosePending = false; + + int numSqlline = everyLine.length; + while (cnt < numSqlline) { + + currentKeyword = everyLine[cnt]; + everyLine[cnt] = currentKeyword = currentKeyword.replaceAll("^\\s+", ""); + + rule = identifyCommentingRule(currentKeyword, commentClosePending); + commentClosePending = isCommentPending(rule); + if (isIgnoreFullLine(rule)) { + start = getStartLength(cnt, start, indention, startln); + cnt++; + continue; + } + currentKeyword = findEndOfKeyWord(currentKeyword); + + if (indention != 0) { + startln[cnt] = start = indention; + lastKeyLength = getLastKeyLengthForKeyword(currentKeyword, lastKeyLength); + + } else if (isKeyWordIndentEnd(currentKeyword)) { + startln[cnt] = start = beginCounter * 4; + } else if (isNewSqlOrKeywordIndent(currentKeyword)) { + startln[cnt] = start = beginCounter * 4; + lastKeyLength = currentKeyword.length(); + } else if (isKeyWord(currentKeyword)) { + if (lastKeyLength == -1) { + minKeyStart = startln[cnt] = start; + } else { + startln[cnt] = start = start + (lastKeyLength - currentKeyword.length()); + minKeyStart = getMinKeyStart(start, minKeyStart); + } + lastKeyLength = currentKeyword.length(); + } else { + startln[cnt] = start; + } + + indention = getIndent(currentKeyword, indention); + + cnt++; + } + + getStartIn(formattedQuery, numSqlline, minKeyStart, everyLine, startln); + + return formattedQuery.toString(); + } + + private int getStartLength(int cnt, int start, int indention, int[] startln) { + if (indention != 0) { + startln[cnt] = start = indention; + } else { + startln[cnt] = start; + } + return start; + } + + private void getStartIn(StringBuilder formattedQuery, int numSqlline, int minKeyStart, String[] everyLine, + int[] startln) { + for (int index = 0; index < numSqlline; index++) { + startln[index] -= minKeyStart; + } + + concateSpaces(formattedQuery, numSqlline, everyLine, startln); + } + + private int getMinKeyStart(int start, int minKeyStartParam) { + int minKeyStart = minKeyStartParam; + if (start < minKeyStart) { + minKeyStart = start; + } + return minKeyStart; + } + + private int getLastKeyLengthForKeyword(String currentKeyword, int lastKeyLengthParam) { + int lastKeyLength = lastKeyLengthParam; + if (isKeyWord(currentKeyword)) { + lastKeyLength = currentKeyword.length(); + } + return lastKeyLength; + } + + /** + * Concate spaces. + * + * @param formattedQuery the formatted query + * @param numSqlline the num sqlline + * @param everyLine the every line + * @param startln the startln + * @return the int + */ + private int concateSpaces(StringBuilder formattedQuery, int numSqlline, String[] everyLine, int[] startln) { + int index; + String leadingSpaces = ""; + + for (index = 0; index < numSqlline; index++) { + leadingSpaces = ""; + for (int s = 0; s < startln[index]; s++) { + leadingSpaces = leadingSpaces.concat(" "); + } + + everyLine[index] = leadingSpaces.concat(everyLine[index]); + formattedQuery.append(everyLine[index]); + appendLineSeperator(formattedQuery, index, numSqlline); + } + return index; + } + + /** + * Checks if is ignore full line. + * + * @param rule the rule + * @return true, if is ignore full line + */ + private boolean isIgnoreFullLine(int rule) { + return IGNORE_FULL_LINE == (rule & IGNORE_FULL_LINE); + } + + /** + * Append line seperator. + * + * @param formattedQuery the formatted query + * @param index the i + * @param numSqlline the num sqlline + */ + private void appendLineSeperator(StringBuilder formattedQuery, int index, int numSqlline) { + if (index < numSqlline - 1) { + formattedQuery.append(MPPDBIDEConstants.LINE_SEPARATOR); + } + } + + /** + * Checks if is new sql or keyword indent. + * + * @param currentKeyword the current keyword + * @return true, if is new sql or keyword indent + */ + private boolean isNewSqlOrKeywordIndent(String currentKeyword) { + return isNewSql(currentKeyword) || isKeyWordIndent(currentKeyword); + } + + /** + * Checks if is comment pending. + * + * @param rule the rule + * @return true, if is comment pending + */ + private boolean isCommentPending(int rule) { + boolean commentClosePending = false; + if (COMMENT_CLOSE_PENDING == (rule & COMMENT_CLOSE_PENDING)) { + commentClosePending = true; + } else { + commentClosePending = false; + } + return commentClosePending; + } + + /** + * Find end of key word. + * + * @param currentKeyWordParam the current key word param + * @return the string + */ + private String findEndOfKeyWord(String currentKeyWordParam) { + String currentKeyWord = currentKeyWordParam; + int index = currentKeyWord.indexOf(' '); + if (currentKeyWord.toLowerCase(Locale.ENGLISH).matches("end loop[\\s*;*]")) { + MPPDBIDELoggerUtility.none("End loop encountered"); + } else if (currentKeyWord.toLowerCase(Locale.ENGLISH).matches("end if[\\s*;*]")) { + MPPDBIDELoggerUtility.none("End if encountered"); + } else if (-1 < index) { + currentKeyWord = currentKeyWord.substring(0, index); + } + return currentKeyWord; + } + + /** + * Identify commenting rule. + * + * @param currentKeyWord the current key word + * @param commentClosePending the comment close pending + * @return the int + */ + private int identifyCommentingRule(String currentKeyWord, boolean commentClosePending) { + int lastCommentStartPos = 0; + int lastCommentClosePos = 0; + int rule = 0; + + if (currentKeyWord.length() < 2) { + if (commentClosePending) { + return IGNORE_FULL_LINE | COMMENT_CLOSE_PENDING; + } + + return IGNORE_FULL_LINE; + } + + if (currentKeyWord.substring(0, 2).matches("--") || currentKeyWord.substring(0, 2).matches("//")) { + // because the line starts with single-line comment start characters + if (commentClosePending) { + return IGNORE_FULL_LINE | COMMENT_CLOSE_PENDING; + } + + return IGNORE_FULL_LINE; + } + + lastCommentStartPos = currentKeyWord.lastIndexOf("/*"); + if (-1 == lastCommentStartPos && !commentClosePending) { + return VALID_LINE; + } + + if (0 == lastCommentStartPos) { + // because the line starts with multi-line comment start characters + rule = IGNORE_FULL_LINE; + } else { + /* + * Two possibilities are possible: 1. The line is a valid line as no + * comment at the beginning. 2. Line part of the comment that was + * started earlier. + */ + if (commentClosePending) { + rule = IGNORE_FULL_LINE; + } else { + rule = VALID_LINE; + } + } + + // we need to check if there is any end multi line comment characters. + lastCommentClosePos = currentKeyWord.lastIndexOf("*/"); + + rule = checkForMultipleCommentEnd(commentClosePending, lastCommentStartPos, lastCommentClosePos, rule); + + return rule; + + } + + private int checkForMultipleCommentEnd(boolean commentClosePending, int lastCommentStartPos, + int lastCommentClosePos, int rule) { + if (-1 == lastCommentClosePos) { + /* + * We have no end comment characters. + */ + if (-1 == lastCommentStartPos) { + // we could not find both the start and end multi line comment + // characters. + if (commentClosePending) { + // we continue to say that end multi line is expected. + rule |= COMMENT_CLOSE_PENDING; + } + } else { + // we found start multi line comment, but no end multi line + // comment characters. + // we continue to say that end multi line is expected. + rule |= COMMENT_CLOSE_PENDING; + } + } else { + if (-1 == lastCommentStartPos) { + // may be some old comment is getting closed. + rule = IGNORE_FULL_LINE; + } else if (lastCommentClosePos < lastCommentStartPos) { + // cases like /* xxxxx */ abc /* + rule |= COMMENT_CLOSE_PENDING; + } + } + return rule; + } + + /** + * Checks if is key word indent. + * + * @param currentKeyWord the current key word + * @return true, if is key word indent + */ + private boolean isKeyWordIndent(String currentKeyWord) { + return indentSQLWords.contains(currentKeyWord.toLowerCase(Locale.ENGLISH)); + } + + /** + * Gets the indent. + * + * @param currentKeyWord the current key word + * @param currentIndentation the current indentation + * @return the indent + */ + private int getIndent(String currentKeyWord, int currentIndentation) { + if (indentSQLWords.contains(currentKeyWord.toLowerCase(Locale.ENGLISH))) { + beginCounter++; + return 4 * beginCounter; + } + return 0; + } + + /** + * Checks if is key word indent end. + * + * @param currentKeyWord the current key word + * @return true, if is key word indent end + */ + private boolean isKeyWordIndentEnd(String currentKeyWord) { + if (currentKeyWord.toLowerCase(Locale.ENGLISH).matches("end\\s*;*\\$*") + || currentKeyWord.toLowerCase(Locale.ENGLISH).matches("end\\s*;*\\$function\\$*")) { + if (!"end if;".equalsIgnoreCase(currentKeyWord) && !"end loop;".equalsIgnoreCase(currentKeyWord)) { + beginCounter--; + return true; + } + + } + + return false; + } + + /** + * Checks if is new sql. + * + * @param currentKeyWord the current key word + * @return true, if is new sql + */ + private boolean isNewSql(String currentKeyWord) { + if (newSQLWords.contains(currentKeyWord.toLowerCase(Locale.ENGLISH))) { + return true; + } + + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/PLSourceEditorCore.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/PLSourceEditorCore.java new file mode 100644 index 0000000000000000000000000000000000000000..b45bb730f3de1df20b62f77221f9c253725d4e05 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/PLSourceEditorCore.java @@ -0,0 +1,2535 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Locale; + +import javax.annotation.PreDestroy; + +import org.eclipse.core.commands.Command; +import org.eclipse.core.commands.ParameterizedCommand; +import org.eclipse.e4.core.commands.ECommandService; +import org.eclipse.e4.core.commands.EHandlerService; +import org.eclipse.e4.ui.workbench.modeling.ESelectionService; +import org.eclipse.jface.bindings.keys.KeyStroke; +import org.eclipse.jface.bindings.keys.ParseException; +import org.eclipse.jface.bindings.keys.SWTKeySupport; +import org.eclipse.jface.preference.PreferenceStore; +import org.eclipse.jface.resource.FontDescriptor; +import org.eclipse.jface.resource.JFaceResources; +import org.eclipse.jface.resource.LocalResourceManager; +import org.eclipse.jface.resource.ResourceManager; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.DocumentRewriteSession; +import org.eclipse.jface.text.DocumentRewriteSessionType; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IDocumentExtension2; +import org.eclipse.jface.text.IDocumentExtension3; +import org.eclipse.jface.text.IDocumentExtension4; +import org.eclipse.jface.text.IDocumentPartitioner; +import org.eclipse.jface.text.IFindReplaceTarget; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextListener; +import org.eclipse.jface.text.ITextOperationTarget; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.text.ITypedRegion; +import org.eclipse.jface.text.Region; +import org.eclipse.jface.text.TextEvent; +import org.eclipse.jface.text.TextSelection; +import org.eclipse.jface.text.TextUtilities; +import org.eclipse.jface.text.TextViewer; +import org.eclipse.jface.text.reconciler.IReconciler; +import org.eclipse.jface.text.source.Annotation; +import org.eclipse.jface.text.source.AnnotationModel; +import org.eclipse.jface.text.source.CompositeRuler; +import org.eclipse.jface.text.source.IAnnotationAccess; +import org.eclipse.jface.text.source.IOverviewRuler; +import org.eclipse.jface.text.source.ISharedTextColors; +import org.eclipse.jface.text.source.OverviewRuler; +import org.eclipse.jface.text.source.SourceViewer; +import org.eclipse.jface.text.source.projection.ProjectionAnnotation; +import org.eclipse.jface.text.source.projection.ProjectionAnnotationModel; +import org.eclipse.jface.text.source.projection.ProjectionSupport; +import org.eclipse.jface.text.source.projection.ProjectionViewer; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.LineBackgroundEvent; +import org.eclipse.swt.custom.LineBackgroundListener; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.custom.VerifyKeyListener; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.events.KeyListener; +import org.eclipse.swt.events.MouseAdapter; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.events.MouseListener; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.events.VerifyEvent; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.FontData; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.MenuItem; +import org.eclipse.swt.widgets.Widget; +import org.eclipse.ui.internal.editors.text.EditorsPlugin; +import org.eclipse.ui.texteditor.SourceViewerDecorationSupport; + +import org.opengauss.mppdbide.adapter.keywordssyntax.SQLSyntax; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.view.core.SelectMenuItem; +import org.opengauss.mppdbide.view.handler.debug.DebugHandlerUtils; +import org.opengauss.mppdbide.view.handler.debug.DebugServiceHelper; +import org.opengauss.mppdbide.view.prefernces.DSFormatterPreferencePage; +import org.opengauss.mppdbide.view.prefernces.FormatterPreferenceKeys; +import org.opengauss.mppdbide.view.prefernces.IAutoCompletePreference; +import org.opengauss.mppdbide.view.prefernces.KeyBindingWrapper; +import org.opengauss.mppdbide.view.prefernces.PreferenceWrapper; +import org.opengauss.mppdbide.view.ui.DBAssistantWindow; +import org.opengauss.mppdbide.view.ui.FindAndReplaceOptions; +import org.opengauss.mppdbide.view.ui.PLSourceEditor; +import org.opengauss.mppdbide.view.ui.terminal.SQLTerminal; +import org.opengauss.mppdbide.view.ui.terminal.SQLTerminalFormatterUIWorker; +import org.opengauss.mppdbide.view.uidisplay.UIDisplayFactoryProvider; +import org.opengauss.mppdbide.view.uidisplay.UIDisplayState; +import org.opengauss.mppdbide.view.uidisplay.uidisplayif.UIDisplayStateIf; +import org.opengauss.mppdbide.view.utils.IUserPreference; +import org.opengauss.mppdbide.view.utils.TerminalStatusBar; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs.MESSAGEDIALOGTYPE; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; +import org.opengauss.mppdbide.view.workerjob.UIWorkerJob; + +/** + * Title: class Description: The Class PLSourceEditorCore. + * + * @since 3.0.0 + */ +public final class PLSourceEditorCore extends SelectMenuItem implements IPropertyChangeListener { + private static final String FORMAT_COMMAND_ID = "org.opengauss.mppdbide.command.id.format"; + + private ECommandService commandService; + + private EHandlerService handlerService; + + private ESelectionService selectionService; + + private volatile SourceViewer viewer; + + private IAnnotationAccess fAnnotationAccess; + + private IDocument doc; + + private ArrayList jobsAssociatedToTerminal; + + /** + * The Constant ANNOTATION_RULER_WIDTH. + */ + public static final int ANNOTATION_RULER_WIDTH = 16; + + private SQLSourceViewerDecorationSupport fSourceViewerDecorationSupport; + + /** + * The Constant SPACE_BETWEEN_RULER. + */ + public static final int SPACE_BETWEEN_RULER = 1; + + /** + * The Constant SERVER_BREAKPOINT_LINE_OFFSET. + */ + public static final int SERVER_BREAKPOINT_LINE_OFFSET = 1; + + private SQLSourceViewerConfig config; + + private AnnotationModel fAnnotationModel; + + /** + * The exec progres bar. + */ + TerminalStatusBar execProgresBar; + + private Menu menu; + + private MenuItem menuCut; + + private MenuItem menuPaste; + + private MenuItem menuSQLCmd; + + private String sqlCmdMenuKey; + + private String sqlCmdMenuIcon; + + private FindAndReplaceOptions findAndReplaceoptions; + + private int lastSearchReturnIndex; + + private boolean atleastOneMatchFound; + + private String prevText = ""; + + private FindAndReplaceOptions options; + + private int counterForTxtInEditor = 0; + + private MenuItem toggleLineComments; + + private MenuItem toggleBlockComments; + + private MenuItem menuFormat; + + /** + * The Constant SL_COMMENT. + */ + public static final String SL_COMMENT = "--"; + + /** + * The Constant INDENT_OPERATION. + */ + public static final String INDENT_OPERATION = "indent"; + + /** + * The Constant UNINDENT_OPERATION. + */ + public static final String UNINDENT_OPERATION = "unindent"; + + private PreferenceStore preferenceStore; + + private boolean disableCommentIndentUndo; + + private SQLSyntax syntax; + + private Font font; + + private ResourceManager resManager; + + /** + * Title: enum Description: The Enum EDITORACTIONKEY. + */ + private enum EDITORACTIONKEY { + NOKEY, AUTO_SUGGEST, CODE_TEMPLATE, KEY_AUTO_SUGGEST, INSERT_AUTO_SUGGEST + }; + + private int highlightLineNum = -1; + + /** + * Instantiates a new PL source editor core. + * + * @param fAnnotationModel the f annotation model + * @param fAnnotationAccess the f annotation access + */ + + /** + * Default constructor will create the annotation model which doesn't need + * any component creation. + */ + public PLSourceEditorCore(AnnotationModel fAnnotationModel, IAnnotationAccess fAnnotationAccess) { + this.fAnnotationModel = fAnnotationModel; + this.fAnnotationAccess = fAnnotationAccess; + preferenceStore = PreferenceWrapper.getInstance().getPreferenceStore(); + preferenceStore.addPropertyChangeListener(this); + jobsAssociatedToTerminal = new ArrayList(5); + } + + /** + * Set highlight line num + * + * @param lineNum the highlight line num + */ + public void setHighlightLineNum (int lineNum) { + this.highlightLineNum = lineNum; + } + + /** + * Get highlight line num + * + * @return int the highlight line num + */ + public int getHighlightLineNum () { + return this.highlightLineNum; + } + + /** + * Creates the editor. + * + * @param parent the parent + * @param compositeRuler the composite ruler + * @param ruler the ruler + * @param syntx the syntx + * @param isSQLTerminal the is SQL terminal + */ + public void createEditor(Composite parent, CompositeRuler compositeRuler, OverviewRuler ruler, SQLSyntax syntx, + boolean isSQLTerminal) { + Composite viewerComposite = new Composite(parent, SWT.NONE); + viewerComposite.setLayout(new GridLayout(1, false)); + + // check is folding enabled + + boolean isFoldingEnabled = PreferenceWrapper.getInstance().getPreferenceStore() + .getBoolean("sqlterminal.folding"); + + if (isFoldingEnabled) { + ISharedTextColors sharedColors = EditorsPlugin.getDefault().getSharedTextColors(); + IOverviewRuler overviewRuler = new OverviewRuler(fAnnotationAccess, 12, sharedColors); + viewer = new ProjectionViewer(viewerComposite, compositeRuler, overviewRuler, true, + SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); + + } else { + viewer = new SourceViewer(viewerComposite, compositeRuler, ruler, ruler != null, + SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); + + } + + viewer.getTextWidget().setData(MPPDBIDEConstants.SWTBOT_KEY, "ID_TXT_SQLTERMINAL_TEXT_001"); + viewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + setDocument(new Document(""), 0); + + if (isFoldingEnabled && viewer instanceof ProjectionViewer) { + ProjectionSupport projectionSupport = new ProjectionSupport((ProjectionViewer) viewer, fAnnotationAccess, + getSharedColors()); + projectionSupport.install(); + + // turn projection mode on + viewer.doOperation(ProjectionViewer.TOGGLE); + } + + resManager = new LocalResourceManager(JFaceResources.getResources(), viewerComposite); + font = resManager.createFont(FontDescriptor.createFrom("Courier New", + preferenceStore.getInt(MPPDBIDEConstants.PREF_FONT_STYLE_SIZE), SWT.NORMAL)); + + viewer.getTextWidget().setFont(font); + + setDecoration(); + + menu = new Menu(getControl()); + viewer.getTextWidget().setMenu(menu); + addCutMenuItem(menu); + addCopyMenuItem(menu); + addPasteMenuItem(menu); + addSelectAllMenuItem(menu); + addToggleLineCommentMenuItem(menu); + addToggleBlockCommentMenuItem(menu); + addFormatMenuItem(menu); + addExecStmtMenuItem(menu); + + this.config = new SQLSourceViewerConfig(syntx); + setTabStrategy(); + + viewer.configure(this.config); + + this.execProgresBar = createStatusBar(viewerComposite, isSQLTerminal); + + addListners(); + } + + /** + * Gets the shared colors. + * + * @return the shared colors + */ + protected ISharedTextColors getSharedColors() { + return EditorsPlugin.getDefault().getSharedTextColors(); + } + + /** + * Creates the status bar. + * + * @param gridComposite the grid composite + * @param isTerminal the is terminal + * @return the terminal status bar + */ + private TerminalStatusBar createStatusBar(Composite gridComposite, boolean isTerminal) { + TerminalStatusBar statusBar = null; + TerminalStatusBar prevStatusBar = UIDisplayState.getInstaDisplayState().getPrevStatusBar(); + boolean useOldTimerObject = UIDisplayState.getInstaDisplayState().isDebugInProgresOnNewEditor() + && prevStatusBar != null; + if (useOldTimerObject) { + statusBar = new TerminalStatusBar(prevStatusBar); + } else { + statusBar = new TerminalStatusBar(); + } + statusBar.setHandlerServices(commandService, handlerService); + statusBar.createStatusGrid(gridComposite, isTerminal); + if (useOldTimerObject) { + statusBar.justShowBar(); + UIDisplayState.getInstaDisplayState().setDebugInProgresNewEd(false); + } + return statusBar; + } + + /** + * Gets the exec status bar. + * + * @return the exec status bar + */ + public TerminalStatusBar getExecStatusBar() { + return this.execProgresBar; + } + + /** + * Show exec progress bar. + */ + public void showExecProgressBar() { + this.execProgresBar.showProgresBar(); + } + + /** + * Hide exec progress bar. + */ + public void hideExecProgressBar() { + if (null != this.execProgresBar) { + this.execProgresBar.hideProgresBar(); + } + } + + /** + * Sets the tab strategy. + */ + private void setTabStrategy() { + String[] types = config.getConfiguredContentTypes(viewer); + config.setUpdatedPrefixes(viewer); + configurePrefixesForEachContentType(types); + } + + /** + * Update SQL configurations on DB connect. + * + * @param db the db + */ + public void updateSQLConfigurationsOnDBConnect(Database db) { + Display.getDefault().syncExec(new Runnable() { + @Override + public void run() { + SQLSyntax sytx = null; + if (db != null && db.isConnected()) { + sytx = db.getSqlSyntax(); + if (viewer != null) { + SQLSourceViewerConfig configuration = reconfigureSourceViewerConfig(sytx); + configuration.setDatabase(db); + } + } else { + reconfigureSourceViewerConfig(sytx).setDatabase(db); + } + } + }); + } + + /** + * Reconfigure source viewer config. + * + * @param sytx the sytx + * @return the SQL source viewer config + */ + private SQLSourceViewerConfig reconfigureSourceViewerConfig(SQLSyntax sytx) { + this.viewer.unconfigure(); + SQLSourceViewerConfig configuration = new SQLSourceViewerConfig(sytx); + this.viewer.configure(configuration); + return configuration; + } + + /** + * Sets the command and handler service. + * + * @param commandServce the command servce + * @param handlerServce the handler servce + * @param selectionServce the selection servce + */ + public void setCommandAndHandlerService(ECommandService commandServce, EHandlerService handlerServce, + ESelectionService selectionServce) { + this.commandService = commandServce; + this.handlerService = handlerServce; + this.selectionService = selectionServce; + } + + /** + * Gets the menu. + * + * @return the menu + */ + public Menu getMenu() { + return menu; + } + + /** + * Sets the sql cmd menu key. + * + * @param sqlCmdMenuKey the new sql cmd menu key + */ + public void setSqlCmdMenuKey(String sqlCmdMenuKey) { + this.sqlCmdMenuKey = sqlCmdMenuKey; + } + + /** + * Sets the sql cmd menu icon. + * + * @param sqlCmdMenuIcon the new sql cmd menu icon + */ + public void setSqlCmdMenuIcon(String sqlCmdMenuIcon) { + this.sqlCmdMenuIcon = sqlCmdMenuIcon; + } + + /** + * Gets the find and replaceoptions. + * + * @return the find and replaceoptions + */ + public FindAndReplaceOptions getFindAndReplaceoptions() { + return findAndReplaceoptions; + } + + /** + * Sets the find and replaceoptions. + * + * @param optins the new find and replaceoptions + */ + public void setFindAndReplaceoptions(FindAndReplaceOptions optins) { + this.findAndReplaceoptions = optins; + } + + /** + * Gets the control. + * + * @return the control + */ + public Control getControl() { + Control srcContrl = viewer.getControl(); + if (srcContrl instanceof Composite) { + Composite cmpst = (Composite) srcContrl; + Control[] childControls = cmpst.getChildren(); + Control childControl = null; + for (int count = 0; count < childControls.length; count++) { + childControl = childControls[count]; + if (childControl instanceof StyledText) { + srcContrl = childControl; + break; + } + } + } + + return srcContrl; + } + + /** + * Create decoration (line highlighting, breakpoint line hightlighting etc). + */ + private void setDecoration() { + + ISharedTextColors sharedColors = EditorsPlugin.getDefault().getSharedTextColors(); + fSourceViewerDecorationSupport = new SQLSourceViewerDecorationSupport(viewer, null, fAnnotationAccess, + sharedColors); + fSourceViewerDecorationSupport.installDecorations(); + + } + + /** + * Gets the f source viewer decoration support. + * + * @return the f source viewer decoration support + */ + public SourceViewerDecorationSupport getfSourceViewerDecorationSupport() { + return fSourceViewerDecorationSupport; + } + + /** + * Install decoration support. + */ + public void installDecorationSupport() { + + fSourceViewerDecorationSupport.setCursorLinePainterPreferenceKeys(IUserPreference.CURRENT_LINE_VISIBILITY, + IUserPreference.CURRENTLINE_COLOR); + } + + /** + * Sets the document. + * + * @param document the new document + * @param fileSizeInMB the file size in MB + */ + public void setDocument(final IDocument document, double fileSizeInMB) { + if (null != this.doc) { + fAnnotationModel.removeAllAnnotations(); + } + + if (viewer.getDocument() != null) { + IDocumentPartitioner docPartitioner = ((IDocumentExtension3) viewer.getDocument()) + .getDocumentPartitioner(SQLPartitionScanner.SQL_PARTITIONING); + if (docPartitioner != null) { + docPartitioner.disconnect(); + } + } + this.doc = document; + viewer.setDocument(document, fAnnotationModel); + SQLDocumentPartitioner.connectDocument(document, fileSizeInMB); + MPPDBIDELoggerUtility.debug("GUI: PLSourceEditorCore: Display source."); + } + + /** + * Load SQL data. + * + * @param newData the new data + * @param caretOffset the caret offset + * @param replaceoffSet the replaceoff set + */ + public void loadSQLData(String newData, int caretOffset, int replaceoffSet, double fileSizeInMB) { + // Shift caret before start of the loaded data + fAnnotationModel.removeAllAnnotations(); + if (!(viewer.getDocument() instanceof IDocumentExtension3)) { + return; + } + IDocumentPartitioner documentPartitioner = ((IDocumentExtension3) viewer.getDocument()) + .getDocumentPartitioner(SQLPartitionScanner.SQL_PARTITIONING); + if (null != documentPartitioner) { + documentPartitioner.disconnect(); + } + try { + + viewer.getDocument().replace(replaceoffSet, 0, newData); + + } catch (BadLocationException exception) { + MPPDBIDELoggerUtility.error("Error while loading SQL data", exception); + } + + viewer.getTextWidget().setCaretOffset(caretOffset); + viewer.revealRange(caretOffset, 1); + + SQLDocumentPartitioner.connectDocument(viewer.getDocument(), fileSizeInMB); + } + + /** + * Destroy document. + */ + public void destroyDocument() { + this.doc = null; + } + + /** + * Sets the editable. + * + * @param isEditable the new editable + */ + public void setEditable(final boolean isEditable) { + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + viewer.setEditable(isEditable); + } + }); + } + + /** + * Goto line. + * + * @param line the line + * @param db the db + */ + public void gotoLine(int line, Database db) { + if (null == doc) { + return; + } + + int lineOffset = line - SERVER_BREAKPOINT_LINE_OFFSET; + try { + int start = doc.getLineOffset(lineOffset); + int length = doc.getLineLength(lineOffset); + viewer.getTextWidget().setSelection(start); + viewer.revealRange(start, length); + } catch (BadLocationException e) { + UIDisplayStateIf displayState = UIDisplayFactoryProvider.getUIDisplayStateIf(); + } + } + + /** + * Go to line number. + * + * @param line the line + */ + public void goToLineNumber(int line) { + if (null == doc) { + return; + } + + int lineOffset = line - MPPDBIDEConstants.LINE_NUMBER_OFFSET; + try { + int start = doc.getLineOffset(lineOffset); + int length = doc.getLineLength(lineOffset); + viewer.revealRange(start, length); + if (viewer instanceof ProjectionViewer) { + ProjectionViewer projectionViewer = (ProjectionViewer)viewer; + projectionViewer.getProjectionAnnotationModel().expandAll(start, length); + } + viewer.setSelectedRange(start, 0); + + } catch (BadLocationException exception) { + MPPDBIDELoggerUtility.error("Error getting Line number", exception); + + } + + } + + /** + * Gets the source viewer. + * + * @return the source viewer + */ + public SourceViewer getSourceViewer() { + return viewer; + } + + /** + * Gets the editor action keys. + * + * @param event the event + * @return the editor action keys + */ + private EDITORACTIONKEY getEditorActionKeys(KeyEvent event) { + try { + KeyStroke actualKeyStroke = SWTKeySupport + .convertAcceleratorToKeyStroke(SWTKeySupport.convertEventToUnmodifiedAccelerator(event)); + + if (KeyStroke.getInstance(KeyBindingWrapper.getInstance().getAutoSugestKey()).equals(actualKeyStroke)) { + return EDITORACTIONKEY.AUTO_SUGGEST; + } else if (KeyStroke.getInstance(KeyBindingWrapper.getInstance().getCodeTemplateKey()) + .equals(actualKeyStroke)) { + return EDITORACTIONKEY.CODE_TEMPLATE; + } else if (KeyStroke.getInstance("SHIFT+9").equals(actualKeyStroke) + || KeyStroke.getInstance(",").equals(actualKeyStroke)) { + return EDITORACTIONKEY.INSERT_AUTO_SUGGEST; + } else if (!(actualKeyStroke.toString().contains("CTRL") || actualKeyStroke.toString().contains("ALT"))) { + + return EDITORACTIONKEY.KEY_AUTO_SUGGEST; + } + } catch (ParseException exception) { + MPPDBIDELoggerUtility.error("Parse exception while getting key stroke", exception); + } + + return EDITORACTIONKEY.NOKEY; + } + + /** + * Add listener to the current source editor control. + */ + private void addListners() { + /* + * Adding a selection change listener and postSelection change listener + * for mars eclipse environment when the UPPERCASE and LOWERCASE and + * other commands and their handler could be executed + */ + viewer.addPostSelectionChangedListener(new PostEditorSelectionChangedListener()); + viewer.addSelectionChangedListener(new EditorSelectionChangedListener()); + viewer.appendVerifyKeyListener(appendViewerVerifyKeyListener()); + viewer.getTextWidget().addKeyListener(addViewerKeyListener()); + viewer.getTextWidget().addMouseListener(new MouseAdapter() { + @Override + public void mouseDown(MouseEvent e) { + cancelHighlight(); + } + }); + viewer.getTextWidget().addVerifyKeyListener(new VerifyKeyListener() { + @Override + public void verifyKey(VerifyEvent event) { + + if (event.keyCode != SWT.TAB) { + + return; + } + + if (event.stateMask == SWT.SHIFT) { + performIndentUnindentOperation(UNINDENT_OPERATION, event); + } else { + performIndentUnindentOperation(INDENT_OPERATION, event); + } + + } + + }); + + viewer.addTextListener(new ITextListener() { + @Override + public void textChanged(TextEvent event) { + if (!disableCommentIndentUndo) { + DBAssistantWindow.toggleCurrentAssitant(false); + } + } + }); + } + + private void cancelHighlight () { + int lineNum = getHighlightLineNum(); + if (lineNum != -1) { + DebugServiceHelper.getInstance().notifyCancelHighlight(lineNum); + } + } + + private KeyListener addViewerKeyListener() { + return new KeyListener() { + + @Override + public void keyPressed(KeyEvent e) { + + } + + @Override + public void keyReleased(KeyEvent event) { + viewer.setData("ISALIASCHECK", false); + + EDITORACTIONKEY action = getEditorActionKeys(event); + + if (event.character == '(' || event.character == ',') { + if (viewer.canDoOperation(SourceViewer.CONTENTASSIST_PROPOSALS)) { + viewer.doOperation(SourceViewer.CONTENTASSIST_PROPOSALS); + } + return; + } + + if ((EDITORACTIONKEY.KEY_AUTO_SUGGEST == action) && (event.keyCode > 32 && event.keyCode <= 126) + || event.keyCode == 0) { + Widget widget = event.widget; + StyledText text = (StyledText) widget; + String prefix = getPrefixForAutoSuggest(text); + + if (prefix != null && prefix.length() >= PreferenceWrapper.getInstance().getPreferenceStore() + .getInt(IAutoCompletePreference.AUTO_COMPLETE_PREFERENCE_KEY)) { + if (event.keyCode == 46) { + viewer.setData("ISALIASCHECK", true); + } + if (viewer.canDoOperation(SourceViewer.CONTENTASSIST_PROPOSALS)) { + viewer.doOperation(SourceViewer.CONTENTASSIST_PROPOSALS); + + return; + } + } + } + + } + + }; + } + + private VerifyKeyListener appendViewerVerifyKeyListener() { + return new VerifyKeyListener() { + @Override + public void verifyKey(VerifyEvent event) { + viewer.setData("ISALIASCHECK", false); + EDITORACTIONKEY action = getEditorActionKeys(event); + + if (EDITORACTIONKEY.CODE_TEMPLATE == action) { + if (viewer.canDoOperation(SourceViewer.CONTENTASSIST_CONTEXT_INFORMATION)) { + viewer.doOperation(SourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); + } + event.doit = false; + return; + } + + if (EDITORACTIONKEY.AUTO_SUGGEST == action) { + if (viewer.canDoOperation(SourceViewer.CONTENTASSIST_PROPOSALS)) { + viewer.setData("ISALIASCHECK", true); + viewer.doOperation(SourceViewer.CONTENTASSIST_PROPOSALS); + } + event.doit = false; + return; + } + + } + }; + } + + private String getPrefixForAutoSuggest(StyledText text) { + boolean isContinue = true; + int offset = text.getCaretOffset() == 0 ? 0 : text.getCaretOffset() - 1; + char ch = '\0'; + while (isContinue && offset > 0) { + try { + + ch = viewer.getDocument().getChar(offset); + + if (Character.isWhitespace(ch)) { + break; + } + offset--; + } catch (BadLocationException exception) { + MPPDBIDELoggerUtility.error("Error while getting prefix for auto suggest", exception); + } + } + + String prefix = null; + try { + if (text.getCaretOffset() > 0) { + prefix = viewer.getDocument().get(offset, text.getCaretOffset() - offset); + prefix = prefix.trim(); + } + } catch (BadLocationException exception) { + MPPDBIDELoggerUtility.error("Error while getting prefix for auto suggest", exception); + } + return prefix; + } + + /** + * Enable toggle current assist. + */ + private void enableToggleCurrentAssist() { + disableCommentIndentUndo = false; + } + + /** + * Disable toggle current assist. + */ + private void disableToggleCurrentAssist() { + disableCommentIndentUndo = true; + } + + /** + * Perform indent unindent operation. + * + * @param operation the operation + * @param event the event + */ + public void performIndentUnindentOperation(String operation, VerifyEvent event) { + try { + disableToggleCurrentAssist(); + IDocumentExtension2 extension = (IDocumentExtension2) doc; + extension.ignorePostNotificationReplaces(); + if (event != null) { + handleVerifyEvent(operation, event); + } else { + handleNullEvent(operation); + } + + extension.acceptPostNotificationReplaces(); + } catch (OutOfMemoryError e) { + displayErrorDialog(); + } finally { + enableToggleCurrentAssist(); + } + } + + private void handleNullEvent(String operation) { + if (operation.equals(INDENT_OPERATION)) { + ITextSelection textSelection = (ITextSelection) viewer.getSelection(); + if (textSelection.getLength() > 0) { + performShiftOperation(); + } + } else if (operation.equals(UNINDENT_OPERATION)) { + performShiftLeft(); + } + } + + private void handleVerifyEvent(String operation, VerifyEvent event) { + if (operation.equals(INDENT_OPERATION)) { + ITextSelection textSelection = (ITextSelection) viewer.getSelection(); + if (textSelection.getLength() > 0 + && (textSelection.getText() != null && textSelection.getText().contains("\n"))) { + performShiftOperation(); + event.doit = false; + } else if (DSFormatterPreferencePage.isTabToSpaceEnabled()) { + insertSpacesOnIndentForSingleLine(); + event.doit = false; + } + } else if (operation.equals(UNINDENT_OPERATION)) { + performShiftLeft(); + event.doit = false; + } + } + + /** + * Gets the selected line count. + * + * @return the selected line count + */ + public boolean getSelectedLineCount() { + ITextSelection selection = (ITextSelection) viewer.getSelection(); + String text = selection.getText(); + /* + * Issue: Unable to perform Indent/Unindent for the single line selected + * Query Code change:Condition now checks for single line also. if + * nothing is selected,buttons are not enabled + */ + + if ((selection.getEndLine() - selection.getStartLine() >= 0) && (text != null && !text.isEmpty())) { + return true; + } else { + if (text != null && text.endsWith("\n")) { + return true; + } else { + return false; + } + } + } + + /** + * Perform shift operation. + */ + public void performShiftOperation() { + reconcilerUninstall(); + viewer.doOperation(ITextOperationTarget.SHIFT_RIGHT); + reconcilerInstall(); + } + + /** + * Insert spaces on indent for single line. + */ + private void insertSpacesOnIndentForSingleLine() { + ITextSelection selection = (ITextSelection) viewer.getSelection(); + try { + String spacesString = DSFormatterPreferencePage.getStringWithSpaces(); + doc.replace(selection.getOffset(), selection.getLength(), spacesString); + viewer.getTextWidget().setCaretOffset(selection.getOffset() + spacesString.length()); + viewer.revealRange(viewer.getTextWidget().getCaretOffset(), 1); + } catch (BadLocationException exception) { + MPPDBIDELoggerUtility.error("PLSourceEditorCore: BadLocationException occurred.", exception); + } + } + + /** + * The listener interface for receiving editorSelectionChanged events. The + * class that is interested in processing a editorSelectionChanged event + * implements this interface, and the object created with that class is + * registered with a component using the component's + * addEditorSelectionChangedListener method. When the + * editorSelectionChanged event occurs, that object's appropriate method is + * invoked. EditorSelectionChangedEvent + */ + private class EditorSelectionChangedListener implements ISelectionChangedListener { + @Override + public void selectionChanged(SelectionChangedEvent event) { + ISelection selection = event.getSelection(); + selectionService.setSelection(selection); + + String selectionStr = ((TextSelection) selection).getText(); + if ((null != selectionStr) && !"".equals(selectionStr.trim())) { + DBAssistantWindow.execSQL(selectionStr); + } + } + } + + /** + * The listener interface for receiving postEditorSelectionChanged events. + * The class that is interested in processing a postEditorSelectionChanged + * event implements this interface, and the object created with that class + * is registered with a component using the component's + * addPostEditorSelectionChangedListener method. When the + * postEditorSelectionChanged event occurs, that object's appropriate method + * is invoked. PostEditorSelectionChangedEvent + */ + private class PostEditorSelectionChangedListener implements ISelectionChangedListener { + @Override + public void selectionChanged(SelectionChangedEvent event) { + ISelection selection = event.getSelection(); + selectionService.setSelection(selection); + } + } + + /** + * Gets the document. + * + * @return the document + */ + public IDocument getDocument() { + return doc; + } + + /** + * Gets the source viewer line of offset. + * + * @param offset the offset + * @return the source viewer line of offset + * @throws BadLocationException the bad location exception + */ + public int getsourceViewerLineOfOffset(int offset) throws BadLocationException { + return viewer.getDocument().getLineOfOffset(offset); + } + + /** + * Gets the selection count. + * + * @return the selection count + */ + public int getSelectionCount() { + return viewer.getTextWidget().getSelectionCount(); + } + + /** + * Lock source viewer redraw. + */ + public void lockSourceViewerRedraw() { + this.viewer.setRedraw(false); + } + + /** + * Unlock source viewer redraw. + */ + public void unlockSourceViewerRedraw() { + this.viewer.setRedraw(true); + } + + /** + * Select all doc text. + */ + public void selectAllDocText() { + viewer.doOperation(ITextOperationTarget.SELECT_ALL); + } + + /** + * Cut selected doc text. + */ + public void cutSelectedDocText() { + viewer.doOperation(ITextOperationTarget.CUT); + } + + /** + * Copy doc text. + */ + public void copyDocText() { + try { + LineBackgroundListener lineBackgroundListener = getLineBackgroundColorListener(); + /* + * To avoid copying of Blue background color override it with + * background color listener + */ + StyledText styledText = (StyledText) viewer.getTextWidget(); + styledText.addLineBackgroundListener(lineBackgroundListener); + viewer.doOperation(ITextOperationTarget.COPY); + // Remove background color listener so UI screen will get blue + // background selection. + styledText.removeLineBackgroundListener(lineBackgroundListener); + } catch (OutOfMemoryError e) { + MPPDBIDEDialogs.generateOKMessageDialogInUI(MESSAGEDIALOGTYPE.ERROR, true, + MessageConfigLoader.getProperty(IMessagesConstants.TITLE_OUT_OF_MEMORY), e.getMessage()); + } + + } + + /** + * Gets the line background color listener. + * + * @return the line background color listener + */ + public static LineBackgroundListener getLineBackgroundColorListener() { + return new LineBackgroundListener() { + @Override + public void lineGetBackground(LineBackgroundEvent event) { + event.lineBackground = SQLSyntaxColorProvider.BACKGROUND_COLOR; + } + }; + } + + /** + * Paste selected doc text. + */ + public void pasteSelectedDocText() { + viewer.doOperation(ITextOperationTarget.PASTE); + } + + /** + * Can undo. + * + * @return true, if successful + */ + public boolean canUndo() { + return viewer.canDoOperation(ITextOperationTarget.UNDO); + } + + /** + * Can redo. + * + * @return true, if successful + */ + public boolean canRedo() { + return viewer.canDoOperation(ITextOperationTarget.REDO); + } + + /** + * Undo. + */ + public void undo() { + + reconcilerUninstall(); + + disableToggleCurrentAssist(); + viewer.doOperation(ITextOperationTarget.UNDO); + postToggleLineComment(); + + } + + /** + * Redo. + */ + public void redo() { + + reconcilerUninstall(); + + disableToggleCurrentAssist(); + viewer.doOperation(ITextOperationTarget.REDO); + postToggleLineComment(); + + } + + private void reconcilerUninstall() { + + IReconciler reconciler = getReconciler(); + + if (null != reconciler) { + reconciler.uninstall(); + } + + } + + private void reconcilerInstall() { + + IReconciler reconciler = getReconciler(); + + if (null != reconciler) { + reconciler.install(viewer); + } + + } + + private IReconciler getReconciler() { + Object sqlStrategy = viewer.getTextWidget().getData(SQLFoldingConstants.MONORECONCILER); + + IReconciler reconciler = null; + if (sqlStrategy instanceof IReconciler) { + reconciler = (IReconciler) sqlStrategy; + } + return reconciler; + } + + /** + * Sets the database. + * + * @param database the new database + */ + public void setDatabase(Database database) { + if (null != database) { + this.config.setDatabase(database); + } + } + + /** + * Adds the cut menu item. + * + * @param menuItem the menu item + */ + private void addCutMenuItem(Menu menuItem) { + menuCut = new MenuItem(menuItem, SWT.PUSH); + menuCut.setText(MessageConfigLoader.getProperty(IMessagesConstants.STATUS_MSG_PLVIEWER_OPTION_CUT)); + menuCut.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent event) { + cutSelectedDocText(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent event) { + + } + }); + menuCut.setImage(IconUtility.getIconImage(IiconPath.ICO_CUT, this.getClass())); + } + + /** + * Adds the paste menu item. + * + * @param menuItem the menu item + */ + private void addPasteMenuItem(Menu menuItem) { + menuPaste = new MenuItem(menuItem, SWT.PUSH); + menuPaste.setText(MessageConfigLoader.getProperty(IMessagesConstants.STATUS_MSG_PLVIEWER_OPTION_PASTE)); + menuPaste.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent event) { + pasteSelectedDocText(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent event) { + + } + }); + menuPaste.setImage(IconUtility.getIconImage(IiconPath.ICO_PASTE, this.getClass())); + } + + /** + * Adds the exec stmt menu item. + * + * @param menuItem the menu item + */ + private void addExecStmtMenuItem(Menu menuItem) { + menuSQLCmd = new MenuItem(menuItem, SWT.PUSH); + + menuSQLCmd.setText(MessageConfigLoader.getProperty(this.sqlCmdMenuKey)); + + menuSQLCmd.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent event) { + Command command = commandService + .getCommand("org.opengauss.mppdbide.command.id.executeobjectbrowseritemfromtoolbar"); + ParameterizedCommand parameterizedCommand = ParameterizedCommand.generateCommand(command, null); + handlerService.executeHandler(parameterizedCommand); + } + + @Override + public void widgetDefaultSelected(SelectionEvent event) { + + } + }); + menuSQLCmd.setImage(IconUtility.getIconImage(sqlCmdMenuIcon, this.getClass())); + + } + + /** + * Adds the toggle line comment menu item. + * + * @param menuItem the menu item + */ + private void addToggleLineCommentMenuItem(Menu menuItem) { + toggleLineComments = new MenuItem(menuItem, SWT.PUSH); + toggleLineComments.setText(MessageConfigLoader + .getProperty(IMessagesConstants.PREFERENCE_SHORTCUT_KEY_BINDING_TOGGLE_LINE_COMMENTS)); + toggleLineComments.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent event) { + Command cmd = commandService.getCommand("org.opengauss.mppdbide.view.command.ToggleLineComment"); + ParameterizedCommand parameterizedCmd = new ParameterizedCommand(cmd, null); + handlerService.executeHandler(parameterizedCmd); + } + + @Override + public void widgetDefaultSelected(SelectionEvent event) { + + } + }); + toggleLineComments.setImage(IconUtility.getIconImage(IiconPath.ICON_TOGGLE_LINE_COMMENTS, this.getClass())); + } + + /** + * Adds the toggle block comment menu item. + * + * @param menuItem the menu item + */ + private void addToggleBlockCommentMenuItem(Menu menuItem) { + toggleBlockComments = new MenuItem(menuItem, SWT.PUSH); + toggleBlockComments.setText(MessageConfigLoader + .getProperty(IMessagesConstants.PREFERENCE_SHORTCUT_KEY_BINDING_TOGGLE_BLOCK_COMMENTS)); + toggleBlockComments.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent event) { + Command cmd = commandService.getCommand("org.opengauss.mppdbide.view.command.ToggleBlockComment"); + ParameterizedCommand parameterizedCmd = new ParameterizedCommand(cmd, null); + handlerService.executeHandler(parameterizedCmd); + } + + @Override + public void widgetDefaultSelected(SelectionEvent event) { + + } + }); + toggleBlockComments.setImage(IconUtility.getIconImage(IiconPath.ICON_TOGGLE_BLOCK_COMMENTS, this.getClass())); + } + + /** + * Adds the format menu item. + * + * @param menu the menu + */ + private void addFormatMenuItem(Menu menu) { + menuFormat = new MenuItem(menu, SWT.PUSH); + menuFormat + .setText(MessageConfigLoader.getProperty(IMessagesConstants.SQL_TERMINAL_RIGHT_CLICK_MENU_ITEM_FORMAT)); + menuFormat.setImage( + IconUtility.getIconImage(IiconPath.ICON_SQL_TERMINAL_RIGHT_CLICK_MENU_FORMAT, this.getClass())); + menuFormat.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent e) { + Command cmd = commandService.getCommand(FORMAT_COMMAND_ID); + ParameterizedCommand parameterizedCmd = new ParameterizedCommand(cmd, null); + handlerService.executeHandler(parameterizedCmd); + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + } + }); + } + + /** + * Toggle cut copy select all. + * + * @param toggelCut the toggel cut + * @param toggelCopy the toggel copy + * @param toggelSelectAll the toggel select all + * @param toggleCompile the toggle compile + * @param togglePaste the toggle paste + */ + public void toggleCutCopySelectAll(boolean toggelCut, boolean toggelCopy, boolean toggelSelectAll, + boolean toggleCompile, boolean togglePaste) { + menuCut.setEnabled(toggelCut); + menuPaste.setEnabled(togglePaste); + getMenuCopy().setEnabled(toggelCopy); + getMenuSelectAll().setEnabled(toggelSelectAll); + menuSQLCmd.setEnabled(toggleCompile); + menuFormatEnableDisable(); + } + + private void menuFormatEnableDisable() { + ParameterizedCommand parameterizedCmd = new ParameterizedCommand(commandService.getCommand(FORMAT_COMMAND_ID), + null); + boolean canFormat = handlerService.canExecute(parameterizedCmd); + menuFormat.setEnabled(canFormat); + } + + /** + * Gets the menu SQL cmd. + * + * @return the menu SQL cmd + */ + public MenuItem getMenuSQLCmd() { + return menuSQLCmd; + } + + /** + * Sets the menu SQL cmd. + * + * @param menuSQLCmd the new menu SQL cmd + */ + public void setMenuSQLCmd(MenuItem menuSQLCmd) { + this.menuSQLCmd = menuSQLCmd; + } + + /** + * Sets the selected query. + * + * @param query the new selected query + */ + public void setSelectedQuery(String query) { + int offset = viewer.getTextWidget().getCaretOffset(); + + StringBuilder txt = new StringBuilder(viewer.getTextWidget().getText()); + + txt.insert(offset, query); + + viewer.getDocument().set(txt.toString()); + viewer.getTextWidget().setCaretOffset(offset + query.length()); + } + + /** + * Find text. + * + * @param isReplace the is replace + */ + public void findText(boolean isReplace) { + + lastSearchReturnIndex = 0; + options = getFindAndReplaceoptions(); + IFindReplaceTarget findReplaceTarget = viewer.getFindReplaceTarget(); + + if ((!options.isCaseSensitive() && !prevText.equalsIgnoreCase(options.getSearchText())) + || (options.isCaseSensitive() && !prevText.equals(options.getSearchText()))) { + atleastOneMatchFound = false; + prevText = options.getSearchText(); + if (counterForTxtInEditor > 0) { + counterForTxtInEditor--; + } + + } + + int searchStartPosition = getSearchStartPosition(options.isForwardSearch()); + + lastSearchReturnIndex = findReplaceTarget.findAndSelect(searchStartPosition, options.getSearchText(), + options.isForwardSearch(), options.isCaseSensitive(), options.isWholeWord()); + + if (lastSearchReturnIndex > -1 && null != options.getReplaceText() && isReplace) { + findReplaceTarget.replaceSelection(options.getReplaceText()); + } + + findTextPart1(searchStartPosition); + + findTextPart2(findReplaceTarget, isReplace); + } + + /** + * Find text part 1. + * + * @param searchStartPosition the search start position + */ + private void findTextPart1(int searchStartPosition) { + if ((lastSearchReturnIndex > -1) && !atleastOneMatchFound) { + counterForTxtInEditor++; + atleastOneMatchFound = true; + } + if (options.isWholeWord() && lastSearchReturnIndex == -1 && !options.isWrapAround()) { + + if ((prevText.equals(options.getSearchText()) && counterForTxtInEditor > 0) || searchStartPosition == 0) { + atleastOneMatchFound = true; + + } else { + atleastOneMatchFound = false; + } + } + } + + /** + * Find text part 2. + * + * @param findReplaceTarget the find replace target + * @param isReplace the is replace + */ + private void findTextPart2(IFindReplaceTarget findReplaceTarget, boolean isReplace) { + if (isWholeWordMatch()) { + handleWholeWordMatch(findReplaceTarget, isReplace); + } else if (isAlteastOneWordMatch()) { + handleAtleastOneWordMatch(findReplaceTarget, isReplace); + } else { + searchTextNotFoundDialog(); + } + } + + private void handleAtleastOneWordMatch(IFindReplaceTarget findReplaceTarget, boolean isReplace) { + int searchStartPosition = 0; + if (-1 == lastSearchReturnIndex && options.isWrapAround()) { + searchStartPosition = getSearchStartPosition(options.isForwardSearch()); + lastSearchReturnIndex = findReplaceTarget.findAndSelect(searchStartPosition, options.getSearchText(), + options.isForwardSearch(), options.isCaseSensitive(), options.isWholeWord()); + if (lastSearchReturnIndex > -1 && null != options.getReplaceText() && isReplace) { + findReplaceTarget.replaceSelection(options.getReplaceText()); + } + } + if (-1 == lastSearchReturnIndex) { + searchTextNotFoundDialog(); + } + } + + private boolean isAlteastOneWordMatch() { + return atleastOneMatchFound || (options.isForwardSearch() && options.isWrapAround()) + || (options.isBackwardSearch() && options.isWrapAround()); + } + + private boolean isWholeWordMatch() { + return options.isWholeWord() && lastSearchReturnIndex == -1 && options.isWrapAround(); + } + + private void handleWholeWordMatch(IFindReplaceTarget findReplaceTarget, boolean isReplace) { + int searchStartPosition = 0; + searchStartPosition = getSearchStartPosition(options.isForwardSearch()); + lastSearchReturnIndex = findReplaceTarget.findAndSelect(searchStartPosition, options.getSearchText(), + options.isForwardSearch(), options.isCaseSensitive(), options.isWholeWord()); + if (lastSearchReturnIndex > -1 && null != options.getReplaceText() && isReplace) { + findReplaceTarget.replaceSelection(options.getReplaceText()); + } + if (lastSearchReturnIndex == -1) { + searchTextNotFoundDialog(); + } + } + + /** + * Search text not found dialog. + */ + public void searchTextNotFoundDialog() { + MPPDBIDEDialogs.generateOKMessageDialog(MESSAGEDIALOGTYPE.INFORMATION, true, + MessageConfigLoader.getProperty(IMessagesConstants.FIND_REPLACE_SEARCH_NOT_FOUND), + MessageConfigLoader.getProperty(IMessagesConstants.FIND_REPLACE_SEARCH_NOT_FOUND) + '!'); + atleastOneMatchFound = false; + lastSearchReturnIndex = 0; + } + + /** + * Change case. + * + * @param strChangeType the str change type + */ + public void changeCase(String strChangeType) { + try { + ITextSelection textSel = (ITextSelection) viewer.getSelectionProvider().getSelection(); + removeAnnotation(textSel); + IFindReplaceTarget findReplaceTarget = viewer.getFindReplaceTarget(); + ITextSelection selection = (ITextSelection) viewer.getSelection(); + String strText = getText(textSel); + int searchStartPosition = selection.getOffset(); + int leadingWhiteSpaceCount = strText.indexOf(strText.trim()); + int selected = findReplaceTarget.findAndSelect(searchStartPosition + leadingWhiteSpaceCount, strText.trim(), + true, false, false); + disableToggleCurrentAssist(); + if (selected <= -1) { + return; + } + validateStringInComment(strChangeType, findReplaceTarget, strText); + } catch (OutOfMemoryError e) { + displayErrorDialog(); + } finally { + enableToggleCurrentAssist(); + } + } + + /** + * Validate string in comment. + * + * @param strChangeType the str change type + * @param findReplaceTarget the find replace target + * @param strText the str text + */ + private void validateStringInComment(String strChangeType, IFindReplaceTarget findReplaceTarget, String strText) { + StringBuilder sbConverted = new StringBuilder(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + boolean isSingleQuote = false; + boolean isDoubleQuote = false; + boolean isMultiLineComment = false; + boolean isSingleLineComment = false; + int multiLineCommentDepth = 0; + int charPosition = 0; + char[] chText = strText.toCharArray(); + int textLength = chText.length; + for (char ch : chText) { + isSingleLineComment = isSingleLineCommentCheck(isMultiLineComment, charPosition, chText, textLength, ch); + if (isMultiLineComment(isSingleLineComment, charPosition, chText, textLength, ch)) { + if (isMultiLineComment) { + multiLineCommentDepth++; + } else { + isMultiLineComment = true; + } + } + if (isNotMultiLineComment(isSingleLineComment, charPosition, chText, textLength, ch)) { + + if (multiLineCommentDepth > 0) { + multiLineCommentDepth--; + } else { + isMultiLineComment = false; + } + } + isSingleQuote = setSingleQuote(isDoubleQuote, isMultiLineComment, isSingleLineComment, ch); + isDoubleQuote = setDoubleQuote(isSingleQuote, isMultiLineComment, isSingleLineComment, ch); + if (isNotComment(isSingleQuote, isDoubleQuote, isMultiLineComment, isSingleLineComment)) { + handleNotComment(strChangeType, sbConverted, ch); + } else { + sbConverted.append(Character.toString(ch)); + } + charPosition++; + } + findReplaceTarget.replaceSelection(sbConverted.toString().trim()); + } + + /** + * Sets the double quote. + * + * @param isSingleQuote the is single quote + * @param isMultiLineComment the is multi line comment + * @param isSingleLineComment the is single line comment + * @param ch the ch + * @return true, if successful + */ + private boolean setDoubleQuote(boolean isSingleQuote, boolean isMultiLineComment, boolean isSingleLineComment, + char ch) { + boolean isDoubleQuote = false; + if (isDoubleQuote(isSingleQuote, isMultiLineComment, isSingleLineComment, ch)) { + isDoubleQuote = !isDoubleQuote; + } + return isDoubleQuote; + } + + /** + * Sets the single quote. + * + * @param isDoubleQuote the is double quote + * @param isMultiLineComment the is multi line comment + * @param isSingleLineComment the is single line comment + * @param ch the ch + * @return true, if successful + */ + private boolean setSingleQuote(boolean isDoubleQuote, boolean isMultiLineComment, boolean isSingleLineComment, + char ch) { + boolean isSingleQuote = false; + if (isSingleQuote(isDoubleQuote, isMultiLineComment, isSingleLineComment, ch)) { + isSingleQuote = !isSingleQuote; + } + return isSingleQuote; + } + + /** + * Checks if is single line comment. + * + * @param isMultiLineComment the is multi line comment + * @param charPosition the char position + * @param chText the ch text + * @param textLength the text length + * @param ch the ch + * @return true, if is single line comment + */ + private boolean isSingleLineCommentCheck(boolean isMultiLineComment, int charPosition, char[] chText, + int textLength, char ch) { + boolean isSingleLineComment = false; + if (isSingleLineComment(isMultiLineComment, charPosition, chText, textLength, ch)) { + isSingleLineComment = true; + } + if ('\n' == ch) { + isSingleLineComment = false; + } + return isSingleLineComment; + } + + /** + * Handle not comment. + * + * @param strChangeType the str change type + * @param sbConverted the sb converted + * @param ch the ch + */ + private void handleNotComment(String strChangeType, StringBuilder sbConverted, char ch) { + if (IMessagesConstants.UPPER_CASE.equals(strChangeType)) { + sbConverted.append(Character.toString(ch).toUpperCase(Locale.ENGLISH)); + } else if (IMessagesConstants.LOWER_CASE.equals(strChangeType)) { + sbConverted.append(Character.toString(ch).toLowerCase(Locale.ENGLISH)); + } + } + + /** + * Checks if is not comment. + * + * @param isSingleQuote the is single quote + * @param isDoubleQuote the is double quote + * @param isMultiLineComment the is multi line comment + * @param isSingleLineComment the is single line comment + * @return true, if is not comment + */ + private boolean isNotComment(boolean isSingleQuote, boolean isDoubleQuote, boolean isMultiLineComment, + boolean isSingleLineComment) { + return !isSingleLineComment && !isMultiLineComment && !isDoubleQuote && !isSingleQuote; + } + + /** + * Checks if is double quote. + * + * @param isSingleQuote the is single quote + * @param isMultiLineComment the is multi line comment + * @param isSingleLineComment the is single line comment + * @param ch the ch + * @return true, if is double quote + */ + private boolean isDoubleQuote(boolean isSingleQuote, boolean isMultiLineComment, boolean isSingleLineComment, + char ch) { + return !isSingleQuote && !isSingleLineComment && !isMultiLineComment && '\"' == ch; + } + + /** + * Checks if is single quote. + * + * @param isDoubleQuote the is double quote + * @param isMultiLineComment the is multi line comment + * @param isSingleLineComment the is single line comment + * @param ch the ch + * @return true, if is single quote + */ + private boolean isSingleQuote(boolean isDoubleQuote, boolean isMultiLineComment, boolean isSingleLineComment, + char ch) { + return !isDoubleQuote && !isSingleLineComment && !isMultiLineComment && '\'' == ch; + } + + /** + * Checks if is not multi line comment. + * + * @param isSingleLineComment the is single line comment + * @param charPosition the char position + * @param chText the ch text + * @param textLength the text length + * @param ch the ch + * @return true, if is not multi line comment + */ + private boolean isNotMultiLineComment(boolean isSingleLineComment, int charPosition, char[] chText, int textLength, + char ch) { + return '*' == ch && textLength > charPosition + 1 && '/' == chText[charPosition + 1] && !isSingleLineComment; + } + + /** + * Checks if is multi line comment. + * + * @param isSingleLineComment the is single line comment + * @param charPosition the char position + * @param chText the ch text + * @param textLength the text length + * @param ch the ch + * @return true, if is multi line comment + */ + private boolean isMultiLineComment(boolean isSingleLineComment, int charPosition, char[] chText, int textLength, + char ch) { + return '/' == ch && textLength > charPosition + 1 && '*' == chText[charPosition + 1] && !isSingleLineComment; + } + + /** + * Checks if is single line comment. + * + * @param isMultiLineComment the is multi line comment + * @param charPosition the char position + * @param chText the ch text + * @param textLength the text length + * @param ch the ch + * @return true, if is single line comment + */ + private boolean isSingleLineComment(boolean isMultiLineComment, int charPosition, char[] chText, int textLength, + char ch) { + return '-' == ch && textLength > charPosition + 1 && '-' == chText[charPosition + 1] && !isMultiLineComment; + } + + /** + * Gets the text. + * + * @param textSel the text sel + * @return the text + */ + private String getText(ITextSelection textSel) { + String strText = textSel.getText(); + if (null == strText) { + strText = ""; + } + return strText; + } + + /** + * Removes the annotation. + * + * @param textSel the text sel + */ + private void removeAnnotation(ITextSelection textSel) { + if (textSel.getLength() > 0) { + int startLine = textSel.getStartLine() + 1; + int endLine = textSel.getEndLine() + 1; + for (int index = startLine; index <= endLine; index++) { + Iterator iter = fAnnotationModel.getAnnotationIterator(); + while (iter.hasNext()) { + Annotation annotation = iter.next(); + if (annotation instanceof ErrorAnnotation) { + ErrorAnnotation errorAnnotation = (ErrorAnnotation) annotation; + if (errorAnnotation.getLine() == index) { + fAnnotationModel.removeAnnotation(errorAnnotation); + } + } + } + } + } + } + + /** + * Toggle block comment. + */ + public void toggleBlockComment() { + + try { + reconcilerUninstall(); + disableToggleCurrentAssist(); + IDocument document = viewer.getDocument(); + ITextSelection selection = (ITextSelection) viewer.getSelection(); + int selOffset = selection.getOffset(); + int selLength = selection.getLength(); + String selText = null != selection.getText() ? selection.getText() : ""; + int blockCommentOpenLen = MPPDBIDEConstants.ML_COMMENT_START.length(); + int blockCommentEndLen = MPPDBIDEConstants.ML_COMMENT_END.length(); + + DocumentRewriteSession rewriteSession = null; + rewriteSession = getRewriteSession(document); + + if (selText.startsWith(MPPDBIDEConstants.ML_COMMENT_START) + && selText.endsWith(MPPDBIDEConstants.ML_COMMENT_END)) { + // Remove comments + selLength = selLength - blockCommentEndLen - blockCommentOpenLen; + document.replace(selOffset, blockCommentOpenLen, ""); + if ((selOffset + selLength - 2) >= 0 && "/ ".equals(document.get(selOffset + selLength - 2, 2))) { + document.replace(selOffset + selLength - 1, blockCommentEndLen + 1, ""); + } else { + document.replace(selOffset + selLength, blockCommentEndLen, ""); + } + } else { + // Add comment + document.replace(selOffset, 0, MPPDBIDEConstants.ML_COMMENT_START); + if ("/".equals(document.get(selOffset + selLength + blockCommentOpenLen - 1, 1))) { + document.replace(selOffset + selLength + blockCommentOpenLen, 0, + " " + MPPDBIDEConstants.ML_COMMENT_END); + selLength += blockCommentOpenLen + blockCommentEndLen + 1; + } else { + document.replace(selOffset + selLength + blockCommentOpenLen, 0, MPPDBIDEConstants.ML_COMMENT_END); + selLength += blockCommentOpenLen + blockCommentEndLen; + } + } + + handleDocRewriteSession(document, selOffset, selLength, rewriteSession); + } catch (BadLocationException ble) { + MPPDBIDELoggerUtility.error("PLSourceEditorCore: BadLocationException occurred.", ble); + } catch (OutOfMemoryError e) { + displayErrorDialog(); + } finally { + postToggleLineComment(); + } + } + + /** + * Perform shift left. + */ + private void performShiftLeft() { + + reconcilerUninstall(); + + if (viewer.getUndoManager() != null) { + viewer.getUndoManager().beginCompoundChange(); + } + + IDocument document = getDocument(); + try { + ITextSelection selection = (ITextSelection) viewer.getSelection(); + IRegion block = getTextBlockFromSelection(selection); + ITypedRegion[] regions = TextUtilities.computePartitioning(document, SQLPartitionScanner.SQL_PARTITIONING, + block.getOffset(), block.getLength(), false); + // [start line, end line, start line, end line, ...] + int[] lines = new int[regions.length * 2]; + for (int iregion = 0, jregion = 0; iregion < regions.length; iregion++, jregion += 2) { + // start line of region + lines[jregion] = getFirstCompleteLineOfRegion(regions[iregion]); + // end line of region + int length = regions[iregion].getLength(); + int offset = regions[iregion].getOffset() + length; + if (length > 0) { + offset--; + } + + lines[jregion + 1] = lines[jregion] == -1 ? -1 : document.getLineOfOffset(offset); + } + + viewer.setRedraw(false); + + // Perform the shift operation. + for (int iPos = 0, jPosos = 0; iPos < regions.length; iPos++, jPosos += 2) { + String[] prefixes = config.getIndentPrefixes(viewer, config.getConfiguredContentTypes(viewer)[0]); + if (prefixes.length > 0 && lines[jPosos] >= 0 && lines[jPosos + 1] >= 0) { + shiftLeft(lines[jPosos], lines[jPosos + 1], prefixes); + } + } + } catch (BadLocationException exception) { + MPPDBIDELoggerUtility.error("PLSourceEditorCore: BadLocationException occurred.", exception); + } + + viewer.setRedraw(true); + if (viewer.getUndoManager() != null) { + viewer.getUndoManager().endCompoundChange(); + } + + reconcilerInstall(); + + } + + /** + * Shift left. + * + * @param startLine the start line + * @param endLine the end line + * @param prefixes the prefixes + */ + private void shiftLeft(int startLine, int endLine, String[] prefixes) { + IDocument document = getDocument(); + + try { + String text; + IRegion[] occurrences = new IRegion[endLine - startLine + 1]; + + // find all the first occurrences of prefix in the given lines + for (int count = 0; count < occurrences.length; count++) { + IRegion line = document.getLineInformation(startLine + count); + text = document.get(line.getOffset(), line.getLength()); + + int index = -1; + int length = 0; + if (text.length() != 0 && text.charAt(0) == '\t') { + index = line.getOffset(); + length = 1; + } else { + index = line.getOffset(); + int spaceCounter = 0; + int loopBoundary = text.length() < DSFormatterPreferencePage.getIndentSize() ? text.length() + : DSFormatterPreferencePage.getIndentSize(); + while (spaceCounter < loopBoundary && text.charAt(spaceCounter) == ' ') { + spaceCounter++; + } + + length = spaceCounter; + } + + if (length == 0) { + // found a non-shifting line + continue; + } + + occurrences[count] = new Region(index, length); + } + + // OK - change the document + int decrement = 0; + for (int count = 0; count < occurrences.length; count++) { + IRegion region = occurrences[count]; + if (region != null) { + document.replace(region.getOffset() - decrement, region.getLength(), ""); // $NON-NLS-1$ + decrement += region.getLength(); + } + } + + } catch (BadLocationException exception) { + MPPDBIDELoggerUtility.error("PLSourceEditorCore: BadLocationException occurred.", exception); + } + } + + /** + * Gets the first complete line of region. + * + * @param region the region + * @return the first complete line of region + */ + private int getFirstCompleteLineOfRegion(IRegion region) { + + try { + + IDocument document = getDocument(); + + int startLine = document.getLineOfOffset(region.getOffset()); + + int offset = document.getLineOffset(startLine); + if (offset >= region.getOffset()) { + return startLine; + + } + + offset = document.getLineOffset(startLine + 1); + return (offset > region.getOffset() + region.getLength()) ? -1 : startLine + 1; + + } catch (BadLocationException exception) { + MPPDBIDELoggerUtility.error("PLSourceEditorCore: BadLocationException occurred.", exception); + } + + return -1; + } + + /** + * Gets the text block from selection. + * + * @param selection the selection + * @return the text block from selection + * @throws BadLocationException the bad location exception + */ + private IRegion getTextBlockFromSelection(ITextSelection selection) throws BadLocationException { + IDocument document = getDocument(); + int start = document.getLineOffset(selection.getStartLine()); + int end; + int endLine = selection.getEndLine(); + if (document.getNumberOfLines() > endLine + 1) { + end = document.getLineOffset(endLine + 1); + } else { + end = document.getLength(); + } + return new Region(start, end - start); + } + + /** + * Gets the text. + * + * @return the text + */ + public String getText() { + return getDocument().get(); + } + + /** + * Toggle line comment. + */ + public void toggleLineComment() { + try { + ITextSelection textSelection = handlePreToggleLineComment(); + IDocument document = viewer.getDocument(); + int selOffset = textSelection.getOffset(); + int selLength = textSelection.getLength(); + boolean firstLineFlag = true; + int startLine = textSelection.getStartLine(); + int endLine = textSelection.getEndLine(); + int lineCommentLen = SL_COMMENT.length(); + boolean lineComment = false; + int selLineNo = 0; + DocumentRewriteSession rewriteSession = getRewriteSession(document); + for (int lineNum = startLine; lineNum <= endLine; lineNum++) { + int lineOffset = document.getLineOffset(lineNum); + int lineLength = document.getLineLength(lineNum); + int trimLength = 0; + selLineNo++; + String lineText = document.get(lineOffset, lineLength); + lineComment = isLineComment(selLineNo, lineText); + if (lineComment) { + trimLength = deleteTabOrSpaceChar(lineText); + if (lineText.trim().startsWith("--")) { // Remove comment + document.replace(lineOffset + trimLength, lineCommentLen, ""); + if (isSeloffsetAndLineoffsetEqual(selOffset, firstLineFlag, lineOffset)) { + selLength -= lineCommentLen; + } else if (isSeloffsetAndLineoffsetNotEqual(selOffset, firstLineFlag, lineOffset)) { + selOffset -= lineCommentLen; + } else { + selLength -= lineCommentLen; + } + } + } else { + document.replace(lineOffset, 0, SL_COMMENT); // Add + // comment + if (isSeloffsetAndLineoffsetNotEqual(selOffset, firstLineFlag, lineOffset)) { + selOffset += lineCommentLen; + } else { + selLength += lineCommentLen; + } + } + firstLineFlag = false; + } + handleDocRewriteSession(document, selOffset, selLength, rewriteSession); + } catch (OutOfMemoryError e) { + displayErrorDialog(); + } catch (BadLocationException ble) { + MPPDBIDELoggerUtility.error("PLSourceEditorCore: BadLocationException occurred.", ble); + } finally { + postToggleLineComment(); + } + } + + private void postToggleLineComment() { + enableToggleCurrentAssist(); + reconcilerInstall(); + } + + private ITextSelection handlePreToggleLineComment() { + reconcilerUninstall(); + disableToggleCurrentAssist(); + ITextSelection textSelection = (ITextSelection) viewer.getSelection(); + return textSelection; + } + + private void handleDocRewriteSession(IDocument document, int selOffset, int selLength, + DocumentRewriteSession rewriteSession) { + stopDocumentRewriteSession(document, rewriteSession); + // set the selection after toggle the comments + setViewerSelection(selOffset, selLength); + } + + private void displayErrorDialog() { + MPPDBIDEDialogs.generateOKMessageDialogInUI(MESSAGEDIALOGTYPE.INFORMATION, true, + MessageConfigLoader.getProperty(IMessagesConstants.TITLE_OUT_OF_MEMORY), + MessageConfigLoader.getProperty(IMessagesConstants.ERR_OUT_OF_MEMORY_OCCURED)); + } + + /** + * Delete tab or space char. + * + * @param lineText the line text + * @return the int + */ + private int deleteTabOrSpaceChar(String lineText) { + int trimLength = 0; + if (!"".equals(lineText)) { + + StringBuffer sb = new StringBuffer(lineText); + for (;;) { + if (isLineStartWithHaveSpaceOrTabChar(sb)) { + sb.deleteCharAt(0); + trimLength++; + } else { + break; + } + } + } + return trimLength; + } + + /** + * Checks if is seloffset and lineoffset not equal. + * + * @param selOffset the sel offset + * @param firstLineFlag the first line flag + * @param lineOffset the line offset + * @return true, if is seloffset and lineoffset not equal + */ + private boolean isSeloffsetAndLineoffsetNotEqual(int selOffset, boolean firstLineFlag, int lineOffset) { + return lineOffset != selOffset && firstLineFlag; + } + + /** + * Checks if is seloffset and lineoffset equal. + * + * @param selOffset the sel offset + * @param firstLineFlag the first line flag + * @param lineOffset the line offset + * @return true, if is seloffset and lineoffset equal + */ + private boolean isSeloffsetAndLineoffsetEqual(int selOffset, boolean firstLineFlag, int lineOffset) { + return lineOffset == selOffset && firstLineFlag; + } + + /** + * Checks if is line start with have space or tab char. + * + * @param sb the sb + * @return true, if is line start with have space or tab char + */ + private boolean isLineStartWithHaveSpaceOrTabChar(StringBuffer sb) { + return sb.charAt(0) == ' ' || sb.charAt(0) == '\t'; + } + + /** + * Checks if is line comment. + * + * @param selLineNo the sel line no + * @param lineText the line text + * @return true, if is line comment + */ + private boolean isLineComment(int selLineNo, String lineText) { + return (lineText.trim()).startsWith(SL_COMMENT); + } + + /** + * Gets the rewrite session. + * + * @param document the document + * @return the rewrite session + */ + private DocumentRewriteSession getRewriteSession(IDocument document) { + DocumentRewriteSession rewriteSession = null; + if (document instanceof IDocumentExtension4) { + rewriteSession = ((IDocumentExtension4) document) + .startRewriteSession(DocumentRewriteSessionType.SEQUENTIAL); + } + return rewriteSession; + } + + /** + * Stop document rewrite session. + * + * @param document the document + * @param rewriteSession the rewrite session + */ + private void stopDocumentRewriteSession(IDocument document, DocumentRewriteSession rewriteSession) { + if (rewriteSession != null) { + ((IDocumentExtension4) document).stopRewriteSession(rewriteSession); + } + } + + /** + * Sets the viewer selection. + * + * @param selOffset the sel offset + * @param selLength the sel length + */ + private void setViewerSelection(int selOffset, int selLength) { + if (selLength > 0) { + viewer.getSelectionProvider().setSelection(new TextSelection(selOffset, selLength)); + } + } + + /** + * Gets the search start position. + * + * @param isFwdSearch the is fwd search + * @return the search start position + */ + public int getSearchStartPosition(boolean isFwdSearch) { + TextViewer textViewer = (TextViewer) viewer; + + int searchStartPosition = 0; + if (!isFwdSearch) { + searchStartPosition = -1; + } + + if (lastSearchReturnIndex != -1) { + ITextSelection selection = (ITextSelection) textViewer.getSelection(); + searchStartPosition = selection.getOffset(); + if (isFwdSearch) { + searchStartPosition += selection.getLength(); + } else { + searchStartPosition--; + if (!options.isWrapAround() && searchStartPosition < 0) { + searchStartPosition = 0; + } + } + } + + return searchStartPosition; + } + + /** + * Clear doc content. + */ + public void clearDocContent() { + this.doc.set(""); + } + + /** + * Clear status bar. + */ + public void clearStatusBar() { + this.execProgresBar = null; + } + + /** + * Uninstall decoration. + */ + public void uninstallDecoration() { + if (fSourceViewerDecorationSupport != null) { + fSourceViewerDecorationSupport.uninstall(); + fSourceViewerDecorationSupport = null; + } + } + + /** + * Toggle comments enable disable. + * + * @param partObject the part object + */ + public void toggleCommentsEnableDisable(Object partObject) { + boolean isEnabled = this.getSourceViewer().isEditable(); + if (partObject instanceof SQLTerminal) { + SQLTerminal terminal = (SQLTerminal) partObject; + isEnabled = terminal.getTerminalCore().getSourceViewer().isEditable(); + } else if (partObject instanceof PLSourceEditor) { + PLSourceEditor sourceEditor = (PLSourceEditor) partObject; + isEnabled = sourceEditor.getSourceEditorCore().getSourceViewer().isEditable(); + } + toggleLineComments.setEnabled(isEnabled); + toggleBlockComments.setEnabled(isEnabled); + + } + + /** + * Property change. + * + * @param event the event + */ + @Override + public void propertyChange(PropertyChangeEvent event) { + String preferencePropertyName = event.getProperty(); + if (preferencePropertyName.equals(FormatterPreferenceKeys.GEN_TAB_CHAR_PREF)) { + configurePrefixes(); + // handle for insert tab and perform change of tab width + Boolean isInsertTabOptionSelected = (Boolean) event.getNewValue(); + if (!isInsertTabOptionSelected) { + reconfigureTabWidth(); + } + } else if (preferencePropertyName.equals(FormatterPreferenceKeys.GEN_CHAR_SIZE_PREF)) { + configurePrefixes(); + // change the tab width + reconfigureTabWidth(); + } + + } + + /** + * Configure prefixes. + */ + private void configurePrefixes() { + String[] types = config.getConfiguredContentTypes(viewer); + config.setUpdatedPrefixes(viewer); + configurePrefixesForEachContentType(types); + } + + /** + * Configure prefixes for each content type. + * + * @param types the types + */ + private void configurePrefixesForEachContentType(String[] types) { + for (String type : types) { + String[] indentPrefixes = config.getIndentPrefixes(viewer, type); + viewer.setIndentPrefixes(indentPrefixes, type); + } + } + + /** + * Reconfigure tab width. + */ + private void reconfigureTabWidth() { + if (viewer.getTextWidget() != null) { + viewer.getTextWidget().setTabs(config.getTabWidth(viewer)); + } + } + + /** + * Checks if is editable. + * + * @return true, if is editable + */ + public boolean isEditable() { + return viewer.isEditable(); + } + + /** + * Gets the syntax. + * + * @return the syntax + */ + public SQLSyntax getSyntax() { + return syntax; + } + + /** + * Sets the syntax. + * + * @param syntax the new syntax + */ + public void setSyntax(SQLSyntax syntax) { + this.syntax = syntax; + } + + /** + * Gets the viewer doc. + * + * @return the viewer doc + */ + public String getViewerDoc() { + return viewer.getDocument().get(); + } + + /** + * Reset font. + */ + public void resetFont() { + FontData fontData = this.font.getFontData()[0]; + fontData.setHeight(preferenceStore.getInt(MPPDBIDEConstants.PREF_FONT_STYLE_SIZE)); + font = resManager.createFont(FontDescriptor.createFrom(fontData)); + + viewer.getTextWidget().setFont(font); + + viewer.setDocument(this.doc, fAnnotationModel); + } + + private void clearFont() { + if (null != resManager && null != preferenceStore) { + resManager.destroyFont(FontDescriptor.createFrom("Courier New", + preferenceStore.getInt(MPPDBIDEConstants.PREF_FONT_STYLE_SIZE), SWT.NORMAL)); + font = null; + resManager = null; + } + } + + /** + * get the selected query + * + * @return the selected query + */ + public String getSelectedQry() { + if (!(getSourceViewer().getSelectionProvider().getSelection() instanceof ITextSelection)) { + return getDocument().get(); + } + final ITextSelection textSel = (ITextSelection) getSourceViewer().getSelectionProvider().getSelection(); + String query = textSel.getText(); + if (query != null && query.length() > 0) { + return query; + } else { + return getDocument().get(); + } + + } + + /** + * start the Job to format the contents + */ + public void doFormattingOfContents() { + SQLTerminalFormatterUIWorker formatWorker = new SQLTerminalFormatterUIWorker(this, "Format SQL - "); + jobsAssociatedToTerminal.add(formatWorker); + formatWorker.schedule(); + } + + /** + * to remove completed Job + * + * @param job which job need to be removed + */ + public void removeCompletedJob(UIWorkerJob job) { + boolean isRemoveOk = this.jobsAssociatedToTerminal.remove(job); + + if (!isRemoveOk) { + MPPDBIDELoggerUtility.error("Unable to remove job : " + job.getName() + " from the list"); + } + } + + /** + * Gets the f annotation model. + * + * @return the f annotation model + */ + public AnnotationModel getfAnnotationModel() { + return fAnnotationModel; + } + + /** + * pre destroy + */ + @PreDestroy + public void preDestroy() { + if (null != viewer) { + viewer.unconfigure(); + } + fAnnotationAccess = null; + if (null != doc) { + IDocumentPartitioner documentPartitioner = ((IDocumentExtension3) doc) + .getDocumentPartitioner(SQLPartitionScanner.SQL_PARTITIONING); + if (null != documentPartitioner) { + if (documentPartitioner instanceof SQLDocumentPartitioner) { + SQLDocumentPartitioner partitioner = (SQLDocumentPartitioner) documentPartitioner; + partitioner.clearScanner(); + } + documentPartitioner.disconnect(); + } + doc.set(""); + destroyDocument(); + } + if (null != fAnnotationModel) { + fAnnotationModel.removeAllAnnotations(); + } + uninstallDecoration(); + clearStatusBar(); + if (null != jobsAssociatedToTerminal) { + jobsAssociatedToTerminal.clear(); + jobsAssociatedToTerminal = null; + } + if (null != config) { + config.preDestroy(); + config = null; + } + findAndReplaceoptions = null; + options = null; + if (null != syntax) { + this.syntax = null; + } + clearFont(); + if (null != preferenceStore) { + preferenceStore.removePropertyChangeListener(this); + preferenceStore = null; + } + MPPDBIDELoggerUtility + .info(MessageConfigLoader.getProperty(IMessagesConstants.GUI_PLSOURCEEDITORCORE_SOURCE_EDITOR_CLEARED)); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLCodeScanner.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLCodeScanner.java new file mode 100644 index 0000000000000000000000000000000000000000..c70188f56074ed26bb096d9fcb2e474b7448140d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLCodeScanner.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map.Entry; + +import org.eclipse.jface.text.TextAttribute; +import org.eclipse.jface.text.rules.EndOfLineRule; +import org.eclipse.jface.text.rules.IRule; +import org.eclipse.jface.text.rules.IToken; +import org.eclipse.jface.text.rules.RuleBasedScanner; +import org.eclipse.jface.text.rules.SingleLineRule; +import org.eclipse.jface.text.rules.Token; +import org.eclipse.jface.text.rules.WhitespaceRule; +import org.eclipse.jface.text.rules.WordRule; +import org.eclipse.swt.SWT; + +import org.opengauss.mppdbide.adapter.keywordssyntax.SQLSyntax; +import org.opengauss.mppdbide.gauss.sqlparser.comm.ISQLSyntax; +import org.opengauss.mppdbide.gauss.sqlparser.comm.NestedMultipleLineRule; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class SQLCodeScanner. + * + * @since 3.0.0 + */ +public class SQLCodeScanner extends RuleBasedScanner implements ISQLSyntax { + + /** + * The syntax. + */ + SQLSyntax syntax; + + /** + * Instantiates a new SQL code scanner. + * + * @param sqlSyntax the sql syntax + */ + public SQLCodeScanner(SQLSyntax sqlSyntax) { + this.syntax = sqlSyntax; + SQLSyntaxColorProvider provider = SQLEditorPlugin.getDefault().getColorProvider(); + + IToken predicate = new Token( + new TextAttribute(provider.getColor(SQLSyntaxColorProvider.getPREDICATES()), null, SWT.BOLD, null)); + + IToken string = new Token( + new TextAttribute(provider.getColor(SQLSyntaxColorProvider.getSTRING()), null, SWT.NORMAL)); + IToken singlecomment = new Token(new TextAttribute( + provider.getColor(SQLSyntaxColorProvider.getSQLSingleLineComment()), null, SWT.NORMAL)); + IToken multi = new Token( + new TextAttribute(provider.getColor(SQLSyntaxColorProvider.SQL_MULTI_LINE_COMMENT), null, SWT.NORMAL)); + + IToken other = new Token(new TextAttribute(provider.getColor(SQLSyntaxColorProvider.getDEFAULT()))); + + setDefaultReturnToken(other); + List rules = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + addCommentRules(singlecomment, multi, rules); + + addStringQuoteRules(string, rules); + + addPredicateRules(predicate, other, rules); + + rules.add(new WhitespaceRule(new SQLWhiteSpaceDetector())); + + WordRule wordRule = addKeywordRules(provider, other); + + rules.add(wordRule); + + IRule[] res = new IRule[rules.size()]; + rules.toArray(res); + setRules(res); + wordRule = null; + } + + /** + * Adds the keyword rules. + * + * @param provider the provider + * @param other the other + * @return the word rule + */ + private WordRule addKeywordRules(SQLSyntaxColorProvider provider, IToken other) { + IToken unreservedKeyword = new Token(new TextAttribute( + provider.getColor(SQLSyntaxColorProvider.getUnreservedKeyword()), null, SWT.BOLD, null)); + + IToken reservedkeywords = new Token(new TextAttribute( + provider.getColor(SQLSyntaxColorProvider.getReservedKeyword()), null, SWT.BOLD, null)); + + IToken constant = new Token( + new TextAttribute(provider.getColor(SQLSyntaxColorProvider.getCONSTANTS()), null, SWT.BOLD, null)); + + IToken type = new Token( + new TextAttribute(provider.getColor(SQLSyntaxColorProvider.getTYPE()), null, SWT.BOLD, null)); + + WordRule wordRule = new WordRule(new SQLWordDetector(syntax), other, true); + + for (Entry entry : syntax.getConstants().entrySet()) { + wordRule.addWord(entry.getKey(), constant); + } + + for (Entry entry : syntax.getUnreservedkrywords().entrySet()) { + wordRule.addWord(entry.getKey(), unreservedKeyword); + } + + for (Entry entry : syntax.getReservedkrywords().entrySet()) { + wordRule.addWord(entry.getKey(), reservedkeywords); + } + + for (Entry entry : syntax.getTypes().entrySet()) { + wordRule.addWord(entry.getKey(), type); + } + return wordRule; + } + + /** + * Adds the predicate rules. + * + * @param predicate the predicate + * @param other the other + * @param rules the rules + */ + private void addPredicateRules(IToken predicate, IToken other, List rules) { + WordRule predicateRule = new WordRule(new SQLPredicateDetector(syntax), other, true); + for (Entry entry : syntax.getPredicates().entrySet()) { + predicateRule.addWord(entry.getKey(), predicate); + } + rules.add(predicateRule); + } + + /** + * Adds the string quote rules. + * + * @param string the string + * @param rules the rules + */ + private void addStringQuoteRules(IToken string, List rules) { + rules.add(new SingleLineRule("\"", "\"", string, '\\')); + rules.add(new SingleLineRule("'", "'", string, '\\')); + rules.add(new SingleLineRule("'", "'", string)); + } + + /** + * Adds the comment rules. + * + * @param singlecomment the singlecomment + * @param multi the multi + * @param rules the rules + */ + private void addCommentRules(IToken singlecomment, IToken multi, List rules) { + rules.add(new EndOfLineRule("--", singlecomment, (char) 0)); + rules.add(new NestedMultipleLineRule("/*", "*/", multi, '\0', true)); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLContentAssist.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLContentAssist.java new file mode 100644 index 0000000000000000000000000000000000000000..0f8e302ff06c942852b8aff91debfb24241a2b17 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLContentAssist.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import org.eclipse.jface.text.contentassist.ContentAssistant; + +/** + * + * Title: class + * + * Description: The Class SQLContentAssist. + * + * @since 3.0.0 + */ +public class SQLContentAssist extends ContentAssistant { + + private String[] currentPrefix = new String[0]; + + /** + * Checks if is proposal popup active. + * + * @return true, if is proposal popup active + */ + @Override + public boolean isProposalPopupActive() { + return super.isProposalPopupActive(); + } + + /** + * Hide. + */ + @Override + public void hide() { + super.hide(); + } + + /** + * Sets the current prefix. + * + * @param prefix the new current prefix + */ + public void setCurrentPrefix(String[] prefix) { + if (prefix != null) { + currentPrefix = prefix.clone(); + } + } + + /** + * Gets the current prefix. + * + * @return the current prefix + */ + public String[] getCurrentPrefix() { + return currentPrefix.clone(); + } + + /** + * Show possible completions. + * + * @return the string + */ + @Override + public String showPossibleCompletions() { + SQLContentAssistProcessor.setLookupTemplates(false); + return super.showPossibleCompletions(); + } + + /** + * Show context information. + * + * @return the string + */ + @Override + public String showContextInformation() { + SQLContentAssistProcessor.setLookupTemplates(true); + return super.showPossibleCompletions(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLContentAssistAliasProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLContentAssistAliasProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..8810eddc16c9096e721e5f56c368b5fdc12f2706 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLContentAssistAliasProcessor.java @@ -0,0 +1,268 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map.Entry; +import java.util.Set; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.concurrent.atomic.AtomicInteger; + +import org.opengauss.mppdbide.bl.contentassist.ContentAssistProcesserData.AutoSuggestComparator; +import org.opengauss.mppdbide.bl.queryparser.ParseContext; +import org.opengauss.mppdbide.bl.serverdatacache.Alias; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.presentation.contentassistprocesser.ContentAssistProcesserCore; +import org.opengauss.mppdbide.utils.CustomStringUtility; +import org.opengauss.mppdbide.utils.JSQLParserUtils; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.view.aliasparser.AliasParserManager; +import org.opengauss.mppdbide.view.aliasparser.AliasRequestResponsePacket; +import org.opengauss.mppdbide.view.aliasparser.AliasRequestResponsePacketState; + +/** + * + * Title: class + * + * Description: The Class SQLContentAssistAliasProcessor. + * + * @since 3.0.0 + */ +public class SQLContentAssistAliasProcessor { + + private String prefix; + private String fullContent; + private int offset; + private SortedMap aliasMap; + private List wordBreakCharList; + private static final int WAIT_INTERVAL_FOR_ALIAS_PARSER = 10; /* ms */ + private static final int WAIT_ITERATION_FOR_ALIAS_PARSER = 300; + private AtomicInteger uniqueIds; + + /** + * Instantiates a new SQL content assist alias processor. + * + * @param inPrefix the in prefix + * @param inFullContent the in full content + * @param inOffset the in offset + * @param inWordBreakCharList the in word break char list + */ + public SQLContentAssistAliasProcessor(String inPrefix, String inFullContent, int inOffset, + List inWordBreakCharList) { + prefix = inPrefix; + fullContent = inFullContent; + offset = inOffset; + uniqueIds = new AtomicInteger(0); + aliasMap = null; + wordBreakCharList = inWordBreakCharList; + } + + /** + * Compute alias proposal. + * + * @param core the core + * @return true, if successful + */ + public boolean computeAliasProposal(ContentAssistProcesserCore core) { + /* + * Null check for prefix is needed as it can be set to null in the + * constructor + */ + if (null == prefix) { + return false; + } + + boolean isPrefixEndsWithDot = CustomStringUtility.isEndsWithDot(prefix); + HashMap> aliasToTableNameMap = null; + + aliasToTableNameMap = parseAndGetAliasMap(fullContent, isPrefixEndsWithDot); + + if (null != aliasToTableNameMap && aliasToTableNameMap.size() > 0) { + /* + * Assumption: There will only be 2 parts in the prefix Replace + * alias in prefix by corresponding table name + */ + String firstPrefixPart = null; + String lastPrefixPart = null; + if (!isPrefixEndsWithDot && !prefix.isEmpty()) { + String[] splitPrefix = JSQLParserUtils.getSplitQualifiedName(prefix, false); + if (null != splitPrefix && splitPrefix.length > 1) { + firstPrefixPart = splitPrefix[0]; + lastPrefixPart = splitPrefix[splitPrefix.length - 1]; + } + + if (null != firstPrefixPart) { + prefix = firstPrefixPart.concat("."); + } + } + prefix = findMatchingTableNameForAlias(aliasToTableNameMap, core); + + if (null != lastPrefixPart && null != prefix) { + prefix = prefix.concat(lastPrefixPart); + } + } + + return true; + } + + /** + * Find matching table name for alias. + * + * @param aliasToTableNameMap the alias to table name map + * @param core the core + * @return the string + */ + private String findMatchingTableNameForAlias(HashMap> aliasToTableNameMap, + ContentAssistProcesserCore core) { + /* Replace Alias by its mapping table/view/column name */ + if (null != aliasToTableNameMap && !aliasToTableNameMap.isEmpty() && !prefix.isEmpty()) { + String element = null; + for (Entry> entry : aliasToTableNameMap.entrySet()) { + element = entry.getKey(); + if (CustomStringUtility.getFormattedStringForAliasCompare(element).equals(CustomStringUtility + .getFormattedStringForAliasCompare(prefix.substring(0, prefix.length() - 1)))) { + List tableNamelist = aliasToTableNameMap.get(element); + /* Only add table name, not schema name */ + if (tableNamelist.size() > 0) { + prefix = core.findString(tableNamelist.get(tableNamelist.size() - 1).concat("."), + wordBreakCharList); + break; + } + } + } + } + return prefix; + } + + /** + * Parses the and get alias map.Parse the query and get parsed data + * + * @param currentQuery the current query + * @param isPrefixEndsWithDot the is prefix ends with dot + * @return the hash map + */ + private HashMap> parseAndGetAliasMap(String currentQuery, boolean isPrefixEndsWithDot) { + if (null == currentQuery) { + return null; + } + + /* Get unique packet id */ + int uniquePacketId = uniqueIds.incrementAndGet(); + + /* Build the packet for alias parser */ + AliasRequestResponsePacket packet = new AliasRequestResponsePacket(currentQuery, uniquePacketId, + isPrefixEndsWithDot, offset); + + /* Add packet to alias parser queue */ + AliasParserManager.getInstance().submitAliasParserJob(packet); + + HashMap> aliasToTableNameMap = null; + + int aliasParserWaitCounter = WAIT_ITERATION_FOR_ALIAS_PARSER; + + /* + * Wait for WAIT_ITERATION_FOR_ALIAS_PARSER X + * WAIT_INTERVAL_FOR_ALIAS_PARSER ms at most + */ + while (AliasRequestResponsePacketState.RESPONSE != packet.getPacketState() && aliasParserWaitCounter >= 0) { + try { + Thread.sleep(WAIT_INTERVAL_FOR_ALIAS_PARSER); + } catch (InterruptedException e) { + MPPDBIDELoggerUtility.warn("Warning: InterruptedException occurs"); + return aliasToTableNameMap; + } + aliasParserWaitCounter--; + } + + if (null != packet.getPContext()) { + /* Received response from alias parser in time */ + ParseContext aliasPc = packet.getPContext(); + aliasToTableNameMap = aliasPc.getAliasToTableNameMap(); + + if (!isPrefixEndsWithDot) { + List matchedAliases = getMatchingAliasNames(prefix, aliasToTableNameMap); + if (!matchedAliases.isEmpty()) { + aliasMap = getAliasProposals(matchedAliases); + } + } + } else { + /* Did not receive response from alias parser in time */ + AliasParserManager.getInstance().cancelAliasParserJob(uniquePacketId); + } + + return aliasToTableNameMap; + } + + /** + * Gets the matching alias names. + * + * @param inPrefix the in prefix + * @param aliasToTableNameMap the alias to table name map + * @return the matching alias names + */ + private ArrayList getMatchingAliasNames(String inPrefix, + HashMap> aliasToTableNameMap) { + ArrayList matchedAliasNames = new ArrayList(1); + if (!aliasToTableNameMap.isEmpty()) { + Set aliasList = aliasToTableNameMap.keySet(); + for (String element : aliasList) { + if (element.startsWith(inPrefix)) { + matchedAliasNames.add(element); + } + } + } + return matchedAliasNames; + } + + /** + * Gets the alias proposals. + * + * @param matchedAliases the matched aliases + * @return the alias proposals + */ + private SortedMap getAliasProposals(List matchedAliases) { + SortedMap aliasList = new TreeMap(new AutoSuggestComparator()); + + for (String element : matchedAliases) { + Alias aliasObject = new Alias(element, OBJECTTYPE.ALIAS); + aliasList.put(ServerObject.getQualifiedObjectNameHandleQuotes(aliasObject.getName()) + " - Alias", + aliasObject); + } + return aliasList; + } + + /** + * Gets the processed prefix. + * + * @return the processed prefix + */ + public String getProcessedPrefix() { + return this.prefix; + } + + /** + * Gets the computed alias map. + * + * @return the computed alias map + */ + public SortedMap getComputedAliasMap() { + return this.aliasMap; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLContentAssistProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLContentAssistProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..219077ccf18123a5c05d0fbc0b4089d7cf84661b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLContentAssistProcessor.java @@ -0,0 +1,612 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map.Entry; +import java.util.SortedMap; + +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.ITypedRegion; +import org.eclipse.jface.text.contentassist.CompletionProposal; +import org.eclipse.jface.text.contentassist.ICompletionProposal; +import org.eclipse.jface.text.contentassist.IContentAssistProcessor; +import org.eclipse.jface.text.contentassist.IContextInformation; +import org.eclipse.jface.text.contentassist.IContextInformationValidator; +import org.eclipse.jface.text.source.SourceViewer; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Display; + +import org.opengauss.mppdbide.adapter.gauss.DBConnection; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.DatabaseUtils; +import org.opengauss.mppdbide.bl.serverdatacache.INamespace; +import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.bl.util.ExecTimer; +import org.opengauss.mppdbide.bl.util.IExecTimer; +import org.opengauss.mppdbide.presentation.contentassistprocesser.ContentAssistProcesserCore; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.StatusMessage; +import org.opengauss.mppdbide.utils.messaging.StatusMessageList; +import org.opengauss.mppdbide.view.core.sourceeditor.templates.TemplateCompletionProcessor; +import org.opengauss.mppdbide.view.ui.ObjectBrowser; +import org.opengauss.mppdbide.view.utils.BottomStatusBar; +import org.opengauss.mppdbide.view.utils.CharPairsUtil; +import org.opengauss.mppdbide.view.utils.DSDefaultCharacterPairMatcherUtil; +import org.opengauss.mppdbide.view.utils.UIElement; +import org.opengauss.mppdbide.view.utils.UserPreference; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.iconmapper.IcoPathMapper; +import org.opengauss.mppdbide.view.workerjob.UIWorkerJob; + +/** + * + * Title: class + * + * Description: The Class SQLContentAssistProcessor. + * + * @since 3.0.0 + */ +public class SQLContentAssistProcessor implements IContentAssistProcessor { + private IExecTimer timer; + private SQLContentAssist assistant = null; + private ContentAssistProcesserCore core; + private volatile Database database; + private LinkedHashMap autoMap = null; + private static LinkedHashMap map = null; + private static boolean lookupTemplates = false; + + /** + * Instantiates a new SQL content assist processor. + * + * @param assistant the assistant + */ + public SQLContentAssistProcessor(SQLContentAssist assistant) { + this.assistant = assistant; + } + + /** + * Sets the lookup templates. + * + * @param lookupTemplates the new lookup templates + */ + public static void setLookupTemplates(boolean lookupTemplates) { + SQLContentAssistProcessor.lookupTemplates = lookupTemplates; + } + + /** + * Make template proposals. + * + * @param viewer the viewer + * @param offset the offset + * @return the i completion proposal[] + */ + private ICompletionProposal[] makeTemplateProposals(ITextViewer viewer, int offset) { + TemplateCompletionProcessor templateProcessor = new TemplateCompletionProcessor(assistant); + return templateProcessor.computeCompletionProposals(viewer, offset); + } + + /** + * Compute completion proposals. + * + * @param viewer the viewer + * @param offset the offset + * @return the i completion proposal[] + */ + @Override + public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) { + setContentAssistDefaultValues(); + if (lookupTemplates) { + return makeTemplateProposals(viewer, offset); + } + if (isPartitionContainSQLComment(viewer, offset)) { + return new ICompletionProposal[] { + new FakeCompletionProposal(MessageConfigLoader.getProperty(IMessagesConstants.NO_PROPOSAL), offset)}; + } + timer = new ExecTimer(" Autosuggest Object Load Time "); + timer.start(); + core = new ContentAssistProcesserCore(database); + + String fullContent = viewer.getDocument().get(); + String fullPretext = null; + String prefix = null; + SortedMap aliasMap = null; + + if (validateFullText(fullContent)) { + fullPretext = fullContent.substring(0, offset); + prefix = core.findString(fullPretext, DatabaseUtils.getCharacterList(database)); + if (canCheckForAlias(viewer)) { + assistant.enableAutoInsert(true); + assistant.setShowEmptyList(true); + SQLContentAssistAliasProcessor aliasProcessor = new SQLContentAssistAliasProcessor(prefix, fullContent, + offset, DatabaseUtils.getCharacterList(database)); + + boolean isSuccess = aliasProcessor.computeAliasProposal(core); + if (isSuccess) { + prefix = aliasProcessor.getProcessedPrefix(); + aliasMap = aliasProcessor.getComputedAliasMap(); + } + } + } + getValidAutoSuggestList(fullPretext, prefix); + addAutoMapAndSetup(aliasMap); + assistant.setCurrentPrefix(core.getCurrentPrefix()); + boolean isLoading = false; + if (null == autoMap) { + return new ICompletionProposal[0]; + } else { + isLoading = loadUnloadedData(); + } + clearAliasMap(aliasMap); + return prepareCompletionProposal(autoMap, offset, core.getReplaceLength(), isLoading, viewer); + + } + + private boolean validateFullText(String fullContent) { + return null != fullContent && !fullContent.isEmpty(); + } + + private void setContentAssistDefaultValues() { + assistant.enableAutoInsert(false); + assistant.setShowEmptyList(false); + assistant.setCurrentPrefix(new String[0]); + this.assistant.setEmptyMessage(MessageConfigLoader.getProperty(IMessagesConstants.NO_PROPOSAL)); + } + + private void getValidAutoSuggestList(String fullPretext, String prefix) { + if (!MPPDBIDEConstants.INVALID_INSERT.equals(prefix)) { + autoMap = core.getContextProposals(prefix, fullPretext); + } + } + + private boolean canCheckForAlias(ITextViewer viewer) { + SourceViewer view = (SourceViewer) viewer; + boolean isAliasCheck = false; + if (view != null && view.getData("ISALIASCHECK") != null) { + isAliasCheck = ((Boolean) view.getData("ISALIASCHECK")).booleanValue(); + } + return isAliasCheck; + } + + /** + * Load unloaded data. + * + * @return true, if successful + */ + private boolean loadUnloadedData() { + boolean isLoading = false; + if (validateForNonLoaded()) { + isLoading = true; + // start + final BottomStatusBar btmStatusBar = UIElement.getInstance().getProgressBarOnTop(); + StatusMessage statMsg = new StatusMessage( + MessageConfigLoader.getProperty(IMessagesConstants.STATUS_MSG_AUTO_SUGGEST)); + AutoSuggestWorker job = new AutoSuggestWorker(MPPDBIDEConstants.CANCELABLEJOB, core.getCurrentPrefix(), + statMsg); + job.setTaskDB(database); + StatusMessageList.getInstance().push(statMsg); + activateBottomStatusbar(btmStatusBar); + // end + job.schedule(); + } + return isLoading; + } + + private boolean validateForNonLoaded() { + return database != null && core != null && !database.isLoadingNamespaceInProgress() + && core.isAnyNonLoadedObject(); + } + + /** + * Clear alias map. + * + * @param aliasMap the alias map + */ + private void clearAliasMap(SortedMap aliasMap) { + if (null != aliasMap) { + aliasMap.clear(); + } + } + + /** + * Checks if is partition contain SQL comment. + * + * @param viewer the viewer + * @param offset the offset + * @return true, if is partition contain SQL comment + */ + private boolean isPartitionContainSQLComment(ITextViewer viewer, int offset) { + try { + ITypedRegion region = (ITypedRegion) DSDefaultCharacterPairMatcherUtil.getRegion(viewer.getDocument(), + offset, new CharPairsUtil(new char[0]), true, DSDefaultCharacterPairMatcherUtil.SQL_PARTITIONING, + false, true); + + if (null != region) { + String partition = region.getType(); + return partition.equals(DSDefaultCharacterPairMatcherUtil.SQL_COMMENT) + || partition.equals(DSDefaultCharacterPairMatcherUtil.SQL_MULTILINE_COMMENT) + || partition.equals(DSDefaultCharacterPairMatcherUtil.SINGLE_LINE_COMMENT); + } + } catch (BadLocationException exception) { + MPPDBIDELoggerUtility.error( + "SQLContentAssistProcessor: BadLocationException occurred while getting partition.", exception); + } + return false; + } + + /** + * Activate bottom statusbar. + * + * @param btmStatusBar the btm status bar + */ + private void activateBottomStatusbar(final BottomStatusBar btmStatusBar) { + if (btmStatusBar != null) { + btmStatusBar.activateStatusbar(); + } + } + + /** + * Adds the auto map and setup. + * + * @param aliasMap the alias map + */ + private void addAutoMapAndSetup(SortedMap aliasMap) { + if (null != aliasMap && !aliasMap.isEmpty()) { + autoMap.putAll(aliasMap); + } + + if (((UserPreference) UserPreference.getInstance()).isIsenableTestability()) { + setMap(autoMap); + } + } + + /** + * Prepare completion proposal. + * + * @param serverObjMap the server obj map + * @param offset the offset + * @param lastWordLen the last word len + * @param isLoading the is loading + * @param viewer the viewer + * @return the i completion proposal[] + */ + private ICompletionProposal[] prepareCompletionProposal(LinkedHashMap serverObjMap, + int offset, int lastWordLen, boolean isLoading, ITextViewer viewer) { + boolean isAutoSuggest = true; + int itemCount = 0; + String message = null; + ArrayList proposals = new ArrayList(itemCount); + if (validateMap(serverObjMap, isLoading)) { + message = MessageConfigLoader.getProperty(IMessagesConstants.AUTO_SUGGEST_LOADING); + return new ICompletionProposal[] {new FakeCompletionProposal(message, offset)}; + } + + itemCount = serverObjMap.size(); + + ICompletionProposal[] proposalArray = null; + proposalArray = getProposalArray(isLoading, itemCount); + String objectName = null; + Iterator> itr = serverObjMap.entrySet().iterator(); + while (itr.hasNext()) { + Entry entry = (Entry) itr.next(); + ServerObject obj = entry.getValue(); + + objectName = obj.getAutoSuggestionName(isAutoSuggest); + + if (offset < lastWordLen) { + return new ICompletionProposal[0]; + } + addProposal(offset, lastWordLen, proposals, objectName, entry, obj); + } + addLabelIfLoading(offset, isLoading, proposals); + isAutoSuggest = false; + postCompleteOperation(serverObjMap); + + return proposals.toArray(proposalArray); + } + + private boolean validateMap(LinkedHashMap serverObjMap, boolean isLoading) { + return (null == serverObjMap || 0 == serverObjMap.size()) && isLoading; + } + + private void addProposal(int offset, int lastWordLen, ArrayList proposals, String objectName, + Entry entry, ServerObject obj) { + CompletionProposal proposal = null; + if (null != objectName) { + proposal = new CompletionProposal(objectName, offset - lastWordLen, lastWordLen, objectName.length(), + getImageFor(obj.getType()), entry.getKey(), null, null); + proposals.add(proposal); + } + } + + private void postCompleteOperation(LinkedHashMap serverObjMap) { + try { + timer.stopAndLog(); + serverObjMap.clear(); + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("Exception while getting elapsed time", exception); + } + } + + private void addLabelIfLoading(int offset, boolean isLoading, ArrayList proposals) { + if (isLoading) { + proposals.add(new FakeCompletionProposal( + MessageConfigLoader.getProperty(IMessagesConstants.AUTO_SUGGEST_LOADING), offset)); + } + } + + private ICompletionProposal[] getProposalArray(boolean isLoading, int itemCount) { + ICompletionProposal[] proposalArray; + if (isLoading) { + proposalArray = new ICompletionProposal[itemCount + 1]; + } else { + proposalArray = new ICompletionProposal[itemCount]; + } + return proposalArray; + } + + /** + * Compute context information. + * + * @param viewer the viewer + * @param offset the offset + * @return the i context information[] + */ + @Override + public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) { + + return new IContextInformation[0]; + } + + /** + * Gets the completion proposal auto activation characters. + * + * @return the completion proposal auto activation characters + */ + @Override + public char[] getCompletionProposalAutoActivationCharacters() { + // Bug Fix: Auto activation showing templates after template hot key + // pressed and closed. + // Setting flag as false so that auto activator shows DB Objects, only + // if popup is not active + if (!assistant.isProposalPopupActive()) { + SQLContentAssistProcessor.setLookupTemplates(false); + } + + return ".".toCharArray(); + } + + /** + * Gets the context information auto activation characters. + * + * @return the context information auto activation characters + */ + @Override + public char[] getContextInformationAutoActivationCharacters() { + + return new char[0]; + } + + /** + * Gets the error message. + * + * @return the error message + */ + @Override + public String getErrorMessage() { + + return null; + } + + /** + * Gets the context information validator. + * + * @return the context information validator + */ + @Override + public IContextInformationValidator getContextInformationValidator() { + + return null; + } + + /** + * Gets the image for. + * + * @param type the type + * @return the image for + */ + private Image getImageFor(OBJECTTYPE type) { + String iconName = IcoPathMapper.getImagePathForObject(type); + if (null != iconName) { + return IconUtility.getIconImage(iconName, this.getClass()); + } + return null; + } + + /** + * Sets the database. + * + * @param database the new database + */ + public void setDatabase(Database database) { + this.database = database; + } + + /** + * Sets the map. + * + * @param map the map + */ + public static void setMap(LinkedHashMap map) { + SQLContentAssistProcessor.map = map; + } + + /** + * Gets the map. + * + * @return the map + */ + public static LinkedHashMap getMap() { + return SQLContentAssistProcessor.map; + } + + /** + * + * Title: class + * + * Description: The Class AutoSuggestWorker. + */ + private final class AutoSuggestWorker extends UIWorkerJob { + + private String[] prefixes; + + private DBConnection connection = null; + private StatusMessage statMsg; + + /** + * Instantiates a new auto suggest worker. + * + * @param family the family + * @param prefixes the prefixes + * @param statMsg the stat msg + */ + public AutoSuggestWorker(Object family, String[] prefixes, StatusMessage statMsg) { + super(MessageConfigLoader.getProperty(IMessagesConstants.STATUS_MSG_AUTO_SUGGEST), family); + this.prefixes = prefixes; + this.statMsg = statMsg; + } + + @Override + public Object doJob() + throws DatabaseOperationException, DatabaseCriticalException, MPPDBIDEException, Exception { + connection = database.getConnectionManager().getFreeConnection(); + core.findNonLoadedDatabaseObjectsOnDemand(connection); + return null; + } + + @Override + public void onSuccessUIAction(Object obj) { + if (isSameSuggestionActive()) { + assistant.hide(); + assistant.showPossibleCompletions(); + } + + /* Trigger refresh of loaded schema in OB */ + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + try { + String schemaName = ""; + if (prefixes.length > 0) { + /* Schema name is the 1st element in prefix array */ + schemaName = prefixes[0]; + } + + if (schemaName.isEmpty()) { + return; + } + + INamespace schema = database.getNameSpaceByName(schemaName); + ObjectBrowser objectBrowserModel = UIElement.getInstance().getObjectBrowserModel(); + if (null != objectBrowserModel) { + objectBrowserModel.refreshObject(schema); + } + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("Error while fetching objects from Database", exception); + return; + } + } + + }); + } + + /** + * Checks if is same suggestion active. + * + * @return true, if is same suggestion active + */ + private boolean isSameSuggestionActive() { + String[] currentPrefix = assistant.getCurrentPrefix(); + boolean isSame = false; + for (int index = 0; index < currentPrefix.length && index < prefixes.length; ++index) { + if (currentPrefix[index] != null && prefixes[index] != null + && currentPrefix[index].equals(prefixes[index])) { + isSame = true; + } else { + return false; + } + } + return isSame && assistant.isProposalPopupActive(); + } + + @Override + public void onMPPDBIDEExceptionUIAction(MPPDBIDEException exception) { + MPPDBIDELoggerUtility.error("Error while initializing the SQL Connection", exception); + assistant.hide(); + } + + @Override + public void onCriticalExceptionUIAction(DatabaseCriticalException exception) { + MPPDBIDELoggerUtility.error("SQLContentAssistProcessor: Critical exception occurred.", exception); + assistant.hide(); + } + + @Override + public void onOperationalExceptionUIAction(DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("SQLContentAssistProcessor: Operation exception occurred.", exception); + assistant.hide(); + } + + @Override + public void finalCleanup() { + if (connection != null) { + database.getConnectionManager().releaseConnection(connection); + } + } + + @Override + public void finalCleanupUI() { + BottomStatusBar btstat = UIElement.getInstance().getProgressBarOnTop(); + if (btstat != null) { + btstat.hideStatusbar(this.statMsg); + } + } + + @Override + protected void canceling() { + super.canceling(); + try { + if (connection != null) { + connection.cancelQuery(); + } + } catch (Exception exception) { + MPPDBIDELoggerUtility.error("Cancel Query for autosuggest failed", exception); + } + } + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLDocumentPartitioner.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLDocumentPartitioner.java new file mode 100644 index 0000000000000000000000000000000000000000..84b42196bd1143a11b4e620d34959da193f54218 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLDocumentPartitioner.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IDocumentExtension3; +import org.eclipse.jface.text.IDocumentPartitioner; +import org.eclipse.jface.text.rules.FastPartitioner; +import org.eclipse.jface.text.rules.IPartitionTokenScanner; + +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class SQLDocumentPartitioner. + * + * @since 3.0.0 + */ +public class SQLDocumentPartitioner extends FastPartitioner { + + /** + * Instantiates a new SQL document partitioner. + * + * @param scanner the scanner + * @param legalContentTypes the legal content types + */ + public SQLDocumentPartitioner(IPartitionTokenScanner scanner, String[] legalContentTypes) { + super(scanner, legalContentTypes); + } + + /** + * Gets the content types. + * + * @return the content types + */ + public static String[] getContentTypes() { + return new String[] {SQLPartitionScanner.SQL_COMMENT, SQLPartitionScanner.SQL_MULTILINE_COMMENT, + SQLPartitionScanner.SQL_STRING, SQLPartitionScanner.SQL_DOUBLE_QUOTES_IDENTIFIER}; + } + + /** + * Connect document. + * + * @param doc the doc + */ + public static void connectDocument(IDocument doc, double fileSize) { + IDocumentExtension3 ext3Doc = (IDocumentExtension3) doc; + + SQLPartitionScanner scanner = new SQLPartitionScanner(); + IDocumentPartitioner sqlPartitioner = new SQLDocumentPartitioner(scanner, getContentTypes()); + sqlPartitioner.connect(doc); + if (fileSize <= MPPDBIDEConstants.FILE_LIMIT_FOR_SYNTAX_COLOR) { + ext3Doc.setDocumentPartitioner(SQLPartitionScanner.SQL_PARTITIONING, sqlPartitioner); + } + } + + /** + * clearScanner : to clear mem leak + */ + public void clearScanner() { + if (super.fScanner instanceof SQLPartitionScanner) { + SQLPartitionScanner scanner = (SQLPartitionScanner) super.fScanner; + scanner.preDestroy(); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLDoubleClickStrategy.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLDoubleClickStrategy.java new file mode 100644 index 0000000000000000000000000000000000000000..82209d24fe5c91d311b0962c2b8dda24d3374576 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLDoubleClickStrategy.java @@ -0,0 +1,199 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ITextDoubleClickStrategy; +import org.eclipse.jface.text.ITextViewer; + +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.view.utils.CharPairsUtil; +import org.opengauss.mppdbide.view.utils.DSDefaultCharacterPairMatcherUtil; +import org.opengauss.mppdbide.view.utils.DSRegion; + +/** + * + * Title: class + * + * Description: The Class SQLDoubleClickStrategy. + * + * @since 3.0.0 + */ +public class SQLDoubleClickStrategy implements ITextDoubleClickStrategy { + + /** + * The text. + */ + protected ITextViewer fText; + + /** + * The current position. + */ + protected int currentPosition; + + /** + * The start position. + */ + protected int startPosition; + + /** + * The end position. + */ + protected int endPosition; + + /** + * Instantiates a new SQL double click strategy. + */ + public SQLDoubleClickStrategy() { + super(); + } + + /** + * Double clicked. + * + * @param viewer the viewer + */ + @Override + public void doubleClicked(ITextViewer viewer) { + /* Get the viewer we are dealing with. */ + fText = viewer; + + /* Get the double-click location in the document. */ + currentPosition = viewer.getSelectedRange().x; + + if (currentPosition < 0 || currentPosition > fText.getDocument().getLength()) { + return; + } + + try { + if (!selectBracketBlock()) { + selectWord(); + } + } catch (BadLocationException exception) { + // do nothing + MPPDBIDELoggerUtility.error("SQLDoubleClickStrategy.doubleClicked(): BadLocationException occurred.", + exception); + } + } + + /** + * Match brackets at. + * + * @return true, if successful + * @throws BadLocationException the bad location exception + */ + protected boolean matchBracketsAt() throws BadLocationException { + boolean isForward = true; + CharPairsUtil fPairs = new CharPairsUtil(DSDefaultCharacterPairMatcherUtil.getMatchPunctuations()); + + DSRegion region = (DSRegion) DSDefaultCharacterPairMatcherUtil.getRegion(fText.getDocument(), currentPosition, + fPairs, isForward, DSDefaultCharacterPairMatcherUtil.SQL_PARTITIONING, true, false); + if (null != region) { + String partition = null != region.getPartitionType() ? region.getPartitionType() : ""; + if ((partition.equals(DSDefaultCharacterPairMatcherUtil.SQL_DOUBLE_QUOTES_IDENTIFIER) + || partition.equals(DSDefaultCharacterPairMatcherUtil.SQL_STRING)) && region.getForward()) { + startPosition = region.getOffset() - 1; + endPosition = region.getOffset() + region.getLength() - 1; + return true; + } else { + startPosition = region.getOffset(); + endPosition = region.getOffset() + region.getLength() - 1; + return true; + } + } + + return false; + + } + + /** + * Match word. + * + * @return true, if successful + */ + protected boolean matchWord() { + IDocument doc = fText.getDocument(); + + try { + int position = currentPosition; + char chr; + + // Scan back to get the beginning of the word. + while (position >= 0) { + chr = doc.getChar(position); + if (!Character.isJavaIdentifierPart(chr)) { + break; + } + --position; + } + startPosition = position; + + // Scan forward for the end of the word. + position = currentPosition; + int length = doc.getLength(); + while (position < length) { + chr = doc.getChar(position); + if (!Character.isJavaIdentifierPart(chr)) { + break; + } + ++position; + } + endPosition = position; + + return true; + } catch (BadLocationException exception) { + // do nothing + MPPDBIDELoggerUtility.error("SQLDoubleClickStrategy.matchWord(): BadLocationException occurred.", + exception); + } + + return false; + } + + /** + * Select bracket block. + * + * @return true, if successful + * @throws BadLocationException the bad location exception + */ + protected boolean selectBracketBlock() throws BadLocationException { + if (matchBracketsAt()) { + if (startPosition == endPosition) { + fText.setSelectedRange(startPosition, 0); + } else { + fText.setSelectedRange(startPosition + 1, endPosition - startPosition - 1); + } + + return true; + } + return false; + } + + /** + * Select word. + */ + protected void selectWord() { + if (matchWord()) { + if (startPosition == endPosition) { + fText.setSelectedRange(startPosition, 0); + } else { + fText.setSelectedRange(startPosition + 1, endPosition - startPosition - 1); + } + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLEditorHyperLink.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLEditorHyperLink.java new file mode 100644 index 0000000000000000000000000000000000000000..ace53220bf0716471b61a8b6e35f08bf278a5c07 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLEditorHyperLink.java @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import org.eclipse.core.commands.Command; +import org.eclipse.core.commands.ParameterizedCommand; +import org.eclipse.e4.core.contexts.IEclipseContext; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.hyperlink.IHyperlink; + +import org.opengauss.mppdbide.bl.serverdatacache.IDebugObject; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.eclipse.dependent.EclipseContextDSKeys; +import org.opengauss.mppdbide.eclipse.dependent.EclipseInjections; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.handler.HandlerUtilities; +import org.opengauss.mppdbide.view.handler.IHandlerUtilities; +import org.opengauss.mppdbide.view.uidisplay.UIDisplayFactoryProvider; + +/** + * + * Title: class + * + * Description: The Class SQLEditorHyperLink. + * + * @since 3.0.0 + */ +public class SQLEditorHyperLink implements IHyperlink { + private IRegion region; + private ServerObject serverObj; + + /** + * Instantiates a new SQL editor hyper link. + * + * @param region the region + * @param serverObj the server obj + */ + public SQLEditorHyperLink(IRegion region, ServerObject serverObj) { + super(); + this.region = region; + this.serverObj = serverObj; + } + + /** + * Gets the hyperlink region. + * + * @return the hyperlink region + */ + @Override + public IRegion getHyperlinkRegion() { + return this.region; + } + + /** + * Gets the type label. + * + * @return the type label + */ + @Override + public String getTypeLabel() { + return this.serverObj.getTypeLabel(); + } + + /** + * Gets the hyperlink text. + * + * @return the hyperlink text + */ + @Override + public String getHyperlinkText() { + return this.serverObj.getSearchName().trim(); + } + + /** + * Open. + */ + @Override + public void open() { + switch (serverObj.getType()) { + case SQLFUNCTION: + case PLSQLFUNCTION: + case CFUNCTION: { + if (serverObj instanceof IDebugObject) { + IDebugObject func = (IDebugObject) serverObj; + try { + HandlerUtilities.displaySourceCodeInEditor(func, false); + } catch (DatabaseOperationException exception) { + + if (!exception.getMessage().contentEquals( + MessageConfigLoader.getProperty(IMessagesConstants.ERR_BL_INVALID_STATE))) { + IHandlerUtilities.handleGetSrcCodeException(func); + } + + return; + + } catch (DatabaseCriticalException exception) { + UIDisplayFactoryProvider.getUIDisplayStateIf().handleDBCriticalError(exception, + func.getDatabase()); + return; + } + } + break; + } + case TABLEMETADATA: + case VIEW_META_DATA: + case PARTITION_TABLE: { + IEclipseContext eclipseContext = EclipseInjections.getInstance().getEclipseContext(); + eclipseContext.set(EclipseContextDSKeys.SERVER_OBJECT, serverObj); + String command = "org.opengauss.mppdbide.command.id.properties"; + + Command cmd = EclipseInjections.getInstance().getCommandService().getCommand(command); + ParameterizedCommand parameterizedCmd = new ParameterizedCommand(cmd, null); + if (EclipseInjections.getInstance().getHandlerService().canExecute(parameterizedCmd)) { + // execute the command + EclipseInjections.getInstance().getHandlerService().executeHandler(parameterizedCmd); + + } + break; + } + + default: { + break; + } + } + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLEditorParser.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLEditorParser.java new file mode 100644 index 0000000000000000000000000000000000000000..1c0a92b60c8fa6d78b9c3e3799266d087f8bfb16 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLEditorParser.java @@ -0,0 +1,332 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.rules.IToken; +import org.eclipse.swt.widgets.Display; + +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.SQLToken; +import org.opengauss.mppdbide.gauss.sqlparser.SQLTokenConstants; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.RuleBean; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.SQLScriptElement; +import org.opengauss.mppdbide.gauss.sqlparser.bean.scriptif.ScriptBlockInfo; +import org.opengauss.mppdbide.gauss.sqlparser.bean.tokendata.ISQLTokenData; +import org.opengauss.mppdbide.gauss.sqlparser.comm.SQLEditorParserBase; +import org.opengauss.mppdbide.gauss.sqlparser.comm.SQLFoldingRuleManager; +import org.opengauss.mppdbide.gauss.sqlparser.handler.AbstractCreateHandler; +import org.opengauss.mppdbide.gauss.sqlparser.handler.AbstractRuleHandler; +import org.opengauss.mppdbide.gauss.sqlparser.handler.RuleHandlerConfig; +import org.opengauss.mppdbide.gauss.sqlparser.handler.SQLUnionRuleHandler; +import org.opengauss.mppdbide.gauss.sqlparser.handlerif.RuleHandlerIf; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: SQLEditorParser + * + * @since 3.0.0 + */ +public class SQLEditorParser extends SQLEditorParserBase { + + /** + * Instantiates a new SQL editor parser. + */ + public SQLEditorParser() { + + } + + /** + * Checks if is folding enabled. + * + * @return true, if is folding enabled + */ + public boolean isFoldingEnabled() { + return true; + } + + /** + * Extract script queries. + * + * @param startOffset the start offset + * @param length the length + * @param scriptMode the script mode + * @param keepDelimiters the keep delimiters + * @param parseParameters the parse parameters + * @return the list + */ + public List extractScriptQueries(int startOffset, int length, boolean scriptMode, + boolean keepDelimiters, boolean parseParameters) { + List queryList = new ArrayList<>(); + + IDocument document = getDocument(); + if (document == null) { + return queryList; + } + + for (int queryOffset = startOffset;;) { + List query = parseQueryCheck(document, queryOffset, startOffset + length, queryOffset, + scriptMode, keepDelimiters); + if (query == null) { + break; + } + + if (query.size() > 0) { + queryList.addAll(query); + queryOffset = queryList.get(queryList.size() - 1).getOffset() + + queryList.get(queryList.size() - 1).getLength(); + } else { + break; + } + + } + + return queryList; + } + + private AbstractRuleHandler getRuleHandlarByToken(SQLToken lToken, ScriptBlockInfo curBlock) { + + AbstractRuleHandler ruleHandlarByToken = RuleHandlerConfig.getInstance().getRuleHandle(lToken.getType()); + + if (ruleHandlarByToken instanceof SQLUnionRuleHandler) { + return null; + } + + if (null == curBlock) { + return ruleHandlarByToken; + } + + RuleHandlerIf currentRuleHandler = curBlock.getAbstractRuleHandler(); + + if ((lToken.getType() == SQLTokenConstants.T_SQL_DDL_CREATE_FUNC + || lToken.getType() == SQLTokenConstants.T_SQL_DDL_CREATE_PROC)) { + if (currentRuleHandler instanceof AbstractCreateHandler) { + AbstractCreateHandler createhandlar = (AbstractCreateHandler) currentRuleHandler; + boolean packageStmt = createhandlar.isPackageStmt(currentRuleHandler, curBlock, lToken); + if (packageStmt) { + return ruleHandlarByToken; + } + } + return null; + } + + if (currentRuleHandler.isRuleHandlerValid(ruleHandlarByToken, curBlock, lToken)) { + return ruleHandlarByToken; + } + + return null; + + } + + /** + * Parses the query check. + * + * @param document the document + * @param startPos the start pos + * @param endPos the end pos + * @param currentPos the current pos + * @param scriptMode the script mode + * @param keepDelimiters the keep delimiters + * @return the list + */ + protected List parseQueryCheck(final IDocument document, final int startPos, final int endPos, + final int currentPos, final boolean scriptMode, final boolean keepDelimiters) { + if (endPos - startPos <= 0) { + return null; + } + return parseQuery(document, startPos, endPos, currentPos, scriptMode, keepDelimiters); + } + + /** + * Parses the query. + * + * @param document the document + * @param startPos the start pos + * @param endPos the end pos + * @param currentPos the current pos + * @param scriptMode the script mode + * @param keepDelimiters the keep delimiters + * @return the list + */ + protected List parseQuery(final IDocument document, final int startPos, final int endPos, + final int currentPos, final boolean scriptMode, final boolean keepDelimiters) { + List lretList = new ArrayList(); + ruleManager.setRange(document, startPos, endPos - startPos); + ScriptBlockInfo curBlock = null; + for (;;) { + IToken token = ruleManager.nextToken(); + int tokenOffset = ruleManager.getTokenOffset(); + int tokenLength = ruleManager.getTokenLength(); + String currentToken = getCurrentToken(tokenOffset, tokenLength); + int tokenType = token instanceof SQLToken ? ((SQLToken) token).getType() : SQLTokenConstants.T_SQL_UNKNOWN; + if (tokenOffset < startPos) { + // This may happen with EOF tokens (bug in jface?) + return lretList; + } + ISQLTokenData sqlTokenData = getSQLTokenData(ruleManager, token, currentToken); + // if it is not of the token specified then can return handle + // optional token end + RuleBean optRuleBean = checkBlockEndWithOptionalToken(lretList, curBlock, token, tokenType, currentToken); + if (null != optRuleBean) { + curBlock = optRuleBean.getScriptBlockInfo(); + if (optRuleBean.isContinueLoop()) { + continue; + } + if (null == curBlock) { + return lretList; + } + } + if (tokenType != SQLTokenConstants.T_SQL_UNKNOWN) { + // 1. if the curBlock is null then get the handler by token + AbstractRuleHandler ruleHandlarByToken = getRuleHandlarByToken((SQLToken) token, curBlock); + if (null == curBlock) { + if (null == ruleHandlarByToken) { + // some thing went wrong the token is not associated + // with handler the token in not folding token + continue; + } + curBlock = ruleHandlarByToken.createScriptBlock(null, sqlTokenData, tokenOffset); + } else { + // get rule manager wrapper + curBlock.setCurrentKnownToken(currentToken); + curBlock = getCurrentBlockHandle(lretList, curBlock, token, ruleHandlarByToken, sqlTokenData); + if (null == curBlock) { + return handleEndLineStmt(lretList, ruleManager, document); + } + addLastKnownTokenDetails(curBlock, tokenOffset, tokenLength, currentToken); + if (curBlock.isInvokeParent()) { + curBlock = getCurrentBlockHandle(lretList, curBlock, token, ruleHandlarByToken, sqlTokenData); + if (null == curBlock) { + return handleEndLineStmt(lretList, ruleManager, document); + } + } + } + } + handleLastTokenData(curBlock, token, tokenOffset, tokenLength, currentToken); + if (token.isEOF()) { + return getEOFRetVal(curBlock, lretList); + } + } + } + + private List handleEndLineStmt(List lretList, SQLFoldingRuleManager ruleManager, + IDocument document) { + if (!lretList.isEmpty()) { + ruleManager.nextToken(); + int tokenOffset = ruleManager.getTokenOffset(); + int tokenLength = ruleManager.getTokenLength(); + String currentToken = getCurrentToken(tokenOffset, tokenLength); + + // the below condition will be matched + // and after the statement is the EOF and there is no new line chars + // is available + // Happens only in windows. + + if ("\r".equalsIgnoreCase(currentToken)) { + while (!ruleManager.nextToken().isEOF()) { + int tokenOffsetN = ruleManager.getTokenOffset(); + int tokenLengthN = ruleManager.getTokenLength(); + currentToken = getCurrentToken(tokenOffsetN, tokenLengthN); + + if ("\n".equalsIgnoreCase(currentToken)) { + + Display.getDefault().syncExec(new Runnable() { + @Override + public void run() { + try { + document.replace(tokenOffset, (tokenOffsetN + tokenLengthN) - tokenOffset, + System.lineSeparator() + document.get(tokenOffset + tokenLength, + tokenOffsetN - (tokenOffset + tokenLength))); + } catch (BadLocationException badPadEx) { + MPPDBIDELoggerUtility.error( + "Exception while Document replace while Folding and Unfolding Change", + badPadEx); + } + + } + }); + return lretList; + } + + } + + } + } + + return lretList; + + } + + /** + * Check block end with optional token. + * + * @param lretList the lret list + * @param curBlock the cur block + * @param token the token + * @param tokenType the token type + * @param currentToken the current token + * @return the rule bean + */ + public RuleBean checkBlockEndWithOptionalToken(List lretList, ScriptBlockInfo curBlock, + IToken token, int tokenType, String currentToken) { + RuleBean ruleBean = null; + + if (null == currentToken || StringUtils.isEmpty(currentToken.trim())) { + return null; + } + + if (null != curBlock && curBlock.getNextOptTokenToEnd() != SQLTokenConstants.T_SQL_UNKNOWN) { + + if (curBlock.getNextOptTokenToEnd() == tokenType) { + ISQLTokenData sqlTokenData = getSQLTokenData(ruleManager, token, currentToken); + ruleBean = curBlock.getAbstractRuleHandler().endOptionalScript(curBlock, lretList, getSQLToken(token), + sqlTokenData); + + ruleBean.setContinueLoop(true); + + } else if (curBlock.getNextMiddleOptTokenToEnd() == tokenType) { + ruleBean = new RuleBean(); + ruleBean.setScriptBlockInfo(curBlock); + ruleBean.setContinueLoop(true); + + } else { + + ISQLTokenData lastTokenData = getSQLTokenData(ruleManager, token, currentToken); + lastTokenData.setTokenLength(curBlock.getLastKnownTokenlenght()); + lastTokenData.setTokenOffset(curBlock.getLastKnownTokenOffSet()); + + SQLToken dummyToken = null; + + if (!(token instanceof SQLToken)) { + dummyToken = new SQLToken(SQLTokenConstants.T_SQL_DUMMY, SQLFoldingConstants.SQL_TOKEN_DUMMY); + } else { + dummyToken = (SQLToken) token; + } + + ruleBean = curBlock.getAbstractRuleHandler().endOptionalScript(curBlock, lretList, dummyToken, + lastTokenData); + } + + } + return ruleBean; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLEditorPlugin.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLEditorPlugin.java new file mode 100644 index 0000000000000000000000000000000000000000..41a32f5d48a309a25d6fd25513e94246ee870a2e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLEditorPlugin.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import org.eclipse.ui.plugin.AbstractUIPlugin; + +import org.opengauss.mppdbide.adapter.keywordssyntax.SQLSyntax; + +/** + * + * Title: class + * + * Description: The Class SQLEditorPlugin. + * + * @since 3.0.0 + */ +public class SQLEditorPlugin extends AbstractUIPlugin { + private static volatile SQLEditorPlugin plugin = null; + private static volatile SQLSyntaxColorProvider colorProvider = null; + private SQLCodeScanner codeScanner = null; + + /** + * The Constant SQL_PARTITIONING. + */ + public static final String SQL_PARTITIONING = "__sql_partitioning"; // $NON-NLS-1$ + + private SQLPartitionScanner fPartitionScanner; + private static final Object INSTANCE_LOCK = new Object(); + + /** + * Gets the partition scanner. + * + * @return the partition scanner + */ + public SQLPartitionScanner getPartitionScanner() { + if (fPartitionScanner == null) { + fPartitionScanner = new SQLPartitionScanner(); + } + return fPartitionScanner; + } + + /** + * Gets the default. + * + * @return the default + */ + public static SQLEditorPlugin getDefault() { + if (null == plugin) { + synchronized (INSTANCE_LOCK) { + if (null == plugin) { + plugin = new SQLEditorPlugin(); + } + } + } + return plugin; + } + + /** + * Gets the color provider. + * + * @return the color provider + */ + public SQLSyntaxColorProvider getColorProvider() { + if (null == colorProvider) { + synchronized (INSTANCE_LOCK) { + if (null == colorProvider) { + colorProvider = new SQLSyntaxColorProvider(); + } + } + } + return colorProvider; + } + + /** + * Gets the SQL code scanner. + * + * @param sqlSyntax the sql syntax + * @return the SQL code scanner + */ + public SQLCodeScanner getSQLCodeScanner(SQLSyntax sqlSyntax) { + if (null == codeScanner && sqlSyntax != null) { + codeScanner = new SQLCodeScanner(sqlSyntax); + } + + return codeScanner; + } + + /** + * Sets the SQL code scanner. + * + * @param sqlSyntax the new SQL code scanner + */ + public void setSQLCodeScanner(SQLSyntax sqlSyntax) { + codeScanner = getSQLCodeScanner(sqlSyntax); + + if (codeScanner != null) { + codeScanner = null; + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLObjectHyperLinkPresenter.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLObjectHyperLinkPresenter.java new file mode 100644 index 0000000000000000000000000000000000000000..b3645fd23b6d4641033db6a5a36ee2922083ffe8 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLObjectHyperLinkPresenter.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import org.eclipse.jface.text.hyperlink.IHyperlink; +import org.eclipse.jface.text.hyperlink.MultipleHyperlinkPresenter; +import org.eclipse.swt.graphics.RGB; + +/** + * + * Title: class + * + * Description: The Class SQLObjectHyperLinkPresenter. + * + * @since 3.0.0 + */ +public class SQLObjectHyperLinkPresenter extends MultipleHyperlinkPresenter { + + /** + * Instantiates a new SQL object hyper link presenter. + */ + public SQLObjectHyperLinkPresenter() { + super(new RGB(0, 0, 255)); + } + + /** + * Show hyperlinks. + * + * @param hyperlinks the hyperlinks + */ + @Override + public void showHyperlinks(IHyperlink[] hyperlinks) { + super.showHyperlinks(hyperlinks); + } + + /** + * Can show multiple hyperlinks. + * + * @return true, if successful + */ + @Override + public boolean canShowMultipleHyperlinks() { + return true; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLObjectLinkDetector.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLObjectLinkDetector.java new file mode 100644 index 0000000000000000000000000000000000000000..d38851ee1f3a462195fdaf7c7bbb73325b9ad0f1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLObjectLinkDetector.java @@ -0,0 +1,465 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.Region; +import org.eclipse.jface.text.hyperlink.AbstractHyperlinkDetector; +import org.eclipse.jface.text.hyperlink.IHyperlink; + +import org.opengauss.mppdbide.bl.contentassist.ContentAssistProcesserData; +import org.opengauss.mppdbide.bl.contentassist.ContentAssistUtilIf; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; + +/** + * + * Title: class + * + * Description: The Class SQLObjectLinkDetector. + * + * @since 3.0.0 + */ +public class SQLObjectLinkDetector extends AbstractHyperlinkDetector { + private Database database = null; + private static final int OBJECTS_WITHOUT_SCHEMA = 1; + private static final int OBJECTS_WITH_SCHEMA = 2; + private static final int OBJECTS_ONLY_SCHEMAS = 3; + private ContentAssistUtilIf contentAssistUtil; + private ContentAssistProcesserData contentAssistProcesserData; + + /** + * Detect hyperlinks. + * + * @param textViewer the text viewer + * @param region the region + * @param canShowMultipleHyperlinks the can show multiple hyperlinks + * @return the i hyperlink[] + */ + @Override + public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { + if (null == getDabase() || !getDabase().isConnected()) { + return null; + } + contentAssistProcesserData = new ContentAssistProcesserData(getDabase()); + contentAssistUtil = contentAssistProcesserData.getContentAssistUtil(); + + IDocument doc = textViewer.getDocument(); + int offset = region.getOffset(); + String fullContent = doc.get(); + int searchEnd = getSearchEnd(fullContent, offset); + + String neededstring = fullContent.substring(0, searchEnd); + int searchStart = getSearchStartPos(neededstring); + neededstring = getSearchString(neededstring, searchStart); + + String searchPrefix = neededstring; + + if (null == searchPrefix) { + return null; + } + + String[] prefixes = contentAssistUtil.getPrefixHyperLink(searchPrefix); + + if (prefixes.length == 2) { + if (prefixes[0].trim().startsWith("\"")) { + searchStart = searchStart + 1; + } + } + SortedMap map = resolveCurrentItemProposal(getDabase(), prefixes); + + if (null == map || 0 == map.size()) { + return null; + } + IHyperlink[] links = new IHyperlink[map.size()]; + int index = 0; + for (ServerObject obj : map.values()) { + + links[index] = createHyperLink(searchStart, searchEnd - searchStart, obj); + index++; + } + return links; + } + + /** + * Gets the search string. + * + * @param fullPretext the full pretext + * @param pos the pos + * @return the search string + */ + private String getSearchString(String fullPretext, int pos) { + String retStr; + + if (-1 == pos) { + return null; + } + + retStr = fullPretext.substring(pos); + + if ("".equals(retStr)) { + return null; + } + return retStr; + } + + /** + * Resolve current item proposal. + * + * @param db the db + * @param prefixes the prefixes + * @return the sorted map + */ + public SortedMap resolveCurrentItemProposal(Database db, String[] prefixes) { + int prefixLength = prefixes.length; + SortedMap retMap = new TreeMap(); + + if (null == db || !db.isConnected()) { + return null; + } + switch (prefixLength) { + case 1: { + retMap = handleOnPrefLengthisOne(db, prefixes, prefixLength); + break; + } + case 2: { + retMap = handleOnprefLengthisTwo(db, prefixes, prefixLength); + break; + } + default: { + break; + } + } + + return retMap; + } + + /** + * Handle onpref lengthis two. + * + * @param db the db + * @param prefixes the prefixes + * @param prefixLength the prefix length + * @return the sorted map + */ + private SortedMap handleOnprefLengthisTwo(Database db, String[] prefixes, int prefixLength) { + SortedMap retMap; + String strPrefix = ""; + strPrefix = prefixes[0]; + // Can be Schema.Table + retMap = new TreeMap(); + retMap = findMatchingCaseInsensitiveObjects(db, strPrefix, retMap, 3); + if (!strPrefix.contains("\"")) { + retMap = getMatchingObjectsIfContaindQuotes(db, retMap, strPrefix); + } + strPrefix = prefixes[1]; + SortedMap retMap1 = findMatchingCaseInsensitiveObjects(db, strPrefix, retMap, + prefixLength); + if (!strPrefix.contains("\"")) { + handleIfPrefContainQuotes(db, prefixLength, retMap, strPrefix, retMap1); + } + retMap = new TreeMap(); + retMap.putAll(retMap1); + // Get the object and find the child + return retMap; + } + + /** + * Gets the matching objects if containd quotes. + * + * @param db the db + * @param retMapParam the ret map param + * @param strPrefix the str prefix + * @return the matching objects if containd quotes + */ + private SortedMap getMatchingObjectsIfContaindQuotes(Database db, + SortedMap retMapParam, String strPrefix) { + SortedMap retMap = retMapParam; + if (!strPrefix.equals(strPrefix.toUpperCase(Locale.ENGLISH))) { + retMap = findMatchingCaseInsensitiveObjects(db, strPrefix.toUpperCase(Locale.ENGLISH), retMap, 3); + } + if (!strPrefix.equals(strPrefix.toLowerCase(Locale.ENGLISH))) { + retMap = findMatchingCaseInsensitiveObjects(db, strPrefix.toLowerCase(Locale.ENGLISH), retMap, 3); + } + return retMap; + } + + /** + * Handle if pref contain quotes. + * + * @param db the db + * @param prefixLength the prefix length + * @param retMap the ret map + * @param strPrefix the str prefix + * @param retMap1 the ret map 1 + */ + private void handleIfPrefContainQuotes(Database db, int prefixLength, SortedMap retMap, + String strPrefix, SortedMap retMap1) { + if (!strPrefix.equals(strPrefix.toUpperCase(Locale.ENGLISH))) { + retMap1.putAll(findMatchingCaseInsensitiveObjects(db, strPrefix.toUpperCase(Locale.ENGLISH), retMap, + prefixLength)); + } + if (!strPrefix.equals(strPrefix.toLowerCase(Locale.ENGLISH))) { + retMap1.putAll(findMatchingCaseInsensitiveObjects(db, strPrefix.toLowerCase(Locale.ENGLISH), retMap, + prefixLength)); + } + } + + /** + * Handle on pref lengthis one. + * + * @param db the db + * @param prefixes the prefixes + * @param prefixLength the prefix length + * @return the sorted map + */ + private SortedMap handleOnPrefLengthisOne(Database db, String[] prefixes, int prefixLength) { + SortedMap retMap; + String strPrefix = ""; + strPrefix = prefixes[0]; + + // 1. Table name + retMap = new TreeMap(); + retMap = findMatchingCaseInsensitiveObjects(db, strPrefix, retMap, prefixLength); + if (!strPrefix.contains("\"")) { + if (!strPrefix.equals(strPrefix.toUpperCase(Locale.ENGLISH))) { + retMap = findMatchingCaseInsensitiveObjects(db, strPrefix.toUpperCase(Locale.ENGLISH), retMap, + prefixLength); + } + if (!strPrefix.equals(strPrefix.toLowerCase(Locale.ENGLISH))) { + retMap = findMatchingCaseInsensitiveObjects(db, strPrefix.toLowerCase(Locale.ENGLISH), retMap, + prefixLength); + } + } + return retMap; + } + + /** + * Find matching case insensitive objects. + * + * @param db the db + * @param prefix the prefix + * @param retMapParam the ret map param + * @param objLevel the obj level + * @return the sorted map + */ + private SortedMap findMatchingCaseInsensitiveObjects(Database db, String prefix, + SortedMap retMapParam, int objLevel) { + SortedMap retMap = retMapParam; + if (OBJECTS_WITHOUT_SCHEMA == objLevel) { + retMap.putAll(contentAssistUtil.findExactMatchingTables(prefix)); + retMap.putAll(contentAssistUtil.findExactMatchingDebugObjects(prefix)); + retMap.putAll(contentAssistUtil.findExactMatchingViews(prefix)); + } + if (OBJECTS_ONLY_SCHEMAS == objLevel) { + retMap.putAll(findMatchingChildObjects(prefix)); + } + if (OBJECTS_WITH_SCHEMA == objLevel) { + retMap = findMatchingInChild(retMap, prefix); + } + + return retMap; + } + + /** + * Find matching child objects. + * + * @param prefix the prefix + * @return the sorted map + */ + public SortedMap findMatchingChildObjects(String prefix) { + SortedMap retObj = new TreeMap(); + retObj.putAll(contentAssistUtil.findExactMatchingNamespaces(prefix)); + retObj.putAll(contentAssistUtil.findExactMatchingTables(prefix)); + retObj.putAll(contentAssistUtil.findExactMatchingDebugObjects(prefix)); + retObj.putAll(contentAssistUtil.findExactMatchingViews(prefix)); + retObj.putAll(contentAssistUtil.findExactMatchingSequences(prefix)); + retObj.putAll(contentAssistUtil.findExactMatchingSynonyms(prefix)); + + return retObj; + + } + + /** + * Find matching in child. + * + * @param servObjs the serv objs + * @param prefix the prefix + * @return the sorted map + */ + private SortedMap findMatchingInChild(SortedMap servObjs, + String prefix) { + SortedMap found = new TreeMap(); + for (ServerObject servObj : servObjs.values()) { + switch (servObj.getType()) { + case NAMESPACE: { + // Redundant check, but its required for static tools + if (servObj instanceof Namespace) { + Namespace ns = (Namespace) servObj; + found.putAll(ns.findMatchingHyperlink(prefix)); + } + break; + } + default: { + // Ignore other types + break; + } + } + } + + return found; + } + + /** + * Gets the search end. + * + * @param fullContent the full content + * @param offset the offset + * @return the search end + */ + private int getSearchEnd(String fullContent, int offset) { + if (fullContent.trim().isEmpty()) { + return 0; + } + + int pos = offset; + int boundary = fullContent.length(); + char ch = '\0'; + List charList = new ArrayList(25); + addCharsToCharList(charList); + while (pos < boundary) { + ch = fullContent.charAt(pos); + + if (!charList.isEmpty() && !charList.contains(ch) && !Character.isJavaIdentifierPart(ch)) { + break; + } + ++pos; + } + + return pos; + } + + /** + * Creates the hyper link. + * + * @param offset the offset + * @param length the length + * @param obj the obj + * @return the SQL editor hyper link + */ + private SQLEditorHyperLink createHyperLink(int offset, int length, ServerObject obj) { + return createHyperLink(new Region(offset, length), obj); + } + + /** + * Creates the hyper link. + * + * @param region the region + * @param obj the obj + * @return the SQL editor hyper link + */ + private SQLEditorHyperLink createHyperLink(Region region, ServerObject obj) { + return new SQLEditorHyperLink(region, obj); + } + + /** + * Gets the search start pos. + * + * @param fullPretext the full pretext + * @return the search start pos + */ + private int getSearchStartPos(String fullPretext) { + if (fullPretext.trim().isEmpty()) { + return -1; + } + + int pos = fullPretext.length() - 1; + char ch = '\0'; + List charList = new ArrayList(25); + addCharsToCharList(charList); + while (pos > 0) { + ch = fullPretext.charAt(pos); + + charList.add('.'); + + if (!Character.isJavaIdentifierPart(ch) && !charList.isEmpty() && !charList.contains(ch)) { + break; + } + --pos; + } + + return 0 == pos ? 0 : pos + 1; + } + + /** + * Adds the chars to char list. + * + * @param charList the char list + */ + private void addCharsToCharList(List charList) { + charList.add('"'); + charList.add('*'); + charList.add('&'); + charList.add('$'); + charList.add('_'); + charList.add('#'); + charList.add('@'); + charList.add('+'); + charList.add('-'); + charList.add('/'); + charList.add('<'); + charList.add('>'); + charList.add('='); + charList.add('~'); + charList.add('!'); + charList.add('%'); + charList.add('^'); + charList.add('|'); + charList.add('`'); + charList.add('?'); + charList.add('\''); + charList.add('\\'); + charList.add(','); + } + + /** + * Sets the database. + * + * @param db the new database + */ + public void setDatabase(Database db) { + this.database = db; + } + + /** + * Gets the dabase. + * + * @return the dabase + */ + public Database getDabase() { + return this.database; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLPartitionScanner.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLPartitionScanner.java new file mode 100644 index 0000000000000000000000000000000000000000..dddb792cc6b02f3d751e0e0dcda93ffb2f1d71bc --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLPartitionScanner.java @@ -0,0 +1,212 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.PreDestroy; + +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ITypedRegion; +import org.eclipse.jface.text.TextUtilities; +import org.eclipse.jface.text.rules.EndOfLineRule; +import org.eclipse.jface.text.rules.ICharacterScanner; +import org.eclipse.jface.text.rules.IPredicateRule; +import org.eclipse.jface.text.rules.IToken; +import org.eclipse.jface.text.rules.IWordDetector; +import org.eclipse.jface.text.rules.RuleBasedPartitionScanner; +import org.eclipse.jface.text.rules.Token; +import org.eclipse.jface.text.rules.WordRule; + +import org.opengauss.mppdbide.gauss.sqlparser.comm.ISQLSyntax; +import org.opengauss.mppdbide.gauss.sqlparser.comm.NestedMultipleLineRule; +import org.opengauss.mppdbide.gauss.sqlparser.comm.NestedQuotesRule; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class SQLPartitionScanner. + * + * @since 3.0.0 + */ +public class SQLPartitionScanner extends RuleBasedPartitionScanner implements ISQLSyntax { + + /** + * The tkn comment. + */ + IToken tknComment = new Token(SQL_COMMENT); + + /** + * The tkn multiline comment. + */ + IToken tknMultilineComment = new Token(SQL_MULTILINE_COMMENT); + + /** + * The tkn sql double quotes identifier. + */ + IToken tknSqlDoubleQuotesIdentifier = new Token(SQL_DOUBLE_QUOTES_IDENTIFIER); + + /** + * The tkn sql string. + */ + IToken tknSqlString = new Token(SQL_STRING); + + /** + * The rules. + */ + List rules = new ArrayList(); + + /** + * Instantiates a new SQL partition scanner. + */ + + public SQLPartitionScanner() { + super(); + initializeRules(); + + IPredicateRule[] result = new IPredicateRule[rules.size()]; + rules.toArray(result); + setPredicateRules(result); + } + + /** + * Initialize rules. + */ + private void initializeRules() { + rules.add(new EndOfLineRule("--", tknComment)); + rules.add(new EmptyBlockCommentRule(tknMultilineComment)); + rules.add(new NestedMultipleLineRule("/*", "*/", tknMultilineComment, (char) 0, true)); + rules.add(new NestedQuotesRule("\"", "\"", tknSqlDoubleQuotesIdentifier, '"', true)); + rules.add(new NestedQuotesRule("'", "'", tknSqlString, '\'', true)); + } + + /** + * Clear rules. + */ + private void clearRules() { + for (IPredicateRule rule : rules) { + rule = null; + } + rules.clear(); + } + + /** + * Gets the scanned partition string. + * + * @return the scanned partition string + */ + public String getScannedPartitionString() { + try { + return fDocument.get(fPartitionOffset, fOffset - fPartitionOffset); + } catch (BadLocationException e) { + // Ignore, nothing to be done. + MPPDBIDELoggerUtility.debug("Bad Location Exception for scanner."); + } + + return ""; + } + + /** + * Gets the document regions. + * + * @param doc the doc + * @return the document regions + */ + public static ITypedRegion[] getDocumentRegions(IDocument doc) { + ITypedRegion[] retRegions = null; + + try { + retRegions = TextUtilities.computePartitioning(doc, SQL_PARTITIONING, 0, doc.getLength(), false); + } catch (BadLocationException e) { + // Ignore, nothing to be done. + MPPDBIDELoggerUtility.debug("Bad Location Exception for scanner."); + } + + return retRegions; + } + + /** + * + * Title: class + * + * Description: The Class EmptyBlockCommentDetector. + */ + private static class EmptyBlockCommentDetector implements IWordDetector { + + /** + * Checks if is word start. + * + * @param chr the c + * @return true, if is word start + */ + public boolean isWordStart(char chr) { + return chr == '/'; + } + + /** + * Checks if is word part. + * + * @param chr the c + * @return true, if is word part + */ + public boolean isWordPart(char chr) { + return chr == '*' || chr == '/'; + } + } + + /** + * + * Title: class + * + * Description: The Class EmptyBlockCommentRule. + */ + private static class EmptyBlockCommentRule extends WordRule implements IPredicateRule { + private IToken emptyCommentToken; + + /** + * Instantiates a new empty block comment rule. + * + * @param token the token + */ + public EmptyBlockCommentRule(IToken token) { + super(new EmptyBlockCommentDetector()); + emptyCommentToken = token; + addWord("/**/", emptyCommentToken); + } + + @Override + public IToken getSuccessToken() { + return emptyCommentToken; + } + + @Override + public IToken evaluate(ICharacterScanner scanner, boolean resume) { + return evaluate(scanner); + } + } + + /** + * Pre destroy + */ + @PreDestroy + public void preDestroy() { + clearRules(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLPredicateDetector.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLPredicateDetector.java new file mode 100644 index 0000000000000000000000000000000000000000..af55dbfaf2a6bee50d4e2f32ffc522499362b3a4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLPredicateDetector.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import java.util.Map.Entry; + +import org.eclipse.jface.text.rules.IWordDetector; +import org.eclipse.jface.text.rules.RuleBasedScanner; + +import org.opengauss.mppdbide.adapter.keywordssyntax.SQLSyntax; + +/** + * + * Title: class + * + * Description: The Class SQLPredicateDetector. + * + * @since 3.0.0 + */ +public class SQLPredicateDetector extends RuleBasedScanner implements IWordDetector { + + /** + * The syntax. + */ + SQLSyntax syntax; + + /** + * Instantiates a new SQL predicate detector. + * + * @param syntax the syntax + */ + public SQLPredicateDetector(SQLSyntax syntax) { + this.syntax = syntax; + } + + /** + * Checks if is word start. + * + * @param chr the chr + * @return true, if is word start + */ + @Override + public boolean isWordStart(char chr) { + + for (Entry entry : syntax.getPredicates().entrySet()) { + if (entry.getKey().charAt(0) == chr) { + return true; + } + } + + return false; + } + + /** + * Checks if is word part. + * + * @param chr the chr + * @return true, if is word part + */ + @Override + public boolean isWordPart(char chr) { + + for (Entry entry : syntax.getPredicates().entrySet()) { + if (entry.getKey().indexOf(chr) != -1) { + return true; + } + } + + return false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLReconcilingStrategy.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLReconcilingStrategy.java new file mode 100644 index 0000000000000000000000000000000000000000..8be9a0442e5922549f1538fc8b3c4697b5e5d6b7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLReconcilingStrategy.java @@ -0,0 +1,262 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.reconciler.DirtyRegion; +import org.eclipse.jface.text.reconciler.IReconcilingStrategy; +import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension; +import org.eclipse.jface.text.source.Annotation; +import org.eclipse.jface.text.source.projection.ProjectionAnnotation; +import org.eclipse.jface.text.source.projection.ProjectionAnnotationModel; + +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.SQLScriptElement; +import org.opengauss.mppdbide.gauss.sqlparser.bean.pos.SQLScriptPosition; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: SQLReconcilingStrategy + * + * @since 3.0.0 + */ +public class SQLReconcilingStrategy implements IReconcilingStrategy, IReconcilingStrategyExtension { + + private SQLEditorParser editor; + private IDocument document; + + private int regionOffset; + + private final Object lock = new Object(); + + /** + * Gets the editor. + * + * @return the editor + */ + public SQLEditorParser getEditor() { + return editor; + } + + /** + * Sets the editor. + * + * @param editor the new editor + */ + public void setEditor(SQLEditorParser editor) { + this.editor = editor; + } + + /** + * Sets the document. + * + * @param document the new document + */ + @Override + public void setDocument(IDocument document) { + this.document = document; + } + + /** + * Reconcile. + * + * @param dirtyRegion the dirty region + * @param subRegion the sub region + */ + @Override + public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) { + synchronized (lock) { + calculatePositions(dirtyRegion); + } + } + + /** + * Reconcile. + * + * @param partition the partition + */ + @Override + public void reconcile(IRegion partition) { + synchronized (lock) { + calculatePositions(partition); + } + } + + /** + * Sets the progress monitor. + * + * @param monitor the new progress monitor + */ + @Override + public void setProgressMonitor(IProgressMonitor monitor) { + } + + /** + * Initial reconcile. + */ + @Override + public void initialReconcile() { + synchronized (lock) { + calculatePositions(null); + } + } + + private List parsedPositions = new ArrayList<>(); + + /** + * Calculate positions. + * + * @param partition the partition + */ + protected void calculatePositions(IRegion partition) { + if (null == editor || null == document) { + return; + } + + List removedAnnotations = null; + + regionOffset = 0; + + ProjectionAnnotationModel annotationModel = editor.getProjectionAnnotationModel(); + if (annotationModel == null) { + return; + } + List queries; + try { + queries = editor.extractScriptQueries(regionOffset, document.getLength() - regionOffset, false, true, + false); + } catch (Exception exception) { + MPPDBIDELoggerUtility.error("Exception while Parsing the sql for SQL Folding", exception); + return; + } + + List removedPositions = new ArrayList<>(); + for (SQLScriptPosition sp : parsedPositions) { + if (sp.getOffset() >= regionOffset) { + removedPositions.add(sp); + } + } + if (!removedPositions.isEmpty()) { + parsedPositions.removeAll(removedPositions); + removedAnnotations = new ArrayList<>(); + for (SQLScriptPosition removedPosition : removedPositions) { + if (removedPosition.isMultiline()) { + removedAnnotations.add(removedPosition.getFoldingAnnotation()); + } + } + } + + Map addedAnnotations = handleAddedModifiedProjections(queries); + if (removedAnnotations != null || !isEmpty(addedAnnotations)) { + + annotationModel.modifyAnnotations( + removedAnnotations == null ? null + : removedAnnotations.toArray(new Annotation[removedAnnotations.size()]), + addedAnnotations, null); + } + } + + /** + * Handle added modified projections. + * + * @param queries the queries + * @return the map + */ + public Map handleAddedModifiedProjections(List queries) { + + Map addedAnnotations = new HashMap<>(); + + if (null == document) { + return addedAnnotations; + } + + try { + List addedPositions = new ArrayList<>(); + int documentLength = document.getLength(); + addPosition(queries, addedPositions, documentLength); + if (!addedPositions.isEmpty()) { + final int firstQueryPos = addedPositions.get(0).getOffset(); + int posBeforeFirst = 0; + for (int i = 0; i < parsedPositions.size(); i++) { + SQLScriptPosition sp = parsedPositions.get(i); + if (sp.getOffset() >= firstQueryPos) { + break; + } + posBeforeFirst = i; + } + parsedPositions.addAll(posBeforeFirst, addedPositions); + + for (SQLScriptPosition pos : addedPositions) { + if (pos.isMultiline()) { + addedAnnotations.put(pos.getFoldingAnnotation(), pos); + } + } + } + } catch (Exception exception) { + MPPDBIDELoggerUtility.error("Exception while Parsing the sql for SQL Folding", exception); + } + return addedAnnotations; + } + + private void addPosition(List queries, List addedPositions, int documentLength) + throws BadLocationException { + for (SQLScriptElement se : queries) { + int queryOffset = se.getOffset(); + int queryLength = se.getLength(); + + if (queryOffset == 0 && queryLength == 0) { + MPPDBIDELoggerUtility.error("queryOffset & queryLength is null, Some script present with 0 length"); + continue; + } + + boolean isMultiline = document.getLineOfOffset(queryOffset) != document + .getLineOfOffset(queryOffset + queryLength); + + // Expand query to the end of line + for (int i = queryOffset + queryLength; i < documentLength; i++) { + char ch = document.getChar(i); + if (Character.isWhitespace(ch)) { + queryLength++; + } + if (ch == '\n') { + break; + } + } + addedPositions + .add(new SQLScriptPosition(queryOffset, queryLength, isMultiline, new ProjectionAnnotation())); + } + } + + /** + * Checks if is empty. + * + * @param value the value + * @return true, if is empty + */ + public boolean isEmpty(Map value) { + return value == null || value.isEmpty(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLSourceViewerConfig.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLSourceViewerConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..3fecafadcbe9239cc3c51dc86ec47e9fe09eb051 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLSourceViewerConfig.java @@ -0,0 +1,400 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import javax.annotation.PreDestroy; + +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ITextDoubleClickStrategy; +import org.eclipse.jface.text.ITextHover; +import org.eclipse.jface.text.IUndoManager; +import org.eclipse.jface.text.TextAttribute; +import org.eclipse.jface.text.contentassist.IContentAssistant; +import org.eclipse.jface.text.hyperlink.IHyperlinkDetector; +import org.eclipse.jface.text.hyperlink.IHyperlinkPresenter; +import org.eclipse.jface.text.presentation.IPresentationReconciler; +import org.eclipse.jface.text.presentation.PresentationReconciler; +import org.eclipse.jface.text.reconciler.IReconciler; +import org.eclipse.jface.text.reconciler.MonoReconciler; +import org.eclipse.jface.text.rules.BufferedRuleBasedScanner; +import org.eclipse.jface.text.rules.DefaultDamagerRepairer; +import org.eclipse.jface.text.rules.Token; +import org.eclipse.jface.text.source.ISourceViewer; +import org.eclipse.jface.text.source.SourceViewerConfiguration; +import org.eclipse.jface.text.source.projection.ProjectionViewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.widgets.Display; + +import org.opengauss.mppdbide.adapter.keywordssyntax.KeywordsFactoryProvider; +import org.opengauss.mppdbide.adapter.keywordssyntax.KeywordsToTrieConverter; +import org.opengauss.mppdbide.adapter.keywordssyntax.SQLSyntax; +import org.opengauss.mppdbide.bl.serverdatacache.Database; +import org.opengauss.mppdbide.gauss.sqlparser.SQLFoldingConstants; +import org.opengauss.mppdbide.gauss.sqlparser.comm.ISQLSyntax; +import org.opengauss.mppdbide.gauss.sqlparser.comm.SQLFoldingRuleManager; +import org.opengauss.mppdbide.view.prefernces.DSFormatterPreferencePage; + +/** + * + * Title: class + * + * Description: The Class SQLSourceViewerConfig. + * + * @since 3.0.0 + */ +public class SQLSourceViewerConfig extends SourceViewerConfiguration { + private SQLContentAssistProcessor processor = null; + private SQLObjectLinkDetector objectLinkDetector = null; + private SQLObjectHyperLinkPresenter hyperlinkPresenter; + private PresentationReconciler reconciler = null; + private String[] retPrefixes; + private SQLSyntax syntax; + + /** + * Instantiates a new SQL source viewer config. + * + * @param syntax the syntax + */ + public SQLSourceViewerConfig(SQLSyntax syntax) { + this.syntax = syntax; + } + + /** + * Gets the configured content types. + * + * @param sourceViewer the source viewer + * @return the configured content types + */ + @Override + public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) { + return new String[] {IDocument.DEFAULT_CONTENT_TYPE, ISQLSyntax.SQL_MULTILINE_COMMENT, + ISQLSyntax.SINGLE_LINE_COMMENT, ISQLSyntax.SQL_COMMENT, ISQLSyntax.SQL_CODE, ISQLSyntax.SQL_STRING, + ISQLSyntax.SQL_DOUBLE_QUOTES_IDENTIFIER}; + } + + /** + * Gets the content assistant. + * + * @param sourceViewer the source viewer + * @return the content assistant + */ + @Override + public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { + + SQLContentAssist assistant = new SQLContentAssist(); + processor = new SQLContentAssistProcessor(assistant); + assistant.setContentAssistProcessor(processor, IDocument.DEFAULT_CONTENT_TYPE); + assistant.enableAutoActivation(true); + assistant.setAutoActivationDelay(500); + assistant.enableAutoInsert(false); + assistant.setShowEmptyList(false); + assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer)); + + Color whiteColor = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE); + Color blackColor = Display.getCurrent().getSystemColor(SWT.COLOR_BLACK); + assistant.setProposalSelectorForeground(blackColor); + assistant.setProposalSelectorBackground(whiteColor); + + return assistant; + } + + /** + * Gets the configured document partitioning. + * + * @param sourceViewer the source viewer + * @return the configured document partitioning + */ + @Override + public String getConfiguredDocumentPartitioning(ISourceViewer sourceViewer) { + return SQLCodeScanner.SQL_PARTITIONING; + } + + /** + * Gets the presentation reconciler. + * + * @return the presentation reconciler + */ + public IPresentationReconciler getPresentationReconciler() { + return this.reconciler; + } + + /** + * + * Title: class + * + * Description: The Class SQLSingleTokenScanner. + */ + private static class SQLSingleTokenScanner extends BufferedRuleBasedScanner { + + /** + * Instantiates a new SQL single token scanner. + * + * @param attr the attr + */ + public SQLSingleTokenScanner(TextAttribute attr) { + setDefaultReturnToken(new Token(attr)); + } + } + + /** + * Gets the double click strategy. + * + * @param sourceViewer the source viewer + * @param contentType the content type + * @return the double click strategy + */ + @Override + public ITextDoubleClickStrategy getDoubleClickStrategy(ISourceViewer sourceViewer, String contentType) { + return new SQLDoubleClickStrategy(); + } + + /** + * Load SQL syntax. + * + * @return the SQL syntax + */ + public SQLSyntax loadSQLSyntax() { + if (this.syntax == null) { + SQLSyntax syntx = new SQLSyntax(); + return KeywordsToTrieConverter.convertKeywordstoTrie(syntx, + KeywordsFactoryProvider.getKeywordsFactory().getKeywords()); + } + return this.syntax; + + } + + /** + * Gets the presentation reconciler. + * + * @param sourceViewer the source viewer + * @return the presentation reconciler + */ + @Override + public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) { + reconciler = new PresentationReconciler(); + String docPartitioning = getConfiguredDocumentPartitioning(sourceViewer); + reconciler.setDocumentPartitioning(docPartitioning); + + SQLEditorPlugin.getDefault().setSQLCodeScanner(loadSQLSyntax()); + + DefaultDamagerRepairer dr = new DefaultDamagerRepairer( + SQLEditorPlugin.getDefault().getSQLCodeScanner(loadSQLSyntax())); + reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); + reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); + + SQLSyntaxColorProvider colorProvider = new SQLSyntaxColorProvider(); + + // rule for multi-line comments + // We just need a scanner that does nothing but returns a token with + // the corresponding text attributes + configureDamagerRepairer(reconciler, colorProvider, ISQLSyntax.SQL_MULTILINE_COMMENT); + + // Add a "damager-repairer" for changes within one-line SQL comments. + configureDamagerRepairer(reconciler, colorProvider, ISQLSyntax.SQL_COMMENT); + + // Add a "damager-repairer" for changes within quoted literals. + configureDamagerRepairer(reconciler, colorProvider, ISQLSyntax.SQL_STRING); + + // Add a "damager-repairer" for changes within delimited identifiers. + configureDamagerRepairer(reconciler, colorProvider, ISQLSyntax.SQL_DOUBLE_QUOTES_IDENTIFIER); + + return reconciler; + } + + /** + * Configure damager repairer. + * + * @param drReconciler the dr reconciler + * @param colorProvider the color provider + * @param contentType the content type + */ + private void configureDamagerRepairer(PresentationReconciler drReconciler, SQLSyntaxColorProvider colorProvider, + String contentType) { + TextAttribute colorAttribute = colorProvider.createTextAttribute(contentType); + DefaultDamagerRepairer dr = new DefaultDamagerRepairer(new SQLSingleTokenScanner(colorAttribute)); + drReconciler.setDamager(dr, contentType); + drReconciler.setRepairer(dr, contentType); + } + + /** + * Gets the undo manager. + * + * @param sourceViewer the source viewer + * @return the undo manager + */ + @Override + public IUndoManager getUndoManager(ISourceViewer sourceViewer) { + return super.getUndoManager(sourceViewer); + } + + /** + * Sets the database. + * + * @param database the new database + */ + public void setDatabase(Database database) { + if (null != processor) { + processor.setDatabase(database); + } + if (null != this.objectLinkDetector) { + this.objectLinkDetector.setDatabase(database); + } + } + + /** + * Gets the hyperlink detectors. + * + * @param sourceViewer the source viewer + * @return the hyperlink detectors + */ + @Override + public IHyperlinkDetector[] getHyperlinkDetectors(ISourceViewer sourceViewer) { + if (sourceViewer != null) { + this.objectLinkDetector = new SQLObjectLinkDetector(); + return new IHyperlinkDetector[] {this.objectLinkDetector}; + } + + return new IHyperlinkDetector[0]; + } + + /** + * Gets the hyperlink presenter. + * + * @param sourceViewer the source viewer + * @return the hyperlink presenter + */ + @Override + public IHyperlinkPresenter getHyperlinkPresenter(ISourceViewer sourceViewer) { + this.hyperlinkPresenter = new SQLObjectHyperLinkPresenter(); + return hyperlinkPresenter; + } + + /** + * Gets the text hover. + * + * @param sourceViewer the source viewer + * @param contentType the content type + * @return the text hover + */ + @Override + public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) { + return null; + } + + /** + * Gets the tab width. + * + * @param sourceViewer the source viewer + * @return the tab width + */ + @Override + public int getTabWidth(ISourceViewer sourceViewer) { + return DSFormatterPreferencePage.getIndentSize(); + } + + /** + * Gets the indent prefixes. + * + * @param sourceViewer the source viewer + * @param contentType the content type + * @return the indent prefixes + */ + @Override + public String[] getIndentPrefixes(ISourceViewer sourceViewer, String contentType) { + if (retPrefixes == null) { + setUpdatedPrefixes(sourceViewer); + } + + return retPrefixes.clone(); + } + + /** + * Sets the updated prefixes. + * + * @param sourceViewer the new updated prefixes + */ + public void setUpdatedPrefixes(ISourceViewer sourceViewer) { + + if (DSFormatterPreferencePage.isTabToSpaceEnabled()) { + retPrefixes = new String[] {" ", "\t", ""}; + retPrefixes[0] = DSFormatterPreferencePage.getStringWithSpaces(); + } else { + retPrefixes = new String[] {"\t", " ", ""}; + retPrefixes[1] = DSFormatterPreferencePage.getStringWithSpaces(); + } + + } + + /** + * Gets the reconciler. + * + * @param sourceViewer the source viewer + * @return the reconciler + */ + public IReconciler getReconciler(ISourceViewer sourceViewer) { + + if (!(sourceViewer instanceof ProjectionViewer)) { + return null; + + } + + Object sqlStrategy = sourceViewer.getTextWidget().getData(SQLFoldingConstants.SQLRECONCILINGSTRATEGY); + + if (null != sqlStrategy && sqlStrategy instanceof SQLReconcilingStrategy) { + + MonoReconciler mReconciler = new MonoReconciler((SQLReconcilingStrategy) sqlStrategy, true); + mReconciler.setDelay(300); + sourceViewer.getTextWidget().setData(SQLFoldingConstants.MONORECONCILER, mReconciler); + return mReconciler; + + } else { + SQLReconcilingStrategy strategy = new SQLReconcilingStrategy(); + + SQLEditorParser lSQLEditorParser = new SQLEditorParser(); + + lSQLEditorParser.setSourceViewer((ProjectionViewer) sourceViewer); + + SQLFoldingRuleManager lSQLRuleManager = new SQLFoldingRuleManager(); + + lSQLRuleManager.refreshRules(); + + lSQLEditorParser.setRuleManager(lSQLRuleManager); + + strategy.setEditor(lSQLEditorParser); + + MonoReconciler mReconciler = new MonoReconciler(strategy, true); + mReconciler.setDelay(300); + sourceViewer.getTextWidget().setData(SQLFoldingConstants.SQLRECONCILINGSTRATEGY, strategy); + sourceViewer.getTextWidget().setData(SQLFoldingConstants.MONORECONCILER, mReconciler); + return mReconciler; + + } + + } + + /** + * pre destroy + */ + @PreDestroy + public void preDestroy() { + processor = null; + objectLinkDetector = null; + hyperlinkPresenter = null; + reconciler = null; + syntax = null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLSourceViewerDecorationSupport.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLSourceViewerDecorationSupport.java new file mode 100644 index 0000000000000000000000000000000000000000..dae26afdd99bb2cab56384314d1dcb38f9f2f90e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLSourceViewerDecorationSupport.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.text.source.IAnnotationAccess; +import org.eclipse.jface.text.source.ICharacterPairMatcher; +import org.eclipse.jface.text.source.IOverviewRuler; +import org.eclipse.jface.text.source.ISharedTextColors; +import org.eclipse.jface.text.source.ISourceViewer; +import org.eclipse.ui.texteditor.SourceViewerDecorationSupport; + +import org.opengauss.mppdbide.view.utils.DSDefaultCharacterPairMatcherUtil; +import org.opengauss.mppdbide.view.utils.UserPreference; + +/** + * + * Title: class + * + * Description: The Class SQLSourceViewerDecorationSupport. + * + * @since 3.0.0 + */ +public class SQLSourceViewerDecorationSupport extends SourceViewerDecorationSupport { + + /** + * Instantiates a new SQL source viewer decoration support. + * + * @param sourceViewer the source viewer + * @param overviewRuler the overview ruler + * @param annotationAccess the annotation access + * @param sharedTextColors the shared text colors + */ + public SQLSourceViewerDecorationSupport(ISourceViewer sourceViewer, IOverviewRuler overviewRuler, + IAnnotationAccess annotationAccess, ISharedTextColors sharedTextColors) { + super(sourceViewer, overviewRuler, annotationAccess, sharedTextColors); + + } + + /** + * Install decorations. + */ + public void installDecorations() { + // Added for highlight the punctuation marks + ICharacterPairMatcher matcherQuotes = new DSDefaultCharacterPairMatcher( + DSDefaultCharacterPairMatcherUtil.getMatchPunctuations(), + DSDefaultCharacterPairMatcherUtil.SQL_PARTITIONING, true); + setCharacterPairMatcher(matcherQuotes); + setMatchingCharacterPainterPreferenceKeys(DSDefaultCharacterPairMatcherUtil.EDITOR_MATCHING_BRACKETS, + DSDefaultCharacterPairMatcherUtil.EDITOR_MATCHING_BRACKETS_COLOR); + + // Enable bracket highlighting in the preference store + IPreferenceStore prefStore = UserPreference.getInstance().getPrefernceStore(); + prefStore.setDefault(DSDefaultCharacterPairMatcherUtil.EDITOR_MATCHING_BRACKETS, true); + prefStore.setDefault(DSDefaultCharacterPairMatcherUtil.EDITOR_MATCHING_BRACKETS_COLOR, "255,0,0"); + + install(prefStore); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLSyntaxColorProvider.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLSyntaxColorProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..7d67c146e265f73c9145b4586248a30ea2402c72 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLSyntaxColorProvider.java @@ -0,0 +1,443 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.eclipse.jface.preference.PreferenceConverter; +import org.eclipse.jface.preference.PreferenceStore; +import org.eclipse.jface.resource.StringConverter; +import org.eclipse.jface.text.TextAttribute; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.widgets.Display; + +import org.opengauss.mppdbide.gauss.sqlparser.comm.ISQLSyntax; +import org.opengauss.mppdbide.view.prefernces.PreferenceWrapper; + +/** + * + * Title: class + * + * Description: The Class SQLSyntaxColorProvider. + * + * @since 3.0.0 + */ +public class SQLSyntaxColorProvider { + + /** + * The Constant BACKGROUND. + */ + public static final RGB BACKGROUND = new RGB(255, 255, 255); + + /** + * use for debug position highlight + */ + public static final RGB DEBUG_POSITION = new RGB(0xfc, 0xfc, 0x00); + + /** + * use for debug breakpoint position highlight + */ + public static final RGB DEBUG_BREAKPOINT_POSITION = new RGB(0xfc, 0xfc, 0x00); + + /** + * use for debug stack first line position highlight + */ + public static final RGB DEBUG_STACK_POSITION = new RGB(0xfc, 0xfc, 0x00); + + /** + * The Constant SQL_MULTI_LINE_COMMENT. + */ + public static final RGB SQL_MULTI_LINE_COMMENT = new RGB(70, 130, 180); + + /** + * The Constant BACKGROUND_COLOR. + */ + public static final Color BACKGROUND_COLOR = new Color(Display.getCurrent(), BACKGROUND); + + /** + * use for debug position highlight + */ + public static final Color DEBUG_POSITION_COLOR = new Color( + Display.getCurrent(), + DEBUG_POSITION); + + /** + * use for debug breakpoint position highlight + */ + public static final Color DEBUG_BREAKPOINT_POSITION_COLOR = new Color( + Display.getCurrent(), + DEBUG_BREAKPOINT_POSITION); + + /** + * use for debug stack first line position highlight + */ + public static final Color DEBUG_STACK_POSITION_COLOR = new Color( + Display.getCurrent(), + DEBUG_STACK_POSITION); + + private static RGB sqlSingleLineComment = null; + private static RGB defaultt = null; + private static RGB unreservedKeyword = null; + private static RGB reservedKeyword = null; + private static RGB type = null; + private static RGB predicates = null; + private static RGB constants = null; + private static RGB string = null; + private static RGB sqlMultiLineComment = null; + + /** + * The color table. + */ + protected Map colorTable = new HashMap(10); + + /** + * The Constant PREF_SQL_SINGLE_LINE_COMMENT. + */ + public static final String PREF_SQL_SINGLE_LINE_COMMENT = "editor.syntaxcoloring.singlelinecomment"; + + /** + * The Constant PREF_SQL_MULTI_LINE_COMMENT. + */ + public static final String PREF_SQL_MULTI_LINE_COMMENT = "editor.syntaxcoloring.singlelinecomment"; + + /** + * The Constant PREF_DEFAULT. + */ + public static final String PREF_DEFAULT = "editor.syntaxcoloring.default"; + + /** + * The Constant PREF_UNRESERVED_KEYWORD. + */ + public static final String PREF_UNRESERVED_KEYWORD = "editor.syntaxcoloring.unservedkeyword"; + + /** + * The Constant PREF_RESERVED_KEYWORD. + */ + public static final String PREF_RESERVED_KEYWORD = "editor.syntaxcoloring.reservedkeyword"; + + /** + * The Constant PREF_TYPE. + */ + public static final String PREF_TYPE = "editor.syntaxcoloring.type"; + + /** + * The Constant PREF_PREDICATES. + */ + public static final String PREF_PREDICATES = "editor.syntaxcoloring.predicate"; + + /** + * The Constant PREF_CONSTANTS. + */ + public static final String PREF_CONSTANTS = "editor.syntaxcoloring.constants"; + + /** + * The Constant PREF_STRING. + */ + public static final String PREF_STRING = "editor.syntaxcoloring.strings"; + + /** + * Dispose. + */ + public void dispose() { + Iterator entry = colorTable.values().iterator(); + boolean hasNext = entry.hasNext(); + while (hasNext) { + ((Color) entry.next()).dispose(); + hasNext = entry.hasNext(); + } + } + + /** + * Gets the color. + * + * @param rgb the rgb + * @return the color + */ + public Color getColor(RGB rgb) { + Color clr = (Color) colorTable.get(rgb); + if (clr == null) { + clr = new Color(Display.getCurrent(), rgb); + colorTable.put(rgb, clr); + } + return clr; + } + + /** + * Sets the default preferences. + * + * @param preferenceStore the new default preferences + */ + public static void setDefaultPreferences(PreferenceStore preferenceStore) { + preferenceStore.setDefault(PREF_SQL_SINGLE_LINE_COMMENT, StringConverter.asString(new RGB(128, 128, 128))); + preferenceStore.setDefault(PREF_SQL_MULTI_LINE_COMMENT, StringConverter.asString(new RGB(128, 128, 128))); + preferenceStore.setDefault(PREF_DEFAULT, StringConverter.asString(new RGB(0, 0, 0))); + preferenceStore.setDefault(PREF_UNRESERVED_KEYWORD, StringConverter.asString(new RGB(128, 0, 0))); + preferenceStore.setDefault(PREF_RESERVED_KEYWORD, StringConverter.asString(new RGB(128, 0, 0))); + preferenceStore.setDefault(PREF_TYPE, StringConverter.asString(new RGB(0, 0, 128))); + preferenceStore.setDefault(PREF_PREDICATES, StringConverter.asString(new RGB(255, 0, 0))); + preferenceStore.setDefault(PREF_CONSTANTS, StringConverter.asString(new RGB(0, 64, 0))); + preferenceStore.setDefault(PREF_STRING, StringConverter.asString(new RGB(0, 128, 0))); + } + + /** + * Sets the preference color. + * + * @param ps the new preference color + */ + public static void setPreferenceColor(PreferenceStore ps) { + setSQLSingleLineComment(setPreferences(ps, PREF_SQL_SINGLE_LINE_COMMENT)); + setSQLMultiLineComment(setPreferences(ps, PREF_SQL_MULTI_LINE_COMMENT)); + setDEFAULT(setPreferences(ps, PREF_DEFAULT)); + setUnreservedKeyword(setPreferences(ps, PREF_UNRESERVED_KEYWORD)); + setReservedKeyword(setPreferences(ps, PREF_RESERVED_KEYWORD)); + setTYPE(setPreferences(ps, PREF_TYPE)); + setPREDICATES(setPreferences(ps, PREF_PREDICATES)); + setCONSTANTS(setPreferences(ps, PREF_CONSTANTS)); + setSTRING(setPreferences(ps, PREF_STRING)); + } + + /** + * Sets the preferences. + * + * @param ps the ps + * @param str the str + * @return the rgb + */ + public static RGB setPreferences(PreferenceStore ps, String str) { + RGB rgb = null; + if (validateColor(ps.getString(str))) { + rgb = PreferenceConverter.getColor(ps, str); + } else { + rgb = PreferenceConverter.getDefaultColor(ps, str); + } + return rgb; + + } + + /** + * Validate color. + * + * @param str the str + * @return true, if successful + */ + public static boolean validateColor(String str) { + + Pattern colorPattern = Pattern.compile("\\b(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\," + + "(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\,(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\b"); + Matcher colorMatcher = colorPattern.matcher(str); + + if (!colorMatcher.matches()) { + PreferenceWrapper.getInstance().setPreferenceValid(true); + return false; + } + return true; + + } + + /** + * Creates the text attribute. + * + * @param syntax the syntax + * @return the text attribute + */ + public TextAttribute createTextAttribute(String syntax) { + switch (syntax) { + case ISQLSyntax.SQL_COMMENT: { + return new TextAttribute(getColor(getSQLSingleLineComment())); + } + case ISQLSyntax.SQL_MULTILINE_COMMENT: { + return new TextAttribute(getColor(getSqlMultiLineComment())); + } + case ISQLSyntax.SQL_STRING: { + return new TextAttribute(getColor(getSTRING())); + } + case ISQLSyntax.SQL_DOUBLE_QUOTES_IDENTIFIER: { + return new TextAttribute(getColor(getSTRING())); + } + default: { + return new TextAttribute(getColor(getDEFAULT())); + } + } + } + + /** + * Gets the SQL single line comment. + * + * @return the SQL single line comment + */ + public static RGB getSQLSingleLineComment() { + return sqlSingleLineComment; + } + + /** + * Sets the SQL single line comment. + * + * @param sqlSingleLineCmnt the new SQL single line comment + */ + public static void setSQLSingleLineComment(RGB sqlSingleLineCmnt) { + sqlSingleLineComment = sqlSingleLineCmnt; + } + + /** + * Gets the default. + * + * @return the default + */ + public static RGB getDEFAULT() { + return defaultt; + } + + /** + * Sets the default. + * + * @param dEFAULT the new default + */ + public static void setDEFAULT(RGB dEFAULT) { + defaultt = dEFAULT; + } + + /** + * Gets the unreserved keyword. + * + * @return the unreserved keyword + */ + public static RGB getUnreservedKeyword() { + return unreservedKeyword; + } + + /** + * Sets the unreserved keyword. + * + * @param unReservedKeyword the new unreserved keyword + */ + public static void setUnreservedKeyword(RGB unReservedKeyword) { + unreservedKeyword = unReservedKeyword; + } + + /** + * Gets the reserved keyword. + * + * @return the reserved keyword + */ + public static RGB getReservedKeyword() { + return reservedKeyword; + } + + /** + * Sets the reserved keyword. + * + * @param rESERVEDKeyword the new reserved keyword + */ + public static void setReservedKeyword(RGB rESERVEDKeyword) { + reservedKeyword = rESERVEDKeyword; + } + + /** + * Gets the type. + * + * @return the type + */ + public static RGB getTYPE() { + return type; + } + + /** + * Sets the type. + * + * @param tYPE the new type + */ + public static void setTYPE(RGB tYPE) { + type = tYPE; + } + + /** + * Gets the predicates. + * + * @return the predicates + */ + public static RGB getPREDICATES() { + return predicates; + } + + /** + * Sets the predicates. + * + * @param pREDICATES the new predicates + */ + public static void setPREDICATES(RGB pREDICATES) { + predicates = pREDICATES; + } + + /** + * Gets the constants. + * + * @return the constants + */ + public static RGB getCONSTANTS() { + return constants; + } + + /** + * Sets the constants. + * + * @param cONSTANTS the new constants + */ + public static void setCONSTANTS(RGB cONSTANTS) { + constants = cONSTANTS; + } + + /** + * Gets the string. + * + * @return the string + */ + public static RGB getSTRING() { + return string; + } + + /** + * Sets the string. + * + * @param sTRING the new string + */ + public static void setSTRING(RGB sTRING) { + string = sTRING; + } + + /** + * Gets the sql multi line comment. + * + * @return the sql multi line comment + */ + public static RGB getSqlMultiLineComment() { + return sqlMultiLineComment; + } + + /** + * Sets the SQL multi line comment. + * + * @param coMMENT the new SQL multi line comment + */ + public static void setSQLMultiLineComment(RGB coMMENT) { + sqlMultiLineComment = coMMENT; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLWhiteSpaceDetector.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLWhiteSpaceDetector.java new file mode 100644 index 0000000000000000000000000000000000000000..59c2162b3fb063597e863f1cbfdcf1fb13695ce6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLWhiteSpaceDetector.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import org.eclipse.jface.text.rules.IWhitespaceDetector; + +/** + * + * Title: class + * + * Description: The Class SQLWhiteSpaceDetector. + * + * @since 3.0.0 + */ +public class SQLWhiteSpaceDetector implements IWhitespaceDetector { + + /** + * Checks if is whitespace. + * + * @param chr the chr + * @return true, if is whitespace + */ + public boolean isWhitespace(char chr) { + return Character.isWhitespace(chr); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLWordDetector.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLWordDetector.java new file mode 100644 index 0000000000000000000000000000000000000000..1b583d85f88b1bd953ee5315160db5996e652947 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/SQLWordDetector.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor; + +import java.util.HashSet; +import java.util.Map.Entry; +import java.util.Set; + +import org.eclipse.jface.text.rules.IWordDetector; +import org.eclipse.jface.text.rules.RuleBasedScanner; + +import org.opengauss.mppdbide.adapter.keywordssyntax.SQLSyntax; + +/** + * + * Title: class + * + * Description: The Class SQLWordDetector. + * + * @since 3.0.0 + */ +public class SQLWordDetector extends RuleBasedScanner implements IWordDetector { + private Set startChars = new HashSet<>(); + private Set keywordChars = new HashSet<>(); + + /** + * Instantiates a new SQL word detector. + * + * @param syntax the syntax + */ + public SQLWordDetector(SQLSyntax syntax) { + for (Entry entry : syntax.getReservedkrywords().entrySet()) { + startChars.add(entry.getKey().charAt(0)); + + char[] chars = entry.getKey().toCharArray(); + for (int index = 0; index < chars.length; index++) { + keywordChars.add(chars[index]); + } + } + for (Entry entry : syntax.getTypes().entrySet()) { + startChars.add(entry.getKey().charAt(0)); + + char[] chars = entry.getKey().toCharArray(); + for (int pos = 0; pos < chars.length; pos++) { + keywordChars.add(chars[pos]); + } + } + for (Entry entry : syntax.getConstants().entrySet()) { + startChars.add(entry.getKey().charAt(0)); + + char[] chars = entry.getKey().toCharArray(); + for (int conIndex = 0; conIndex < chars.length; conIndex++) { + keywordChars.add(chars[conIndex]); + } + } + for (Entry entry : syntax.getUnreservedkrywords().entrySet()) { + startChars.add(entry.getKey().charAt(0)); + + char[] chars = entry.getKey().toCharArray(); + for (int kwIndex = 0; kwIndex < chars.length; kwIndex++) { + keywordChars.add(chars[kwIndex]); + } + } + } + + /** + * Checks if is word start. + * + * @param character the character + * @return true, if is word start + */ + public boolean isWordStart(char character) { + char lowerC = Character.toUpperCase(character); + + return this.startChars.contains(lowerC) ? true : false; + } + + /** + * Checks if is word part. + * + * @param character the character + * @return true, if is word part + */ + public boolean isWordPart(char character) { + char lowerC = Character.toUpperCase(character); + + return this.keywordChars.contains(lowerC) ? true : false; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/ColumnLayout.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/ColumnLayout.java new file mode 100644 index 0000000000000000000000000000000000000000..60d89e732d61da97ab5eb572efe577add7f2e1d2 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/ColumnLayout.java @@ -0,0 +1,325 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor.templates; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.jface.viewers.ColumnLayoutData; +import org.eclipse.jface.viewers.ColumnPixelData; +import org.eclipse.jface.viewers.ColumnWeightData; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Layout; +import org.eclipse.swt.widgets.ScrollBar; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.TableColumn; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.InvalidDataException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * + * Title: class + * + * Description: The Class ColumnLayout. + * + * @since 3.0.0 + */ +public final class ColumnLayout extends Layout { + + private static final String RECALCULATE_LAYOUT = "recalculateKey"; + + /** + * The number of extra pixels taken as horizontal trim by the table column. + * To ensure there are N pixels available for the content of the column, + * assign N+COLUMN_TRIM for the column width. + */ + private static int columnTrim; + static { + String platform = SWT.getPlatform(); + if ("win32".equals(platform)) { + columnTrim = 4; + } else { + columnTrim = 3; + } + } + + private List columns = new ArrayList(); + + /** + * Adds the column data. + * + * @param data the data + */ + public void addColumnData(ColumnLayoutData data) { + columns.add(data); + } + + /** + * Compute table size. + * + * @param table the table + * @param wHint the w hint + * @param hHint the h hint + * @return the point + */ + private Point computeTableSize(Table table, int wHint, int hHint) { + Point result = table.computeSize(wHint, hHint); + + int tableWidth = 0; + int size = columns.size(); + for (int index = 0; index < size; ++index) { + ColumnLayoutData layoutData = (ColumnLayoutData) columns.get(index); + if (layoutData instanceof ColumnPixelData) { + ColumnPixelData col = (ColumnPixelData) layoutData; + tableWidth += col.width; + if (col.addTrim) { + tableWidth += columnTrim; + } + } else if (layoutData instanceof ColumnWeightData) { + ColumnWeightData col = (ColumnWeightData) layoutData; + tableWidth += col.minimumWidth; + } else { + MPPDBIDELoggerUtility.error(MessageConfigLoader.getProperty(IMessagesConstants.COLUMN_LAYOUT_ERROR)); + } + } + if (result != null && tableWidth > result.x) { + result.x = tableWidth; + } + + return result; + } + + /** + * Layout table. + * + * @param table the table + * @param width the width + * @param area the area + * @param increase the increase + * @throws InvalidDataException + */ + private void layoutTable(final Table table, final int width, final Rectangle area, final boolean increase) + throws InvalidDataException { + final TableColumn[] tableColumns = table.getColumns(); + final int columnSize = Math.min(columns.size(), tableColumns.length); + final int[] columnWidths = new int[columnSize]; + + final int[] weightIter = new int[columnSize]; + int numberOfWeightCols = 0; + + int fixedColWidth = 0; + int minWeightColWidth = 0; + int totalColWeight = 0; + + // First calc space occupied by fixed columns + for (int index = 0; index < columnSize; index++) { + ColumnLayoutData col = (ColumnLayoutData) columns.get(index); + if (col instanceof ColumnPixelData) { + ColumnPixelData cpd = (ColumnPixelData) col; + int pixels = cpd.width; + if (cpd.addTrim) { + pixels += columnTrim; + } + columnWidths[index] = pixels; + fixedColWidth += pixels; + } else if (col instanceof ColumnWeightData) { + ColumnWeightData cw = (ColumnWeightData) col; + weightIter[numberOfWeightCols] = index; + numberOfWeightCols++; + totalColWeight += cw.weight; + minWeightColWidth += cw.minimumWidth; + columnWidths[index] = cw.minimumWidth; + } else { + throw new InvalidDataException(IMessagesConstants.COLUMN_LAYOUT_ERROR); + } + } + + // For columns that have a weight + calculateClmWidth(width, columnWidths, weightIter, numberOfWeightCols, fixedColWidth, minWeightColWidth, + totalColWeight); + + setTableSize(table, area, increase, tableColumns, columnSize, columnWidths); + } + + /** + * Sets the table size. + * + * @param table the table + * @param area the area + * @param increase the increase + * @param tableColumns the table columns + * @param columnSize the column size + * @param columnWidths the column widths + */ + private void setTableSize(final Table table, final Rectangle area, final boolean increase, + final TableColumn[] tableColumns, final int columnSize, final int[] columnWidths) { + if (increase) { + table.setSize(area.width, area.height); + } + for (int indx = 0; indx < columnSize; indx++) { + tableColumns[indx].setWidth(columnWidths[indx]); + } + if (!increase) { + table.setSize(area.width, area.height); + } + } + + /** + * Calculate clm width. + * + * @param width the width + * @param columnWidths the column widths + * @param weightIter the weight iter + * @param numberOfWeightCols the number of weight cols + * @param fixedColWidth the fixed col width + * @param minWeightColWidth the min weight col width + * @param totalColWeight the total col weight + */ + private void calculateClmWidth(final int width, final int[] columnWidths, final int[] weightIter, + int numberOfWeightCols, int fixedColWidth, int minWeightColWidth, int totalColWeight) { + final int restIncludingMinWidths = width - fixedColWidth; + final int rest = restIncludingMinWidths - minWeightColWidth; + if (numberOfWeightCols > 0 && rest > 0) { + distributeToWeightCol(columnWidths, weightIter, numberOfWeightCols, totalColWeight, restIncludingMinWidths, + rest); + } + } + + /** + * Distribute to weight col. + * + * @param columnWidths the column widths + * @param weightIter the weight iter + * @param numberOfWeightCols the number of weight cols + * @param totalColWeight the total col weight + * @param restIncludingMinWidths the rest including min widths + * @param rest the rest + */ + private void distributeToWeightCol(final int[] columnWidths, final int[] weightIter, int numberOfWeightCols, + int totalColWeight, final int restIncludingMinWidths, final int rest) { + // Modify weights to reflect what each column already + // has due to its min. Otherwise, columns with low + // minimums get discriminated. + int totalWantedPixels = 0; + final int[] wantedPixels = new int[numberOfWeightCols]; + for (int pos = 0; pos < numberOfWeightCols; pos++) { + ColumnWeightData cw = (ColumnWeightData) columns.get(weightIter[pos]); + wantedPixels[pos] = totalColWeight == 0 ? 0 : cw.weight * restIncludingMinWidths / totalColWeight; + totalWantedPixels += wantedPixels[pos]; + } + + // Now distribute the rest to the columns with weight. + int totalDistributed = 0; + for (int cnt = 0; cnt < numberOfWeightCols; ++cnt) { + int pixels = totalWantedPixels == 0 ? 0 : wantedPixels[cnt] * rest / totalWantedPixels; + totalDistributed += pixels; + columnWidths[weightIter[cnt]] += pixels; + } + + // Distribute any remaining pixels to columns with weight. + int diff = rest - totalDistributed; + for (int count = 0; diff > 0; count = (count + 1) % numberOfWeightCols) { + ++columnWidths[weightIter[count]]; + --diff; + } + } + + /** + * Compute size. + * + * @param composite the composite + * @param wHint the w hint + * @param hHint the h hint + * @param flushCache the flush cache + * @return the point + */ + protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) { + return computeTableSize(getTable(composite), wHint, hHint); + } + + /** + * Layout. + * + * @param composite the composite + * @param flushCache the flush cache + */ + protected void layout(Composite composite, boolean flushCache) { + Rectangle area = composite.getClientArea(); + Table table = getTable(composite); + int tableWidth = table.getSize().x; + int trim = computeTrim(area, table, tableWidth); + int width = Math.max(0, area.width - trim); + + if (width > 1) { + try { + layoutTable(table, width, area, tableWidth < area.width); + } catch (InvalidDataException exception) { + MPPDBIDELoggerUtility.error(exception.getDBErrorMessage()); + return; + } + } + + if (composite.getData(RECALCULATE_LAYOUT) == null) { + composite.setData(RECALCULATE_LAYOUT, Boolean.FALSE); + composite.layout(); + } + } + + /** + * Compute trim. + * + * @param area the area + * @param table the table + * @param tableWidth the table width + * @return the int + */ + private int computeTrim(Rectangle area, Table table, int tableWidth) { + Point preferredSize = computeTableSize(table, area.width, area.height); + int trim; + if (tableWidth > 1) { + trim = tableWidth - table.getClientArea().width; + } else { + // initially, the table has no extend and no client area - use the + // border with plus some padding as educated guess + trim = 2 * table.getBorderWidth() + 1; + } + if (null != preferredSize && preferredSize.y > area.height) { + // Subtract the scrollbar width from the total column width + // if a vertical scrollbar will be required, but is not currently + // showing (in which case it is already subtracted above) + ScrollBar vBar = table.getVerticalBar(); + Point vBarSize = vBar.getSize(); + trim += vBarSize.x; + } + return trim; + } + + /** + * Gets the table. + * + * @param composite the composite + * @return the table + */ + private Table getTable(Composite composite) { + return (Table) composite.getChildren()[0]; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/StatusInfo.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/StatusInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..ef0ddf50dde96e966a9667879b09389f31165016 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/StatusInfo.java @@ -0,0 +1,204 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor.templates; + +import org.eclipse.core.runtime.IStatus; + +/** + * + * Title: class + * + * Description: The Class StatusInfo. + * + * @since 3.0.0 + */ +public class StatusInfo implements IStatus { + + private String statusMessage; + private int severity; + + /** + * Instantiates a new status info. + */ + public StatusInfo() { + this(OK, null); + } + + /** + * Instantiates a new status info. + * + * @param severity the severity + * @param message the message + */ + public StatusInfo(int severity, String message) { + this.statusMessage = message; + this.severity = severity; + } + + /** + * Checks if is ok. + * + * @return true, if is ok + */ + public boolean isOK() { + return severity == IStatus.OK; + } + + /** + * Checks if is warning. + * + * @return true, if is warning + */ + public boolean isWarning() { + return severity == IStatus.WARNING; + } + + /** + * Checks if is info. + * + * @return true, if is info + */ + public boolean isInfo() { + return severity == IStatus.INFO; + } + + /** + * Checks if is error. + * + * @return true, if is error + */ + public boolean isError() { + return severity == IStatus.ERROR; + } + + /** + * Gets the message. + * + * @return the message + */ + public String getMessage() { + return statusMessage; + } + + /** + * Sets the error. + * + * @param errorMessage the new error + */ + public void setError(String errorMessage) { + if (null != errorMessage) { + statusMessage = errorMessage; + severity = IStatus.ERROR; + } + } + + /** + * Sets the warning. + * + * @param warningMessage the new warning + */ + public void setWarning(String warningMessage) { + if (null != warningMessage) { + statusMessage = warningMessage; + severity = IStatus.WARNING; + } + } + + /** + * Sets the info. + * + * @param infoMessage the new info + */ + public void setInfo(String infoMessage) { + if (null != infoMessage) { + statusMessage = infoMessage; + severity = IStatus.INFO; + } + } + + /** + * Sets the OK. + */ + public void setOK() { + statusMessage = null; + severity = IStatus.OK; + } + + /** + * Matches. + * + * @param severityMask the severity mask + * @return true, if successful + */ + public boolean matches(int severityMask) { + return (severity & severityMask) != 0; + } + + /** + * Checks if is multi status. + * + * @return true, if is multi status + */ + public boolean isMultiStatus() { + return false; + } + + /** + * Gets the severity. + * + * @return the severity + */ + public int getSeverity() { + return severity; + } + + /** + * Gets the plugin. + * + * @return the plugin + */ + public String getPlugin() { + return null; + } + + /** + * Gets the exception. + * + * @return the exception + */ + public Throwable getException() { + return null; + } + + /** + * Gets the code. + * + * @return the code + */ + public int getCode() { + return severity; + } + + /** + * Gets the children. + * + * @return the children + */ + public IStatus[] getChildren() { + return new IStatus[0]; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/TemplateCompletionProcessor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/TemplateCompletionProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..4b029d1baa01ad11ac733a62dffdf450db1fbe52 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/TemplateCompletionProcessor.java @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor.templates; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.Region; +import org.eclipse.jface.text.contentassist.ICompletionProposal; +import org.eclipse.jface.text.contentassist.IContentAssistProcessor; +import org.eclipse.jface.text.contentassist.IContextInformation; +import org.eclipse.jface.text.contentassist.IContextInformationValidator; + +import org.opengauss.mppdbide.bl.util.ExecTimer; +import org.opengauss.mppdbide.bl.util.IExecTimer; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.view.core.sourceeditor.FakeCompletionProposal; +import org.opengauss.mppdbide.view.core.sourceeditor.SQLContentAssist; +import org.opengauss.mppdbide.view.core.sourceeditor.templates.persistence.TemplateIf; +import org.opengauss.mppdbide.view.utils.consts.UIConstants; + +/** + * + * Title: class + * + * Description: The Class TemplateCompletionProcessor. + * + * @since 3.0.0 + */ +public class TemplateCompletionProcessor implements IContentAssistProcessor { + private IExecTimer timer; + private SQLContentAssist assistant = null; + private static final char NEW_LINE_CHAR = '\n'; + + /** + * Instantiates a new template completion processor. + * + * @param assitant the assitant + */ + public TemplateCompletionProcessor(SQLContentAssist assitant) { + this.assistant = assitant; + } + + /** + * Compute completion proposals. + * + * @param viewer the viewer + * @param offset the offset + * @return the i completion proposal[] + */ + @Override + public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) { + timer = new ExecTimer("Code Template Load Time"); + timer.start(); + + assistant.setCurrentPrefix(new String[0]); + + String fullContent = viewer.getDocument().get(); + + int beginOffset = 0; + + if (offset > UIConstants.NAME_MAX_LEN * 2) { + beginOffset = offset - UIConstants.NAME_MAX_LEN * 2; + } + + String fullPretext = fullContent.substring(beginOffset, offset); + String prefix = findString(fullPretext); + if (prefix == null) { + prefix = ""; + } + + this.assistant.setEmptyMessage(MessageConfigLoader.getProperty(IMessagesConstants.NO_PROPOSAL)); + + final List templateProposals = new ArrayList<>(); + + TemplateStore ts = TemplateStoreManager.getInstance().getTemplateStore(); + boolean isMatchCase = TemplateStoreManager.getInstance().isMatchCase(); + + TemplateIf[] templates = ts.getMatchedTemplates(prefix, isMatchCase); + + /* No matching template found, then show No proposal. */ + if (null == templates) { + return new ICompletionProposal[] { + new FakeCompletionProposal(MessageConfigLoader.getProperty(IMessagesConstants.NO_PROPOSAL), offset)}; + } + + for (TemplateIf template : templates) { + templateProposals + .add(new TemplateProposal(template, new Region(offset - prefix.length(), 0), null, isMatchCase)); + } + + Collections.sort(templateProposals, new Comparator() { + @Override + public int compare(TemplateProposal o1, TemplateProposal o2) { + return o1.getDisplayString().compareTo(o2.getDisplayString()); + } + }); + + try { + timer.stopAndLog(); + } catch (DatabaseOperationException exception) { + MPPDBIDELoggerUtility.error("Exception while getting elapsed time", exception); + } + + return templateProposals.toArray(new ICompletionProposal[templateProposals.size()]); + } + + /** + * Compute context information. + * + * @param viewer the viewer + * @param offset the offset + * @return the i context information[] + */ + @Override + public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) { + + return new IContextInformation[0]; + } + + /** + * Gets the completion proposal auto activation characters. + * + * @return the completion proposal auto activation characters + */ + @Override + public char[] getCompletionProposalAutoActivationCharacters() { + + return new char[0]; + } + + /** + * Gets the context information auto activation characters. + * + * @return the context information auto activation characters + */ + @Override + public char[] getContextInformationAutoActivationCharacters() { + + return new char[0]; + } + + /** + * Gets the error message. + * + * @return the error message + */ + @Override + public String getErrorMessage() { + + return null; + } + + /** + * Gets the context information validator. + * + * @return the context information validator + */ + @Override + public IContextInformationValidator getContextInformationValidator() { + + return null; + } + + /** + * Find string. + * + * @param pretext the pretext + * @return the string + */ + private String findString(String pretext) { + if (pretext.trim().isEmpty()) { + return null; + } + int pos = pretext.length() - 1; + int ch = '\0'; + + while (pos >= 0) { + ch = pretext.charAt(pos); + + if (NEW_LINE_CHAR == ch) { + break; + } else if (Character.isWhitespace(ch)) { + break; + } + + --pos; + } + + String retStr = null; + retStr = pretext.substring(pos + 1); + retStr = retStr.trim(); + + return retStr; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/TemplateContentProvider.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/TemplateContentProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..580c192e17dbf3c4af12b02169bd3050b9a7c332 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/TemplateContentProvider.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor.templates; + +import org.eclipse.jface.viewers.IStructuredContentProvider; +import org.eclipse.jface.viewers.Viewer; + +/** + * + * Title: class + * + * Description: The Class TemplateContentProvider. + * + * @since 3.0.0 + */ +public class TemplateContentProvider implements IStructuredContentProvider { + + /** + * The store. + */ + private TemplateStore store; + + /** + * Gets the elements. + * + * @param input the input + * @return the elements + */ + public Object[] getElements(Object input) { + return store.getTemplateData(false); + } + + /** + * Input changed. + * + * @param viewer the viewer + * @param oldInput the old input + * @param newInput the new input + */ + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + store = (TemplateStore) newInput; + } + + /** + * Dispose. + */ + public void dispose() { + store = null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/TemplateProposal.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/TemplateProposal.java new file mode 100644 index 0000000000000000000000000000000000000000..c1d3daa54bf97674c2e55231b4c00ff965777a0a --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/TemplateProposal.java @@ -0,0 +1,355 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor.templates; + +import java.text.MessageFormat; +import java.util.Locale; + +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.DocumentEvent; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IInformationControlCreator; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.Region; +import org.eclipse.jface.text.contentassist.ICompletionProposal; +import org.eclipse.jface.text.contentassist.ICompletionProposalExtension; +import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2; +import org.eclipse.jface.text.contentassist.ICompletionProposalExtension3; +import org.eclipse.jface.text.contentassist.IContextInformation; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Point; + +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.view.core.sourceeditor.templates.persistence.TemplateIf; + +/** + * + * Title: class + * + * Description: The Class TemplateProposal. + * + * @since 3.0.0 + */ +public class TemplateProposal implements ICompletionProposal, ICompletionProposalExtension, + ICompletionProposalExtension2, ICompletionProposalExtension3 { + private TemplateIf template; + private String displayString; + private Image image; + private IRegion region; + + private IRegion fSelectedRegion; + private IInformationControlCreator informationControlCreator; + private boolean isMatchCase; + + /** + * Instantiates a new template proposal. + * + * @param template2 the template 2 + * @param region the region + * @param image the image + * @param isMatchCase the is match case + */ + public TemplateProposal(TemplateIf template2, IRegion region, Image image, boolean isMatchCase) { + this.template = template2; + this.image = image; + this.region = region; + + this.displayString = null; + this.isMatchCase = isMatchCase; + } + + /** + * Gets the formatted string. + * + * @param args the args + * @return the formatted string + */ + private String getFormattedString(Object[] args) { + return MessageFormat.format(" {0} - {1}", args); + } + + /** + * Gets the display string. + * + * @return the display string + */ + public String getDisplayString() { + if (displayString == null) { + String[] arguments = new String[] {template.getName(), template.getDescription()}; + displayString = getFormattedString(arguments); + } + + return displayString; + } + + /** + * Sets the display string. + * + * @param displayString the new display string + */ + public void setDisplayString(String displayString) { + this.displayString = displayString; + } + + /** + * Gets the template. + * + * @return the template + */ + protected final TemplateIf getTemplate() { + return template; + } + + /** + * Apply. + * + * @param document the document + */ + @Override + public void apply(IDocument document) { + + } + + /** + * Gets the selection. + * + * @param document the document + * @return the selection + */ + @Override + public Point getSelection(IDocument document) { + return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength()); + } + + /** + * Gets the additional proposal info. + * + * @return the additional proposal info + */ + @Override + public String getAdditionalProposalInfo() { + return template.getPattern(); + } + + /** + * Gets the image. + * + * @return the image + */ + @Override + public Image getImage() { + return image; + } + + /** + * Gets the context information. + * + * @return the context information + */ + @Override + public IContextInformation getContextInformation() { + return null; + } + + /** + * Sets the information control creator. + * + * @param informationControlCreator the new information control creator + */ + public final void setInformationControlCreator(IInformationControlCreator informationControlCreator) { + this.informationControlCreator = informationControlCreator; + } + + /** + * Gets the information control creator. + * + * @return the information control creator + */ + @Override + public IInformationControlCreator getInformationControlCreator() { + + return informationControlCreator; + } + + /** + * Gets the prefix completion text. + * + * @param document the document + * @param completionOffset the completion offset + * @return the prefix completion text + */ + @Override + public CharSequence getPrefixCompletionText(IDocument document, int completionOffset) { + return template.getName(); + } + + /** + * Gets the prefix completion start. + * + * @param document the document + * @param completionOffset the completion offset + * @return the prefix completion start + */ + @Override + public int getPrefixCompletionStart(IDocument document, int completionOffset) { + return getReplaceOffset(); + } + + /** + * Apply. + * + * @param viewer the viewer + * @param trigger the trigger + * @param stateMask the state mask + * @param offset the offset + */ + @Override + public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { + IDocument document = viewer.getDocument(); + try { + int start = getReplaceOffset(); + int end = Math.max(getReplaceEndOffset(), offset); + + // insert template string + document.replace(start, end - start, template.getPattern()); + fSelectedRegion = new Region(getCaretOffSet(template.getPattern()) + start, 0); + } catch (BadLocationException exception) { + MPPDBIDELoggerUtility.error("TemplateProposal: BadLocationException occurred.", exception); + } + + } + + /** + * Selected. + * + * @param viewer the viewer + * @param smartToggle the smart toggle + */ + @Override + public void selected(ITextViewer viewer, boolean smartToggle) { + + } + + /** + * Unselected. + * + * @param viewer the viewer + */ + @Override + public void unselected(ITextViewer viewer) { + } + + /** + * Validate. + * + * @param document the document + * @param offset the offset + * @param event the event + * @return true, if successful + */ + @Override + public boolean validate(IDocument document, int offset, DocumentEvent event) { + try { + int replaceOffset = getReplaceOffset(); + if (offset >= replaceOffset) { + String content = document.get(replaceOffset, offset - replaceOffset); + if (!isMatchCase) { + return template.getName().toLowerCase(Locale.ENGLISH) + .startsWith(content.toLowerCase(Locale.ENGLISH)); + } else { + return template.getName().startsWith(content); + } + } + } catch (BadLocationException exception) { + MPPDBIDELoggerUtility.error("TemplateProposal: BadLocationException occurred.", exception); + } + + return false; + } + + /** + * Apply. + * + * @param document the document + * @param trigger the trigger + * @param offset the offset + */ + @Override + public void apply(IDocument document, char trigger, int offset) { + // not in use + } + + /** + * Checks if is valid for. + * + * @param document the document + * @param offset the offset + * @return true, if is valid for + */ + @Override + public boolean isValidFor(IDocument document, int offset) { + return false; + } + + /** + * Gets the trigger characters. + * + * @return the trigger characters + */ + @Override + public char[] getTriggerCharacters() { + return new char[0]; + } + + /** + * Gets the context information position. + * + * @return the context information position + */ + @Override + public int getContextInformationPosition() { + return region.getOffset(); + } + + /** + * Gets the replace offset. + * + * @return the replace offset + */ + private final int getReplaceOffset() { + return region.getOffset(); + } + + /** + * Gets the replace end offset. + * + * @return the replace end offset + */ + private final int getReplaceEndOffset() { + return region.getOffset() + region.getLength(); + } + + /** + * Gets the caret off set. + * + * @param buffer the buffer + * @return the caret off set + */ + private int getCaretOffSet(String buffer) { + return buffer.length(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/TemplateReaderWriter.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/TemplateReaderWriter.java new file mode 100644 index 0000000000000000000000000000000000000000..42b43208196d718fd16c9d195b943d1b81883a4c --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/TemplateReaderWriter.java @@ -0,0 +1,427 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor.templates; + +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +import org.eclipse.jface.text.templates.TemplateException; + +import com.google.gson.Gson; +import com.google.gson.JsonIOException; +import com.google.gson.JsonSyntaxException; +import com.google.gson.annotations.SerializedName; +import com.google.gson.reflect.TypeToken; +import com.google.gson.stream.JsonWriter; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.view.core.sourceeditor.templates.persistence.TemplateFactory; +import org.opengauss.mppdbide.view.core.sourceeditor.templates.persistence.TemplateIf; +import org.opengauss.mppdbide.view.core.sourceeditor.templates.persistence.TemplatePersistenceDataIf; + +/** + * + * Title: class + * + * Description: The Class TemplateReaderWriter. + * + * @since 3.0.0 + */ +public class TemplateReaderWriter { + + /** + * + * Title: class + * + * Description: The Class TemplateJsonData. + */ + private static final class TemplateJsonData { + @SerializedName("deleted") + private String deleted; + + @SerializedName("description") + private String description; + + @SerializedName("enabled") + private String enabled; + + @SerializedName("name") + private String name; + + @SerializedName("pattern") + private String pattern; + + @SerializedName("id") + private String id; + + /** + * Instantiates a new template json data. + * + * @param template the template + * @param id2 the id 2 + * @param deleted2 the deleted 2 + * @param enabled2 the enabled 2 + */ + private TemplateJsonData(TemplateIf template, String id2, String deleted2, String enabled2) { + this.setDeleted(deleted2); + this.enabled = enabled2; + this.id = id2; + this.name = template.getName(); + this.description = template.getDescription(); + this.pattern = template.getPattern(); + } + + /** + * Gets the description. + * + * @return the description + */ + private String getDescription() { + return description; + } + + /** + * Gets the name. + * + * @return the name + */ + private String getName() { + return name; + } + + /** + * Gets the pattern. + * + * @return the pattern + */ + private String getPattern() { + return pattern; + } + + /** + * Gets the id. + * + * @return the id + */ + private String getId() { + return id; + } + + /** + * Gets the enabled. + * + * @return the enabled + */ + private String getEnabled() { + return enabled; + } + + /** + * Gets the deleted. + * + * @return the deleted + */ + private String getDeleted() { + return deleted; + } + + /** + * Sets the deleted. + * + * @param deleted the new deleted + */ + public void setDeleted(String deleted) { + this.deleted = deleted; + } + } + + /** + * + * Title: class + * + * Description: The Class TemplatesMetadata. + */ + private static final class TemplatesMetadata { + @SerializedName("version") + private String version; + + @SerializedName("encoding") + private String encoding; + + @SerializedName("templates") + private ArrayList templates; + + /** + * Instantiates a new templates metadata. + * + * @param version the version + * @param encoding the encoding + */ + private TemplatesMetadata(String version, String encoding) { + this.setVersion(version); + this.setEncoding(encoding); + this.setTemplates(null); + } + + /** + * Gets the templates. + * + * @return the templates + */ + public ArrayList getTemplates() { + return templates; + } + + /** + * Sets the templates. + * + * @param templates the new templates + */ + public void setTemplates(ArrayList templates) { + this.templates = templates; + } + + /** + * Sets the encoding. + * + * @param encoding the new encoding + */ + public void setEncoding(String encoding) { + this.encoding = encoding; + } + + /** + * Gets the encoding. + * + * @return the encoding + */ + public String getEncoding() { + return encoding; + } + + /** + * Sets the version. + * + * @param version the new version + */ + public void setVersion(String version) { + this.version = version; + } + + /** + * Gets the version. + * + * @return the version + */ + public String getVersion() { + return version; + } + } + + private static final String TEMPLATE_VERSION_NUMBER = "1.0.0"; + + /** + * Instantiates a new template reader writer. + */ + public TemplateReaderWriter() { + } + + /** + * Read. + * + * @param reader the reader + * @return the template persistence data if[] + * @throws IOException Signals that an I/O exception has occurred. + */ + public TemplatePersistenceDataIf[] read(Reader reader) throws IOException { + try { + Collection templates = new ArrayList(1); + Set ids = new HashSet(); + + Gson gson = new Gson(); + TemplatesMetadata templateMD = null; + try { + templateMD = gson.fromJson(reader, getType()); + } catch (JsonIOException e) { + throw new IOException(MessageConfigLoader.getProperty(IMessagesConstants.CODE_TEMPLATE_JSONEXCEPTION)); + } catch (JsonSyntaxException e) { + throw new IOException(MessageConfigLoader.getProperty(IMessagesConstants.CODE_TEMPLATE_JSONEXCEPTION)); + } + + if (templateMD == null) { + throw new IOException(MessageConfigLoader.getProperty(IMessagesConstants.CODE_TEMPLATE_JSONEXCEPTION)); + } + addLoggerForVersion(templateMD); + addValidatedTemplate(templates, ids, templateMD); + + return (TemplatePersistenceDataIf[]) templates.toArray(new TemplatePersistenceDataIf[templates.size()]); + + } catch (TemplateException e) { + throw new IOException(e.getMessage()); + } + } + + private void addLoggerForVersion(TemplatesMetadata templateMD) { + if (MPPDBIDELoggerUtility.isInfoEnabled()) { + MPPDBIDELoggerUtility + .info("Template Version " + templateMD.getVersion() + " Encoding " + templateMD.getEncoding()); + } + } + + private void addValidatedTemplate(Collection templates, Set ids, + TemplatesMetadata templateMD) throws IOException, TemplateException { + ArrayList templateItems = templateMD.getTemplates(); + int count = templateItems.size(); + TemplateJsonData item = null; + for (int indx = 0; indx != count; indx++) { + item = templateItems.get(indx); + if (item == null) { + continue; + } else if (validateItem(item)) { + throw new IOException( + MessageConfigLoader.getProperty(IMessagesConstants.CODE_TEMPLATE_MISSING_REQUIRED_ATTR)); + } + + String id = item.getId(); + if (validateId(ids, id)) { + throw new IOException(MessageConfigLoader.getProperty(IMessagesConstants.CODE_TEMPLATE_DUPLICATE_ID)); + } + + boolean deleted = getBooleanValue(item.getDeleted(), false); + boolean enabled = getBooleanValue(item.getEnabled(), true); + + String name = item.getName(); + String description = item.getDescription(); + description = addDefaultDescription(description); + + String pattern = item.getPattern(); + + TemplateIf template = TemplateFactory.getTemplate(name, description, pattern); + TemplatePersistenceDataIf data = TemplateFactory.getTemplatePersistenceData(template, enabled, id, deleted); + + templates.add(data); + } + } + + private String addDefaultDescription(String descriptionParam) { + String description = descriptionParam; + if (description == null) { + description = ""; + } + return description; + } + + private boolean validateId(Set ids, String id) { + return id != null && !("".equals(id)) && ids.contains(id); + } + + private boolean validateItem(TemplateJsonData item) { + return item.getName() == null || item.getPattern() == null || item.getDeleted() == null + || item.getEnabled() == null; + } + + /** + * Gets the type. + * + * @return the type + */ + private Type getType() { + return new TemplatesMetadataTypeToken().getType(); + } + + /** + * + * Title: class + * + * Description: The Class TemplatesMetadataTypeToken. + */ + private static final class TemplatesMetadataTypeToken extends TypeToken { + } + + /** + * Save. + * + * @param templates the templates + * @param writer the writer + * @throws IOException Signals that an I/O exception has occurred. + */ + public void save(TemplatePersistenceDataIf[] templates, Writer writer) throws IOException { + JsonWriter jsonWriter = null; + try { + TemplatesMetadata templatesMD = new TemplatesMetadata(TEMPLATE_VERSION_NUMBER, + StandardCharsets.UTF_8.name()); + + TemplateJsonData templateJson = null; + ArrayList list = new ArrayList(1); + + for (int cnt = 0; cnt < templates.length; cnt++) { + TemplatePersistenceDataIf data = templates[cnt]; + TemplateIf template = data.getTemplate(); + + String enabled = data.isEnabled() ? Boolean.toString(true) : Boolean.toString(false); + String deleted = data.isDeleted() ? Boolean.toString(true) : Boolean.toString(false); + + templateJson = new TemplateJsonData(template, data.getId(), deleted, enabled); + list.add(templateJson); + } + + templatesMD.setTemplates(list); + + Gson gson = new Gson(); + jsonWriter = new JsonWriter(writer); + gson.toJson(templatesMD, getType(), jsonWriter); + } catch (JsonIOException e) { + throw new IOException(MessageConfigLoader.getProperty(IMessagesConstants.CODE_TEMPLATE_JSONEXCEPTION)); + } finally { + if (jsonWriter != null) { + try { + jsonWriter.close(); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("Error while closing JsonWriter", exception); + } + } + } + } + + /** + * Gets the boolean value. + * + * @param attributeVal the attribute val + * @param defaultValue the default value + * @return the boolean value + * @throws TemplateException the template exception + */ + private boolean getBooleanValue(String attributeVal, boolean defaultValue) throws TemplateException { + if (attributeVal == null) { + return defaultValue; + } else if (attributeVal.equals(Boolean.toString(true))) { + return true; + } else if (attributeVal.equals(Boolean.toString(false))) { + return false; + } else { + throw new TemplateException( + MessageConfigLoader.getProperty(IMessagesConstants.CODE_TEMPLATE_ILLEGAL_BOOLEAN_ATTR)); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/TemplateStore.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/TemplateStore.java new file mode 100644 index 0000000000000000000000000000000000000000..2213c6e570721123130904f79038dcf3cd405a74 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/TemplateStore.java @@ -0,0 +1,348 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor.templates; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; + +import org.eclipse.jface.preference.IPersistentPreferenceStore; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipse.jface.util.PropertyChangeEvent; + +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.view.core.sourceeditor.templates.persistence.TemplateFactory; +import org.opengauss.mppdbide.view.core.sourceeditor.templates.persistence.TemplateIf; +import org.opengauss.mppdbide.view.core.sourceeditor.templates.persistence.TemplatePersistenceDataIf; + +/** + * + * Title: class + * + * Description: The Class TemplateStore. + * + * @since 3.0.0 + */ +public class TemplateStore { + private final List templates = new ArrayList(7); + + private IPreferenceStore preferenceStore; + private String key; + + /** + * The property listener, if any is registered, null otherwise. + * + * @since 3.2 + */ + private IPropertyChangeListener fPropertyChangeListener; + + private boolean ignorePreferenceStoreChanges; + + /** + * Instantiates a new template store. + * + * @param ps the ps + * @param key the key + */ + public TemplateStore(IPreferenceStore ps, String key) { + this.preferenceStore = ps; + this.key = key; + } + + /** + * Load. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + public void load() throws IOException { + templates.clear(); + loadContributedTemplates(); + loadCustomTemplates(); + } + + /** + * Start listening for preference changes. + */ + public final void startListeningForPreferenceChanges() { + if (fPropertyChangeListener == null) { + fPropertyChangeListener = new IPropertyChangeListener() { + + /** + * Property change. + * + * @param event the event + */ + public void propertyChange(PropertyChangeEvent event) { + /* + * Don't load if we are in the process of saving ourselves. + * We are in sync anyway after the save operation, and + * clients may trigger reloading by listening to preference + * store updates. + */ + if (!ignorePreferenceStoreChanges && key.equals(event.getProperty())) { + try { + load(); + } catch (IOException exception) { + handleException(exception); + } + } + } + }; + + preferenceStore.addPropertyChangeListener(fPropertyChangeListener); + } + } + + /** + * Handle exception. + * + * @param ioException the x + */ + private void handleException(IOException ioException) { + MPPDBIDELoggerUtility.error("TemplateStore: IOException occurred.", ioException); + } + + /** + * Hook method to load contributed templates. Contributed templates are + * superseded by customized versions of user added templates stored in the + * preferences. + *

    + * The default implementation does nothing. + *

    + * + * @throws IOException if loading fails + */ + private void loadContributedTemplates() throws IOException { + String pref = preferenceStore.getDefaultString(key); + if (pref != null && pref.trim().length() > 0) { + Reader readerInput = new StringReader(pref); + TemplateReaderWriter templateReader = new TemplateReaderWriter(); + TemplatePersistenceDataIf[] templatedatas = templateReader.read(readerInput); + for (int cnt = 0; cnt < templatedatas.length; cnt++) { + TemplatePersistenceDataIf data = templatedatas[cnt]; + if (data.isCustom()) { + MPPDBIDELoggerUtility.info("Selected template is custom."); + } else { + templates.add(data); + } + } + } + } + + /** + * Save. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + public void save() throws IOException { + ArrayList custom = new ArrayList(1); + for (Iterator it = templates.iterator(); it.hasNext();) { + TemplatePersistenceDataIf templatedata = it.next(); + // don't save deleted user-added templates + if (templatedata.isCustom() && !(templatedata.isUserAdded() && templatedata.isDeleted())) { + custom.add(templatedata); + } + } + + StringWriter output = new StringWriter(); + TemplateReaderWriter templateWriter = new TemplateReaderWriter(); + templateWriter.save((TemplatePersistenceDataIf[]) custom.toArray(new TemplatePersistenceDataIf[custom.size()]), + output); + + ignorePreferenceStoreChanges = true; + try { + preferenceStore.setValue(key, output.toString()); + if (preferenceStore instanceof IPersistentPreferenceStore) { + ((IPersistentPreferenceStore) preferenceStore).save(); + } + } finally { + ignorePreferenceStoreChanges = false; + } + } + + /** + * Adds the. + * + * @param data the data + */ + public void add(TemplatePersistenceDataIf data) { + if (data.isUserAdded()) { + templates.add(data); + } else { + for (Iterator it = templates.iterator(); it.hasNext();) { + TemplatePersistenceDataIf data2 = it.next(); + if (data2.getId() != null && data2.getId().equals(data.getId())) { + data2.setTemplate(data.getTemplate()); + data2.setDeleted(data.isDeleted()); + data2.setEnabled(data.isEnabled()); + return; + } + } + + // here add an id which is not contributed as add-on + if (data.getTemplate() != null) { + TemplatePersistenceDataIf newData = TemplateFactory.getTemplatePersistenceData(data.getTemplate(), + data.isEnabled()); + templates.add(newData); + } + } + } + + /** + * Delete. + * + * @param templatedata the templatedata + */ + public void delete(TemplatePersistenceDataIf templatedata) { + if (templatedata.isUserAdded()) { + templates.remove(templatedata); + } else { + templatedata.setDeleted(true); + } + } + + /** + * Restore deleted. + */ + public void restoreDeleted() { + for (Iterator it = templates.iterator(); it.hasNext();) { + TemplatePersistenceDataIf templateData = it.next(); + if (templateData.isDeleted()) { + templateData.setDeleted(false); + } + } + } + + /** + * Restore defaults. + * + * @param doSave the do save + */ + public void restoreDefaults(boolean doSave) { + String oldValue = null; + if (!doSave) { + oldValue = preferenceStore.getString(key); + } + + try { + ignorePreferenceStoreChanges = true; + preferenceStore.setToDefault(key); + } finally { + ignorePreferenceStoreChanges = false; + } + + try { + load(); + } catch (IOException exception) { + MPPDBIDELoggerUtility.error("TemplateStore: IOException occurred.", exception); + } + + if (oldValue != null) { + try { + ignorePreferenceStoreChanges = true; + preferenceStore.putValue(key, oldValue); + } finally { + ignorePreferenceStoreChanges = false; + } + } + } + + /** + * Gets the template data. + * + * @param includeDeleted the include deleted + * @return the template data + */ + public TemplatePersistenceDataIf[] getTemplateData(boolean includeDeleted) { + List datas = new ArrayList(1); + for (Iterator it = templates.iterator(); it.hasNext();) { + TemplatePersistenceDataIf templateData = it.next(); + if (includeDeleted || !templateData.isDeleted()) { + datas.add(templateData); + } + } + + return (TemplatePersistenceDataIf[]) datas.toArray(new TemplatePersistenceDataIf[datas.size()]); + } + + /** + * Load custom templates. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + private void loadCustomTemplates() throws IOException { + + if (null == preferenceStore) { + return; + } + + String pref = preferenceStore.getString(key); + if (pref != null && pref.trim().length() > 0) { + Reader readerInput = new StringReader(pref); + TemplateReaderWriter reader = new TemplateReaderWriter(); + TemplatePersistenceDataIf[] templatedatas = reader.read(readerInput); + for (int index = 0; index < templatedatas.length; index++) { + TemplatePersistenceDataIf data = templatedatas[index]; + add(data); + } + } + } + + /** + * Gets the matched templates. + * + * @param prefixParam the prefix param + * @param isMatchCase the is match case + * @return the matched templates + */ + public TemplateIf[] getMatchedTemplates(String prefixParam, boolean isMatchCase) { + List result = new ArrayList(5); + String prefix = prefixParam; + if ("".equals(prefix)) { + for (TemplatePersistenceDataIf obj : templates) { + if (obj.isEnabled() && !obj.isDeleted()) { + result.add(obj.getTemplate()); + } + } + + return (TemplateIf[]) result.toArray(new TemplateIf[result.size()]); + } + + if (isMatchCase) { + for (TemplatePersistenceDataIf obj : templates) { + if (obj.isEnabled() && !obj.isDeleted() && obj.getTemplate().getName().startsWith(prefix)) { + result.add(obj.getTemplate()); + } + } + } else { + prefix = prefix.toLowerCase(Locale.ENGLISH); + for (TemplatePersistenceDataIf obj : templates) { + if (obj.isEnabled() && !obj.isDeleted() + && obj.getTemplate().getName().toLowerCase(Locale.ENGLISH).startsWith(prefix)) { + result.add(obj.getTemplate()); + } + } + } + + return (TemplateIf[]) result.toArray(new TemplateIf[result.size()]); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/TemplateStoreManager.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/TemplateStoreManager.java new file mode 100644 index 0000000000000000000000000000000000000000..98807d00df7b5f3e9c02955d0d9d1aa816ede701 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/TemplateStoreManager.java @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor.templates; + +import java.io.IOException; + +import org.eclipse.jface.preference.PreferenceStore; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.view.core.sourceeditor.templates.persistence.TemplatePersistenceDataIf; +import org.opengauss.mppdbide.view.utils.consts.UIConstants; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs.MESSAGEDIALOGTYPE; + +/** + * + * Title: class + * + * Description: The Class TemplateStoreManager. + * + * @since 3.0.0 + */ +public class TemplateStoreManager { + private TemplateStore templateStore = null; + + private boolean matchCase = true; + + private static TemplateStoreManager instance = new TemplateStoreManager(); + + private final Object LOCK = new Object(); + + /** + * Instantiates a new template store manager. + */ + private TemplateStoreManager() { + + } + + /** + * Gets the single instance of TemplateStoreManager. + * + * @return single instance of TemplateStoreManager + */ + public static TemplateStoreManager getInstance() { + return instance; + } + + /** + * Creates the template store. + * + * @param ps the ps + */ + public void createTemplateStore(PreferenceStore ps) { + synchronized (LOCK) { + if (templateStore == null && null != ps) { + templateStore = new TemplateStore(ps, UIConstants.TEMPLATESTORE_PREFERENCE_KEY); + try { + templateStore.load(); + } catch (IOException e) { + MPPDBIDELoggerUtility.error("TemplateStoreManager: Ioexception occurred."); + } catch (Exception e1) { + MPPDBIDEDialogs.generateOKMessageDialog(MESSAGEDIALOGTYPE.ERROR, true, + MessageConfigLoader.getProperty(IMessagesConstants.ERR_TEMPLATE_LOAD_FAILURE_TITLE), + MessageConfigLoader.getProperty(IMessagesConstants.ERR_PREFERENCE_LOAD_FAILURE_DETAIL)); + } + templateStore.startListeningForPreferenceChanges(); + } + + } + } + + /** + * Load. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + public void load() throws IOException { + + templateStore.load(); + } + + /** + * Gets the template store. + * + * @return the template store + */ + public TemplateStore getTemplateStore() { + return templateStore; + } + + /** + * Gets the template data. + * + * @param includeDeleted the include deleted + * @return the template data + */ + public TemplatePersistenceDataIf[] getTemplateData(boolean includeDeleted) { + return templateStore.getTemplateData(includeDeleted); + } + + /** + * Adds the. + * + * @param data the data + */ + public void add(TemplatePersistenceDataIf data) { + templateStore.add(data); + } + + /** + * Delete. + * + * @param data the data + */ + public void delete(TemplatePersistenceDataIf data) { + templateStore.delete(data); + } + + /** + * Restore deleted. + */ + public void restoreDeleted() { + templateStore.restoreDeleted(); + } + + /** + * Restore defaults. + * + * @param doSave the do save + */ + public void restoreDefaults(boolean doSave) { + templateStore.restoreDefaults(doSave); + } + + /** + * Save. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + public void save() throws IOException { + templateStore.save(); + } + + /** + * Checks if is match case. + * + * @return true, if is match case + */ + public boolean isMatchCase() { + return matchCase; + } + + /** + * Sets the match case. + * + * @param isMatchCase the new match case + */ + public void setMatchCase(boolean isMatchCase) { + this.matchCase = isMatchCase; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/persistence/Template.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/persistence/Template.java new file mode 100644 index 0000000000000000000000000000000000000000..f11bce333c705417b2d8342ecf19d0bef44e0ecd --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/persistence/Template.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor.templates.persistence; + +/** + * + * Title: class + * + * Description: The Class Template. + * + * @since 3.0.0 + */ +public class Template implements TemplateIf { + private String name; + private String description; + private String pattern; + + /** + * Instantiates a new template. + * + * @param template the template + */ + public Template(TemplateIf template) { + this(template.getName(), template.getDescription(), template.getPattern()); + } + + /** + * Instantiates a new template. + * + * @param name the name + * @param description the description + * @param pattern the pattern + */ + public Template(String name, String description, String pattern) { + this.description = description; + this.name = name; + this.pattern = pattern; + } + + /** + * Hash code. + * + * @return the int + */ + public int hashCode() { + return name.hashCode() ^ pattern.hashCode(); + } + + /** + * Gets the description. + * + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Gets the pattern. + * + * @return the pattern + */ + public String getPattern() { + return pattern; + } + + /** + * Equals. + * + * @param object the object + * @return true, if successful + */ + public boolean equals(Object object) { + if (!(object instanceof Template)) { + return false; + } + + Template temp = (Template) object; + if (temp == this) { + return true; + } + + return temp.name.equals(name) && temp.pattern.equals(pattern) && temp.description.equals(description); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/persistence/TemplateFactory.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/persistence/TemplateFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..aa4d3ae1311957d586644a5a5261f6e9a5ceeefb --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/persistence/TemplateFactory.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor.templates.persistence; + +/** + * Title: TemplateFactory + * + * Description: A factory for creating Template objects. + * + * @since 3.0.0 + */ +public final class TemplateFactory { + + /** + * Gets the template. + * + * @param template the template + * @return the template + */ + public static TemplateIf getTemplate(TemplateIf template) { + return new Template(template); + } + + /** + * Gets the template. + * + * @param name the name + * @param description the description + * @param pattern the pattern + * @return the template + */ + public static TemplateIf getTemplate(String name, String description, String pattern) { + return new Template(name, description, pattern); + } + + /** + * Gets the template persistence data. + * + * @param template the template + * @param enabled the enabled + * @return the template persistence data + */ + public static TemplatePersistenceDataIf getTemplatePersistenceData(TemplateIf template, boolean enabled) { + return new TemplatePersistenceData(template, enabled); + } + + /** + * Gets the template persistence data. + * + * @param template the template + * @param enabled the enabled + * @param id2 the id 2 + * @param deleted the deleted + * @return the template persistence data + */ + public static TemplatePersistenceDataIf getTemplatePersistenceData(TemplateIf template, boolean enabled, String id2, + boolean deleted) { + return new TemplatePersistenceData(template, enabled, id2, deleted); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/persistence/TemplateIf.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/persistence/TemplateIf.java new file mode 100644 index 0000000000000000000000000000000000000000..03c5c2bd23c08f49a669c01993349049dbee447d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/persistence/TemplateIf.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor.templates.persistence; + +/** + * + * Title: interface + * + * Description: The Interface TemplateIf. + * + * @since 3.0.0 + */ +public interface TemplateIf { + + /** + * Gets the description. + * + * @return the description + */ + public String getDescription(); + + /** + * Gets the name. + * + * @return the name + */ + public String getName(); + + /** + * Gets the pattern. + * + * @return the pattern + */ + public String getPattern(); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/persistence/TemplatePersistenceData.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/persistence/TemplatePersistenceData.java new file mode 100644 index 0000000000000000000000000000000000000000..0897884a31a346d34544ba178a097ccafac58964 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/persistence/TemplatePersistenceData.java @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor.templates.persistence; + +import org.eclipse.core.runtime.Assert; + +/** + * + * Title: class + * + * Description: The Class TemplatePersistenceData. + * + * @since 3.0.0 + */ +public class TemplatePersistenceData implements TemplatePersistenceDataIf { + private final TemplateIf originalTemplate; + private final String id; + private final boolean originalIsEnabled; + + private TemplateIf customTemplate = null; + private boolean isDeleted = false; + private boolean customIsEnabled = true; + + /** + * Instantiates a new template persistence data. + * + * @param template the template + * @param enabled the enabled + */ + public TemplatePersistenceData(TemplateIf template, boolean enabled) { + this(template, enabled, null); + } + + /** + * Creates a new instance. If id is not null, the + * instance is represents a template that is contributed and can be + * identified via its id. + * + * @param template the template which is stored by the new instance + * @param enabled whether the template is enabled + * @param id the id of the template, or null if a user-added + * instance should be created + */ + private TemplatePersistenceData(TemplateIf template, boolean enabled, String id) { + this(template, enabled, id, false); + } + + /** + * Instantiates a new template persistence data. + * + * @param template the template + * @param enabled the enabled + * @param id2 the id 2 + * @param deleted the deleted + */ + public TemplatePersistenceData(TemplateIf template, boolean enabled, String id2, boolean deleted) { + Assert.isNotNull(template); + this.originalTemplate = template; + this.customTemplate = template; + this.originalIsEnabled = enabled; + this.customIsEnabled = enabled; + this.id = id2; + this.isDeleted = deleted; + } + + /** + * Gets the id. + * + * @return the id + */ + public String getId() { + return id; + } + + /** + * Checks if is deleted. + * + * @return true, if is deleted + */ + public boolean isDeleted() { + return isDeleted; + } + + /** + * Sets the deleted. + * + * @param isDeleted1 the new deleted + */ + public void setDeleted(boolean isDeleted1) { + this.isDeleted = isDeleted1; + } + + /** + * Gets the template. + * + * @return the template + */ + public TemplateIf getTemplate() { + return customTemplate; + } + + /** + * Sets the template. + * + * @param template the new template + */ + public void setTemplate(TemplateIf template) { + this.customTemplate = template; + } + + /** + * Checks if is custom. + * + * @return true, if is custom + */ + public boolean isCustom() { + return id == null || isDeleted || originalIsEnabled != customIsEnabled + || !originalTemplate.equals(customTemplate); + } + + /** + * Checks if is modified. + * + * @return true, if is modified + */ + public boolean isModified() { + return isCustom() && !isUserAdded(); + } + + /** + * Checks if is user added. + * + * @return true, if is user added + */ + public boolean isUserAdded() { + return id == null; + } + + /** + * Revert. + */ + public void revert() { + customTemplate = originalTemplate; + customIsEnabled = originalIsEnabled; + isDeleted = false; + } + + /** + * Checks if is enabled. + * + * @return true, if is enabled + */ + public boolean isEnabled() { + return customIsEnabled; + } + + /** + * Sets the enabled. + * + * @param isEnabled the new enabled + */ + public void setEnabled(boolean isEnabled) { + customIsEnabled = isEnabled; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/persistence/TemplatePersistenceDataIf.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/persistence/TemplatePersistenceDataIf.java new file mode 100644 index 0000000000000000000000000000000000000000..9ea5351c0cbd76cf925103dee0b42e7e3282f124 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/sourceeditor/templates/persistence/TemplatePersistenceDataIf.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.sourceeditor.templates.persistence; + +/** + * + * Title: interface + * + * Description: The Interface TemplatePersistenceDataIf. + * + * @since 3.0.0 + */ +public interface TemplatePersistenceDataIf { + + /** + * Gets the id. + * + * @return the id + */ + public String getId(); + + /** + * Checks if is deleted. + * + * @return true, if is deleted + */ + public boolean isDeleted(); + + /** + * Sets the deleted. + * + * @param isDeleted1 the new deleted + */ + public void setDeleted(boolean isDeleted1); + + /** + * Gets the template. + * + * @return the template + */ + public TemplateIf getTemplate(); + + /** + * Sets the template. + * + * @param template the new template + */ + public void setTemplate(TemplateIf template); + + /** + * Checks if is custom. + * + * @return true, if is custom + */ + public boolean isCustom(); + + /** + * Checks if is modified. + * + * @return true, if is modified + */ + public boolean isModified(); + + /** + * Checks if is user added. + * + * @return true, if is user added + */ + public boolean isUserAdded(); + + /** + * Revert. + */ + public void revert(); + + /** + * Checks if is enabled. + * + * @return true, if is enabled + */ + public boolean isEnabled(); + + /** + * Sets the enabled. + * + * @param isEnabled the new enabled + */ + public void setEnabled(boolean isEnabled); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/statusbar/ObjBrowserStatusbar.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/statusbar/ObjBrowserStatusbar.java new file mode 100644 index 0000000000000000000000000000000000000000..92998c0c40da2f8a746d897a8bb130bc0984dab6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/statusbar/ObjBrowserStatusbar.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.statusbar; + +import org.eclipse.swt.widgets.Label; + +import org.opengauss.mppdbide.utils.messaging.GlobaMessageQueueUtil; +import org.opengauss.mppdbide.utils.messaging.Message; +import org.opengauss.mppdbide.utils.messaging.MessageQueue; + +/** + * + * Title: class + * + * Description: The Class ObjBrowserStatusbar. + * + * @since 3.0.0 + */ +public final class ObjBrowserStatusbar implements ObjBrowserStatusbarIf { + private static volatile ObjBrowserStatusbar instance; + private Label statusItem; + private MessageQueue messages; + private StatusMessageDisplayJob displayJob = null; + private static final Object INSTANCELOCK = new Object(); + + // This Class represents DS Status bar, not OB. Name is kept to reduce + // impact. + private ObjBrowserStatusbar() { + } + + /** + * Inits the. + * + * @param toolItem the tool item + */ + public void init(Label toolItem) { + initObjects(toolItem); + } + + private void initObjects(Label toolItem) { + statusItem = toolItem; + synchronized (INSTANCELOCK) { + messages = GlobaMessageQueueUtil.getInstance().getMessageQueue(); + } + } + + /** + * Gets the single instance of ObjBrowserStatusbar. + * + * @return single instance of ObjBrowserStatusbar + */ + public static ObjBrowserStatusbar getInstance() { + if (null == instance) { + synchronized (INSTANCELOCK) { + if (null == instance) { + instance = new ObjBrowserStatusbar(); + } + } + } + return instance; + } + + /** + * Display message. + * + * @param msg the msg + */ + public void displayMessage(Message msg) { + synchronized (INSTANCELOCK) { + if (null == displayJob) { + displayJob = new StatusMessageDisplayJob(statusItem, messages); + displayJob.schedule(); + } + + messages.push(msg); + } + } + + /** + * Destroy. + */ + public void destroy() { + synchronized (INSTANCELOCK) { + if (null != displayJob) { + displayJob.setExit(); + } + } + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/statusbar/ObjBrowserStatusbarIf.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/statusbar/ObjBrowserStatusbarIf.java new file mode 100644 index 0000000000000000000000000000000000000000..a42a1305166216898cf7912252bafa82c1c0ae6b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/statusbar/ObjBrowserStatusbarIf.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.statusbar; + +import org.eclipse.swt.widgets.Label; + +import org.opengauss.mppdbide.utils.messaging.Message; + +/** + * + * Title: interface + * + * Description: The Interface ObjBrowserStatusbarIf. + * + * @since 3.0.0 + */ +public interface ObjBrowserStatusbarIf { + + /** + * Display message. + * + * @param msg the msg + */ + void displayMessage(Message msg); + + /** + * Destroy. + */ + void destroy(); + + /** + * Inits the. + * + * @param toolItem the tool item + */ + void init(Label toolItem); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/statusbar/ObjectBrowserStatusBarProvider.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/statusbar/ObjectBrowserStatusBarProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..784aef11d07bb9ac3a62ee5ac14362d3e5831e3e --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/statusbar/ObjectBrowserStatusBarProvider.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.statusbar; + +/** + * + * Title: class + * + * Description: The Class ObjectBrowserStatusBarProvider. + * + * @since 3.0.0 + */ +public abstract class ObjectBrowserStatusBarProvider { + + /** + * Gets the status bar. + * + * @return the status bar + */ + public static ObjBrowserStatusbarIf getStatusBar() { + return ObjBrowserStatusbar.getInstance(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/statusbar/StatusMessageDisplayJob.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/statusbar/StatusMessageDisplayJob.java new file mode 100644 index 0000000000000000000000000000000000000000..e5da29d0ca6e432b0df7e3a64d5541a226e26125 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/core/statusbar/StatusMessageDisplayJob.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.core.statusbar; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Label; + +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.messaging.Message; +import org.opengauss.mppdbide.utils.messaging.MessageQueue; + +/** + * + * Title: class + * + * Description: The Class StatusMessageDisplayJob. + * + * @since 3.0.0 + */ +public class StatusMessageDisplayJob extends Job { + private volatile Label toolItem; + private MessageQueue msgs; + private static final int SUCCESS_MESSAGE_SCHEDULE_TIME = 1000; + private static final int MESSAGE_SCHEDULE_TIME = 3000; + private boolean isExit = false; + private final Object INSTANCE_LOCK = new Object(); + + /** + * Instantiates a new status message display job. + * + * @param toolItem the tool item + * @param messages the messages + */ + public StatusMessageDisplayJob(Label toolItem, MessageQueue messages) { + super("Object Browser status display"); + this.toolItem = toolItem; + this.msgs = messages; + } + + /** + * Run. + * + * @param monitor the monitor + * @return the i status + */ + @Override + protected IStatus run(IProgressMonitor monitor) { + + try { + while (!isExit) { + Message msg = msgs.pop(); + while (msg != null) { + final String tmpMsg = msg.getMessage(); + Display.getDefault().syncExec(new Runnable() { + @Override + public void run() { + synchronized (INSTANCE_LOCK) { + if (!toolItem.isDisposed()) { + toolItem.setText(tmpMsg); + toolItem.pack(); + } + + } + } + }); + + msg = msgs.pop(); + Thread.sleep(MESSAGE_SCHEDULE_TIME); + } + + Thread.sleep(SUCCESS_MESSAGE_SCHEDULE_TIME); + } + } catch (InterruptedException exception) { + MPPDBIDELoggerUtility.error("InterruptedException while displaying stutus message ..", exception); + } + return Status.OK_STATUS; + } + + /** + * Sets the exit. + */ + public void setExit() { + isExit = true; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionContentProvider.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionContentProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..8c6b2007b9c2802f55077070ad4982158dd08f7f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionContentProvider.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.createfunction; + +import java.util.List; + +import org.eclipse.jface.viewers.IStructuredContentProvider; + +/** + * Title: ListStructuredContentProvider for use + * + * @since 3.0.0 + */ +public class CreateFunctionContentProvider implements IStructuredContentProvider { + @Override + public Object[] getElements(Object inputElement) { + if (inputElement instanceof List) { + return ((List) inputElement).toArray(); + } + return new Object[0]; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionControlAdapter.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionControlAdapter.java new file mode 100644 index 0000000000000000000000000000000000000000..05866c6ca70d46a8697758a0203a0ced6910bf60 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionControlAdapter.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.createfunction; + +import java.util.List; +import java.util.stream.IntStream; + +import org.eclipse.swt.events.ControlAdapter; +import org.eclipse.swt.events.ControlEvent; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.TableColumn; + +/** + * Title: DebugControlAdapter for use + * Description: the control adapter + * + * @since 3.0.0 + */ +public class CreateFunctionControlAdapter extends ControlAdapter { + /** + * this is min less column size + */ + public static final int DEFAULT_SIZE_SHOW = 20; + + private Table table; + private CreateFunctionParamsTitle titles; + + public CreateFunctionControlAdapter(Table table, CreateFunctionParamsTitle header) { + this.table = table; + this.titles = header; + } + + @Override + public void controlResized(ControlEvent e) { + Point point = table.getSize(); + List scales = titles.getScales(); + int totalScale = scales.stream().mapToInt(val -> val).sum(); + TableColumn[] columns = table.getColumns(); + IntStream.iterate(0, seed -> seed + 1).limit(scales.size()).forEach(idx -> { + TableColumn column = columns[idx]; + int columnSize = point.x * scales.get(idx) / totalScale; + column.setWidth(columnSize < DEFAULT_SIZE_SHOW ? DEFAULT_SIZE_SHOW : columnSize); + }); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionDataLableProvider.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionDataLableProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..0a334e8fb96462ef9a492106707d7901ce1a01ed --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionDataLableProvider.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.createfunction; + +import org.eclipse.jface.viewers.ColumnLabelProvider; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.widgets.Display; + +/** + * Title: DebugSourceDataLableProvider for use + * + * @since 3.0.0 + */ +public class CreateFunctionDataLableProvider extends ColumnLabelProvider { + private int titleIndex; + + public CreateFunctionDataLableProvider(int titleIndex) { + this.titleIndex = titleIndex; + } + + @Override + public String getText(Object element) { + if (element instanceof CreateFunctionParam) { + CreateFunctionParam data = (CreateFunctionParam) element; + return data.getValue(titleIndex).toString(); + } + return super.getText(element); + } + + @Override + public Color getForeground(Object element) { + if (element instanceof CreateFunctionParam) { + return new Color(Display.getCurrent(), new RGB(255, 0, 0)); + } + return super.getForeground(element); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionEditingSupport.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionEditingSupport.java new file mode 100644 index 0000000000000000000000000000000000000000..d6e823d52f36050e71548774fd70db93343fa4fe --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionEditingSupport.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.createfunction; + +import java.util.Optional; + +import org.eclipse.jface.viewers.CellEditor; +import org.eclipse.jface.viewers.ColumnViewer; +import org.eclipse.jface.viewers.ComboBoxCellEditor; +import org.eclipse.jface.viewers.EditingSupport; +import org.eclipse.jface.viewers.TableViewer; +import org.eclipse.jface.viewers.TextCellEditor; + +/** + * Title: DebugEditingSupport for use + * + * @since 3.0.0 + */ +public class CreateFunctionEditingSupport extends EditingSupport { + private int index; + private ComboBoxCellEditor comboBoxCellEditor; + + public CreateFunctionEditingSupport(ColumnViewer viewer, int index) { + super(viewer); + this.index = index; + } + + @Override + protected void setValue(Object element, Object value) { + CreateFunctionParam data = (CreateFunctionParam) element; + if (data.isSupportCombo(index)) { + data.setComboValue(index, (Integer)value); + } else { + data.setObject(index, value.toString()); + } + getViewer().refresh(); + } + + @Override + protected Object getValue(Object element) { + CreateFunctionParam data = (CreateFunctionParam) element; + if (data.isSupportCombo(index)) { + return data.getComboValue(index); + } else { + return data.getValue(index); + } + } + + @Override + protected CellEditor getCellEditor(Object element) { + ColumnViewer viewer = getViewer(); + if (!(viewer instanceof TableViewer)) { + return null; + } + TableViewer tableViewer = (TableViewer) viewer; + CreateFunctionParam data = (CreateFunctionParam) element; + if (data.isSupportCombo(index)) { + if (comboBoxCellEditor == null) { + comboBoxCellEditor = new ComboBoxCellEditor( + tableViewer.getTable(), + data.getSupportItems(index) + ); + } + return comboBoxCellEditor; + } else { + return new TextCellEditor(tableViewer.getTable()); + } + } + + @Override + protected boolean canEdit(Object element) { + return true; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionMainDlg.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionMainDlg.java new file mode 100644 index 0000000000000000000000000000000000000000..77600a099eefa7d3d7ea67a1cb3a123be0302137 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionMainDlg.java @@ -0,0 +1,818 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.createfunction; + +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Dialog; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.Text; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.createfunction.CreateFunctionUiData.ErrType; +import org.opengauss.mppdbide.view.utils.UIVerifier; + +import org.eclipse.swt.custom.SashForm; +import org.eclipse.swt.layout.FillLayout; + +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; +import java.util.stream.IntStream; + +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.TableViewer; +import org.eclipse.jface.viewers.TableViewerColumn; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.CTabFolder; +import org.eclipse.swt.custom.CTabItem; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.widgets.Group; + +/** + * Title: CreateFunctionMainDlg for use + * + * @since 3.0.0 + */ +public class CreateFunctionMainDlg extends Dialog { + private static final String MOVE_UP = "\u2191"; + private static final String MOVE_DOWN = "\u2193"; + /** + * Dialog open result + */ + protected int result = -1; + + /** + * Dialog shell + */ + protected Shell shell; + + private String initLanguage; + private Table tableParam; + private Text textPreview; + private CreateFunctionRelyInfo relyInfo; + private Label lblSchemaText; + private TableViewer tableViewer; + private CTabFolder tabFolder; + private CTabItem tabItemFunction; + private CTabItem tableItemPreview; + private Text text; + private Combo comboRetType; + private Text textFunctionBodyTemp; + private SashForm sashFormOfFunctionSelect; + private Combo comboLanguage; + private Button btnFunction; + private Button btnProcedure; + private Button btnTrigger; + private FuncTypeEnum curFuncType; + private SashForm paramSashForm; + private SashForm sashForm; + private Button btnCheckFunctionNameCase; + + /** + * Create the dialog. + * + * @param parent the parent + * @param style the style + */ + public CreateFunctionMainDlg(Shell parent, int style) { + super(parent, SWT.DIALOG_TRIM | SWT.MIN | SWT.RESIZE | SWT.APPLICATION_MODAL); + setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_CREATE_FUNCTION)); + } + + /** + * Open the dialog. + * + * @return int the result + */ + public int open() { + createContents(); + shell.open(); + shell.layout(); + initLanguageUi(); + Display display = getParent().getDisplay(); + while (!shell.isDisposed()) { + if (!display.readAndDispatch()) { + display.sleep(); + } + } + return result; + } + + /** + * + * description: set rely info, must called before open dialog + * + * @param CreateFunctionRelyInfo the info + * @return void no need return value + */ + public void setRelyInfo(CreateFunctionRelyInfo info) { + this.relyInfo = info; + } + + /** + * Set the title + * + * @param String the title string + */ + public void setTitle(String string) { + setText(string); + shell.setText(string); + } + + /** + * Create contents of the dialog. + */ + private void createContents() { + createMainShell(); + createFunctionPage(); + previewPage(); + } + + private void previewPage() { + tableItemPreview = new CTabItem(tabFolder, SWT.NONE); + tableItemPreview.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_SQL_PREVIEW)); + + SashForm sashForm4 = new SashForm(tabFolder, SWT.VERTICAL); + tableItemPreview.setControl(sashForm4); + + Label lblNewLabel1 = new Label(sashForm4, SWT.NONE); + lblNewLabel1.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_SQL_PREVIEW)); + + textPreview = new Text(sashForm4, SWT.BORDER | SWT.V_SCROLL | SWT.MULTI); + + fourButtonUi(sashForm4); + + sashForm4.setWeights(new int[] {1, 13, 1}); + } + + private void fourButtonUi(SashForm sashForm4) { + SashForm sashForm5 = new SashForm(sashForm4, SWT.NONE); + + hideLabel(sashForm5); + + backButton(sashForm5); + + cancelButton(sashForm5); + + okEditButton(sashForm5); + + okButton(sashForm5); + + sashForm5.setWeights(new int[] {4, 1, 1, 1, 1}); + } + + private void okButton(SashForm sashForm5) { + Button btnOk = new Button(sashForm5, SWT.NONE); + btnOk.setToolTipText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_TOOLTIP_COMPILE)); + btnOk.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + result = 0; + String sourceCode = textPreview.getText().trim(); + relyInfo.execute(sourceCode, true); + getParent().dispose(); + } + }); + btnOk.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_BUTTON_COMPILE)); + } + + private void okEditButton(SashForm sashForm5) { + Button btnOkEdit = new Button(sashForm5, SWT.NONE); + btnOkEdit.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + result = 0; + String sourceCode = textPreview.getText().trim(); + relyInfo.execute(sourceCode, false); + getParent().dispose(); + } + }); + btnOkEdit.setToolTipText(MessageConfigLoader.getProperty( + IMessagesConstants.CREATE_FUNCTION_UI_TOOLTIP_NO_COMPILE)); + btnOkEdit.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_BUTTON_NO_COMPILE)); + } + + private void cancelButton(SashForm sashForm5) { + Button btnCancelPreview = new Button(sashForm5, SWT.NONE); + btnCancelPreview.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + getParent().dispose(); + } + }); + btnCancelPreview.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_BUTTON_CANCEL)); + } + + private void hideLabel(SashForm sashForm5) { + Label labelPreview = new Label(sashForm5, SWT.NONE); + labelPreview.setText(""); + } + + private void backButton(SashForm sashForm5) { + Button btnBack = new Button(sashForm5, SWT.NONE); + btnBack.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + tabFolder.setSelection(tabItemFunction); + } + }); + btnBack.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_BUTTON_BACK)); + } + + private void createMainShell() { + shell = new Shell(getParent(), getStyle()); + shell.setSize(650, 600); + shell.setText(getText()); + shell.setLayout(new FillLayout(SWT.HORIZONTAL)); + tabFolder = new CTabFolder(shell, SWT.BORDER); + tabFolder.setSelectionBackground(Display.getCurrent().getSystemColor( + SWT.COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT)); + } + + private void createFunctionPage() { + tabItemFunction = new CTabItem(tabFolder, SWT.NONE); + tabItemFunction.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_CREATE_FUNCTION)); + + SashForm mainForm = new SashForm(tabFolder, SWT.VERTICAL); + tabItemFunction.setControl(mainForm); + + schemaAndFunctionNameUi(mainForm); + functionOrProcedureUi(mainForm); + paramListUi(mainForm); + functionBody(mainForm); + buttonUi(mainForm); + + mainForm.setWeights(new int[] {4, 4, 15, 15, 2}); + } + + private void buttonUi(SashForm mainForm) { + SashForm sashForm2 = new SashForm(mainForm, SWT.NONE); + + Label lblInfoShow = new Label(sashForm2, SWT.NONE); + lblInfoShow.setForeground( + new Color(getParent().getDisplay(), + new RGB(255, 0, 0)) + ); + + Button btnNext = new Button(sashForm2, SWT.NONE); + btnNext.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + CreateFunctionUiData uiData = getFunctionUiData(); + ErrType errType = uiData.valid(); + if (errType == ErrType.ERR_SUCCESS) { + tabFolder.setSelection(tableItemPreview); + textPreview.setText(uiData.getFunctionDefine()); + lblInfoShow.setText(""); + } else { + lblInfoShow.setText(errType.getProperty(errType)); + } + } + }); + btnNext.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_BUTTON_NEXT)); + + Button btnCancel = new Button(sashForm2, SWT.NONE); + btnCancel.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + getParent().dispose(); + } + }); + btnCancel.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_BUTTON_CANCEL)); + + sashForm2.setWeights(new int[] {5, 1, 1}); + } + + private void functionBody(SashForm mainForm) { + SashForm sashForm3 = new SashForm(mainForm, SWT.VERTICAL); + + Label lblNewLabel = new Label(sashForm3, SWT.NONE); + lblNewLabel.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_FUNCTION_BODY)); + + textFunctionBodyTemp = new Text(sashForm3, SWT.BORDER | SWT.V_SCROLL | SWT.MULTI); + textFunctionBodyTemp.setText(relyInfo.getFunctionBodyTemplate(comboLanguage.getText())); + sashForm3.setWeights(new int[] {1, 6}); + } + + private void paramListUi(SashForm mainForm) { + paramSashForm = new SashForm(mainForm, SWT.BORDER | SWT.SMOOTH | SWT.VERTICAL); + + SashForm sashForm1 = new SashForm(paramSashForm, SWT.VERTICAL); + + paramListButtonUi(sashForm1); + paramListTableUi(sashForm1); + + sashForm1.setWeights(new int[] {1, 6}); + paramSashForm.setWeights(new int[] {3}); + } + + private void paramListTableUi(SashForm sashForm1) { + SashForm paramTableSashFrom = new SashForm(sashForm1, SWT.NONE); + + paramTableUi(paramTableSashFrom); + paramMoveUi(paramTableSashFrom); + + paramTableSashFrom.setWeights(new int[] {8, 1}); + } + + private void paramMoveUi(SashForm paramTableSashFrom) { + SashForm tableOptSashForm = new SashForm(paramTableSashFrom, SWT.VERTICAL); + + hideLabel(tableOptSashForm); + + Button btnRollToHead = new Button(tableOptSashForm, SWT.NONE); + btnRollToHead.addSelectionListener(new OrderChangeAdapter(OrderChangeAdapter.UP_HEAD, this)); + btnRollToHead.setText(MOVE_UP + MOVE_UP); + + Button btnRollStep = new Button(tableOptSashForm, SWT.NONE); + btnRollStep.addSelectionListener(new OrderChangeAdapter(OrderChangeAdapter.UP, this)); + btnRollStep.setText(MOVE_UP); + + Button btnDownStep = new Button(tableOptSashForm, SWT.NONE); + btnDownStep.addSelectionListener(new OrderChangeAdapter(OrderChangeAdapter.DOWN, this)); + btnDownStep.setText(MOVE_DOWN); + + Button btnDownToBottom = new Button(tableOptSashForm, SWT.NONE); + btnDownToBottom.addSelectionListener(new OrderChangeAdapter(OrderChangeAdapter.DOWN_BOTTOM, this)); + btnDownToBottom.setText(MOVE_DOWN + MOVE_DOWN); + + hideLabel(tableOptSashForm); + + tableOptSashForm.setWeights(new int[] {1, 1, 1, 1, 1, 1}); + } + + private void paramTableUi(SashForm paramTableSashFrom) { + Composite composite = new Composite(paramTableSashFrom, SWT.H_SCROLL | SWT.V_SCROLL); + composite.setLayout(new FillLayout(SWT.HORIZONTAL)); + + tableViewer = new TableViewer(composite, SWT.BORDER | SWT.FULL_SELECTION); + tableParam = tableViewer.getTable(); + tableParam.setHeaderVisible(true); + tableParam.setLinesVisible(true); + initTableViewer(); + } + + private void paramListButtonUi(SashForm sashForm1) { + SashForm paramSearchSashForm = new SashForm(sashForm1, SWT.NONE); + + Label lblParamSearch = new Label(paramSearchSashForm, SWT.NONE); + lblParamSearch.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_PARAM_LIST)); + + Button btnResetAll = new Button(paramSearchSashForm, SWT.NONE); + btnResetAll.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + removeAllData(); + } + }); + btnResetAll.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_BUTTON_RESET)); + + Composite compSplit = new Composite(paramSearchSashForm, SWT.NONE); + compSplit.setEnabled(false); + + Button btnAddParam = new Button(paramSearchSashForm, SWT.NONE); + btnAddParam.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + addData(new CreateFunctionParam(relyInfo, new CreateFunctionParamsTitle())); + } + }); + btnAddParam.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_BUTTON_ADD)); + + Button btnDelParam = new Button(paramSearchSashForm, SWT.NONE); + btnDelParam.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + Optional data = getSelectCreateFunctionParam(); + if (data.isPresent()) { + removeData(data.get()); + } + } + }); + btnDelParam.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_BUTTON_DELETE)); + paramSearchSashForm.setWeights(new int[] {4, 2, 8, 2, 2}); + } + + private void functionOrProcedureUi(SashForm mainForm) { + SashForm retTypeSashForm = new SashForm(mainForm, SWT.BORDER); + + sashForm = new SashForm(retTypeSashForm, SWT.NONE); + + functionOrProcedureButton(); + languageAndReturnType(); + + sashForm.setWeights(new int[] {1, 1}); + retTypeSashForm.setWeights(new int[] {2}); + } + + private void languageAndReturnType() { + sashFormOfFunctionSelect = new SashForm(sashForm, SWT.VERTICAL); + + SashForm sashForm8 = new SashForm(sashFormOfFunctionSelect, SWT.NONE); + + Label lblNewLabel2 = new Label(sashForm8, SWT.NONE); + lblNewLabel2.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_LANGUAGE)); + + comboLanguage = new Combo(sashForm8, SWT.READ_ONLY); + comboLanguage.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + updateTemplateBody(comboLanguage.getText()); + } + }); + initComboLanguage(comboLanguage); + sashForm8.setWeights(new int[] {1, 1}); + + SashForm sashForm7 = new SashForm(sashFormOfFunctionSelect, SWT.NONE); + + Label lblRetType = new Label(sashForm7, SWT.NONE); + lblRetType.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_RETURN_TYPE)); + + comboRetType = new Combo(sashForm7, SWT.NONE); + initReturnTypeCombo(comboRetType); + sashForm7.setWeights(new int[] {1, 1}); + sashFormOfFunctionSelect.setWeights(new int[] {1, 1}); + } + + private void functionOrProcedureButton() { + Group group = new Group(sashForm, SWT.NONE); + group.setLayout(new FillLayout(SWT.HORIZONTAL)); + + btnFunction = new Button(group, SWT.RADIO); + btnFunction.setSelection(true); + btnFunction.addSelectionListener(new FunctionOrProcedureAdapter(this, tabItemFunction, FuncTypeEnum.FUNCTION)); + btnFunction.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_FUNCTION)); + curFuncType = FuncTypeEnum.FUNCTION; + + btnProcedure = new Button(group, SWT.RADIO); + btnProcedure.addSelectionListener( + new FunctionOrProcedureAdapter(this, tabItemFunction, FuncTypeEnum.PROCEDURE)); + btnProcedure.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_PROCEDURE)); + + btnTrigger = new Button(group, SWT.RADIO); + btnTrigger.addSelectionListener(new FunctionOrProcedureAdapter(this, tabItemFunction, FuncTypeEnum.TRIGGER)); + btnTrigger.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_TRIGGER)); + } + + private void schemaAndFunctionNameUi(SashForm mainForm) { + SashForm nameSshForm = new SashForm(mainForm, SWT.BORDER | SWT.SMOOTH | SWT.VERTICAL); + + SashForm nameSshFormAll = new SashForm(nameSshForm, SWT.VERTICAL); + + SashForm schemaSshForm = new SashForm(nameSshFormAll, SWT.NONE); + schemaSshForm.setSashWidth(0); + + Label lblSchema = new Label(schemaSshForm, SWT.NONE); + lblSchema.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_SCHEMA)); + + lblSchemaText = new Label(schemaSshForm, SWT.NONE); + lblSchemaText.setText(relyInfo.getSchameName()); + schemaSshForm.setWeights(new int[] {1, 4}); + + SashForm functionNameSshForm = new SashForm(nameSshFormAll, SWT.NONE); + functionNameSshForm.setSashWidth(0); + + Label lblFunctionName = new Label(functionNameSshForm, SWT.NONE); + lblFunctionName.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_FUNCTION_NAME)); + + text = new Text(functionNameSshForm, SWT.BORDER); + UIVerifier.verifyTextSize(text, 63); + new Label(functionNameSshForm, SWT.NONE); + + btnCheckFunctionNameCase = new Button(functionNameSshForm, SWT.CHECK | SWT.CENTER); + btnCheckFunctionNameCase.setText(MessageConfigLoader.getProperty(IMessagesConstants.CREATE_TABLE_CASE)); + functionNameSshForm.setWeights(new int[] {10, 32, 1, 7}); + nameSshFormAll.setWeights(new int[] {1, 1}); + nameSshForm.setWeights(new int[] {1}); + } + + private void initReturnTypeCombo(Combo tempCombo) { + for (String type: relyInfo.getSupportTypes()) { + tempCombo.add(type); + } + } + + private void initTableViewer() { + tableViewer.setContentProvider(new CreateFunctionContentProvider()); + CreateFunctionParamsTitle paramsTitles = new CreateFunctionParamsTitle(); + List titles = paramsTitles.getTitles(); + IntStream.iterate(0, seed -> seed + 1).limit(titles.size()).forEach(idx -> { + TableViewerColumn column = new TableViewerColumn(tableViewer, SWT.NONE); + column.getColumn().setWidth(20); + column.getColumn().setText(titles.get(idx)); + column.setEditingSupport(new CreateFunctionEditingSupport(tableViewer, idx)); + column.setLabelProvider(new CreateFunctionDataLableProvider(idx)); + }); + tableParam.addControlListener(new CreateFunctionControlAdapter(tableParam, paramsTitles)); + } + + /** + * Get function ui data + * + * @return CreateFunctionUiData the create function ui data + */ + public CreateFunctionUiData getFunctionUiData() { + String functionName = text.getText(); + boolean functionNameCase = btnCheckFunctionNameCase.getSelection(); + String functionReturnType = comboRetType.getText(); + String functionBody = textFunctionBodyTemp.getText(); + String language = btnFunction.getSelection() ? comboLanguage.getText() : curFuncType.language; + LinkedList params = getDataList().orElse(new LinkedList()); + return new CreateFunctionUiData( + relyInfo, + functionName, + functionNameCase, + language, + functionReturnType, + params, + functionBody); + } + + /** + * description: get data list from tableviewer + * + * @return Optional> the data list + */ + @SuppressWarnings("unchecked") + public Optional> getDataList() { + Object inputs = tableViewer.getInput(); + if (inputs instanceof LinkedList) { + return Optional.of((LinkedList) inputs); + } + return Optional.empty(); + } + + /** + * description: add data + * + * @param data the data to add + * @return boolean true if add success + */ + public boolean addData(CreateFunctionParam data) { + Optional> inputOptional = getDataList(); + List newInputs; + if (!inputOptional.isPresent()) { + newInputs = new LinkedList(); + } else { + newInputs = inputOptional.get(); + } + newInputs.add(data); + tableViewer.setInput(newInputs); + tableViewer.refresh(); + return true; + } + + /** + * description: remove data + * + * @param data the data to remove, must already in tableviewer + * @return boolean true if success + */ + public boolean removeData(CreateFunctionParam data) { + boolean isRemoved = false; + Optional> inputOptional = getDataList(); + if (inputOptional.isPresent()) { + LinkedList inputs = inputOptional.get(); + isRemoved = inputs.remove(data); + tableViewer.refresh(); + } + return isRemoved; + } + + /** + * description: remove all data + */ + public void removeAllData() { + tableViewer.setInput(null); + tableViewer.refresh(); + } + + /** + * description: reset all data + * + * @param dataList the set data list + */ + public void resetAllData(LinkedList dataList) { + tableViewer.setInput(dataList); + tableViewer.refresh(); + } + + /** + * Get select create function param + * + * @return Optional the function param + */ + public Optional getSelectCreateFunctionParam() { + IStructuredSelection structSelect = tableViewer.getStructuredSelection(); + Object obj = structSelect.getFirstElement(); + if (obj instanceof CreateFunctionParam) { + return Optional.of((CreateFunctionParam) obj); + } else { + return Optional.empty(); + } + } + + private class FunctionOrProcedureAdapter extends SelectionAdapter { + private CreateFunctionMainDlg dlg; + private CTabItem tableItemFunction; + private FuncTypeEnum funcType; + + public FunctionOrProcedureAdapter(CreateFunctionMainDlg dlg, + CTabItem tableItemFunction, FuncTypeEnum funcType) { + this.dlg = dlg; + this.tableItemFunction = tableItemFunction; + this.funcType = funcType; + } + + @Override + public void widgetSelected(SelectionEvent event) { + Button btn = (Button) event.widget; + if (btn.getSelection()) { + curFuncType = funcType; + dlg.getSashFormOfFunctionSelect().setVisible(funcType == FuncTypeEnum.FUNCTION); + dlg.setTitle(functionOrProcedureText(funcType)); + tableItemFunction.setText(functionOrProcedureText(funcType)); + boolean paramEnable = true; + if (funcType == FuncTypeEnum.TRIGGER) { + dlg.removeAllData(); + paramEnable = false; + } + dlg.paramSashForm.setEnabled(paramEnable); + updateTemplateBody(funcType == FuncTypeEnum.FUNCTION ? comboLanguage.getText() : funcType.language); + } + } + + private String functionOrProcedureText (FuncTypeEnum funcType) { + return MessageConfigLoader.getProperty(IMessagesConstants.CREATE_FUNCTION_UI_CREATE) + + MessageConfigLoader.getProperty(funcType.name) + + ((funcType == FuncTypeEnum.TRIGGER) ? + MessageConfigLoader.getProperty(FuncTypeEnum.FUNCTION.name) : ""); + } + } + + private static class OrderChangeAdapter extends SelectionAdapter { + /** + * Move to top + */ + public static final int UP_HEAD = 0x1; + /** + * Move up + */ + public static final int UP = 0x2; + /** + * Move down + */ + public static final int DOWN = 0x4; + /** + * Move to bottom + */ + public static final int DOWN_BOTTOM = 0x8; + private int optMove = 0; + private CreateFunctionMainDlg dlg; + + public OrderChangeAdapter(int optMove, CreateFunctionMainDlg dlg) { + this.optMove = optMove; + this.dlg = dlg; + } + + @Override + public void widgetSelected(SelectionEvent e) { + Optional optData = dlg.getSelectCreateFunctionParam(); + if (!optData.isPresent()) { + return; + } + CreateFunctionParam data = optData.get(); + // because these already have data, so this must have list data + LinkedList linkList = dlg.getDataList().get(); + int pos = linkList.indexOf(data); + int desPos = -1; + if (optMove == UP_HEAD) { + desPos = 0; + } else if (optMove == UP) { + desPos = pos - 1; + } else if (optMove == DOWN) { + desPos = pos + 1; + } else { + desPos = linkList.size() - 1; + } + + if (desPos == pos || desPos < 0 || desPos >= linkList.size()) { + return; + } + Collections.swap(linkList, pos, desPos); + dlg.resetAllData(linkList); + } + } + + /** + * Set init language + * + * @param String the language + */ + public void setInitLanguage(String language) { + this.initLanguage = language; + } + + /** + * Init language ui + */ + public void initLanguageUi() { + FuncTypeEnum funcType; + if (CreateFunctionRelyInfo.PROCEDURE.equals(initLanguage)) { + funcType = FuncTypeEnum.PROCEDURE; + } else if (CreateFunctionRelyInfo.LANGUAGE_TRIGGER.equals(initLanguage)) { + funcType = FuncTypeEnum.TRIGGER; + } else { + funcType = FuncTypeEnum.FUNCTION; + } + btnStateChange(funcType); + } + + private void btnStateChange(FuncTypeEnum funcType) { + btnFunction.setSelection(funcType == FuncTypeEnum.FUNCTION); + btnProcedure.setSelection(funcType == FuncTypeEnum.PROCEDURE); + btnTrigger.setSelection(funcType == FuncTypeEnum.TRIGGER); + Button nodifyBtn = null; + switch (funcType) { + case PROCEDURE: + nodifyBtn = btnProcedure; + break; + case TRIGGER: + nodifyBtn = btnTrigger; + break; + case FUNCTION: + default: + nodifyBtn = btnFunction; + break; + } + if (funcType == FuncTypeEnum.FUNCTION) { + int index = relyInfo.getSupportLanguage().indexOf(initLanguage); + comboLanguage.select(Math.max(0, index)); + } + nodifyBtn.notifyListeners(SWT.Selection, null); + } + + /** + * Gets the sash form when function selected + * + * @return SashForm the sash form when function selected + */ + public SashForm getSashFormOfFunctionSelect() { + return sashFormOfFunctionSelect; + } + + private void initComboLanguage(Combo comboLanguage) { + List languages = relyInfo.getSupportLanguage(); + for (String lang : languages) { + comboLanguage.add(lang); + } + comboLanguage.select(0); + } + + private void updateTemplateBody(String language) { + textFunctionBodyTemp.setText(relyInfo.getFunctionBodyTemplate(language)); + } + + private enum FuncTypeEnum { + FUNCTION(IMessagesConstants.CREATE_FUNCTION_UI_FUNCTION, CreateFunctionRelyInfo.LANGUAGE_PLP), + PROCEDURE(IMessagesConstants.CREATE_FUNCTION_UI_PROCEDURE, CreateFunctionRelyInfo.PROCEDURE), + TRIGGER(IMessagesConstants.CREATE_FUNCTION_UI_TRIGGER, CreateFunctionRelyInfo.LANGUAGE_TRIGGER); + + /** + * The name + */ + public final String name; + + /** + * The language + */ + public final String language; + private FuncTypeEnum(String name, String language) { + this.name = name; + this.language = language; + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionParam.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionParam.java new file mode 100644 index 0000000000000000000000000000000000000000..1236c0ac1a8020d081ae29f5bc727e13c63f320d --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionParam.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.createfunction; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Title: ListDebugSourceDataAdapter for use + * + * @since 3.0.0 + */ +public class CreateFunctionParam { + /** + * Invalid param name + */ + public static final String DEFAULT_PARAM_NAME = "<>"; + private static final int IDX_MODE = 1; + private static final int IDX_TYPE = 2; + private List dataArrays = new ArrayList<>(4); + private CreateFunctionParamsTitle titles; + private CreateFunctionRelyInfo info; + private Map comboValues = new HashMap<>(); + private int indexOfMode = 0; + private int indexOfType = 0; + + public CreateFunctionParam(CreateFunctionRelyInfo info, CreateFunctionParamsTitle titles) { + this(info, titles, DEFAULT_PARAM_NAME, ""); + } + + public CreateFunctionParam(CreateFunctionRelyInfo info, + CreateFunctionParamsTitle titles, + String name, + String dataDefault) { + this.info = info; + this.titles = titles; + for (int i = 0, n = this.titles.getTitles().size(); i < n; i++) { + comboValues.put(i, getSupportItems(i)); + } + dataArrays.add(name); + dataArrays.add(comboValues.get(1)[indexOfMode]); + dataArrays.add(comboValues.get(2)[indexOfType]); + dataArrays.add(dataDefault); + } + + /** + * Get value + * + * @param int the title index + * @return Object the Object + */ + public Object getValue(int titleIndex) { + return dataArrays.get(titleIndex); + } + + /** + * Get combo value + * + * @param int the title index + * @return Integer the combo value + */ + public Integer getComboValue(int titleIndex) { + if (titleIndex == IDX_MODE) { + return indexOfMode; + } else if (titleIndex == IDX_TYPE) { + return indexOfType; + } else { + // can't run here! + return 0; + } + } + + /** + * Set combo value + * + * @param int the title index + * @param int the index value + */ + public void setComboValue(int titleIndex, int indexValue) { + if (indexValue == -1) { + return; + } + String value = comboValues.get(titleIndex)[indexValue]; + if (titleIndex == IDX_MODE) { + indexOfMode = indexValue; + } else if (titleIndex == IDX_TYPE) { + indexOfType = indexValue; + } else { + // can't run here + } + setObject(titleIndex, value); + } + + /** + * Set object + * + * @param int the title index + * @param String the value + */ + public void setObject(int titleIndex, String value) { + dataArrays.set(titleIndex, value); + } + + /** + * Is support combo + * + * @param int the title index + * @return boolean true if is support combo + */ + public boolean isSupportCombo(int titleIndex) { + return titleIndex == IDX_MODE || titleIndex == IDX_TYPE; + } + + /** + * Get support items + * + * @param int the title index + * @return String[] the support items + */ + public String[] getSupportItems(int titleIndex) { + if (titleIndex == IDX_MODE) { + return new String[] {"IN", "OUT", "INOUT"}; + } else if (titleIndex == IDX_TYPE) { + return info.getSupportTypes().toArray(new String[] {}); + } else { + return new String[] {}; + } + } + + /** + * Get datas + * + * @return List the data list + */ + public List getDatas() { + return dataArrays; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionParamsTitle.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionParamsTitle.java new file mode 100644 index 0000000000000000000000000000000000000000..1fe65b2069cc02a10279d2b96fab29247bba48ed --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionParamsTitle.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.createfunction; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collector; +import java.util.stream.Collectors; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * Title: CreateFunctionParamsTitle for use + * + * @since 3.0.0 + */ +public class CreateFunctionParamsTitle { + private static final String PARAM_NAME = IMessagesConstants.CREATE_FUNCTION_UI_PARAM_NAME; + private static final String PARAM_MODE = IMessagesConstants.CREATE_FUNCTION_UI_PARAM_MODE; + private static final String PARAM_TYPE = IMessagesConstants.CREATE_FUNCTION_UI_PARAM_TYPE; + private static final String PARAM_DEFAULT = IMessagesConstants.CREATE_FUNCTION_UI_PARAM_DEFAULT; + private static List titleList = Arrays.asList(PARAM_NAME, PARAM_MODE, PARAM_TYPE, PARAM_DEFAULT); + + /** + * Get titles + * + * @return List the title list + */ + public List getTitles() { + return titleList.stream() + .map(param -> getContent(param)) + .collect(Collectors.toList()); + } + + /** + * Get scales + * + * @return List the scale list + */ + public List getScales() { + return Arrays.asList(1, 1, 1, 1); + } + + private String getContent (String param) { + return MessageConfigLoader.getProperty(param); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionRelyInfo.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionRelyInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..d3fb14ac1a04d39d056e726b2965a895b2056b84 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionRelyInfo.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.createfunction; + +import java.util.Arrays; +import java.util.List; + +/** + * Title: CreateFunctionRelyInfo for use + * + * @since 3.0.0 + */ +public interface CreateFunctionRelyInfo { + /** + * define language when select procedure + */ + String PROCEDURE = "PROCEDURE"; + /** + * define language when select plpgsql + */ + String LANGUAGE_PLP = "PLPGSQL"; + /** + * define language when select sql + */ + String LANGUAGE_SQL = "SQL"; + /** + * define language when select c + */ + String LANGUAGE_C = "C"; + /** + * define lanaguage when select trigger + */ + String LANGUAGE_TRIGGER = "TRIGGER"; + + /** + * + * description: get schema name + * + * @return String schema name + */ + String getSchameName(); + + /** + * + * description:get line separator + * + * @return String line separator + */ + default String getLineSeparator() { + return System.lineSeparator(); + } + + /** + * + * description: get slash + * + * @return String the slash + */ + default String getEscapeForwardSlash() { + return "/"; + } + + /** + * + * description: get all supported types + * + * @return List the supported types + */ + List getSupportTypes(); + + /** + * + * description: get all support function language + * + * @return List the support language + */ + default List getSupportLanguage() { + return Arrays.asList( + LANGUAGE_PLP, + LANGUAGE_SQL, + LANGUAGE_C); + } + + /** + * + * description: get function body template + * + * @param String the language + * @return String the body template + */ + String getFunctionBodyTemplate(String language); + + /** + * + * description: run source code, this interface must be async! + * + * @param sourceCode the code + * @param autoCompile if auto compile + */ + void execute(String sourceCode, boolean autoCompile); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionUiData.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionUiData.java new file mode 100644 index 0000000000000000000000000000000000000000..03682437034ce770f737f64fca3a3edee94b29f1 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/CreateFunctionUiData.java @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.createfunction; + +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; + +/** + * Title: CreateFunctionUiData for use + * + * @since 3.0.0 + */ +public class CreateFunctionUiData { + /** + * Title: ErrType for use + * Description: this use to show err msg of ui param + */ + public enum ErrType { + ERR_SUCCESS("success"), + ERR_FUNCNAME(IMessagesConstants.CREATE_FUNCTION_UI_ERR_FUNC_NAME), + ERR_FUNCBODY(IMessagesConstants.CREATE_FUNCTION_UI_ERR_FUNC_BODY); + + /** + * The error message string + */ + public final String errMsg; + ErrType(String errMsg) { + this.errMsg = errMsg; + } + + /** + * Gets property + * + * @param ErrType the error type + * @return String the error string + */ + public String getProperty(ErrType errType) { + return MessageConfigLoader.getProperty(errType.errMsg); + } + } + + private CreateFunctionRelyInfo relyInfo; + private String functionName; + private boolean functionNameCase; + private String language; + private String functionReturnType; + private List> paramList; + private String functionBody; + + public CreateFunctionUiData( + CreateFunctionRelyInfo relyInfo, + String functionName, + boolean functionNameCase, + String language, + String functionReturnType, + List paramList, + String functionBody) { + this.relyInfo = relyInfo; + this.functionName = functionName; + this.functionNameCase = functionNameCase; + this.language = language; + this.functionReturnType = functionReturnType; + this.paramList = new ArrayList<>(); + for (CreateFunctionParam param: paramList) { + this.paramList.add(new ArrayList(param.getDatas())); + } + this.functionBody = functionBody; + } + + /** + * Check if is valid + * + * @return ErrType the error type + */ + public ErrType valid() { + if ("".equals(this.functionName)) { + return ErrType.ERR_FUNCNAME; + } + if ("".equals(this.functionBody)) { + return ErrType.ERR_FUNCBODY; + } + return ErrType.ERR_SUCCESS; + } + + private boolean isProcedure() { + return CreateFunctionRelyInfo.PROCEDURE.equals(language); + } + + private boolean isTrigger() { + return CreateFunctionRelyInfo.LANGUAGE_TRIGGER.equals(language); + } + + private String functionType() { + return isProcedure() ? "PROCEDURE" : "FUNCTION"; + } + + /** + * Get function define + * + * @return String the function define + */ + public String getFunctionDefine() { + StringBuilder sb = new StringBuilder(128); + sb.append("CREATE OR REPLACE " + functionType() + " "); + sb.append(relyInfo.getSchameName()); + sb.append("."); + if (functionNameCase) { + sb.append("\"").append(functionName).append("\""); + } else { + sb.append(functionName); + } + sb.append(" ("); + sb.append(formatParam()); + sb.append(")"); + + sb.append(relyInfo.getLineSeparator()); + + if (!isProcedure()) { + if (isTrigger()) { + sb.append("\tRETURNS ").append(CreateFunctionRelyInfo.LANGUAGE_TRIGGER); + sb.append(relyInfo.getLineSeparator()); + } + if (!"".equals(functionReturnType)) { + sb.append("\tRETURNS ").append(functionReturnType); + sb.append(relyInfo.getLineSeparator()); + } + sb.append("\tLANGUAGE " + + (isTrigger() ? CreateFunctionRelyInfo.LANGUAGE_PLP : language)); + sb.append(relyInfo.getLineSeparator()); + } + sb.append(functionBody); + return sb.toString(); + } + + /** + * Format params + * + * @return String the formatted param string + */ + public String formatParam() { + if (isTrigger()) { + return ""; + } + StringBuilder sb = new StringBuilder(); + if (this.paramList.size() != 0) { + sb.append(relyInfo.getLineSeparator()); + } + + int index = 0; + for (List param: this.paramList) { + String name = param.get(0).trim(); + String mode = param.get(1).trim(); + String type = param.get(2).trim(); + if (!CreateFunctionParam.DEFAULT_PARAM_NAME.equals(name)) { + sb.append(name); + sb.append(" "); + } + sb.append(mode); + sb.append(" "); + sb.append(type); + String defaultValue = param.get(3).trim(); + if (!"".equals(defaultValue)) { + sb.append(" DEFAULT "); + sb.append(defaultValue); + } + if (index != this.paramList.size() - 1) { + sb.append(","); + sb.append(relyInfo.getLineSeparator()); + } + index += 1; + } + if (this.paramList.size() != 0) { + sb.append(relyInfo.getLineSeparator()); + } + + return sb.toString(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/DsCreateFunctionRelyInfo.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/DsCreateFunctionRelyInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..dfda927352533aa1366a087bbc5c8afaf7aae5cc --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createfunction/DsCreateFunctionRelyInfo.java @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.createfunction; + +import java.util.List; +import java.util.stream.Collectors; + +import org.opengauss.mppdbide.bl.serverdatacache.TypeMetaData; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ObjectGroup; +import org.opengauss.mppdbide.bl.serverdatacache.groups.ObjectList; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; + +/** + * Title: class + * Description: The Class DebugEditorItem. + * + * @since 3.0.0 + */ +public class DsCreateFunctionRelyInfo implements CreateFunctionRelyInfo { + private String schameName; + private String sourceCode = null; + private List validTypes; + private boolean autoCompile = true; + + public DsCreateFunctionRelyInfo(ObjectGroup objGroup) { + ObjectList types = objGroup.getDatabase().getDefaultDatatype(); + validTypes = types.getList().stream() + .map(curType -> curType.getName()) + .collect(Collectors.toList()); + } + + public void setSchameName(String schameName) { + this.schameName = schameName; + } + + public String getSourceCode() { + return sourceCode; + } + + public boolean getAutoCompile() { + return autoCompile; + } + + @Override + public String getSchameName() { + return schameName; + } + + @Override + public List getSupportTypes() { + return validTypes; + } + + @Override + public void execute(String sourceCode, boolean autoCompile) { + MPPDBIDELoggerUtility.info("source code:" + sourceCode); + this.sourceCode = sourceCode; + this.autoCompile = autoCompile; + } + + @Override + public String getFunctionBodyTemplate(String language) { + if (CreateFunctionRelyInfo.PROCEDURE.equals(language)) { + return commonTemplateBody(true); + } else if ("C".equals(language)) { + return cLanguageTemplateBody(); + } else if ("SQL".equals(language)) { + return sqlLanguageTemplateBody(); + } else { + return commonTemplateBody(false); + } + } + + private String cLanguageTemplateBody() { + StringBuilder sb = new StringBuilder(); + sb.append("AS "); + sb.append(getLineSeparator()); + sb.append("\t'/*iso file path and name*/',$$/*function name*/$$"); + sb.append(getLineSeparator()); + sb.append(getEscapeForwardSlash()); + return sb.toString(); + } + + private String sqlLanguageTemplateBody() { + StringBuilder sb = new StringBuilder(); + sb.append("AS $$"); + sb.append(getLineSeparator()); + sb.append("\t/*executable_section*/"); + sb.append(getLineSeparator()); + sb.append(getLineSeparator()); + sb.append("$$"); + sb.append(getLineSeparator()); + sb.append(getEscapeForwardSlash()); + return sb.toString(); + } + + private String commonTemplateBody(boolean isProcedure) { + StringBuilder sb = new StringBuilder(128); + sb.append("AS"); + if (!isProcedure) { + sb.append(" $$"); + } + sb.append(getLineSeparator()); + sb.append("DECLARE"); + sb.append(getLineSeparator()); + sb.append("\t/*declaration_section*/"); + sb.append(getLineSeparator()); + sb.append(getLineSeparator()); + + sb.append("BEGIN"); + sb.append(getLineSeparator()); + sb.append("\t/*executable_section*/"); + sb.append(getLineSeparator()); + sb.append(getLineSeparator()); + + sb.append("END;"); + if (!isProcedure) { + sb.append("$$"); + } + sb.append(getLineSeparator()); + sb.append(getEscapeForwardSlash()); + return sb.toString(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createobj/ICreateTable.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createobj/ICreateTable.java new file mode 100644 index 0000000000000000000000000000000000000000..6ffa4df96de2a703728633864eee7b059c273458 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createobj/ICreateTable.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.createobj; + +/** + * + * Title: interface + * + * Description: The Interface ICreateTable. + * + * @since 3.0.0 + */ +public interface ICreateTable { + + /** + * Inits the. + */ + void init(); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createobj/factory/CreateTableUiFactory.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createobj/factory/CreateTableUiFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..79b90bd4e08be08a47025191f0376fe70e001d40 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createobj/factory/CreateTableUiFactory.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.createobj.factory; + +import org.eclipse.swt.widgets.Shell; + +import org.opengauss.mppdbide.bl.serverdatacache.INamespace; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.DBTYPE; +import org.opengauss.mppdbide.view.createobj.ICreateTable; +import org.opengauss.mppdbide.view.createobj.olap.CreateTableImpl; + +/** + * Title: CreateTableUiFactory + * + * Description:A factory for creating CreateTableUi objects. + * + * @since 3.0.0 + */ +public final class CreateTableUiFactory { + + private CreateTableUiFactory() { + + } + + /** + * Gets the creates the table UI initializer. + * + * @param shell the shell + * @param namespace the namespace + * @param server the server + * @return the creates the table UI initializer + */ + public static ICreateTable getCreateTableUIInitializer(Shell shell, INamespace namespace, Server server) { + + DBTYPE dbType = namespace.getDatabase().getDBType(); + + if (dbType == DBTYPE.OPENGAUSS) { + return new CreateTableImpl(shell, namespace, server); + } + return null; + + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createobj/handler/CreateTableHandler.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createobj/handler/CreateTableHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..4472a01027bd03b9048d73df0969eeb1851e7609 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createobj/handler/CreateTableHandler.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.createobj.handler; + +import org.eclipse.e4.core.di.annotations.CanExecute; +import org.eclipse.e4.core.di.annotations.Execute; +import org.eclipse.swt.widgets.Shell; + +import org.opengauss.mppdbide.bl.serverdatacache.INamespace; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.view.createobj.ICreateTable; +import org.opengauss.mppdbide.view.createobj.factory.CreateTableUiFactory; +import org.opengauss.mppdbide.view.handler.IHandlerUtilities; +import org.opengauss.mppdbide.view.search.SearchWindow; +import org.opengauss.mppdbide.view.utils.UIElement; + +/** + * + * Title: class + * + * Description: The Class CreateTableHandler. + * + * @since 3.0.0 + */ +public class CreateTableHandler { + + /** + * Execute. + * + * @param shell the shell + */ + @Execute + public void execute(final Shell shell) { + INamespace ns = IHandlerUtilities.getSelectedTableGroup(); + if (null != ns) { + Server server = ns.getDatabase().getServer(); + ICreateTable createTableUIInitializer = CreateTableUiFactory.getCreateTableUIInitializer(shell, ns, server); + if (createTableUIInitializer == null) { + return; + } + createTableUIInitializer.init(); + } + } + + /** + * Can execute. + * + * @return true, if successful + */ + @CanExecute + public boolean canExecute() { + Object object = UIElement.getInstance().getActivePartObject(); + if (object instanceof SearchWindow) { + return false; + } + INamespace ns = IHandlerUtilities.getSelectedTableGroup(); + return null != ns; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createobj/olap/CreateTableImpl.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createobj/olap/CreateTableImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..2ef47c87ea774cc672f7b4792d53681e49186b4b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/createobj/olap/CreateTableImpl.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.createobj.olap; + +import org.eclipse.swt.widgets.Shell; + +import org.opengauss.mppdbide.bl.serverdatacache.INamespace; +import org.opengauss.mppdbide.bl.serverdatacache.Namespace; +import org.opengauss.mppdbide.bl.serverdatacache.Server; +import org.opengauss.mppdbide.view.createobj.ICreateTable; +import org.opengauss.mppdbide.view.ui.table.CreateTable; + +/** + * + * Title: class + * + * Description: The Class CreateTableImpl. + * + * @since 3.0.0 + */ +public class CreateTableImpl implements ICreateTable { + + private Shell shell; + private Namespace namespace; + private Server server; + + /** + * Instantiates a new creates the table impl. + * + * @param shell the shell + * @param namespace the namespace + * @param server the server + */ + public CreateTableImpl(Shell shell, INamespace namespace, Server server) { + this.shell = shell; + this.namespace = (Namespace) namespace; + this.server = server; + } + + /** + * Inits the. + */ + @Override + public void init() { + CreateTable dlog = new CreateTable(shell, server, namespace); + dlog.open(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/data/DSViewApplicationObjectManager.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/data/DSViewApplicationObjectManager.java new file mode 100644 index 0000000000000000000000000000000000000000..a44e427e2c94e39294aa6d0799176b8923fb86d9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/data/DSViewApplicationObjectManager.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.data; + +import org.eclipse.e4.ui.model.application.MApplication; +import org.eclipse.e4.ui.workbench.modeling.EModelService; +import org.eclipse.e4.ui.workbench.modeling.EPartService; + +/** + * + * Title: class + * + * Description: The Class DSViewApplicationObjectManager. + * + * @since 3.0.0 + */ +public final class DSViewApplicationObjectManager implements DSViewApplicationObjectManagerIf { + + private static volatile DSViewApplicationObjectManager instance = null; + private static final Object LOCK = new Object(); + + private EPartService partService = null; + private EModelService modelService = null; + private MApplication application = null; + + /** + * Gets the single instance of DSViewApplicationObjectManager. + * + * @return single instance of DSViewApplicationObjectManager + */ + public static DSViewApplicationObjectManager getInstance() { + if (instance == null) { + synchronized (LOCK) { + if (instance == null) { + instance = new DSViewApplicationObjectManager(); + } + } + } + return instance; + } + + private DSViewApplicationObjectManager() { + + } + + /** + * Gets the part service. + * + * @return the part service + */ + public EPartService getPartService() { + return partService; + } + + /** + * Sets the part service. + * + * @param partService the new part service + */ + public void setPartService(EPartService partService) { + this.partService = partService; + } + + /** + * Gets the model service. + * + * @return the model service + */ + public EModelService getModelService() { + return modelService; + } + + /** + * Sets the model service. + * + * @param modelService the new model service + */ + public void setModelService(EModelService modelService) { + this.modelService = modelService; + } + + /** + * Gets the application. + * + * @return the application + */ + public MApplication getApplication() { + return application; + } + + /** + * Sets the application. + * + * @param application the new application + */ + public void setApplication(MApplication application) { + this.application = application; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/data/DSViewApplicationObjectManagerIf.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/data/DSViewApplicationObjectManagerIf.java new file mode 100644 index 0000000000000000000000000000000000000000..c18f8bd697c83b8df0c1d74403bbdd5284d4f8ac --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/data/DSViewApplicationObjectManagerIf.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.data; + +import org.eclipse.e4.ui.model.application.MApplication; +import org.eclipse.e4.ui.workbench.modeling.EModelService; +import org.eclipse.e4.ui.workbench.modeling.EPartService; + +/** + * + * Title: interface + * + * Description: The Interface DSViewApplicationObjectManagerIf. + * + * @since 3.0.0 + */ +public interface DSViewApplicationObjectManagerIf { + + /** + * Gets the part service. + * + * @return the part service + */ + public EPartService getPartService(); + + /** + * Sets the part service. + * + * @param partService the new part service + */ + public void setPartService(EPartService partService); + + /** + * Gets the model service. + * + * @return the model service + */ + public EModelService getModelService(); + + /** + * Sets the model service. + * + * @param modelService the new model service + */ + public void setModelService(EModelService modelService); + + /** + * Gets the application. + * + * @return the application + */ + public MApplication getApplication(); + + /** + * Sets the application. + * + * @param application the new application + */ + public void setApplication(MApplication application); + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/data/DSViewDataManager.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/data/DSViewDataManager.java new file mode 100644 index 0000000000000000000000000000000000000000..69282d00fe59a4dce7e9f3e02d3b492e341017e6 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/data/DSViewDataManager.java @@ -0,0 +1,253 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.data; + +import java.util.ArrayList; +import java.util.List; + +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * Title: class Description: The Class DSViewDataManager. + * + * @since 3.0.0 + */ +public final class DSViewDataManager { + + private static volatile DSViewDataManager instance = null; + + private static final Object LOCK = new Object(); + + private boolean showExplainPlanWarningsMultipleQuery = false; + + private boolean showExplainPlanWarningsAnalyzeQuery = false; + + private boolean isDebugBkptNotSupportedPopup = false; + + private boolean showCommitConfirmation = false; + + private boolean showRollbackConfirmation = false; + + private String currentOsUserPath; + + private List sourceViewerIds = new ArrayList(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); + + private boolean wbGoingToClose = false; + + private String treeRenderPolicy = null; + + /** + * Gets the single instance of DSViewDataManager. + * + * @return single instance of DSViewDataManager + */ + public static DSViewDataManager getInstance() { + if (instance == null) { + synchronized (LOCK) { + if (instance == null) { + instance = new DSViewDataManager(); + } + } + } + return instance; + } + + private DSViewDataManager() { + } + + /** + * Checks if is debug bkpt not supported popup. + * + * @return true, if is debug bkpt not supported popup + */ + public boolean isDebugBkptNotSupportedPopup() { + return isDebugBkptNotSupportedPopup; + } + + /** + * Sets the debug bkpt not supported popup. + * + * @param lDebugBreakpointSupported the new debug bkpt not supported popup + */ + public void setDebugBkptNotSupportedPopup(boolean lDebugBreakpointSupported) { + isDebugBkptNotSupportedPopup = lDebugBreakpointSupported; + } + + /** + * Checks if is show explain plan warnings analyze query. + * + * @return true, if is show explain plan warnings analyze query + */ + public boolean isShowExplainPlanWarningsAnalyzeQuery() { + return showExplainPlanWarningsAnalyzeQuery; + } + + /** + * Sets the show explain plan warnings analyze query. + * + * @param lShowExplainPlanWarningsAnalyzeQuery the new show explain plan + * warnings analyze query + */ + public void setShowExplainPlanWarningsAnalyzeQuery(boolean lShowExplainPlanWarningsAnalyzeQuery) { + showExplainPlanWarningsAnalyzeQuery = lShowExplainPlanWarningsAnalyzeQuery; + } + + /** + * Checks if is show explain plan warnings multiple query. + * + * @return true, if is show explain plan warnings multiple query + */ + public boolean isShowExplainPlanWarningsMultipleQuery() { + return showExplainPlanWarningsMultipleQuery; + } + + /** + * Sets the show explain plan warnings multiple query. + * + * @param lShowExplainPlanWarningsMultipleQuery the new show explain plan + * warnings multiple query + */ + public void setShowExplainPlanWarningsMultipleQuery(boolean lShowExplainPlanWarningsMultipleQuery) { + showExplainPlanWarningsMultipleQuery = lShowExplainPlanWarningsMultipleQuery; + } + + /** + * Checks if is show commit confirmation. + * + * @return true, if is show commit confirmation + */ + public boolean isShowCommitConfirmation() { + return showCommitConfirmation; + } + + /** + * Sets the show commit confirmation. + * + * @param lShowCommitConfirmation the new show commit confirmation + */ + public void setShowCommitConfirmation(boolean lShowCommitConfirmation) { + showCommitConfirmation = lShowCommitConfirmation; + } + + /** + * Checks if is show rollback confirmation. + * + * @return true, if is show rollback confirmation + */ + public boolean isShowRollbackConfirmation() { + return showRollbackConfirmation; + } + + /** + * Sets the show rollback confirmation. + * + * @param lShowRollbackConfirmation the new show rollback confirmation + */ + public void setShowRollbackConfirmation(boolean lShowRollbackConfirmation) { + showRollbackConfirmation = lShowRollbackConfirmation; + } + + /** + * Gets the current os user path. + * + * @return the current os user path + */ + public String getCurrentOsUserPath() { + return currentOsUserPath; + } + + /** + * Sets the current os user path. + * + * @param currentOsUserPath the new current os user path + */ + public void setCurrentOsUserPath(String currentOsUserPath) { + this.currentOsUserPath = currentOsUserPath; + } + + /** + * Gets the source viewer id. + * + * @return the source viewer id + */ + public List getSourceViewerId() { + return sourceViewerIds; + } + + /** + * Sets the source viewer id. + * + * @param sourceViewerId the new source viewer id + */ + public void setSourceViewerId(List sourceViewerId) { + this.sourceViewerIds = sourceViewerId; + } + + /** + * Adds the source viewer id. + * + * @param id the id + */ + public void addSourceViewerId(String id) { + sourceViewerIds.add(id); + } + + /** + * Removes the source viewer id only. + * + * @param id the id + */ + public void removeSourceViewerIdOnly(String id) { + sourceViewerIds.remove(id); + } + + /** + * Checks if is wb going to close. + * + * @return true, if is wb going to close + */ + public boolean isWbGoingToClose() { + return wbGoingToClose; + } + + /** + * Sets the wb going to close. + * + * @param wbGoingToClose the new wb going to close + */ + public void setWbGoingToClose(boolean wbGoingToClose) { + this.wbGoingToClose = wbGoingToClose; + } + + /** + * get the tree render policy + * + * @return returns policy type + */ + public String getTreeRenderPolicy() { + return treeRenderPolicy; + } + + /** + * set the tree render policy + * + * @param treeRenderPolicy set the tree render policy + */ + public void setTreeRenderPolicy(String treeRenderPolicy) { + this.treeRenderPolicy = treeRenderPolicy; + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/data/DSViewFactoryManager.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/data/DSViewFactoryManager.java new file mode 100644 index 0000000000000000000000000000000000000000..e23ae2da0b02de21ff8afa220d7abbbb32d53ed7 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/data/DSViewFactoryManager.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.data; + +/** + * + * Title: class + * + * Description: The Class DSViewFactoryManager. + * + * @since 3.0.0 + */ +public abstract class DSViewFactoryManager { + + /** + * Gets the DS view application object manager. + * + * @return the DS view application object manager + */ + public static DSViewApplicationObjectManagerIf getDSViewApplicationObjectManager() { + return DSViewApplicationObjectManager.getInstance(); + } + +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/diskmgr/OsUserDiskManager.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/diskmgr/OsUserDiskManager.java new file mode 100644 index 0000000000000000000000000000000000000000..69b91601f815aca27263a6a4c0867ad8fac1c195 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/diskmgr/OsUserDiskManager.java @@ -0,0 +1,260 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.diskmgr; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.Normalizer; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.util.BLUtils; +import org.opengauss.mppdbide.utils.EnvirnmentVariableValidator; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.exceptions.DataStudioSecurityException; +import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; +import org.opengauss.mppdbide.utils.exceptions.MPPDBIDEException; +import org.opengauss.mppdbide.utils.files.FilePermissionFactory; +import org.opengauss.mppdbide.utils.files.ISetFilePermission; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.utils.security.SecureUtil; +import org.opengauss.mppdbide.view.autosave.AutoSaveManager; +import org.opengauss.mppdbide.view.data.DSViewDataManager; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs.MESSAGEDIALOGTYPE; + +/** + * + * Title: class + * + * Description: The Class OsUserDiskManager. + * + * @since 3.0.0 + */ +public final class OsUserDiskManager { + private static final String LOGS = "logs"; + private static final String DATA_STUDIO_LOG = "Data Studio.log"; + private static final String DATA_STUDIO_SECURITY_LOG = "security.log"; + private static final String DATA_STUDIO_OPERATION_LOG = "operation.log"; + private String userDataFolder = MPPDBIDEConstants.USER_DATA_FOLDER; + private String usrFolderName = ""; + private ISetFilePermission filePermissions = FilePermissionFactory.getFilePermissionInstance(); + private static volatile OsUserDiskManager instance; + private static final Object LOCK = new Object(); + private String currentOsUserPath; + + /** + * Gets the single instance of OsUserDiskManager. + * + * @return single instance of OsUserDiskManager + */ + public static OsUserDiskManager getInstance() { + + if (instance == null) { + synchronized (LOCK) { + if (instance == null) { + instance = new OsUserDiskManager(); + } + } + + } + + return instance; + } + + private OsUserDiskManager() { + + } + + private void initializeOsUserName() throws DataStudioSecurityException { + String usrName = EnvirnmentVariableValidator.validateAndGetUserName(); + if (usrName.isEmpty()) { + throw new DataStudioSecurityException("Not able to get the OS Username."); + } + usrFolderName = usrName; + } + + /** + * Creates the parent folder structure. + * + * @param isReadFilePath the is read file path + * @throws MPPDBIDEException the MPPDBIDE exception + */ + public void createParentFolderStructure(String isReadFilePath) throws MPPDBIDEException { + + Path folderPath = getUserDataFolderPath(); + String normalizedFolderPath = (folderPath != null && folderPath.normalize() != null) + ? folderPath.normalize().toString() + : ""; + filePermissions.createFileWithPermission(normalizedFolderPath, true, null, false); + + // Create osUserFolder + SecureUtil secureUtil = new SecureUtil(); + createOsUserFolderStructure(folderPath, secureUtil); + + // Create the log folder + createLogFolder(isReadFilePath); + + // Get Initial Instance of SecureUtil and Create User level security + // folder + secureUtil.runPreEncryptionTask(); + + } + + private void createOsUserFolderStructure(Path folderPath, SecureUtil secureUtil) throws MPPDBIDEException { + + currentOsUserPath = getOsUserFolderPath(folderPath); + DSViewDataManager.getInstance().setCurrentOsUserPath(currentOsUserPath); + + filePermissions.createFileWithPermission(currentOsUserPath, true, null, true); + + secureUtil.setPackagePath(currentOsUserPath); + + ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath(currentOsUserPath); + AutoSaveManager.getInstance().getDiskUtility().setOsCurrentUserFolderPath(currentOsUserPath); + } + + private String getOsUserFolderPath(Path folderPath) throws DataStudioSecurityException { + if ("".equals(usrFolderName)) { + initializeOsUserName(); + if (null == usrFolderName || "".equals(usrFolderName)) { + MPPDBIDELoggerUtility.error("Not able to get the OS Username."); + throw new DataStudioSecurityException("Not able to get the OS Username."); + } + } + Path osUserFolderPath = Paths.get(userDataFolder, usrFolderName); + return osUserFolderPath.toString(); + } + + private void createLogFolder(String logFolder) throws MPPDBIDEException { + + try { + String logPath = null; + if (null != logFolder && !".".equals(logFolder)) { + File file = new File(logFolder); + if (!file.exists()) { + createFileIfNotExiste(); + logPath = currentOsUserPath; + } else { + createPermissionIfFileExists(logFolder, file); + logPath = logFolder + File.separator + usrFolderName; + } + + } else { + createNewLogFolder(); + logPath = currentOsUserPath; + } + // add to system property. + System.setProperty("mppide.log", + logPath + File.separator + LOGS + File.separator + DATA_STUDIO_LOG); + System.setProperty("mppidesecurity.log", + logPath + File.separator + LOGS + File.separator + DATA_STUDIO_SECURITY_LOG); + System.setProperty("mppideoperation.log", + logPath + File.separator + LOGS + File.separator + DATA_STUDIO_OPERATION_LOG); + } catch (DatabaseOperationException e) { + MPPDBIDEDialogs.generateOKMessageDialog(MESSAGEDIALOGTYPE.ERROR, true, + MessageConfigLoader.getProperty(IMessagesConstants.LOG_ERR_TITLE), + MessageConfigLoader.getProperty(IMessagesConstants.LOG_ERR_MSG, e.getMessage())); + } + + MPPDBIDELoggerUtility.checkAndCreateLogger(true); + } + + private void createNewLogFolder() throws MPPDBIDEException { + File file = new File(currentOsUserPath); + // Check if folder has write permission + boolean canWrite = Files.isWritable(file.toPath()); + + if (canWrite) { + String logsFolder = currentOsUserPath + File.separator + LOGS; + ISetFilePermission withPermission = FilePermissionFactory.getFilePermissionInstance(); + Path pathLogsFolder = withPermission.createFileWithPermission(logsFolder, true, null, true); + + if (Files.isWritable(pathLogsFolder) || pathLogsFolder.toFile().exists()) { + String logFileName = pathLogsFolder + File.separator + DATA_STUDIO_LOG; + createLogFile("mppide.log", logFileName); + String securitylogFileName = pathLogsFolder + File.separator + DATA_STUDIO_SECURITY_LOG; + createLogFile("mppidesecurity.log", securitylogFileName); + String operationlogFileName = pathLogsFolder + File.separator + DATA_STUDIO_OPERATION_LOG; + createLogFile("mppideoperation.log", operationlogFileName); + } + } + } + + private void createLogFile(String propertyName, String logFileName) + throws DatabaseOperationException, MPPDBIDEException { + boolean canWrite; + + ISetFilePermission withPermissionLogFileName = FilePermissionFactory.getFilePermissionInstance(); + Path pathLogFileName = withPermissionLogFileName.createFileWithPermission(logFileName, false, null, true); + + // check if the file has write permission + canWrite = Files.isWritable(pathLogFileName); + // If if file has write permission or file does not exist, + // set + // the user mentioned path + // If file does not exist, log4j framework will create the + // file + if (canWrite || !pathLogFileName.toFile().exists()) { + System.setProperty(propertyName, logFileName); + } else { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_BL_CREATE_FILE_DIRECTORY)); + throw new MPPDBIDEException(IMessagesConstants.ERR_BL_CREATE_FILE_DIRECTORY); + } + } + + private void createPermissionIfFileExists(String logFolder, File file) + throws DatabaseOperationException, MPPDBIDEException { + // Check if folder has write permission + boolean canWrite = Files.isWritable(file.toPath()); + + if (canWrite) { + String userDirectory = logFolder + File.separator + usrFolderName + File.separator; + filePermissions.createFileWithPermission(userDirectory, true, null, true); + } else { + MPPDBIDELoggerUtility + .error(MessageConfigLoader.getProperty(IMessagesConstants.ERR_BL_CREATE_FILE_DIRECTORY)); + throw new MPPDBIDEException(IMessagesConstants.ERR_BL_CREATE_FILE_DIRECTORY); + } + } + + private void createFileIfNotExiste() throws DatabaseOperationException { + String logsDir; + MPPDBIDEDialogs.generateOKMessageDialog(MESSAGEDIALOGTYPE.INFORMATION, true, + MessageConfigLoader.getProperty(IMessagesConstants.INCORRECT_PATH), + MessageConfigLoader.getProperty(IMessagesConstants.INCORRECT_PATH_MSG)); + logsDir = currentOsUserPath + File.separator + LOGS; + + filePermissions.createFileWithPermission(logsDir, true, null, true); + } + + /** + * Gets the user data folder path. + * + * @return the user data folder path + */ + public Path getUserDataFolderPath() { + Path parentPath = Paths.get(BLUtils.getInstance().getInstallationLocation(), + MPPDBIDEConstants.USER_DATA_FOLDER); + return (parentPath.toAbsolutePath() != null) ? parentPath.toAbsolutePath().normalize() : null; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/dto/version/UIVersionDO.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/dto/version/UIVersionDO.java new file mode 100644 index 0000000000000000000000000000000000000000..afa739386c6d6a3bd72e42d632f43887649e6527 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/dto/version/UIVersionDO.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.dto.version; + +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; + +/** + * + * Title: class + * + * Description: The Class UIVersionDO. + * + * @since 3.0.0 + */ +public class UIVersionDO { + private static final String RELEASE_NAME = "Data Studio "; + private static final int VERSION = 2; + private static final String DOT = "."; + private static final int SUB_VERSION = 1; + private static final int SUB_SUB_VERSION = 0; + private static final String MINOR_VERSION = ""; + + /** + * Gets the UI version. + * + * @return the UI version + */ + public static String getUIVersion() { + StringBuilder sb = new StringBuilder(RELEASE_NAME); + sb.append(VERSION).append(DOT).append(SUB_VERSION).append(DOT).append(SUB_SUB_VERSION) + .append(MPPDBIDEConstants.SPACE_CHAR).append(MINOR_VERSION); + return sb.toString(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/editor/extension/IEditorExtension.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/editor/extension/IEditorExtension.java new file mode 100644 index 0000000000000000000000000000000000000000..9e9f64b04b919adf3c7d9252edaaad8f3fd982b9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/editor/extension/IEditorExtension.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.editor.extension; + +/** + * + * Title: interface + * + * Description: The Interface IEditorExtension. + * + * @since 3.0.0 + */ +public interface IEditorExtension { + + /** + * Format queries. + * + * @param input the input + * @param startOffset the start offset + * @param lineDelimiter the line delimiter + * @return the string + */ + String formatQueries(String input, int startOffset, String lineDelimiter); +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/contextmenu/ERAttributeVisibility.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/contextmenu/ERAttributeVisibility.java new file mode 100644 index 0000000000000000000000000000000000000000..c9c197d4e548ffd663ae05ad7e09c49a452887e4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/contextmenu/ERAttributeVisibility.java @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.erd.contextmenu; + +import org.eclipse.jface.preference.IPreferenceStore; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.prefernces.PreferenceWrapper; + +/** + * Title: ERAttributeVisibility + * + * Description: The enum category of show attribute. + * + * @since 3.0.0 + */ +public enum ERAttributeVisibility { + + /** + * The all. + */ + ALL(1, MessageConfigLoader.getProperty(IMessagesConstants.ATTRIBUTE_VIS_ALL)), + + /** + * The any keys. + */ + ANY_KEYS(2, MessageConfigLoader.getProperty(IMessagesConstants.ATTRIBUTE_VIS_ANY_KEY)), + + /** + * The primary key. + */ + PRIMARY_KEY(4, MessageConfigLoader.getProperty(IMessagesConstants.ATTRIBUTE_VIS_PRIMARY_KEY)), + + /** + * The none. + */ + NONE(8, MessageConfigLoader.getProperty(IMessagesConstants.ATTRIBUTE_VIS_NONE)); + + private static final IPreferenceStore PREFERENCE_STORE = PreferenceWrapper.getInstance().getPreferenceStore(); + + private final int value; + private final String title; + + /** + * Instantiates a new ER attribute visibility. + * + * @param value the value + * @param title the title + */ + ERAttributeVisibility(int value, String title) { + this.value = value; + this.title = title; + } + + /** + * Gets the value. + * + * @return the value + */ + public int getValue() { + return value; + } + + /** + * Gets the title. + * + * @return the title + */ + public String getTitle() { + return title; + } + + /** + * Gets the default visibility. + * + * @return the default visibility + */ + public static ERAttributeVisibility getDefaultVisibility() { + String attrVisibilityString = PREFERENCE_STORE.getString(ERPreferencekeys.PREF_ATTR_VISIBILITY); + if (!(null == attrVisibilityString || attrVisibilityString.length() == 0)) { + return ERAttributeVisibility.valueOf(attrVisibilityString); + } + + return ALL; + } + + /** + * Sets the default visibility. + * + * @param visibility the new default visibility + */ + static void setDefaultVisiblity(ERAttributeVisibility visibility) { + PREFERENCE_STORE.setValue(ERPreferencekeys.PREF_ATTR_VISIBILITY, visibility.name()); + } + + /** + * Checks if is all. + * + * @return true, if is all + */ + public static boolean isAll() { + return ALL == getDefaultVisibility(); + } + + /** + * Checks if is any key. + * + * @return true, if is any key + */ + public static boolean isAnyKey() { + return ANY_KEYS == getDefaultVisibility(); + } + + /** + * Checks if is primary key. + * + * @return true, if is primary key + */ + public static boolean isPrimaryKey() { + return PRIMARY_KEY == getDefaultVisibility(); + } + + /** + * Checks if is none. + * + * @return true, if is none + */ + public static boolean isNone() { + return NONE == getDefaultVisibility(); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/contextmenu/ERContextMenu.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/contextmenu/ERContextMenu.java new file mode 100644 index 0000000000000000000000000000000000000000..47e65a07cb579a80dc3d7ffd91b8b192e467f4ee --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/contextmenu/ERContextMenu.java @@ -0,0 +1,289 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.erd.contextmenu; + +import java.util.Collections; +import java.util.List; + +import org.eclipse.e4.ui.model.application.ui.basic.MPart; +import org.eclipse.gef.graph.Graph; +import org.eclipse.gef.mvc.fx.viewer.IViewer; + +import org.opengauss.mppdbide.presentation.erd.AbstractERPresentation; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.erd.convertor.ERModelToGraphModelConvertor; +import org.opengauss.mppdbide.view.ui.erd.ERPart; +import org.opengauss.mppdbide.view.utils.UIElement; + +import javafx.scene.control.CheckMenuItem; +import javafx.scene.control.ContextMenu; +import javafx.scene.control.Menu; +import javafx.scene.control.RadioMenuItem; +import javafx.scene.control.ToggleGroup; + +/** + * Title: ERContextMenu Description: the popup menu. + * + * @since 3.0.0 + */ +public class ERContextMenu extends ContextMenu { + private IViewer viewer; + private AbstractERPresentation diagram; + + private Menu viewStyleMenu; + private CheckMenuItem showIconsItem; + private CheckMenuItem showDataTypesItem; + private CheckMenuItem showNullabilityItem; + private CheckMenuItem showCommentsItem; + private CheckMenuItem showFullyQualifiedNamesItem; + private Menu attributeVisibilityMenu; + private RadioMenuItem attrVisibilityAllItem; + private RadioMenuItem attrVisibilityAnyKeysItem; + private RadioMenuItem attrVisibilityPrimaryKeyItem; + private RadioMenuItem attrVisibilityNoneItem; + + /** + * Instantiates a new ER context menu. + * + * @param viewer the viewer + * @param diagram the diagram + */ + public ERContextMenu(IViewer viewer, AbstractERPresentation diagram) { + this.viewer = viewer; + this.diagram = diagram; + } + + /** + * Inits the ER context menu. + */ + public void initERContextMenu() { + viewStyleMenu = new Menu(); + viewStyleMenu.setText(MessageConfigLoader.getProperty(IMessagesConstants.VIEW_STYLES)); + getItems().add(viewStyleMenu); + attributeVisibilityMenu = new Menu(); + attributeVisibilityMenu.setText(MessageConfigLoader.getProperty(IMessagesConstants.SHOW_ATTRIBUTES)); + getItems().add(attributeVisibilityMenu); + + addShowIconsMenuItem(viewStyleMenu); + addShowDataTypesMenuItem(viewStyleMenu); + addShowNullabilityMenuItem(viewStyleMenu); + addShowCommentsMenuItem(viewStyleMenu); + addShowFullyQualifiedNamesMenuItem(viewStyleMenu); + + ToggleGroup toggleGroup = new ToggleGroup(); + addAttrVisibilityAllItem(attributeVisibilityMenu, toggleGroup); + addAttrVisibilityAnyKeysItem(attributeVisibilityMenu, toggleGroup); + addAttrVisibilityPrimaryKeyItem(attributeVisibilityMenu, toggleGroup); + addAttrVisibilityNoneItem(attributeVisibilityMenu, toggleGroup); + } + + /** + * Gets the viewer. + * + * @return the viewer + */ + public IViewer getViewer() { + return viewer; + } + + /** + * Gets the diagram. + * + * @return the diagram + */ + public AbstractERPresentation getDiagram() { + return diagram; + } + + private void addShowIconsMenuItem(Menu menu) { + showIconsItem = new CheckMenuItem(); + ERViewStyle style = ERViewStyle.ICONS; + showIconsItem.setText(style.getTitle()); + showIconsItem.setSelected(isCheckedViewStyle(style)); + showIconsItem.setOnAction(actionEvent -> { + refreshViewStyle(style); + }); + menu.getItems().add(showIconsItem); + } + + private void addShowDataTypesMenuItem(Menu menu) { + showDataTypesItem = new CheckMenuItem(); + ERViewStyle style = ERViewStyle.TYPES; + showDataTypesItem.setText(style.getTitle()); + showDataTypesItem.setSelected(isCheckedViewStyle(style)); + showDataTypesItem.setOnAction(actionEvent -> { + refreshViewStyle(style); + }); + menu.getItems().add(showDataTypesItem); + } + + private void addShowNullabilityMenuItem(Menu menu) { + showNullabilityItem = new CheckMenuItem(); + ERViewStyle style = ERViewStyle.NULLABILITY; + showNullabilityItem.setText(style.getTitle()); + showNullabilityItem.setSelected(isCheckedViewStyle(style)); + showNullabilityItem.setOnAction(actionEvent -> { + refreshViewStyle(style); + }); + menu.getItems().add(showNullabilityItem); + } + + private void addShowCommentsMenuItem(Menu menu) { + showCommentsItem = new CheckMenuItem(); + ERViewStyle style = ERViewStyle.COMMENTS; + showCommentsItem.setText(style.getTitle()); + showCommentsItem.setSelected(isCheckedViewStyle(style)); + showCommentsItem.setOnAction(actionEvent -> { + refreshViewStyle(style); + }); + menu.getItems().add(showCommentsItem); + } + + private void addShowFullyQualifiedNamesMenuItem(Menu menu) { + showFullyQualifiedNamesItem = new CheckMenuItem(); + ERViewStyle style = ERViewStyle.ENTITY_FQN; + showFullyQualifiedNamesItem.setText(style.getTitle()); + showFullyQualifiedNamesItem.setSelected(isCheckedViewStyle(style)); + showFullyQualifiedNamesItem.setOnAction(actionEvent -> { + refreshViewStyle(style); + }); + menu.getItems().add(showFullyQualifiedNamesItem); + } + + /** + * Check if the ERDViewStyle is checked. + * + * @Title: isChecked + * @param style the style + * @return true, if the ERDViewStyle is checked. + */ + private boolean isCheckedViewStyle(ERViewStyle style) { + return ERViewStyle.isContainViewStyle(ERViewStyle.getDefaultStyles(), style); + } + + private void refreshViewStyle(ERViewStyle style) { + ERViewStyle.setAttributeStyle(style, !isCheckedViewStyle(style)); + if (ERViewStyle.getAttributeStyles().size() == 0) { + ERViewStyle.setAttributeStyle(ERViewStyle.ICONS, true); + showIconsItem.setSelected(true); + } + + List list = UIElement.getInstance().getAllOpenERPart(); + for (MPart mPart : list) { + if (mPart.getObject() instanceof ERPart) { + ERPart erPart = (ERPart) mPart.getObject(); + + AbstractERPresentation erDiagram = erPart.getErContextMenu().getDiagram(); + Graph graph = ERModelToGraphModelConvertor.getGraphModel(erDiagram); + erPart.getErContextMenu().getViewer().getContents().setAll(Collections.singletonList(graph)); + erPart.getErContextMenu().setItemsSelectStatu(); + } + } + } + + private void setItemsSelectStatu() { + if (ERViewStyle.isShowIcons()) { + showIconsItem.setSelected(true); + } else { + showIconsItem.setSelected(false); + } + + if (ERViewStyle.isShowDataTypes()) { + showDataTypesItem.setSelected(true); + } else { + showDataTypesItem.setSelected(false); + } + + if (ERViewStyle.isShowNullability()) { + showNullabilityItem.setSelected(true); + } else { + showNullabilityItem.setSelected(false); + } + + if (ERViewStyle.isShowComments()) { + showCommentsItem.setSelected(true); + } else { + showCommentsItem.setSelected(false); + } + + if (ERViewStyle.isShowFullyQualifiedNames()) { + showFullyQualifiedNamesItem.setSelected(true); + } else { + showFullyQualifiedNamesItem.setSelected(false); + } + } + + private void addAttrVisibilityAllItem(Menu menu, ToggleGroup toggleGroup) { + attrVisibilityAllItem = new RadioMenuItem(); + ERAttributeVisibility visibility = ERAttributeVisibility.ALL; + attrVisibilityAllItem.setText(visibility.getTitle()); + attrVisibilityAllItem.setSelected(isCheckedAttributeVisibility(visibility)); + attrVisibilityAllItem.setOnAction(actionEvent -> { + refreshAttributeVisibility(visibility); + }); + attrVisibilityAllItem.setToggleGroup(toggleGroup); + menu.getItems().add(attrVisibilityAllItem); + } + + private void addAttrVisibilityAnyKeysItem(Menu menu, ToggleGroup toggleGroup) { + attrVisibilityAnyKeysItem = new RadioMenuItem(); + ERAttributeVisibility visibility = ERAttributeVisibility.ANY_KEYS; + attrVisibilityAnyKeysItem.setText(visibility.getTitle()); + attrVisibilityAnyKeysItem.setSelected(isCheckedAttributeVisibility(visibility)); + attrVisibilityAnyKeysItem.setOnAction(actionEvent -> { + refreshAttributeVisibility(visibility); + }); + attrVisibilityAnyKeysItem.setToggleGroup(toggleGroup); + menu.getItems().add(attrVisibilityAnyKeysItem); + } + + private void addAttrVisibilityPrimaryKeyItem(Menu menu, ToggleGroup toggleGroup) { + attrVisibilityPrimaryKeyItem = new RadioMenuItem(); + ERAttributeVisibility visibility = ERAttributeVisibility.PRIMARY_KEY; + attrVisibilityPrimaryKeyItem.setText(visibility.getTitle()); + attrVisibilityPrimaryKeyItem.setSelected(isCheckedAttributeVisibility(visibility)); + attrVisibilityPrimaryKeyItem.setOnAction(actionEvent -> { + refreshAttributeVisibility(visibility); + }); + attrVisibilityPrimaryKeyItem.setToggleGroup(toggleGroup); + menu.getItems().add(attrVisibilityPrimaryKeyItem); + } + + private void addAttrVisibilityNoneItem(Menu menu, ToggleGroup toggleGroup) { + attrVisibilityNoneItem = new RadioMenuItem(); + ERAttributeVisibility visibility = ERAttributeVisibility.NONE; + attrVisibilityNoneItem.setText(visibility.getTitle()); + attrVisibilityNoneItem.setSelected(isCheckedAttributeVisibility(visibility)); + attrVisibilityNoneItem.setOnAction(actionEvent -> { + refreshAttributeVisibility(visibility); + }); + attrVisibilityNoneItem.setToggleGroup(toggleGroup); + menu.getItems().add(attrVisibilityNoneItem); + } + + private boolean isCheckedAttributeVisibility(ERAttributeVisibility visibility) { + return visibility == ERAttributeVisibility.getDefaultVisibility(); + } + + private void refreshAttributeVisibility(ERAttributeVisibility visibility) { + ERAttributeVisibility.setDefaultVisiblity(visibility); + + AbstractERPresentation digram = this.getDiagram(); + Graph graph = ERModelToGraphModelConvertor.getGraphModel(digram); + this.getViewer().getContents().setAll(Collections.singletonList(graph)); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/contextmenu/ERPreferencePage.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/contextmenu/ERPreferencePage.java new file mode 100644 index 0000000000000000000000000000000000000000..e9708881e6245e79f2925c0af2361d33462feecf --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/contextmenu/ERPreferencePage.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.erd.contextmenu; + +import org.eclipse.jface.preference.PreferenceStore; + +/** + * Title: ERPreferencePage + * + * @since 3.0.0 + */ +public class ERPreferencePage { + + /** + * Sets the default preferences. + * + * @param preferenceStore the new default preferences + */ + public static void setDefaultPreferences(PreferenceStore preferenceStore) { + + preferenceStore.setDefault(ERPreferencekeys.PREF_ATTR_STYLES, ERViewStyle.ICONS.name()); + + preferenceStore.setDefault(ERPreferencekeys.PREF_ATTR_VISIBILITY, ERAttributeVisibility.ALL.name()); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/contextmenu/ERPreferencekeys.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/contextmenu/ERPreferencekeys.java new file mode 100644 index 0000000000000000000000000000000000000000..114c25d3d19fb1b0804887b10d97c2bf36593d0f --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/contextmenu/ERPreferencekeys.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.erd.contextmenu; + +/** + * + * Title: ERPreferencekeys + * + * @since 3.0.0 + */ +public interface ERPreferencekeys { + String PREF_ATTR_STYLES = "org.opengauss.mppdbide.view.erd.contextmenu.erviewstyle"; + + String PREF_ATTR_VISIBILITY = "org.opengauss.mppdbide.view.erd.contextmenu.erattributevisibility"; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/contextmenu/ERViewStyle.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/contextmenu/ERViewStyle.java new file mode 100644 index 0000000000000000000000000000000000000000..6f6e4b193f62a67b09c91e639f03e7bdfbc5f5e3 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/contextmenu/ERViewStyle.java @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.erd.contextmenu; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.jface.preference.IPreferenceStore; + +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.view.prefernces.PreferenceWrapper; + +/** + * Title: ERViewStyle + * + * Description: The enum category of view styles. + * + * @since 3.0.0 + */ +public enum ERViewStyle { + + /** + * The icons. + */ + ICONS(1, MessageConfigLoader.getProperty(IMessagesConstants.SHOW_ICONS)), + + /** + * The types. + */ + TYPES(2, MessageConfigLoader.getProperty(IMessagesConstants.SHOW_DATA_TYPES)), + + /** + * The nullability. + */ + NULLABILITY(4, MessageConfigLoader.getProperty(IMessagesConstants.SHOW_NULLABILITY)), + + /** + * The comments. + */ + COMMENTS(8, MessageConfigLoader.getProperty(IMessagesConstants.SHOW_COMMENTS)), + + /** + * The entity fqn. + */ + ENTITY_FQN(16, MessageConfigLoader.getProperty(IMessagesConstants.SHOW_FULLY_QUALIFIED_NAMES)); + + private static final IPreferenceStore PREFERENCE_STORE = PreferenceWrapper.getInstance().getPreferenceStore(); + private static List attributeStyles = getDefaultStyles(); + + private final int value; + private final String title; + + /** + * Instantiates a new ER view style. + * + * @param value the value + * @param title the title + */ + ERViewStyle(int value, String title) { + this.value = value; + this.title = title; + } + + /** + * Gets the value. + * + * @return the value + */ + public int getValue() { + return value; + } + + /** + * Gets the title. + * + * @return the title + */ + public String getTitle() { + return title; + } + + /** + * Gets the default styles. + * + * @return the default styles + */ + public static List getDefaultStyles() { + String attrString = PREFERENCE_STORE.getString(ERPreferencekeys.PREF_ATTR_STYLES); + List vsList = new ArrayList<>(); + if (!(attrString == null || attrString.length() == 0)) { + String[] psList = attrString.split(","); + for (int i = 0; i < psList.length; i++) { + vsList.add(ERViewStyle.valueOf(psList[i])); + } + } else { + vsList.add(ICONS); + } + + return vsList; + } + + /** + * Sets the default styles. + * + * @param styles the new default styles + */ + private static void setDefaultStyles(List styles) { + StringBuffer stylesString = new StringBuffer(); + for (ERViewStyle style : styles) { + if (!(stylesString.length() == 0)) { + stylesString.append(","); + } + stylesString.append(style.name()); + } + PREFERENCE_STORE.setValue(ERPreferencekeys.PREF_ATTR_STYLES, stylesString.toString()); + } + + /** + * Sets the attribute style. + * + * @param style the style + * @param enable the enable + */ + public static void setAttributeStyle(ERViewStyle style, boolean enable) { + if (enable) { + attributeStyles.add(style); + } else { + attributeStyles.remove(style); + } + setDefaultStyles(attributeStyles); + } + + /** + * Gets the attribute styles. + * + * @return the attribute styles + */ + public static List getAttributeStyles() { + return attributeStyles; + } + + /** + * Checks if is contain view style. + * + * @param vsList the vs list + * @param style the style + * @return true, if is contain view style + */ + public static boolean isContainViewStyle(List vsList, ERViewStyle style) { + if (null == vsList) { + return false; + } + + return vsList.contains(style); + } + + /** + * Checks if is show icons. + * + * @return true, if is show icons + */ + public static boolean isShowIcons() { + return getDefaultStyles().contains(ICONS); + } + + /** + * Checks if is show data types. + * + * @return true, if is show data types + */ + public static boolean isShowDataTypes() { + return getDefaultStyles().contains(TYPES); + } + + /** + * Checks if is show nullability. + * + * @return true, if is show nullability + */ + public static boolean isShowNullability() { + return getDefaultStyles().contains(NULLABILITY); + } + + /** + * Checks if is show comments. + * + * @return true, if is show comments + */ + public static boolean isShowComments() { + return getDefaultStyles().contains(COMMENTS); + } + + /** + * Checks if is show fully qualified names. + * + * @return true, if is show fully qualified names + */ + public static boolean isShowFullyQualifiedNames() { + return getDefaultStyles().contains(ENTITY_FQN); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/convertor/ERModelToGraphModelConvertor.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/convertor/ERModelToGraphModelConvertor.java new file mode 100644 index 0000000000000000000000000000000000000000..7cc8924dac00584d39d29aaec2591ee29e09a8f4 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/convertor/ERModelToGraphModelConvertor.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.erd.convertor; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.eclipse.gef.geometry.planar.Point; +import org.eclipse.gef.graph.Edge; +import org.eclipse.gef.graph.Edge.Builder; +import org.eclipse.gef.graph.Graph; +import org.eclipse.gef.graph.Node; +import org.eclipse.gef.zest.fx.ZestProperties; + +import org.opengauss.mppdbide.bl.erd.model.AbstractERAssociation; +import org.opengauss.mppdbide.bl.erd.model.AbstractEREntity; +import org.opengauss.mppdbide.bl.erd.model.IERNodeConstants; +import org.opengauss.mppdbide.bl.serverdatacache.ServerObject; +import org.opengauss.mppdbide.presentation.erd.AbstractERPresentation; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.view.erd.visuals.ERLayout; +import org.opengauss.mppdbide.view.erd.visuals.IERVisualStyleConstants; + +import javafx.scene.shape.Circle; +import javafx.scene.shape.Polygon; + +/** + * Title: ERModelToGraphModelConvertor + * + * @since 3.0.0 + */ +public class ERModelToGraphModelConvertor { + + /** + * Gets the graph model. + * + * @param presentation the presentation + * @return the graph model + */ + public static Graph getGraphModel(AbstractERPresentation presentation) { + List nodes = new ArrayList<>(1); + List edges = new ArrayList<>(1); + Map nodeMap = new HashMap(1); + + for (AbstractEREntity entity : presentation.getEntities()) { + org.eclipse.gef.graph.Node.Builder nodeBuilder = new org.eclipse.gef.graph.Node.Builder(); + nodeBuilder.attr(IERNodeConstants.LABEL, entity.getName()).attr(IERNodeConstants.NODE_PROPERTY, entity); + Node builtNode = nodeBuilder.buildNode(); + nodeMap.put(entity, builtNode); + nodes.add(builtNode); + } + + for (AbstractERAssociation association : presentation.getAssociations()) { + Node sourceNode = nodeMap.get(association.getSourceEntity()); + Node targetNode = nodeMap.get(association.getTargetEntity()); + int associationNum = association.getAssociationNum(); + List list = new ArrayList(); + if (associationNum == 0) { + if (sourceNode.equals(targetNode)) { + list.add(new Point(600, 500)); + list.add(new Point(600, 550)); + } + } else if (associationNum >= 1) { + if (sourceNode.equals(targetNode)) { + list.add(new Point(associationNum * 40 + 500, associationNum * 40 + 500)); + list.add(new Point(associationNum * 40 + 500, associationNum * 40 + 550)); + } else { + list.add(new Point(associationNum * 40 + 500, associationNum * 40 + 600)); + } + } + Builder edgeBuilder = new Builder(sourceNode, targetNode) + .attr(ZestProperties.TOOLTIP__E, getTooltip(association)) + .attr(ZestProperties.CONTROL_POINTS__E, list); + Edge edge = edgeBuilder.buildEdge(); + getEdgeAttributes(edge); + edges.add(edge); + } + return new Graph.Builder().nodes(nodes.toArray(new Node[] {})).edges(edges.toArray(new Edge[] {})) + .attr(ZestProperties.LAYOUT_ALGORITHM__G, new ERLayout()).build(); + } + + private static void getEdgeAttributes(Edge edge) { + Map edgeAttributes = new HashMap<>(); + edgeAttributes.put(ZestProperties.SOURCE_DECORATION__E, + new Polygon(10.0, 0.0, 5, -5, 0.0, 0.0, 5, 5, 10.0, 0.0)); + edgeAttributes.put(ZestProperties.TARGET_DECORATION__E, new Circle(4)); + edgeAttributes.put(ZestProperties.CURVE_CSS_STYLE__E, IERVisualStyleConstants.EDGE_STYLE); + edge.attributesProperty().putAll(edgeAttributes); + } + + private static String getTooltip(AbstractERAssociation association) { + StringBuffer toolTipText = new StringBuffer(MPPDBIDEConstants.STRING_BUILDER_CAPACITY); + toolTipText.append(association.getSourceEntity().getFullyQualifiedName()); + toolTipText.append("-- " + association.getTargetEntity().getFullyQualifiedName()); + return toolTipText.toString(); + } +} \ No newline at end of file diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/parts/ERNodePart.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/parts/ERNodePart.java new file mode 100644 index 0000000000000000000000000000000000000000..eab1741b5f27aefb86f425fb0328e26dc092bc83 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/parts/ERNodePart.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.erd.parts; + +import org.eclipse.gef.zest.fx.parts.NodePart; + +import org.opengauss.mppdbide.bl.erd.model.AbstractEREntity; +import org.opengauss.mppdbide.bl.erd.model.IERNodeConstants; +import org.opengauss.mppdbide.view.erd.visuals.EREntityVisual; + +import javafx.beans.property.ReadOnlyMapProperty; +import javafx.scene.Group; + +/** + * The Class ERNodePart. + * + * @ClassName: ERNodePart + * @Description: The Class ERNodePart. + * + * @since 3.0.0 + */ +public class ERNodePart extends NodePart { + + @Override + protected Group doCreateVisual() { + ReadOnlyMapProperty property = getContent().attributesProperty(); + AbstractEREntity entity = (AbstractEREntity) property.get(IERNodeConstants.NODE_PROPERTY); + EREntityVisual entityVisual = new EREntityVisual(entity); + entityVisual.initEREntityVisual(entity); + return entityVisual; + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/parts/ERPartFactory.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/parts/ERPartFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..a661d2464ef42730cd2c5a84b75aeb0143dc8dc9 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/parts/ERPartFactory.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.erd.parts; + +import java.util.Map; + +import org.eclipse.gef.mvc.fx.parts.IContentPart; +import org.eclipse.gef.zest.fx.parts.ZestFxContentPartFactory; + +import com.google.inject.Inject; +import com.google.inject.Injector; + +/** + * The Class ERPartFactory. + * + * @ClassName: ERPartFactory + * @Description: The Class ERPartFactory. + * + * @since 3.0.0 + */ +public class ERPartFactory extends ZestFxContentPartFactory { + @Inject + private Injector injector; + + @Override + public IContentPart createContentPart(Object content, Map contextMap) { + if (content instanceof org.eclipse.gef.graph.Node) { + // create custom node if we find the custom attribute + ERNodePart part = new ERNodePart(); + injector.injectMembers(part); + return part; + } + return super.createContentPart(content, contextMap); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/visuals/EREntityVisual.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/visuals/EREntityVisual.java new file mode 100644 index 0000000000000000000000000000000000000000..26b64e93edfb8510f846fffe2a8eb77a69ce532b --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/visuals/EREntityVisual.java @@ -0,0 +1,328 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.erd.visuals; + +import org.opengauss.mppdbide.bl.erd.model.AbstractERAttribute; +import org.opengauss.mppdbide.bl.erd.model.AbstractEREntity; +import org.opengauss.mppdbide.view.erd.contextmenu.ERAttributeVisibility; +import org.opengauss.mppdbide.view.erd.contextmenu.ERViewStyle; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +import javafx.geometry.Insets; +import javafx.geometry.Pos; +import javafx.scene.Group; +import javafx.scene.control.Separator; +import javafx.scene.image.ImageView; +import javafx.scene.layout.Background; +import javafx.scene.layout.BackgroundFill; +import javafx.scene.layout.ColumnConstraints; +import javafx.scene.layout.CornerRadii; +import javafx.scene.layout.GridPane; +import javafx.scene.layout.HBox; +import javafx.scene.layout.Priority; +import javafx.scene.layout.VBox; +import javafx.scene.paint.Color; +import javafx.scene.text.Font; +import javafx.scene.text.Text; + +/** + * Title: EREntityVisual + * + * @since 3.0.0 + */ +public class EREntityVisual extends Group { + + /** + * The entity visual. + */ + protected VBox entityVisual; + + /** + * The table header. + */ + protected VBox tableHeader; + + /** + * The primary key visual. + */ + protected VBox primaryKeyVisual; + + /** + * The foreign key visual. + */ + protected VBox foreignKeyVisual; + + /** + * The attribute visual. + */ + protected VBox attributeVisual; + + /** + * The entity. + */ + protected AbstractEREntity entity; + + /** + * The column index. + */ + protected int columnIndex = 0; + + /** + * Instantiates a new ER entity visual. + * + * @param entity the entity + */ + public EREntityVisual(AbstractEREntity entity) { + this.entity = entity; + tableHeader = new VBox(5); + entityVisual = new VBox(0); + primaryKeyVisual = new VBox(1); + foreignKeyVisual = new VBox(1); + attributeVisual = new VBox(1); + } + + /** + * Inits the ER entity visual. + * + * @param entity the entity + */ + public void initEREntityVisual(AbstractEREntity entity) { + entityVisual.setStyle(IERVisualStyleConstants.ENTITY_VISUAL_STYLE); + addTableHeader(tableHeader); + addAttrList(primaryKeyVisual, foreignKeyVisual, attributeVisual); + addSpecialComponensts(entityVisual); + getChildren().addAll(entityVisual); + } + + /** + * Adds the table header. + * + * @param tableHeader the table header + */ + protected void addTableHeader(VBox tableHeader) { + tableHeader.setStyle(IERVisualStyleConstants.TABLE_HEADER_STYLE); + tableHeader.setMinHeight(25); + + // Get the table name + boolean useFQN = ERViewStyle.isShowFullyQualifiedNames(); + String tableName = useFQN ? entity.getFullyQualifiedName() : entity.getName(); + Text tableNameText = new Text(tableName); + tableNameText.setStyle(IERVisualStyleConstants.TABLE_HEADER_STYLE); + tableNameText.setFont(Font.font("Verdana", 12)); + + // Get the table comment + Text tableCommentText = new Text(); + tableCommentText.setStyle(IERVisualStyleConstants.TABLE_HEADER_STYLE); + tableCommentText.setFont(Font.font("Verdana", 12)); + boolean showComments = ERViewStyle.isShowComments(); + String comments = entity.getTableComments(); + if (showComments && null != comments) { + tableCommentText.setText(comments); + } + + // get the table icon + ImageView tableIcon = new ImageView( + new javafx.scene.image.Image(IconUtility.getIconImageUri(IiconPath.ICO_TABLE, getClass()))); + + HBox tableNameBox = new HBox(8); + tableNameBox.setStyle(IERVisualStyleConstants.TABLE_HEADER_STYLE); + tableNameBox.getChildren().addAll(tableIcon, tableNameText); + + Color color = getColor(entity.isCurrentTable()); + tableHeader.setBackground(new Background(new BackgroundFill(color, CornerRadii.EMPTY, Insets.EMPTY))); + tableHeader.getChildren().add(tableNameBox); + if (showComments && null != comments) { + tableHeader.getChildren().add(tableCommentText); + } + } + + /** + * Adds the attr list. + * + * @param primaryKeyVisual the primary key visual + * @param foreignKeyVisual the foreign key visual + * @param attributeVisual the attribute visual + */ + public void addAttrList(VBox primaryKeyVisual, VBox foreignKeyVisual, VBox attributeVisual) { + for (AbstractERAttribute attribute : entity.getAttributes()) { + GridPane gridpane = new GridPane(); + gridpane.setAlignment(Pos.CENTER_LEFT); + gridpane.setPadding(new Insets(3)); + gridpane.setHgap(15); + + columnIndex = 0; + if (ERViewStyle.isShowIcons()) { + addIconColumn(gridpane, attribute); + } + addColumnNameColumn(gridpane, attribute); + + if (ERViewStyle.isShowDataTypes()) { + addDtaTypeColumn(gridpane, attribute); + } + + if (ERViewStyle.isShowNullability() && entity.isHasNotNullColumns()) { + addNullAbilityColumn(gridpane, attribute); + } + + if (ERViewStyle.isShowComments() && entity.isHasColumnComments()) { + addCommentColumn(gridpane, attribute); + } + + if (attribute.isInPrimaryKey()) { + primaryKeyVisual.getChildren().add(gridpane); + } else if (attribute.isInForeignKey()) { + foreignKeyVisual.getChildren().add(gridpane); + } else { + attributeVisual.getChildren().add(gridpane); + } + } + } + + /** + * Sets the attribute text style. + * + * @param text the new attribute text style + */ + protected void setAttributeTextStyle(Text text) { + text.setStyle(IERVisualStyleConstants.ATTRIBUTE_TEXT_STYLE); + text.setFont(Font.font("Verdana", 13)); + } + + /** + * add the icon of the column including data type and isKey. + * + * @param gridpane the gridpane + * @param attribute the attribute + */ + private void addIconColumn(GridPane gridpane, AbstractERAttribute attribute) { + ColumnConstraints iconColumn = new ColumnConstraints(); + gridpane.getColumnConstraints().add(iconColumn); + HBox iconBox = new HBox(5); + iconBox.setAlignment(Pos.CENTER); + + ImageView primaryKeyIcon = new ImageView( + new javafx.scene.image.Image(IconUtility.getIconImageUri(IiconPath.ER_PRIMARY_KEY, getClass()))); + ImageView foreignKeyIcon = new ImageView( + new javafx.scene.image.Image(IconUtility.getIconImageUri(IiconPath.ER_FOREIGN_KEY, getClass()))); + ImageView dataTypeIcon = new ImageView(new javafx.scene.image.Image( + IconUtility.getIconImageUri(IconUtility.getObjectImage(attribute), getClass()))); + if (attribute.isInPrimaryKey()) { + iconBox.getChildren().add(primaryKeyIcon); + } + if (attribute.isInForeignKey()) { + iconBox.getChildren().add(foreignKeyIcon); + } + iconBox.getChildren().add(dataTypeIcon); + gridpane.add(iconBox, columnIndex++, 0); + } + + private void addColumnNameColumn(GridPane gridpane, AbstractERAttribute attribute) { + ColumnConstraints columnNameColumn = new ColumnConstraints(); + columnNameColumn.setHgrow(Priority.ALWAYS); + gridpane.getColumnConstraints().add(columnNameColumn); + Text columnNameText = new Text(attribute.getName()); + setAttributeTextStyle(columnNameText); + gridpane.add(columnNameText, columnIndex++, 0); + } + + /** + * Adds the dta type column. + * + * @param gridpane the gridpane + * @param attribute the attribute + */ + public void addDtaTypeColumn(GridPane gridpane, AbstractERAttribute attribute) { + ColumnConstraints dataTypeColumn = new ColumnConstraints(); + gridpane.getColumnConstraints().add(dataTypeColumn); + String dataTypeString = attribute.getDataTypes(); + Text dataTypeText = new Text(dataTypeString); + setAttributeTextStyle(dataTypeText); + gridpane.add(dataTypeText, columnIndex++, 0); + } + + /** + * Adds the null ability column. + * + * @param gridpane the gridpane + * @param attribute the attribute + */ + protected void addNullAbilityColumn(GridPane gridpane, AbstractERAttribute attribute) { + ColumnConstraints nullAbilityColumn = new ColumnConstraints(70); + gridpane.getColumnConstraints().add(nullAbilityColumn); + Text nullAbilityText = new Text(attribute.getNullability()); + setAttributeTextStyle(nullAbilityText); + gridpane.add(nullAbilityText, columnIndex++, 0); + } + + /** + * Adds the comment column. + * + * @param gridpane the gridpane + * @param attribute the attribute + */ + protected void addCommentColumn(GridPane gridpane, AbstractERAttribute attribute) { + ColumnConstraints commentColumn = new ColumnConstraints(250); + gridpane.getColumnConstraints().add(commentColumn); + Text commentText = new Text(); + if (attribute.getComments() != null) { + commentText.setText("-" + attribute.getComments()); + } + setAttributeTextStyle(commentText); + commentText.setWrappingWidth(250); + gridpane.add(commentText, columnIndex++, 0); + } + + /** + * Adds the special componensts. + * + * @param entityVisual the entity visual + */ + public void addSpecialComponensts(VBox entityVisual) { + // Construct Separator Line + Separator keyLine; + Separator attrLine; + keyLine = new Separator(); + keyLine.setStyle(IERVisualStyleConstants.LINE_STYLE); + attrLine = new Separator(); + attrLine.setStyle(IERVisualStyleConstants.LINE_STYLE); + + if (ERAttributeVisibility.isNone()) { + entityVisual.getChildren().addAll(tableHeader); + } else if (ERAttributeVisibility.isPrimaryKey()) { + entityVisual.getChildren().addAll(tableHeader, keyLine, primaryKeyVisual); + } else if (ERAttributeVisibility.isAnyKey()) { + entityVisual.getChildren().addAll(tableHeader, keyLine, primaryKeyVisual, attrLine, foreignKeyVisual); + } else { + entityVisual.getChildren().addAll(tableHeader, keyLine, primaryKeyVisual, attrLine, foreignKeyVisual, + attributeVisual); + } + } + + /** + * Gets the color. + * + * @param isCurrentTable the is current table + * @return the color + */ + public Color getColor(boolean isCurrentTable) { + if (isCurrentTable) { + return Color.rgb(167, 220, 224); + } else { + return Color.rgb(250, 218, 141); + } + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/visuals/ERLayout.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/visuals/ERLayout.java new file mode 100644 index 0000000000000000000000000000000000000000..fd1e21b3e1ff59c8b9a4bbd1c3df0875063f0486 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/visuals/ERLayout.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.erd.visuals; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.eclipse.gef.geometry.planar.Dimension; +import org.eclipse.gef.geometry.planar.Point; +import org.eclipse.gef.geometry.planar.Rectangle; +import org.eclipse.gef.graph.Node; +import org.eclipse.gef.layout.ILayoutAlgorithm; +import org.eclipse.gef.layout.LayoutContext; +import org.eclipse.gef.layout.LayoutProperties; + +/** + * Title: ERLayout Description: The layout algorithm for ER Diagram. + * + * @since 3.0.0 + */ +public class ERLayout implements ILayoutAlgorithm { + private static final double HEIGHT_GAP = 10; + + private static final double VERTICAL_SPACING = 16; + + /** + * Makes this algorithm perform layout computation and apply it to its + * context. + */ + public void applyLayout(LayoutContext context, boolean clean) { + if (!clean) { + return; + } + + ArrayList> entitiesList = new ArrayList<>(); + List entities = new ArrayList<>(); + // all the tables needs to layout. + for (Node node : context.getGraph().getNodes()) { + entities.add(node); + } + + for (Node node : entities) { + addToEntitiesList(node, entitiesList); + } + + Collections.sort(entitiesList, new Comparator>() { + /** + * Compare the height of two rows, the higher will be layout below. + */ + public int compare(List row1, List row2) { + Node entityRow1 = row1.get(0); + Node entityRow2 = row2.get(0); + return (int) (LayoutProperties.getLocation(entityRow1).y - LayoutProperties.getLocation(entityRow2).y); + } + }); + + int heightSoFar = 0; + Rectangle bounds = LayoutProperties.getBounds(context.getGraph()); + for (List currentRow : entitiesList) { + int index = 0; + /** + * bounds.getWidth() / 2 is the center of the graph, 75 is the + * estimated width of each table the width represent the begin + * loyoutX of currentRow + */ + int width = (int) (bounds.getWidth() / 2 - currentRow.size() * 75); + + // the currentRow's height and the vertical spacing + heightSoFar += LayoutProperties.getSize(currentRow.get(0)).height + VERTICAL_SPACING; + for (Node entity : currentRow) { + Dimension size = LayoutProperties.getSize(entity); + /** + * set location of the entity, (size.width / 2, size.height / 2) + * is the center of the entity 10 * ++index is the spacing in + * currentRow tables + */ + LayoutProperties.setLocation(entity, + new Point(width + 10 * ++index + size.width / 2, heightSoFar + size.height / 2)); + width += size.width; + } + } + } + + /** + * @Title: addToEntitiesList + * @Description: add the entity to entitiesList, entities will add to the + * same row, if their heights differ slightly + * @param entity: the entity need add to the entitiesList. + * @param entitiesList: all the tables divided into different rows. + */ + private void addToEntitiesList(Node entity, ArrayList> entitiesList) { + double layoutY = LayoutProperties.getLocation(entity).y; + + for (List currentRow : entitiesList) { + Node currentRowEntity = currentRow.get(0); + double currentRowY = LayoutProperties.getLocation(currentRowEntity).y; + if (layoutY >= currentRowY - HEIGHT_GAP && layoutY <= currentRowY + HEIGHT_GAP) { + currentRow.add(entity); + return; + } + } + + List newRow = new ArrayList<>(); + newRow.add(entity); + entitiesList.add(newRow); + } +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/visuals/IERVisualStyleConstants.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/visuals/IERVisualStyleConstants.java new file mode 100644 index 0000000000000000000000000000000000000000..37fc134d4187004fa378647af85efd91fabf2c11 --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/erd/visuals/IERVisualStyleConstants.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.erd.visuals; + +/** + * Title: ERVisualStyleConstants + * + * @since 3.0.0 + */ +public interface IERVisualStyleConstants { + /** + * The entity visual style. + */ + String ENTITY_VISUAL_STYLE = "-fx-border-color: deepskyblue; -fx-border-width: 2; -fx-background-color: white;"; + + /** + * The table header style. + */ + String TABLE_HEADER_STYLE = "-fx-alignment : center"; + + /** + * The attribute text style. + */ + String ATTRIBUTE_TEXT_STYLE = "-fx-text-alignment : left"; + + /** + * The line style. + */ + String LINE_STYLE = "-fx-border-style: solid; -fx-border-width: 2 0 0 0; -fx-border-color: deepskyblue"; + + /** + * The edge style. + */ + String EDGE_STYLE = "-fx-stroke-style : deepskyblue"; +} diff --git a/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/exportimportdsconnections/ExportConnectionProfilesDialog.java b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/exportimportdsconnections/ExportConnectionProfilesDialog.java new file mode 100644 index 0000000000000000000000000000000000000000..ddf8857ed9cb82e0325b2b7cae3df9de2d3b64fc --- /dev/null +++ b/code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/exportimportdsconnections/ExportConnectionProfilesDialog.java @@ -0,0 +1,618 @@ +/* + * Copyright (c) 2022 Huawei Technologies Co.,Ltd. + * + * openGauss is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, + * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, + * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +package org.opengauss.mppdbide.view.exportimportdsconnections; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.viewers.ArrayContentProvider; +import org.eclipse.jface.viewers.TableViewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.TableEditor; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.events.VerifyEvent; +import org.eclipse.swt.events.VerifyListener; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.FileDialog; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.TableColumn; +import org.eclipse.swt.widgets.TableItem; +import org.eclipse.swt.widgets.Text; + +import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; +import org.opengauss.mppdbide.bl.serverdatacache.ProfileDiskUtility; +import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo; +import org.opengauss.mppdbide.presentation.exportimportdsconnectionprofiles.ExportConnectionCore; +import org.opengauss.mppdbide.utils.IMessagesConstants; +import org.opengauss.mppdbide.utils.MPPDBIDEConstants; +import org.opengauss.mppdbide.utils.files.FileValidationUtils; +import org.opengauss.mppdbide.utils.loader.MessageConfigLoader; +import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs; +import org.opengauss.mppdbide.view.utils.dialog.MPPDBIDEDialogs.MESSAGEDIALOGTYPE; +import org.opengauss.mppdbide.view.utils.icon.IconUtility; +import org.opengauss.mppdbide.view.utils.icon.IiconPath; + +/** + * + * Title: class + * + * Description: The Class ExportConnectionProfilesDialog. + * + * @since 3.0.0 + */ +public class ExportConnectionProfilesDialog extends Dialog { + + private Text outputPathText; + private Button checkButton; + private Button selectAllBtn; + private Button clearAllBtn; + private Table connectionTable; + private String[] connNames; + private String[] connDetails; + private List userSelectedConn; + private List